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