From c784f86098570b8409e99f2c66fcea1776635453 Mon Sep 17 00:00:00 2001 From: AdaWorldAPI Date: Thu, 29 Jan 2026 20:39:44 +0100 Subject: [PATCH 1/2] Add src/cognitive/substrate.rs (audit recovery from session) --- src/cognitive/substrate.rs | 586 +++++++++++++++++++++++++++++++++++++ 1 file changed, 586 insertions(+) create mode 100644 src/cognitive/substrate.rs diff --git a/src/cognitive/substrate.rs b/src/cognitive/substrate.rs new file mode 100644 index 0000000..45fec14 --- /dev/null +++ b/src/cognitive/substrate.rs @@ -0,0 +1,586 @@ +//! Unified Cognitive Substrate +//! +//! Integrates all cognitive components into one resonance field: +//! - QuadTriangles (4 × 10K-bit VSA) +//! - 7-Layer Consciousness Stack +//! - Collapse Gate with SIMD SD +//! - 12 Thinking Styles +//! - mRNA Cross-Pollination +//! +//! ```text +//! ┌─────────────────────────────────────────────────────────────────────┐ +//! │ UNIFIED COGNITIVE SUBSTRATE │ +//! │ │ +//! │ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │ +//! │ │ QuadTriangle │ │ 7-Layer │ │ Thinking │ │ +//! │ │ (40K-bit) │◄──►│ Consciousness│◄──►│ Style │ │ +//! │ │ │ │ │ │ Modulation │ │ +//! │ │ Processing │ │ L7: Meta │ │ │ │ +//! │ │ Content │ │ L6: Exec │ │ Analytical │ │ +//! │ │ Gestalt │ │ L5: Working │ │ Creative │ │ +//! │ │ Crystal │ │ L4: Episodic │ │ Focused │ │ +//! │ │ │ │ L3: Semantic │ │ Intuitive │ │ +//! │ └───────┬───────┘ │ L2: Pattern │ │ ... │ │ +//! │ │ │ L1: Sensory │ └───────┬───────┘ │ +//! │ │ └───────┬───────┘ │ │ +//! │ │ │ │ │ +//! │ ▼ ▼ ▼ │ +//! │ ┌─────────────────────────────────────────────────────────────┐ │ +//! │ │ mRNA RESONANCE FIELD │ │ +//! │ │ │ │ +//! │ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │ +//! │ │ │ Concept │ │ Concept │ │ Concept │ │ ... │ │ │ +//! │ │ │ 10K │ │ 10K │ │ 10K │ │ │ │ │ +//! │ │ └────┬────┘ └────┬────┘ └────┬────┘ └─────────┘ │ │ +//! │ │ │ │ │ │ │ +//! │ │ └────────────┴────────────┘ │ │ +//! │ │ │ │ │ +//! │ │ SUPERPOSITION │ │ +//! │ │ (10K-bit) │ │ +//! │ └─────────────────────┬───────────────────────────────────────┘ │ +//! │ │ │ +//! │ ▼ │ +//! │ ┌─────────────────────────────────────────────────────────────┐ │ +//! │ │ COLLAPSE GATE │ │ +//! │ │ │ │ +//! │ │ SD < 0.15 │ 0.15 ≤ SD ≤ 0.35 │ SD > 0.35 │ │ +//! │ │ ─────────── │ ───────────────── │ ─────────── │ │ +//! │ │ ?? FLOW │ ?? HOLD │ ?? BLOCK │ │ +//! │ │ (commit) │ (superposition) │ (clarify) │ │ +//! │ └─────────────────────────────────────────────────────────────┘ │ +//! └─────────────────────────────────────────────────────────────────────┘ +//! ``` + +use std::sync::{Arc, RwLock}; +use std::time::Instant; + +use crate::core::{Fingerprint, VsaOps}; +use crate::cognitive::style::{ThinkingStyle, FieldModulation}; +use crate::cognitive::quad_triangle::{QuadTriangle, TriangleId, CognitiveProfiles}; +use crate::cognitive::seven_layer::{SevenLayerNode, LayerId, ConsciousnessSnapshot, process_layers_wave, snapshot_consciousness}; +use crate::cognitive::collapse_gate::{GateState, CollapseDecision, evaluate_gate, calculate_sd}; +use crate::fabric::mrna::{MRNA, TaggedConcept, Subsystem}; +use crate::fabric::butterfly::{ButterflyDetector, Butterfly}; + +// ============================================================================= +// COGNITIVE STATE +// ============================================================================= + +/// Complete cognitive state at a moment +#[derive(Clone)] +pub struct CognitiveState { + /// Quad-triangle cognitive texture + pub quad_triangle: QuadTriangle, + + /// 7-layer consciousness markers + pub consciousness: SevenLayerNode, + + /// Current thinking style + pub thinking_style: ThinkingStyle, + + /// Last collapse decision + pub last_collapse: Option, + + /// Processing cycle + pub cycle: u64, + + /// Timestamp + pub timestamp: Instant, +} + +impl CognitiveState { + /// Create new cognitive state + pub fn new(path: &str) -> Self { + Self { + quad_triangle: QuadTriangle::neutral(), + consciousness: SevenLayerNode::new(path), + thinking_style: ThinkingStyle::Analytical, + last_collapse: None, + cycle: 0, + timestamp: Instant::now(), + } + } + + /// Get global fingerprint (quad-triangle + consciousness) + pub fn fingerprint(&self) -> Fingerprint { + let qt_fp = self.quad_triangle.fingerprint().clone(); + let cs_fp = self.consciousness.vsa_core.clone(); + Fingerprint::bundle(&[qt_fp, cs_fp]) + } +} + +// ============================================================================= +// UNIFIED COGNITIVE SUBSTRATE +// ============================================================================= + +/// Unified cognitive substrate +pub struct CognitiveSubstrate { + /// mRNA resonance field + mrna: Arc, + + /// Butterfly detector + butterfly: ButterflyDetector, + + /// Current cognitive state + state: RwLock, + + /// Cognitive profiles cache + profiles: CognitiveProfilesCache, +} + +/// Cached cognitive profiles +struct CognitiveProfilesCache { + analytical: QuadTriangle, + creative: QuadTriangle, + empathic: QuadTriangle, + procedural: QuadTriangle, + counterfactual: QuadTriangle, +} + +impl Default for CognitiveProfilesCache { + fn default() -> Self { + Self { + analytical: CognitiveProfiles::analytical(), + creative: CognitiveProfiles::creative(), + empathic: CognitiveProfiles::empathic(), + procedural: CognitiveProfiles::procedural(), + counterfactual: CognitiveProfiles::counterfactual(), + } + } +} + +impl CognitiveSubstrate { + /// Create new cognitive substrate + pub fn new() -> Self { + Self { + mrna: Arc::new(MRNA::new()), + butterfly: ButterflyDetector::new(), + state: RwLock::new(CognitiveState::new("root")), + profiles: CognitiveProfilesCache::default(), + } + } + + /// Create with specific thinking style + pub fn with_style(style: ThinkingStyle) -> Self { + let substrate = Self::new(); + substrate.set_thinking_style(style); + substrate + } + + // ========================================================================= + // THINKING STYLE + // ========================================================================= + + /// Set thinking style (modulates all subsystems) + pub fn set_thinking_style(&self, style: ThinkingStyle) { + // Update mRNA field + self.mrna.set_style(style); + + // Update butterfly sensitivity + self.butterfly.set_sensitivity(style.butterfly_sensitivity()); + + // Update cognitive state + if let Ok(mut state) = self.state.write() { + state.thinking_style = style; + + // Nudge quad-triangle toward style-appropriate profile + let target = self.profile_for_style(style); + state.quad_triangle.nudge_toward(target, 0.3); + } + } + + /// Get thinking style + pub fn thinking_style(&self) -> ThinkingStyle { + self.state.read().map(|s| s.thinking_style).unwrap_or(ThinkingStyle::Analytical) + } + + /// Get profile for thinking style + fn profile_for_style(&self, style: ThinkingStyle) -> &QuadTriangle { + match style { + ThinkingStyle::Analytical | ThinkingStyle::Convergent | ThinkingStyle::Systematic => { + &self.profiles.analytical + } + ThinkingStyle::Creative | ThinkingStyle::Divergent | ThinkingStyle::Exploratory => { + &self.profiles.creative + } + ThinkingStyle::Focused => &self.profiles.procedural, + ThinkingStyle::Diffuse | ThinkingStyle::Peripheral => &self.profiles.empathic, + ThinkingStyle::Intuitive => &self.profiles.creative, + ThinkingStyle::Deliberate => &self.profiles.analytical, + ThinkingStyle::Metacognitive => &self.profiles.counterfactual, + } + } + + // ========================================================================= + // POLLINATION + // ========================================================================= + + /// Pollinate field with concept (returns resonances) + pub fn pollinate(&self, concept: &Fingerprint) -> Vec<(TaggedConcept, f32)> { + self.mrna.pollinate(concept) + } + + /// Pollinate from specific subsystem + pub fn pollinate_from(&self, subsystem: Subsystem, concept: &Fingerprint) -> Vec<(TaggedConcept, f32)> { + self.mrna.pollinate_from(subsystem, concept) + } + + /// Check cross-pollination between subsystems + pub fn cross_pollinate( + &self, + source: Subsystem, + concept: &Fingerprint, + target: Subsystem, + ) -> Option { + self.mrna.cross_pollinate(source, concept, target) + } + + // ========================================================================= + // CONSCIOUSNESS PROCESSING + // ========================================================================= + + /// Process input through 7-layer consciousness + pub fn process_consciousness(&self, input: &Fingerprint) -> ConsciousnessSnapshot { + let mut state = self.state.write().expect("lock poisoned"); + state.cycle += 1; + + // Process through layers + let _results = process_layers_wave(&mut state.consciousness, input, state.cycle); + + // Take snapshot + snapshot_consciousness(&state.consciousness, state.cycle) + } + + /// Get current consciousness snapshot + pub fn consciousness_snapshot(&self) -> ConsciousnessSnapshot { + let state = self.state.read().expect("lock poisoned"); + snapshot_consciousness(&state.consciousness, state.cycle) + } + + // ========================================================================= + // COLLAPSE GATE + // ========================================================================= + + /// Evaluate collapse gate for candidates + pub fn evaluate_collapse(&self, candidate_scores: &[f32]) -> CollapseDecision { + let decision = evaluate_gate(candidate_scores, true); + + // Store last decision + if let Ok(mut state) = self.state.write() { + state.last_collapse = Some(decision.clone()); + } + + decision + } + + /// Check if collapse is permitted + pub fn can_collapse(&self, candidate_scores: &[f32]) -> bool { + let decision = evaluate_gate(candidate_scores, true); + decision.can_collapse + } + + /// Get collapse gate state + pub fn gate_state(&self, candidate_scores: &[f32]) -> GateState { + let sd = calculate_sd(candidate_scores); + crate::cognitive::collapse_gate::get_gate_state(sd) + } + + // ========================================================================= + // BUTTERFLY DETECTION + // ========================================================================= + + /// Detect butterfly effects in resonance cascade + pub fn detect_butterfly(&self, input: &Fingerprint, cascade_size: usize) -> Option { + self.butterfly.detect( + &self.mrna.history(), + input, + cascade_size, + ) + } + + /// Predict butterfly effect before execution + pub fn predict_butterfly(&self, hypothetical: &Fingerprint) -> Option { + let prediction = self.butterfly.predict(hypothetical, &self.mrna); + if prediction.confidence > 0.5 { + Some(prediction.predicted_amplification) + } else { + None + } + } + + // ========================================================================= + // QUAD-TRIANGLE + // ========================================================================= + + /// Get quad-triangle state + pub fn quad_triangle(&self) -> QuadTriangle { + self.state.read().expect("lock poisoned").quad_triangle.clone() + } + + /// Set quad-triangle activations + pub fn set_quad_triangle_activations( + &self, + processing: [f32; 3], + content: [f32; 3], + gestalt: [f32; 3], + crystallization: [f32; 3], + ) { + if let Ok(mut state) = self.state.write() { + state.quad_triangle = QuadTriangle::with_activations( + processing, content, gestalt, crystallization + ); + } + } + + /// Get cognitive signature + pub fn cognitive_signature(&self) -> String { + self.state.read() + .map(|s| s.quad_triangle.signature()) + .unwrap_or_else(|_| "Unknown".to_string()) + } + + /// Check if in global flow + pub fn is_global_flow(&self) -> bool { + self.state.read() + .map(|s| s.quad_triangle.is_global_flow()) + .unwrap_or(false) + } + + // ========================================================================= + // UNIFIED QUERY + // ========================================================================= + + /// Unified resonance query across all subsystems + pub fn query(&self, input: &Fingerprint) -> UnifiedQueryResult { + let state = self.state.read().expect("lock poisoned"); + + // Quad-triangle resonance + let qt_resonance = state.quad_triangle.query_resonance(input); + + // Consciousness resonance (against VSA core) + let consciousness_resonance = input.similarity(&state.consciousness.vsa_core); + + // mRNA field resonance + let field_resonances = self.mrna.pollinate(input); + let mrna_resonance = if field_resonances.is_empty() { + 0.0 + } else { + field_resonances.iter().map(|(_, r)| *r).sum::() / field_resonances.len() as f32 + }; + + // Style modulation + let modulation = state.thinking_style.field_modulation(); + + // Combined score (weighted by style) + let combined = ( + qt_resonance * modulation.depth_bias + + consciousness_resonance * modulation.breadth_bias + + mrna_resonance * (1.0 - modulation.noise_tolerance) + ) / 3.0; + + UnifiedQueryResult { + quad_triangle_resonance: qt_resonance, + consciousness_resonance, + mrna_resonance, + combined_score: combined, + thinking_style: state.thinking_style, + cognitive_signature: state.quad_triangle.signature(), + flow_count: state.quad_triangle.flow_count(), + } + } + + // ========================================================================= + // STATE MANAGEMENT + // ========================================================================= + + /// Get current cycle + pub fn cycle(&self) -> u64 { + self.state.read().map(|s| s.cycle).unwrap_or(0) + } + + /// Get global fingerprint + pub fn fingerprint(&self) -> Fingerprint { + self.state.read() + .map(|s| s.fingerprint()) + .unwrap_or_else(|_| Fingerprint::zero()) + } + + /// Reset to neutral state + pub fn reset(&self) { + if let Ok(mut state) = self.state.write() { + *state = CognitiveState::new("root"); + } + self.mrna.clear(); + } +} + +impl Default for CognitiveSubstrate { + fn default() -> Self { + Self::new() + } +} + +// ============================================================================= +// UNIFIED QUERY RESULT +// ============================================================================= + +/// Result of unified resonance query +#[derive(Clone, Debug)] +pub struct UnifiedQueryResult { + /// Resonance with quad-triangle + pub quad_triangle_resonance: f32, + + /// Resonance with consciousness core + pub consciousness_resonance: f32, + + /// Resonance with mRNA field + pub mrna_resonance: f32, + + /// Combined weighted score + pub combined_score: f32, + + /// Current thinking style + pub thinking_style: ThinkingStyle, + + /// Cognitive signature + pub cognitive_signature: String, + + /// Number of triangles in flow + pub flow_count: usize, +} + +// ============================================================================= +// COGNITIVE FABRIC (Full Integration) +// ============================================================================= + +/// Complete cognitive fabric with all subsystems +pub struct CognitiveFabric { + /// Core substrate + pub substrate: CognitiveSubstrate, + + /// mRNA reference + pub mrna: Arc, + + /// Butterfly detector + pub butterfly: ButterflyDetector, +} + +impl CognitiveFabric { + /// Create new cognitive fabric + pub fn new() -> Self { + let substrate = CognitiveSubstrate::new(); + let mrna = substrate.mrna.clone(); + let butterfly = ButterflyDetector::new(); + + Self { substrate, mrna, butterfly } + } + + /// Create with thinking style + pub fn with_style(style: ThinkingStyle) -> Self { + let mut fabric = Self::new(); + fabric.substrate.set_thinking_style(style); + fabric.butterfly.set_sensitivity(style.butterfly_sensitivity()); + fabric + } + + /// Full cognitive cycle + pub fn cognitive_cycle(&mut self, input: &Fingerprint) -> CognitiveCycleResult { + // 1. Pollinate mRNA field + let resonances = self.substrate.pollinate(input); + + // 2. Process consciousness + let consciousness = self.substrate.process_consciousness(input); + + // 3. Check for butterfly + let butterfly = self.substrate.detect_butterfly(input, resonances.len()); + + // 4. Unified query + let query = self.substrate.query(input); + + // 5. Evaluate collapse if we have resonances + let collapse = if !resonances.is_empty() { + let scores: Vec = resonances.iter().map(|(_, r)| *r).collect(); + Some(self.substrate.evaluate_collapse(&scores)) + } else { + None + }; + + CognitiveCycleResult { + resonances, + consciousness, + butterfly, + query, + collapse, + cycle: self.substrate.cycle(), + } + } +} + +impl Default for CognitiveFabric { + fn default() -> Self { + Self::new() + } +} + +/// Result of full cognitive cycle +#[derive(Clone)] +pub struct CognitiveCycleResult { + /// mRNA resonances + pub resonances: Vec<(TaggedConcept, f32)>, + + /// Consciousness snapshot + pub consciousness: ConsciousnessSnapshot, + + /// Detected butterfly (if any) + pub butterfly: Option, + + /// Unified query result + pub query: UnifiedQueryResult, + + /// Collapse decision (if applicable) + pub collapse: Option, + + /// Cycle number + pub cycle: u64, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_substrate_creation() { + let substrate = CognitiveSubstrate::new(); + assert_eq!(substrate.thinking_style(), ThinkingStyle::Analytical); + } + + #[test] + fn test_style_modulation() { + let substrate = CognitiveSubstrate::new(); + + substrate.set_thinking_style(ThinkingStyle::Creative); + assert_eq!(substrate.thinking_style(), ThinkingStyle::Creative); + + // Signature should reflect creative profile + let sig = substrate.cognitive_signature(); + assert!(!sig.is_empty()); + } + + #[test] + fn test_unified_query() { + let substrate = CognitiveSubstrate::new(); + let input = Fingerprint::from_content("test input"); + + let result = substrate.query(&input); + assert!(result.combined_score >= 0.0 && result.combined_score <= 1.0); + } + + #[test] + fn test_cognitive_cycle() { + let mut fabric = CognitiveFabric::new(); + let input = Fingerprint::from_content("test stimulus"); + + let result = fabric.cognitive_cycle(&input); + assert!(result.cycle > 0); + } +} From fc66829d014d2d60821ad1215c356384d00d7c39 Mon Sep 17 00:00:00 2001 From: AdaWorldAPI Date: Thu, 29 Jan 2026 20:39:44 +0100 Subject: [PATCH 2/2] Add src/cognitive/grammar_engine.rs (audit recovery from session) --- src/cognitive/grammar_engine.rs | 569 ++++++++++++++++++++++++++++++++ 1 file changed, 569 insertions(+) create mode 100644 src/cognitive/grammar_engine.rs diff --git a/src/cognitive/grammar_engine.rs b/src/cognitive/grammar_engine.rs new file mode 100644 index 0000000..d4053a5 --- /dev/null +++ b/src/cognitive/grammar_engine.rs @@ -0,0 +1,569 @@ +//! Grammar-Aware Cognitive Engine +//! +//! Unified integration of: +//! - 4 QuadTriangles (10K-bit VSA corners) +//! - 7-Layer Consciousness Stack +//! - 12 Thinking Styles +//! - Collapse Gate (SIMD SD) +//! - mRNA Cross-Pollination +//! +//! ```text +//! ┌─────────────────────────────────────────────────────────────────────────┐ +//! │ GRAMMAR-AWARE COGNITIVE ENGINE │ +//! │ │ +//! │ INPUT ─────────────────────────────────────────────────────────────► │ +//! │ │ │ +//! │ ▼ │ +//! │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ +//! │ │ GRAMMAR │───►│ QUAD-TRI │───►│ 7-LAYER │ │ +//! │ │ PARSER │ │ RESONANCE │ │ STACK │ │ +//! │ └─────────────┘ └─────────────┘ └─────────────┘ │ +//! │ │ │ │ │ +//! │ ▼ ▼ ▼ │ +//! │ ┌─────────────────────────────────────────────────────┐ │ +//! │ │ mRNA CROSS-POLLINATION │ │ +//! │ │ │ │ +//! │ │ Grammar ←──► Thinking ←──► Memory ←──► Action │ │ +//! │ └─────────────────────────────────────────────────────┘ │ +//! │ │ │ +//! │ ▼ │ +//! │ ┌─────────────────────────────────────────────────────┐ │ +//! │ │ COLLAPSE GATE (SD) │ │ +//! │ │ │ │ +//! │ │ FLOW ◄────────┬────────┬────────► BLOCK │ │ +//! │ │ (commit) │ HOLD │ (clarify) │ │ +//! │ └─────────────────────────────────────────────────────┘ │ +//! │ │ │ +//! │ ▼ │ +//! │ OUTPUT ◄───────────────────────────────────────────────────────── │ +//! └─────────────────────────────────────────────────────────────────────────┘ +//! ``` + +use std::time::Instant; +use crate::core::{Fingerprint, VsaOps}; +use crate::cognitive::{ + ThinkingStyle, + QuadTriangle, TriangleId, CognitiveProfiles, + GateState, CollapseDecision, evaluate_gate, + SevenLayerNode, LayerId, process_layers_wave, snapshot_consciousness, ConsciousnessSnapshot, +}; +use crate::fabric::{MRNA, Subsystem, ButterflyDetector, Butterfly}; + +// ============================================================================= +// GRAMMAR TRIANGLE (Input from parser) +// ============================================================================= + +/// Grammar role (from parser) +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum GrammarRole { + Subject, + Predicate, + Object, + IndirectObject, + Modifier, + Determiner, + Complement, + Adjunct, +} + +/// Grammar triangle from parser +#[derive(Clone, Debug)] +pub struct GrammarTriangle { + pub role: GrammarRole, + pub filler: String, + pub frame_type: String, + pub confidence: f32, + pub fingerprint: Fingerprint, +} + +impl GrammarTriangle { + pub fn new(role: GrammarRole, filler: &str, frame_type: &str, confidence: f32) -> Self { + let content = format!("{}:{}:{}", role_name(&role), filler, frame_type); + Self { + role, + filler: filler.to_string(), + frame_type: frame_type.to_string(), + confidence, + fingerprint: Fingerprint::from_content(&content), + } + } +} + +fn role_name(role: &GrammarRole) -> &'static str { + match role { + GrammarRole::Subject => "SUBJ", + GrammarRole::Predicate => "PRED", + GrammarRole::Object => "OBJ", + GrammarRole::IndirectObject => "IOBJ", + GrammarRole::Modifier => "MOD", + GrammarRole::Determiner => "DET", + GrammarRole::Complement => "COMP", + GrammarRole::Adjunct => "ADJ", + } +} + +// ============================================================================= +// COGNITIVE STATE +// ============================================================================= + +/// Current cognitive state +#[derive(Clone)] +pub struct CognitiveState { + /// Active thinking style + pub style: ThinkingStyle, + + /// Quad-triangle cognitive texture + pub quad_triangle: QuadTriangle, + + /// 7-layer consciousness node + pub consciousness: SevenLayerNode, + + /// Processing cycle + pub cycle: u64, + + /// Last snapshot + pub last_snapshot: Option, +} + +impl Default for CognitiveState { + fn default() -> Self { + Self { + style: ThinkingStyle::Analytical, + quad_triangle: QuadTriangle::neutral(), + consciousness: SevenLayerNode::new("cognitive_state"), + cycle: 0, + last_snapshot: None, + } + } +} + +// ============================================================================= +// GRAMMAR-AWARE ENGINE +// ============================================================================= + +/// Grammar-aware cognitive engine +pub struct GrammarCognitiveEngine { + /// Current cognitive state + state: CognitiveState, + + /// mRNA cross-pollination substrate + mrna: MRNA, + + /// Butterfly detector + butterfly: ButterflyDetector, + + /// Accumulated grammar triangles + grammar_buffer: Vec, + + /// Collapse history + collapse_history: Vec, +} + +impl GrammarCognitiveEngine { + /// Create new engine + pub fn new() -> Self { + Self { + state: CognitiveState::default(), + mrna: MRNA::new(), + butterfly: ButterflyDetector::new(), + grammar_buffer: Vec::new(), + collapse_history: Vec::new(), + } + } + + /// Create with specific thinking style + pub fn with_style(style: ThinkingStyle) -> Self { + let mut engine = Self::new(); + engine.set_style(style); + engine + } + + /// Set thinking style (modulates all processing) + pub fn set_style(&mut self, style: ThinkingStyle) { + self.state.style = style; + self.mrna.set_style(style); + self.butterfly.set_sensitivity(style.butterfly_sensitivity()); + + // Nudge quad-triangle toward style-appropriate profile + let target = style_to_quad_triangle(style); + self.state.quad_triangle.nudge_toward(&target, 0.3); + } + + /// Get current style + pub fn style(&self) -> ThinkingStyle { + self.state.style + } + + /// Process grammar triangles from parser + pub fn ingest_grammar(&mut self, triangles: Vec) -> IngestResult { + let start = Instant::now(); + + // Bundle all grammar fingerprints + let fps: Vec = triangles.iter() + .map(|t| t.fingerprint.clone()) + .collect(); + + let grammar_fp = if fps.is_empty() { + Fingerprint::zero() + } else { + Fingerprint::bundle(&fps) + }; + + // Cross-pollinate with mRNA + let resonances = self.mrna.pollinate_from(Subsystem::Query, &grammar_fp); + + // Check for butterfly effects + let butterfly = self.butterfly.detect( + self.mrna.history(), + &grammar_fp, + resonances.len() + ); + + // Process through 7-layer stack + self.state.cycle += 1; + let layer_results = process_layers_wave( + &mut self.state.consciousness, + &grammar_fp, + self.state.cycle + ); + + // Take consciousness snapshot + let snapshot = snapshot_consciousness(&self.state.consciousness, self.state.cycle); + self.state.last_snapshot = Some(snapshot.clone()); + + // Update quad-triangle based on grammar coherence + let grammar_coherence = triangles.iter() + .map(|t| t.confidence) + .sum::() / triangles.len().max(1) as f32; + + self.update_quad_triangle_from_grammar(grammar_coherence); + + // Store in buffer + self.grammar_buffer.extend(triangles); + + IngestResult { + resonance_count: resonances.len(), + butterfly, + snapshot, + processing_time: start.elapsed(), + grammar_coherence, + } + } + + /// Evaluate collapse for current candidates + pub fn evaluate_collapse(&mut self, candidate_scores: &[f32]) -> CollapseDecision { + // Get style-modulated thresholds + let modulation = self.state.style.field_modulation(); + + // Evaluate gate + let decision = evaluate_gate(candidate_scores, true); + + // Store in history + self.collapse_history.push(decision.clone()); + + // Cross-pollinate collapse decision + if decision.can_collapse { + if let Some(winner) = decision.winner_index { + let collapse_fp = Fingerprint::from_content(&format!("collapse:{}", winner)); + self.mrna.pollinate_from(Subsystem::Learning, &collapse_fp); + } + } + + decision + } + + /// Get quad-triangle resonance with query + pub fn quad_resonance(&self, query: &Fingerprint) -> f32 { + self.state.quad_triangle.query_resonance(query) + } + + /// Get cognitive signature + pub fn signature(&self) -> String { + self.state.quad_triangle.signature() + } + + /// Get flow count (how many triangles in flow state) + pub fn flow_count(&self) -> usize { + self.state.quad_triangle.flow_count() + } + + /// Check if in global flow + pub fn is_global_flow(&self) -> bool { + self.state.quad_triangle.is_global_flow() + } + + /// Get consciousness coherence + pub fn coherence(&self) -> f32 { + self.state.last_snapshot + .as_ref() + .map(|s| s.coherence) + .unwrap_or(0.0) + } + + /// Get emergence level + pub fn emergence(&self) -> f32 { + self.state.last_snapshot + .as_ref() + .map(|s| s.emergence) + .unwrap_or(0.0) + } + + /// Get dominant consciousness layer + pub fn dominant_layer(&self) -> LayerId { + self.state.last_snapshot + .as_ref() + .map(|s| s.dominant_layer) + .unwrap_or(LayerId::L1) + } + + /// Get mRNA superposition + pub fn mrna_superposition(&self) -> Fingerprint { + self.mrna.superposition() + } + + /// Get current cycle + pub fn cycle(&self) -> u64 { + self.state.cycle + } + + /// Get collapse history + pub fn collapse_history(&self) -> &[CollapseDecision] { + &self.collapse_history + } + + /// Clear grammar buffer + pub fn clear_grammar_buffer(&mut self) { + self.grammar_buffer.clear(); + } + + /// Get grammar buffer + pub fn grammar_buffer(&self) -> &[GrammarTriangle] { + &self.grammar_buffer + } + + // ========================================================================= + // INTERNAL + // ========================================================================= + + fn update_quad_triangle_from_grammar(&mut self, coherence: f32) { + // High coherence → boost analytical processing + if coherence > 0.7 { + let current = self.state.quad_triangle.processing.activations(); + self.state.quad_triangle.processing.set_activations( + (current[0] + 0.1).min(1.0), // Boost analytical + current[1], + current[2], + ); + } + + // Low coherence → boost intuitive processing + if coherence < 0.3 { + let current = self.state.quad_triangle.processing.activations(); + self.state.quad_triangle.processing.set_activations( + current[0], + (current[1] + 0.1).min(1.0), // Boost intuitive + current[2], + ); + } + + // Update gestalt based on coherence + let current = self.state.quad_triangle.gestalt.activations(); + self.state.quad_triangle.gestalt.set_activations( + coherence, // Coherence corner reflects grammar coherence + current[1], + current[2], + ); + } +} + +impl Default for GrammarCognitiveEngine { + fn default() -> Self { + Self::new() + } +} + +// ============================================================================= +// INGEST RESULT +// ============================================================================= + +/// Result of grammar ingestion +#[derive(Clone, Debug)] +pub struct IngestResult { + /// Number of resonances triggered + pub resonance_count: usize, + + /// Butterfly effect detected (if any) + pub butterfly: Option, + + /// Consciousness snapshot + pub snapshot: ConsciousnessSnapshot, + + /// Processing time + pub processing_time: std::time::Duration, + + /// Grammar coherence + pub grammar_coherence: f32, +} + +// ============================================================================= +// STYLE TO QUAD-TRIANGLE MAPPING +// ============================================================================= + +fn style_to_quad_triangle(style: ThinkingStyle) -> QuadTriangle { + match style { + ThinkingStyle::Analytical => CognitiveProfiles::analytical(), + ThinkingStyle::Convergent => CognitiveProfiles::analytical(), + ThinkingStyle::Systematic => CognitiveProfiles::procedural(), + + ThinkingStyle::Creative => CognitiveProfiles::creative(), + ThinkingStyle::Divergent => CognitiveProfiles::creative(), + ThinkingStyle::Exploratory => CognitiveProfiles::creative(), + + ThinkingStyle::Focused => CognitiveProfiles::analytical(), + ThinkingStyle::Diffuse => CognitiveProfiles::empathic(), + ThinkingStyle::Peripheral => CognitiveProfiles::empathic(), + + ThinkingStyle::Intuitive => CognitiveProfiles::empathic(), + ThinkingStyle::Deliberate => CognitiveProfiles::procedural(), + + ThinkingStyle::Metacognitive => CognitiveProfiles::counterfactual(), + } +} + +// ============================================================================= +// BATCH PROCESSING +// ============================================================================= + +/// Process multiple inputs in batch +pub fn process_batch( + engine: &mut GrammarCognitiveEngine, + inputs: Vec>, +) -> Vec { + inputs.into_iter() + .map(|triangles| engine.ingest_grammar(triangles)) + .collect() +} + +// ============================================================================= +// SERIALIZATION +// ============================================================================= + +/// Serialize engine state to bytes +pub fn serialize_state(engine: &GrammarCognitiveEngine) -> Vec { + let mut bytes = Vec::new(); + + // Style (1 byte) + bytes.push(engine.state.style as u8); + + // Quad-triangle (12 floats = 48 bytes) + for f in engine.state.quad_triangle.to_floats() { + bytes.extend_from_slice(&f.to_le_bytes()); + } + + // Cycle (8 bytes) + bytes.extend_from_slice(&engine.state.cycle.to_le_bytes()); + + bytes +} + +/// Deserialize engine state from bytes +pub fn deserialize_state(bytes: &[u8]) -> Option { + if bytes.len() < 57 { + return None; + } + + let mut engine = GrammarCognitiveEngine::new(); + + // Style + let style = match bytes[0] { + 0 => ThinkingStyle::Analytical, + 1 => ThinkingStyle::Convergent, + 2 => ThinkingStyle::Systematic, + 3 => ThinkingStyle::Creative, + 4 => ThinkingStyle::Divergent, + 5 => ThinkingStyle::Exploratory, + 6 => ThinkingStyle::Focused, + 7 => ThinkingStyle::Diffuse, + 8 => ThinkingStyle::Peripheral, + 9 => ThinkingStyle::Intuitive, + 10 => ThinkingStyle::Deliberate, + 11 => ThinkingStyle::Metacognitive, + _ => ThinkingStyle::Analytical, + }; + engine.set_style(style); + + // Quad-triangle + let mut floats = [0.0f32; 12]; + for i in 0..12 { + let start = 1 + i * 4; + floats[i] = f32::from_le_bytes([ + bytes[start], bytes[start + 1], bytes[start + 2], bytes[start + 3] + ]); + } + engine.state.quad_triangle = QuadTriangle::from_floats(floats); + + // Cycle + let cycle_bytes: [u8; 8] = bytes[49..57].try_into().ok()?; + engine.state.cycle = u64::from_le_bytes(cycle_bytes); + + Some(engine) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_engine_creation() { + let engine = GrammarCognitiveEngine::new(); + assert_eq!(engine.cycle(), 0); + } + + #[test] + fn test_style_setting() { + let mut engine = GrammarCognitiveEngine::new(); + engine.set_style(ThinkingStyle::Creative); + assert_eq!(engine.style(), ThinkingStyle::Creative); + } + + #[test] + fn test_grammar_ingestion() { + let mut engine = GrammarCognitiveEngine::new(); + + let triangles = vec![ + GrammarTriangle::new(GrammarRole::Subject, "cat", "NP", 0.9), + GrammarTriangle::new(GrammarRole::Predicate, "sat", "VP", 0.8), + GrammarTriangle::new(GrammarRole::Object, "mat", "NP", 0.85), + ]; + + let result = engine.ingest_grammar(triangles); + assert!(result.grammar_coherence > 0.0); + assert_eq!(engine.cycle(), 1); + } + + #[test] + fn test_collapse_evaluation() { + let mut engine = GrammarCognitiveEngine::new(); + + // Tight consensus should FLOW + let decision = engine.evaluate_collapse(&[0.9, 0.85, 0.88]); + assert_eq!(decision.state, GateState::Flow); + + // High variance should BLOCK + let decision = engine.evaluate_collapse(&[0.9, 0.1, 0.5]); + assert_eq!(decision.state, GateState::Block); + } + + #[test] + fn test_serialization() { + let mut engine = GrammarCognitiveEngine::new(); + engine.set_style(ThinkingStyle::Creative); + engine.state.cycle = 42; + + let bytes = serialize_state(&engine); + let restored = deserialize_state(&bytes).unwrap(); + + assert_eq!(restored.style(), ThinkingStyle::Creative); + assert_eq!(restored.cycle(), 42); + } +}