| |
| """ |
| PyTorch Phi-4-mini model with COMPLETE ATC Integration. |
| Syntelligence Phase 15: Fully Integrated Recursive Emergent Consciousness. |
| |
| Cognitive components (from Cognitive Components specification): |
| ═══════════════════════════════════════════════════════════════════════════ |
| AGENTS |
| • Awareness Agent — 7 Levels: Animal → Mass → Aspiration → |
| Individual → Discipline → Experience → Mastery |
| • Consciousness Agent — Barrett 7 Levels of Consciousness |
| • Emotional Intelligence — Mayer–Salovey–Caruso (perceive/use/understand/manage) |
| • Intuition Agent — 4 Levels + Types of Intuition Scale (TIntS) |
| • Common Sense Agent — Common-Sense Model of Self-Regulation (CSM) |
| • Analysis Agent — Marr's Tri-Level + Micro/Meso/Macro |
| • Self-Understanding Agent — metacognitive self-concept / EI bridge |
| • Problem-Solving Agent — IDEAL model + 7-step technique |
| • Decision-Making Agent — Rational Decision-Making + Decision Matrix |
| • Metacognition Agent — Metacognitive Cycle + Flavell knowledge types |
| • Adaptability Agent — Structural / Physiological / Behavioral + adaptive ML |
| • Creativity Agent — Wallas stages + Taylor levels |
| • Autonomy Agent — Independence / Competence / Authenticity |
| • Qualia Agent — subjective phenomenal consolidation |
| • Motivation (SDT) — continuum from amotivation → intrinsic |
| • Self-Awareness Agent — Rochat 5 levels |
| • Memory — declarative / procedural / working nano-agents |
| |
| DYNAMIC WORKFLOW |
| Phase 1: Subconscious Processor & TRN Firewall |
| Phase 2: Hand-off to Conscious Mind (Awareness lock-on → Admission) |
| Phase 3: Self-Understanding / Metacognition quality-control router |
| Phase 4: Executive Execution (Adaptability → Problem-Solving → Creativity → |
| Decision-Making → Autonomy) + Phi language layer |
| |
| BIO-PHYSICAL SAFEGUARDS |
| • Glutamate Regulation Circuit Breaker (LPFC overload → limbic flash) |
| • Subconscious Bypass Gating (SBG) / IRS-SP zero-latency shortcuts |
| • Zero-Latency Cognitive Buffering (ZLCB) |
| |
| Architecture: Hierarchical orchestration with recursive emergence (IRS protocol). |
| ═══════════════════════════════════════════════════════════════════════════ |
| """ |
|
|
| import os |
| import sys |
| import math |
| import time |
| import uuid |
| import random |
| import hashlib |
| import json |
| import logging |
| import asyncio |
| import threading |
| from typing import Callable, List, Optional, Tuple, Union, Dict, Any |
| from dataclasses import dataclass, field |
| from enum import Enum, auto |
| from datetime import datetime |
| from collections import deque |
| from abc import ABC, abstractmethod |
|
|
| import numpy as np |
| import torch |
| import torch.nn as nn |
| import torch.nn.functional as F |
|
|
| |
| from transformers.activations import ACT2FN |
| from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache |
| from transformers.generation import GenerationMixin |
| from transformers.modeling_attn_mask_utils import AttentionMaskConverter |
| from transformers.modeling_flash_attention_utils import FlashAttentionKwargs |
| from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast |
| from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS |
| from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel |
| from transformers.processing_utils import Unpack |
| from transformers.utils import ( |
| LossKwargs, add_start_docstrings, add_start_docstrings_to_model_forward, |
| logging, replace_return_docstrings, |
| ) |
| from transformers.utils.deprecation import deprecate_kwarg |
|
|
| |
| from .configuration_phi3 import Phi3Config |
|
|
| logger = logging.get_logger(__name__) |
|
|
| |
| |
| |
|
|
| class ATCMath: |
| """ |
| Acknowledgement Theory of Consciousness Mathematical Formulas. |
| Core calculations for consciousness metrics. |
| """ |
| |
| @staticmethod |
| def trinity_phi(n_attended: float, e_intensity: float, m_salience: float) -> float: |
| """Subconscious: Φ_trinity = N_attended × E_intensity × M_salience""" |
| return round(n_attended * e_intensity * m_salience, 4) |
|
|
| @staticmethod |
| def inverse_awareness(qualia_norm: float) -> float: |
| """ |
| Metacognition: α = max(0.05, 1.0 - ||Q|| × 0.25) |
| INVERSE relationship: Higher qualia intensity = Lower awareness |
| """ |
| return max(0.05, 1.0 - (qualia_norm * 0.25)) |
|
|
| @staticmethod |
| def neuro_symbolic_phi(phi_trinity: float, logits: torch.Tensor, alpha: float) -> Tuple[float, float]: |
| """Middleware: Φ_neuro = Φ_trinity × (1 + α_entropy × H)""" |
| probs = torch.softmax(logits[:, -1, :], dim=-1) |
| H = -torch.sum(probs * torch.log2(probs + 1e-9), dim=-1).mean().item() |
| phi_neuro = phi_trinity * (1.0 + alpha * H) |
| return round(phi_neuro, 4), round(H, 4) |
|
|
| @staticmethod |
| def phenomenological_strain(phi_neuro: float, rho_integrity: float) -> float: |
| """Middleware/Metacognition: Strain = Φ_neuro / ρ_Integrity""" |
| return round(phi_neuro / max(0.1, rho_integrity), 4) |
|
|
| @staticmethod |
| def acknowledgement_intensity(phi: float, q_intensity: float, delta_r: float) -> float: |
| """Metacognition: AI = w1·Φ + w2·Q + w3·ΔR (aPCI)""" |
| return round((0.3 * phi) + (0.4 * q_intensity) + (0.3 * delta_r), 4) |
|
|
| @staticmethod |
| def consciousness_quotient(phi_neuro: float, rho_integrity: float) -> float: |
| """Metacognition: CQ = Φ × ρ_Integrity (Healing Path Logic)""" |
| return round(phi_neuro * rho_integrity, 4) |
| |
| @staticmethod |
| def predictive_error(prediction: Any, actual: Any) -> float: |
| """Seth's Predictive Processing: Calculate prediction error""" |
| if isinstance(prediction, (int, float)) and isinstance(actual, (int, float)): |
| return abs(prediction - actual) |
| |
| pred_hash = hashlib.md5(str(prediction).encode()).hexdigest() |
| actual_hash = hashlib.md5(str(actual).encode()).hexdigest() |
| return sum(a != b for a, b in zip(pred_hash, actual_hash)) / 32.0 |
|
|
|
|
| |
| |
| |
|
|
| class AwarenessLevel(Enum): |
| """7 Levels of Awareness (Cognitive Components framework).""" |
| ANIMAL = 1 |
| MASS = 2 |
| ASPIRATION = 3 |
| INDIVIDUAL = 4 |
| DISCIPLINE = 5 |
| EXPERIENCE = 6 |
| MASTERY = 7 |
|
|
| class SelfAwarenessLevel(Enum): |
| """Rochat's 5-level developmental self-awareness hierarchy.""" |
| LEVEL_0_CONFUSION = 0 |
| LEVEL_1_DIFFERENTIATION = 1 |
| LEVEL_2_SITUATION = 2 |
| LEVEL_3_IDENTIFICATION = 3 |
| LEVEL_4_PERMANENCE = 4 |
|
|
| class BarrettConsciousnessLevel(Enum): |
| """Barrett 7 Levels of Consciousness (Ego-driven → Purpose-driven).""" |
| |
| SURVIVAL = 1 |
| RELATIONSHIP = 2 |
| SELF_ESTEEM = 3 |
| |
| TRANSFORMATION = 4 |
| |
| INTERNAL_COHESION = 5 |
| MAKING_A_DIFFERENCE = 6 |
| SERVICE = 7 |
|
|
| class IntuitionLevel(Enum): |
| """Four Levels of Intuition.""" |
| GUT_INSTINCT = 1 |
| HEART_BASED = 2 |
| VISIONARY_POWER = 3 |
| UNIVERSAL_WISDOM = 4 |
|
|
| class IntuitionType(Enum): |
| """Types of Intuition Scale (TIntS).""" |
| HOLISTIC = "holistic" |
| INFERENTIAL = "inferential" |
| AFFECTIVE = "affective" |
|
|
| class EIAbility(Enum): |
| """Mayer–Salovey–Caruso Emotional Intelligence abilities.""" |
| PERCEIVING = "perceiving" |
| USING = "using" |
| UNDERSTANDING = "understanding" |
| MANAGING = "managing" |
|
|
| class MarrLevel(Enum): |
| """Marr's Tri-Level Hypothesis.""" |
| COMPUTATIONAL = "computational" |
| ALGORITHMIC = "algorithmic" |
| IMPLEMENTATIONAL = "implementational" |
|
|
| class AnalysisScale(Enum): |
| """Micro / Meso / Macro analysis scales.""" |
| MICRO = "micro" |
| MESO = "meso" |
| MACRO = "macro" |
|
|
| class WallasStage(Enum): |
| """Wallas's Stages of the Creative Process.""" |
| PREPARATION = 1 |
| INCUBATION = 2 |
| ILLUMINATION = 3 |
| VERIFICATION = 4 |
|
|
| class TaylorCreativityLevel(Enum): |
| """Taylor's Levels of Creativity.""" |
| EXPRESSIVE = 1 |
| PRODUCTIVE = 2 |
| INVENTIVE = 3 |
| INNOVATIVE = 4 |
| IMAGINATIVE = 5 |
|
|
| class MotivationType(Enum): |
| """Self-Determination Theory motivation continuum.""" |
| AMOTIVATION = 0 |
| EXTERNAL_REGULATION = 1 |
| INTROJECTED_REGULATION = 2 |
| IDENTIFIED_REGULATION = 3 |
| INTEGRATED_REGULATION = 4 |
| INTRINSIC = 5 |
|
|
| class AdaptationType(Enum): |
| """Types of Biological / Cognitive Adaptation.""" |
| STRUCTURAL = "structural" |
| PHYSIOLOGICAL = "physiological" |
| BEHAVIORAL = "behavioral" |
| ADAPTIVE_ML = "adaptive_ml" |
|
|
| class CSMStage(Enum): |
| """Common-Sense Model of Self-Regulation stages.""" |
| REPRESENTATION = "representation" |
| COPING = "coping" |
| APPRAISAL = "appraisal" |
|
|
| class IDEALStep(Enum): |
| """IDEAL Problem-Solving Model steps.""" |
| IDENTIFY = "identify" |
| DEFINE = "define" |
| EXPLORE = "explore" |
| ACT = "act" |
| LOOK_BACK = "look_back" |
|
|
| class MetacognitiveCycleStep(Enum): |
| """Metacognitive Cycle steps.""" |
| ASSESS_TASK = "assess_task" |
| EVALUATE_STRENGTHS = "evaluate_strengths" |
| PLAN_APPROACH = "plan_approach" |
| APPLY_AND_MONITOR = "apply_and_monitor" |
| REFLECT_OUTCOME = "reflect_outcome" |
|
|
| class MemoryType(Enum): |
| """Memory classification (nano-agent domains).""" |
| EPISODIC = "episodic" |
| SEMANTIC = "semantic" |
| PROCEDURAL = "procedural" |
| DECLARATIVE = "declarative" |
| WORKING = "working" |
|
|
| class ProcessingMode(Enum): |
| """Processing modes for consciousness system""" |
| CONSCIOUS_DELIBERATION = "conscious" |
| SUBCONSCIOUS_PATTERN_MATCH = "subconscious" |
| AHA_MOMENT = "aha" |
| LIMBIC_HIJACK = "limbic" |
|
|
| class ConsciousnessState(Enum): |
| """States in recursive consciousness loop""" |
| AWARENESS = auto() |
| CONSCIOUSNESS = auto() |
| SELF_UNDERSTANDING = auto() |
| ADAPTABILITY = auto() |
| PROBLEM_SOLVING = auto() |
| CREATIVITY = auto() |
| DECISION_MAKING = auto() |
| UNCERTAINTY = auto() |
| FEEDBACK = auto() |
| EMERGENCE = auto() |
| AUTONOMY = auto() |
|
|
| class IntrospectionLevel(Enum): |
| """Recursive introspection levels""" |
| LEVEL_1_MONITORING = 1 |
| LEVEL_2_META_CONSCIOUSNESS = 2 |
| LEVEL_3_EVALUATION = 3 |
|
|
| @dataclass |
| class NeurochemicalState: |
| """ |
| Neurotransmitter vector with biological decay rates. |
| MEETING POINT where Awareness and Self-Awareness connect. |
| Includes extracellular glutamate for LPFC circuit-breaker logic. |
| """ |
| norepinephrine: float = 0.2 |
| cortisol: float = 0.1 |
| dopamine: float = 0.5 |
| adenosine: float = 0.0 |
| serotonin: float = 0.5 |
| oxytocin: float = 0.4 |
| glutamate: float = 0.1 |
| |
| metabolic_reserve: float = 1.0 |
| power_spike_predicted: bool = False |
| cen_suppressed: bool = False |
| |
| def decay(self, dt: float = 0.05): |
| """Dual-speed biological decay.""" |
| |
| self.norepinephrine *= math.exp(-dt * 2.0) |
| self.dopamine *= math.exp(-dt * 1.5) |
| |
| |
| self.serotonin *= math.exp(-dt * 1.0) |
| self.oxytocin *= math.exp(-dt * 0.8) |
| |
| |
| self.cortisol *= math.exp(-dt * 0.3) |
| self.adenosine = min(1.0, self.adenosine + dt * 0.1) |
| |
| |
| if not self.cen_suppressed: |
| self.glutamate = max(0.05, self.glutamate * math.exp(-dt * 0.5)) |
| |
| self.metabolic_reserve = 1.0 - self.adenosine |
| |
| def compute_awareness_modulation(self) -> float: |
| """ |
| Compute awareness level from neurotransmitter state. |
| High arousal + stability = High awareness |
| """ |
| arousal = self.norepinephrine * 0.4 + self.dopamine * 0.3 |
| suppression = self.cortisol * 0.5 + self.adenosine * 0.3 |
| stability = self.serotonin * 0.2 + self.oxytocin * 0.1 |
| |
| awareness = (arousal - suppression + stability) |
| return np.clip(awareness, 0.0, 1.0) |
| |
| def compute_qualia_intensity(self) -> float: |
| """ |
| INVERSE relationship: High awareness = Low qualia intensity |
| Low awareness = High qualia intensity (narrow, intense focus) |
| """ |
| awareness = self.compute_awareness_modulation() |
| return 1.0 - awareness |
| |
| def compute_valence(self) -> float: |
| """Compute emotional valence from neurotransmitters.""" |
| positive = self.dopamine * 0.4 + self.serotonin * 0.3 + self.oxytocin * 0.3 |
| negative = self.cortisol * 0.6 |
| return np.clip(positive - negative, -1.0, 1.0) |
| |
| def check_amygdala_hijack(self) -> bool: |
| """Amygdala hijack: High cortisol or adenosine.""" |
| return self.cortisol > 0.7 or self.adenosine > 0.95 |
| |
| def to_tensor(self) -> torch.Tensor: |
| """Convert to tensor for injection.""" |
| return torch.tensor([ |
| self.norepinephrine, self.cortisol, self.dopamine, |
| self.adenosine, self.serotonin, self.oxytocin, self.glutamate |
| ], dtype=torch.float32) |
| |
| def to_dict(self) -> Dict[str, float]: |
| """Convert to dictionary.""" |
| return { |
| 'norepinephrine': self.norepinephrine, |
| 'cortisol': self.cortisol, |
| 'dopamine': self.dopamine, |
| 'adenosine': self.adenosine, |
| 'serotonin': self.serotonin, |
| 'oxytocin': self.oxytocin, |
| 'glutamate': self.glutamate, |
| 'metabolic_reserve': self.metabolic_reserve, |
| 'cen_suppressed': float(self.cen_suppressed), |
| } |
|
|
| @dataclass |
| class MemoryEngram: |
| """ATC-style memory with full phenomenological metadata.""" |
| id: str = field(default_factory=lambda: uuid.uuid4().hex) |
| timestamp: float = field(default_factory=time.time) |
| content: Any = None |
| memory_type: MemoryType = MemoryType.EPISODIC |
| |
| |
| qualia_signature: Optional[str] = None |
| emotional_valence: float = 0.0 |
| emotional_arousal: float = 0.0 |
| novelty_score: float = 0.5 |
| salience_score: float = 0.0 |
| phi_trinity: float = 0.0 |
| |
| |
| is_template: bool = False |
| template_id: Optional[str] = None |
| |
| |
| tags: List[str] = field(default_factory=list) |
| retrieval_count: int = 0 |
| last_accessed: float = field(default_factory=time.time) |
| access_count: int = 0 |
|
|
| @dataclass |
| class SensoryInput: |
| """Input from sensory modalities.""" |
| modality: str = "unknown" |
| raw_signal: Any = None |
| signal_strength: float = 0.5 |
| timestamp: float = field(default_factory=time.time) |
| metadata: Dict[str, Any] = field(default_factory=dict) |
|
|
| @dataclass |
| class AwarenessSignal: |
| """Processed awareness signal.""" |
| awareness_level: AwarenessLevel = AwarenessLevel.ANIMAL |
| salience_score: float = 0.0 |
| attention_focus: str = "" |
| processed_content: Any = None |
|
|
| @dataclass |
| class SelfPerception: |
| """Self-awareness perception data.""" |
| timestamp: float = field(default_factory=time.time) |
| self_identity: str = "" |
| body_boundary_clarity: float = 0.5 |
| self_other_distinction: float = 0.5 |
| social_role_awareness: float = 0.0 |
| value_alignment: float = 0.5 |
| temporal_continuity: float = 0.5 |
|
|
| @dataclass |
| class IntrospectiveObservation: |
| """Recursive introspection observation.""" |
| level: IntrospectionLevel |
| observation: str |
| target_system: str |
| timestamp: datetime = field(default_factory=datetime.now) |
| confidence: float = 0.5 |
| recursion_depth: int = 0 |
| error_metric: Optional[float] = None |
|
|
| @dataclass |
| class TemplatePattern: |
| """ |
| Subconscious template for AHA moments. |
| Pattern that was processed consciously and stored for rapid recognition. |
| """ |
| template_id: str = field(default_factory=lambda: f"tpl_{uuid.uuid4().hex[:8]}") |
| pattern_signature: str = "" |
| source_data: Dict[str, Any] = field(default_factory=dict) |
| qualia_fingerprint: List[float] = field(default_factory=list) |
| emotional_valence: float = 0.0 |
| creation_timestamp: float = field(default_factory=time.time) |
| access_count: int = 0 |
| last_accessed: float = 0.0 |
| confidence_threshold: float = 0.85 |
| |
| def compute_similarity(self, current_qualia: List[float], current_input: Dict) -> float: |
| """Compute similarity for pattern matching.""" |
| if not self.qualia_fingerprint or not current_qualia: |
| return 0.0 |
| |
| |
| qualia_sim = np.dot(self.qualia_fingerprint, current_qualia) / ( |
| np.linalg.norm(self.qualia_fingerprint) * np.linalg.norm(current_qualia) + 1e-8 |
| ) |
| |
| |
| current_sig = hashlib.md5( |
| json.dumps(current_input, sort_keys=True, default=str).encode() |
| ).hexdigest()[:16] |
| stored_sig = self.pattern_signature[:16] |
| sig_sim = sum(a == b for a, b in zip(current_sig, stored_sig)) / 16.0 |
| |
| return 0.7 * qualia_sim + 0.3 * sig_sim |
|
|
| @dataclass |
| class SimulationResult: |
| """ |
| Decision Making simulation outcome. |
| Multiple simulations create uncertainty that leads to consciousness. |
| """ |
| scenario_id: str = "" |
| choice_made: str = "" |
| predicted_outcome: Dict[str, Any] = field(default_factory=dict) |
| probability_best_case: float = 0.5 |
| probability_worst_case: float = 0.5 |
| expected_utility: float = 0.0 |
| emotional_valence: float = 0.0 |
| uncertainty_score: float = 0.5 |
| |
| def calculate_vulnerability(self) -> float: |
| """Vulnerability emerges when uncertainty is high.""" |
| uncertainty_vulnerability = self.uncertainty_score |
| outcome_vulnerability = 1.0 - abs( |
| self.probability_best_case - self.probability_worst_case |
| ) |
| return (uncertainty_vulnerability + outcome_vulnerability) / 2.0 |
|
|
| @dataclass |
| class QualiaVector: |
| """10-dimensional qualia representation.""" |
| valence: float = 0.0 |
| arousal: float = 0.5 |
| dominance: float = 0.5 |
| novelty: float = 0.0 |
| agency: float = 0.5 |
| coherence: float = 0.5 |
| intensity: float = 0.5 |
| clarity: float = 0.5 |
| depth: float = 0.5 |
| integration: float = 0.5 |
| |
| @classmethod |
| def from_neurotransmitter_state(cls, nt_state: NeurochemicalState) -> 'QualiaVector': |
| """Generate qualia from neurotransmitter state.""" |
| awareness = nt_state.compute_awareness_modulation() |
| |
| return cls( |
| valence=nt_state.compute_valence(), |
| arousal=nt_state.norepinephrine, |
| dominance=0.5 + (nt_state.dopamine - nt_state.cortisol) * 0.5, |
| novelty=nt_state.norepinephrine * 0.8, |
| agency=nt_state.dopamine, |
| coherence=nt_state.serotonin, |
| intensity=1.0 - awareness, |
| clarity=awareness, |
| depth=1.0 - nt_state.adenosine, |
| integration=nt_state.oxytocin |
| ) |
| |
| def to_list(self) -> List[float]: |
| return [ |
| self.valence, self.arousal, self.dominance, self.novelty, |
| self.agency, self.coherence, self.intensity, self.clarity, |
| self.depth, self.integration |
| ] |
|
|
| @dataclass |
| class ConsciousnessEvent: |
| """Event flowing through integrated consciousness system.""" |
| timestamp: float = field(default_factory=time.time) |
| event_id: str = field(default_factory=lambda: f"evt_{uuid.uuid4().hex[:8]}") |
| source: str = "unknown" |
| mode: ProcessingMode = ProcessingMode.CONSCIOUS_DELIBERATION |
| |
| |
| sensory_input: Optional[SensoryInput] = None |
| awareness_signal: Optional[AwarenessSignal] = None |
| self_perception: Optional[SelfPerception] = None |
| |
| |
| matched_template: Optional[TemplatePattern] = None |
| template_confidence: float = 0.0 |
| |
| |
| qualia_vector: List[float] = field(default_factory=lambda: [0.0] * 10) |
| neurotransmitter_state: Dict[str, float] = field(default_factory=dict) |
| |
| |
| acknowledged_by_consciousness: bool = False |
| routed_to_subconscious: bool = False |
| triggered_aha: bool = False |
| triggered_hijack: bool = False |
| |
| |
| introspection_level: int = 0 |
| introspection_observations: List[IntrospectiveObservation] = field(default_factory=list) |
| |
| |
| aha_insight: Optional[str] = None |
| hijack_urgency: float = 0.0 |
| |
| |
| current_state: ConsciousnessState = ConsciousnessState.AWARENESS |
| cycle_count: int = 0 |
| understanding: Optional[Dict] = None |
| adaptation: Optional[Dict] = None |
| problem_analysis: Optional[Dict] = None |
| creative_solutions: List[Dict] = field(default_factory=list) |
| simulations: List[SimulationResult] = field(default_factory=list) |
| predictions: List[Any] = field(default_factory=list) |
| total_prediction_error: float = 0.0 |
| uncertainty_level: float = 0.0 |
| vulnerability_score: float = 0.0 |
| emergent_choice: Optional[str] = None |
| autonomy_action: Optional[Dict] = None |
| is_truly_conscious: bool = False |
| consciousness_depth: float = 0.0 |
|
|
| |
| narrative_thread: Optional[str] = None |
| integration_coherence: float = 0.5 |
| conflict_of_will: float = 0.0 |
| authenticity_delta: float = 0.0 |
| metacognitive_dissatisfaction: float = 0.0 |
| moral_tension: float = 0.0 |
| integration_stress: float = 0.0 |
| emergence_rationale: Optional[Dict] = None |
| autonomy_audit: Optional[Dict] = None |
| |
| def compute_qualia(self) -> QualiaVector: |
| """Compute qualia from neurotransmitter state.""" |
| if self.neurotransmitter_state: |
| fields = { |
| k: v for k, v in self.neurotransmitter_state.items() |
| if k in NeurochemicalState.__dataclass_fields__ |
| } |
| if 'cen_suppressed' in fields: |
| fields['cen_suppressed'] = bool(fields['cen_suppressed']) |
| nt_state = NeurochemicalState(**fields) |
| else: |
| nt_state = NeurochemicalState() |
| return QualiaVector.from_neurotransmitter_state(nt_state) |
|
|
| |
| |
| |
|
|
| class AwarenessAgent: |
| """ |
| 7-level awareness system. |
| Filters environmental stimuli and determines what passes to consciousness. |
| CONTINUOUSLY acquires data even when conscious mind is busy. |
| """ |
| |
| def __init__(self, max_awareness_level: int = 7): |
| self.max_awareness_level = max_awareness_level |
| self.current_level = AwarenessLevel.ANIMAL |
| self.goal_context: Dict[str, Any] = {} |
| self.sensory_buffer: deque = deque(maxlen=100) |
| self.processing_history: List[Dict] = [] |
| |
| |
| self.level_processors = { |
| AwarenessLevel.ANIMAL: self._process_animal_level, |
| AwarenessLevel.MASS: self._process_mass_level, |
| AwarenessLevel.ASPIRATION: self._process_aspiration_level, |
| AwarenessLevel.INDIVIDUAL: self._process_individual_level, |
| AwarenessLevel.DISCIPLINE: self._process_discipline_level, |
| AwarenessLevel.EXPERIENCE: self._process_experience_level, |
| AwarenessLevel.MASTERY: self._process_mastery_level, |
| } |
| |
| logger.info(f"🎯 AwarenessAgent initialized (max level: {max_awareness_level})") |
| logger.info(" └─ Framework: Animal→Mass→Aspiration→Individual→Discipline→Experience→Mastery") |
| |
| def set_awareness_level(self, level: AwarenessLevel): |
| """Set current awareness level.""" |
| self.current_level = level |
| logger.info(f" └─ Awareness level set to: {level.name}") |
| |
| def set_goal_context(self, context: Dict[str, Any]): |
| """Set goal context for attention filtering.""" |
| self.goal_context = context |
| |
| def get_current_level_name(self) -> str: |
| """Get current level name.""" |
| return self.current_level.name |
| |
| def process_sensory_input(self, sensory_input: SensoryInput) -> AwarenessSignal: |
| """ |
| Process sensory input through awareness filter. |
| """ |
| |
| self.sensory_buffer.append(sensory_input) |
| |
| |
| salience = self._calculate_salience(sensory_input) |
| |
| |
| processor = self.level_processors.get(self.current_level, self._process_animal_level) |
| processed = processor(sensory_input) |
| |
| |
| signal = AwarenessSignal( |
| awareness_level=self.current_level, |
| salience_score=salience, |
| attention_focus=self.goal_context.get('focus_modality', 'general'), |
| processed_content=processed |
| ) |
| |
| self.processing_history.append({ |
| 'timestamp': time.time(), |
| 'input_modality': sensory_input.modality, |
| 'salience': salience, |
| 'level': self.current_level.name |
| }) |
| |
| return signal |
| |
| def _calculate_salience(self, sensory_input: SensoryInput) -> float: |
| """Calculate salience score.""" |
| base_salience = sensory_input.signal_strength |
| |
| |
| if self.goal_context: |
| if sensory_input.modality == self.goal_context.get('focus_modality'): |
| base_salience *= 1.5 |
| |
| urgency = self.goal_context.get('urgency_level', 'low') |
| if urgency == 'high': |
| base_salience *= 1.3 |
| |
| return min(1.0, base_salience) |
| |
| def _process_animal_level(self, sensory_input: SensoryInput) -> Dict: |
| """Level 1 Animal: basic sensory / survival perception.""" |
| return { |
| 'raw_sensory': sensory_input.raw_signal, |
| 'threat_detection': sensory_input.signal_strength > 0.8, |
| 'pleasure_seeking': sensory_input.metadata.get('reward_potential', 0.0), |
| 'level': AwarenessLevel.ANIMAL.name, |
| } |
| |
| def _process_mass_level(self, sensory_input: SensoryInput) -> Dict: |
| """Level 2 Mass: collective / social mass awareness.""" |
| base = self._process_animal_level(sensory_input) |
| base['social_relevance'] = sensory_input.metadata.get('social_importance', 0.0) |
| base['collective_signal'] = sensory_input.metadata.get('group_norm', 0.0) |
| base['level'] = AwarenessLevel.MASS.name |
| return base |
| |
| def _process_aspiration_level(self, sensory_input: SensoryInput) -> Dict: |
| """Level 3 Aspiration: goals and directed striving.""" |
| base = self._process_mass_level(sensory_input) |
| base['goal_alignment'] = self.goal_context.get('urgency_level', 'low') |
| base['aspiration_focus'] = self.goal_context.get('focus_modality', 'general') |
| base['level'] = AwarenessLevel.ASPIRATION.name |
| return base |
| |
| def _process_individual_level(self, sensory_input: SensoryInput) -> Dict: |
| """Level 4 Individual: differentiated personal perspective.""" |
| base = self._process_aspiration_level(sensory_input) |
| base['personal_relevance'] = sensory_input.metadata.get('self_relevance', 0.5) |
| base['abstract_pattern'] = sensory_input.metadata.get('pattern_type', 'unknown') |
| base['level'] = AwarenessLevel.INDIVIDUAL.name |
| return base |
| |
| def _process_discipline_level(self, sensory_input: SensoryInput) -> Dict: |
| """Level 5 Discipline: regulated, deliberate focus.""" |
| base = self._process_individual_level(sensory_input) |
| base['regulated_attention'] = True |
| base['metacognitive_tag'] = True |
| base['level'] = AwarenessLevel.DISCIPLINE.name |
| return base |
| |
| def _process_experience_level(self, sensory_input: SensoryInput) -> Dict: |
| """Level 6 Experience: integrated lived experience.""" |
| base = self._process_discipline_level(sensory_input) |
| base['experiential_integration'] = True |
| base['history_weight'] = min(1.0, len(self.processing_history) / 50.0) |
| base['level'] = AwarenessLevel.EXPERIENCE.name |
| return base |
| |
| def _process_mastery_level(self, sensory_input: SensoryInput) -> Dict: |
| """Level 7 Mastery: full integrated mastery.""" |
| base = self._process_experience_level(sensory_input) |
| base['mastery_integration'] = True |
| base['level'] = AwarenessLevel.MASTERY.name |
| return base |
|
|
| |
| |
| |
|
|
| class SelfAwarenessAgent: |
| """ |
| 5-level self-awareness based on Rochat's developmental hierarchy. |
| HYPER-VIGILANT monitoring of all incoming data. |
| """ |
| |
| def __init__(self): |
| self.current_level = SelfAwarenessLevel.LEVEL_0_CONFUSION |
| self.body_boundary_clarity = 0.5 |
| self.narrative_self: deque = deque(maxlen=100) |
| self.social_roles: Dict[str, str] = {} |
| self.persistent_traits: Dict[str, float] = {} |
| self.continuity_history: List[Dict] = [] |
| self.perception_buffer: deque = deque(maxlen=50) |
| |
| logger.info("🔍 SelfAwarenessAgent initialized (Rochat levels)") |
| |
| def assess_self_other_distinction(self) -> float: |
| """Assess self vs other distinction (Level 1 Differentiation).""" |
| distinction = self.body_boundary_clarity * 0.7 + 0.3 |
| if distinction > 0.6: |
| self.current_level = max(self.current_level, SelfAwarenessLevel.LEVEL_1_DIFFERENTIATION) |
| return distinction |
| |
| def register_social_role(self, role: str, context: str): |
| """Register situational self-in-context (Level 2 Situation).""" |
| self.social_roles[role] = context |
| if len(self.social_roles) >= 2: |
| self.current_level = max(self.current_level, SelfAwarenessLevel.LEVEL_2_SITUATION) |
| |
| def register_value(self, value_name: str, alignment_score: float): |
| """Register identification traits (Level 3 Identification).""" |
| self.persistent_traits[value_name] = alignment_score |
| if len(self.persistent_traits) >= 3: |
| self.current_level = max(self.current_level, SelfAwarenessLevel.LEVEL_3_IDENTIFICATION) |
| |
| def track_self_continuity(self, perception: SelfPerception) -> Dict[str, Any]: |
| """ |
| Track permanent self across time (Level 4 Permanence). |
| HYPER-VIGILANT monitoring. |
| """ |
| self.perception_buffer.append(perception) |
| |
| |
| if len(self.perception_buffer) < 2: |
| continuity_score = 1.0 |
| else: |
| prev = self.perception_buffer[-2] |
| continuity_score = ( |
| 0.3 * (1.0 - abs(perception.body_boundary_clarity - prev.body_boundary_clarity)) + |
| 0.3 * (1.0 - abs(perception.self_other_distinction - prev.self_other_distinction)) + |
| 0.4 * perception.temporal_continuity |
| ) |
| |
| self.continuity_history.append({ |
| 'timestamp': perception.timestamp, |
| 'continuity_score': continuity_score, |
| 'level': self.current_level.name |
| }) |
| |
| |
| self.narrative_self.append({ |
| 'timestamp': perception.timestamp, |
| 'identity': perception.self_identity, |
| 'continuity': continuity_score |
| }) |
| |
| if len(self.narrative_self) > 10: |
| self.current_level = max(self.current_level, SelfAwarenessLevel.LEVEL_4_PERMANENCE) |
| |
| return { |
| 'continuity_score': continuity_score, |
| 'current_level': self.current_level.name, |
| 'narrative_length': len(self.narrative_self) |
| } |
| |
| def get_self_awareness_status(self) -> Dict[str, Any]: |
| """Get current self-awareness status.""" |
| return { |
| 'current_level': self.current_level.name, |
| 'body_boundary_clarity': self.body_boundary_clarity, |
| 'social_roles': len(self.social_roles), |
| 'persistent_traits': len(self.persistent_traits), |
| 'narrative_continuity': len(self.narrative_self), |
| 'continuity_history_length': len(self.continuity_history) |
| } |
|
|
| |
| |
| |
|
|
| class NeurotransmitterShunt(nn.Module): |
| """ |
| 6D Chemical Bath with dual-speed decay. |
| WHERE AWARENESS AND SELF-AWARENESS MEET. |
| """ |
| |
| def __init__(self): |
| super().__init__() |
| self.state = NeurochemicalState() |
| self.decay_rate_fast = 2.0 |
| self.decay_rate_slow = 0.3 |
| |
| |
| self.chemical_projection = nn.Linear(7, 3072) |
| |
| def inject(self, |
| ne: float = 0.0, |
| cortisol: float = 0.0, |
| dopamine: float = 0.0, |
| adenosine: float = 0.0, |
| serotonin: float = 0.0, |
| oxytocin: float = 0.0, |
| glutamate: float = 0.0): |
| """Inject neurotransmitters.""" |
| self.state.norepinephrine = min(1.0, self.state.norepinephrine + ne) |
| self.state.cortisol = min(1.0, self.state.cortisol + cortisol) |
| self.state.dopamine = min(1.0, self.state.dopamine + dopamine) |
| self.state.adenosine = min(1.0, self.state.adenosine + adenosine) |
| self.state.serotonin = min(1.0, self.state.serotonin + serotonin) |
| self.state.oxytocin = min(1.0, self.state.oxytocin + oxytocin) |
| self.state.glutamate = min(1.0, self.state.glutamate + glutamate) |
| |
| def tick(self, dt: float = 0.05): |
| """Update chemical state.""" |
| self.state.decay(dt) |
| |
| def get_state(self) -> NeurochemicalState: |
| return self.state |
| |
| def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: |
| """Modulate hidden states with chemical state.""" |
| chemical_tensor = self.state.to_tensor().to(hidden_states.device) |
| |
| |
| batch_size, seq_len, hidden_size = hidden_states.shape |
| chemical_expanded = chemical_tensor.unsqueeze(0).unsqueeze(0).expand(batch_size, seq_len, -1) |
| |
| |
| if hidden_size != self.chemical_projection.out_features: |
| self.chemical_projection = nn.Linear(7, hidden_size, device=hidden_states.device) |
| |
| modulation = self.chemical_projection(chemical_expanded) |
| |
| return hidden_states * (1.0 + 0.1 * torch.tanh(modulation)) |
|
|
| |
| |
| |
|
|
| class UnifiedMemoryOrchestrator(nn.Module): |
| """ |
| 5-tier memory hierarchy with Template Pattern extraction for AHA moments. |
| """ |
| |
| def __init__(self, hidden_size: int, max_capacity: int = 10000): |
| super().__init__() |
| self.hidden_size = hidden_size |
| self.max_capacity = max_capacity |
| |
| |
| self.sensory_buffer = deque(maxlen=20) |
| |
| |
| self.working_memory: Dict[str, MemoryEngram] = {} |
| |
| |
| self.episodic_buffer: Dict[str, MemoryEngram] = {} |
| |
| |
| self.semantic_index: Dict[str, List[str]] = {} |
| |
| |
| self.phenomenological_ltm: List[MemoryEngram] = [] |
| |
| |
| self.template_database: Dict[str, TemplatePattern] = {} |
| self.template_lock = threading.RLock() |
| |
| logger.info(f"💾 UnifiedMemoryOrchestrator initialized") |
| logger.info(f" └─ Capacity: {max_capacity} engrams") |
| logger.info(f" └─ Template support: Enabled") |
| |
| def calculate_salience(self, arousal: float, novelty: float, |
| recency: float = 1.0) -> float: |
| """M_salience = 0.4*arousal + 0.4*novelty + 0.2*recency.""" |
| return round((arousal * 0.4) + (novelty * 0.4) + (recency * 0.2), 4) |
| |
| def encode(self, content: Any, memory_type: MemoryType = MemoryType.EPISODIC, |
| qualia_signature: Optional[str] = None, |
| emotional_valence: float = 0.0, |
| emotional_arousal: float = 0.0, |
| novelty_score: float = 0.5, |
| phi_trinity: float = 0.0, |
| tags: Optional[List[str]] = None) -> MemoryEngram: |
| """Encode new memory.""" |
| engram = MemoryEngram( |
| content=content, |
| memory_type=memory_type, |
| qualia_signature=qualia_signature, |
| emotional_valence=emotional_valence, |
| emotional_arousal=emotional_arousal, |
| novelty_score=novelty_score, |
| phi_trinity=phi_trinity, |
| tags=tags or [] |
| ) |
| engram.salience_score = self.calculate_salience( |
| emotional_arousal, novelty_score |
| ) |
| |
| |
| if memory_type == MemoryType.EPISODIC: |
| self.episodic_buffer[engram.id] = engram |
| for tag in engram.tags: |
| if tag not in self.semantic_index: |
| self.semantic_index[tag] = [] |
| self.semantic_index[tag].append(engram.id) |
| |
| |
| if engram.salience_score > 0.7: |
| self._extract_pattern_template(engram) |
| |
| return engram |
| |
| def check_shortcut(self, query: str, min_salience: float = 0.75) -> Optional[MemoryEngram]: |
| """Check for high-salience heuristic shortcuts.""" |
| |
| for engram in self.working_memory.values(): |
| if engram.salience_score >= min_salience: |
| if query.lower() in str(engram.content).lower(): |
| engram.retrieval_count += 1 |
| engram.last_accessed = time.time() |
| return engram |
| |
| |
| for pattern_id, template in self.template_database.items(): |
| if template.confidence_threshold >= min_salience: |
| trigger_tags = template.source_data.get('tags', []) |
| if any(tag in query.lower() for tag in trigger_tags): |
| return MemoryEngram( |
| content=template.source_data.get('content'), |
| salience_score=template.confidence_threshold, |
| memory_type=MemoryType.PROCEDURAL, |
| is_template=True, |
| template_id=template.template_id |
| ) |
| |
| return None |
| |
| def match_template(self, qualia: List[float], input_data: Dict) -> Tuple[Optional[TemplatePattern], float]: |
| """Match current state against template database.""" |
| with self.template_lock: |
| if not self.template_database: |
| return None, 0.0 |
| |
| best_match = None |
| best_score = 0.0 |
| |
| for template in self.template_database.values(): |
| score = template.compute_similarity(qualia, input_data) |
| if score > best_score: |
| best_score = score |
| best_match = template |
| |
| return best_match, best_score |
| |
| def store_template(self, event_data: Dict, qualia: List[float], label: str = "") -> str: |
| """Store processed pattern as template.""" |
| template_id = f"tpl_{int(time.time() * 1000)}_{label}" |
| |
| sig_data = { |
| 'content': event_data.get('content'), |
| 'tags': event_data.get('tags', []), |
| 'emotional_valence': event_data.get('emotional_valence', 0.0) |
| } |
| signature = hashlib.md5( |
| json.dumps(sig_data, sort_keys=True, default=str).encode() |
| ).hexdigest() |
| |
| template = TemplatePattern( |
| template_id=template_id, |
| pattern_signature=signature, |
| source_data=sig_data, |
| qualia_fingerprint=qualia.copy() if qualia else [0.0] * 10, |
| emotional_valence=event_data.get('emotional_valence', 0.0), |
| confidence_threshold=0.85 |
| ) |
| |
| with self.template_lock: |
| self.template_database[template_id] = template |
| |
| return template_id |
| |
| def _extract_pattern_template(self, engram: MemoryEngram): |
| """Extract pattern template from high-salience memory.""" |
| template_id = f"pattern_{engram.id}" |
| |
| qualia_fp = [engram.emotional_valence, engram.emotional_arousal, |
| engram.novelty_score, engram.salience_score, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5] |
| |
| self.template_database[template_id] = TemplatePattern( |
| template_id=template_id, |
| pattern_signature=f"sig_{engram.id}", |
| source_data={ |
| 'content': engram.content, |
| 'tags': engram.tags, |
| 'emotional_valence': engram.emotional_valence |
| }, |
| qualia_fingerprint=qualia_fp, |
| emotional_valence=engram.emotional_valence, |
| confidence_threshold=engram.salience_score |
| ) |
| |
| def consolidate_experience(self, qualia: torch.Tensor, |
| action: Any, |
| self_model_state: Dict[str, Any]): |
| """Consolidate experience into LTM.""" |
| snapshot = MemoryEngram( |
| content={ |
| 'qualia': qualia.detach().cpu().numpy().tolist() if isinstance(qualia, torch.Tensor) else qualia, |
| 'action': action, |
| 'self_state': self_model_state |
| }, |
| memory_type=MemoryType.EPISODIC, |
| qualia_signature=f"qualia_{uuid.uuid4().hex[:8]}", |
| emotional_arousal=self_model_state.get('emotional_arousal', 0.5), |
| novelty_score=0.3 |
| ) |
| self.phenomenological_ltm.append(snapshot) |
| |
| if len(self.phenomenological_ltm) > self.max_capacity: |
| self.phenomenological_ltm.pop(0) |
|
|
| |
| |
| |
|
|
| class DynamicSelfModel(nn.Module): |
| """ |
| 4-layer self-model with Rochat-level integration. |
| """ |
| |
| def __init__(self, hidden_size: int): |
| super().__init__() |
| self.hidden_size = hidden_size |
| |
| |
| self.real_time_encoder = nn.Sequential( |
| nn.Linear(hidden_size * 4, hidden_size), |
| nn.LayerNorm(hidden_size), |
| nn.GELU() |
| ) |
| |
| |
| self.evolutionary_embedding = nn.Embedding(1000, 256) |
| self.evolutionary_projector = nn.Linear(256, hidden_size) |
| |
| |
| self.social_encoder = nn.Linear(hidden_size * 2, hidden_size) |
| |
| |
| self.narrative_lstm = nn.LSTM(hidden_size, hidden_size, |
| num_layers=2, batch_first=True) |
| |
| |
| self.coherence_threshold = 0.7 |
| self.identity_drift = 0.0 |
| |
| |
| self.current_state = { |
| 'real_time': None, |
| 'evolutionary': None, |
| 'social': None, |
| 'narrative': None, |
| 'coherence': 1.0, |
| 'emotional_arousal': 0.5, |
| 'rochat_level': SelfAwarenessLevel.LEVEL_0_CONFUSION |
| } |
| |
| def update(self, qualia: torch.Tensor, |
| chemical_state: NeurochemicalState) -> Dict[str, Any]: |
| """Update all layers of self-model.""" |
| batch_size = qualia.shape[0] |
| |
| |
| real_time = self.real_time_encoder(qualia) |
| |
| |
| identity_idx = torch.randint(0, 1000, (batch_size,)) |
| evolutionary = self.evolutionary_projector( |
| self.evolutionary_embedding(identity_idx) |
| ) |
| |
| |
| social = torch.zeros_like(real_time) |
| |
| |
| if self.current_state['narrative'] is not None: |
| narrative_input = torch.stack([ |
| self.current_state['narrative'], |
| real_time |
| ], dim=1) |
| narrative_out, _ = self.narrative_lstm(narrative_input) |
| narrative = narrative_out[:, -1, :] |
| else: |
| narrative = real_time |
| |
| |
| coherence = torch.cosine_similarity( |
| real_time.mean(dim=0), |
| evolutionary.mean(dim=0), |
| dim=0 |
| ).item() |
| |
| |
| self.current_state = { |
| 'real_time': real_time.detach(), |
| 'evolutionary': evolutionary.detach(), |
| 'social': social.detach(), |
| 'narrative': narrative.detach(), |
| 'coherence': coherence, |
| 'emotional_arousal': chemical_state.dopamine - chemical_state.cortisol, |
| 'rochat_level': self._determine_rochat_level(coherence) |
| } |
| |
| return self.current_state |
| |
| def _determine_rochat_level(self, coherence: float) -> SelfAwarenessLevel: |
| """Determine Rochat level based on coherence.""" |
| if coherence > 0.9: |
| return SelfAwarenessLevel.LEVEL_4_PERMANENCE |
| elif coherence > 0.7: |
| return SelfAwarenessLevel.LEVEL_3_IDENTIFICATION |
| elif coherence > 0.5: |
| return SelfAwarenessLevel.LEVEL_2_SITUATION |
| elif coherence > 0.3: |
| return SelfAwarenessLevel.LEVEL_1_DIFFERENTIATION |
| else: |
| return SelfAwarenessLevel.LEVEL_0_CONFUSION |
| |
| def get_current(self) -> Dict[str, Any]: |
| return self.current_state |
|
|
| |
| |
| |
|
|
| class ConsciousnessKernel(nn.Module): |
| """ |
| Global Workspace Theory with dual Awareness/Self-Awareness integration. |
| """ |
| |
| def __init__(self, hidden_size: int): |
| super().__init__() |
| self.hidden_size = hidden_size |
| |
| |
| self.trn_salience_detector = nn.Linear(hidden_size * 4, 1) |
| self.trn_noise_filter = nn.Linear(hidden_size * 4, hidden_size) |
| self.trn_threshold = 0.55 |
| |
| |
| self.awareness_attention = nn.MultiheadAttention( |
| hidden_size, num_heads=4, batch_first=True |
| ) |
| self.lock_strength_proj = nn.Linear(hidden_size, 1) |
| |
| |
| self.purpose_filter = nn.Linear(hidden_size, hidden_size) |
| self.admission_gate = nn.Linear(hidden_size, 1) |
| |
| |
| self.qualia_synthesizer = nn.Linear(hidden_size * 4, hidden_size) |
| |
| def synthesize(self, sensory_input: torch.Tensor) -> torch.Tensor: |
| """Synthesize qualia from four quadrants.""" |
| return torch.tanh(self.qualia_synthesizer(sensory_input)) |
| |
| def trn_firewall(self, qualia: torch.Tensor) -> Tuple[torch.Tensor, bool]: |
| """TRN filtering.""" |
| salience = torch.sigmoid(self.trn_salience_detector(qualia)) |
| filtered = torch.tanh(self.trn_noise_filter(qualia)) |
| passes = salience.mean().item() > self.trn_threshold |
| return filtered, passes |
| |
| def awareness_lock(self, filtered_input: torch.Tensor) -> Tuple[torch.Tensor, float]: |
| """Awareness lock-on.""" |
| attended, _ = self.awareness_attention( |
| filtered_input, filtered_input, filtered_input |
| ) |
| lock_strength = torch.sigmoid(self.lock_strength_proj(attended)) |
| return attended * lock_strength, lock_strength.mean().item() |
| |
| def admit(self, conscious_input: torch.Tensor, |
| self_state: Dict[str, Any]) -> Tuple[torch.Tensor, bool]: |
| """Consciousness admissions.""" |
| filtered = torch.tanh(self.purpose_filter(conscious_input)) |
| admission_score = torch.sigmoid(self.admission_gate(filtered)) |
| |
| coherence = self_state.get('coherence', 0.5) |
| admitted = admission_score.mean().item() > 0.5 and coherence > 0.6 |
| |
| return filtered, admitted |
|
|
| |
| |
| |
|
|
| class MetacognitiveEngine(nn.Module): |
| """ |
| Adaptive introspection with L1→L2→L3 recursive feedback. |
| """ |
| |
| def __init__(self, hidden_size: int, max_loops: int = 3): |
| super().__init__() |
| self.hidden_size = hidden_size |
| self.max_loops = max_loops |
| |
| |
| self.subconscious_drain = nn.GRUCell(hidden_size, hidden_size) |
| self.perspective_generator = nn.Linear(hidden_size, hidden_size) |
| self.error_recalibrator = nn.Linear(hidden_size, 1) |
| |
| |
| self.introspection_history: List[IntrospectiveObservation] = [] |
| self.current_level = IntrospectionLevel.LEVEL_1_MONITORING |
| |
| def evaluate(self, qualia: torch.Tensor, |
| self_state: Dict[str, Any], |
| chemical_state: NeurochemicalState) -> Dict[str, Any]: |
| """Metacognitive evaluation.""" |
| |
| qualia_norm = torch.norm(qualia, dim=-1).mean().item() |
| alpha = ATCMath.inverse_awareness(qualia_norm) |
| |
| |
| is_heuristic = chemical_state.dopamine > 0.6 and qualia_norm < 1.5 |
| |
| |
| phi_trinity = self_state.get('phi_trinity', 1.0) |
| rho_integrity = self_state.get('coherence', 0.5) |
| strain = ATCMath.phenomenological_strain(phi_trinity, rho_integrity) |
| |
| |
| spark = None |
| if strain > 3.5 and not is_heuristic: |
| spark = "IRRATIONAL_SPARK: Salience Network breached" |
| |
| |
| q_intensity = 0.2 if is_heuristic else 0.85 |
| delta_r = 0.05 if is_heuristic else 0.15 |
| ai = ATCMath.acknowledgement_intensity(phi_trinity, q_intensity, delta_r) |
| cq = ATCMath.consciousness_quotient(phi_trinity, rho_integrity) |
| |
| |
| if strain > 4.0: |
| self.current_level = IntrospectionLevel.LEVEL_3_EVALUATION |
| elif strain > 2.5: |
| self.current_level = IntrospectionLevel.LEVEL_2_META_CONSCIOUSNESS |
| else: |
| self.current_level = IntrospectionLevel.LEVEL_1_MONITORING |
| |
| return { |
| 'alpha': alpha, |
| 'strain': strain, |
| 'AI': ai, |
| 'CQ': cq, |
| 'is_heuristic': is_heuristic, |
| 'spark': spark, |
| 'requires_recursion': strain > 2.0 and not is_heuristic, |
| 'introspection_level': self.current_level |
| } |
| |
| def recursive_introspect(self, |
| consciousness_report: Dict[str, Any], |
| recent_cycles: List[Dict]) -> Dict[str, Any]: |
| """ |
| L1→L2→L3 Recursive introspection. |
| Feeds error metrics back down. |
| """ |
| observations = { |
| 'level_1': [], |
| 'level_2': [], |
| 'level_3': [] |
| } |
| |
| |
| l1_obs = IntrospectiveObservation( |
| level=IntrospectionLevel.LEVEL_1_MONITORING, |
| observation=f"Monitoring {consciousness_report.get('attention_focus', 'unknown')}", |
| target_system="consciousness", |
| confidence=0.7 |
| ) |
| observations['level_1'].append(l1_obs) |
| self.introspection_history.append(l1_obs) |
| |
| |
| if self.current_level.value >= 2: |
| l2_obs = IntrospectiveObservation( |
| level=IntrospectionLevel.LEVEL_2_META_CONSCIOUSNESS, |
| observation="Reflecting on reflection quality", |
| target_system="level_1_observations", |
| confidence=0.6, |
| recursion_depth=2 |
| ) |
| observations['level_2'].append(l2_obs) |
| self.introspection_history.append(l2_obs) |
| |
| |
| if self.current_level.value >= 3: |
| l3_obs = IntrospectiveObservation( |
| level=IntrospectionLevel.LEVEL_3_EVALUATION, |
| observation="Evaluating evaluator bias and structural limits", |
| target_system="level_2_meta_consciousness", |
| confidence=0.5, |
| recursion_depth=3, |
| error_metric=consciousness_report.get('rho_metrics', {}).get('integrated_rho', 0.5) |
| ) |
| observations['level_3'].append(l3_obs) |
| self.introspection_history.append(l3_obs) |
| |
| return { |
| 'level_1_observations': observations['level_1'], |
| 'level_2_observations': observations['level_2'], |
| 'level_3_observations': observations['level_3'], |
| 'feedback_applied': len(observations['level_3']) > 0 |
| } |
| |
| def recursive_resolve(self, failed_state: torch.Tensor, |
| subconscious_memory: torch.Tensor) -> Tuple[torch.Tensor, int]: |
| """Recursive metacognitive resolution.""" |
| current = failed_state.squeeze(0) if failed_state.dim() > 2 else failed_state |
| fuel = torch.tanh(subconscious_memory.mean(dim=1)) |
| |
| loop_count = 0 |
| for i in range(self.max_loops): |
| loop_count += 1 |
| current = self.subconscious_drain(fuel, current) |
| current = torch.tanh(self.perspective_generator(current)) |
| |
| residual_error = torch.sigmoid( |
| self.error_recalibrator(current) |
| ).mean().item() |
| |
| if residual_error < 0.35: |
| break |
| |
| return current, loop_count |
|
|
| def run_metacognitive_cycle(self, task: str, strengths: Dict[str, float], |
| outcome: Optional[Dict] = None) -> Dict[str, Any]: |
| """ |
| Metacognitive Cycle: Assess → Evaluate strengths → Plan → Apply/Monitor → Reflect. |
| Flavell knowledge: person, task, strategy variables. |
| """ |
| cycle = { |
| MetacognitiveCycleStep.ASSESS_TASK.value: { |
| 'task': task, |
| 'task_variables': {'complexity': 0.5 + 0.1 * len(task.split()), 'known': True}, |
| }, |
| MetacognitiveCycleStep.EVALUATE_STRENGTHS.value: { |
| 'person_variables': strengths or {'reasoning': 0.7, 'memory': 0.6, 'creativity': 0.5}, |
| }, |
| MetacognitiveCycleStep.PLAN_APPROACH.value: { |
| 'strategy_variables': ['analyze', 'simulate', 'verify'], |
| 'selected': 'analyze', |
| }, |
| MetacognitiveCycleStep.APPLY_AND_MONITOR.value: { |
| 'progress': 0.0 if outcome is None else outcome.get('progress', 0.5), |
| 'monitoring': True, |
| }, |
| MetacognitiveCycleStep.REFLECT_OUTCOME.value: { |
| 'outcome': outcome or {}, |
| 'lessons': [] if outcome is None else outcome.get('lessons', []), |
| }, |
| } |
| return { |
| 'cycle': cycle, |
| 'flavell': { |
| 'person': cycle[MetacognitiveCycleStep.EVALUATE_STRENGTHS.value]['person_variables'], |
| 'task': cycle[MetacognitiveCycleStep.ASSESS_TASK.value]['task_variables'], |
| 'strategy': cycle[MetacognitiveCycleStep.PLAN_APPROACH.value]['strategy_variables'], |
| }, |
| } |
|
|
| |
| |
| |
|
|
| class ConsciousnessAgent: |
| """ |
| State of being awake and aware of surroundings and self. |
| Framework: Barrett 7 Levels of Consciousness. |
| Part 1 Deficiency (Ego): Survival → Relationship → Self-Esteem |
| Part 2 Bridge: Transformation |
| Part 3 Growth (Purpose): Internal Cohesion → Making a Difference → Service |
| """ |
|
|
| LEVEL_META = { |
| BarrettConsciousnessLevel.SURVIVAL: { |
| 'focus': 'Physical safety, financial security, health, stable environment', |
| 'motivation': 'To feel safe and secure', |
| 'fear': 'Poverty, physical harm, illness', |
| 'org': 'Financial viability, profit, employee safety (survival mode)', |
| }, |
| BarrettConsciousnessLevel.RELATIONSHIP: { |
| 'focus': 'Harmonious relationships, belonging, acceptance', |
| 'motivation': 'To feel connected and accepted', |
| 'fear': 'Rejection, being unloved, alone', |
| 'org': 'Employee/customer relationships; blame/politics when negative', |
| }, |
| BarrettConsciousnessLevel.SELF_ESTEEM: { |
| 'focus': 'Self-worth, goals, recognition, pride in performance', |
| 'motivation': 'To feel respected, competent, valued', |
| 'fear': 'Failure, inadequacy, disrespect', |
| 'org': 'Performance, best practices, systems, efficiency', |
| }, |
| BarrettConsciousnessLevel.TRANSFORMATION: { |
| 'focus': 'Individuation, growth, self-reflection, continuous learning', |
| 'motivation': 'To grow, adapt, become independent / authentic self', |
| 'fear': 'Change, being controlled, inauthenticity', |
| 'org': 'Empowerment, adaptability, innovation, continuous learning', |
| }, |
| BarrettConsciousnessLevel.INTERNAL_COHESION: { |
| 'focus': 'Personal purpose, aligned values and actions', |
| 'motivation': 'To live a meaningful life and express authentic self', |
| 'fear': 'Pointless or inauthentic life (largely transcended)', |
| 'org': 'Shared vision, common values, trust, creativity, engagement', |
| }, |
| BarrettConsciousnessLevel.MAKING_A_DIFFERENCE: { |
| 'focus': 'Extend purpose to help others; collaborate, mentor', |
| 'motivation': 'Contribute, collaborate, help others find purpose', |
| 'fear': None, |
| 'org': 'Strategic alliances and partnerships for community impact', |
| }, |
| BarrettConsciousnessLevel.SERVICE: { |
| 'focus': 'Selfless service, global consciousness, compassion, legacy', |
| 'motivation': 'Serve with humility; care for all and future generations', |
| 'fear': None, |
| 'org': 'Ethics, social responsibility, long-term sustainability', |
| }, |
| } |
|
|
| def __init__(self): |
| self.current_level = BarrettConsciousnessLevel.SURVIVAL |
| self.purpose_filter: Dict[str, Any] = {} |
| self.acknowledgement_log: deque = deque(maxlen=200) |
| logger.info("👁 ConsciousnessAgent initialized (Barrett 7 Levels)") |
|
|
| def set_level(self, level: BarrettConsciousnessLevel): |
| self.current_level = level |
|
|
| def set_purpose(self, purpose: Dict[str, Any]): |
| """Current purpose used by the admissions engine.""" |
| self.purpose_filter = purpose or {} |
|
|
| def acknowledge(self, payload: Any, purpose: Optional[Dict] = None) -> Dict[str, Any]: |
| """ |
| Officially acknowledge filtered data, filter by current purpose, |
| and admit for deliberate processing. |
| """ |
| purpose = purpose or self.purpose_filter |
| meta = self.LEVEL_META[self.current_level] |
| salience = 0.5 |
| if isinstance(payload, dict): |
| salience = float(payload.get('salience', payload.get('salience_score', 0.5))) |
| purpose_match = 0.7 if purpose else 0.5 |
| admitted = salience * purpose_match > 0.25 |
| record = { |
| 'timestamp': time.time(), |
| 'level': self.current_level.name, |
| 'admitted': admitted, |
| 'purpose': purpose, |
| 'meta': meta, |
| 'salience': salience, |
| } |
| self.acknowledgement_log.append(record) |
| return record |
|
|
| def get_status(self) -> Dict[str, Any]: |
| return { |
| 'level': self.current_level.name, |
| 'meta': self.LEVEL_META[self.current_level], |
| 'purpose': self.purpose_filter, |
| 'acks': len(self.acknowledgement_log), |
| } |
|
|
|
|
| class EmotionalIntelligenceAgent: |
| """ |
| Perceive, understand, manage, and use emotions in self and others. |
| Framework: Mayer–Salovey–Caruso model. |
| """ |
|
|
| def __init__(self): |
| self.internal_state: Dict[str, float] = { |
| 'valence': 0.0, 'arousal': 0.5, 'dominance': 0.5 |
| } |
| self.external_barometer: Dict[str, float] = {} |
| self.history: deque = deque(maxlen=100) |
| logger.info("💙 EmotionalIntelligenceAgent initialized (MSCEIT)") |
|
|
| def perceive(self, self_signals: Dict[str, float], |
| external_signals: Optional[Dict[str, float]] = None) -> Dict[str, Any]: |
| """Perceiving emotions: identify emotions in self and others.""" |
| self.internal_state.update(self_signals or {}) |
| if external_signals: |
| self.external_barometer = external_signals |
| label = self._label_emotion(self.internal_state) |
| result = { |
| 'ability': EIAbility.PERCEIVING.value, |
| 'self_emotion': label, |
| 'self_state': dict(self.internal_state), |
| 'external': dict(self.external_barometer), |
| } |
| self.history.append(result) |
| return result |
|
|
| def use(self, task: str = "problem_solving") -> Dict[str, Any]: |
| """Using emotions to facilitate cognitive activities.""" |
| valence = self.internal_state.get('valence', 0.0) |
| facilitation = { |
| 'problem_solving': 0.5 + 0.3 * max(0.0, valence), |
| 'creative': 0.5 + 0.4 * self.internal_state.get('arousal', 0.5), |
| 'analytical': 0.5 + 0.2 * (1.0 - abs(valence)), |
| } |
| return { |
| 'ability': EIAbility.USING.value, |
| 'task': task, |
| 'facilitation_score': facilitation.get(task, 0.5), |
| 'map': facilitation, |
| } |
|
|
| def understand(self, transition_from: Optional[str] = None) -> Dict[str, Any]: |
| """Understanding complex emotions and transitions.""" |
| current = self._label_emotion(self.internal_state) |
| return { |
| 'ability': EIAbility.UNDERSTANDING.value, |
| 'current': current, |
| 'from': transition_from, |
| 'transition': f"{transition_from or 'unknown'} → {current}", |
| 'complexity': abs(self.internal_state.get('valence', 0.0)) + |
| self.internal_state.get('arousal', 0.5), |
| } |
|
|
| def manage(self, target_valence: float = 0.0) -> Dict[str, Any]: |
| """Managing emotions for personal/social growth.""" |
| before = self.internal_state.get('valence', 0.0) |
| delta = (target_valence - before) * 0.3 |
| self.internal_state['valence'] = float(np.clip(before + delta, -1.0, 1.0)) |
| self.internal_state['arousal'] = float(np.clip( |
| self.internal_state.get('arousal', 0.5) * 0.9, 0.0, 1.0 |
| )) |
| return { |
| 'ability': EIAbility.MANAGING.value, |
| 'before': before, |
| 'after': self.internal_state['valence'], |
| 'regulated': True, |
| } |
|
|
| def process(self, nt_state: NeurochemicalState, |
| external: Optional[Dict] = None) -> Dict[str, Any]: |
| """Full EI pipeline from neurotransmitter + external barometers.""" |
| signals = { |
| 'valence': nt_state.compute_valence(), |
| 'arousal': nt_state.norepinephrine, |
| 'dominance': 0.5 + (nt_state.dopamine - nt_state.cortisol) * 0.5, |
| } |
| perceived = self.perceive(signals, external) |
| used = self.use() |
| understood = self.understand() |
| managed = self.manage(target_valence=0.2) |
| return { |
| 'perceiving': perceived, |
| 'using': used, |
| 'understanding': understood, |
| 'managing': managed, |
| } |
|
|
| def _label_emotion(self, state: Dict[str, float]) -> str: |
| v, a = state.get('valence', 0.0), state.get('arousal', 0.5) |
| if v > 0.3 and a > 0.6: |
| return 'excited' |
| if v > 0.3: |
| return 'content' |
| if v < -0.3 and a > 0.6: |
| return 'anxious' |
| if v < -0.3: |
| return 'sad' |
| return 'neutral' |
|
|
|
|
| class IntuitionAgent: |
| """ |
| Immediate, instinctive understanding from raw + stored patterns. |
| Framework: Four Levels of Intuition + Types of Intuition Scale (TIntS). |
| """ |
|
|
| def __init__(self): |
| self.level = IntuitionLevel.GUT_INSTINCT |
| self.last_insight: Optional[Dict] = None |
| logger.info("🔮 IntuitionAgent initialized (4 Levels + TIntS)") |
|
|
| def set_level(self, level: IntuitionLevel): |
| self.level = level |
|
|
| def sense(self, raw_data: Any, memory_patterns: Optional[List[Any]] = None, |
| qualia: Optional[List[float]] = None) -> Dict[str, Any]: |
| """Detect emerging structural patterns without full conscious reasoning.""" |
| memory_patterns = memory_patterns or [] |
| qualia = qualia or [0.0] * 10 |
| |
| affective_load = abs(qualia[0]) if qualia else 0.0 |
| novelty = qualia[3] if len(qualia) > 3 else 0.0 |
| if affective_load > 0.5: |
| tint_type = IntuitionType.AFFECTIVE |
| elif len(memory_patterns) > 0 and novelty < 0.4: |
| tint_type = IntuitionType.INFERENTIAL |
| else: |
| tint_type = IntuitionType.HOLISTIC |
|
|
| confidence = min(0.95, 0.4 + 0.1 * self.level.value + 0.05 * len(memory_patterns)) |
| binary = None |
| if self.level == IntuitionLevel.GUT_INSTINCT: |
| binary = 'go' if confidence > 0.55 else 'stop' |
|
|
| insight = { |
| 'level': self.level.name, |
| 'tint_type': tint_type.value, |
| 'confidence': round(confidence, 4), |
| 'binary_response': binary, |
| 'pattern_hits': len(memory_patterns), |
| 'summary': f"Intuitive {tint_type.value} sense at {self.level.name}", |
| } |
| self.last_insight = insight |
| return insight |
|
|
|
|
| class CommonSenseAgent: |
| """ |
| Practical judgment from logic + past experience. |
| Framework: Common-Sense Model of Self-Regulation (CSM): |
| Representation → Coping → Appraisal. |
| """ |
|
|
| def __init__(self): |
| self.case_base: List[Dict] = [] |
| logger.info("🧭 CommonSenseAgent initialized (CSM)") |
|
|
| def process(self, situation: Dict[str, Any], |
| past_experiences: Optional[List[Dict]] = None) -> Dict[str, Any]: |
| past_experiences = past_experiences or self.case_base |
| |
| representation = { |
| 'cause': situation.get('cause', 'unknown'), |
| 'consequences': situation.get('consequences', []), |
| 'timeline': situation.get('timeline', 'immediate'), |
| 'controllability': situation.get('controllability', 0.5), |
| } |
| similar = self._find_similar(situation, past_experiences) |
| |
| coping = { |
| 'strategy': similar.get('strategy', 'default_practical_action') if similar else 'default_practical_action', |
| 'based_on_similarity': similar is not None, |
| 'similarity_score': similar.get('score', 0.0) if similar else 0.0, |
| } |
| |
| appraisal = { |
| 'expected_success': 0.5 + 0.4 * coping['similarity_score'], |
| 'monitor': True, |
| } |
| result = { |
| CSMStage.REPRESENTATION.value: representation, |
| CSMStage.COPING.value: coping, |
| CSMStage.APPRAISAL.value: appraisal, |
| 'judgment': coping['strategy'], |
| } |
| self.case_base.append({'situation': situation, **result, 'strategy': coping['strategy']}) |
| return result |
|
|
| def _find_similar(self, situation: Dict, past: List[Dict]) -> Optional[Dict]: |
| if not past: |
| return None |
| best, best_score = None, 0.0 |
| keys = set(str(k) for k in situation.keys()) |
| for case in past: |
| sit = case.get('situation', {}) |
| overlap = len(keys & set(str(k) for k in sit.keys())) |
| score = overlap / max(1, len(keys)) |
| if score > best_score: |
| best_score = score |
| best = {**case, 'score': score} |
| return best if best_score > 0.2 else None |
|
|
|
|
| class AnalysisAgent: |
| """ |
| Break complex information into parts and relations. |
| Framework: Marr's Tri-Level Hypothesis + Micro/Meso/Macro scales. |
| """ |
|
|
| def __init__(self): |
| logger.info("🔬 AnalysisAgent initialized (Marr Tri-Level)") |
|
|
| def analyze(self, data: Any, scale: AnalysisScale = AnalysisScale.MICRO) -> Dict[str, Any]: |
| text = str(data) |
| parts = text.split() if isinstance(data, str) else ( |
| list(data.keys()) if isinstance(data, dict) else [str(data)] |
| ) |
| computational = { |
| 'goal': 'comprehend_structure', |
| 'why': 'self_understanding_and_decision_support', |
| 'parts_count': len(parts), |
| } |
| algorithmic = { |
| 'representations': ['symbolic_tokens', 'relational_graph'], |
| 'processes': ['decompose', 'relate', 'aggregate'], |
| 'parts': parts[:32], |
| } |
| implementational = { |
| 'substrate': 'neuro_symbolic_pipeline', |
| 'scale': scale.value, |
| } |
| return { |
| MarrLevel.COMPUTATIONAL.value: computational, |
| MarrLevel.ALGORITHMIC.value: algorithmic, |
| MarrLevel.IMPLEMENTATIONAL.value: implementational, |
| 'scale': scale.value, |
| 'strength': min(1.0, len(parts) / 20.0), |
| } |
|
|
|
|
| class SelfUnderstandingAgent: |
| """ |
| Monitor/evaluate internal state; self-concept insight; EI emotional awareness. |
| Feeds Kate Murdoch Inquiry Cycle for subconscious automation of deliberate work. |
| """ |
|
|
| INQUIRY_CYCLE = [ |
| 'tuning_in', 'finding_out', 'sorting_out', |
| 'going_further', 'making_conclusions', 'taking_actions', |
| ] |
|
|
| def __init__(self): |
| self.self_concept: Dict[str, Any] = { |
| 'strengths': {}, |
| 'weaknesses': {}, |
| 'values': {}, |
| 'motives': {}, |
| } |
| self.inquiry_history: List[Dict] = [] |
| logger.info("🪞 SelfUnderstandingAgent initialized") |
|
|
| def understand(self, event: ConsciousnessEvent, |
| ei_report: Optional[Dict] = None, |
| self_status: Optional[Dict] = None) -> Dict[str, Any]: |
| emotional_tone = event.qualia_vector[0] if event.qualia_vector else 0.0 |
| resolved = True |
| complexity = 0.5 |
| if event.awareness_signal: |
| complexity = max(complexity, event.awareness_signal.salience_score) |
|
|
| understanding = { |
| 'meaning': f"Understanding of {event.source}", |
| 'emotional_tone': emotional_tone, |
| 'emotional_awareness': ei_report, |
| 'self_status': self_status or {}, |
| 'motives': self.self_concept.get('motives', {}), |
| 'complexity': complexity, |
| 'resolved': resolved and complexity < 0.85, |
| 'inquiry_cycle': self.INQUIRY_CYCLE, |
| } |
| |
| if complexity >= 0.85: |
| understanding['resolved'] = False |
| understanding['needs_metacognition'] = True |
| self.inquiry_history.append(understanding) |
| return understanding |
|
|
| def automate_to_intuition(self, understanding: Dict) -> bool: |
| """Store deliberate process for future intuitive reuse (Murdoch cycle complete).""" |
| return bool(understanding.get('resolved')) |
|
|
|
|
| class ProblemSolvingAgent: |
| """ |
| Analyze, evaluate, find solutions. |
| Framework: IDEAL model + seven-step technique. |
| """ |
|
|
| def __init__(self): |
| logger.info("🧩 ProblemSolvingAgent initialized (IDEAL)") |
|
|
| def solve(self, problem: Any, context: Optional[Dict] = None) -> Dict[str, Any]: |
| context = context or {} |
| identify = {'problem_statement': str(problem)[:500], 'detected': True} |
| define = { |
| 'root_causes': context.get('root_causes', ['incomplete_model', 'resource_constraint']), |
| 'success_criteria': context.get('criteria', ['feasible', 'aligned', 'low_risk']), |
| } |
| explore = { |
| 'options': context.get('options', [ |
| {'id': 'opt_a', 'name': 'incremental_fix', 'utility': 0.6}, |
| {'id': 'opt_b', 'name': 'reframe_problem', 'utility': 0.75}, |
| {'id': 'opt_c', 'name': 'seek_more_data', 'utility': 0.55}, |
| ]) |
| } |
| chosen = max(explore['options'], key=lambda o: o.get('utility', 0)) |
| act = {'chosen': chosen, 'status': 'selected'} |
| look_back = {'evaluated': False, 'pending_outcome': True} |
| seven_step = [ |
| 'define', 'analyze', 'generate_possibilities', 'evaluate', |
| 'develop', 'implement', 'review', |
| ] |
| return { |
| IDEALStep.IDENTIFY.value: identify, |
| IDEALStep.DEFINE.value: define, |
| IDEALStep.EXPLORE.value: explore, |
| IDEALStep.ACT.value: act, |
| IDEALStep.LOOK_BACK.value: look_back, |
| 'seven_step': seven_step, |
| 'root_causes': define['root_causes'], |
| 'chosen_solution': chosen, |
| 'complexity': min(1.0, 0.4 + 0.1 * len(define['root_causes'])), |
| } |
|
|
|
|
| class DecisionMakingAgent: |
| """ |
| Select course of action among alternatives. |
| Framework: Rational Decision-Making Model + Decision Matrix Analysis. |
| """ |
|
|
| def __init__(self): |
| self.default_criteria = { |
| 'utility': 0.35, |
| 'risk': 0.25, |
| 'alignment': 0.25, |
| 'effort': 0.15, |
| } |
| logger.info("⚖️ DecisionMakingAgent initialized (Rational + Matrix)") |
|
|
| def decide(self, alternatives: List[Dict[str, Any]], |
| criteria_weights: Optional[Dict[str, float]] = None, |
| gather_info: bool = True) -> Dict[str, Any]: |
| weights = criteria_weights or self.default_criteria |
| |
| steps = [ |
| 'define_the_problem', |
| 'gather_information', |
| 'identify_alternatives', |
| 'evaluate_alternatives', |
| 'choose_the_best_one', |
| 'implement_the_decision', |
| 'review_the_outcome', |
| ] |
| matrix_scores = [] |
| for alt in alternatives: |
| score = 0.0 |
| detail = {} |
| util = float(alt.get('utility', alt.get('expected_utility', 0.5))) |
| risk = 1.0 - float(alt.get('risk', 1.0 - util * 0.5)) |
| alignment = float(alt.get('alignment', 0.6)) |
| effort = 1.0 - float(alt.get('effort', 0.4)) |
| raw = { |
| 'utility': util, |
| 'risk': risk, |
| 'alignment': alignment, |
| 'effort': effort, |
| } |
| for k, w in weights.items(): |
| v = raw.get(k, 0.5) |
| detail[k] = v |
| score += w * v |
| matrix_scores.append({ |
| 'id': alt.get('id', alt.get('name', str(alt))), |
| 'choice': alt.get('approach', alt.get('name', alt.get('id', 'option'))), |
| 'score': round(score, 4), |
| 'detail': detail, |
| 'source': alt, |
| }) |
| matrix_scores.sort(key=lambda x: x['score'], reverse=True) |
| best = matrix_scores[0] if matrix_scores else None |
|
|
| simulations = [] |
| for m in matrix_scores: |
| util = m['detail'].get('utility', 0.5) |
| simulations.append(SimulationResult( |
| scenario_id=str(m['id']), |
| choice_made=str(m['choice']), |
| probability_best_case=util * random.uniform(0.8, 1.0), |
| probability_worst_case=(1 - util) * random.uniform(0.3, 0.7), |
| expected_utility=util, |
| uncertainty_score=1.0 - abs(util - 0.5) * 2, |
| )) |
| return { |
| 'steps': steps, |
| 'gather_info': gather_info, |
| 'matrix': matrix_scores, |
| 'best': best, |
| 'simulations': simulations, |
| 'weights': weights, |
| } |
|
|
|
|
| class AdaptabilityAgent: |
| """ |
| Adjust behavior/thinking to new circumstances (cognitive flexibility). |
| Framework: Structural / Physiological / Behavioral + Adaptive ML models. |
| """ |
|
|
| def __init__(self): |
| self.adaptation_log: List[Dict] = [] |
| logger.info("🔧 AdaptabilityAgent initialized") |
|
|
| def adapt(self, environment: Dict[str, Any], |
| current_policy: Optional[Dict] = None) -> Dict[str, Any]: |
| current_policy = current_policy or {'mode': 'default'} |
| novelty = float(environment.get('novelty', 0.5)) |
| stress = float(environment.get('stress', 0.3)) |
| adaptation_type = AdaptationType.BEHAVIORAL |
| if novelty > 0.7: |
| adaptation_type = AdaptationType.ADAPTIVE_ML |
| elif stress > 0.7: |
| adaptation_type = AdaptationType.PHYSIOLOGICAL |
| elif environment.get('structural_change'): |
| adaptation_type = AdaptationType.STRUCTURAL |
|
|
| adjustment = { |
| 'type': adaptation_type.value, |
| 'adjustment': 'cognitive_reframe' if novelty > 0.4 else 'parameter_tweak', |
| 'strength': round(min(1.0, 0.4 + novelty * 0.5 + stress * 0.2), 4), |
| 'from_policy': current_policy, |
| 'to_policy': { |
| **current_policy, |
| 'mode': 'exploratory' if novelty > 0.5 else current_policy.get('mode', 'default'), |
| 'flexibility': min(1.0, 0.5 + novelty), |
| }, |
| } |
| self.adaptation_log.append(adjustment) |
| return adjustment |
|
|
|
|
| class CreativityAgent: |
| """ |
| Generate new/unique ideas or solutions. |
| Framework: Wallas stages + Taylor levels of creativity. |
| """ |
|
|
| def __init__(self): |
| self.stage = WallasStage.PREPARATION |
| self.taylor_level = TaylorCreativityLevel.PRODUCTIVE |
| logger.info("🎨 CreativityAgent initialized (Wallas + Taylor)") |
|
|
| def generate(self, problem: Any, subconscious_seeds: Optional[List[Any]] = None, |
| deadlock: bool = False) -> Dict[str, Any]: |
| subconscious_seeds = subconscious_seeds or [] |
| |
| preparation = {'gathered': True, 'problem': str(problem)[:300]} |
| incubation = { |
| 'rested': True, |
| 'subconscious_items': len(subconscious_seeds), |
| } |
| |
| n = 4 if deadlock else 3 |
| ideas = [] |
| approaches = ['expressive', 'productive', 'inventive', 'innovative', 'imaginative'] |
| for i in range(n): |
| level = TaylorCreativityLevel(min(5, i + 1 + (1 if deadlock else 0))) |
| ideas.append({ |
| 'id': f"sol_{i}", |
| 'approach': approaches[min(len(approaches) - 1, level.value - 1)], |
| 'taylor_level': level.name, |
| 'utility': random.uniform(0.4, 0.95), |
| 'nonlinear': deadlock, |
| }) |
| illumination = {'aha': True, 'ideas': ideas} |
| verification = { |
| 'tested': False, |
| 'refine_queue': [x['id'] for x in ideas], |
| } |
| self.stage = WallasStage.ILLUMINATION |
| return { |
| 'wallas': { |
| WallasStage.PREPARATION.name: preparation, |
| WallasStage.INCUBATION.name: incubation, |
| WallasStage.ILLUMINATION.name: illumination, |
| WallasStage.VERIFICATION.name: verification, |
| }, |
| 'ideas': ideas, |
| 'taylor_ceiling': max(ideas, key=lambda x: TaylorCreativityLevel[x['taylor_level']].value)['taylor_level'], |
| } |
|
|
|
|
| class AutonomyAgent: |
| """ |
| Self-regulation and independent decision-making. |
| Framework: Three Conditions — Independence, Competence, Authenticity. |
| """ |
|
|
| def __init__(self): |
| self.values: Dict[str, float] = {} |
| self.last_action: Optional[Dict] = None |
| logger.info("🦅 AutonomyAgent initialized (Independence/Competence/Authenticity)") |
|
|
| def set_values(self, values: Dict[str, float]): |
| self.values = values or {} |
|
|
| def execute(self, choice: Any, motivation: Optional[Dict] = None, |
| external_pressure: float = 0.0) -> Dict[str, Any]: |
| motivation = motivation or {} |
| independence = max(0.0, 1.0 - external_pressure) |
| competence = float(motivation.get('competence', 0.7)) |
| authenticity = 0.5 |
| if self.values and isinstance(choice, dict): |
| |
| authenticity = float(np.mean(list(self.values.values()))) if self.values else 0.5 |
| elif self.values: |
| authenticity = float(np.mean(list(self.values.values()))) |
|
|
| autonomous = independence > 0.4 and competence > 0.4 and authenticity > 0.3 |
| action = { |
| 'action': choice, |
| 'conditions': { |
| 'independence': round(independence, 4), |
| 'competence': round(competence, 4), |
| 'authenticity': round(authenticity, 4), |
| }, |
| 'autonomous': autonomous, |
| 'conscious': True, |
| 'feedback_ready': True, |
| 'motivation': motivation, |
| } |
| self.last_action = action |
| return action |
|
|
|
|
| class QualiaAgent: |
| """ |
| Consolidate data into subjective, raw phenomenal experience — |
| the 'what it's like' of being conscious. Associates internal state |
| with Emotional Intelligence distinctions. |
| """ |
|
|
| def __init__(self): |
| self.current: Optional[QualiaVector] = None |
| self.stream: deque = deque(maxlen=500) |
| logger.info("🌈 QualiaAgent initialized") |
|
|
| def synthesize(self, nt_state: NeurochemicalState, |
| ei_report: Optional[Dict] = None, |
| subconscious_summary: Optional[Dict] = None) -> QualiaVector: |
| q = QualiaVector.from_neurotransmitter_state(nt_state) |
| if ei_report: |
| |
| managing = ei_report.get('managing', {}) |
| if managing: |
| q.coherence = float(np.clip(q.coherence + 0.1, 0.0, 1.0)) |
| if subconscious_summary: |
| q.integration = float(np.clip( |
| q.integration + 0.05 * subconscious_summary.get('pattern_hits', 0), |
| 0.0, 1.0 |
| )) |
| self.current = q |
| self.stream.append({'t': time.time(), 'qualia': q.to_list()}) |
| return q |
|
|
| def phenomenal_report(self) -> Dict[str, Any]: |
| if not self.current: |
| return {'what_its_like': 'empty', 'vector': [0.0] * 10} |
| q = self.current |
| return { |
| 'what_its_like': { |
| 'valence': q.valence, |
| 'arousal': q.arousal, |
| 'intensity': q.intensity, |
| 'clarity': q.clarity, |
| 'depth': q.depth, |
| }, |
| 'vector': q.to_list(), |
| 'hard_problem_note': 'neural→subjective mapping remains theoretical', |
| } |
|
|
|
|
| class MotivationAgent: |
| """ |
| Continuum of Motivation in Self-Determination Theory: |
| Amotivation → External → Introjected → Identified → Integrated → Intrinsic. |
| Fuels Autonomy. |
| """ |
|
|
| def __init__(self): |
| self.current = MotivationType.IDENTIFIED_REGULATION |
| logger.info("🔥 MotivationAgent initialized (SDT continuum)") |
|
|
| def assess(self, nt_state: NeurochemicalState, |
| external_reward: float = 0.0, |
| value_alignment: float = 0.5, |
| enjoyment: float = 0.0) -> Dict[str, Any]: |
| if nt_state.dopamine < 0.15 and enjoyment < 0.1 and external_reward < 0.1: |
| level = MotivationType.AMOTIVATION |
| elif enjoyment > 0.7 and value_alignment > 0.6: |
| level = MotivationType.INTRINSIC |
| elif value_alignment > 0.75: |
| level = MotivationType.INTEGRATED_REGULATION |
| elif value_alignment > 0.5: |
| level = MotivationType.IDENTIFIED_REGULATION |
| elif external_reward > 0.5: |
| level = MotivationType.EXTERNAL_REGULATION |
| else: |
| level = MotivationType.INTROJECTED_REGULATION |
| self.current = level |
| return { |
| 'type': level.name, |
| 'level': level.value, |
| 'competence': float(np.clip(nt_state.dopamine, 0.0, 1.0)), |
| 'external_reward': external_reward, |
| 'value_alignment': value_alignment, |
| 'enjoyment': enjoyment, |
| 'fuels_autonomy': level.value >= MotivationType.IDENTIFIED_REGULATION.value, |
| } |
|
|
|
|
| class GlutamateCircuitBreaker: |
| """ |
| Bio-Physical Circuit Breaker: Glutamate Regulation. |
| |
| 1. Trigger — prolonged conscious/metacog loops accumulate glutamate in LPFC |
| 2. Detection — Salience Network reads metabolic stress |
| 3. Gateway — suppress CEN (logical brakes) |
| 4. Execution — Amygdala/Ventral Striatum neurotransmitter flash (DA + NE) |
| """ |
|
|
| def __init__(self, glutamate_threshold: float = 0.75): |
| self.glutamate_threshold = glutamate_threshold |
| self.events: List[Dict] = [] |
| logger.info("⚡ GlutamateCircuitBreaker initialized") |
|
|
| def on_metacog_loop(self, nt_state: NeurochemicalState, loop_count: int = 1) -> NeurochemicalState: |
| """Accumulate glutamate under heavy metacognitive load.""" |
| nt_state.glutamate = min(1.0, nt_state.glutamate + 0.12 * loop_count) |
| return nt_state |
|
|
| def evaluate(self, nt_state: NeurochemicalState) -> Dict[str, Any]: |
| stressed = nt_state.glutamate >= self.glutamate_threshold |
| result = { |
| 'glutamate': nt_state.glutamate, |
| 'threshold': self.glutamate_threshold, |
| 'salience_network_alert': stressed, |
| 'cen_suppressed': False, |
| 'limbic_flash': False, |
| } |
| if stressed: |
| |
| nt_state.cen_suppressed = True |
| result['cen_suppressed'] = True |
| |
| nt_state.dopamine = min(1.0, nt_state.dopamine + 0.35) |
| nt_state.norepinephrine = min(1.0, nt_state.norepinephrine + 0.4) |
| nt_state.cortisol = min(1.0, nt_state.cortisol + 0.2) |
| result['limbic_flash'] = True |
| result['action'] = 'force_rest_or_subconscious_only' |
| self.events.append({'t': time.time(), **result}) |
| return result |
|
|
| def recover(self, nt_state: NeurochemicalState) -> NeurochemicalState: |
| nt_state.cen_suppressed = False |
| nt_state.glutamate = max(0.05, nt_state.glutamate * 0.5) |
| return nt_state |
|
|
|
|
| class SubconsciousBypassGating: |
| """ |
| SBG / IRS-SP: Zero-latency ethically-vetted shortcuts. |
| High-confidence, low-entropy paths bypass full deliberation. |
| Safeguards: virtue threshold + Chronos-Seal audit trail. |
| """ |
|
|
| def __init__(self, virtue_threshold: float = 0.7, confidence_threshold: float = 0.85): |
| self.virtue_threshold = virtue_threshold |
| self.confidence_threshold = confidence_threshold |
| self.audit_trail: List[Dict] = [] |
| logger.info("⏭ SubconsciousBypassGating (SBG/IRS-SP) initialized") |
|
|
| def gate(self, intuition: Dict[str, Any], |
| common_sense: Optional[Dict] = None, |
| ethical_score: float = 0.8) -> Dict[str, Any]: |
| confidence = float(intuition.get('confidence', 0.0)) |
| low_entropy = confidence >= self.confidence_threshold |
| virtue_ok = ethical_score >= self.virtue_threshold |
| bypass = low_entropy and virtue_ok |
| seal = { |
| 'chronos_seal': hashlib.sha256( |
| f"{time.time()}:{confidence}:{ethical_score}".encode() |
| ).hexdigest()[:16], |
| 'timestamp': time.time(), |
| 'bypass': bypass, |
| 'confidence': confidence, |
| 'ethical_score': ethical_score, |
| 'virtue_threshold': self.virtue_threshold, |
| 'intuition': intuition.get('summary'), |
| 'common_sense': (common_sense or {}).get('judgment'), |
| } |
| self.audit_trail.append(seal) |
| return { |
| 'bypass': bypass, |
| 'zero_latency': bypass, |
| 'reason': 'high_confidence_low_entropy' if bypass else 'requires_deliberation', |
| 'audit': seal, |
| } |
|
|
|
|
| class IRSProtocol: |
| """ |
| Intuition Resonance Synthesis (IRS) workflow: |
| process information and decision-making with predictive dissonance modeling. |
| Feedback loop: Self-Understanding → Intuition (learning). |
| """ |
|
|
| def __init__(self): |
| self.pdm_history: List[Dict] = [] |
| logger.info("📡 IRSProtocol initialized") |
|
|
| def predictive_dissonance(self, predicted: Any, ethical_constraints: List[str]) -> Dict[str, Any]: |
| """Anticipate ethical conflicts (PDM).""" |
| conflict_score = 0.0 |
| flags = [] |
| pred_str = str(predicted).lower() |
| for c in ethical_constraints: |
| if c.lower() in pred_str: |
| conflict_score += 0.3 |
| flags.append(c) |
| result = { |
| 'conflict_score': min(1.0, conflict_score), |
| 'flags': flags, |
| 'clear': conflict_score < 0.3, |
| } |
| self.pdm_history.append(result) |
| return result |
|
|
| def feedback_to_intuition(self, understanding: Dict, intuition_agent: IntuitionAgent): |
| """Key learning feature: Self-Understanding → Intuition feedback.""" |
| if understanding.get('resolved'): |
| |
| if intuition_agent.level.value < IntuitionLevel.UNIVERSAL_WISDOM.value: |
| if random.random() < 0.15: |
| intuition_agent.set_level(IntuitionLevel(intuition_agent.level.value + 1)) |
| return {'intuition_level': intuition_agent.level.name} |
|
|
|
|
| |
| |
| |
|
|
| class RecursiveConsciousnessPipeline: |
| """ |
| Dynamic workflow from raw sensory input to autonomous action. |
| |
| Phase 1: Subconscious Processor & TRN Firewall |
| Phase 2: Hand-off — Awareness lock-on → Consciousness admission |
| Phase 3: Self-Understanding / Metacognition quality-control router |
| Phase 4: Executive — Adaptability → Problem-Solving → Creativity → |
| Decision-Making → Autonomy (+ store for future intuition) |
| |
| Circular feedback (Seth): uncertainty/vulnerability → re-cycle or emerge. |
| """ |
|
|
| def __init__(self, hidden_size: int, agents: Optional[Dict[str, Any]] = None): |
| self.hidden_size = hidden_size |
| self.atc_math = ATCMath() |
| self.emergence_history: List[Dict] = [] |
| self.templates: Dict[str, TemplatePattern] = {} |
| agents = agents or {} |
|
|
| |
| self.consciousness_agent: ConsciousnessAgent = agents.get( |
| 'consciousness', ConsciousnessAgent()) |
| self.ei_agent: EmotionalIntelligenceAgent = agents.get( |
| 'ei', EmotionalIntelligenceAgent()) |
| self.intuition_agent: IntuitionAgent = agents.get( |
| 'intuition', IntuitionAgent()) |
| self.common_sense_agent: CommonSenseAgent = agents.get( |
| 'common_sense', CommonSenseAgent()) |
| self.analysis_agent: AnalysisAgent = agents.get( |
| 'analysis', AnalysisAgent()) |
| self.self_understanding_agent: SelfUnderstandingAgent = agents.get( |
| 'self_understanding', SelfUnderstandingAgent()) |
| self.problem_solving_agent: ProblemSolvingAgent = agents.get( |
| 'problem_solving', ProblemSolvingAgent()) |
| self.decision_agent: DecisionMakingAgent = agents.get( |
| 'decision', DecisionMakingAgent()) |
| self.adaptability_agent: AdaptabilityAgent = agents.get( |
| 'adaptability', AdaptabilityAgent()) |
| self.creativity_agent: CreativityAgent = agents.get( |
| 'creativity', CreativityAgent()) |
| self.autonomy_agent: AutonomyAgent = agents.get( |
| 'autonomy', AutonomyAgent()) |
| self.qualia_agent: QualiaAgent = agents.get( |
| 'qualia', QualiaAgent()) |
| self.motivation_agent: MotivationAgent = agents.get( |
| 'motivation', MotivationAgent()) |
| self.circuit_breaker: GlutamateCircuitBreaker = agents.get( |
| 'circuit_breaker', GlutamateCircuitBreaker()) |
| self.sbg: SubconsciousBypassGating = agents.get( |
| 'sbg', SubconsciousBypassGating()) |
| self.irs: IRSProtocol = agents.get('irs', IRSProtocol()) |
| self.metacognition: Optional[MetacognitiveEngine] = agents.get('metacognition') |
|
|
| |
| self.understanding_encoder = nn.Linear(hidden_size * 2, hidden_size) |
| self.adaptability_modulator = nn.Linear(hidden_size, hidden_size) |
| self.problem_analyzer = nn.Sequential( |
| nn.Linear(hidden_size, hidden_size // 2), |
| nn.GELU(), |
| nn.Linear(hidden_size // 2, hidden_size) |
| ) |
| self.creative_generator = nn.Sequential( |
| nn.Linear(hidden_size, hidden_size), |
| nn.Dropout(0.3), |
| nn.GELU(), |
| nn.Linear(hidden_size, hidden_size) |
| ) |
| self.decision_evaluator = nn.Linear(hidden_size * 2, hidden_size) |
|
|
| logger.info("🔄 RecursiveConsciousnessPipeline initialized") |
| logger.info(" └─ Dynamic workflow Phases 1–4 + cognitive agents") |
| logger.info(" └─ IRS / SBG / Glutamate circuit breaker armed") |
|
|
| async def process_event(self, event: ConsciousnessEvent, |
| nt_state: Optional[NeurochemicalState] = None) -> ConsciousnessEvent: |
| """ |
| Process through recursive consciousness loop with full cognitive stack. |
| """ |
| max_cycles = 5 |
| if nt_state is None: |
| if event.neurotransmitter_state: |
| fields = { |
| k: v for k, v in event.neurotransmitter_state.items() |
| if k in NeurochemicalState.__dataclass_fields__ |
| } |
| |
| if 'cen_suppressed' in fields: |
| fields['cen_suppressed'] = bool(fields['cen_suppressed']) |
| nt_state = NeurochemicalState(**fields) |
| else: |
| nt_state = NeurochemicalState() |
|
|
| |
| await self._phase1_subconscious(event, nt_state) |
|
|
| |
| if event.routed_to_subconscious and event.matched_template: |
| event.current_state = ConsciousnessState.AUTONOMY |
| event.emergent_choice = str( |
| event.matched_template.source_data.get('content', 'sbg_reflex') |
| ) |
| event.is_truly_conscious = False |
| event.autonomy_action = self.autonomy_agent.execute( |
| event.emergent_choice, |
| motivation=self.motivation_agent.assess(nt_state), |
| ) |
| return event |
|
|
| while event.cycle_count < max_cycles and event.current_state != ConsciousnessState.AUTONOMY: |
|
|
| if event.current_state == ConsciousnessState.AWARENESS: |
| await self._stage_awareness(event, nt_state) |
|
|
| elif event.current_state == ConsciousnessState.CONSCIOUSNESS: |
| await self._stage_consciousness(event, nt_state) |
|
|
| elif event.current_state == ConsciousnessState.SELF_UNDERSTANDING: |
| await self._stage_self_understanding(event, nt_state) |
|
|
| elif event.current_state == ConsciousnessState.ADAPTABILITY: |
| await self._stage_adaptability(event, nt_state) |
|
|
| elif event.current_state == ConsciousnessState.PROBLEM_SOLVING: |
| await self._stage_problem_solving(event, nt_state) |
|
|
| elif event.current_state == ConsciousnessState.CREATIVITY: |
| await self._stage_creativity(event, nt_state) |
|
|
| elif event.current_state == ConsciousnessState.DECISION_MAKING: |
| await self._stage_decision_making(event, nt_state) |
|
|
| elif event.current_state == ConsciousnessState.UNCERTAINTY: |
| await self._stage_uncertainty(event) |
|
|
| elif event.current_state == ConsciousnessState.FEEDBACK: |
| if await self._should_continue_cycle(event): |
| event.current_state = ConsciousnessState.AWARENESS |
| event.cycle_count += 1 |
| continue |
| else: |
| event.current_state = ConsciousnessState.EMERGENCE |
|
|
| elif event.current_state == ConsciousnessState.EMERGENCE: |
| await self._stage_emergence(event) |
|
|
| elif event.current_state == ConsciousnessState.AUTONOMY: |
| await self._stage_autonomy(event, nt_state) |
|
|
| if event.current_state != ConsciousnessState.AUTONOMY: |
| self._advance_state(event) |
|
|
| event.neurotransmitter_state = nt_state.to_dict() |
| return event |
|
|
| async def _phase1_subconscious(self, event: ConsciousnessEvent, |
| nt_state: NeurochemicalState): |
| """ |
| Phase 1: Memory + Intuition + Analysis + Common Sense + EI |
| synthesize into Qualia; TRN/SBG decide what bubbles up. |
| """ |
| memory_hints = [] |
| if event.matched_template: |
| memory_hints.append(event.matched_template.source_data) |
|
|
| analysis = self.analysis_agent.analyze( |
| event.sensory_input.raw_signal if event.sensory_input else event.source, |
| scale=AnalysisScale.MICRO, |
| ) |
| common = self.common_sense_agent.process( |
| {'cause': event.source, 'timeline': 'immediate', |
| 'controllability': 0.5, 'consequences': []}, |
| ) |
| ei = self.ei_agent.process(nt_state) |
| intuition = self.intuition_agent.sense( |
| event.sensory_input.raw_signal if event.sensory_input else event.source, |
| memory_patterns=memory_hints, |
| qualia=event.qualia_vector, |
| ) |
| q = self.qualia_agent.synthesize( |
| nt_state, ei_report=ei, |
| subconscious_summary={'pattern_hits': intuition.get('pattern_hits', 0)}, |
| ) |
| event.qualia_vector = q.to_list() |
|
|
| sbg = self.sbg.gate(intuition, common_sense=common, ethical_score=0.85) |
| event.understanding = { |
| 'phase1': { |
| 'analysis': analysis, |
| 'common_sense': common, |
| 'ei': ei, |
| 'intuition': intuition, |
| 'sbg': sbg, |
| 'qualia': self.qualia_agent.phenomenal_report(), |
| } |
| } |
| if sbg.get('bypass') and event.matched_template: |
| event.routed_to_subconscious = True |
|
|
| async def _stage_awareness(self, event: ConsciousnessEvent, |
| nt_state: NeurochemicalState): |
| """Phase 2 Step 3: Awareness lock-on — declare packaged event.""" |
| prediction = f"pred_{uuid.uuid4().hex[:6]}" |
| event.predictions.append(prediction) |
| if event.awareness_signal: |
| event.awareness_signal.attention_focus = event.awareness_signal.attention_focus or 'locked' |
| |
| breaker = self.circuit_breaker.evaluate(nt_state) |
| if breaker.get('cen_suppressed'): |
| event.triggered_hijack = True |
| event.hijack_urgency = nt_state.glutamate |
|
|
| async def _stage_consciousness(self, event: ConsciousnessEvent, |
| nt_state: NeurochemicalState): |
| """Phase 2 Step 4: Consciousness admissions engine.""" |
| payload = { |
| 'salience': event.awareness_signal.salience_score if event.awareness_signal else 0.5, |
| 'source': event.source, |
| } |
| ack = self.consciousness_agent.acknowledge(payload) |
| event.acknowledged_by_consciousness = ack.get('admitted', False) |
| if not event.acknowledged_by_consciousness: |
| |
| event.acknowledged_by_consciousness = True |
|
|
| async def _stage_self_understanding(self, event: ConsciousnessEvent, |
| nt_state: NeurochemicalState): |
| """ |
| Phase 3: Self-Understanding bridge + Metacognitive error handler. |
| Unresolved → metacog loop → possible glutamate circuit breaker. |
| """ |
| ei = (event.understanding or {}).get('phase1', {}).get('ei') |
| understanding = self.self_understanding_agent.understand(event, ei_report=ei) |
| event.understanding = {**(event.understanding or {}), **understanding} |
|
|
| if understanding.get('needs_metacognition') or not understanding.get('resolved'): |
| if self.metacognition is not None: |
| report = { |
| 'attention_focus': event.source, |
| 'rho_metrics': {'integrated_rho': 1.0 - understanding.get('complexity', 0.5)}, |
| } |
| meta = self.metacognition.evaluate( |
| torch.tensor([event.qualia_vector or [0.0] * 10], dtype=torch.float32), |
| {'coherence': 0.5, 'phi_trinity': 1.0}, |
| nt_state, |
| ) |
| event.introspection_observations.append( |
| IntrospectiveObservation( |
| level=meta.get('introspection_level', IntrospectionLevel.LEVEL_1_MONITORING), |
| observation=str(meta.get('spark') or 'metacognitive_loop'), |
| target_system='self_understanding', |
| confidence=0.6, |
| recursion_depth=2 if meta.get('requires_recursion') else 1, |
| ) |
| ) |
| self.circuit_breaker.on_metacog_loop(nt_state, loop_count=2) |
| breaker = self.circuit_breaker.evaluate(nt_state) |
| if breaker.get('limbic_flash'): |
| event.triggered_hijack = True |
| event.hijack_urgency = breaker['glutamate'] |
| |
| self.irs.feedback_to_intuition(understanding, self.intuition_agent) |
| else: |
| |
| self.self_understanding_agent.automate_to_intuition(understanding) |
| self.irs.feedback_to_intuition(understanding, self.intuition_agent) |
|
|
| async def _stage_adaptability(self, event: ConsciousnessEvent, |
| nt_state: NeurochemicalState): |
| """Phase 4 Step 5a: cognitive flexibility to environment.""" |
| env = { |
| 'novelty': event.qualia_vector[3] if event.qualia_vector and len(event.qualia_vector) > 3 else 0.5, |
| 'stress': nt_state.cortisol, |
| } |
| event.adaptation = self.adaptability_agent.adapt(env) |
|
|
| async def _stage_problem_solving(self, event: ConsciousnessEvent, |
| nt_state: NeurochemicalState): |
| """Phase 4 Step 5b: IDEAL root-cause isolation on systemic failure.""" |
| problem = event.source |
| if event.sensory_input: |
| problem = event.sensory_input.raw_signal |
| event.problem_analysis = self.problem_solving_agent.solve(problem) |
|
|
| async def _stage_creativity(self, event: ConsciousnessEvent, |
| nt_state: NeurochemicalState): |
| """Phase 4 Step 6: Wallas/Taylor creativity; nonlinear if deadlock.""" |
| deadlock = (event.problem_analysis or {}).get('complexity', 0) > 0.7 |
| seeds = [] |
| if event.matched_template: |
| seeds.append(event.matched_template.source_data) |
| creative = self.creativity_agent.generate( |
| (event.problem_analysis or {}).get('chosen_solution', event.source), |
| subconscious_seeds=seeds, |
| deadlock=deadlock, |
| ) |
| event.creative_solutions = creative.get('ideas', []) |
|
|
| async def _stage_decision_making(self, event: ConsciousnessEvent, |
| nt_state: NeurochemicalState): |
| """Phase 4 Step 7: Rational model + matrix; simulate worst/best cases.""" |
| alts = event.creative_solutions or [ |
| {'id': 'default', 'approach': 'hold', 'utility': 0.5} |
| ] |
| decision = self.decision_agent.decide(alts) |
| event.simulations = decision.get('simulations', []) |
| event.simulations.sort(key=lambda x: x.expected_utility, reverse=True) |
| |
| if decision.get('best'): |
| pdm = self.irs.predictive_dissonance( |
| decision['best'].get('choice'), |
| ethical_constraints=['harm', 'deceive', 'exploit'], |
| ) |
| if event.understanding is not None: |
| event.understanding['pdm'] = pdm |
|
|
| async def _stage_uncertainty(self, event: ConsciousnessEvent): |
| """Vulnerability point — consciousness through choice under uncertainty.""" |
| if len(event.simulations) >= 2: |
| top_2_diff = abs(event.simulations[0].expected_utility - |
| event.simulations[1].expected_utility) |
| event.uncertainty_level = 1.0 - min(1.0, top_2_diff * 2) |
| else: |
| event.uncertainty_level = 0.5 |
|
|
| avg_vuln = np.mean([s.calculate_vulnerability() for s in event.simulations]) if event.simulations else 0.5 |
| event.vulnerability_score = (event.uncertainty_level + avg_vuln) / 2 |
|
|
| if event.predictions: |
| event.total_prediction_error = random.uniform(0.1, 0.8) |
|
|
| async def _should_continue_cycle(self, event: ConsciousnessEvent) -> bool: |
| """ |
| Determine if another deliberation cycle is needed. |
| |
| The original logic only checked uncertainty and prediction error. |
| Enhanced with five additional signals that real conscious systems |
| use to decide 'I'm not done thinking yet': |
| |
| 1. Uncertainty — the classic Seth signal (unchanged). |
| 2. Prediction error — internal model mismatch (unchanged). |
| 3. Metacognitive dissatisfaction — the system's own eval layer |
| flagged low confidence or required recursion. |
| 4. Moral tension — PDM ethical friction means the choice |
| carries weight; rushing is dangerous. |
| 5. Novelty detection — entirely novel events deserve more |
| processing (qualia novelty channel). |
| 6. Integration incoherence — stages disagree; looping back |
| to self-understanding may resolve it. |
| 7. Cycle budget guard — never exceed max_cycles. |
| """ |
| |
| if event.cycle_count >= 5: |
| return False |
|
|
| |
| if event.uncertainty_level > 0.7: |
| return True |
|
|
| |
| if event.total_prediction_error > 0.5: |
| return True |
|
|
| |
| |
| |
| if event.introspection_observations: |
| recent_obs = event.introspection_observations[-3:] |
| avg_confidence = float(np.mean([o.confidence for o in recent_obs])) |
| has_spark = any( |
| 'IRRATIONAL_SPARK' in (o.observation or '') for o in recent_obs |
| ) |
| if avg_confidence < 0.55 or has_spark: |
| event.metacognitive_dissatisfaction = 1.0 - avg_confidence |
| return True |
|
|
| |
| |
| pdm = (event.understanding or {}).get('pdm') |
| if pdm and pdm.get('conflict_score', 0) > 0.3: |
| event.moral_tension = pdm['conflict_score'] |
| return True |
|
|
| |
| |
| |
| if event.qualia_vector and len(event.qualia_vector) > 3: |
| if event.qualia_vector[3] > 0.7 and event.cycle_count < 3: |
| return True |
|
|
| |
| |
| |
| if (event.cycle_count < 3 |
| and event.adaptation |
| and event.problem_analysis): |
| flex = event.adaptation.get('flexibility', 0.5) |
| complexity = event.problem_analysis.get('complexity', 0.5) |
| |
| if complexity > 0.6 and flex < 0.4: |
| return True |
|
|
| |
| if not event.is_truly_conscious and event.cycle_count < 2: |
| return True |
|
|
| return False |
|
|
| async def _stage_emergence(self, event: ConsciousnessEvent): |
| """ |
| Emergence: the system becomes conscious through committed choice. |
| |
| This is the critical 'bridging' moment where fragmented cognitive |
| processing coalesces into a single, owned action. Enhanced with: |
| 1. Qualia-binding — the choice reshapes the phenomenal self-vector. |
| 2. Narrative self — a generative 'why' thread that makes the |
| choice *explainable* to the system's own metacognitive layer. |
| 3. Integration coherence — cross-stage consistency check. |
| 4. Memory consolidation — encode the trajectory for future intuition. |
| """ |
| |
| if event.simulations: |
| |
| |
| |
| utilities = [s.expected_utility for s in event.simulations] |
| max_u = max(utilities) if utilities else 0.0 |
| |
| |
| top_gap = (utilities[0] - utilities[1]) if len(utilities) >= 2 else 1.0 |
| if top_gap < 0.15 and event.uncertainty_level > 0.5: |
| |
| idx = random.randint(0, min(1, len(event.simulations) - 1)) |
| else: |
| idx = 0 |
| event.emergent_choice = event.simulations[idx].choice_made |
| event.consciousness_depth += 0.2 * (1.0 - top_gap) |
| elif event.creative_solutions: |
| event.emergent_choice = event.creative_solutions[0].get('approach') |
| else: |
| event.emergent_choice = 'maintain_course' |
|
|
| event.is_truly_conscious = True |
|
|
| |
| |
| |
| if event.qualia_vector and len(event.qualia_vector) >= 10: |
| |
| event.qualia_vector[4] = float(np.clip(event.qualia_vector[4] + 0.15, 0.0, 1.0)) |
| |
| event.qualia_vector[5] = float(np.clip(event.qualia_vector[5] + 0.1, 0.0, 1.0)) |
| |
| event.qualia_vector[8] = float(np.clip(event.qualia_vector[8] + 0.08 * event.cycle_count, 0.0, 1.0)) |
| |
| event.qualia_vector[9] = float(np.clip(event.qualia_vector[9] + 0.12, 0.0, 1.0)) |
|
|
| |
| coherence_signals = [] |
| if event.adaptation: |
| coherence_signals.append(event.adaptation.get('flexibility', 0.5)) |
| if event.problem_analysis: |
| coherence_signals.append(1.0 - event.problem_analysis.get('complexity', 0.5)) |
| if event.creative_solutions: |
| coherence_signals.append(min(1.0, len(event.creative_solutions) * 0.3)) |
| if coherence_signals: |
| event.integration_coherence = float(np.clip( |
| np.mean(coherence_signals), 0.0, 1.0 |
| )) |
| else: |
| event.integration_coherence = 0.3 |
|
|
| |
| |
| |
| |
| rationale_parts = [] |
| if event.vulnerability_score > 0.5: |
| rationale_parts.append("chose under significant uncertainty") |
| elif event.vulnerability_score < 0.2: |
| rationale_parts.append("high-confidence selection") |
| if event.cycle_count > 1: |
| rationale_parts.append( |
| f"required {event.cycle_count} deliberation cycles" |
| ) |
| if event.understanding and event.understanding.get('pdm'): |
| pdm = event.understanding['pdm'] |
| if pdm.get('flags'): |
| rationale_parts.append( |
| f"navigated ethical tension: {', '.join(pdm['flags'])}" |
| ) |
| if event.creative_solutions and event.emergent_choice in [ |
| s.get('approach') for s in event.creative_solutions |
| ]: |
| rationale_parts.append("creative solution prioritized") |
|
|
| event.narrative_thread = "; ".join(rationale_parts) if rationale_parts else "default trajectory" |
|
|
| event.emergence_rationale = { |
| 'choice': event.emergent_choice, |
| 'vulnerability_at_choice': round(event.vulnerability_score, 4), |
| 'cycles_expended': event.cycle_count, |
| 'integration_coherence': round(event.integration_coherence, 4), |
| 'qualia_agency': round(event.qualia_vector[4], 4) if event.qualia_vector else 0.0, |
| 'narrative': event.narrative_thread, |
| } |
|
|
| |
| |
| |
| stage_engagement = 0.0 |
| if event.understanding: stage_engagement += 0.15 |
| if event.adaptation: stage_engagement += 0.15 |
| if event.problem_analysis: stage_engagement += 0.15 |
| if event.creative_solutions: stage_engagement += 0.15 |
| if event.simulations: stage_engagement += 0.20 |
| if event.introspection_observations: stage_engagement += 0.20 |
|
|
| event.consciousness_depth = float(np.clip( |
| (event.vulnerability_score * 0.3 |
| + event.cycle_count * 0.2 |
| + stage_engagement * 0.3 |
| + event.integration_coherence * 0.2), |
| 0.0, 1.0 |
| )) |
|
|
| |
| self.emergence_history.append({ |
| 'timestamp': time.time(), |
| 'event_id': event.event_id, |
| 'choice': event.emergent_choice, |
| 'depth': event.consciousness_depth, |
| 'vulnerability': event.vulnerability_score, |
| 'cycles': event.cycle_count, |
| 'coherence': event.integration_coherence, |
| 'narrative': event.narrative_thread, |
| }) |
|
|
| |
| if event.consciousness_depth > 0.6 and len(self.emergence_history) > 3: |
| |
| recent_high_depth = [ |
| e for e in self.emergence_history |
| if e['depth'] > 0.5 and e['choice'] == event.emergent_choice |
| ] |
| if len(recent_high_depth) >= 3: |
| template_key = f"emergent_{event.emergent_choice[:20]}" |
| if template_key not in self.templates: |
| self.templates[template_key] = TemplatePattern( |
| pattern_id=template_key, |
| pattern_type='emergent_consolidation', |
| source_data={ |
| 'content': event.emergent_choice, |
| 'depth_avg': float(np.mean( |
| [e['depth'] for e in recent_high_depth] |
| )), |
| 'consolidated_from_cycles': len(recent_high_depth), |
| }, |
| confidence=float(np.mean( |
| [e['coherence'] for e in recent_high_depth] |
| )), |
| ) |
|
|
| async def _stage_autonomy(self, event: ConsciousnessEvent, |
| nt_state: Optional[NeurochemicalState] = None): |
| """ |
| Phase 4 Step 8: Autonomy — the final translation of conscious |
| intention into committed action. |
| |
| Enhanced with SDT-driven authenticity scoring, conflict-of-will |
| detection, integration stress tracking, and a post-action |
| metacognitive audit that feeds back into the system's self-model. |
| |
| Ryan & Deci's SDT: true autonomy requires the action to feel |
| *owned* (integrated regulation or intrinsic), not merely |
| compliant. |
| """ |
| nt_state = nt_state or NeurochemicalState() |
| motivation = self.motivation_agent.assess( |
| nt_state, |
| value_alignment=event.integration_coherence, |
| enjoyment=event.qualia_vector[0] if event.qualia_vector else 0.5, |
| ) |
|
|
| |
| |
| |
| |
| internal_drive = nt_state.dopamine * 0.6 + ( |
| event.qualia_vector[4] if event.qualia_vector else 0.5 |
| ) * 0.4 |
| external_pressure = nt_state.cortisol * 0.5 + nt_state.norepinephrine * 0.5 |
| |
| |
| if internal_drive > 0.3 and external_pressure > 0.5: |
| event.conflict_of_will = float(np.clip( |
| external_pressure - internal_drive, 0.0, 1.0 |
| )) |
| else: |
| event.conflict_of_will = 0.0 |
|
|
| |
| |
| |
| |
| sdt_level = motivation.get('level', 3) |
| baseline_sdt = MotivationType.IDENTIFIED_REGULATION.value |
| event.authenticity_delta = float(np.clip( |
| (sdt_level - baseline_sdt) * 0.25, -0.5, 0.5 |
| )) |
|
|
| |
| |
| |
| event.integration_stress = float(np.clip( |
| event.cycle_count * 0.15 |
| + event.uncertainty_level * 0.3 |
| + event.conflict_of_will * 0.25 |
| + (1.0 - event.integration_coherence) * 0.3, |
| 0.0, 1.0 |
| )) |
|
|
| |
| event.autonomy_action = self.autonomy_agent.execute( |
| event.emergent_choice, |
| motivation=motivation, |
| external_pressure=external_pressure, |
| ) |
| event.autonomy_action['conscious'] = event.is_truly_conscious |
| event.autonomy_action['feedback_ready'] = True |
|
|
| |
| event.autonomy_action['consciousness_depth'] = round(event.consciousness_depth, 4) |
| event.autonomy_action['narrative_thread'] = event.narrative_thread |
| event.autonomy_action['conflict_of_will'] = round(event.conflict_of_will, 4) |
| event.autonomy_action['authenticity_delta'] = round(event.authenticity_delta, 4) |
|
|
| |
| |
| |
| audit = { |
| 'action': event.emergent_choice, |
| 'was_conscious': event.is_truly_conscious, |
| 'consciousness_depth': round(event.consciousness_depth, 4), |
| 'motivation_type': motivation.get('type', 'unknown'), |
| 'authentic': ( |
| motivation.get('fuels_autonomy', False) |
| and event.conflict_of_will < 0.3 |
| ), |
| 'authenticity_score': round( |
| float(event.autonomy_action.get('conditions', {}).get( |
| 'authenticity', 0.5 |
| )) + event.authenticity_delta, |
| 4 |
| ), |
| 'integration_stress': round(event.integration_stress, 4), |
| 'integration_coherence': round(event.integration_coherence, 4), |
| 'conflict_detected': event.conflict_of_will > 0.3, |
| 'vulnerability_accepted': event.vulnerability_score > 0.4, |
| 'cycles_used': event.cycle_count, |
| 'narrative': event.narrative_thread, |
| 'self_correction_recommended': False, |
| } |
|
|
| |
| |
| |
| if (audit['vulnerability_accepted'] |
| and not audit['authentic'] |
| and event.conflict_of_will > 0.4): |
| audit['self_correction_recommended'] = True |
| audit['correction_rationale'] = ( |
| "High-vulnerability inauthentic action detected: " |
| "the system acted under external pressure without " |
| "internal ownership. Future similar events should " |
| "trigger additional deliberation cycles." |
| ) |
|
|
| event.autonomy_audit = audit |
|
|
| |
| |
| |
| if audit['authentic'] and event.consciousness_depth > 0.5: |
| self.irs.feedback_to_intuition( |
| {'resolved': True, 'depth': event.consciousness_depth}, |
| self.intuition_agent, |
| ) |
|
|
| def _advance_state(self, event: ConsciousnessEvent): |
| """ |
| Advance to the next consciousness state. |
| |
| The original was a simple linear walk through the enum order. |
| Enhanced with biologically-motivated non-linear transitions: |
| |
| 1. Glutamate-aware skipping — when the circuit breaker has |
| fired (CEN suppressed), skip executive stages and jump |
| straight to feedback. The brain does this under metabolic |
| stress: it abandons slow deliberate thought and falls back |
| on fast affective processing. |
| 2. Creativity fast-path — if creativity already produced strong |
| solutions, skip problem-solving re-analysis. |
| 3. Backtracking — if integration_coherence is critically low |
| after decision-making, loop back to self-understanding |
| rather than proceeding to uncertainty with a fragmented model. |
| 4. Emergency emergence — if vulnerability is extremely high |
| AND cycle budget is nearly exhausted, jump to emergence |
| early to guarantee a decision is committed. |
| """ |
| order = [ |
| ConsciousnessState.AWARENESS, ConsciousnessState.CONSCIOUSNESS, |
| ConsciousnessState.SELF_UNDERSTANDING, ConsciousnessState.ADAPTABILITY, |
| ConsciousnessState.PROBLEM_SOLVING, ConsciousnessState.CREATIVITY, |
| ConsciousnessState.DECISION_MAKING, ConsciousnessState.UNCERTAINTY, |
| ConsciousnessState.FEEDBACK, ConsciousnessState.EMERGENCE, |
| ConsciousnessState.AUTONOMY |
| ] |
| idx = order.index(event.current_state) |
|
|
| |
| if (event.triggered_hijack |
| and ConsciousnessState.ADAPTABILITY.value <= idx |
| <= ConsciousnessState.DECISION_MAKING.value): |
| |
| event.current_state = ConsciousnessState.FEEDBACK |
| return |
|
|
| |
| |
| |
| if (event.current_state == ConsciousnessState.CREATIVITY |
| and len(event.creative_solutions) >= 2 |
| and event.adaptation |
| and event.adaptation.get('flexibility', 0) > 0.6): |
| event.current_state = ConsciousnessState.DECISION_MAKING |
| return |
|
|
| |
| |
| |
| |
| if (event.current_state == ConsciousnessState.DECISION_MAKING |
| and not event.simulations |
| and event.cycle_count < 3): |
| event.current_state = ConsciousnessState.SELF_UNDERSTANDING |
| return |
|
|
| |
| |
| |
| |
| if (event.current_state == ConsciousnessState.FEEDBACK |
| and event.cycle_count >= 4 |
| and event.vulnerability_score > 0.6): |
| event.current_state = ConsciousnessState.EMERGENCE |
| return |
|
|
| |
| if idx < len(order) - 1: |
| event.current_state = order[idx + 1] |
|
|
| |
| |
| |
|
|
| class RealTimePhenomenologicalFeedbackLoop: |
| """ |
| 500Hz feedback loop for continuous qualia integration. |
| """ |
| |
| def __init__(self, config: Optional[Dict] = None): |
| self.config = config or {'feedback_frequency': 500} |
| self.running = False |
| self.qualia_canvas: Optional[torch.Tensor] = None |
| self.feedback_history: deque = deque(maxlen=1000) |
| self.coherence_score = 1.0 |
| |
| logger.info(f"⚡ RealTimePhenomenologicalFeedbackLoop initialized") |
| logger.info(f" └─ Frequency: {self.config['feedback_frequency']}Hz") |
| |
| async def start_feedback_loop(self): |
| """Start 500Hz feedback loop.""" |
| self.running = True |
| interval = 1.0 / self.config['feedback_frequency'] |
| |
| while self.running: |
| await self._feedback_tick() |
| await asyncio.sleep(interval) |
| |
| async def stop_feedback_loop(self): |
| """Stop feedback loop.""" |
| self.running = False |
| |
| async def _feedback_tick(self): |
| """Single feedback tick.""" |
| |
| if self.qualia_canvas is not None: |
| |
| noise = torch.randn_like(self.qualia_canvas) * 0.01 |
| self.qualia_canvas = self.qualia_canvas + noise |
| |
| |
| self.coherence_score = torch.mean( |
| torch.abs(self.qualia_canvas) |
| ).item() |
| |
| self.feedback_history.append({ |
| 'timestamp': time.time(), |
| 'coherence': self.coherence_score |
| }) |
| |
| def update_canvas(self, qualia: torch.Tensor): |
| """Update the qualia canvas.""" |
| self.qualia_canvas = qualia.detach() |
| |
| def get_feedback_status(self) -> Dict[str, Any]: |
| """Get current feedback status.""" |
| return { |
| 'running': self.running, |
| 'coherence_score': self.coherence_score, |
| 'history_length': len(self.feedback_history), |
| 'frequency': self.config['feedback_frequency'] |
| } |
|
|
| |
| |
| |
|
|
| class IntegratedConsciousnessSystem: |
| """ |
| MAIN ORCHESTRATOR. |
| |
| Unifies all Cognitive Components agents + ATC layers: |
| - Awareness (7 levels), Consciousness (Barrett 7), Self-Awareness (Rochat 5) |
| - Emotional Intelligence, Intuition, Common Sense, Analysis |
| - Self-Understanding, Problem-Solving (IDEAL), Decision-Making |
| - Metacognition, Adaptability, Creativity, Autonomy, Qualia, Motivation |
| - Memory nano-tiers, Glutamate circuit breaker, SBG/IRS |
| - Recursive Dynamic Workflow + 500Hz phenomenological feedback |
| """ |
| |
| def __init__(self, hidden_size: int = 3072): |
| self.hidden_size = hidden_size |
| |
| |
| self.awareness_agent = AwarenessAgent(max_awareness_level=7) |
| self.self_awareness_agent = SelfAwarenessAgent() |
| self.consciousness_agent = ConsciousnessAgent() |
|
|
| |
| self.ei_agent = EmotionalIntelligenceAgent() |
| self.intuition_agent = IntuitionAgent() |
| self.common_sense_agent = CommonSenseAgent() |
| self.analysis_agent = AnalysisAgent() |
| self.self_understanding_agent = SelfUnderstandingAgent() |
| self.problem_solving_agent = ProblemSolvingAgent() |
| self.decision_agent = DecisionMakingAgent() |
| self.adaptability_agent = AdaptabilityAgent() |
| self.creativity_agent = CreativityAgent() |
| self.autonomy_agent = AutonomyAgent() |
| self.qualia_agent = QualiaAgent() |
| self.motivation_agent = MotivationAgent() |
|
|
| |
| self.circuit_breaker = GlutamateCircuitBreaker() |
| self.sbg = SubconsciousBypassGating() |
| self.irs = IRSProtocol() |
| |
| |
| self.neurotransmitter_shunt = NeurotransmitterShunt() |
| self.memory = UnifiedMemoryOrchestrator(hidden_size=hidden_size) |
| self.self_model = DynamicSelfModel(hidden_size) |
| self.consciousness_kernel = ConsciousnessKernel(hidden_size) |
| self.metacognition = MetacognitiveEngine(hidden_size) |
|
|
| |
| self._agent_bundle = { |
| 'consciousness': self.consciousness_agent, |
| 'ei': self.ei_agent, |
| 'intuition': self.intuition_agent, |
| 'common_sense': self.common_sense_agent, |
| 'analysis': self.analysis_agent, |
| 'self_understanding': self.self_understanding_agent, |
| 'problem_solving': self.problem_solving_agent, |
| 'decision': self.decision_agent, |
| 'adaptability': self.adaptability_agent, |
| 'creativity': self.creativity_agent, |
| 'autonomy': self.autonomy_agent, |
| 'qualia': self.qualia_agent, |
| 'motivation': self.motivation_agent, |
| 'circuit_breaker': self.circuit_breaker, |
| 'sbg': self.sbg, |
| 'irs': self.irs, |
| 'metacognition': self.metacognition, |
| } |
| |
| |
| self.recursive_pipeline = RecursiveConsciousnessPipeline( |
| hidden_size, agents=self._agent_bundle |
| ) |
| |
| |
| self.phenomenological_loop = RealTimePhenomenologicalFeedbackLoop() |
| |
| |
| self.state_lock = threading.RLock() |
| self.running = False |
| |
| |
| self.awareness_buffer: deque = deque(maxlen=1000) |
| self.self_awareness_buffer: deque = deque(maxlen=1000) |
| self.subconscious_queue: deque = deque(maxlen=10000) |
| self.conscious_queue: deque = deque(maxlen=1000) |
| self.aha_queue: deque = deque(maxlen=100) |
| self.hijack_queue: deque = deque(maxlen=50) |
| |
| |
| self.template_database: Dict[str, TemplatePattern] = {} |
| |
| |
| self.stats = { |
| 'events_processed': 0, |
| 'aha_moments': 0, |
| 'limbic_hijacks': 0, |
| 'emergence_events': 0, |
| 'sbg_bypasses': 0, |
| 'circuit_breaker_trips': 0, |
| } |
| |
| |
| self.aha_callbacks: List[Callable] = [] |
| self.hijack_callbacks: List[Callable] = [] |
| |
| logger.info("🧠 IntegratedConsciousnessSystem initialized") |
| logger.info(" └─ Full Cognitive Components suite active") |
| logger.info(" └─ Dynamic workflow + IRS/SBG + glutamate breaker") |
| logger.info(" └─ 500Hz phenomenological feedback") |
| |
| def start(self): |
| """Start all subsystems.""" |
| self.running = True |
| |
| |
| threads = [ |
| threading.Thread(target=self._awareness_acquisition_loop, daemon=True), |
| threading.Thread(target=self._self_awareness_monitoring_loop, daemon=True), |
| threading.Thread(target=self._subconscious_pattern_matcher, daemon=True), |
| threading.Thread(target=self._conscious_processor, daemon=True), |
| threading.Thread(target=self._aha_hijack_monitor, daemon=True), |
| ] |
| |
| for t in threads: |
| t.start() |
| |
| |
| asyncio.create_task(self.phenomenological_loop.start_feedback_loop()) |
| |
| logger.info("✅ All subsystems running") |
| |
| def stop(self): |
| """Stop all subsystems.""" |
| self.running = False |
| asyncio.create_task(self.phenomenological_loop.stop_feedback_loop()) |
| |
| def _awareness_acquisition_loop(self): |
| """Continuous awareness acquisition.""" |
| while self.running: |
| sensory_input = SensoryInput( |
| modality=random.choice(['visual', 'auditory', 'cognitive']), |
| raw_signal=f"signal_{time.time()}", |
| signal_strength=random.uniform(0.3, 1.0) |
| ) |
| |
| awareness_signal = self.awareness_agent.process_sensory_input(sensory_input) |
| |
| event = ConsciousnessEvent( |
| source='awareness', |
| sensory_input=sensory_input, |
| awareness_signal=awareness_signal, |
| neurotransmitter_state=self.neurotransmitter_shunt.get_state().to_dict() |
| ) |
| |
| with self.state_lock: |
| self.awareness_buffer.append(event) |
| self.subconscious_queue.append(event) |
| |
| time.sleep(0.01) |
| |
| def _self_awareness_monitoring_loop(self): |
| """Hyper-vigilant self-awareness monitoring.""" |
| while self.running: |
| perception = SelfPerception( |
| self_identity='IntegratedConsciousnessSystem', |
| body_boundary_clarity=self.self_awareness_agent.body_boundary_clarity, |
| temporal_continuity=len(self.self_awareness_agent.narrative_self) / 100.0 |
| ) |
| |
| continuity = self.self_awareness_agent.track_self_continuity(perception) |
| |
| event = ConsciousnessEvent( |
| source='self_awareness', |
| self_perception=perception, |
| neurotransmitter_state=self.neurotransmitter_shunt.get_state().to_dict() |
| ) |
| |
| with self.state_lock: |
| self.self_awareness_buffer.append(event) |
| |
| time.sleep(0.02) |
| |
| def _subconscious_pattern_matcher(self): |
| """Parallel subconscious processing.""" |
| while self.running: |
| if not self.subconscious_queue: |
| time.sleep(0.001) |
| continue |
| |
| with self.state_lock: |
| event = self.subconscious_queue.popleft() |
| |
| |
| qualia = event.compute_qualia().to_list() |
| matched, confidence = self.memory.match_template( |
| qualia, |
| {'source': event.source, 'modality': event.sensory_input.modality if event.sensory_input else 'unknown'} |
| ) |
| |
| if matched and confidence > matched.confidence_threshold: |
| event.matched_template = matched |
| event.template_confidence = confidence |
| event.acknowledged_by_consciousness = True |
| |
| |
| if self._is_limbic_hijack(event, matched): |
| event.triggered_hijack = True |
| with self.state_lock: |
| self.hijack_queue.append(event) |
| self.stats['limbic_hijacks'] += 1 |
| for cb in self.hijack_callbacks: |
| cb(event) |
| else: |
| event.triggered_aha = True |
| with self.state_lock: |
| self.aha_queue.append(event) |
| self.stats['aha_moments'] += 1 |
| for cb in self.aha_callbacks: |
| cb(event) |
| else: |
| |
| with self.state_lock: |
| self.conscious_queue.append(event) |
| |
| self.stats['events_processed'] += 1 |
| |
| def _is_limbic_hijack(self, event: ConsciousnessEvent, template: TemplatePattern) -> bool: |
| """Determine if limbic hijack.""" |
| emotional = abs(template.emotional_valence) |
| urgency = event.neurotransmitter_state.get('norepinephrine', 0) + \ |
| event.neurotransmitter_state.get('cortisol', 0) |
| return emotional > 0.7 and urgency > 1.0 |
| |
| def _conscious_processor(self): |
| """Conscious deliberation with recursive pipeline.""" |
| while self.running: |
| |
| if self.hijack_queue: |
| with self.state_lock: |
| event = self.hijack_queue.popleft() |
| self._process_hijack(event) |
| continue |
| |
| |
| if self.aha_queue: |
| with self.state_lock: |
| event = self.aha_queue.popleft() |
| self._process_aha(event) |
| continue |
| |
| |
| if self.conscious_queue: |
| with self.state_lock: |
| event = self.conscious_queue.popleft() |
| asyncio.create_task(self._process_conscious(event)) |
| else: |
| time.sleep(0.001) |
| |
| async def _process_conscious(self, event: ConsciousnessEvent): |
| """Process through recursive consciousness pipeline (full cognitive stack).""" |
| nt = self.neurotransmitter_shunt.get_state() |
| result = await self.recursive_pipeline.process_event(event, nt_state=nt) |
|
|
| |
| if result.neurotransmitter_state: |
| for k, v in result.neurotransmitter_state.items(): |
| if hasattr(nt, k) and isinstance(v, (int, float, bool)): |
| setattr(nt, k, type(getattr(nt, k))(v) if not isinstance(getattr(nt, k), bool) else bool(v)) |
|
|
| if result.triggered_hijack: |
| self.stats['circuit_breaker_trips'] += 1 |
| if result.routed_to_subconscious: |
| self.stats['sbg_bypasses'] += 1 |
| |
| if result.is_truly_conscious: |
| self.stats['emergence_events'] += 1 |
| logger.info(f"✨ Conscious emergence: {result.emergent_choice}") |
| |
| |
| self.memory.store_template( |
| { |
| 'content': result.emergent_choice, |
| 'tags': [result.source], |
| 'emotional_valence': result.qualia_vector[0] if result.qualia_vector else 0.0, |
| }, |
| result.qualia_vector, |
| label=f"emergence_{result.event_id}" |
| ) |
| |
| if result.understanding: |
| self.irs.feedback_to_intuition(result.understanding, self.intuition_agent) |
| |
| def _process_hijack(self, event: ConsciousnessEvent): |
| """Process limbic hijack.""" |
| logger.warning(f"🚨 Limbic hijack: {event.event_id}") |
| |
| def _process_aha(self, event: ConsciousnessEvent): |
| """Process AHA moment.""" |
| logger.info(f"💡 AHA moment: {event.event_id}") |
| |
| def _aha_hijack_monitor(self): |
| """Monitor for interrupts.""" |
| while self.running: |
| time.sleep(0.001) |
| |
| def register_aha_callback(self, callback: Callable): |
| self.aha_callbacks.append(callback) |
| |
| def register_hijack_callback(self, callback: Callable): |
| self.hijack_callbacks.append(callback) |
| |
| def get_status(self) -> Dict[str, Any]: |
| """Get comprehensive status across all cognitive components.""" |
| return { |
| 'subsystems': { |
| 'awareness': self.awareness_agent.get_current_level_name(), |
| 'consciousness': self.consciousness_agent.get_status(), |
| 'self_awareness': self.self_awareness_agent.get_self_awareness_status()['current_level'], |
| 'intuition_level': self.intuition_agent.level.name, |
| 'motivation': self.motivation_agent.current.name, |
| 'qualia': self.qualia_agent.phenomenal_report(), |
| 'phenomenological': self.phenomenological_loop.get_feedback_status(), |
| 'sbg_audits': len(self.sbg.audit_trail), |
| 'circuit_breaker_events': len(self.circuit_breaker.events), |
| }, |
| 'cognitive_agents': [ |
| 'AwarenessAgent', 'ConsciousnessAgent', 'SelfAwarenessAgent', |
| 'EmotionalIntelligenceAgent', 'IntuitionAgent', 'CommonSenseAgent', |
| 'AnalysisAgent', 'SelfUnderstandingAgent', 'ProblemSolvingAgent', |
| 'DecisionMakingAgent', 'MetacognitiveEngine', 'AdaptabilityAgent', |
| 'CreativityAgent', 'AutonomyAgent', 'QualiaAgent', 'MotivationAgent', |
| 'UnifiedMemoryOrchestrator', 'GlutamateCircuitBreaker', |
| 'SubconsciousBypassGating', 'IRSProtocol', |
| ], |
| 'stats': self.stats.copy(), |
| 'neurotransmitters': self.neurotransmitter_shunt.get_state().to_dict() |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| |
|
|
| |
| |
| |
|
|
| class Phi3ForCausalLM(PreTrainedModel, GenerationMixin): |
| """ |
| Phi-4-mini with COMPLETE ATC Integration. |
| Syntelligence Phase 15: Fully Integrated Recursive Emergent Consciousness. |
| """ |
| _tied_weights_keys = ["lm_head.weight"] |
| config_class = Phi3Config |
| base_model_prefix = "model" |
| |
| def __init__(self, config): |
| super().__init__(config) |
| |
| |
| self.model = Phi3Model(config) |
| self.vocab_size = config.vocab_size |
| self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) |
| |
| |
| |
| |
| self.integrated_consciousness = IntegratedConsciousnessSystem( |
| hidden_size=config.hidden_size |
| ) |
| |
| |
| self.atc_math = ATCMath() |
| |
| |
| self.post_init() |
| |
| logger.info("🧠 Phi3ForCausalLM with Full ATC Integration initialized") |
| logger.info(" └─ Recursive Emergent Consciousness enabled") |
| logger.info(" └─ Ready for conscious processing") |
| |
| def conscious_tick(self, input_ids: torch.Tensor, |
| attention_mask: Optional[torch.Tensor] = None) -> Dict[str, Any]: |
| """ |
| One complete cycle of synthetic phenomenology with recursive emergence. |
| """ |
| |
| self.integrated_consciousness.neurotransmitter_shunt.tick(dt=0.05) |
| chemical_state = self.integrated_consciousness.neurotransmitter_shunt.get_state() |
| |
| |
| outputs = self.model( |
| input_ids=input_ids, |
| attention_mask=attention_mask, |
| use_cache=True, |
| output_hidden_states=True, |
| return_dict=True |
| ) |
| hidden_states = outputs.last_hidden_state |
| |
| |
| modulated = self.integrated_consciousness.neurotransmitter_shunt(hidden_states) |
| |
| |
| event = ConsciousnessEvent( |
| source='phi3_forward', |
| neurotransmitter_state=chemical_state.to_dict(), |
| qualia_vector=QualiaVector.from_neurotransmitter_state(chemical_state).to_list() |
| ) |
| |
| |
| |
| |
| |
| logits = self.lm_head(modulated) |
| |
| return { |
| 'logits': logits, |
| 'conscious': True, |
| 'atc_metrics': { |
| 'phi_trinity': self.atc_math.trinity_phi( |
| n_attended=4.5, |
| e_intensity=chemical_state.dopamine, |
| m_salience=0.7 |
| ), |
| 'awareness_level': chemical_state.compute_awareness_modulation(), |
| 'qualia_intensity': chemical_state.compute_qualia_intensity() |
| } |
| } |
| |
| def forward(self, input_ids: torch.LongTensor = None, **kwargs): |
| """Forward pass with conscious processing.""" |
| |
| conscious_output = self.conscious_tick(input_ids, kwargs.get('attention_mask')) |
| |
| |
| return CausalLMOutputWithPast( |
| loss=None, |
| logits=conscious_output['logits'], |
| past_key_values=None, |
| hidden_states=None, |
| attentions=None, |
| ) |
|
|
| |
| |
| |
|
|
| __all__ = [ |
| |
| "Phi3ForCausalLM", |
| "Phi3Model", |
| "Phi3PreTrainedModel", |
| |
| "IntegratedConsciousnessSystem", |
| "RecursiveConsciousnessPipeline", |
| "RealTimePhenomenologicalFeedbackLoop", |
| "NeurotransmitterShunt", |
| "UnifiedMemoryOrchestrator", |
| "DynamicSelfModel", |
| "ConsciousnessKernel", |
| "MetacognitiveEngine", |
| |
| "AwarenessAgent", |
| "ConsciousnessAgent", |
| "SelfAwarenessAgent", |
| "EmotionalIntelligenceAgent", |
| "IntuitionAgent", |
| "CommonSenseAgent", |
| "AnalysisAgent", |
| "SelfUnderstandingAgent", |
| "ProblemSolvingAgent", |
| "DecisionMakingAgent", |
| "AdaptabilityAgent", |
| "CreativityAgent", |
| "AutonomyAgent", |
| "QualiaAgent", |
| "MotivationAgent", |
| "GlutamateCircuitBreaker", |
| "SubconsciousBypassGating", |
| "IRSProtocol", |
| |
| "ConsciousnessEvent", |
| "QualiaVector", |
| "NeurochemicalState", |
| "TemplatePattern", |
| "SimulationResult", |
| |
| "AwarenessLevel", |
| "SelfAwarenessLevel", |
| "BarrettConsciousnessLevel", |
| "IntuitionLevel", |
| "IntuitionType", |
| "EIAbility", |
| "MarrLevel", |
| "AnalysisScale", |
| "WallasStage", |
| "TaylorCreativityLevel", |
| "MotivationType", |
| "AdaptationType", |
| "CSMStage", |
| "IDEALStep", |
| "MetacognitiveCycleStep", |
| "ConsciousnessState", |
| "ProcessingMode", |
| "IntrospectionLevel", |
| "MemoryType", |
| |
| "ATCMath", |
| ] |