feagi-evolutionary 0.0.62

Evolution and Genome Management - Genotype operations for FEAGI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
// Copyright 2025 Neuraville Inc.
// SPDX-License-Identifier: Apache-2.0

/*!
Export a branch of the brain-region tree as an independent `RuntimeGenome` suitable for
`save_genome_to_json` (flat format 3.0).

A nested circuit is exported as a **child** of a new `Root Brain Region`. The circuit
keeps its original region name and cortical-area membership so reload and new experiments
show internals inside that circuit, not flattened onto the genome root.

Exporting a region already named `Root Brain Region` is left as-is (full-tree export).

Cortical mappings that target areas outside the branch are stripped from
`cortical_mapping_dst` to avoid dangling references.

Classifiers whose parent circuit is in the branch travel with the export.
Their owned areas (kernel memory, class memory, detection twins) stay in the
genome so reload still treats the stamp as a classifier.

Copyright 2025 Neuraville Inc.
*/

use crate::runtime::{GenomeMetadata, GenomeSignatures, GenomeStats, RuntimeGenome};
use crate::{EvoError, EvoResult};
use feagi_structures::genomic::brain_regions::{
    BrainRegion, RegionID, RegionType, ROOT_BRAIN_REGION_NAME,
};
use feagi_structures::genomic::classifiers::Classifier;
use feagi_structures::genomic::cortical_area::{CorticalArea, CorticalID};
use serde_json::{json, Value};
use std::collections::{HashMap, HashSet, VecDeque};

/// True when `parent_region_id` is missing, empty, self, or not present in `brain_regions`.
fn region_is_parentless(
    region_id: &str,
    region: &BrainRegion,
    brain_regions: &HashMap<String, BrainRegion>,
) -> bool {
    !matches!(
        region
            .properties
            .get("parent_region_id")
            .and_then(|v| v.as_str())
            .map(str::trim)
            .filter(|p| !p.is_empty()),
        Some(parent) if parent != region_id && brain_regions.contains_key(parent)
    )
}

/// If the map has regions but no `Root Brain Region`, insert one and parent every
/// parentless region under it. Existing region names and area membership are unchanged.
///
/// Returns the new root region id when wrapping happened.
pub fn wrap_parentless_regions_under_named_root(
    brain_regions: &mut HashMap<String, BrainRegion>,
) -> Option<String> {
    if brain_regions.is_empty() {
        return None;
    }
    if brain_regions
        .values()
        .any(|r| r.name == ROOT_BRAIN_REGION_NAME)
    {
        return None;
    }

    let parentless: Vec<String> = brain_regions
        .iter()
        .filter(|(rid, region)| region_is_parentless(rid, region, brain_regions))
        .map(|(rid, _)| rid.clone())
        .collect();

    let wrapper_id = RegionID::new();
    let wrapper_key = wrapper_id.to_string();
    // Name is the non-empty canonical root label.
    let wrapper = BrainRegion::new(
        wrapper_id,
        ROOT_BRAIN_REGION_NAME.to_string(),
        RegionType::Undefined,
    )
    .expect("ROOT_BRAIN_REGION_NAME is a non-empty constant");

    for rid in &parentless {
        if let Some(region) = brain_regions.get_mut(rid) {
            region.add_property("parent_region_id".to_string(), json!(wrapper_key.clone()));
        }
    }
    brain_regions.insert(wrapper_key.clone(), wrapper);
    Some(wrapper_key)
}

/// Seed/template labels that are not a user-chosen circuit name.
fn is_placeholder_circuit_title(title: &str) -> bool {
    let t = title.trim();
    t.is_empty()
        || t.eq_ignore_ascii_case("untitled")
        || t.eq_ignore_ascii_case("autogen circuit")
        || t.eq_ignore_ascii_case("neural circuit")
        || t.eq_ignore_ascii_case("the essential genome")
        || t.eq_ignore_ascii_case("current genome")
        || t.eq_ignore_ascii_case("exported genome")
        || t == ROOT_BRAIN_REGION_NAME
}

/// Display name for an exported circuit: live `.name`, then title properties.
fn region_display_name(region: &BrainRegion) -> String {
    let from_name = region.name.trim();
    if !from_name.is_empty() && !is_placeholder_circuit_title(from_name) {
        return from_name.to_string();
    }
    for key in ["region_title", "title", "name"] {
        if let Some(prop) = region
            .properties
            .get(key)
            .and_then(|v| v.as_str())
            .map(str::trim)
            .filter(|s| !s.is_empty())
        {
            if !is_placeholder_circuit_title(prop) {
                return prop.to_string();
            }
        }
    }
    if !from_name.is_empty() {
        return from_name.to_string();
    }
    "Neural circuit".to_string()
}

