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