Skip to main content

feagi_evolutionary/
runtime.rs

1// Copyright 2025 Neuraville Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4/*!
5Runtime genome representation for FEAGI.
6
7This module defines the in-memory Rust objects that represent a loaded genome.
8These objects are created by the genome parser and consumed by neuroembryogenesis.
9
10Copyright 2025 Neuraville Inc.
11Licensed under the Apache License, Version 2.0
12*/
13
14use feagi_structures::genomic::classifiers::Classifier;
15use feagi_structures::genomic::cortical_area::CorticalArea;
16use feagi_structures::genomic::cortical_area::CorticalID;
17use feagi_structures::genomic::BrainRegion;
18use serde::{Deserialize, Serialize};
19use std::collections::HashMap;
20
21/// Complete runtime genome representation
22#[derive(Debug, Clone)]
23pub struct RuntimeGenome {
24    /// Genome metadata
25    pub metadata: GenomeMetadata,
26
27    /// Cortical areas (by cortical_id as CorticalID)
28    pub cortical_areas: HashMap<CorticalID, CorticalArea>,
29
30    /// Brain regions (by region_id)
31    pub brain_regions: HashMap<String, BrainRegion>,
32
33    /// Classifier assemblies (by classifier_id). Parallel to `brain_regions`;
34    /// not a region and not exportable as a circuit.
35    pub classifiers: HashMap<String, Classifier>,
36
37    /// Morphology registry
38    pub morphologies: MorphologyRegistry,
39
40    /// Modulator instances. Each instance owns one driver cortical area.
41    pub modulators: crate::modulators::ModulatorRegistry,
42
43    /// Physiology configuration
44    pub physiology: PhysiologyConfig,
45
46    /// Genome signatures
47    pub signatures: GenomeSignatures,
48
49    /// Statistics
50    pub stats: GenomeStats,
51
52    /// Recorded structural changes (optional top-level `change_history` key).
53    ///
54    /// Opaque entries owned by the change ledger in `feagi-services`; the genome only
55    /// carries them. Never part of `signatures`.
56    pub change_history: Vec<serde_json::Value>,
57}
58
59impl RuntimeGenome {
60    /// Add every rule a classifier requires that its mapping lists lack.
61    ///
62    /// The classifier record is authoritative for its sample, class, and
63    /// associative edges. Existing rules are left as they are.
64    /// Returns the number of rules added.
65    pub fn apply_classifier_required_mappings(&mut self) -> usize {
66        let mut added = 0usize;
67        for classifier in self.classifiers.values() {
68            let Some(associative_window) =
69                CorticalID::try_from_base_64(&classifier.sample_memory_id)
70                    .ok()
71                    .and_then(|id| self.cortical_areas.get(&id))
72                    .and_then(|area| crate::extract_memory_properties(&area.properties))
73                    .map(|props| props.temporal_depth)
74            else {
75                continue;
76            };
77            for mapping in classifier.required_mappings() {
78                let Ok(dst_id) = CorticalID::try_from_base_64(&mapping.dst_area_id) else {
79                    continue;
80                };
81                if !self.cortical_areas.contains_key(&dst_id) {
82                    continue;
83                }
84                let Ok(src_id) = CorticalID::try_from_base_64(&mapping.src_area_id) else {
85                    continue;
86                };
87                let Some(src_area) = self.cortical_areas.get_mut(&src_id) else {
88                    continue;
89                };
90                let Some(mapping_dst) = src_area
91                    .properties
92                    .entry("cortical_mapping_dst".to_string())
93                    .or_insert_with(|| serde_json::json!({}))
94                    .as_object_mut()
95                else {
96                    continue;
97                };
98                let Some(rules) = mapping_dst
99                    .entry(mapping.dst_area_id.clone())
100                    .or_insert_with(|| serde_json::json!([]))
101                    .as_array_mut()
102                else {
103                    continue;
104                };
105                let present = rules.iter().any(|rule| {
106                    rule.get("morphology_id").and_then(|v| v.as_str())
107                        == Some(mapping.morphology_id.as_str())
108                });
109                if present {
110                    continue;
111                }
112                rules.push(
113                    feagi_structures::genomic::classifiers::classifier_mapping_rule(
114                        &mapping.morphology_id,
115                        associative_window,
116                    ),
117                );
118                added += 1;
119            }
120        }
121        added
122    }
123}
124
125/// Genome metadata
126#[derive(Debug, Clone, Serialize, Deserialize)]
127pub struct GenomeMetadata {
128    pub genome_id: String,
129    pub genome_title: String,
130    pub genome_description: String,
131    pub version: String,
132    pub timestamp: f64, // Unix timestamp
133
134    /// Root brain region ID (UUID string) - explicit identification for O(1) lookup
135    /// This eliminates the need to search through all regions to find which has no parent
136    #[serde(skip_serializing_if = "Option::is_none")]
137    pub brain_regions_root: Option<String>,
138}
139
140/// Neuron morphology registry
141#[derive(Debug, Clone, Default)]
142pub struct MorphologyRegistry {
143    /// All morphologies by morphology_id
144    morphologies: HashMap<String, Morphology>,
145}
146
147impl MorphologyRegistry {
148    /// Create empty registry
149    pub fn new() -> Self {
150        Self::default()
151    }
152
153    /// Add a morphology
154    pub fn add_morphology(&mut self, id: String, morphology: Morphology) {
155        self.morphologies.insert(id, morphology);
156    }
157
158    /// Get a morphology by ID
159    pub fn get(&self, id: &str) -> Option<&Morphology> {
160        self.morphologies.get(id)
161    }
162
163    /// Check if morphology exists
164    pub fn contains(&self, id: &str) -> bool {
165        self.morphologies.contains_key(id)
166    }
167
168    /// Get all morphology IDs
169    pub fn morphology_ids(&self) -> Vec<String> {
170        self.morphologies.keys().cloned().collect()
171    }
172
173    /// Remove a morphology by ID.
174    ///
175    /// Returns true if the morphology existed and was removed.
176    pub fn remove_morphology(&mut self, id: &str) -> bool {
177        self.morphologies.remove(id).is_some()
178    }
179
180    /// Get count of morphologies
181    pub fn count(&self) -> usize {
182        self.morphologies.len()
183    }
184
185    /// Iterate over all morphologies
186    pub fn iter(&self) -> impl Iterator<Item = (&String, &Morphology)> {
187        self.morphologies.iter()
188    }
189}
190
191/// Neuron morphology definition
192#[derive(Debug, Clone, Serialize, Deserialize)]
193pub struct Morphology {
194    /// Morphology type: "vectors", "patterns", "functions", or "composite"
195    pub morphology_type: MorphologyType,
196
197    /// Morphology parameters
198    pub parameters: MorphologyParameters,
199
200    /// Morphology class: "core", "custom", etc.
201    pub class: String,
202}
203
204/// Morphology type enum
205#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
206#[serde(rename_all = "lowercase")]
207pub enum MorphologyType {
208    /// Vector-based morphology (3D offset vectors)
209    Vectors,
210
211    /// Pattern-based morphology (source → destination patterns)
212    Patterns,
213
214    /// Function-based morphology (built-in algorithms)
215    Functions,
216
217    /// Composite morphology (combines multiple morphologies)
218    Composite,
219}
220
221/// Morphology parameters (type-specific)
222#[derive(Debug, Clone, Serialize, Deserialize)]
223#[serde(untagged)]
224pub enum MorphologyParameters {
225    /// Vector parameters: list of [x, y, z] offsets
226    Vectors { vectors: Vec<[i32; 3]> },
227
228    /// Pattern parameters: list of [source_pattern, dest_pattern] pairs
229    Patterns {
230        patterns: Vec<[Vec<PatternElement>; 2]>,
231    },
232
233    /// Function parameters: empty for built-in functions
234    Functions {},
235
236    /// Composite parameters: combines seed + pattern + mapper
237    Composite {
238        src_seed: [u32; 3],
239        src_pattern: Vec<[i32; 2]>,
240        mapper_morphology: String,
241    },
242}
243
244/// Pattern element: exact value, wildcard (*), skip (?), exclude (!), relative, or `N..M`
245#[derive(Debug, Clone, PartialEq, Eq)]
246pub enum PatternElement {
247    /// Exact coordinate value
248    Value(i32),
249    /// Wildcard - matches any value
250    Wildcard, // "*"
251    /// Skip - don't check this coordinate
252    Skip, // "?"
253    /// Exclude - exclude this coordinate
254    Exclude, // "!"
255    /// All coordinates strictly above source on this axis
256    DirectionPositive, // "?+"
257    /// All coordinates strictly below source on this axis
258    DirectionNegative, // "?-"
259    /// All coordinates at or above source on this axis
260    DirectionPositiveInclusive, // "?+="
261    /// All coordinates at or below source on this axis
262    DirectionNegativeInclusive, // "?-="
263    /// Single coordinate at offset from source
264    Offset(i32), // "?+N" or "?-N"
265    /// Inclusive range relative to source [src+lo, src+hi]
266    Range(i32, i32), // "?-A:?+B"
267    /// Inclusive absolute range [N, M]
268    AbsoluteRange(i32, i32), // "N..M"
269}
270
271// Custom serialization to convert PatternElement back to JSON properly
272impl Serialize for PatternElement {
273    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
274    where
275        S: serde::Serializer,
276    {
277        match self {
278            PatternElement::Value(v) => serializer.serialize_i32(*v),
279            PatternElement::Wildcard => serializer.serialize_str("*"),
280            PatternElement::Skip => serializer.serialize_str("?"),
281            PatternElement::Exclude => serializer.serialize_str("!"),
282            PatternElement::DirectionPositive => serializer.serialize_str("?+"),
283            PatternElement::DirectionNegative => serializer.serialize_str("?-"),
284            PatternElement::DirectionPositiveInclusive => serializer.serialize_str("?+="),
285            PatternElement::DirectionNegativeInclusive => serializer.serialize_str("?-="),
286            PatternElement::Offset(off) => {
287                if *off >= 0 {
288                    serializer.serialize_str(&format!("?+{}", off))
289                } else {
290                    serializer.serialize_str(&format!("?{}", off))
291                }
292            }
293            PatternElement::Range(lo, hi) => {
294                let lo_str = if *lo >= 0 {
295                    format!("?+{}", lo)
296                } else {
297                    format!("?{}", lo)
298                };
299                let hi_str = if *hi >= 0 {
300                    format!("?+{}", hi)
301                } else {
302                    format!("?{}", hi)
303                };
304                serializer.serialize_str(&format!("{}:{}", lo_str, hi_str))
305            }
306            PatternElement::AbsoluteRange(lo, hi) => {
307                serializer.serialize_str(&format!("{}..{}", lo, hi))
308            }
309        }
310    }
311}
312
313// Custom deserialization to parse JSON into PatternElement
314impl<'de> Deserialize<'de> for PatternElement {
315    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
316    where
317        D: serde::Deserializer<'de>,
318    {
319        let value = serde_json::Value::deserialize(deserializer)?;
320        match value {
321            serde_json::Value::Number(n) => {
322                if let Some(i) = n.as_i64() {
323                    Ok(PatternElement::Value(i as i32))
324                } else {
325                    Err(serde::de::Error::custom(
326                        "Pattern element must be an integer",
327                    ))
328                }
329            }
330            serde_json::Value::String(s) => Self::parse_string(&s)
331                .ok_or_else(|| serde::de::Error::custom(format!("Unknown pattern element: {}", s))),
332            _ => Err(serde::de::Error::custom(
333                "Pattern element must be number or string",
334            )),
335        }
336    }
337}
338
339impl PatternElement {
340    /// Parse a pattern element from its string representation.
341    pub fn parse_string(s: &str) -> Option<Self> {
342        match s {
343            "*" => Some(PatternElement::Wildcard),
344            "?" => Some(PatternElement::Skip),
345            "!" => Some(PatternElement::Exclude),
346            "?+" => Some(PatternElement::DirectionPositive),
347            "?-" => Some(PatternElement::DirectionNegative),
348            "?+=" => Some(PatternElement::DirectionPositiveInclusive),
349            "?-=" => Some(PatternElement::DirectionNegativeInclusive),
350            _ => {
351                if let Some(range) = Self::try_parse_range(s) {
352                    return Some(range);
353                }
354                if let Some(abs_range) = Self::try_parse_absolute_range(s) {
355                    return Some(abs_range);
356                }
357                if let Some(offset) = Self::try_parse_offset(s) {
358                    return Some(offset);
359                }
360                None
361            }
362        }
363    }
364
365    fn try_parse_range(s: &str) -> Option<Self> {
366        let parts: Vec<&str> = s.split(':').collect();
367        if parts.len() != 2 {
368            return None;
369        }
370        let lo = Self::extract_relative_offset(parts[0])?;
371        let hi = Self::extract_relative_offset(parts[1])?;
372        Some(PatternElement::Range(lo, hi))
373    }
374
375    fn try_parse_absolute_range(s: &str) -> Option<Self> {
376        let idx = s.find("..")?;
377        if s[idx + 2..].contains("..") {
378            return None;
379        }
380        let lo = s[..idx].parse::<i32>().ok()?;
381        let hi = s[idx + 2..].parse::<i32>().ok()?;
382        Some(PatternElement::AbsoluteRange(lo, hi))
383    }
384
385    fn try_parse_offset(s: &str) -> Option<Self> {
386        let offset = Self::extract_relative_offset(s)?;
387        Some(PatternElement::Offset(offset))
388    }
389
390    fn extract_relative_offset(s: &str) -> Option<i32> {
391        if !s.starts_with('?') {
392            return None;
393        }
394        let rest = &s[1..];
395        if rest.is_empty() || rest == "+" || rest == "-" || rest == "+=" || rest == "-=" {
396            return None;
397        }
398        rest.parse::<i32>().ok()
399    }
400}
401
402/// Physiology configuration (runtime parameters)
403#[derive(Debug, Clone, Serialize, Deserialize)]
404pub struct PhysiologyConfig {
405    /// Simulation timestep in seconds (formerly burst_delay)
406    pub simulation_timestep: f64,
407
408    /// Maximum neuron age
409    pub max_age: u64,
410
411    /// Evolution burst count
412    pub evolution_burst_count: u64,
413
414    /// IPU idle threshold
415    pub ipu_idle_threshold: u64,
416
417    /// Plasticity queue depth
418    pub plasticity_queue_depth: usize,
419
420    /// Lifespan management interval
421    pub lifespan_mgmt_interval: u64,
422
423    /// Quantization precision for numeric values
424    /// Options: "fp32" (default), "fp16", "int8"
425    #[serde(default = "default_quantization_precision")]
426    pub quantization_precision: String,
427}
428
429pub fn default_quantization_precision() -> String {
430    "int8".to_string() // Default to INT8 for memory efficiency
431}
432
433impl Default for PhysiologyConfig {
434    fn default() -> Self {
435        Self {
436            simulation_timestep: 0.025,
437            max_age: 10_000_000,
438            evolution_burst_count: 50,
439            ipu_idle_threshold: 1000,
440            plasticity_queue_depth: 3,
441            lifespan_mgmt_interval: 10,
442            quantization_precision: default_quantization_precision(),
443        }
444    }
445}
446
447/// Genome signatures for comparison
448#[derive(Debug, Clone, Serialize, Deserialize)]
449pub struct GenomeSignatures {
450    /// Full genome signature
451    pub genome: String,
452
453    /// Blueprint signature
454    pub blueprint: String,
455
456    /// Physiology signature
457    pub physiology: String,
458
459    /// Morphologies signature (optional, for future extension)
460    #[serde(skip_serializing_if = "Option::is_none")]
461    pub morphologies: Option<String>,
462}
463
464/// Genome statistics
465#[derive(Debug, Clone, Serialize, Deserialize, Default)]
466pub struct GenomeStats {
467    /// Innate cortical area count
468    pub innate_cortical_area_count: usize,
469
470    /// Innate neuron count
471    pub innate_neuron_count: usize,
472
473    /// Innate synapse count
474    pub innate_synapse_count: usize,
475}
476
477#[cfg(test)]
478mod tests {
479    use super::*;
480
481    #[test]
482    fn test_morphology_registry_creation() {
483        let registry = MorphologyRegistry::new();
484        assert_eq!(registry.count(), 0);
485    }
486
487    #[test]
488    fn test_morphology_registry_add_and_get() {
489        let mut registry = MorphologyRegistry::new();
490
491        let morphology = Morphology {
492            morphology_type: MorphologyType::Vectors,
493            parameters: MorphologyParameters::Vectors {
494                vectors: vec![[1, 0, 0], [0, 1, 0]],
495            },
496            class: "test".to_string(),
497        };
498
499        registry.add_morphology("test_morph".to_string(), morphology);
500
501        assert_eq!(registry.count(), 1);
502        assert!(registry.contains("test_morph"));
503        assert!(registry.get("test_morph").is_some());
504    }
505
506    fn classifier_genome(sample_to_memory_rules: Vec<serde_json::Value>) -> RuntimeGenome {
507        use feagi_structures::genomic::classifiers::Classifier;
508        use feagi_structures::genomic::cortical_area::{
509            CorticalAreaDimensions, CorticalAreaType, CustomCorticalType, MemoryCorticalType,
510        };
511
512        let area = |id: &str, is_memory: bool| {
513            let kind = if is_memory {
514                CorticalAreaType::Memory(MemoryCorticalType::Memory)
515            } else {
516                CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire)
517            };
518            let mut area = CorticalArea::new(
519                CorticalID::try_from_base_64(id).expect("id"),
520                0,
521                id.to_string(),
522                CorticalAreaDimensions::new(1, 1, 1).expect("dims"),
523                (0, 0, 0).into(),
524                kind,
525            )
526            .expect("area");
527            if is_memory {
528                area.properties
529                    .insert("is_mem_type".to_string(), serde_json::json!(true));
530                area.properties
531                    .insert("temporal_depth".to_string(), serde_json::json!(2));
532            }
533            area
534        };
535        let mut sample = area("Y01OSVNUX9w=", false);
536        sample.properties.insert(
537            "cortical_mapping_dst".to_string(),
538            serde_json::json!({ "bU1OSVNUXx8=": sample_to_memory_rules }),
539        );
540        let mut cortical_areas = HashMap::new();
541        for a in [
542            sample,
543            area("Y01OSVNUX+E=", false),
544            area("Y01OSVNUX8Y=", false),
545            area("bU1OSVNUXx8=", true),
546            area("bU1OSVNUXyA=", true),
547        ] {
548            cortical_areas.insert(a.cortical_id, a);
549        }
550        let classifier = Classifier {
551            classifier_id: "clf".to_string(),
552            name: "clf".to_string(),
553            parent_region_id: "region".to_string(),
554            coordinates_3d: [0, 0, 0],
555            sample_area_ids: vec!["Y01OSVNUX9w=".to_string()],
556            class_bindings: vec![
557                feagi_structures::genomic::classifiers::ClassifierClassBinding {
558                    class_area_id: "Y01OSVNUX+E=".to_string(),
559                    class_output_area_id: "Y01OSVNUX8Y=".to_string(),
560                },
561            ],
562            sample_memory_id: "bU1OSVNUXx8=".to_string(),
563            class_memory_id: "bU1OSVNUXyA=".to_string(),
564            error_area_id: "err".to_string(),
565            reward_training: false,
566            answer_feedback_area_id: None,
567            pain_area_id: None,
568            pleasure_area_id: None,
569            answer_latency_bursts: 0,
570            learn_area_id: None,
571            confidence_area_id: None,
572            properties: HashMap::new(),
573        };
574        RuntimeGenome {
575            metadata: GenomeMetadata {
576                genome_id: "t".to_string(),
577                genome_title: "t".to_string(),
578                genome_description: String::new(),
579                version: "3.0".to_string(),
580                timestamp: 0.0,
581                brain_regions_root: None,
582            },
583            cortical_areas,
584            brain_regions: HashMap::new(),
585            classifiers: HashMap::from([("clf".to_string(), classifier)]),
586            morphologies: MorphologyRegistry::new(),
587            modulators: crate::modulators::ModulatorRegistry::new(),
588            physiology: PhysiologyConfig::default(),
589            signatures: GenomeSignatures {
590                genome: "0".to_string(),
591                blueprint: "0".to_string(),
592                physiology: "0".to_string(),
593                morphologies: None,
594            },
595            stats: GenomeStats::default(),
596            change_history: Vec::new(),
597        }
598    }
599
600    fn morphologies(genome: &RuntimeGenome, src: &str, dst: &str) -> Vec<String> {
601        genome.cortical_areas[&CorticalID::try_from_base_64(src).unwrap()]
602            .properties
603            .get("cortical_mapping_dst")
604            .and_then(|m| m.get(dst))
605            .and_then(|r| r.as_array())
606            .map(|rules| {
607                rules
608                    .iter()
609                    .filter_map(|r| r["morphology_id"].as_str().map(str::to_string))
610                    .collect()
611            })
612            .unwrap_or_default()
613    }
614
615    #[test]
616    fn missing_classifier_edges_are_restored() {
617        use feagi_structures::genomic::classifiers::classifier_mapping_rule;
618        let mut genome = classifier_genome(vec![classifier_mapping_rule("classifier_sample", 2)]);
619
620        let added = genome.apply_classifier_required_mappings();
621
622        assert_eq!(
623            morphologies(&genome, "Y01OSVNUX9w=", "bU1OSVNUXx8="),
624            vec!["classifier_sample".to_string()]
625        );
626        assert_eq!(
627            morphologies(&genome, "Y01OSVNUX+E=", "bU1OSVNUXyA="),
628            vec!["classifier_class".to_string()]
629        );
630        let assoc = morphologies(&genome, "bU1OSVNUXx8=", "bU1OSVNUXyA=");
631        assert_eq!(assoc, vec!["associative_memory".to_string()]);
632        let assoc_rule = &genome.cortical_areas
633            [&CorticalID::try_from_base_64("bU1OSVNUXx8=").unwrap()]
634            .properties["cortical_mapping_dst"]["bU1OSVNUXyA="][0];
635        assert_eq!(assoc_rule["plasticity_window"], serde_json::json!(2));
636        assert_eq!(added, 2);
637    }
638
639    #[test]
640    fn complete_classifier_edges_are_left_unchanged() {
641        use feagi_structures::genomic::classifiers::classifier_mapping_rule;
642        let mut genome = classifier_genome(vec![classifier_mapping_rule("classifier_sample", 2)]);
643        genome.apply_classifier_required_mappings();
644        let before = genome.cortical_areas.clone();
645
646        assert_eq!(genome.apply_classifier_required_mappings(), 0);
647        for (id, area) in &before {
648            assert_eq!(
649                area.properties.get("cortical_mapping_dst"),
650                genome.cortical_areas[id]
651                    .properties
652                    .get("cortical_mapping_dst")
653            );
654        }
655    }
656
657    #[test]
658    fn test_physiology_config_default() {
659        let config = PhysiologyConfig::default();
660        assert_eq!(config.simulation_timestep, 0.025);
661        assert_eq!(config.max_age, 10_000_000);
662    }
663}