Skip to main content

feagi_evolutionary/genome/
parser.rs

1// Copyright 2025 Neuraville Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4/*!
5Genome JSON parser.
6
7Parses FEAGI 2.1 genome JSON format into runtime data structures.
8
9## Genome Structure (v2.1)
10
11```json
12{
13  "genome_id": "...",
14  "genome_title": "...",
15  "version": "2.1",
16  "blueprint": {
17    "cortical_id": {
18      "cortical_name": "...",
19      "block_boundaries": [x, y, z],
20      "relative_coordinate": [x, y, z],
21      "cortical_type": "IPU/OPU/CUSTOM/CORE/MEMORY",
22      ...
23    }
24  },
25  "brain_regions": {
26    "root": {
27      "title": "...",
28      "parent_region_id": null,
29      "coordinate_3d": [x, y, z],
30      "cortical_areas": ["cortical_id1", ...],
31      "regions": ["child_region_id1", ...]
32    }
33  },
34  "neuron_morphologies": { ... },
35  "physiology": { ... }
36}
37```
38
39Copyright 2025 Neuraville Inc.
40Licensed under the Apache License, Version 2.0
41*/
42
43use serde::{Deserialize, Serialize};
44use serde_json::Value;
45use std::collections::HashMap;
46use tracing::warn;
47
48use crate::genome::migration::membership::fold_genome_region_membership;
49use crate::types::{EvoError, EvoResult};
50use feagi_structures::genomic::brain_regions::RegionID;
51use feagi_structures::genomic::classifiers::Classifier;
52use feagi_structures::genomic::cortical_area::CorticalID;
53use feagi_structures::genomic::cortical_area::{
54    CorticalArea, CorticalAreaDimensions as Dimensions,
55};
56use feagi_structures::genomic::descriptors::GenomeCoordinate3D;
57use feagi_structures::genomic::{BrainRegion, RegionType};
58
59/// Parsed genome data ready for ConnectomeManager
60#[derive(Debug, Clone)]
61pub struct ParsedGenome {
62    /// Genome metadata
63    pub genome_id: String,
64    pub genome_title: String,
65    pub version: String,
66
67    /// Cortical areas extracted from blueprint
68    pub cortical_areas: Vec<CorticalArea>,
69
70    /// Brain regions and hierarchy
71    pub brain_regions: Vec<(BrainRegion, Option<String>)>, // (region, parent_id)
72
73    /// First-class classifier assemblies (parallel to brain_regions)
74    pub classifiers: Vec<Classifier>,
75
76    /// Raw neuron morphologies (for later processing)
77    pub neuron_morphologies: HashMap<String, Value>,
78
79    /// Raw modulator instances (for later processing)
80    pub modulators: HashMap<String, Value>,
81
82    /// Raw physiology data (for later processing)
83    pub physiology: Option<Value>,
84
85    /// Recorded structural changes, carried as-is (see `RuntimeGenome::change_history`)
86    pub change_history: Vec<Value>,
87}
88
89/// Raw genome JSON structure for deserialization
90#[derive(Debug, Clone, Deserialize, Serialize)]
91pub struct RawGenome {
92    pub genome_id: Option<String>,
93    pub genome_title: Option<String>,
94    pub genome_description: Option<String>,
95    pub version: String,
96    /// Integer schema version. Optional on the wire so older genomes that
97    /// pre-date this field still deserialize. The authoritative resolver
98    /// is `crate::genome::schema::detect_schema_version` and consumers
99    /// MUST go through it instead of branching on this field directly.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub genome_schema_version: Option<u32>,
102    pub blueprint: HashMap<String, RawCorticalArea>,
103    #[serde(default)]
104    pub brain_regions: HashMap<String, RawBrainRegion>,
105    #[serde(default)]
106    pub classifiers: HashMap<String, RawClassifier>,
107    #[serde(default)]
108    pub neuron_morphologies: HashMap<String, Value>,
109    #[serde(default)]
110    pub modulators: HashMap<String, Value>,
111    #[serde(default)]
112    pub physiology: Option<Value>,
113    /// Root brain region ID (UUID string) - for O(1) root lookup
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub brain_regions_root: Option<String>,
116    /// Recorded structural changes (optional; see `RuntimeGenome::change_history`)
117    #[serde(default, skip_serializing_if = "Vec::is_empty")]
118    pub change_history: Vec<Value>,
119}
120
121/// Raw cortical area from blueprint
122#[derive(Debug, Clone, Deserialize, Serialize)]
123pub struct RawCorticalArea {
124    pub cortical_name: Option<String>,
125    pub block_boundaries: Option<Vec<u32>>,
126    pub relative_coordinate: Option<Vec<i32>>,
127    pub cortical_type: Option<String>,
128
129    // Optional properties
130    pub group_id: Option<String>,
131    pub sub_group_id: Option<String>,
132    pub per_voxel_neuron_cnt: Option<u32>,
133    pub cortical_mapping_dst: Option<Value>,
134
135    // Neural properties
136    pub synapse_attractivity: Option<f32>,
137    pub refractory_period: Option<u32>,
138    pub firing_threshold: Option<f32>,
139    pub firing_threshold_limit: Option<f32>,
140    pub firing_threshold_increment_x: Option<f32>,
141    pub firing_threshold_increment_y: Option<f32>,
142    pub firing_threshold_increment_z: Option<f32>,
143    pub leak_coefficient: Option<f32>,
144    pub leak_variability: Option<f32>,
145    pub neuron_excitability: Option<f32>,
146    pub postsynaptic_current: Option<f32>,
147    pub postsynaptic_current_max: Option<f32>,
148    pub degeneration: Option<f32>,
149    pub psp_uniform_distribution: Option<bool>,
150    pub mp_charge_accumulation: Option<bool>,
151    pub mp_driven_psp: Option<bool>,
152    pub visualization: Option<bool>,
153    pub burst_engine_activation: Option<bool>,
154    #[serde(rename = "2d_coordinate")]
155    pub coordinate_2d: Option<Vec<i32>>,
156
157    // Memory properties
158    pub is_mem_type: Option<bool>,
159    pub longterm_mem_threshold: Option<u32>,
160    pub lifespan_growth_rate: Option<f32>,
161    pub init_lifespan: Option<u32>,
162    pub temporal_depth: Option<u32>,
163    pub mp_learning_enabled: Option<bool>,
164    pub mp_change_mode: Option<String>,
165    pub mp_delta_quantization: Option<f32>,
166    pub mp_ratio_quantization: Option<f32>,
167    pub min_window_activity: Option<u32>,
168    pub scan_skip_density: Option<f32>,
169    pub memory_neuron_cap: Option<u32>,
170    pub ltm_eviction: Option<String>,
171    pub replay_trigger: Option<String>,
172    pub capture_max_bursts: Option<u32>,
173    pub consecutive_fire_cnt_max: Option<u32>,
174    pub snooze_length: Option<u32>,
175
176    // Allow any other properties (future-proofing)
177    #[serde(flatten)]
178    pub other: HashMap<String, Value>,
179}
180
181/// Raw brain region from genome
182#[derive(Debug, Clone, Deserialize, Serialize)]
183pub struct RawBrainRegion {
184    #[serde(alias = "name")]
185    pub title: Option<String>,
186    pub description: Option<String>,
187    pub parent_region_id: Option<String>,
188    pub coordinate_2d: Option<Vec<i32>>,
189    pub coordinate_3d: Option<Vec<i32>>,
190    /// Legacy wire key. Canonical saves use `cortical_areas`. Parse folds
191    /// `areas` into `cortical_areas` before this alias is applied, so a region
192    /// that still carries both names does not fail as a duplicate field.
193    #[serde(alias = "cortical_areas")]
194    pub areas: Option<Vec<String>>,
195    pub regions: Option<Vec<String>>,
196    pub inputs: Option<Vec<String>>,
197    pub outputs: Option<Vec<String>>,
198    /// Declared interface lists (persisted from RuntimeGenome / PUT region).
199    pub designated_inputs: Option<Vec<String>>,
200    pub designated_outputs: Option<Vec<String>>,
201    pub signature: Option<String>,
202    /// v3 `serde_json::to_value(BrainRegion)` nests `inputs` / `designated_*` under `properties`.
203    pub properties: Option<HashMap<String, Value>>,
204}
205
206/// Raw classifier assembly from the top-level `classifiers` genome key.
207#[derive(Debug, Clone, Deserialize, Serialize)]
208pub struct RawClassifier {
209    #[serde(alias = "title")]
210    pub name: Option<String>,
211    pub parent_region_id: Option<String>,
212    #[serde(alias = "coordinate_3d")]
213    pub coordinates_3d: Option<Vec<i32>>,
214    #[serde(default)]
215    pub sample_area_ids: Vec<String>,
216    #[serde(default)]
217    pub class_bindings: Vec<feagi_structures::genomic::classifiers::ClassifierClassBinding>,
218    pub sample_memory_id: Option<String>,
219    pub class_memory_id: Option<String>,
220    pub error_area_id: Option<String>,
221    #[serde(default)]
222    pub correct_area_id: String,
223    #[serde(default)]
224    pub reward_training: bool,
225    #[serde(default)]
226    pub answer_feedback_area_id: Option<String>,
227    #[serde(default)]
228    pub reward_modulator_ids: Vec<String>,
229    #[serde(default)]
230    pub answer_latency_bursts: u32,
231    #[serde(default)]
232    pub learn_area_id: Option<String>,
233    #[serde(default)]
234    pub confidence_area_id: Option<String>,
235    pub properties: Option<HashMap<String, Value>>,
236}
237
238/// Convert cortical_mapping_dst keys from old format to base64
239///
240/// This ensures all destination cortical IDs in dstmap are stored in the new base64 format.
241fn convert_dstmap_keys_to_base64(dstmap: &Value) -> Value {
242    if let Some(dstmap_obj) = dstmap.as_object() {
243        let mut converted = serde_json::Map::new();
244
245        for (dest_id_str, mapping_value) in dstmap_obj {
246            // Convert destination cortical_id to base64 format
247            match string_to_cortical_id(dest_id_str) {
248                Ok(dest_cortical_id) => {
249                    converted.insert(dest_cortical_id.as_base_64(), mapping_value.clone());
250                }
251                Err(e) => {
252                    // If conversion fails, keep original and log warning
253                    tracing::warn!(
254                        "Failed to convert dstmap key '{}' to base64: {}, keeping original",
255                        dest_id_str,
256                        e
257                    );
258                    converted.insert(dest_id_str.clone(), mapping_value.clone());
259                }
260            }
261        }
262
263        Value::Object(converted)
264    } else {
265        // Not an object, return as-is
266        dstmap.clone()
267    }
268}
269
270/// Convert a string cortical_id to CorticalID
271/// Handles both old 6-char format and new base64 format
272/// CRITICAL: Uses feagi-data-processing types as single source of truth for core areas
273pub fn string_to_cortical_id(id_str: &str) -> EvoResult<CorticalID> {
274    use feagi_structures::genomic::cortical_area::CoreCorticalType;
275
276    // Try base64 first (new format)
277    if let Ok(cortical_id) = CorticalID::try_from_base_64(id_str) {
278        let mut bytes = [0u8; CorticalID::CORTICAL_ID_LENGTH];
279        cortical_id.write_id_to_bytes(&mut bytes);
280        if bytes == *b"___power" {
281            return Ok(CoreCorticalType::Power.to_cortical_id());
282        }
283        if bytes == *b"___death" {
284            return Ok(CoreCorticalType::Death.to_cortical_id());
285        }
286        if bytes == *b"___fatig" {
287            return Ok(CoreCorticalType::Fatigue.to_cortical_id());
288        }
289        if bytes == *b"___pain_" {
290            return Ok(CoreCorticalType::Pain.to_cortical_id());
291        }
292        if bytes == *b"___pleas" {
293            return Ok(CoreCorticalType::Pleasure.to_cortical_id());
294        }
295        if bytes == *b"___fear_" {
296            return Ok(CoreCorticalType::Fear.to_cortical_id());
297        }
298        if bytes == *b"___hope_" {
299            return Ok(CoreCorticalType::Hope.to_cortical_id());
300        }
301        return Ok(cortical_id);
302    }
303
304    // Handle legacy CORE area names (6-char format) - use proper types from feagi-data-processing
305    if id_str == "_power" {
306        return Ok(CoreCorticalType::Power.to_cortical_id());
307    }
308    // Legacy shorthand used by older FEAGI genomes: "___pwr" (6-char) refers to core Power.
309    if id_str == "___pwr" {
310        return Ok(CoreCorticalType::Power.to_cortical_id());
311    }
312    // Legacy 8-char core names used in some BV caches
313    if id_str == "___power" {
314        return Ok(CoreCorticalType::Power.to_cortical_id());
315    }
316    // 8-char padded form of ___pwr (from 6-char padding in legacy flat genomes)
317    if id_str == "___pwr__" {
318        return Ok(CoreCorticalType::Power.to_cortical_id());
319    }
320    if id_str == "___death" {
321        return Ok(CoreCorticalType::Death.to_cortical_id());
322    }
323    if id_str == "___fatig" {
324        return Ok(CoreCorticalType::Fatigue.to_cortical_id());
325    }
326    if id_str == "___pain_" {
327        return Ok(CoreCorticalType::Pain.to_cortical_id());
328    }
329    if id_str == "___pleas" {
330        return Ok(CoreCorticalType::Pleasure.to_cortical_id());
331    }
332    if id_str == "___fear_" {
333        return Ok(CoreCorticalType::Fear.to_cortical_id());
334    }
335    if id_str == "___hope_" {
336        return Ok(CoreCorticalType::Hope.to_cortical_id());
337    }
338    if id_str == "_death" {
339        return Ok(CoreCorticalType::Death.to_cortical_id());
340    }
341    if id_str == "_fatigue" {
342        return Ok(CoreCorticalType::Fatigue.to_cortical_id());
343    }
344    if id_str == "_pain" {
345        return Ok(CoreCorticalType::Pain.to_cortical_id());
346    }
347    if id_str == "_pleasure" {
348        return Ok(CoreCorticalType::Pleasure.to_cortical_id());
349    }
350    if id_str == "_fear" {
351        return Ok(CoreCorticalType::Fear.to_cortical_id());
352    }
353    if id_str == "_hope" {
354        return Ok(CoreCorticalType::Hope.to_cortical_id());
355    }
356
357    // For non-core areas, use CorticalID's legacy ASCII parser (6-char and 8-char)
358    if id_str.len() == 6 || id_str.len() == 8 {
359        CorticalID::try_from_legacy_ascii(id_str).map_err(|e| {
360            EvoError::InvalidArea(format!("Failed to convert cortical_id '{}': {}", id_str, e))
361        })
362    } else {
363        Err(EvoError::InvalidArea(format!(
364            "Invalid cortical_id length: '{}' (expected 6 or 8 ASCII chars, or base64)",
365            id_str
366        )))
367    }
368}
369
370/// Genome parser
371pub struct GenomeParser;
372
373impl GenomeParser {
374    /// Normalize cortical ID list properties (inputs, outputs, designated_*) to base64 strings.
375    fn normalize_brain_region_cortical_id_list_properties(region: &mut BrainRegion, keys: &[&str]) {
376        for key in keys {
377            let Some(val) = region.get_property(key) else {
378                continue;
379            };
380            let Some(arr) = val.as_array() else {
381                continue;
382            };
383            let mut out: Vec<String> = Vec::new();
384            for item in arr {
385                let Some(s) = item.as_str() else {
386                    continue;
387                };
388                match string_to_cortical_id(s) {
389                    Ok(cortical_id) => out.push(cortical_id.as_base_64()),
390                    Err(e) => {
391                        warn!(target: "feagi-evo",
392                            "Failed to convert brain region '{}' entry '{}': {}. Skipping.",
393                            key, s, e);
394                    }
395                }
396            }
397            if out.is_empty() {
398                region.properties.remove(*key);
399            } else {
400                region.add_property((*key).to_string(), serde_json::json!(out));
401            }
402        }
403    }
404
405    /// Parse a genome JSON string into a ParsedGenome
406    ///
407    /// # Arguments
408    ///
409    /// * `json_str` - JSON string of the genome
410    ///
411    /// # Returns
412    ///
413    /// Parsed genome ready for loading into ConnectomeManager
414    ///
415    /// # Errors
416    ///
417    /// Returns error if:
418    /// - JSON is malformed
419    /// - Required fields are missing
420    /// - Data types are invalid
421    ///
422    pub fn parse(json_str: &str) -> EvoResult<ParsedGenome> {
423        // Fold legacy `areas` into `cortical_areas` before struct decode.
424        // Serde treats the alias as the same field and rejects a region that
425        // still has both keys.
426        let mut genome_value: Value = serde_json::from_str(json_str)
427            .map_err(|e| EvoError::InvalidGenome(format!("Failed to parse JSON: {}", e)))?;
428        for note in fold_genome_region_membership(&mut genome_value).data_loss {
429            warn!(target: "feagi-evo", "[GENOME-PARSE] {}", note);
430        }
431        let raw: RawGenome = serde_json::from_value(genome_value)
432            .map_err(|e| EvoError::InvalidGenome(format!("Failed to parse JSON: {}", e)))?;
433
434        // Validate version - support 2.x and 3.x (3.0 is flat format with base64 IDs)
435        if !raw.version.starts_with("2.") && !raw.version.starts_with("3.") && raw.version != "3" {
436            return Err(EvoError::InvalidGenome(format!(
437                "Unsupported genome version: {}. Expected 2.x or 3.x",
438                raw.version
439            )));
440        }
441
442        // Parse cortical areas from blueprint
443        let cortical_areas = Self::parse_cortical_areas(&raw.blueprint)?;
444
445        // Parse brain regions
446        let brain_regions = Self::parse_brain_regions(&raw.brain_regions)?;
447        let classifiers = Self::parse_classifiers(&raw.classifiers)?;
448
449        Ok(ParsedGenome {
450            genome_id: raw.genome_id.unwrap_or_else(|| "unknown".to_string()),
451            genome_title: raw.genome_title.unwrap_or_else(|| "Untitled".to_string()),
452            version: raw.version,
453            cortical_areas,
454            brain_regions,
455            classifiers,
456            neuron_morphologies: raw.neuron_morphologies,
457            modulators: raw.modulators,
458            physiology: raw.physiology,
459            change_history: raw.change_history,
460        })
461    }
462
463    /// Parse cortical areas from blueprint
464    fn parse_cortical_areas(
465        blueprint: &HashMap<String, RawCorticalArea>,
466    ) -> EvoResult<Vec<CorticalArea>> {
467        let mut areas = Vec::with_capacity(blueprint.len());
468
469        for (cortical_id_str, raw_area) in blueprint.iter() {
470            // Skip empty IDs
471            if cortical_id_str.is_empty() {
472                warn!(target: "feagi-evo","Skipping empty cortical_id");
473                continue;
474            }
475
476            // Convert string cortical_id to CorticalID (handles 6-char legacy and base64)
477            let cortical_id = match string_to_cortical_id(cortical_id_str) {
478                Ok(id) => id,
479                Err(e) => {
480                    warn!(target: "feagi-evo","Skipping invalid cortical_id '{}': {}", cortical_id_str, e);
481                    continue;
482                }
483            };
484
485            // Extract required fields
486            let name = raw_area
487                .cortical_name
488                .clone()
489                .unwrap_or_else(|| cortical_id_str.clone());
490
491            let dimensions = if let Some(boundaries) = &raw_area.block_boundaries {
492                if boundaries.len() != 3 {
493                    return Err(EvoError::InvalidArea(format!(
494                        "Invalid block_boundaries for {}: expected 3 values, got {}",
495                        cortical_id_str,
496                        boundaries.len()
497                    )));
498                }
499                Dimensions::new(boundaries[0], boundaries[1], boundaries[2])
500                    .map_err(|e| EvoError::InvalidArea(format!("Invalid dimensions: {}", e)))?
501            } else {
502                // Default to 1x1x1 if not specified (should not happen in valid genomes)
503                warn!(target: "feagi-evo","Cortical area {} missing block_boundaries, defaulting to 1x1x1", cortical_id_str);
504                Dimensions::new(1, 1, 1).map_err(|e| {
505                    EvoError::InvalidArea(format!("Invalid default dimensions: {}", e))
506                })?
507            };
508
509            let position = if let Some(coords) = &raw_area.relative_coordinate {
510                if coords.len() != 3 {
511                    return Err(EvoError::InvalidArea(format!(
512                        "Invalid relative_coordinate for {}: expected 3 values, got {}",
513                        cortical_id_str,
514                        coords.len()
515                    )));
516                }
517                GenomeCoordinate3D::new(coords[0], coords[1], coords[2])
518            } else {
519                // Default to origin if not specified
520                warn!(target: "feagi-evo","Cortical area {} missing relative_coordinate, defaulting to (0,0,0)", cortical_id_str);
521                GenomeCoordinate3D::new(0, 0, 0)
522            };
523
524            // Determine cortical type from cortical_id
525            let cortical_type = cortical_id.as_cortical_type().map_err(|e| {
526                EvoError::InvalidArea(format!(
527                    "Failed to determine cortical type from ID {}: {}",
528                    cortical_id_str, e
529                ))
530            })?;
531
532            // Create cortical area with CorticalID object (zero-copy, type-safe)
533            let mut area = CorticalArea::new(
534                cortical_id,
535                0, // cortical_idx will be assigned by ConnectomeManager
536                name,
537                dimensions,
538                position,
539                cortical_type,
540            )?;
541
542            // Store cortical_type as cortical_group for new type system
543            if let Some(ref cortical_type_str) = raw_area.cortical_type {
544                area.properties.insert(
545                    "cortical_group".to_string(),
546                    serde_json::json!(cortical_type_str),
547                );
548            }
549
550            // Store all properties in the properties HashMap
551            // Neural properties
552            if let Some(v) = raw_area.synapse_attractivity {
553                area.properties
554                    .insert("synapse_attractivity".to_string(), serde_json::json!(v));
555            }
556            if let Some(v) = raw_area.refractory_period {
557                area.properties
558                    .insert("refractory_period".to_string(), serde_json::json!(v));
559            }
560            if let Some(v) = raw_area.firing_threshold {
561                area.properties
562                    .insert("firing_threshold".to_string(), serde_json::json!(v));
563            }
564            if let Some(v) = raw_area.firing_threshold_limit {
565                area.properties
566                    .insert("firing_threshold_limit".to_string(), serde_json::json!(v));
567            }
568            if let Some(v) = raw_area.firing_threshold_increment_x {
569                area.properties.insert(
570                    "firing_threshold_increment_x".to_string(),
571                    serde_json::json!(v),
572                );
573            }
574            if let Some(v) = raw_area.firing_threshold_increment_y {
575                area.properties.insert(
576                    "firing_threshold_increment_y".to_string(),
577                    serde_json::json!(v),
578                );
579            }
580            if let Some(v) = raw_area.firing_threshold_increment_z {
581                area.properties.insert(
582                    "firing_threshold_increment_z".to_string(),
583                    serde_json::json!(v),
584                );
585            }
586            if let Some(v) = raw_area.leak_coefficient {
587                area.properties
588                    .insert("leak_coefficient".to_string(), serde_json::json!(v));
589            }
590            if let Some(v) = raw_area.leak_variability {
591                area.properties
592                    .insert("leak_variability".to_string(), serde_json::json!(v));
593            }
594            if let Some(v) = raw_area.neuron_excitability {
595                area.properties
596                    .insert("neuron_excitability".to_string(), serde_json::json!(v));
597            }
598            if let Some(v) = raw_area.postsynaptic_current {
599                area.properties
600                    .insert("postsynaptic_current".to_string(), serde_json::json!(v));
601            }
602            if let Some(v) = raw_area.postsynaptic_current_max {
603                area.properties
604                    .insert("postsynaptic_current_max".to_string(), serde_json::json!(v));
605            }
606            if let Some(v) = raw_area.degeneration {
607                area.properties
608                    .insert("degeneration".to_string(), serde_json::json!(v));
609            }
610
611            // Boolean properties
612            if let Some(v) = raw_area.psp_uniform_distribution {
613                area.properties
614                    .insert("psp_uniform_distribution".to_string(), serde_json::json!(v));
615            }
616            if let Some(v) = raw_area.mp_charge_accumulation {
617                area.properties
618                    .insert("mp_charge_accumulation".to_string(), serde_json::json!(v));
619            }
620            if let Some(v) = raw_area.mp_driven_psp {
621                area.properties
622                    .insert("mp_driven_psp".to_string(), serde_json::json!(v));
623                tracing::info!(
624                    target: "feagi-evo",
625                    "[GENOME-LOAD] Loaded mp_driven_psp={} for area {}",
626                    v,
627                    cortical_id_str
628                );
629            } else {
630                tracing::debug!(
631                    target: "feagi-evo",
632                    "[GENOME-LOAD] mp_driven_psp not found in raw_area for {}, will use default=false",
633                    cortical_id_str
634                );
635            }
636            if let Some(v) = raw_area.visualization {
637                area.properties
638                    .insert("visualization".to_string(), serde_json::json!(v));
639                // Also store as "visible" for compatibility with getters
640                area.properties
641                    .insert("visible".to_string(), serde_json::json!(v));
642            }
643            if let Some(v) = raw_area.burst_engine_activation {
644                area.properties
645                    .insert("burst_engine_active".to_string(), serde_json::json!(v));
646            }
647            if let Some(v) = raw_area.is_mem_type {
648                area.properties
649                    .insert("is_mem_type".to_string(), serde_json::json!(v));
650            }
651
652            // Memory properties
653            if let Some(v) = raw_area.longterm_mem_threshold {
654                area.properties
655                    .insert("longterm_mem_threshold".to_string(), serde_json::json!(v));
656            }
657            if let Some(v) = raw_area.lifespan_growth_rate {
658                area.properties
659                    .insert("lifespan_growth_rate".to_string(), serde_json::json!(v));
660            }
661            if let Some(v) = raw_area.init_lifespan {
662                area.properties
663                    .insert("init_lifespan".to_string(), serde_json::json!(v));
664            }
665            if let Some(v) = raw_area.temporal_depth {
666                area.properties
667                    .insert("temporal_depth".to_string(), serde_json::json!(v));
668            }
669            if let Some(v) = raw_area.mp_learning_enabled {
670                area.properties
671                    .insert("mp_learning_enabled".to_string(), serde_json::json!(v));
672            }
673            if let Some(v) = &raw_area.mp_change_mode {
674                area.properties
675                    .insert("mp_change_mode".to_string(), serde_json::json!(v));
676            }
677            if let Some(v) = raw_area.mp_delta_quantization {
678                area.properties
679                    .insert("mp_delta_quantization".to_string(), serde_json::json!(v));
680            }
681            if let Some(v) = raw_area.mp_ratio_quantization {
682                area.properties
683                    .insert("mp_ratio_quantization".to_string(), serde_json::json!(v));
684            }
685            if let Some(v) = raw_area.min_window_activity {
686                area.properties
687                    .insert("min_window_activity".to_string(), serde_json::json!(v));
688            }
689            if let Some(v) = raw_area.scan_skip_density {
690                area.properties
691                    .insert("scan_skip_density".to_string(), serde_json::json!(v));
692            }
693            if let Some(v) = raw_area.memory_neuron_cap {
694                area.properties
695                    .insert("memory_neuron_cap".to_string(), serde_json::json!(v));
696            }
697            if let Some(v) = &raw_area.ltm_eviction {
698                area.properties
699                    .insert("ltm_eviction".to_string(), serde_json::json!(v));
700            }
701            if let Some(v) = &raw_area.replay_trigger {
702                area.properties
703                    .insert("replay_trigger".to_string(), serde_json::json!(v));
704            }
705            if let Some(v) = raw_area.capture_max_bursts {
706                area.properties
707                    .insert("capture_max_bursts".to_string(), serde_json::json!(v));
708            }
709            if let Some(v) = raw_area.consecutive_fire_cnt_max {
710                area.properties
711                    .insert("consecutive_fire_cnt_max".to_string(), serde_json::json!(v));
712                // Also store as "consecutive_fire_limit" for getter compatibility
713                area.properties
714                    .insert("consecutive_fire_limit".to_string(), serde_json::json!(v));
715            }
716            if let Some(v) = raw_area.snooze_length {
717                area.properties
718                    .insert("snooze_period".to_string(), serde_json::json!(v));
719            }
720
721            // Other properties
722            if let Some(v) = &raw_area.group_id {
723                area.properties
724                    .insert("group_id".to_string(), serde_json::json!(v));
725            }
726            if let Some(v) = &raw_area.sub_group_id {
727                area.properties
728                    .insert("sub_group_id".to_string(), serde_json::json!(v));
729            }
730            // Store neurons_per_voxel in properties HashMap
731            if let Some(v) = raw_area.per_voxel_neuron_cnt {
732                area.properties
733                    .insert("neurons_per_voxel".to_string(), serde_json::json!(v));
734            }
735            if let Some(v) = &raw_area.cortical_mapping_dst {
736                // Convert dstmap keys from old format to base64
737                let converted_dstmap = convert_dstmap_keys_to_base64(v);
738                area.properties
739                    .insert("cortical_mapping_dst".to_string(), converted_dstmap);
740            }
741            if let Some(v) = &raw_area.coordinate_2d {
742                area.properties
743                    .insert("2d_coordinate".to_string(), serde_json::json!(v));
744            }
745
746            // Store any other custom properties
747            for (key, value) in &raw_area.other {
748                area.properties.insert(key.clone(), value.clone());
749            }
750
751            // Note: cortical_type parsing disabled - CorticalArea is now a minimal data structure
752            // CorticalAreaType information is stored in properties["cortical_group"] if needed
753
754            areas.push(area);
755        }
756
757        Ok(areas)
758    }
759
760    /// Parse brain regions
761    fn parse_brain_regions(
762        raw_regions: &HashMap<String, RawBrainRegion>,
763    ) -> EvoResult<Vec<(BrainRegion, Option<String>)>> {
764        let mut regions = Vec::with_capacity(raw_regions.len());
765
766        for (region_id_str, raw_region) in raw_regions.iter() {
767            let title = raw_region
768                .title
769                .clone()
770                .unwrap_or_else(|| region_id_str.clone());
771
772            // Convert string region_id to RegionID (UUID)
773            // For now, try to parse as UUID if it's already a UUID, otherwise generate new one
774            let region_id = match RegionID::from_string(region_id_str) {
775                Ok(id) => id,
776                Err(_) => {
777                    // If not a valid UUID, generate a new one
778                    // This handles legacy string-based region IDs
779                    RegionID::new()
780                }
781            };
782
783            let region_type = RegionType::Undefined; // Default to Undefined
784
785            let mut region = BrainRegion::new(region_id, title, region_type)?;
786
787            // v3 RuntimeGenome sections nest IO under `properties`; merge before list fields.
788            if let Some(props) = &raw_region.properties {
789                for (k, v) in props {
790                    region.add_property(k.clone(), v.clone());
791                }
792            }
793
794            // Add cortical areas to region (using CorticalID directly)
795            if let Some(areas) = &raw_region.areas {
796                for area_id in areas {
797                    // Convert area_id to CorticalID
798                    match string_to_cortical_id(area_id) {
799                        Ok(cortical_id) => {
800                            region.add_area(cortical_id);
801                        }
802                        Err(e) => {
803                            warn!(target: "feagi-evo",
804                                "Failed to convert brain region area ID '{}' to CorticalID: {}. Skipping.",
805                                area_id, e);
806                        }
807                    }
808                }
809            }
810
811            // Store properties in HashMap
812            if let Some(desc) = &raw_region.description {
813                region.add_property("description".to_string(), serde_json::json!(desc));
814            }
815            if let Some(coord_2d) = &raw_region.coordinate_2d {
816                region.add_property("coordinate_2d".to_string(), serde_json::json!(coord_2d));
817            }
818            if let Some(coord_3d) = &raw_region.coordinate_3d {
819                region.add_property("coordinate_3d".to_string(), serde_json::json!(coord_3d));
820            }
821            // Store inputs/outputs as base64 strings
822            if let Some(inputs) = &raw_region.inputs {
823                let input_ids: Vec<String> = inputs
824                    .iter()
825                    .filter_map(|id| match string_to_cortical_id(id) {
826                        Ok(cortical_id) => Some(cortical_id.as_base_64()),
827                        Err(e) => {
828                            warn!(target: "feagi-evo",
829                                    "Failed to convert brain region input ID '{}': {}. Skipping.",
830                                    id, e);
831                            None
832                        }
833                    })
834                    .collect();
835                if !input_ids.is_empty() {
836                    region.add_property("inputs".to_string(), serde_json::json!(input_ids));
837                }
838            }
839            if let Some(outputs) = &raw_region.outputs {
840                let output_ids: Vec<String> = outputs
841                    .iter()
842                    .filter_map(|id| match string_to_cortical_id(id) {
843                        Ok(cortical_id) => Some(cortical_id.as_base_64()),
844                        Err(e) => {
845                            warn!(target: "feagi-evo",
846                                    "Failed to convert brain region output ID '{}': {}. Skipping.",
847                                    id, e);
848                            None
849                        }
850                    })
851                    .collect();
852                if !output_ids.is_empty() {
853                    region.add_property("outputs".to_string(), serde_json::json!(output_ids));
854                }
855            }
856            if let Some(signature) = &raw_region.signature {
857                region.add_property("signature".to_string(), serde_json::json!(signature));
858            }
859
860            if let Some(d) = &raw_region.designated_inputs {
861                let ids: Vec<String> = d
862                    .iter()
863                    .filter_map(|id| match string_to_cortical_id(id) {
864                        Ok(cortical_id) => Some(cortical_id.as_base_64()),
865                        Err(e) => {
866                            warn!(target: "feagi-evo",
867                                "Failed to convert designated_inputs entry '{}': {}. Skipping.",
868                                id, e);
869                            None
870                        }
871                    })
872                    .collect();
873                if !ids.is_empty() {
874                    region.add_property("designated_inputs".to_string(), serde_json::json!(ids));
875                }
876            }
877            if let Some(d) = &raw_region.designated_outputs {
878                let ids: Vec<String> = d
879                    .iter()
880                    .filter_map(|id| match string_to_cortical_id(id) {
881                        Ok(cortical_id) => Some(cortical_id.as_base_64()),
882                        Err(e) => {
883                            warn!(target: "feagi-evo",
884                                "Failed to convert designated_outputs entry '{}': {}. Skipping.",
885                                id, e);
886                            None
887                        }
888                    })
889                    .collect();
890                if !ids.is_empty() {
891                    region.add_property("designated_outputs".to_string(), serde_json::json!(ids));
892                }
893            }
894
895            Self::normalize_brain_region_cortical_id_list_properties(
896                &mut region,
897                &[
898                    "inputs",
899                    "outputs",
900                    "designated_inputs",
901                    "designated_outputs",
902                ],
903            );
904
905            // Store parent_id for hierarchy construction
906            let parent_id = raw_region.parent_region_id.clone();
907            if let Some(ref parent_id_str) = parent_id {
908                // Store as property for serialization
909                region.add_property(
910                    "parent_region_id".to_string(),
911                    serde_json::json!(parent_id_str),
912                );
913            }
914
915            regions.push((region, parent_id));
916        }
917
918        Ok(regions)
919    }
920
921    fn parse_classifiers(
922        raw_classifiers: &HashMap<String, RawClassifier>,
923    ) -> EvoResult<Vec<Classifier>> {
924        let mut classifiers = Vec::with_capacity(raw_classifiers.len());
925        for (classifier_id, raw) in raw_classifiers {
926            let name = raw
927                .name
928                .clone()
929                .filter(|n| !n.trim().is_empty())
930                .ok_or_else(|| {
931                    EvoError::InvalidArea(format!("Classifier '{}' is missing name", classifier_id))
932                })?;
933            let parent_region_id = raw
934                .parent_region_id
935                .clone()
936                .filter(|n| !n.trim().is_empty())
937                .ok_or_else(|| {
938                    EvoError::InvalidArea(format!(
939                        "Classifier '{}' is missing parent_region_id",
940                        classifier_id
941                    ))
942                })?;
943            let coordinates_3d = match &raw.coordinates_3d {
944                Some(coords) if coords.len() == 3 => [coords[0], coords[1], coords[2]],
945                Some(coords) => {
946                    return Err(EvoError::InvalidArea(format!(
947                        "Classifier '{}' coordinates_3d must have 3 values, got {}",
948                        classifier_id,
949                        coords.len()
950                    )))
951                }
952                None => [0, 0, 0],
953            };
954            let sample_memory_id = raw.sample_memory_id.clone().ok_or_else(|| {
955                EvoError::InvalidArea(format!(
956                    "Classifier '{}' is missing sample_memory_id",
957                    classifier_id
958                ))
959            })?;
960            let class_memory_id = raw.class_memory_id.clone().ok_or_else(|| {
961                EvoError::InvalidArea(format!(
962                    "Classifier '{}' is missing class_memory_id",
963                    classifier_id
964                ))
965            })?;
966            let error_area_id = raw.error_area_id.clone().ok_or_else(|| {
967                EvoError::InvalidArea(format!(
968                    "Classifier '{}' is missing error_area_id",
969                    classifier_id
970                ))
971            })?;
972            let sample_area_ids = raw
973                .sample_area_ids
974                .iter()
975                .map(|id| id.trim().to_string())
976                .filter(|id| !id.is_empty())
977                .collect();
978            let class_bindings = raw
979                .class_bindings
980                .iter()
981                .filter(|binding| !binding.class_area_id.trim().is_empty())
982                .cloned()
983                .collect();
984            classifiers.push(Classifier {
985                classifier_id: classifier_id.clone(),
986                name,
987                parent_region_id,
988                coordinates_3d,
989                sample_area_ids,
990                class_bindings,
991                sample_memory_id,
992                class_memory_id,
993                error_area_id,
994                reward_training: raw.reward_training,
995                answer_feedback_area_id: raw.answer_feedback_area_id.clone(),
996                correct_area_id: raw.correct_area_id.clone(),
997                reward_modulator_ids: raw.reward_modulator_ids.clone(),
998                answer_latency_bursts: raw.answer_latency_bursts,
999                learn_area_id: raw.learn_area_id.clone(),
1000                confidence_area_id: raw.confidence_area_id.clone(),
1001                properties: raw.properties.clone().unwrap_or_default(),
1002            });
1003        }
1004        Ok(classifiers)
1005    }
1006}
1007
1008#[cfg(test)]
1009mod tests {
1010    use super::*;
1011
1012    #[test]
1013    fn parse_folds_legacy_areas_into_cortical_areas() {
1014        let json = r#"{
1015            "version": "2.1",
1016            "blueprint": {
1017                "_power": {
1018                    "cortical_name": "Power",
1019                    "block_boundaries": [1, 1, 1],
1020                    "relative_coordinate": [0, 0, 0],
1021                    "cortical_type": "CORE"
1022                },
1023                "_death": {
1024                    "cortical_name": "Death",
1025                    "block_boundaries": [1, 1, 1],
1026                    "relative_coordinate": [0, 0, 0],
1027                    "cortical_type": "CORE"
1028                }
1029            },
1030            "brain_regions": {
1031                "root": {
1032                    "title": "Root",
1033                    "areas": ["_power"],
1034                    "cortical_areas": ["_death"]
1035                }
1036            }
1037        }"#;
1038
1039        let parsed = GenomeParser::parse(json).unwrap();
1040        let (region, _) = &parsed.brain_regions[0];
1041        let ids: Vec<String> = region
1042            .get_all_areas()
1043            .into_iter()
1044            .map(|id| id.as_base_64())
1045            .collect();
1046        assert!(ids.contains(&string_to_cortical_id("_power").unwrap().as_base_64()));
1047        assert!(ids.contains(&string_to_cortical_id("_death").unwrap().as_base_64()));
1048    }
1049
1050    #[test]
1051    fn parse_accepts_cortical_areas_only_and_a_non_array_legacy_key() {
1052        let cortical_only = r#"{
1053            "version": "2.1",
1054            "blueprint": {
1055                "_death": {
1056                    "cortical_name": "Death",
1057                    "block_boundaries": [1, 1, 1],
1058                    "relative_coordinate": [0, 0, 0],
1059                    "cortical_type": "CORE"
1060                }
1061            },
1062            "brain_regions": {
1063                "root": { "title": "Root", "cortical_areas": ["_death"] }
1064            }
1065        }"#;
1066        let parsed = GenomeParser::parse(cortical_only).unwrap();
1067        let (region, _) = &parsed.brain_regions[0];
1068        assert!(region.contains_area(&string_to_cortical_id("_death").unwrap()));
1069
1070        let dropped_legacy = r#"{
1071            "version": "2.1",
1072            "blueprint": {
1073                "_death": {
1074                    "cortical_name": "Death",
1075                    "block_boundaries": [1, 1, 1],
1076                    "relative_coordinate": [0, 0, 0],
1077                    "cortical_type": "CORE"
1078                }
1079            },
1080            "brain_regions": {
1081                "root": {
1082                    "title": "Root",
1083                    "areas": "not-a-list",
1084                    "cortical_areas": ["_death"]
1085                }
1086            }
1087        }"#;
1088        let parsed = GenomeParser::parse(dropped_legacy).unwrap();
1089        let (region, _) = &parsed.brain_regions[0];
1090        assert_eq!(region.area_count(), 1);
1091        assert!(region.contains_area(&string_to_cortical_id("_death").unwrap()));
1092    }
1093
1094    #[test]
1095    fn test_parse_minimal_genome() {
1096        // Test backward compatibility: parsing v2.1 genome with old 6-byte cortical ID
1097        // Parser should convert old format to base64 for storage
1098        let json = r#"{
1099            "version": "2.1",
1100            "blueprint": {
1101                "_power": {
1102                    "cortical_name": "Test Area",
1103                    "block_boundaries": [10, 10, 10],
1104                    "relative_coordinate": [0, 0, 0],
1105                    "cortical_type": "CORE"
1106                }
1107            },
1108            "brain_regions": {
1109                "root": {
1110                    "title": "Root",
1111                    "parent_region_id": null,
1112                    "areas": ["_power"]
1113                }
1114            }
1115        }"#;
1116
1117        let parsed = GenomeParser::parse(json).unwrap();
1118
1119        assert_eq!(parsed.version, "2.1");
1120        assert_eq!(parsed.cortical_areas.len(), 1);
1121        // Input was "_power" (6 bytes), converted to "___power" (8 bytes, padded at start with underscores) then base64 encoded
1122        assert_eq!(
1123            parsed.cortical_areas[0].cortical_id.as_base_64(),
1124            "X19fcG93ZXI="
1125        );
1126        assert_eq!(parsed.cortical_areas[0].name, "Test Area");
1127        assert_eq!(parsed.brain_regions.len(), 1);
1128
1129        // Phase 2: Verify cortical_type_new is populated
1130        // Note: cortical_type_new field removed - type is encoded in cortical_id
1131        assert!(parsed.cortical_areas[0]
1132            .cortical_id
1133            .as_cortical_type()
1134            .is_ok());
1135    }
1136
1137    #[test]
1138    fn test_parse_multiple_areas() {
1139        // Test parsing multiple cortical areas with old format IDs
1140        let json = r#"{
1141            "version": "2.1",
1142            "blueprint": {
1143                "_power": {
1144                    "cortical_name": "Area 1",
1145                    "cortical_type": "CORE",
1146                    "block_boundaries": [5, 5, 5],
1147                    "relative_coordinate": [0, 0, 0]
1148                },
1149                "_death": {
1150                    "cortical_name": "Area 2",
1151                    "cortical_type": "CORE",
1152                    "block_boundaries": [10, 10, 10],
1153                    "relative_coordinate": [5, 0, 0]
1154                }
1155            }
1156        }"#;
1157
1158        let parsed = GenomeParser::parse(json).unwrap();
1159        assert!(parsed.classifiers.is_empty());
1160
1161        assert_eq!(parsed.cortical_areas.len(), 2);
1162
1163        // Phase 2: Verify both areas have cortical_type_new populated
1164        for area in &parsed.cortical_areas {
1165            assert!(
1166                area.cortical_id.as_cortical_type().is_ok(),
1167                "Area {} should have cortical_type_new populated",
1168                area.cortical_id
1169            );
1170        }
1171    }
1172
1173    #[test]
1174    fn test_string_to_cortical_id_legacy_power_shorthand() {
1175        // Older FEAGI genomes may encode the power core area as "___pwr" (6-char shorthand).
1176        // Migration must map this deterministically to the core Power cortical ID.
1177        use feagi_structures::genomic::cortical_area::CoreCorticalType;
1178        let id = string_to_cortical_id("___pwr").unwrap();
1179        assert_eq!(
1180            id.as_base_64(),
1181            CoreCorticalType::Power.to_cortical_id().as_base_64()
1182        );
1183    }
1184
1185    #[test]
1186    fn test_parse_raw_imu_magnetometer_wire_id() {
1187        // Embodiment-registered Raw IMU magnetometer (subunit 2) from live FEAGI.
1188        // Connectome auto-save must be able to rehydrate this into a runtime genome.
1189        let json = r#"{
1190            "version": "3.0",
1191            "blueprint": {
1192                "aXJpbScAAgA=": {
1193                    "cortical_name": "feagi_body_imu__Abdomen-2",
1194                    "block_boundaries": [3, 1, 10],
1195                    "relative_coordinate": [90, 0, -10],
1196                    "cortical_type": "IPU"
1197                }
1198            },
1199            "brain_regions": {}
1200        }"#;
1201
1202        let parsed = GenomeParser::parse(json).expect("Raw IMU magnetometer genome");
1203        assert_eq!(parsed.cortical_areas.len(), 1);
1204        assert_eq!(
1205            parsed.cortical_areas[0].cortical_id.as_base_64(),
1206            "aXJpbScAAgA="
1207        );
1208        parsed.cortical_areas[0]
1209            .cortical_id
1210            .as_cortical_type()
1211            .expect("magnetometer IO flag must decode");
1212    }
1213
1214    #[test]
1215    fn test_parse_positional_servo_speed_wire_id() {
1216        // Embodiment-registered Positional Servo Speed (subunit 2) from live FEAGI.
1217        // Connectome auto-save must be able to rehydrate this into a runtime genome.
1218        let json = r#"{
1219            "version": "3.0",
1220            "blueprint": {
1221                "b3BzZSEAAAA=": {
1222                    "cortical_name": "Positional Servo Speed",
1223                    "block_boundaries": [6, 1, 20],
1224                    "relative_coordinate": [-58, 0, -10],
1225                    "cortical_type": "OPU"
1226                }
1227            },
1228            "brain_regions": {}
1229        }"#;
1230
1231        let parsed = GenomeParser::parse(json).expect("Positional Servo Speed genome");
1232        assert_eq!(parsed.cortical_areas.len(), 1);
1233        assert_eq!(
1234            parsed.cortical_areas[0].cortical_id.as_base_64(),
1235            "b3BzZSEAAAA="
1236        );
1237        parsed.cortical_areas[0]
1238            .cortical_id
1239            .as_cortical_type()
1240            .expect("positional servo speed IO flag must decode");
1241    }
1242
1243    #[test]
1244    fn test_string_to_cortical_id_legacy_power_padded() {
1245        // 8-char padded form ___pwr__ (from 6-char padding in legacy flat genomes).
1246        use feagi_structures::genomic::cortical_area::CoreCorticalType;
1247        let id = string_to_cortical_id("___pwr__").unwrap();
1248        assert_eq!(
1249            id.as_base_64(),
1250            CoreCorticalType::Power.to_cortical_id().as_base_64()
1251        );
1252    }
1253
1254    #[test]
1255    fn test_parse_with_properties() {
1256        let json = r#"{
1257            "version": "2.1",
1258            "blueprint": {
1259                "mem001": {
1260                    "cortical_name": "Memory Area",
1261                    "block_boundaries": [8, 8, 8],
1262                    "relative_coordinate": [0, 0, 0],
1263                    "cortical_type": "MEMORY",
1264                    "is_mem_type": true,
1265                    "firing_threshold": 50.0,
1266                    "leak_coefficient": 0.9
1267                }
1268            }
1269        }"#;
1270
1271        let parsed = GenomeParser::parse(json).unwrap();
1272
1273        assert_eq!(parsed.cortical_areas.len(), 1);
1274        let area = &parsed.cortical_areas[0];
1275
1276        // Old type system (deprecated)
1277        use feagi_structures::genomic::cortical_area::CorticalAreaType;
1278        assert!(matches!(area.cortical_type, CorticalAreaType::Memory(_)));
1279
1280        // Properties stored correctly
1281        assert!(area.properties.contains_key("is_mem_type"));
1282        assert!(area.properties.contains_key("firing_threshold"));
1283        assert!(area.properties.contains_key("cortical_group"));
1284
1285        // NEW: cortical_type should be derivable from cortical_id (Phase 2)
1286        assert!(
1287            area.cortical_id.as_cortical_type().is_ok(),
1288            "cortical_id should be parseable to cortical_type"
1289        );
1290        if let Ok(cortical_type) = area.cortical_id.as_cortical_type() {
1291            use feagi_structures::genomic::cortical_area::CorticalAreaType;
1292            assert!(
1293                matches!(cortical_type, CorticalAreaType::Memory(_)),
1294                "Should be classified as MEMORY type"
1295            );
1296        }
1297    }
1298
1299    /// v3 save embeds IO lists under `properties`; loading must preserve designated_inputs for BV presets.
1300    #[test]
1301    fn test_parse_v3_brain_region_nested_properties_retains_designated_io() {
1302        let json = r#"{
1303            "version": "3.0",
1304            "blueprint": {
1305                "_power": {
1306                    "cortical_name": "Core",
1307                    "block_boundaries": [10, 10, 10],
1308                    "relative_coordinate": [0, 0, 0],
1309                    "cortical_type": "CORE"
1310                }
1311            },
1312            "brain_regions": {
1313                "550e8400-e29b-41d4-a716-446655440000": {
1314                    "name": "Sub",
1315                    "cortical_areas": ["_power"],
1316                    "properties": {
1317                        "designated_inputs": ["_power"],
1318                        "designated_outputs": []
1319                    }
1320                }
1321            }
1322        }"#;
1323
1324        let parsed = GenomeParser::parse(json).unwrap();
1325        assert_eq!(parsed.brain_regions.len(), 1);
1326        let (region, _) = &parsed.brain_regions[0];
1327        let di = region
1328            .get_property("designated_inputs")
1329            .and_then(|v| v.as_array())
1330            .expect("designated_inputs");
1331        assert_eq!(di.len(), 1);
1332        assert_eq!(di[0].as_str().unwrap(), "X19fcG93ZXI=");
1333    }
1334
1335    #[test]
1336    fn test_parse_brain_region_plain_text_description() {
1337        let json = r#"{
1338            "version": "2.1",
1339            "blueprint": {
1340                "_power": {
1341                    "cortical_name": "Core",
1342                    "block_boundaries": [10, 10, 10],
1343                    "relative_coordinate": [0, 0, 0],
1344                    "cortical_type": "CORE"
1345                }
1346            },
1347            "brain_regions": {
1348                "root": {
1349                    "title": "Root",
1350                    "description": "Holds core physiology and embodiment IO",
1351                    "parent_region_id": null,
1352                    "areas": ["_power"]
1353                }
1354            }
1355        }"#;
1356
1357        let parsed = GenomeParser::parse(json).unwrap();
1358        assert_eq!(parsed.brain_regions.len(), 1);
1359        let (region, _) = &parsed.brain_regions[0];
1360        assert_eq!(
1361            region.get_property("description"),
1362            Some(&serde_json::json!(
1363                "Holds core physiology and embodiment IO"
1364            ))
1365        );
1366    }
1367
1368    #[test]
1369    fn test_invalid_version() {
1370        let json = r#"{
1371            "version": "1.0",
1372            "blueprint": {}
1373        }"#;
1374
1375        let result = GenomeParser::parse(json);
1376        assert!(result.is_err());
1377    }
1378
1379    #[test]
1380    fn test_malformed_json() {
1381        let json = r#"{ "version": "2.1", "blueprint": { malformed"#;
1382
1383        let result = GenomeParser::parse(json);
1384        assert!(result.is_err());
1385    }
1386
1387    #[test]
1388    fn test_cortical_type_new_population() {
1389        // Test that cortical_type_new field is populated during parsing (Phase 2)
1390        // This tests that parsing works with valid cortical IDs and populates types correctly
1391        use feagi_structures::genomic::cortical_area::CoreCorticalType;
1392        let power_id = CoreCorticalType::Power.to_cortical_id().as_base_64();
1393        let json = format!(
1394            r#"{{
1395            "version": "2.1",
1396            "blueprint": {{
1397                "cvision1": {{
1398                    "cortical_name": "Test Custom Vision",
1399                    "cortical_type": "CUSTOM",
1400                    "block_boundaries": [10, 10, 1],
1401                    "relative_coordinate": [0, 0, 0]
1402                }},
1403                "cmotor01": {{
1404                    "cortical_name": "Test Custom Motor",
1405                    "cortical_type": "CUSTOM",
1406                    "block_boundaries": [5, 5, 1],
1407                    "relative_coordinate": [0, 0, 0]
1408                }},
1409                "{}": {{
1410                    "cortical_name": "Test Core",
1411                    "cortical_type": "CORE",
1412                    "block_boundaries": [1, 1, 1],
1413                    "relative_coordinate": [0, 0, 0]
1414                }}
1415            }}
1416        }}"#,
1417            power_id
1418        );
1419
1420        let parsed = GenomeParser::parse(&json).unwrap();
1421        assert_eq!(parsed.cortical_areas.len(), 3);
1422
1423        // Verify all areas have cortical_type_new populated
1424        for area in &parsed.cortical_areas {
1425            assert!(
1426                area.cortical_id.as_cortical_type().is_ok(),
1427                "Area {} should have cortical_type_new populated",
1428                area.cortical_id
1429            );
1430
1431            // Verify cortical_group property is also set
1432            assert!(
1433                area.properties.contains_key("cortical_group"),
1434                "Area {} should have cortical_group property",
1435                area.cortical_id
1436            );
1437
1438            // Verify cortical group is consistent (avoid depending on feagi-brain-development)
1439            if let Some(prop_group) = area
1440                .properties
1441                .get("cortical_group")
1442                .and_then(|v| v.as_str())
1443            {
1444                assert!(
1445                    !prop_group.is_empty(),
1446                    "Area {} should have non-empty cortical_group property",
1447                    area.cortical_id.as_base_64()
1448                );
1449            }
1450        }
1451    }
1452
1453    #[test]
1454    fn test_parse_classifiers_key_parallel_to_regions() {
1455        let json = r#"{
1456            "version": "3.0",
1457            "blueprint": {
1458                "csample": {
1459                    "cortical_name": "Sample",
1460                    "cortical_type": "CUSTOM",
1461                    "block_boundaries": [4, 4, 1],
1462                    "relative_coordinate": [0, 0, 0]
1463                },
1464                "msmem1": {
1465                    "cortical_name": "SampleMem",
1466                    "cortical_type": "MEMORY",
1467                    "block_boundaries": [1, 1, 1],
1468                    "relative_coordinate": [10, 0, 0]
1469                },
1470                "mcmem1": {
1471                    "cortical_name": "ClassMem",
1472                    "cortical_type": "MEMORY",
1473                    "block_boundaries": [1, 1, 1],
1474                    "relative_coordinate": [20, 0, 0]
1475                },
1476                "cout1": {
1477                    "cortical_name": "ClassOutput",
1478                    "cortical_type": "CUSTOM",
1479                    "block_boundaries": [1, 1, 4],
1480                    "relative_coordinate": [30, 0, 0]
1481                },
1482                "cerr1": {
1483                    "cortical_name": "Error",
1484                    "cortical_type": "CUSTOM",
1485                    "block_boundaries": [1, 1, 1],
1486                    "relative_coordinate": [40, 0, 0]
1487                }
1488            },
1489            "brain_regions": {
1490                "root": {
1491                    "title": "root",
1492                    "parent_region_id": "",
1493                    "coordinate_2d": [0, 0],
1494                    "coordinate_3d": [0, 0, 0],
1495                    "areas": ["csample", "msmem1", "mcmem1", "cout1", "cerr1"],
1496                    "regions": [],
1497                    "inputs": [],
1498                    "outputs": []
1499                }
1500            },
1501            "classifiers": {
1502                "clf-1": {
1503                    "name": "object_class",
1504                    "parent_region_id": "root",
1505                    "coordinates_3d": [30, 0, 0],
1506                    "sample_area_ids": ["csample"],
1507                    "class_bindings": [{
1508                        "class_area_id": "cclass",
1509                        "class_output_area_id": "cout1"
1510                    }],
1511                    "sample_memory_id": "msmem1",
1512                    "class_memory_id": "mcmem1",
1513                    "error_area_id": "cerr1"
1514                }
1515            }
1516        }"#;
1517
1518        let parsed = GenomeParser::parse(json).expect("classifier genome");
1519        assert_eq!(parsed.classifiers.len(), 1);
1520        let classifier = &parsed.classifiers[0];
1521        assert_eq!(classifier.classifier_id, "clf-1");
1522        assert_eq!(classifier.name, "object_class");
1523        assert_eq!(classifier.sample_memory_id, "msmem1");
1524        assert_eq!(classifier.class_memory_id, "mcmem1");
1525        assert_eq!(classifier.error_area_id, "cerr1");
1526        assert_eq!(classifier.sample_area_ids, vec!["csample".to_string()]);
1527        assert_eq!(classifier.class_bindings.len(), 1);
1528        assert_eq!(classifier.class_bindings[0].class_output_area_id, "cout1");
1529        assert!(classifier.owned_area_ids().contains(&"cerr1".to_string()));
1530        assert!(classifier.owned_area_ids().contains(&"cout1".to_string()));
1531    }
1532
1533    #[test]
1534    fn test_parse_classifier_without_error_area_is_rejected() {
1535        let json = r#"{
1536            "version": "3.0",
1537            "blueprint": {},
1538            "brain_regions": {},
1539            "classifiers": {
1540                "clf-1": {
1541                    "name": "object_class",
1542                    "parent_region_id": "root",
1543                    "sample_memory_id": "msmem1",
1544                    "class_memory_id": "mcmem1"
1545                }
1546            }
1547        }"#;
1548        let error = GenomeParser::parse(json).expect_err("error_area_id is required");
1549        assert!(error.to_string().contains("error_area_id"), "{error}");
1550    }
1551}