Skip to main content

feagi_evolutionary/
validator.rs

1// Copyright 2025 Neuraville Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4/*!
5Genome validation for FEAGI.
6
7Validates genome structure, morphologies, parameters, and constraints.
8Provides clear error messages for debugging.
9
10Copyright 2025 Neuraville Inc.
11Licensed under the Apache License, Version 2.0
12*/
13
14use crate::{MorphologyParameters, RuntimeGenome};
15// CorticalID is used in function signatures but may appear unused in some contexts
16#[allow(unused_imports)]
17use feagi_structures::genomic::cortical_area::CorticalID;
18use serde_json::Value;
19use std::collections::HashSet;
20use std::str::FromStr;
21
22/// Validation result
23#[derive(Debug, Clone)]
24pub struct ValidationResult {
25    /// Whether the genome is valid
26    pub valid: bool,
27    /// List of errors (blocking issues)
28    pub errors: Vec<String>,
29    /// List of warnings (non-blocking issues)
30    pub warnings: Vec<String>,
31}
32
33impl ValidationResult {
34    /// Create a new valid result
35    pub fn new() -> Self {
36        Self {
37            valid: true,
38            errors: Vec::new(),
39            warnings: Vec::new(),
40        }
41    }
42
43    /// Add an error
44    pub fn add_error(&mut self, error: String) {
45        self.valid = false;
46        self.errors.push(error);
47    }
48
49    /// Add a warning
50    pub fn add_warning(&mut self, warning: String) {
51        self.warnings.push(warning);
52    }
53
54    /// Merge another validation result into this one
55    pub fn merge(&mut self, other: ValidationResult) {
56        if !other.valid {
57            self.valid = false;
58        }
59        self.errors.extend(other.errors);
60        self.warnings.extend(other.warnings);
61    }
62}
63
64impl Default for ValidationResult {
65    fn default() -> Self {
66        Self::new()
67    }
68}
69
70/// Validate a RuntimeGenome
71pub fn validate_genome(genome: &RuntimeGenome) -> ValidationResult {
72    let mut result = ValidationResult::new();
73
74    // Validate metadata
75    validate_metadata(genome, &mut result);
76
77    // Validate cortical areas
78    validate_cortical_areas(genome, &mut result);
79
80    // Validate morphologies
81    validate_morphologies(genome, &mut result);
82
83    // Validate physiology
84    validate_physiology(genome, &mut result);
85
86    // Cross-validate (e.g., check references between sections)
87    cross_validate(genome, &mut result);
88
89    // Warn about memory.capture without a replay loop
90    validate_memory_capture_loops(genome, &mut result);
91
92    result
93}
94
95/// Warning for a memory area that records with `memory.capture` but has no
96/// `sequential_memory` mapping from itself to itself.
97pub const MEMORY_CAPTURE_WITHOUT_LOOP_WARNING: &str = "memory.capture on this area records episodes but cannot replay them: add a sequential_memory mapping from the area to itself.";
98
99/// True when the area's own mapping list holds a `sequential_memory` rule to itself.
100fn area_has_sequential_memory_loop(
101    cortical_id: &CorticalID,
102    area: &feagi_structures::genomic::cortical_area::CorticalArea,
103) -> bool {
104    let Some(Value::Object(dstmap)) = area.properties.get("cortical_mapping_dst") else {
105        return false;
106    };
107    let Some(Value::Array(rules)) = dstmap.get(&cortical_id.as_base_64()) else {
108        return false;
109    };
110    rules.iter().any(|rule| {
111        let id = match rule {
112            Value::Object(obj) => obj.get("morphology_id").and_then(Value::as_str),
113            Value::Array(arr) => arr.first().and_then(Value::as_str),
114            _ => None,
115        };
116        id == Some("sequential_memory")
117    })
118}
119
120/// D10: a memory area subscribed to a `memory.capture` modulator without a self
121/// `sequential_memory` mapping records episodes it cannot replay. Warning only.
122fn validate_memory_capture_loops(genome: &RuntimeGenome, result: &mut ValidationResult) {
123    use feagi_structures::genomic::cortical_area::CorticalAreaType;
124    use feagi_structures::genomic::ModulatorKind;
125
126    for (cortical_id, area) in &genome.cortical_areas {
127        if !matches!(area.cortical_type, CorticalAreaType::Memory(_)) {
128            continue;
129        }
130        let Some(Value::Array(subscribed)) = area.properties.get("modulators") else {
131            continue;
132        };
133        let captures = subscribed.iter().filter_map(Value::as_str).any(|id| {
134            genome
135                .modulators
136                .get(id)
137                .is_some_and(|instance| instance.kind == ModulatorKind::MemoryCapture)
138        });
139        if captures && !area_has_sequential_memory_loop(cortical_id, area) {
140            result.add_warning(MEMORY_CAPTURE_WITHOUT_LOOP_WARNING.to_string());
141        }
142    }
143}
144
145/// Auto-fix common genome issues (zero dimensions, zero per_voxel_neuron_cnt, missing physiology)
146///
147/// This function modifies the genome in-place to fix issues that can be automatically corrected.
148/// Should be called before validation to prevent common user errors.
149///
150/// # Arguments
151/// * `genome` - Mutable reference to genome to fix
152///
153/// # Returns
154/// * Number of fixes applied
155pub fn auto_fix_genome(genome: &mut RuntimeGenome) -> usize {
156    use tracing::info;
157
158    let mut fixes_applied = 0;
159
160    // Fix missing or invalid physiology values
161    if genome.physiology.simulation_timestep <= 0.0 {
162        let default_timestep = crate::runtime::PhysiologyConfig::default().simulation_timestep;
163        info!(
164            "🔧 AUTO-FIX: Invalid simulation_timestep {} → {} (default)",
165            genome.physiology.simulation_timestep, default_timestep
166        );
167        genome.physiology.simulation_timestep = default_timestep;
168        fixes_applied += 1;
169    }
170
171    if genome.physiology.max_age == 0 {
172        let default_age = crate::runtime::PhysiologyConfig::default().max_age;
173        info!("🔧 AUTO-FIX: max_age 0 → {} (default)", default_age);
174        genome.physiology.max_age = default_age;
175        fixes_applied += 1;
176    }
177
178    // Fix missing or invalid quantization_precision
179    if genome.physiology.quantization_precision.is_empty() {
180        let default_precision = crate::runtime::default_quantization_precision();
181        info!(
182            "🔧 AUTO-FIX: Missing quantization_precision → '{}' (default)",
183            default_precision
184        );
185        genome.physiology.quantization_precision = default_precision;
186        fixes_applied += 1;
187    } else {
188        // Normalize to canonical format
189        use feagi_npu_neural::types::Precision;
190        match Precision::from_str(&genome.physiology.quantization_precision) {
191            Ok(precision) => {
192                let canonical = precision.as_str().to_string();
193                if genome.physiology.quantization_precision != canonical {
194                    info!(
195                        "🔧 AUTO-FIX: Quantization precision '{}' → '{}' (normalized)",
196                        genome.physiology.quantization_precision, canonical
197                    );
198                    genome.physiology.quantization_precision = canonical;
199                    fixes_applied += 1;
200                }
201            }
202            Err(_) => {
203                // Invalid precision - will be caught by validator
204                let default_precision = crate::runtime::default_quantization_precision();
205                info!(
206                    "🔧 AUTO-FIX: Invalid quantization_precision '{}' → '{}' (default)",
207                    genome.physiology.quantization_precision, default_precision
208                );
209                genome.physiology.quantization_precision = default_precision;
210                fixes_applied += 1;
211            }
212        }
213    }
214
215    for (cortical_id, area) in &mut genome.cortical_areas {
216        let cortical_id_display = cortical_id.to_string();
217        // Fix zero dimensions
218        if area.dimensions.width == 0 {
219            info!(
220                "🔧 AUTO-FIX: Cortical area '{}' width 0 → 1",
221                cortical_id_display
222            );
223            area.dimensions.width = 1;
224            fixes_applied += 1;
225        }
226        if area.dimensions.height == 0 {
227            info!(
228                "🔧 AUTO-FIX: Cortical area '{}' height 0 → 1",
229                cortical_id_display
230            );
231            area.dimensions.height = 1;
232            fixes_applied += 1;
233        }
234        if area.dimensions.depth == 0 {
235            info!(
236                "🔧 AUTO-FIX: Cortical area '{}' depth 0 → 1",
237                cortical_id_display
238            );
239            area.dimensions.depth = 1;
240            fixes_applied += 1;
241        }
242
243        // Fix zero neurons_per_voxel (stored in properties)
244        let neurons_per_voxel = area
245            .properties
246            .get("neurons_per_voxel")
247            .and_then(|v| v.as_u64())
248            .unwrap_or(0) as u32;
249        if neurons_per_voxel == 0 {
250            info!(
251                "🔧 AUTO-FIX: Cortical area '{}' neurons_per_voxel 0 → 1",
252                cortical_id_display
253            );
254            area.properties
255                .insert("neurons_per_voxel".to_string(), serde_json::json!(1));
256            fixes_applied += 1;
257        }
258    }
259
260    if fixes_applied > 0 {
261        info!(
262            "🔧 AUTO-FIX: Applied {} automatic corrections to genome",
263            fixes_applied
264        );
265    }
266
267    fixes_applied
268}
269
270/// Validate genome metadata
271fn validate_metadata(genome: &RuntimeGenome, result: &mut ValidationResult) {
272    if genome.metadata.genome_id.is_empty() {
273        result.add_error("Genome ID is empty".to_string());
274    }
275
276    if genome.metadata.version.is_empty() {
277        result.add_error("Genome version is empty".to_string());
278    }
279
280    if genome.metadata.version != "2.0" {
281        result.add_warning(format!(
282            "Genome version '{}' may not be fully supported (expected '2.0')",
283            genome.metadata.version
284        ));
285    }
286}
287
288/// Validate cortical areas
289fn validate_cortical_areas(genome: &RuntimeGenome, result: &mut ValidationResult) {
290    if genome.cortical_areas.is_empty() {
291        result.add_warning("Genome has no cortical areas defined".to_string());
292        return;
293    }
294
295    for (cortical_id, area) in &genome.cortical_areas {
296        let cortical_id_display = cortical_id.to_string();
297
298        // CRITICAL: Validate cortical ID format and compliance with feagi-data-processing templates
299        validate_cortical_id_format(cortical_id, &cortical_id_display, result);
300
301        // Validate dimensions - AUTO-FIX zeros to 1
302        if area.dimensions.width == 0 || area.dimensions.height == 0 || area.dimensions.depth == 0 {
303            result.add_warning(format!(
304                "AUTO-FIX: Cortical area '{}' has zero dimension(s): {}x{}x{} - will be corrected to minimum (1,1,1)",
305                cortical_id_display, area.dimensions.width, area.dimensions.height, area.dimensions.depth
306            ));
307            // Note: Auto-fix happens in auto_fix_genome() - this just detects the issue
308        }
309
310        // Validate neurons_per_voxel (stored in properties)
311        let neurons_per_voxel = area
312            .properties
313            .get("neurons_per_voxel")
314            .and_then(|v| v.as_u64())
315            .unwrap_or(0) as u32;
316        if neurons_per_voxel == 0 {
317            result.add_warning(format!(
318                "AUTO-FIX: Cortical area '{}' has neurons_per_voxel=0 - will be corrected to 1",
319                cortical_id_display
320            ));
321        }
322
323        // Warn about very large dimensions
324        let total_voxels = area.dimensions.width * area.dimensions.height * area.dimensions.depth;
325        if total_voxels > 1_000_000 {
326            result.add_warning(format!(
327                "Cortical area '{}' has very large dimensions: {} total voxels",
328                cortical_id_display, total_voxels
329            ));
330        }
331
332        // Validate name
333        if area.name.is_empty() {
334            result.add_warning(format!(
335                "Cortical area '{}' has empty name",
336                cortical_id_display
337            ));
338        }
339
340        validate_memory_mp_encoding(&area.properties, &cortical_id_display, result);
341        validate_neuron_fractions(&area.properties, &cortical_id_display, result);
342    }
343}
344
345/// Leak and leak variability are fractions (0 to 1), not percents. Shared with the schema
346/// bounds in `feagi-services` so load-time and update-time validation cannot drift.
347pub const LEAK_FRACTION_MIN: f64 = 0.0;
348pub const LEAK_FRACTION_MAX: f64 = 1.0;
349/// The consecutive-fire limit is stored as a `u16` count (0 means unlimited).
350pub const CONSECUTIVE_FIRE_COUNT_MAX: f64 = u16::MAX as f64;
351
352/// Reject out-of-range leak, leak variability and consecutive-fire limit values at load.
353fn validate_neuron_fractions(
354    properties: &std::collections::HashMap<String, Value>,
355    cortical_id_display: &str,
356    result: &mut ValidationResult,
357) {
358    for key in ["leak_coefficient", "leak_variability"] {
359        if let Some(n) = properties.get(key).and_then(|v| v.as_f64()) {
360            if !n.is_finite() || !(LEAK_FRACTION_MIN..=LEAK_FRACTION_MAX).contains(&n) {
361                result.add_error(format!(
362                    "Cortical area '{cortical_id_display}': {key} must be >= {LEAK_FRACTION_MIN} and <= {LEAK_FRACTION_MAX} (fraction, not percent); got {n}"
363                ));
364            }
365        }
366    }
367    for key in ["consecutive_fire_cnt_max", "consecutive_fire_limit"] {
368        if let Some(n) = properties.get(key).and_then(|v| v.as_f64()) {
369            if !n.is_finite()
370                || n.fract() != 0.0
371                || !(0.0..=CONSECUTIVE_FIRE_COUNT_MAX).contains(&n)
372            {
373                result.add_error(format!(
374                    "Cortical area '{cortical_id_display}': {key} must be an integer >= 0 and <= {CONSECUTIVE_FIRE_COUNT_MAX}; got {n}"
375                ));
376            }
377        }
378    }
379}
380
381/// Validate MP encoding settings of a memory area.
382///
383/// Change modes need at least two frames; shallower windows are disabled at
384/// registration, so they are reported here as a warning rather than an error.
385fn validate_memory_mp_encoding(
386    properties: &std::collections::HashMap<String, Value>,
387    cortical_id_display: &str,
388    result: &mut ValidationResult,
389) {
390    let Some(mem_props) = crate::extract_memory_properties(properties) else {
391        return;
392    };
393    if let Err(e) = crate::validate_memory_mp_properties(properties) {
394        result.add_error(format!(
395            "Memory area '{}' has invalid MP encoding: {}",
396            cortical_id_display, e
397        ));
398        return;
399    }
400    if mem_props.mp_change_mode != crate::MpChangeMode::None && mem_props.temporal_depth < 2 {
401        result.add_warning(format!(
402            "Memory area '{}' uses {}='{}' with temporal_depth={}; change encoding needs temporal_depth >= 2 and will be disabled",
403            cortical_id_display,
404            crate::MP_CHANGE_MODE_KEY,
405            mem_props.mp_change_mode.as_str(),
406            mem_props.temporal_depth
407        ));
408    }
409}
410
411/// Validate cortical ID format and compliance with feagi-data-processing templates
412fn validate_cortical_id_format(
413    _cortical_id: &CorticalID,
414    display: &str,
415    result: &mut ValidationResult,
416) {
417    // Base64 encoded 8-byte IDs are 12 characters (with padding)
418    // Old format IDs are 8 characters
419    // Accept both formats for backward compatibility
420    if display.len() != 8 && display.len() != 12 {
421        result.add_error(format!(
422            "Invalid cortical ID length: '{}' is {} characters (must be 8 or 12)",
423            display,
424            display.len()
425        ));
426        return;
427    }
428
429    // Check if it's a CORE area (starts with underscore)
430    if display.starts_with('_') {
431        validate_core_area_id(display, result);
432        return;
433    }
434
435    // Check if it's a CUSTOM/MEMORY area (starts with 'c')
436    if display.starts_with('c') {
437        // Custom areas: No strict validation yet, but should follow naming conventions
438        // Just check that it's properly padded
439        if !display.chars().all(|c| c.is_alphanumeric() || c == '_') {
440            result.add_warning(format!(
441                "Custom cortical ID '{}' contains non-alphanumeric characters",
442                display
443            ));
444        }
445        return;
446    }
447
448    // Check if it's an IPU/OPU area (3-char prefix + 5 chars)
449    validate_io_area_id(display, result);
450}
451
452/// Validate CORE area IDs (power, death, etc.) using feagi-data-processing types
453fn validate_core_area_id(display: &str, result: &mut ValidationResult) {
454    use feagi_structures::genomic::cortical_area::CoreCorticalType;
455
456    // Generate valid CORE IDs from the authoritative source (feagi-data-processing)
457    let valid_core_ids: Vec<String> = vec![
458        CoreCorticalType::Power.to_cortical_id().to_string(), // "___power"
459        CoreCorticalType::Death.to_cortical_id().to_string(), // "___death"
460        CoreCorticalType::Fatigue.to_cortical_id().to_string(), // "___fatig"
461        CoreCorticalType::Pain.to_cortical_id().to_string(),  // "___pain_"
462        CoreCorticalType::Pleasure.to_cortical_id().to_string(), // "___pleas"
463        CoreCorticalType::Fear.to_cortical_id().to_string(),  // "___fear_"
464        CoreCorticalType::Hope.to_cortical_id().to_string(),  // "___hope_"
465    ];
466
467    if !valid_core_ids.contains(&display.to_string()) {
468        result.add_error(format!(
469            "Invalid CORE cortical ID: '{}' - must be one of: {:?}",
470            display, valid_core_ids
471        ));
472    }
473}
474
475/// Validate IPU/OPU area IDs (should follow template system)
476fn validate_io_area_id(display: &str, result: &mut ValidationResult) {
477    // IO cortical IDs have format: [i/o][3-char-unit][4-config-bytes]
478    // For IPU: 'i' + 3-char prefix (e.g., "isvi____")
479    // For OPU: 'o' + 3-char prefix (e.g., "omot____")
480    let first_char = display.chars().next().unwrap_or('_');
481    let unit_prefix = &display[1..4]; // Skip first char (i/o), get 3-char unit identifier
482
483    // Known valid IPU prefixes from feagi-data-processing templates
484    const VALID_IPU_PREFIXES: &[&str] = &[
485        "svi", // SegmentedVision (9 areas: isvi____ variants)
486        "aud", // Audio
487        "tac", // Tactile
488        "olf", // Olfactory
489        "vis", // Vision (generic)
490        "dpt", // DepthMap
491    ];
492
493    // Known valid OPU prefixes from feagi-data-processing templates
494    const VALID_OPU_PREFIXES: &[&str] = &[
495        "mot", // Motor (omot____ variants)
496        "voc", // Vocal
497        "gaz", // Gaze control
498        "pse", // Positional Servo
499        "mis", // Miscellaneous
500    ];
501
502    let is_valid_ipu = first_char == 'i' && VALID_IPU_PREFIXES.contains(&unit_prefix);
503    let is_valid_opu = first_char == 'o' && VALID_OPU_PREFIXES.contains(&unit_prefix);
504
505    if !is_valid_ipu && !is_valid_opu {
506        // Check for OLD invalid formats (old format didn't have i/o prefix)
507        if display.starts_with("iic") || display.starts_with("omot") || display.starts_with("ogaz")
508        {
509            result.add_error(format!(
510                "INVALID OLD-FORMAT cortical ID: '{}' - not compliant with feagi-data-processing templates. \
511                Valid IPU format: 'i' + unit_prefix (e.g., 'isvi____'). \
512                Valid OPU format: 'o' + unit_prefix (e.g., 'omot____'). \
513                Valid IPU units: {:?}, Valid OPU units: {:?}. \
514                This genome needs migration to the new format.",
515                display, VALID_IPU_PREFIXES, VALID_OPU_PREFIXES
516            ));
517        } else {
518            result.add_warning(format!(
519                "Unknown cortical ID: '{}' (first char: '{}', unit: '{}') - may not follow feagi-data-processing template system. \
520                Valid IPU format: 'i' + {:?}. Valid OPU format: 'o' + {:?}",
521                display, first_char, unit_prefix, VALID_IPU_PREFIXES, VALID_OPU_PREFIXES
522            ));
523        }
524        return;
525    }
526
527    // Validate the index/suffix part (characters 4-7, skipping i/o and unit prefix)
528    let suffix = &display[4..];
529
530    // For SegmentedVision (isvi), validate index (byte 4 should be 0-8)
531    if first_char == 'i' && unit_prefix == "svi" {
532        if let Some(index_char) = display.chars().nth(4) {
533            if index_char.is_ascii_digit() {
534                let digit = index_char as u8 - b'0';
535                if digit > 8 {
536                    result.add_error(format!(
537                        "Invalid SegmentedVision index: '{}' in '{}' - SegmentedVision has 9 areas (indices 0-8)",
538                        digit, display
539                    ));
540                }
541            }
542        }
543    }
544
545    // Check that suffix is properly padded with underscores
546    if !suffix.chars().all(|c| c.is_alphanumeric() || c == '_') {
547        result.add_warning(format!(
548            "Cortical ID '{}' has invalid characters in suffix (should be alphanumeric or underscore)",
549            display
550        ));
551    }
552}
553
554/// Validate morphologies
555fn validate_morphologies(genome: &RuntimeGenome, result: &mut ValidationResult) {
556    if genome.morphologies.count() == 0 {
557        result.add_warning("Genome has no morphologies defined".to_string());
558        return;
559    }
560
561    // Check for required core morphologies
562    let required_core = vec!["block_to_block", "projector"];
563    for morph_id in required_core {
564        if !genome.morphologies.contains(morph_id) {
565            result.add_warning(format!(
566                "Missing recommended core morphology: '{}'",
567                morph_id
568            ));
569        }
570    }
571
572    for (morphology_id, morphology) in genome.morphologies.iter() {
573        validate_single_morphology(morphology_id, morphology, result);
574    }
575}
576
577/// Validate a single morphology
578fn validate_single_morphology(
579    morphology_id: &str,
580    morphology: &crate::Morphology,
581    result: &mut ValidationResult,
582) {
583    match &morphology.parameters {
584        MorphologyParameters::Vectors { vectors } => {
585            if vectors.is_empty() {
586                result.add_error(format!(
587                    "Morphology '{}' (vectors) has no vectors defined",
588                    morphology_id
589                ));
590            }
591
592            // Check for all-zero vectors (useless)
593            for (i, vec) in vectors.iter().enumerate() {
594                if vec[0] == 0 && vec[1] == 0 && vec[2] == 0 {
595                    result.add_warning(format!(
596                        "Morphology '{}' has zero vector at index {}: [{}, {}, {}]",
597                        morphology_id, i, vec[0], vec[1], vec[2]
598                    ));
599                }
600            }
601        }
602
603        MorphologyParameters::Patterns { patterns } => {
604            if patterns.is_empty() {
605                result.add_error(format!(
606                    "Morphology '{}' (patterns) has no patterns defined",
607                    morphology_id
608                ));
609            }
610
611            for (i, pattern) in patterns.iter().enumerate() {
612                if pattern[0].len() != 3 || pattern[1].len() != 3 {
613                    result.add_error(format!(
614                        "Morphology '{}' pattern {} has invalid structure (expected [src[3], dst[3]])",
615                        morphology_id, i
616                    ));
617                }
618            }
619        }
620
621        MorphologyParameters::Functions {} => {
622            // Functions are built-in, no parameters to validate
623        }
624
625        MorphologyParameters::Composite {
626            src_seed,
627            src_pattern,
628            mapper_morphology,
629        } => {
630            // Validate src_seed
631            if src_seed[0] == 0 || src_seed[1] == 0 || src_seed[2] == 0 {
632                result.add_warning(format!(
633                    "Morphology '{}' has zero dimension in src_seed: [{}, {}, {}]",
634                    morphology_id, src_seed[0], src_seed[1], src_seed[2]
635                ));
636            }
637
638            // Validate src_pattern
639            if src_pattern.is_empty() {
640                result.add_error(format!(
641                    "Morphology '{}' (composite) has empty src_pattern",
642                    morphology_id
643                ));
644            }
645
646            // Validate mapper_morphology reference
647            if mapper_morphology.is_empty() {
648                result.add_error(format!(
649                    "Morphology '{}' (composite) has empty mapper_morphology reference",
650                    morphology_id
651                ));
652            }
653        }
654    }
655}
656
657/// Validate physiology parameters
658fn validate_physiology(genome: &RuntimeGenome, result: &mut ValidationResult) {
659    let phys = &genome.physiology;
660
661    if phys.simulation_timestep <= 0.0 {
662        result.add_error(format!(
663            "Invalid simulation_timestep: {} (must be > 0.0)",
664            phys.simulation_timestep
665        ));
666    }
667
668    if phys.simulation_timestep > 1.0 {
669        result.add_warning(format!(
670            "Very large simulation_timestep: {} seconds (typical: 0.01-0.1)",
671            phys.simulation_timestep
672        ));
673    }
674
675    if phys.max_age == 0 {
676        result.add_warning("max_age is 0 (neurons will never age)".to_string());
677    }
678
679    if phys.plasticity_queue_depth == 0 {
680        result.add_warning("plasticity_queue_depth is 0 (no plasticity history)".to_string());
681    }
682
683    // Validate quantization_precision
684    validate_quantization_precision(&phys.quantization_precision, result);
685}
686
687/// Validate quantization precision value
688fn validate_quantization_precision(precision: &str, result: &mut ValidationResult) {
689    use feagi_npu_neural::types::Precision;
690
691    // Try to parse the precision string
692    match Precision::from_str(precision) {
693        Ok(parsed_precision) => {
694            // Valid - log what was selected
695            if precision != parsed_precision.as_str() {
696                result.add_warning(format!(
697                    "Quantization precision '{}' normalized to '{}'",
698                    precision,
699                    parsed_precision.as_str()
700                ));
701            }
702        }
703        Err(_) => {
704            result.add_error(format!(
705                "Invalid quantization_precision: '{}' (must be 'fp32', 'fp16', or 'int8')",
706                precision
707            ));
708        }
709    }
710}
711
712/// Cross-validate references between genome sections
713fn cross_validate(genome: &RuntimeGenome, result: &mut ValidationResult) {
714    // Build morphology ID set for quick lookup
715    let morphology_ids: HashSet<String> =
716        genome.morphologies.morphology_ids().into_iter().collect();
717
718    // Check if cortical areas reference morphologies in their properties
719    for (cortical_id, area) in &genome.cortical_areas {
720        let cortical_id_display = cortical_id.to_string();
721        if let Some(Value::Object(dstmap)) = area.properties.get("dstmap") {
722            for (dest_area, rules) in dstmap {
723                // Check if destination area exists (convert string to CorticalID)
724                if let Ok(dest_cortical_id) =
725                    crate::genome::parser::string_to_cortical_id(dest_area)
726                {
727                    if !genome.cortical_areas.contains_key(&dest_cortical_id) {
728                        result.add_error(format!(
729                            "Cortical area '{}' references non-existent destination area '{}' in dstmap",
730                            cortical_id_display, dest_area
731                        ));
732                    }
733                } else {
734                    result.add_error(format!(
735                        "Cortical area '{}' has invalid destination area ID '{}' in dstmap",
736                        cortical_id_display, dest_area
737                    ));
738                }
739
740                // Check morphology references in rules
741                if let Value::Array(rules_array) = rules {
742                    for rule in rules_array {
743                        if let Value::Array(rule_array) = rule {
744                            if let Some(Value::String(morph_id)) = rule_array.first() {
745                                if !morphology_ids.contains(morph_id) {
746                                    result.add_error(format!(
747                                        "Cortical area '{}' references undefined morphology '{}' in dstmap rule",
748                                        cortical_id_display, morph_id
749                                    ));
750                                }
751                            }
752                        }
753                    }
754                }
755            }
756        }
757    }
758
759    // Validate brain region references
760    for (region_id, region) in &genome.brain_regions {
761        // Check if cortical areas in region exist
762        for cortical_id in &region.cortical_areas {
763            if !genome.cortical_areas.contains_key(cortical_id) {
764                result.add_error(format!(
765                    "Brain region '{}' references non-existent cortical area '{}'",
766                    region_id, cortical_id
767                ));
768            }
769        }
770    }
771
772    for (classifier_id, classifier) in &genome.classifiers {
773        if classifier.name.trim().is_empty() {
774            result.add_error(format!("Classifier '{}' has an empty name", classifier_id));
775        }
776        if !genome
777            .brain_regions
778            .contains_key(&classifier.parent_region_id)
779        {
780            result.add_error(format!(
781                "Classifier '{}' references unknown parent_region_id '{}'",
782                classifier_id, classifier.parent_region_id
783            ));
784        }
785        for area_id in classifier.owned_area_ids() {
786            if crate::genome::parser::string_to_cortical_id(&area_id)
787                .ok()
788                .and_then(|id| genome.cortical_areas.get(&id).map(|_| ()))
789                .is_none()
790            {
791                result.add_error(format!(
792                    "Classifier '{}' references missing owned area '{}'",
793                    classifier_id, area_id
794                ));
795            }
796        }
797        for area_id in classifier.input_area_ids() {
798            if crate::genome::parser::string_to_cortical_id(&area_id)
799                .ok()
800                .and_then(|id| genome.cortical_areas.get(&id).map(|_| ()))
801                .is_none()
802            {
803                result.add_error(format!(
804                    "Classifier '{}' references missing input area '{}'",
805                    classifier_id, area_id
806                ));
807            }
808        }
809        for modulator_id in &classifier.reward_modulator_ids {
810            match genome.modulators.get(modulator_id) {
811                None => result.add_error(format!(
812                    "Classifier '{}' lists missing reward modulator '{}'",
813                    classifier_id, modulator_id
814                )),
815                Some(instance)
816                    if instance.kind != feagi_structures::genomic::ModulatorKind::Reward =>
817                {
818                    result.add_error(format!(
819                        "Classifier '{}' lists '{}', which is not a Reward modulator",
820                        classifier_id, modulator_id
821                    ))
822                }
823                Some(_) => {}
824            }
825        }
826    }
827
828    // Validate composite morphology references
829    for (morphology_id, morphology) in genome.morphologies.iter() {
830        if let MorphologyParameters::Composite {
831            mapper_morphology, ..
832        } = &morphology.parameters
833        {
834            if !morphology_ids.contains(mapper_morphology) {
835                result.add_error(format!(
836                    "Composite morphology '{}' references undefined mapper morphology '{}'",
837                    morphology_id, mapper_morphology
838                ));
839            }
840        }
841    }
842}
843
844#[cfg(test)]
845mod tests {
846    use super::*;
847    use crate::{
848        GenomeMetadata, GenomeSignatures, GenomeStats, MorphologyRegistry, PhysiologyConfig,
849    };
850    use std::collections::HashMap;
851
852    #[test]
853    fn test_validate_empty_genome() {
854        let genome = RuntimeGenome {
855            metadata: GenomeMetadata {
856                genome_id: "test".to_string(),
857                genome_title: "Test".to_string(),
858                genome_description: "".to_string(),
859                version: "2.0".to_string(),
860                timestamp: 0.0,
861                brain_regions_root: None,
862            },
863            cortical_areas: HashMap::new(),
864            brain_regions: HashMap::new(),
865            classifiers: HashMap::new(),
866            morphologies: MorphologyRegistry::new(),
867            modulators: crate::modulators::ModulatorRegistry::new(),
868            physiology: PhysiologyConfig::default(),
869            signatures: GenomeSignatures {
870                genome: "0".to_string(),
871                blueprint: "0".to_string(),
872                physiology: "0".to_string(),
873                morphologies: None,
874            },
875            stats: GenomeStats::default(),
876            change_history: Vec::new(),
877        };
878
879        let result = validate_genome(&genome);
880
881        // Should have warnings about empty cortical areas and morphologies
882        assert!(!result.warnings.is_empty());
883        println!("Warnings: {:?}", result.warnings);
884    }
885
886    #[test]
887    fn test_validate_valid_genome() {
888        let mut genome = RuntimeGenome {
889            metadata: GenomeMetadata {
890                genome_id: "test_genome".to_string(),
891                genome_title: "Test Genome".to_string(),
892                genome_description: "Valid test genome".to_string(),
893                version: "2.0".to_string(),
894                timestamp: 1234567890.0,
895                brain_regions_root: None,
896            },
897            cortical_areas: HashMap::new(),
898            brain_regions: HashMap::new(),
899            classifiers: HashMap::new(),
900            morphologies: MorphologyRegistry::new(),
901            modulators: crate::modulators::ModulatorRegistry::new(),
902            physiology: PhysiologyConfig::default(),
903            signatures: GenomeSignatures {
904                genome: "abc123".to_string(),
905                blueprint: "def456".to_string(),
906                physiology: "ghi789".to_string(),
907                morphologies: None,
908            },
909            stats: GenomeStats::default(),
910            change_history: Vec::new(),
911        };
912
913        // Add a valid cortical area (use CoreCorticalType::Power)
914        use feagi_structures::genomic::cortical_area::CustomCorticalType;
915        use feagi_structures::genomic::cortical_area::{
916            CoreCorticalType, CorticalArea, CorticalAreaDimensions, CorticalAreaType,
917        };
918        let test_id = CoreCorticalType::Power.to_cortical_id();
919        let area = CorticalArea::new(
920            test_id,
921            0,
922            "Test Area".to_string(),
923            CorticalAreaDimensions::new(10, 10, 10).unwrap(),
924            (0, 0, 0).into(),
925            CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire),
926        )
927        .expect("Failed to create cortical area");
928
929        genome.cortical_areas.insert(test_id, area);
930
931        let result = validate_genome(&genome);
932
933        // Should pass with only warnings (empty morphologies)
934        println!("Errors: {:?}", result.errors);
935        println!("Warnings: {:?}", result.warnings);
936
937        // Genome is valid but has warnings
938        assert!(result.errors.is_empty());
939        assert!(!result.warnings.is_empty()); // Warning about no morphologies
940    }
941
942    #[test]
943    fn test_validate_quantization_precision() {
944        let mut genome = create_minimal_genome();
945
946        // Test 1: Valid precision (fp32)
947        genome.physiology.quantization_precision = "fp32".to_string();
948        let result = validate_genome(&genome);
949        assert!(result.errors.is_empty(), "fp32 should be valid");
950
951        // Test 2: Valid precision (int8)
952        genome.physiology.quantization_precision = "int8".to_string();
953        let result = validate_genome(&genome);
954        assert!(result.errors.is_empty(), "int8 should be valid");
955
956        // Test 3: Valid but non-canonical (i8 → int8)
957        genome.physiology.quantization_precision = "i8".to_string();
958        let result = validate_genome(&genome);
959        assert!(result.errors.is_empty(), "i8 should be valid");
960        assert!(
961            result.warnings.iter().any(|w| w.contains("normalized")),
962            "Should warn about normalization"
963        );
964
965        // Test 4: Invalid precision
966        genome.physiology.quantization_precision = "invalid".to_string();
967        let result = validate_genome(&genome);
968        assert!(!result.errors.is_empty(), "invalid should produce error");
969        assert!(
970            result
971                .errors
972                .iter()
973                .any(|e| e.contains("Invalid quantization_precision")),
974            "Should have quantization error"
975        );
976    }
977
978    #[test]
979    fn test_auto_fix_quantization_precision() {
980        // Test 1: Missing precision (empty string)
981        let mut genome = create_minimal_genome();
982        genome.physiology.quantization_precision = "".to_string();
983
984        let fixes = auto_fix_genome(&mut genome);
985        assert!(fixes > 0, "Should apply at least one fix");
986        assert_eq!(
987            genome.physiology.quantization_precision, "int8",
988            "Should default to int8"
989        );
990
991        // Test 2: Non-canonical (i8 → int8)
992        genome.physiology.quantization_precision = "i8".to_string();
993        let _fixes = auto_fix_genome(&mut genome);
994        assert_eq!(
995            genome.physiology.quantization_precision, "int8",
996            "Should normalize i8 to int8"
997        );
998
999        // Test 3: Invalid → default
1000        genome.physiology.quantization_precision = "invalid".to_string();
1001        let _fixes = auto_fix_genome(&mut genome);
1002        assert_eq!(
1003            genome.physiology.quantization_precision, "int8",
1004            "Invalid should default to int8"
1005        );
1006    }
1007
1008    #[test]
1009    fn test_validate_rejects_out_of_range_leak_and_fire_count() {
1010        let mut result = ValidationResult::new();
1011        let props = std::collections::HashMap::from([
1012            ("leak_coefficient".to_string(), serde_json::json!(25.0)),
1013            ("leak_variability".to_string(), serde_json::json!(0.5)),
1014            (
1015                "consecutive_fire_cnt_max".to_string(),
1016                serde_json::json!(1.5),
1017            ),
1018        ]);
1019        validate_neuron_fractions(&props, "area", &mut result);
1020        assert_eq!(result.errors.len(), 2, "{:?}", result.errors);
1021        assert!(result.errors[0].contains("leak_coefficient"));
1022        assert!(result.errors[1].contains("consecutive_fire_cnt_max"));
1023    }
1024
1025    #[test]
1026    fn test_validate_classifier_requires_parent_region() {
1027        let mut genome = create_minimal_genome();
1028        genome.classifiers.insert(
1029            "clf-1".to_string(),
1030            feagi_structures::genomic::classifiers::Classifier {
1031                classifier_id: "clf-1".to_string(),
1032                name: "demo".to_string(),
1033                parent_region_id: "missing".to_string(),
1034                coordinates_3d: [0, 0, 0],
1035                sample_area_ids: Vec::new(),
1036                class_bindings: vec![
1037                    feagi_structures::genomic::classifiers::ClassifierClassBinding {
1038                        class_area_id: "cclass".to_string(),
1039                        class_output_area_id: "cout1".to_string(),
1040                    },
1041                ],
1042                sample_memory_id: "msmem1".to_string(),
1043                class_memory_id: "mcmem1".to_string(),
1044                error_area_id: "cerr1".to_string(),
1045                reward_training: false,
1046                answer_feedback_area_id: None,
1047                correct_area_id: String::new(),
1048                reward_modulator_ids: vec!["gone".to_string(), "boost".to_string()],
1049                answer_latency_bursts: 0,
1050                learn_area_id: None,
1051                confidence_area_id: None,
1052                properties: HashMap::new(),
1053            },
1054        );
1055        genome.modulators.insert(
1056            "boost".to_string(),
1057            crate::modulators::ModulatorInstance {
1058                kind: feagi_structures::genomic::ModulatorKind::TransmissionGain,
1059                magnitude_percent: 50.0,
1060                effect_duration_bursts: 1,
1061                rest_bursts: 0,
1062                graded: false,
1063                full_scale_potential: None,
1064                driver_cortical_id:
1065                    feagi_structures::genomic::cortical_area::CorticalID::modulator_driver(0),
1066            },
1067        );
1068        let result = validate_genome(&genome);
1069        assert!(result
1070            .errors
1071            .iter()
1072            .any(|error| error.contains("missing reward modulator 'gone'")));
1073        assert!(result
1074            .errors
1075            .iter()
1076            .any(|error| error.contains("'boost', which is not a Reward modulator")));
1077        assert!(result
1078            .errors
1079            .iter()
1080            .any(|error| error.contains("unknown parent_region_id")));
1081        assert!(result
1082            .errors
1083            .iter()
1084            .any(|error| error.contains("missing owned area")));
1085    }
1086
1087    fn create_minimal_genome() -> RuntimeGenome {
1088        RuntimeGenome {
1089            metadata: GenomeMetadata {
1090                genome_id: "test".to_string(),
1091                genome_title: "Test".to_string(),
1092                genome_description: "".to_string(),
1093                version: "2.0".to_string(),
1094                timestamp: 0.0,
1095                brain_regions_root: None,
1096            },
1097            cortical_areas: HashMap::new(),
1098            brain_regions: HashMap::new(),
1099            classifiers: HashMap::new(),
1100            morphologies: MorphologyRegistry::new(),
1101            modulators: crate::modulators::ModulatorRegistry::new(),
1102            physiology: PhysiologyConfig::default(),
1103            signatures: GenomeSignatures {
1104                genome: "0".to_string(),
1105                blueprint: "0".to_string(),
1106                physiology: "0".to_string(),
1107                morphologies: None,
1108            },
1109            stats: GenomeStats::default(),
1110            change_history: Vec::new(),
1111        }
1112    }
1113}