/// Prefer a custom region name; if that is a seed leftover, use `genome_title`.
fn resolve_circuit_title(region_name: &str, genome_title: &str) -> String {
    let region = region_name.trim();
    let genome = genome_title.trim();
    let region_placeholder = is_placeholder_circuit_title(region);
    let genome_placeholder = is_placeholder_circuit_title(genome);
    if !region.is_empty() && !region_placeholder {
        return region.to_string();
    }
    if !genome.is_empty() && !genome_placeholder {
        return genome.to_string();
    }
    if !region.is_empty() {
        return region.to_string();
    }
    if !genome.is_empty() {
        return genome.to_string();
    }
    "Neural circuit".to_string()
}

/// Id of the unique top-level non-root circuit, if the tree has exactly one.
fn unique_top_level_circuit_id(brain_regions: &HashMap<String, BrainRegion>) -> Option<String> {
    let root_id = brain_regions
        .iter()
        .find_map(|(id, region)| (region.name == ROOT_BRAIN_REGION_NAME).then(|| id.clone()));

    let mut candidates: Vec<String> = Vec::new();
    for (id, region) in brain_regions {
        if region.name == ROOT_BRAIN_REGION_NAME {
            continue;
        }
        let is_top = match &root_id {
            Some(root) => region
                .properties
                .get("parent_region_id")
                .and_then(|v| v.as_str())
                .map(|parent| parent == root)
                .unwrap_or_else(|| region_is_parentless(id, region, brain_regions)),
            None => region_is_parentless(id, region, brain_regions),
        };
        if is_top {
            candidates.push(id.clone());
        }
    }
    if candidates.len() == 1 {
        candidates.pop()
    } else {
        None
    }
}

/// When a genome has exactly one top-level circuit, set that circuit's name from
/// `genome_title` if the stored region name is a seed leftover (e.g. "The Essential Genome").
///
/// Returns the name that was written, or `None` when unchanged or not applicable.
pub fn apply_genome_title_to_unique_top_circuit(
    brain_regions: &mut HashMap<String, BrainRegion>,
    genome_title: &str,
) -> Option<String> {
    let id = unique_top_level_circuit_id(brain_regions)?;
    let current = brain_regions.get(&id)?.name.clone();
    let resolved = resolve_circuit_title(&current, genome_title);
    if resolved == current {
        return None;
    }
    let region = brain_regions.get_mut(&id)?;
    region.name = resolved.clone();
    Some(resolved)
}

/// Build a map: parent region id -> direct child region ids (from `parent_region_id` properties).
fn children_by_parent(genome: &RuntimeGenome) -> HashMap<String, Vec<String>> {
    let mut m: HashMap<String, Vec<String>> = HashMap::new();
    for (rid, region) in &genome.brain_regions {
        if let Some(p) = region
            .properties
            .get("parent_region_id")
            .and_then(|v| v.as_str())
        {
            if !p.is_empty() {
                m.entry(p.to_string()).or_default().push(rid.clone());
            }
        }
    }
    m
}

/// Region id and all descendants (BFS), including `root_region_id`.
fn collect_region_branch_ids(
    genome: &RuntimeGenome,
    root_region_id: &str,
    children_by_parent: &HashMap<String, Vec<String>>,
) -> EvoResult<Vec<String>> {
    if !genome.brain_regions.contains_key(root_region_id) {
        return Err(EvoError::InvalidRegion(format!(
            "Unknown region_id: {}",
            root_region_id
        )));
    }

    let mut out: Vec<String> = Vec::new();
    let mut seen: HashSet<String> = HashSet::new();
    let mut q: VecDeque<String> = VecDeque::new();
    q.push_back(root_region_id.to_string());

    while let Some(rid) = q.pop_front() {
        if !seen.insert(rid.clone()) {
            continue;
        }
        out.push(rid.clone());
        if let Some(kids) = children_by_parent.get(&rid) {
            for k in kids {
                q.push_back(k.clone());
            }
        }
    }

    Ok(out)
}

/// Collect cortical IDs (base64) assigned to any region in `branch_region_ids`.
fn cortical_ids_in_branch(genome: &RuntimeGenome, branch_region_ids: &[String]) -> HashSet<String> {
    let mut ids = HashSet::new();
    for rid in branch_region_ids {
        if let Some(br) = genome.brain_regions.get(rid) {
            for cid in &br.cortical_areas {
                ids.insert(cid.as_base_64());
            }
        }
    }
    ids
}

