1use serde::{Deserialize, Serialize};
44use serde_json::Value;
45use std::collections::HashMap;
46use tracing::warn;
47
48use crate::types::{EvoError, EvoResult};
49use feagi_structures::genomic::brain_regions::RegionID;
50use feagi_structures::genomic::classifiers::Classifier;
51use feagi_structures::genomic::cortical_area::CorticalID;
52use feagi_structures::genomic::cortical_area::{
53 CorticalArea, CorticalAreaDimensions as Dimensions,
54};
55use feagi_structures::genomic::descriptors::GenomeCoordinate3D;
56use feagi_structures::genomic::{BrainRegion, RegionType};
57
58#[derive(Debug, Clone)]
60pub struct ParsedGenome {
61 pub genome_id: String,
63 pub genome_title: String,
64 pub version: String,
65
66 pub cortical_areas: Vec<CorticalArea>,
68
69 pub brain_regions: Vec<(BrainRegion, Option<String>)>, pub classifiers: Vec<Classifier>,
74
75 pub neuron_morphologies: HashMap<String, Value>,
77
78 pub modulators: HashMap<String, Value>,
80
81 pub physiology: Option<Value>,
83
84 pub change_history: Vec<Value>,
86}
87
88#[derive(Debug, Clone, Deserialize, Serialize)]
90pub struct RawGenome {
91 pub genome_id: Option<String>,
92 pub genome_title: Option<String>,
93 pub genome_description: Option<String>,
94 pub version: String,
95 #[serde(default, skip_serializing_if = "Option::is_none")]
100 pub genome_schema_version: Option<u32>,
101 pub blueprint: HashMap<String, RawCorticalArea>,
102 #[serde(default)]
103 pub brain_regions: HashMap<String, RawBrainRegion>,
104 #[serde(default)]
105 pub classifiers: HashMap<String, RawClassifier>,
106 #[serde(default)]
107 pub neuron_morphologies: HashMap<String, Value>,
108 #[serde(default)]
109 pub modulators: HashMap<String, Value>,
110 #[serde(default)]
111 pub physiology: Option<Value>,
112 #[serde(default, skip_serializing_if = "Option::is_none")]
114 pub brain_regions_root: Option<String>,
115 #[serde(default, skip_serializing_if = "Vec::is_empty")]
117 pub change_history: Vec<Value>,
118}
119
120#[derive(Debug, Clone, Deserialize, Serialize)]
122pub struct RawCorticalArea {
123 pub cortical_name: Option<String>,
124 pub block_boundaries: Option<Vec<u32>>,
125 pub relative_coordinate: Option<Vec<i32>>,
126 pub cortical_type: Option<String>,
127
128 pub group_id: Option<String>,
130 pub sub_group_id: Option<String>,
131 pub per_voxel_neuron_cnt: Option<u32>,
132 pub cortical_mapping_dst: Option<Value>,
133
134 pub synapse_attractivity: Option<f32>,
136 pub refractory_period: Option<u32>,
137 pub firing_threshold: Option<f32>,
138 pub firing_threshold_limit: Option<f32>,
139 pub firing_threshold_increment_x: Option<f32>,
140 pub firing_threshold_increment_y: Option<f32>,
141 pub firing_threshold_increment_z: Option<f32>,
142 pub leak_coefficient: Option<f32>,
143 pub leak_variability: Option<f32>,
144 pub neuron_excitability: Option<f32>,
145 pub postsynaptic_current: Option<f32>,
146 pub postsynaptic_current_max: Option<f32>,
147 pub degeneration: Option<f32>,
148 pub psp_uniform_distribution: Option<bool>,
149 pub mp_charge_accumulation: Option<bool>,
150 pub mp_driven_psp: Option<bool>,
151 pub visualization: Option<bool>,
152 pub burst_engine_activation: Option<bool>,
153 #[serde(rename = "2d_coordinate")]
154 pub coordinate_2d: Option<Vec<i32>>,
155
156 pub is_mem_type: Option<bool>,
158 pub longterm_mem_threshold: Option<u32>,
159 pub lifespan_growth_rate: Option<f32>,
160 pub init_lifespan: Option<u32>,
161 pub temporal_depth: Option<u32>,
162 pub mp_learning_enabled: Option<bool>,
163 pub mp_change_mode: Option<String>,
164 pub mp_delta_quantization: Option<f32>,
165 pub mp_ratio_quantization: Option<f32>,
166 pub min_window_activity: Option<u32>,
167 pub scan_skip_density: Option<f32>,
168 pub consecutive_fire_cnt_max: Option<u32>,
169 pub snooze_length: Option<u32>,
170
171 #[serde(flatten)]
173 pub other: HashMap<String, Value>,
174}
175
176#[derive(Debug, Clone, Deserialize, Serialize)]
178pub struct RawBrainRegion {
179 #[serde(alias = "name")]
180 pub title: Option<String>,
181 pub description: Option<String>,
182 pub parent_region_id: Option<String>,
183 pub coordinate_2d: Option<Vec<i32>>,
184 pub coordinate_3d: Option<Vec<i32>>,
185 #[serde(alias = "cortical_areas")]
186 pub areas: Option<Vec<String>>,
187 pub regions: Option<Vec<String>>,
188 pub inputs: Option<Vec<String>>,
189 pub outputs: Option<Vec<String>>,
190 pub designated_inputs: Option<Vec<String>>,
192 pub designated_outputs: Option<Vec<String>>,
193 pub signature: Option<String>,
194 pub properties: Option<HashMap<String, Value>>,
196}
197
198#[derive(Debug, Clone, Deserialize, Serialize)]
200pub struct RawClassifier {
201 #[serde(alias = "title")]
202 pub name: Option<String>,
203 pub parent_region_id: Option<String>,
204 #[serde(alias = "coordinate_3d")]
205 pub coordinates_3d: Option<Vec<i32>>,
206 #[serde(default)]
207 pub sample_area_ids: Vec<String>,
208 #[serde(default)]
209 pub class_bindings: Vec<feagi_structures::genomic::classifiers::ClassifierClassBinding>,
210 pub sample_memory_id: Option<String>,
211 pub class_memory_id: Option<String>,
212 pub error_area_id: Option<String>,
213 #[serde(default)]
214 pub reward_training: bool,
215 #[serde(default)]
216 pub answer_feedback_area_id: Option<String>,
217 #[serde(default)]
218 pub pain_area_id: Option<String>,
219 #[serde(default)]
220 pub pleasure_area_id: Option<String>,
221 #[serde(default)]
222 pub answer_latency_bursts: u32,
223 #[serde(default)]
224 pub learn_area_id: Option<String>,
225 #[serde(default)]
226 pub confidence_area_id: Option<String>,
227 pub properties: Option<HashMap<String, Value>>,
228}
229
230fn convert_dstmap_keys_to_base64(dstmap: &Value) -> Value {
234 if let Some(dstmap_obj) = dstmap.as_object() {
235 let mut converted = serde_json::Map::new();
236
237 for (dest_id_str, mapping_value) in dstmap_obj {
238 match string_to_cortical_id(dest_id_str) {
240 Ok(dest_cortical_id) => {
241 converted.insert(dest_cortical_id.as_base_64(), mapping_value.clone());
242 }
243 Err(e) => {
244 tracing::warn!(
246 "Failed to convert dstmap key '{}' to base64: {}, keeping original",
247 dest_id_str,
248 e
249 );
250 converted.insert(dest_id_str.clone(), mapping_value.clone());
251 }
252 }
253 }
254
255 Value::Object(converted)
256 } else {
257 dstmap.clone()
259 }
260}
261
262pub fn string_to_cortical_id(id_str: &str) -> EvoResult<CorticalID> {
266 use feagi_structures::genomic::cortical_area::CoreCorticalType;
267
268 if let Ok(cortical_id) = CorticalID::try_from_base_64(id_str) {
270 let mut bytes = [0u8; CorticalID::CORTICAL_ID_LENGTH];
271 cortical_id.write_id_to_bytes(&mut bytes);
272 if bytes == *b"___power" {
273 return Ok(CoreCorticalType::Power.to_cortical_id());
274 }
275 if bytes == *b"___death" {
276 return Ok(CoreCorticalType::Death.to_cortical_id());
277 }
278 if bytes == *b"___fatig" {
279 return Ok(CoreCorticalType::Fatigue.to_cortical_id());
280 }
281 if bytes == *b"___pain_" {
282 return Ok(CoreCorticalType::Pain.to_cortical_id());
283 }
284 if bytes == *b"___pleas" {
285 return Ok(CoreCorticalType::Pleasure.to_cortical_id());
286 }
287 if bytes == *b"___fear_" {
288 return Ok(CoreCorticalType::Fear.to_cortical_id());
289 }
290 if bytes == *b"___hope_" {
291 return Ok(CoreCorticalType::Hope.to_cortical_id());
292 }
293 return Ok(cortical_id);
294 }
295
296 if id_str == "_power" {
298 return Ok(CoreCorticalType::Power.to_cortical_id());
299 }
300 if id_str == "___pwr" {
302 return Ok(CoreCorticalType::Power.to_cortical_id());
303 }
304 if id_str == "___power" {
306 return Ok(CoreCorticalType::Power.to_cortical_id());
307 }
308 if id_str == "___pwr__" {
310 return Ok(CoreCorticalType::Power.to_cortical_id());
311 }
312 if id_str == "___death" {
313 return Ok(CoreCorticalType::Death.to_cortical_id());
314 }
315 if id_str == "___fatig" {
316 return Ok(CoreCorticalType::Fatigue.to_cortical_id());
317 }
318 if id_str == "___pain_" {
319 return Ok(CoreCorticalType::Pain.to_cortical_id());
320 }
321 if id_str == "___pleas" {
322 return Ok(CoreCorticalType::Pleasure.to_cortical_id());
323 }
324 if id_str == "___fear_" {
325 return Ok(CoreCorticalType::Fear.to_cortical_id());
326 }
327 if id_str == "___hope_" {
328 return Ok(CoreCorticalType::Hope.to_cortical_id());
329 }
330 if id_str == "_death" {
331 return Ok(CoreCorticalType::Death.to_cortical_id());
332 }
333 if id_str == "_fatigue" {
334 return Ok(CoreCorticalType::Fatigue.to_cortical_id());
335 }
336 if id_str == "_pain" {
337 return Ok(CoreCorticalType::Pain.to_cortical_id());
338 }
339 if id_str == "_pleasure" {
340 return Ok(CoreCorticalType::Pleasure.to_cortical_id());
341 }
342 if id_str == "_fear" {
343 return Ok(CoreCorticalType::Fear.to_cortical_id());
344 }
345 if id_str == "_hope" {
346 return Ok(CoreCorticalType::Hope.to_cortical_id());
347 }
348
349 if id_str.len() == 6 || id_str.len() == 8 {
351 CorticalID::try_from_legacy_ascii(id_str).map_err(|e| {
352 EvoError::InvalidArea(format!("Failed to convert cortical_id '{}': {}", id_str, e))
353 })
354 } else {
355 Err(EvoError::InvalidArea(format!(
356 "Invalid cortical_id length: '{}' (expected 6 or 8 ASCII chars, or base64)",
357 id_str
358 )))
359 }
360}
361
362pub struct GenomeParser;
364
365impl GenomeParser {
366 fn normalize_brain_region_cortical_id_list_properties(region: &mut BrainRegion, keys: &[&str]) {
368 for key in keys {
369 let Some(val) = region.get_property(key) else {
370 continue;
371 };
372 let Some(arr) = val.as_array() else {
373 continue;
374 };
375 let mut out: Vec<String> = Vec::new();
376 for item in arr {
377 let Some(s) = item.as_str() else {
378 continue;
379 };
380 match string_to_cortical_id(s) {
381 Ok(cortical_id) => out.push(cortical_id.as_base_64()),
382 Err(e) => {
383 warn!(target: "feagi-evo",
384 "Failed to convert brain region '{}' entry '{}': {}. Skipping.",
385 key, s, e);
386 }
387 }
388 }
389 if out.is_empty() {
390 region.properties.remove(*key);
391 } else {
392 region.add_property((*key).to_string(), serde_json::json!(out));
393 }
394 }
395 }
396
397 pub fn parse(json_str: &str) -> EvoResult<ParsedGenome> {
415 let raw: RawGenome = serde_json::from_str(json_str)
417 .map_err(|e| EvoError::InvalidGenome(format!("Failed to parse JSON: {}", e)))?;
418
419 if !raw.version.starts_with("2.") && !raw.version.starts_with("3.") && raw.version != "3" {
421 return Err(EvoError::InvalidGenome(format!(
422 "Unsupported genome version: {}. Expected 2.x or 3.x",
423 raw.version
424 )));
425 }
426
427 let cortical_areas = Self::parse_cortical_areas(&raw.blueprint)?;
429
430 let brain_regions = Self::parse_brain_regions(&raw.brain_regions)?;
432 let classifiers = Self::parse_classifiers(&raw.classifiers)?;
433
434 Ok(ParsedGenome {
435 genome_id: raw.genome_id.unwrap_or_else(|| "unknown".to_string()),
436 genome_title: raw.genome_title.unwrap_or_else(|| "Untitled".to_string()),
437 version: raw.version,
438 cortical_areas,
439 brain_regions,
440 classifiers,
441 neuron_morphologies: raw.neuron_morphologies,
442 modulators: raw.modulators,
443 physiology: raw.physiology,
444 change_history: raw.change_history,
445 })
446 }
447
448 fn parse_cortical_areas(
450 blueprint: &HashMap<String, RawCorticalArea>,
451 ) -> EvoResult<Vec<CorticalArea>> {
452 let mut areas = Vec::with_capacity(blueprint.len());
453
454 for (cortical_id_str, raw_area) in blueprint.iter() {
455 if cortical_id_str.is_empty() {
457 warn!(target: "feagi-evo","Skipping empty cortical_id");
458 continue;
459 }
460
461 let cortical_id = match string_to_cortical_id(cortical_id_str) {
463 Ok(id) => id,
464 Err(e) => {
465 warn!(target: "feagi-evo","Skipping invalid cortical_id '{}': {}", cortical_id_str, e);
466 continue;
467 }
468 };
469
470 let name = raw_area
472 .cortical_name
473 .clone()
474 .unwrap_or_else(|| cortical_id_str.clone());
475
476 let dimensions = if let Some(boundaries) = &raw_area.block_boundaries {
477 if boundaries.len() != 3 {
478 return Err(EvoError::InvalidArea(format!(
479 "Invalid block_boundaries for {}: expected 3 values, got {}",
480 cortical_id_str,
481 boundaries.len()
482 )));
483 }
484 Dimensions::new(boundaries[0], boundaries[1], boundaries[2])
485 .map_err(|e| EvoError::InvalidArea(format!("Invalid dimensions: {}", e)))?
486 } else {
487 warn!(target: "feagi-evo","Cortical area {} missing block_boundaries, defaulting to 1x1x1", cortical_id_str);
489 Dimensions::new(1, 1, 1).map_err(|e| {
490 EvoError::InvalidArea(format!("Invalid default dimensions: {}", e))
491 })?
492 };
493
494 let position = if let Some(coords) = &raw_area.relative_coordinate {
495 if coords.len() != 3 {
496 return Err(EvoError::InvalidArea(format!(
497 "Invalid relative_coordinate for {}: expected 3 values, got {}",
498 cortical_id_str,
499 coords.len()
500 )));
501 }
502 GenomeCoordinate3D::new(coords[0], coords[1], coords[2])
503 } else {
504 warn!(target: "feagi-evo","Cortical area {} missing relative_coordinate, defaulting to (0,0,0)", cortical_id_str);
506 GenomeCoordinate3D::new(0, 0, 0)
507 };
508
509 let cortical_type = cortical_id.as_cortical_type().map_err(|e| {
511 EvoError::InvalidArea(format!(
512 "Failed to determine cortical type from ID {}: {}",
513 cortical_id_str, e
514 ))
515 })?;
516
517 let mut area = CorticalArea::new(
519 cortical_id,
520 0, name,
522 dimensions,
523 position,
524 cortical_type,
525 )?;
526
527 if let Some(ref cortical_type_str) = raw_area.cortical_type {
529 area.properties.insert(
530 "cortical_group".to_string(),
531 serde_json::json!(cortical_type_str),
532 );
533 }
534
535 if let Some(v) = raw_area.synapse_attractivity {
538 area.properties
539 .insert("synapse_attractivity".to_string(), serde_json::json!(v));
540 }
541 if let Some(v) = raw_area.refractory_period {
542 area.properties
543 .insert("refractory_period".to_string(), serde_json::json!(v));
544 }
545 if let Some(v) = raw_area.firing_threshold {
546 area.properties
547 .insert("firing_threshold".to_string(), serde_json::json!(v));
548 }
549 if let Some(v) = raw_area.firing_threshold_limit {
550 area.properties
551 .insert("firing_threshold_limit".to_string(), serde_json::json!(v));
552 }
553 if let Some(v) = raw_area.firing_threshold_increment_x {
554 area.properties.insert(
555 "firing_threshold_increment_x".to_string(),
556 serde_json::json!(v),
557 );
558 }
559 if let Some(v) = raw_area.firing_threshold_increment_y {
560 area.properties.insert(
561 "firing_threshold_increment_y".to_string(),
562 serde_json::json!(v),
563 );
564 }
565 if let Some(v) = raw_area.firing_threshold_increment_z {
566 area.properties.insert(
567 "firing_threshold_increment_z".to_string(),
568 serde_json::json!(v),
569 );
570 }
571 if let Some(v) = raw_area.leak_coefficient {
572 area.properties
573 .insert("leak_coefficient".to_string(), serde_json::json!(v));
574 }
575 if let Some(v) = raw_area.leak_variability {
576 area.properties
577 .insert("leak_variability".to_string(), serde_json::json!(v));
578 }
579 if let Some(v) = raw_area.neuron_excitability {
580 area.properties
581 .insert("neuron_excitability".to_string(), serde_json::json!(v));
582 }
583 if let Some(v) = raw_area.postsynaptic_current {
584 area.properties
585 .insert("postsynaptic_current".to_string(), serde_json::json!(v));
586 }
587 if let Some(v) = raw_area.postsynaptic_current_max {
588 area.properties
589 .insert("postsynaptic_current_max".to_string(), serde_json::json!(v));
590 }
591 if let Some(v) = raw_area.degeneration {
592 area.properties
593 .insert("degeneration".to_string(), serde_json::json!(v));
594 }
595
596 if let Some(v) = raw_area.psp_uniform_distribution {
598 area.properties
599 .insert("psp_uniform_distribution".to_string(), serde_json::json!(v));
600 }
601 if let Some(v) = raw_area.mp_charge_accumulation {
602 area.properties
603 .insert("mp_charge_accumulation".to_string(), serde_json::json!(v));
604 }
605 if let Some(v) = raw_area.mp_driven_psp {
606 area.properties
607 .insert("mp_driven_psp".to_string(), serde_json::json!(v));
608 tracing::info!(
609 target: "feagi-evo",
610 "[GENOME-LOAD] Loaded mp_driven_psp={} for area {}",
611 v,
612 cortical_id_str
613 );
614 } else {
615 tracing::debug!(
616 target: "feagi-evo",
617 "[GENOME-LOAD] mp_driven_psp not found in raw_area for {}, will use default=false",
618 cortical_id_str
619 );
620 }
621 if let Some(v) = raw_area.visualization {
622 area.properties
623 .insert("visualization".to_string(), serde_json::json!(v));
624 area.properties
626 .insert("visible".to_string(), serde_json::json!(v));
627 }
628 if let Some(v) = raw_area.burst_engine_activation {
629 area.properties
630 .insert("burst_engine_active".to_string(), serde_json::json!(v));
631 }
632 if let Some(v) = raw_area.is_mem_type {
633 area.properties
634 .insert("is_mem_type".to_string(), serde_json::json!(v));
635 }
636
637 if let Some(v) = raw_area.longterm_mem_threshold {
639 area.properties
640 .insert("longterm_mem_threshold".to_string(), serde_json::json!(v));
641 }
642 if let Some(v) = raw_area.lifespan_growth_rate {
643 area.properties
644 .insert("lifespan_growth_rate".to_string(), serde_json::json!(v));
645 }
646 if let Some(v) = raw_area.init_lifespan {
647 area.properties
648 .insert("init_lifespan".to_string(), serde_json::json!(v));
649 }
650 if let Some(v) = raw_area.temporal_depth {
651 area.properties
652 .insert("temporal_depth".to_string(), serde_json::json!(v));
653 }
654 if let Some(v) = raw_area.mp_learning_enabled {
655 area.properties
656 .insert("mp_learning_enabled".to_string(), serde_json::json!(v));
657 }
658 if let Some(v) = &raw_area.mp_change_mode {
659 area.properties
660 .insert("mp_change_mode".to_string(), serde_json::json!(v));
661 }
662 if let Some(v) = raw_area.mp_delta_quantization {
663 area.properties
664 .insert("mp_delta_quantization".to_string(), serde_json::json!(v));
665 }
666 if let Some(v) = raw_area.mp_ratio_quantization {
667 area.properties
668 .insert("mp_ratio_quantization".to_string(), serde_json::json!(v));
669 }
670 if let Some(v) = raw_area.min_window_activity {
671 area.properties
672 .insert("min_window_activity".to_string(), serde_json::json!(v));
673 }
674 if let Some(v) = raw_area.scan_skip_density {
675 area.properties
676 .insert("scan_skip_density".to_string(), serde_json::json!(v));
677 }
678 if let Some(v) = raw_area.consecutive_fire_cnt_max {
679 area.properties
680 .insert("consecutive_fire_cnt_max".to_string(), serde_json::json!(v));
681 area.properties
683 .insert("consecutive_fire_limit".to_string(), serde_json::json!(v));
684 }
685 if let Some(v) = raw_area.snooze_length {
686 area.properties
687 .insert("snooze_period".to_string(), serde_json::json!(v));
688 }
689
690 if let Some(v) = &raw_area.group_id {
692 area.properties
693 .insert("group_id".to_string(), serde_json::json!(v));
694 }
695 if let Some(v) = &raw_area.sub_group_id {
696 area.properties
697 .insert("sub_group_id".to_string(), serde_json::json!(v));
698 }
699 if let Some(v) = raw_area.per_voxel_neuron_cnt {
701 area.properties
702 .insert("neurons_per_voxel".to_string(), serde_json::json!(v));
703 }
704 if let Some(v) = &raw_area.cortical_mapping_dst {
705 let converted_dstmap = convert_dstmap_keys_to_base64(v);
707 area.properties
708 .insert("cortical_mapping_dst".to_string(), converted_dstmap);
709 }
710 if let Some(v) = &raw_area.coordinate_2d {
711 area.properties
712 .insert("2d_coordinate".to_string(), serde_json::json!(v));
713 }
714
715 for (key, value) in &raw_area.other {
717 area.properties.insert(key.clone(), value.clone());
718 }
719
720 areas.push(area);
724 }
725
726 Ok(areas)
727 }
728
729 fn parse_brain_regions(
731 raw_regions: &HashMap<String, RawBrainRegion>,
732 ) -> EvoResult<Vec<(BrainRegion, Option<String>)>> {
733 let mut regions = Vec::with_capacity(raw_regions.len());
734
735 for (region_id_str, raw_region) in raw_regions.iter() {
736 let title = raw_region
737 .title
738 .clone()
739 .unwrap_or_else(|| region_id_str.clone());
740
741 let region_id = match RegionID::from_string(region_id_str) {
744 Ok(id) => id,
745 Err(_) => {
746 RegionID::new()
749 }
750 };
751
752 let region_type = RegionType::Undefined; let mut region = BrainRegion::new(region_id, title, region_type)?;
755
756 if let Some(props) = &raw_region.properties {
758 for (k, v) in props {
759 region.add_property(k.clone(), v.clone());
760 }
761 }
762
763 if let Some(areas) = &raw_region.areas {
765 for area_id in areas {
766 match string_to_cortical_id(area_id) {
768 Ok(cortical_id) => {
769 region.add_area(cortical_id);
770 }
771 Err(e) => {
772 warn!(target: "feagi-evo",
773 "Failed to convert brain region area ID '{}' to CorticalID: {}. Skipping.",
774 area_id, e);
775 }
776 }
777 }
778 }
779
780 if let Some(desc) = &raw_region.description {
782 region.add_property("description".to_string(), serde_json::json!(desc));
783 }
784 if let Some(coord_2d) = &raw_region.coordinate_2d {
785 region.add_property("coordinate_2d".to_string(), serde_json::json!(coord_2d));
786 }
787 if let Some(coord_3d) = &raw_region.coordinate_3d {
788 region.add_property("coordinate_3d".to_string(), serde_json::json!(coord_3d));
789 }
790 if let Some(inputs) = &raw_region.inputs {
792 let input_ids: Vec<String> = inputs
793 .iter()
794 .filter_map(|id| match string_to_cortical_id(id) {
795 Ok(cortical_id) => Some(cortical_id.as_base_64()),
796 Err(e) => {
797 warn!(target: "feagi-evo",
798 "Failed to convert brain region input ID '{}': {}. Skipping.",
799 id, e);
800 None
801 }
802 })
803 .collect();
804 if !input_ids.is_empty() {
805 region.add_property("inputs".to_string(), serde_json::json!(input_ids));
806 }
807 }
808 if let Some(outputs) = &raw_region.outputs {
809 let output_ids: Vec<String> = outputs
810 .iter()
811 .filter_map(|id| match string_to_cortical_id(id) {
812 Ok(cortical_id) => Some(cortical_id.as_base_64()),
813 Err(e) => {
814 warn!(target: "feagi-evo",
815 "Failed to convert brain region output ID '{}': {}. Skipping.",
816 id, e);
817 None
818 }
819 })
820 .collect();
821 if !output_ids.is_empty() {
822 region.add_property("outputs".to_string(), serde_json::json!(output_ids));
823 }
824 }
825 if let Some(signature) = &raw_region.signature {
826 region.add_property("signature".to_string(), serde_json::json!(signature));
827 }
828
829 if let Some(d) = &raw_region.designated_inputs {
830 let ids: Vec<String> = d
831 .iter()
832 .filter_map(|id| match string_to_cortical_id(id) {
833 Ok(cortical_id) => Some(cortical_id.as_base_64()),
834 Err(e) => {
835 warn!(target: "feagi-evo",
836 "Failed to convert designated_inputs entry '{}': {}. Skipping.",
837 id, e);
838 None
839 }
840 })
841 .collect();
842 if !ids.is_empty() {
843 region.add_property("designated_inputs".to_string(), serde_json::json!(ids));
844 }
845 }
846 if let Some(d) = &raw_region.designated_outputs {
847 let ids: Vec<String> = d
848 .iter()
849 .filter_map(|id| match string_to_cortical_id(id) {
850 Ok(cortical_id) => Some(cortical_id.as_base_64()),
851 Err(e) => {
852 warn!(target: "feagi-evo",
853 "Failed to convert designated_outputs entry '{}': {}. Skipping.",
854 id, e);
855 None
856 }
857 })
858 .collect();
859 if !ids.is_empty() {
860 region.add_property("designated_outputs".to_string(), serde_json::json!(ids));
861 }
862 }
863
864 Self::normalize_brain_region_cortical_id_list_properties(
865 &mut region,
866 &[
867 "inputs",
868 "outputs",
869 "designated_inputs",
870 "designated_outputs",
871 ],
872 );
873
874 let parent_id = raw_region.parent_region_id.clone();
876 if let Some(ref parent_id_str) = parent_id {
877 region.add_property(
879 "parent_region_id".to_string(),
880 serde_json::json!(parent_id_str),
881 );
882 }
883
884 regions.push((region, parent_id));
885 }
886
887 Ok(regions)
888 }
889
890 fn parse_classifiers(
891 raw_classifiers: &HashMap<String, RawClassifier>,
892 ) -> EvoResult<Vec<Classifier>> {
893 let mut classifiers = Vec::with_capacity(raw_classifiers.len());
894 for (classifier_id, raw) in raw_classifiers {
895 let name = raw
896 .name
897 .clone()
898 .filter(|n| !n.trim().is_empty())
899 .ok_or_else(|| {
900 EvoError::InvalidArea(format!("Classifier '{}' is missing name", classifier_id))
901 })?;
902 let parent_region_id = raw
903 .parent_region_id
904 .clone()
905 .filter(|n| !n.trim().is_empty())
906 .ok_or_else(|| {
907 EvoError::InvalidArea(format!(
908 "Classifier '{}' is missing parent_region_id",
909 classifier_id
910 ))
911 })?;
912 let coordinates_3d = match &raw.coordinates_3d {
913 Some(coords) if coords.len() == 3 => [coords[0], coords[1], coords[2]],
914 Some(coords) => {
915 return Err(EvoError::InvalidArea(format!(
916 "Classifier '{}' coordinates_3d must have 3 values, got {}",
917 classifier_id,
918 coords.len()
919 )))
920 }
921 None => [0, 0, 0],
922 };
923 let sample_memory_id = raw.sample_memory_id.clone().ok_or_else(|| {
924 EvoError::InvalidArea(format!(
925 "Classifier '{}' is missing sample_memory_id",
926 classifier_id
927 ))
928 })?;
929 let class_memory_id = raw.class_memory_id.clone().ok_or_else(|| {
930 EvoError::InvalidArea(format!(
931 "Classifier '{}' is missing class_memory_id",
932 classifier_id
933 ))
934 })?;
935 let error_area_id = raw.error_area_id.clone().ok_or_else(|| {
936 EvoError::InvalidArea(format!(
937 "Classifier '{}' is missing error_area_id",
938 classifier_id
939 ))
940 })?;
941 let sample_area_ids = raw
942 .sample_area_ids
943 .iter()
944 .map(|id| id.trim().to_string())
945 .filter(|id| !id.is_empty())
946 .collect();
947 let class_bindings = raw
948 .class_bindings
949 .iter()
950 .filter(|binding| !binding.class_area_id.trim().is_empty())
951 .cloned()
952 .collect();
953 classifiers.push(Classifier {
954 classifier_id: classifier_id.clone(),
955 name,
956 parent_region_id,
957 coordinates_3d,
958 sample_area_ids,
959 class_bindings,
960 sample_memory_id,
961 class_memory_id,
962 error_area_id,
963 reward_training: raw.reward_training,
964 answer_feedback_area_id: raw.answer_feedback_area_id.clone(),
965 pain_area_id: raw.pain_area_id.clone(),
966 pleasure_area_id: raw.pleasure_area_id.clone(),
967 answer_latency_bursts: raw.answer_latency_bursts,
968 learn_area_id: raw.learn_area_id.clone(),
969 confidence_area_id: raw.confidence_area_id.clone(),
970 properties: raw.properties.clone().unwrap_or_default(),
971 });
972 }
973 Ok(classifiers)
974 }
975}
976
977#[cfg(test)]
978mod tests {
979 use super::*;
980
981 #[test]
982 fn test_parse_minimal_genome() {
983 let json = r#"{
986 "version": "2.1",
987 "blueprint": {
988 "_power": {
989 "cortical_name": "Test Area",
990 "block_boundaries": [10, 10, 10],
991 "relative_coordinate": [0, 0, 0],
992 "cortical_type": "CORE"
993 }
994 },
995 "brain_regions": {
996 "root": {
997 "title": "Root",
998 "parent_region_id": null,
999 "areas": ["_power"]
1000 }
1001 }
1002 }"#;
1003
1004 let parsed = GenomeParser::parse(json).unwrap();
1005
1006 assert_eq!(parsed.version, "2.1");
1007 assert_eq!(parsed.cortical_areas.len(), 1);
1008 assert_eq!(
1010 parsed.cortical_areas[0].cortical_id.as_base_64(),
1011 "X19fcG93ZXI="
1012 );
1013 assert_eq!(parsed.cortical_areas[0].name, "Test Area");
1014 assert_eq!(parsed.brain_regions.len(), 1);
1015
1016 assert!(parsed.cortical_areas[0]
1019 .cortical_id
1020 .as_cortical_type()
1021 .is_ok());
1022 }
1023
1024 #[test]
1025 fn test_parse_multiple_areas() {
1026 let json = r#"{
1028 "version": "2.1",
1029 "blueprint": {
1030 "_power": {
1031 "cortical_name": "Area 1",
1032 "cortical_type": "CORE",
1033 "block_boundaries": [5, 5, 5],
1034 "relative_coordinate": [0, 0, 0]
1035 },
1036 "_death": {
1037 "cortical_name": "Area 2",
1038 "cortical_type": "CORE",
1039 "block_boundaries": [10, 10, 10],
1040 "relative_coordinate": [5, 0, 0]
1041 }
1042 }
1043 }"#;
1044
1045 let parsed = GenomeParser::parse(json).unwrap();
1046 assert!(parsed.classifiers.is_empty());
1047
1048 assert_eq!(parsed.cortical_areas.len(), 2);
1049
1050 for area in &parsed.cortical_areas {
1052 assert!(
1053 area.cortical_id.as_cortical_type().is_ok(),
1054 "Area {} should have cortical_type_new populated",
1055 area.cortical_id
1056 );
1057 }
1058 }
1059
1060 #[test]
1061 fn test_string_to_cortical_id_legacy_power_shorthand() {
1062 use feagi_structures::genomic::cortical_area::CoreCorticalType;
1065 let id = string_to_cortical_id("___pwr").unwrap();
1066 assert_eq!(
1067 id.as_base_64(),
1068 CoreCorticalType::Power.to_cortical_id().as_base_64()
1069 );
1070 }
1071
1072 #[test]
1073 fn test_parse_raw_imu_magnetometer_wire_id() {
1074 let json = r#"{
1077 "version": "3.0",
1078 "blueprint": {
1079 "aXJpbScAAgA=": {
1080 "cortical_name": "feagi_body_imu__Abdomen-2",
1081 "block_boundaries": [3, 1, 10],
1082 "relative_coordinate": [90, 0, -10],
1083 "cortical_type": "IPU"
1084 }
1085 },
1086 "brain_regions": {}
1087 }"#;
1088
1089 let parsed = GenomeParser::parse(json).expect("Raw IMU magnetometer genome");
1090 assert_eq!(parsed.cortical_areas.len(), 1);
1091 assert_eq!(
1092 parsed.cortical_areas[0].cortical_id.as_base_64(),
1093 "aXJpbScAAgA="
1094 );
1095 parsed.cortical_areas[0]
1096 .cortical_id
1097 .as_cortical_type()
1098 .expect("magnetometer IO flag must decode");
1099 }
1100
1101 #[test]
1102 fn test_parse_positional_servo_speed_wire_id() {
1103 let json = r#"{
1106 "version": "3.0",
1107 "blueprint": {
1108 "b3BzZSEAAAA=": {
1109 "cortical_name": "Positional Servo Speed",
1110 "block_boundaries": [6, 1, 20],
1111 "relative_coordinate": [-58, 0, -10],
1112 "cortical_type": "OPU"
1113 }
1114 },
1115 "brain_regions": {}
1116 }"#;
1117
1118 let parsed = GenomeParser::parse(json).expect("Positional Servo Speed genome");
1119 assert_eq!(parsed.cortical_areas.len(), 1);
1120 assert_eq!(
1121 parsed.cortical_areas[0].cortical_id.as_base_64(),
1122 "b3BzZSEAAAA="
1123 );
1124 parsed.cortical_areas[0]
1125 .cortical_id
1126 .as_cortical_type()
1127 .expect("positional servo speed IO flag must decode");
1128 }
1129
1130 #[test]
1131 fn test_string_to_cortical_id_legacy_power_padded() {
1132 use feagi_structures::genomic::cortical_area::CoreCorticalType;
1134 let id = string_to_cortical_id("___pwr__").unwrap();
1135 assert_eq!(
1136 id.as_base_64(),
1137 CoreCorticalType::Power.to_cortical_id().as_base_64()
1138 );
1139 }
1140
1141 #[test]
1142 fn test_parse_with_properties() {
1143 let json = r#"{
1144 "version": "2.1",
1145 "blueprint": {
1146 "mem001": {
1147 "cortical_name": "Memory Area",
1148 "block_boundaries": [8, 8, 8],
1149 "relative_coordinate": [0, 0, 0],
1150 "cortical_type": "MEMORY",
1151 "is_mem_type": true,
1152 "firing_threshold": 50.0,
1153 "leak_coefficient": 0.9
1154 }
1155 }
1156 }"#;
1157
1158 let parsed = GenomeParser::parse(json).unwrap();
1159
1160 assert_eq!(parsed.cortical_areas.len(), 1);
1161 let area = &parsed.cortical_areas[0];
1162
1163 use feagi_structures::genomic::cortical_area::CorticalAreaType;
1165 assert!(matches!(area.cortical_type, CorticalAreaType::Memory(_)));
1166
1167 assert!(area.properties.contains_key("is_mem_type"));
1169 assert!(area.properties.contains_key("firing_threshold"));
1170 assert!(area.properties.contains_key("cortical_group"));
1171
1172 assert!(
1174 area.cortical_id.as_cortical_type().is_ok(),
1175 "cortical_id should be parseable to cortical_type"
1176 );
1177 if let Ok(cortical_type) = area.cortical_id.as_cortical_type() {
1178 use feagi_structures::genomic::cortical_area::CorticalAreaType;
1179 assert!(
1180 matches!(cortical_type, CorticalAreaType::Memory(_)),
1181 "Should be classified as MEMORY type"
1182 );
1183 }
1184 }
1185
1186 #[test]
1188 fn test_parse_v3_brain_region_nested_properties_retains_designated_io() {
1189 let json = r#"{
1190 "version": "3.0",
1191 "blueprint": {
1192 "_power": {
1193 "cortical_name": "Core",
1194 "block_boundaries": [10, 10, 10],
1195 "relative_coordinate": [0, 0, 0],
1196 "cortical_type": "CORE"
1197 }
1198 },
1199 "brain_regions": {
1200 "550e8400-e29b-41d4-a716-446655440000": {
1201 "name": "Sub",
1202 "cortical_areas": ["_power"],
1203 "properties": {
1204 "designated_inputs": ["_power"],
1205 "designated_outputs": []
1206 }
1207 }
1208 }
1209 }"#;
1210
1211 let parsed = GenomeParser::parse(json).unwrap();
1212 assert_eq!(parsed.brain_regions.len(), 1);
1213 let (region, _) = &parsed.brain_regions[0];
1214 let di = region
1215 .get_property("designated_inputs")
1216 .and_then(|v| v.as_array())
1217 .expect("designated_inputs");
1218 assert_eq!(di.len(), 1);
1219 assert_eq!(di[0].as_str().unwrap(), "X19fcG93ZXI=");
1220 }
1221
1222 #[test]
1223 fn test_parse_brain_region_plain_text_description() {
1224 let json = r#"{
1225 "version": "2.1",
1226 "blueprint": {
1227 "_power": {
1228 "cortical_name": "Core",
1229 "block_boundaries": [10, 10, 10],
1230 "relative_coordinate": [0, 0, 0],
1231 "cortical_type": "CORE"
1232 }
1233 },
1234 "brain_regions": {
1235 "root": {
1236 "title": "Root",
1237 "description": "Holds core physiology and embodiment IO",
1238 "parent_region_id": null,
1239 "areas": ["_power"]
1240 }
1241 }
1242 }"#;
1243
1244 let parsed = GenomeParser::parse(json).unwrap();
1245 assert_eq!(parsed.brain_regions.len(), 1);
1246 let (region, _) = &parsed.brain_regions[0];
1247 assert_eq!(
1248 region.get_property("description"),
1249 Some(&serde_json::json!(
1250 "Holds core physiology and embodiment IO"
1251 ))
1252 );
1253 }
1254
1255 #[test]
1256 fn test_invalid_version() {
1257 let json = r#"{
1258 "version": "1.0",
1259 "blueprint": {}
1260 }"#;
1261
1262 let result = GenomeParser::parse(json);
1263 assert!(result.is_err());
1264 }
1265
1266 #[test]
1267 fn test_malformed_json() {
1268 let json = r#"{ "version": "2.1", "blueprint": { malformed"#;
1269
1270 let result = GenomeParser::parse(json);
1271 assert!(result.is_err());
1272 }
1273
1274 #[test]
1275 fn test_cortical_type_new_population() {
1276 use feagi_structures::genomic::cortical_area::CoreCorticalType;
1279 let power_id = CoreCorticalType::Power.to_cortical_id().as_base_64();
1280 let json = format!(
1281 r#"{{
1282 "version": "2.1",
1283 "blueprint": {{
1284 "cvision1": {{
1285 "cortical_name": "Test Custom Vision",
1286 "cortical_type": "CUSTOM",
1287 "block_boundaries": [10, 10, 1],
1288 "relative_coordinate": [0, 0, 0]
1289 }},
1290 "cmotor01": {{
1291 "cortical_name": "Test Custom Motor",
1292 "cortical_type": "CUSTOM",
1293 "block_boundaries": [5, 5, 1],
1294 "relative_coordinate": [0, 0, 0]
1295 }},
1296 "{}": {{
1297 "cortical_name": "Test Core",
1298 "cortical_type": "CORE",
1299 "block_boundaries": [1, 1, 1],
1300 "relative_coordinate": [0, 0, 0]
1301 }}
1302 }}
1303 }}"#,
1304 power_id
1305 );
1306
1307 let parsed = GenomeParser::parse(&json).unwrap();
1308 assert_eq!(parsed.cortical_areas.len(), 3);
1309
1310 for area in &parsed.cortical_areas {
1312 assert!(
1313 area.cortical_id.as_cortical_type().is_ok(),
1314 "Area {} should have cortical_type_new populated",
1315 area.cortical_id
1316 );
1317
1318 assert!(
1320 area.properties.contains_key("cortical_group"),
1321 "Area {} should have cortical_group property",
1322 area.cortical_id
1323 );
1324
1325 if let Some(prop_group) = area
1327 .properties
1328 .get("cortical_group")
1329 .and_then(|v| v.as_str())
1330 {
1331 assert!(
1332 !prop_group.is_empty(),
1333 "Area {} should have non-empty cortical_group property",
1334 area.cortical_id.as_base_64()
1335 );
1336 }
1337 }
1338 }
1339
1340 #[test]
1341 fn test_parse_classifiers_key_parallel_to_regions() {
1342 let json = r#"{
1343 "version": "3.0",
1344 "blueprint": {
1345 "csample": {
1346 "cortical_name": "Sample",
1347 "cortical_type": "CUSTOM",
1348 "block_boundaries": [4, 4, 1],
1349 "relative_coordinate": [0, 0, 0]
1350 },
1351 "msmem1": {
1352 "cortical_name": "SampleMem",
1353 "cortical_type": "MEMORY",
1354 "block_boundaries": [1, 1, 1],
1355 "relative_coordinate": [10, 0, 0]
1356 },
1357 "mcmem1": {
1358 "cortical_name": "ClassMem",
1359 "cortical_type": "MEMORY",
1360 "block_boundaries": [1, 1, 1],
1361 "relative_coordinate": [20, 0, 0]
1362 },
1363 "cout1": {
1364 "cortical_name": "ClassOutput",
1365 "cortical_type": "CUSTOM",
1366 "block_boundaries": [1, 1, 4],
1367 "relative_coordinate": [30, 0, 0]
1368 },
1369 "cerr1": {
1370 "cortical_name": "Error",
1371 "cortical_type": "CUSTOM",
1372 "block_boundaries": [1, 1, 1],
1373 "relative_coordinate": [40, 0, 0]
1374 }
1375 },
1376 "brain_regions": {
1377 "root": {
1378 "title": "root",
1379 "parent_region_id": "",
1380 "coordinate_2d": [0, 0],
1381 "coordinate_3d": [0, 0, 0],
1382 "areas": ["csample", "msmem1", "mcmem1", "cout1", "cerr1"],
1383 "regions": [],
1384 "inputs": [],
1385 "outputs": []
1386 }
1387 },
1388 "classifiers": {
1389 "clf-1": {
1390 "name": "object_class",
1391 "parent_region_id": "root",
1392 "coordinates_3d": [30, 0, 0],
1393 "sample_area_ids": ["csample"],
1394 "class_bindings": [{
1395 "class_area_id": "cclass",
1396 "class_output_area_id": "cout1"
1397 }],
1398 "sample_memory_id": "msmem1",
1399 "class_memory_id": "mcmem1",
1400 "error_area_id": "cerr1"
1401 }
1402 }
1403 }"#;
1404
1405 let parsed = GenomeParser::parse(json).expect("classifier genome");
1406 assert_eq!(parsed.classifiers.len(), 1);
1407 let classifier = &parsed.classifiers[0];
1408 assert_eq!(classifier.classifier_id, "clf-1");
1409 assert_eq!(classifier.name, "object_class");
1410 assert_eq!(classifier.sample_memory_id, "msmem1");
1411 assert_eq!(classifier.class_memory_id, "mcmem1");
1412 assert_eq!(classifier.error_area_id, "cerr1");
1413 assert_eq!(classifier.sample_area_ids, vec!["csample".to_string()]);
1414 assert_eq!(classifier.class_bindings.len(), 1);
1415 assert_eq!(classifier.class_bindings[0].class_output_area_id, "cout1");
1416 assert!(classifier.owned_area_ids().contains(&"cerr1".to_string()));
1417 assert!(classifier.owned_area_ids().contains(&"cout1".to_string()));
1418 }
1419
1420 #[test]
1421 fn test_parse_classifier_without_error_area_is_rejected() {
1422 let json = r#"{
1423 "version": "3.0",
1424 "blueprint": {},
1425 "brain_regions": {},
1426 "classifiers": {
1427 "clf-1": {
1428 "name": "object_class",
1429 "parent_region_id": "root",
1430 "sample_memory_id": "msmem1",
1431 "class_memory_id": "mcmem1"
1432 }
1433 }
1434 }"#;
1435 let error = GenomeParser::parse(json).expect_err("error_area_id is required");
1436 assert!(error.to_string().contains("error_area_id"), "{error}");
1437 }
1438}