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