/// Remove `cortical_mapping_dst` entries whose destination keys are not in `kept`.
fn modulators_for_kept_areas(
    genome: &RuntimeGenome,
    kept: &mut HashSet<String>,
) -> crate::modulators::ModulatorRegistry {
    let mut ids = std::collections::BTreeSet::new();
    for (cortical_id, area) in &genome.cortical_areas {
        if !kept.contains(&cortical_id.as_base_64()) {
            continue;
        }
        collect_modulator_ids(area.properties.get("modulators"), &mut ids);
        if let Some(dst) = area
            .properties
            .get("cortical_mapping_dst")
            .and_then(|value| value.as_object())
        {
            for rules in dst.values() {
                let Some(rules) = rules.as_array() else {
                    continue;
                };
                for rule in rules {
                    collect_modulator_ids(rule.get("modulators"), &mut ids);
                }
            }
        }
    }
    // A modulator whose driver area is in the export belongs to it, subscribers or not: a region
    // that only drives (a reward harness) must stay self-contained.
    for (id, instance) in genome.modulators.iter() {
        if kept.contains(&instance.driver_cortical_id.as_base_64()) {
            ids.insert(id.to_string());
        }
    }
    let mut registry = crate::modulators::ModulatorRegistry::new();
    for id in ids {
        if let Some(instance) = genome.modulators.get(&id) {
            kept.insert(instance.driver_cortical_id.as_base_64());
            registry.insert(id, instance.clone());
        }
    }
    registry
}

fn collect_modulator_ids(
    value: Option<&serde_json::Value>,
    ids: &mut std::collections::BTreeSet<String>,
) {
    let Some(list) = value.and_then(|value| value.as_array()) else {
        return;
    };
    for entry in list {
        if let Some(id) = entry.as_str() {
            ids.insert(id.to_string());
        }
    }
}

fn strip_dst_mappings_outside_branch(area: &mut CorticalArea, kept: &HashSet<String>) {
    let Some(Value::Object(dst_map)) = area.properties.get_mut("cortical_mapping_dst") else {
        return;
    };
    dst_map.retain(|dst_key, _| kept.contains(dst_key));
}

fn classifier_referenced_area_ids(classifier: &Classifier) -> Vec<String> {
    let mut ids = classifier.owned_area_ids();
    ids.extend(classifier.input_area_ids());
    ids
}

/// Classifiers that belong to the exported branch.
///
/// A classifier is included when its parent circuit is in the branch, or when
/// one of its areas is already a member of that branch. Owned and referenced
/// areas that exist in the source genome are added to `kept_cortical` so the
/// stamp, class memory, and inputs reload with the record.
fn classifiers_for_exported_branch(
    genome: &RuntimeGenome,
    branch_set: &HashSet<String>,
    kept_cortical: &mut HashSet<String>,
    fallback_parent_region_id: &str,
) -> HashMap<String, Classifier> {
    let source_area_ids: HashSet<String> = genome
        .cortical_areas
        .keys()
        .map(CorticalID::as_base_64)
        .collect();
    let mut selected = HashMap::new();
    for (classifier_id, classifier) in &genome.classifiers {
        let parent_in_branch = branch_set.contains(&classifier.parent_region_id);
        let touches_branch = classifier_referenced_area_ids(classifier)
            .iter()
            .any(|area_id| kept_cortical.contains(area_id));
        if !parent_in_branch && !touches_branch {
            continue;
        }
        let mut cloned = classifier.clone();
        if !branch_set.contains(&cloned.parent_region_id) {
            cloned.parent_region_id = fallback_parent_region_id.to_string();
        }
        for area_id in classifier_referenced_area_ids(&cloned) {
            if source_area_ids.contains(&area_id) {
                kept_cortical.insert(area_id);
            }
        }
        selected.insert(classifier_id.clone(), cloned);
    }
    selected
}

fn attach_classifier_areas_to_parent_regions(
    brain_regions: &mut HashMap<String, BrainRegion>,
    classifiers: &HashMap<String, Classifier>,
    kept_cortical: &HashSet<String>,
) {
    for classifier in classifiers.values() {
        let Some(region) = brain_regions.get_mut(&classifier.parent_region_id) else {
            continue;
        };
        for area_id in classifier_referenced_area_ids(classifier) {
            if !kept_cortical.contains(&area_id) {
                continue;
            }
            let Ok(cortical_id) = crate::genome::parser::string_to_cortical_id(&area_id) else {
                continue;
            };
            region.add_area(cortical_id);
        }
    }
}

