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