/// Clone [`RuntimeGenome`] to only include the subtree rooted at `root_region_id`.
///
/// - Preserves physiology and full morphology registry from the source genome.
/// - Sets a new `genome_id`; `genome_title` is the exported circuit's region name.
/// - Nested circuits are wrapped under a new `Root Brain Region`; the circuit name is kept.
/// - Strips synapse destination mappings that leave the branch.
/// - Keeps classifiers parented in the branch, plus the areas those records own.
///
/// `count_synapses` receives the exported cortical area ids and returns the genome-expressed
/// synapse count among them (see [`GenomeStats::from_genome`]); the exported genome's `stats`
/// are computed from the exported areas and that count.
pub fn subset_runtime_genome_for_region_branch(
    genome: &RuntimeGenome,
    root_region_id: &str,
    count_synapses: impl FnOnce(&[CorticalID]) -> usize,
) -> EvoResult<RuntimeGenome> {
    let children = children_by_parent(genome);
    let branch_ids = collect_region_branch_ids(genome, root_region_id, &children)?;
    let branch_set: HashSet<String> = branch_ids.iter().cloned().collect();

    let mut kept_cortical = cortical_ids_in_branch(genome, &branch_ids);
    let classifiers =
        classifiers_for_exported_branch(genome, &branch_set, &mut kept_cortical, root_region_id);
    let modulators = modulators_for_kept_areas(genome, &mut kept_cortical);

    let mut cortical_areas: HashMap<CorticalID, CorticalArea> = HashMap::new();
    for (cid, area) in &genome.cortical_areas {
        let b64 = cid.as_base_64();
        if kept_cortical.contains(&b64) {
            let mut a = area.clone();
            strip_dst_mappings_outside_branch(&mut a, &kept_cortical);
            cortical_areas.insert(*cid, a);
        }
    }

    let mut brain_regions: HashMap<String, BrainRegion> = HashMap::new();
    for rid in &branch_ids {
        let Some(mut br) = genome.brain_regions.get(rid).cloned() else {
            continue;
        };
        if rid == root_region_id {
            br.properties.remove("parent_region_id");
        } else if let Some(parent) = br
            .properties
            .get("parent_region_id")
            .and_then(|v| v.as_str())
        {
            if !branch_set.contains(parent) {
                br.properties.remove("parent_region_id");
            }
        }
        brain_regions.insert(rid.clone(), br);
    }
    attach_classifier_areas_to_parent_regions(&mut brain_regions, &classifiers, &kept_cortical);

    let circuit_name = genome
        .brain_regions
        .get(root_region_id)
        .map(region_display_name)
        .filter(|n| !n.trim().is_empty())
        .unwrap_or_else(|| "Neural circuit".to_string());
    if let Some(circuit) = brain_regions.get_mut(root_region_id) {
        circuit.name = circuit_name.clone();
        // Own driver areas join the circuit root. An adopted driver already belongs to its region.
        for (_, instance) in modulators.iter() {
            if !instance.adopts_driver() {
                circuit.cortical_areas.insert(instance.driver_cortical_id);
            }
        }
    }

    let genome_root_id = wrap_parentless_regions_under_named_root(&mut brain_regions)
        .unwrap_or_else(|| root_region_id.to_string());

    let ts = chrono::Utc::now().timestamp() as f64;
    let new_id = format!("region_export_{}", chrono::Utc::now().timestamp_millis());

    let metadata = GenomeMetadata {
        genome_id: new_id,
        genome_title: circuit_name,
        genome_description: format!(
            "Neural circuit export rooted at region {} from genome {}",
            root_region_id, genome.metadata.genome_id
        ),
        version: genome.metadata.version.clone(),
        timestamp: ts,
        brain_regions_root: Some(genome_root_id),
    };

    let exported_ids: Vec<CorticalID> = cortical_areas.keys().copied().collect();
    let synapse_count = count_synapses(&exported_ids);

    let mut exported = RuntimeGenome {
        metadata,
        cortical_areas,
        brain_regions,
        classifiers,
        morphologies: genome.morphologies.clone(),
        modulators,
        physiology: genome.physiology.clone(),
        signatures: GenomeSignatures {
            genome: "0".to_string(),
            blueprint: "0".to_string(),
            physiology: "0".to_string(),
            morphologies: None,
        },
        stats: GenomeStats::default(),
        change_history: Vec::new(),
    };
    exported.stats = GenomeStats::from_genome(&exported, synapse_count);
    Ok(exported)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::runtime::{
        GenomeMetadata, GenomeSignatures, GenomeStats, MorphologyRegistry, PhysiologyConfig,
        RuntimeGenome,
    };
    use feagi_structures::genomic::brain_regions::{
        BrainRegion, RegionID, RegionType, ROOT_BRAIN_REGION_NAME,
    };
    use feagi_structures::genomic::cortical_area::CorticalID;
    use serde_json::json;
    use std::collections::HashMap;

    fn runtime_parent_and_child() -> (RuntimeGenome, String, String) {
        let parent_rid = RegionID::new();
        let child_rid = RegionID::new();
        let parent_key = parent_rid.to_string();
        let child_key = child_rid.to_string();

        let parent = BrainRegion::new(parent_rid, "Parent".to_string(), RegionType::Undefined)
            .expect("parent region");
        let mut child = BrainRegion::new(child_rid, "Child".to_string(), RegionType::Undefined)
            .expect("child region");
        child.add_property("parent_region_id".to_string(), json!(parent_key.clone()));

        let mut brain_regions = HashMap::new();
        brain_regions.insert(parent_key.clone(), parent);
        brain_regions.insert(child_key.clone(), child);

        let g = RuntimeGenome {
            metadata: GenomeMetadata {
                genome_id: "fixture".to_string(),
                genome_title: "Fixture".to_string(),
                genome_description: String::new(),
                version: "3.0".to_string(),
                timestamp: 0.0,
                brain_regions_root: Some(parent_key.clone()),
            },
            cortical_areas: HashMap::new(),
            brain_regions,
            classifiers: HashMap::new(),
            morphologies: MorphologyRegistry::new(),
            modulators: crate::modulators::ModulatorRegistry::new(),
            physiology: PhysiologyConfig::default(),
            signatures: GenomeSignatures {
                genome: "0".to_string(),
                blueprint: "0".to_string(),
                physiology: "0".to_string(),
                morphologies: None,
            },
            stats: GenomeStats::default(),
            change_history: Vec::new(),
        };
        (g, parent_key, child_key)
    }

    #[test]
    fn subset_rejects_unknown_region() {
        let (g, _p, _c) = runtime_parent_and_child();
        let err = subset_runtime_genome_for_region_branch(&g, "nonexistent-region-id", |_| 0)
            .unwrap_err();
        assert!(matches!(err, EvoError::InvalidRegion(_)));
    }

    #[test]
    fn wrap_is_noop_when_empty_or_root_already_present() {
        let mut empty: HashMap<String, BrainRegion> = HashMap::new();
        assert!(wrap_parentless_regions_under_named_root(&mut empty).is_none());

        let root_id = RegionID::new();
        let root_key = root_id.to_string();
        let root = BrainRegion::new(
            root_id,
            ROOT_BRAIN_REGION_NAME.to_string(),
            RegionType::Undefined,
        )
        .expect("root");
        let mut with_root = HashMap::new();
        with_root.insert(root_key, root);
        assert!(wrap_parentless_regions_under_named_root(&mut with_root).is_none());
        assert_eq!(with_root.len(), 1);
    }

    #[test]
    fn wrap_parents_circuit_under_new_root_and_keeps_circuit_name() {
        let circuit_id = RegionID::new();
        let circuit_key = circuit_id.to_string();
        let area_id = CorticalID::try_from_bytes(b"cst_neur").expect("cortical id");
        let circuit = BrainRegion::new(
            circuit_id,
            "The Essential Genome".to_string(),
            RegionType::Undefined,
        )
        .expect("circuit")
        .with_areas([area_id]);
        let mut regions = HashMap::new();
        regions.insert(circuit_key.clone(), circuit);

        let wrapper_key = wrap_parentless_regions_under_named_root(&mut regions).expect("wrapped");
        assert_eq!(regions.len(), 2);
        assert_eq!(regions[&wrapper_key].name, ROOT_BRAIN_REGION_NAME);
        assert_eq!(regions[&circuit_key].name, "The Essential Genome");
        assert!(regions[&circuit_key].contains_area(&area_id));
        assert!(!regions[&wrapper_key].contains_area(&area_id));
        assert_eq!(
            regions[&circuit_key]
                .properties
                .get("parent_region_id")
                .and_then(|v| v.as_str()),
            Some(wrapper_key.as_str())
        );
        assert!(regions[&wrapper_key].cortical_areas.is_empty());
    }

    #[test]
    fn wrap_keeps_nested_child_parent_and_only_reparents_parentless() {
        let parent_id = RegionID::new();
        let child_id = RegionID::new();
        let parent_key = parent_id.to_string();
        let child_key = child_id.to_string();
        let parent = BrainRegion::new(parent_id, "Circuit".to_string(), RegionType::Undefined)
            .expect("parent");
        let mut child =
            BrainRegion::new(child_id, "Inner".to_string(), RegionType::Undefined).expect("child");
        child.add_property("parent_region_id".to_string(), json!(parent_key.clone()));

        let mut regions = HashMap::new();
        regions.insert(parent_key.clone(), parent);
        regions.insert(child_key.clone(), child);

        let wrapper_key = wrap_parentless_regions_under_named_root(&mut regions).expect("wrapped");
        assert_eq!(
            regions[&parent_key]
                .properties
                .get("parent_region_id")
                .and_then(|v| v.as_str()),
            Some(wrapper_key.as_str())
        );
        assert_eq!(
            regions[&child_key]
                .properties
                .get("parent_region_id")
                .and_then(|v| v.as_str()),
            Some(parent_key.as_str())
        );
        assert_eq!(regions[&parent_key].name, "Circuit");
        assert_eq!(regions[&child_key].name, "Inner");
    }

    #[test]
    fn subset_child_region_is_wrapped_under_new_root_preserving_name() {
        let (g, _parent_key, child_key) = runtime_parent_and_child();
        let sub = subset_runtime_genome_for_region_branch(&g, &child_key, |_| 0).expect("subset");
        assert_eq!(sub.brain_regions.len(), 2);
        assert!(sub.brain_regions.contains_key(&child_key));
        assert_eq!(sub.brain_regions[&child_key].name, "Child");
        assert_eq!(sub.metadata.genome_title, "Child");
        let wrapper_id = sub
            .metadata
            .brain_regions_root
            .as_deref()
            .expect("wrapped root id");
        assert_ne!(wrapper_id, child_key.as_str());
        assert_eq!(sub.brain_regions[wrapper_id].name, ROOT_BRAIN_REGION_NAME);
        assert_eq!(
            sub.brain_regions[&child_key]
                .properties
                .get("parent_region_id")
                .and_then(|v| v.as_str()),
            Some(wrapper_id)
        );
    }

    #[test]
    fn subset_named_root_is_not_double_wrapped() {
        let root_id = RegionID::new();
        let child_id = RegionID::new();
        let root_key = root_id.to_string();
        let child_key = child_id.to_string();
        let root = BrainRegion::new(
            root_id,
            ROOT_BRAIN_REGION_NAME.to_string(),
            RegionType::Undefined,
        )
        .expect("root");
        let mut child = BrainRegion::new(child_id, "Circuit".to_string(), RegionType::Undefined)
            .expect("child");
        child.add_property("parent_region_id".to_string(), json!(root_key.clone()));

        let mut brain_regions = HashMap::new();
        brain_regions.insert(root_key.clone(), root);
        brain_regions.insert(child_key.clone(), child);

        let g = RuntimeGenome {
            metadata: GenomeMetadata {
                genome_id: "fixture".to_string(),
                genome_title: "Fixture".to_string(),
                genome_description: String::new(),
                version: "3.0".to_string(),
                timestamp: 0.0,
                brain_regions_root: Some(root_key.clone()),
            },
            cortical_areas: HashMap::new(),
            brain_regions,
            classifiers: HashMap::new(),
            morphologies: MorphologyRegistry::new(),
            modulators: crate::modulators::ModulatorRegistry::new(),
            physiology: PhysiologyConfig::default(),
            signatures: GenomeSignatures {
                genome: "0".to_string(),
                blueprint: "0".to_string(),
                physiology: "0".to_string(),
                morphologies: None,
            },
            stats: GenomeStats::default(),
            change_history: Vec::new(),
        };

        let sub = subset_runtime_genome_for_region_branch(&g, &root_key, |_| 0).expect("subset");
        let named_roots = sub
            .brain_regions
            .values()
            .filter(|r| r.name == ROOT_BRAIN_REGION_NAME)
            .count();
        assert_eq!(named_roots, 1);
        assert_eq!(sub.brain_regions.len(), 2);
        assert_eq!(
            sub.metadata.brain_regions_root.as_deref(),
            Some(root_key.as_str())
        );
        assert_eq!(sub.brain_regions[&child_key].name, "Circuit");
    }

    #[test]
    fn subset_uses_region_title_property_when_name_is_seed_leftover() {
        let (mut g, _parent_key, child_key) = runtime_parent_and_child();
        {
            let child = g.brain_regions.get_mut(&child_key).expect("child");
            child.name = "The Essential Genome".to_string();
            child.add_property("region_title".to_string(), json!("Goal Seeker"));
        }
        let sub = subset_runtime_genome_for_region_branch(&g, &child_key, |_| 0).expect("subset");
        assert_eq!(sub.brain_regions[&child_key].name, "Goal Seeker");
        assert_eq!(sub.metadata.genome_title, "Goal Seeker");
    }

    #[test]
    fn apply_replaces_essential_genome_name_with_custom_genome_title() {
        let circuit_id = RegionID::new();
        let circuit_key = circuit_id.to_string();
        let root_id = RegionID::new();
        let root_key = root_id.to_string();
        let root = BrainRegion::new(
            root_id,
            ROOT_BRAIN_REGION_NAME.to_string(),
            RegionType::Undefined,
        )
        .expect("root");
        let mut circuit = BrainRegion::new(
            circuit_id,
            "The Essential Genome".to_string(),
            RegionType::Undefined,
        )
        .expect("circuit");
        circuit.add_property("parent_region_id".to_string(), json!(root_key.clone()));
        let mut regions = HashMap::new();
        regions.insert(root_key, root);
        regions.insert(circuit_key.clone(), circuit);

        let written =
            apply_genome_title_to_unique_top_circuit(&mut regions, "Goal Seeker").expect("renamed");
        assert_eq!(written, "Goal Seeker");
        assert_eq!(regions[&circuit_key].name, "Goal Seeker");
        assert_eq!(
            regions
                .values()
                .filter(|r| r.name == ROOT_BRAIN_REGION_NAME)
                .count(),
            1
        );
    }

    #[test]
    fn apply_keeps_custom_region_name_when_genome_title_is_generic() {
        let circuit_id = RegionID::new();
        let circuit_key = circuit_id.to_string();
        let circuit =
            BrainRegion::new(circuit_id, "Goal Seeker".to_string(), RegionType::Undefined)
                .expect("circuit");
        let mut regions = HashMap::new();
        regions.insert(circuit_key.clone(), circuit);
        wrap_parentless_regions_under_named_root(&mut regions);

        assert!(
            apply_genome_title_to_unique_top_circuit(&mut regions, "The Essential Genome")
                .is_none()
        );
        assert_eq!(regions[&circuit_key].name, "Goal Seeker");
    }

    #[test]
    fn apply_skips_when_two_top_level_circuits() {
        let a_id = RegionID::new();
        let b_id = RegionID::new();
        let a_key = a_id.to_string();
        let b_key = b_id.to_string();
        let mut regions = HashMap::new();
        regions.insert(
            a_key,
            BrainRegion::new(a_id, "Circuit A".to_string(), RegionType::Undefined).expect("a"),
        );
        regions.insert(
            b_key,
            BrainRegion::new(b_id, "Circuit B".to_string(), RegionType::Undefined).expect("b"),
        );
        wrap_parentless_regions_under_named_root(&mut regions);
        assert!(apply_genome_title_to_unique_top_circuit(&mut regions, "Hub Title").is_none());
    }

    #[test]
    fn subset_keeps_classifier_parented_in_the_exported_circuit() {
        use feagi_structures::genomic::classifiers::Classifier;
        use feagi_structures::genomic::cortical_area::{
            CorticalAreaDimensions, CorticalAreaType, MemoryCorticalType,
        };

        let (mut genome, _parent_key, child_key) = runtime_parent_and_child();
        let kernel_mem_id = CorticalID::try_from_bytes(b"mkernexp").expect("kernel memory id");
        let mut kernel_mem = CorticalArea::new(
            kernel_mem_id,
            0,
            "Demo_kernel_mem".to_string(),
            CorticalAreaDimensions::new(1, 1, 1).expect("dims"),
            (0, 0, 0).into(),
            CorticalAreaType::Memory(MemoryCorticalType::Memory),
        )
        .expect("kernel memory");
        kernel_mem
            .properties
            .insert("classifier_role".to_string(), json!("kernel_memory"));
        genome
            .brain_regions
            .get_mut(&child_key)
            .expect("child region")
            .add_area(kernel_mem_id);
        genome.cortical_areas.insert(kernel_mem_id, kernel_mem);
        genome.classifiers.insert(
            "clf-1".to_string(),
            Classifier {
                classifier_id: "clf-1".to_string(),
                name: "Demo".to_string(),
                parent_region_id: child_key.clone(),
                coordinates_3d: [1, 2, 3],
                sample_area_ids: Vec::new(),
                class_bindings: Vec::new(),
                sample_memory_id: kernel_mem_id.as_base_64(),
                class_memory_id: kernel_mem_id.as_base_64(),
                error_area_id: "cerr1".to_string(),
                reward_training: false,
                answer_feedback_area_id: None,
                correct_area_id: String::new(),
                reward_modulator_ids: Vec::new(),
                answer_latency_bursts: 0,
                learn_area_id: None,
                confidence_area_id: None,
                properties: HashMap::new(),
            },
        );

        let exported =
            subset_runtime_genome_for_region_branch(&genome, &child_key, |_| 0).expect("subset");
        let classifier = exported
            .classifiers
            .get("clf-1")
            .expect("classifier stays a classifier record");
        assert_eq!(classifier.parent_region_id, child_key);
        assert_eq!(classifier.sample_memory_id, kernel_mem_id.as_base_64());
        assert!(exported.cortical_areas.contains_key(&kernel_mem_id));
        assert!(exported.brain_regions[&child_key]
            .cortical_areas
            .contains(&kernel_mem_id));
    }

    #[test]
    fn region_export_stats_cover_only_the_exported_areas() {
        use feagi_structures::genomic::cortical_area::{
            CorticalAreaDimensions, CorticalAreaType, CustomCorticalType, MemoryCorticalType,
        };

        let (mut genome, parent_key, child_key) = runtime_parent_and_child();
        // (id, region, dims, neurons_per_voxel property, memory area)
        let specs = [
            (b"cstaouta", &parent_key, (2, 1, 1), Some(3), false),
            (b"cstainna", &child_key, (2, 2, 1), None, false),
            (b"cstainnb", &child_key, (1, 1, 1), Some(5), true),
        ];
        for (idx, (raw, region, (x, y, z), per_voxel, is_memory)) in specs.into_iter().enumerate() {
            let id = CorticalID::try_from_bytes(raw).expect("id");
            let cortical_type = if is_memory {
                CorticalAreaType::Memory(MemoryCorticalType::Memory)
            } else {
                CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire)
            };
            let mut area = CorticalArea::new(
                id,
                idx as u32,
                "area".to_string(),
                CorticalAreaDimensions::new(x, y, z).expect("dims"),
                (0, 0, 0).into(),
                cortical_type,
            )
            .expect("area");
            if let Some(n) = per_voxel {
                area.properties
                    .insert("neurons_per_voxel".to_string(), json!(n));
            }
            genome
                .brain_regions
                .get_mut(region)
                .expect("region")
                .add_area(id);
            genome.cortical_areas.insert(id, area);
        }
        genome.stats = GenomeStats {
            innate_cortical_area_count: 99,
            innate_neuron_count: 99,
            innate_synapse_count: 99,
        };

        let mut seen = 0usize;
        let exported = subset_runtime_genome_for_region_branch(&genome, &child_key, |ids| {
            seen = ids.len();
            ids.len() * 10
        })
        .expect("subset");

        // Child region only: 2x2x1 x 1 (default) + 1x1x1 x 5 (memory area included) = 9.
        assert_eq!(seen, 2);
        assert_eq!(exported.stats.innate_cortical_area_count, 2);
        assert_eq!(exported.stats.innate_neuron_count, 9);
        assert_eq!(exported.stats.innate_synapse_count, 20);
    }

    #[test]
    fn subset_keeps_an_adopted_driver_in_its_own_region_only() {
        use feagi_structures::genomic::cortical_area::{
            CorticalAreaDimensions, CorticalAreaType, CustomCorticalType,
        };

        let (mut genome, parent_key, child_key) = runtime_parent_and_child();
        let src_id = CorticalID::try_from_bytes(b"csrcexp1").expect("source id");
        let answer_id = CorticalID::try_from_bytes(b"cansexp1").expect("answer id");
        for (id, region) in [(src_id, &parent_key), (answer_id, &child_key)] {
            let mut area = CorticalArea::new(
                id,
                0,
                "area".to_string(),
                CorticalAreaDimensions::new(1, 1, 1).expect("dims"),
                (0, 0, 0).into(),
                CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire),
            )
            .expect("area");
            if id == src_id {
                area.properties.insert(
                    "cortical_mapping_dst".to_string(),
                    json!({ src_id.as_base_64(): [{"morphology_id": "projector", "modulators": ["answer"]}] }),
                );
            }
            genome
                .brain_regions
                .get_mut(region)
                .expect("region")
                .add_area(id);
            genome.cortical_areas.insert(id, area);
        }
        genome.modulators.insert(
            "answer".to_string(),
            crate::modulators::ModulatorInstance {
                kind: feagi_structures::genomic::ModulatorKind::Reward,
                magnitude_percent: -100.0,
                effect_duration_bursts: 1,
                rest_bursts: 0,
                graded: false,
                full_scale_potential: None,
                driver_cortical_id: answer_id,
            },
        );

        let exported =
            subset_runtime_genome_for_region_branch(&genome, &parent_key, |_| 0).expect("subset");
        assert!(exported.modulators.contains("answer"));
        let homes: Vec<&String> = exported
            .brain_regions
            .iter()
            .filter(|(_, region)| region.cortical_areas.contains(&answer_id))
            .map(|(key, _)| key)
            .collect();
        assert_eq!(
            homes,
            vec![&child_key],
            "an adopted driver stays in its own region"
        );
        // The driver's own region has no subscriber, and still carries the modulator it drives.
        let driver_only =
            subset_runtime_genome_for_region_branch(&genome, &child_key, |_| 0).expect("subset");
        assert!(driver_only.modulators.contains("answer"));
    }

    #[test]
    fn subset_omits_classifier_outside_the_exported_circuit() {
        use feagi_structures::genomic::classifiers::Classifier;

        let (mut genome, parent_key, child_key) = runtime_parent_and_child();
        genome.classifiers.insert(
            "clf-parent".to_string(),
            Classifier {
                classifier_id: "clf-parent".to_string(),
                name: "Parent only".to_string(),
                parent_region_id: parent_key,
                coordinates_3d: [0, 0, 0],
                sample_area_ids: Vec::new(),
                class_bindings: Vec::new(),
                sample_memory_id: "bW1pc3Npbmch".to_string(),
                class_memory_id: "bW1pc3Npbmch".to_string(),
                error_area_id: "cerr1".to_string(),
                reward_training: false,
                answer_feedback_area_id: None,
                correct_area_id: String::new(),
                reward_modulator_ids: Vec::new(),
                answer_latency_bursts: 0,
                learn_area_id: None,
                confidence_area_id: None,
                properties: HashMap::new(),
            },
        );

        let exported =
            subset_runtime_genome_for_region_branch(&genome, &child_key, |_| 0).expect("subset");
        assert!(exported.classifiers.is_empty());
    }
}