feagi-evolutionary 0.0.65

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
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
// Copyright 2025 Neuraville Inc.
// SPDX-License-Identifier: Apache-2.0

/*!
Remap **Custom** and **Memory** cortical IDs on an imported guest genome so they do not collide
with the host connectome.

Core (`___death`, `___power`, `___fatig`, `___pain_`, `___pleas`, `___fear_`, `___hope_`) and IPU/OPU identifiers are **not** remapped: they are
canonical and must continue to match the host’s shared IO and core regions.

Copyright 2025 Neuraville Inc.
Licensed under the Apache License, Version 2.0
*/

use crate::random::random_bytes;
use crate::runtime::RuntimeGenome;
use feagi_structures::genomic::brain_regions::PORT_ENCODING_KEY;
use feagi_structures::genomic::cortical_area::CorticalArea;
use feagi_structures::genomic::cortical_area::CorticalAreaType;
use feagi_structures::genomic::cortical_area::CorticalID;
use feagi_structures::genomic::BrainRegion;
use feagi_structures::FeagiDataError;
use serde_json::Value;
use std::collections::{HashMap, HashSet};

const MAX_ID_ALLOC_ATTEMPTS: u32 = 100_000;

/// Allocate a new cortical ID with the given first-byte prefix (`c` or `m`), distinct from
/// `reserved` (inserts the chosen ID into `reserved`).
fn allocate_unique_typed_id(
    prefix: u8,
    reserved: &mut HashSet<String>,
) -> Result<CorticalID, FeagiDataError> {
    for _ in 0..MAX_ID_ALLOC_ATTEMPTS {
        let mut bytes = [0u8; CorticalID::CORTICAL_ID_LENGTH];
        bytes[0] = prefix;
        random_bytes(&mut bytes[1..]);
        if let Ok(id) = CorticalID::try_from_bytes(&bytes) {
            let s = id.as_base_64();
            if !reserved.contains(&s) {
                reserved.insert(s);
                return Ok(id);
            }
        }
    }
    Err(FeagiDataError::InternalError(
        "Failed to allocate a unique cortical ID for amalgamation remapping".into(),
    ))
}

/// Rewrite the base64 area ids in a region's `inputs`, `outputs`, `designated_inputs` and
/// `designated_outputs` property lists, and the keys of its `port_encoding` map.
pub fn remap_region_io_lists(region: &mut BrainRegion, b64_remap: &HashMap<String, String>) {
    if let Some(Value::Object(entries)) = region.properties.get_mut(PORT_ENCODING_KEY) {
        let taken = std::mem::take(entries);
        for (area_id, entry) in taken {
            let new_id = b64_remap.get(&area_id).cloned().unwrap_or(area_id);
            entries.insert(new_id, entry);
        }
    }
    for key in [
        "inputs",
        "outputs",
        "designated_inputs",
        "designated_outputs",
    ] {
        let Some(val) = region.properties.get_mut(key) else {
            continue;
        };
        let Some(arr) = val.as_array_mut() else {
            continue;
        };
        for item in arr.iter_mut() {
            if let Some(s) = item.as_str() {
                if let Some(n) = b64_remap.get(s) {
                    *item = Value::String(n.clone());
                }
            }
        }
    }
}

/// Mapping-rule fields that hold another area's base64 id.
const RULE_AREA_ID_KEYS: [&str; 3] = [
    "gate_source_area",
    "reward_source_area",
    "punishment_source_area",
];

fn remap_cortical_mapping_dst_keys(
    properties: &mut HashMap<String, Value>,
    b64_remap: &HashMap<String, String>,
) {
    let Some(Value::Object(dstmap)) = properties.get_mut("cortical_mapping_dst") else {
        return;
    };
    let taken = std::mem::take(dstmap);
    let mut new_map = serde_json::Map::new();
    for (k, mut v) in taken {
        let nk = b64_remap.get(&k).cloned().unwrap_or(k);
        if let Value::Array(rules) = &mut v {
            for rule in rules.iter_mut() {
                let Value::Object(rule) = rule else { continue };
                for key in RULE_AREA_ID_KEYS {
                    if let Some(Value::String(id)) = rule.get_mut(key) {
                        remap_id(id, b64_remap);
                    }
                }
            }
        }
        new_map.insert(nk, v);
    }
    properties.insert("cortical_mapping_dst".to_string(), Value::Object(new_map));
}

/// Remap guest **Custom** and **Memory** cortical IDs to fresh values not present in
/// `host_reserved_base64_ids` or elsewhere in this guest genome. Updates cortical area keys,
/// `cortical_mapping_dst` destination keys, brain region membership, and region IO lists.
///
/// Returns `(old_base64, new_base64)` pairs only for IDs that changed.
pub fn remap_guest_custom_memory_cortical_ids_for_amalgamation(
    genome: &mut RuntimeGenome,
    host_reserved_base64_ids: &HashSet<String>,
) -> Result<HashMap<String, String>, FeagiDataError> {
    let mut reserved: HashSet<String> = host_reserved_base64_ids.clone();
    for id in genome.cortical_areas.keys() {
        reserved.insert(id.as_base_64());
    }

    let mut id_remap: HashMap<CorticalID, CorticalID> = HashMap::new();

    for (old_id, area) in genome.cortical_areas.iter() {
        let needs_remapping = matches!(
            &area.cortical_type,
            CorticalAreaType::Custom(_) | CorticalAreaType::Memory(_)
        );
        if !needs_remapping {
            continue;
        }
        let prefix = old_id.as_bytes()[0];
        let new_id = allocate_unique_typed_id(prefix, &mut reserved)?;
        id_remap.insert(*old_id, new_id);
    }

    let mut b64_remap: HashMap<String, String> = HashMap::new();
    for (old_id, new_id) in &id_remap {
        let ob = old_id.as_base_64();
        let nb = new_id.as_base_64();
        if ob != nb {
            b64_remap.insert(ob, nb);
        }
    }

    if id_remap.is_empty() {
        return Ok(b64_remap);
    }

    // Re-key cortical_areas and refresh each area's `cortical_id`.
    let mut new_areas: HashMap<CorticalID, CorticalArea> =
        HashMap::with_capacity(genome.cortical_areas.len());
    for (old_id, mut area) in std::mem::take(&mut genome.cortical_areas) {
        let new_id = id_remap.get(&old_id).copied().unwrap_or(old_id);
        area.cortical_id = new_id;
        new_areas.insert(new_id, area);
    }
    genome.cortical_areas = new_areas;

    for region in genome.brain_regions.values_mut() {
        let mut new_set: HashSet<CorticalID> = HashSet::with_capacity(region.cortical_areas.len());
        for cid in region.cortical_areas.drain() {
            let nid = id_remap.get(&cid).copied().unwrap_or(cid);
            new_set.insert(nid);
        }
        region.cortical_areas = new_set;
        remap_region_io_lists(region, &b64_remap);
    }

    rewrite_area_references(genome, &b64_remap);

    Ok(b64_remap)
}

/// Area property keys whose string value is another area id (classifier assembly links).
const AREA_ID_PROPERTY_KEYS: [&str; 3] = [
    "classifier_class_memory_id",
    "classifier_sample_memory_id",
    "classifier_error_area_id",
];

fn remap_id(id: &mut String, b64_remap: &HashMap<String, String>) {
    if let Some(new_id) = b64_remap.get(id.as_str()) {
        *id = new_id.clone();
    }
}

/// Rewrite every area id held inside one area's properties (`old base64 -> new base64`):
/// `cortical_mapping_dst` destination keys and the `*_source_area` fields of their rules,
/// classifier assembly links, and the memory-twin properties (`memory_twin_areas` keys and
/// values, `memory_twin_of`, `memory_twin_for`).
///
/// This is the one place that knows which area properties carry area ids; the genome store and
/// the live connectome both call it.
pub fn rewrite_area_properties(
    properties: &mut HashMap<String, Value>,
    b64_remap: &HashMap<String, String>,
) {
    if b64_remap.is_empty() {
        return;
    }
    remap_cortical_mapping_dst_keys(properties, b64_remap);
    for key in AREA_ID_PROPERTY_KEYS
        .iter()
        .chain(["memory_twin_of", "memory_twin_for"].iter())
    {
        if let Some(Value::String(id)) = properties.get_mut(*key) {
            remap_id(id, b64_remap);
        }
    }
    if let Some(Value::Object(twins)) = properties.get_mut("memory_twin_areas") {
        let taken = std::mem::take(twins);
        for (source, twin) in taken {
            let new_source = b64_remap.get(&source).cloned().unwrap_or(source);
            let new_twin = match twin {
                Value::String(id) => Value::String(b64_remap.get(&id).cloned().unwrap_or(id)),
                other => other,
            };
            twins.insert(new_source, new_twin);
        }
    }
}

/// Rename areas in a genome in place: area keys, `cortical_id` fields, region membership and
/// region IO lists, and every id-bearing property (see [`rewrite_area_properties`]), classifier
/// fields and modulator drivers. `renames` is a set of simultaneous `(old, new)` pairs, so a swap
/// of two ids is allowed. Neuron data is not touched.
///
/// Fails, leaving the genome unchanged, when an old id is missing, a new id repeats, or a new id
/// is taken by an area that is not itself renamed.
pub fn rename_runtime_genome_areas(
    genome: &mut RuntimeGenome,
    renames: &[(CorticalID, CorticalID)],
) -> Result<(), FeagiDataError> {
    let id_remap: HashMap<CorticalID, CorticalID> = renames.iter().copied().collect();
    if id_remap.len() != renames.len() {
        return Err(FeagiDataError::BadParameters(
            "rename lists the same source area twice".into(),
        ));
    }
    let mut targets: HashSet<CorticalID> = HashSet::new();
    for (old, new) in renames {
        if !genome.cortical_areas.contains_key(old) {
            return Err(FeagiDataError::BadParameters(format!(
                "cortical area {} does not exist",
                old.as_base_64()
            )));
        }
        if !targets.insert(*new) {
            return Err(FeagiDataError::BadParameters(format!(
                "target id {} is used twice",
                new.as_base_64()
            )));
        }
        if genome.cortical_areas.contains_key(new) && !id_remap.contains_key(new) {
            return Err(FeagiDataError::BadParameters(format!(
                "target id {} is already taken",
                new.as_base_64()
            )));
        }
    }
    let b64_remap: HashMap<String, String> = renames
        .iter()
        .filter(|(old, new)| old != new)
        .map(|(old, new)| (old.as_base_64(), new.as_base_64()))
        .collect();
    if b64_remap.is_empty() {
        return Ok(());
    }
    // Phase 1 removes every renamed area, phase 2 inserts them under the new ids.
    let mut moved: Vec<CorticalArea> = Vec::with_capacity(renames.len());
    for (old, new) in renames {
        if let Some(mut area) = genome.cortical_areas.remove(old) {
            area.cortical_id = *new;
            moved.push(area);
        }
    }
    for area in moved {
        genome.cortical_areas.insert(area.cortical_id, area);
    }
    for region in genome.brain_regions.values_mut() {
        let members: Vec<CorticalID> = region.cortical_areas.drain().collect();
        for cid in members {
            region
                .cortical_areas
                .insert(id_remap.get(&cid).copied().unwrap_or(cid));
        }
        remap_region_io_lists(region, &b64_remap);
    }
    rewrite_area_references(genome, &b64_remap);
    Ok(())
}

/// Apply an area-id remap (`old base64 -> new base64`) to every place a guest genome refers to
/// an area by id other than the area key itself: `cortical_mapping_dst` destination keys, area
/// properties that link classifier assembly areas and memory twins, adopted modulator drivers
/// and classifier area fields.
pub(crate) fn rewrite_area_references(
    genome: &mut RuntimeGenome,
    b64_remap: &HashMap<String, String>,
) {
    if b64_remap.is_empty() {
        return;
    }
    for area in genome.cortical_areas.values_mut() {
        rewrite_area_properties(&mut area.properties, b64_remap);
    }
    for id in genome.modulators.ids() {
        let Some(instance) = genome.modulators.get_mut(&id) else {
            continue;
        };
        if let Some(new_id) = b64_remap
            .get(&instance.driver_cortical_id.as_base_64())
            .and_then(|new_id| CorticalID::try_from_base_64(new_id).ok())
        {
            instance.driver_cortical_id = new_id;
        }
    }
    for classifier in genome.classifiers.values_mut() {
        remap_classifier_area_fields(classifier, b64_remap);
    }
}

/// Remap every area id a classifier record holds.
pub fn remap_classifier_area_fields(
    classifier: &mut feagi_structures::genomic::classifiers::Classifier,
    b64_remap: &HashMap<String, String>,
) {
    remap_id(&mut classifier.sample_memory_id, b64_remap);
    remap_id(&mut classifier.class_memory_id, b64_remap);
    remap_id(&mut classifier.error_area_id, b64_remap);
    remap_id(&mut classifier.correct_area_id, b64_remap);
    for id in classifier.sample_area_ids.iter_mut() {
        remap_id(id, b64_remap);
    }
    for binding in classifier.class_bindings.iter_mut() {
        remap_id(&mut binding.class_area_id, b64_remap);
        remap_id(&mut binding.class_output_area_id, b64_remap);
    }
    for id in [
        &mut classifier.answer_feedback_area_id,
        &mut classifier.learn_area_id,
        &mut classifier.confidence_area_id,
    ]
    .into_iter()
    .flatten()
    {
        remap_id(id, b64_remap);
    }
}

/// Re-key guest modulator driver areas after their instances were created in the host
/// (`old base64 -> new base64`, including drivers of reused host modulators), and rewrite every
/// reference to them (mapping destinations, classifier fields, region membership).
pub fn apply_driver_remap(
    genome: &mut RuntimeGenome,
    driver_remap: &HashMap<String, String>,
) -> Result<(), FeagiDataError> {
    if driver_remap.is_empty() {
        return Ok(());
    }
    let mut id_remap: HashMap<CorticalID, CorticalID> = HashMap::new();
    for (old, new) in driver_remap {
        id_remap.insert(
            CorticalID::try_from_base_64(old)?,
            CorticalID::try_from_base_64(new)?,
        );
    }
    let mut new_areas: HashMap<CorticalID, CorticalArea> =
        HashMap::with_capacity(genome.cortical_areas.len());
    for (old_id, mut area) in std::mem::take(&mut genome.cortical_areas) {
        let new_id = id_remap.get(&old_id).copied().unwrap_or(old_id);
        area.cortical_id = new_id;
        new_areas.insert(new_id, area);
    }
    genome.cortical_areas = new_areas;
    for region in genome.brain_regions.values_mut() {
        let members: Vec<CorticalID> = region.cortical_areas.drain().collect();
        for cid in members {
            region
                .cortical_areas
                .insert(id_remap.get(&cid).copied().unwrap_or(cid));
        }
        remap_region_io_lists(region, driver_remap);
    }
    rewrite_area_references(genome, driver_remap);
    Ok(())
}

fn json_string_list(value: Option<&Value>) -> Vec<String> {
    value
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|item| item.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default()
}

/// Declared region IO on the circuit that region-export wrapped under `Root Brain Region`.
///
/// Amalgamation hosts that circuit in a new region. These lists are already remapped to the
/// guest cortical IDs and must be copied onto that new region or the clone drops input/output roles.
pub fn designated_io_lists_for_cloned_circuit(
    genome: &RuntimeGenome,
) -> (Vec<String>, Vec<String>) {
    use feagi_structures::genomic::brain_regions::ROOT_BRAIN_REGION_NAME;

    let root_ids: HashSet<String> = genome
        .brain_regions
        .iter()
        .filter(|(_, region)| region.name == ROOT_BRAIN_REGION_NAME)
        .map(|(id, _)| id.clone())
        .collect();

    let circuit = genome.brain_regions.values().find(|region| {
        let parent = region
            .properties
            .get("parent_region_id")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        if !root_ids.is_empty() {
            root_ids.contains(parent)
        } else {
            parent.is_empty() && region.name != ROOT_BRAIN_REGION_NAME
        }
    });

    let Some(region) = circuit else {
        return (Vec::new(), Vec::new());
    };
    (
        json_string_list(region.properties.get("designated_inputs")),
        json_string_list(region.properties.get("designated_outputs")),
    )
}

/// One sub-region to create under the amalgamation host region.
#[derive(Debug, Clone, PartialEq)]
pub struct AmalgamationRegionSpec {
    /// Fresh region id (UUID string) for the new region.
    pub region_id: String,
    /// Guest region name.
    pub name: String,
    /// Parent region id: another planned region, or the host amalgamation region.
    pub parent_region_id: String,
    /// Guest region properties to carry over (coordinate offset, designated IO remapped and
    /// filtered to imported areas). Never contains parent or membership keys.
    pub properties: HashMap<String, Value>,
}

/// Region tree to build for an amalgamated guest genome.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct AmalgamationRegionPlan {
    /// Sub-regions in parent-before-child order.
    pub sub_regions: Vec<AmalgamationRegionSpec>,
    /// Imported area (base64 id) -> region id it joins. Areas absent here belong to the host
    /// amalgamation region.
    pub area_region: HashMap<String, String>,
    /// Designated inputs for the host region (set only when exactly one guest top-level region
    /// maps onto it).
    pub host_designated_inputs: Vec<String>,
    /// Designated outputs for the host region (same rule as inputs).
    pub host_designated_outputs: Vec<String>,
    /// `port_encoding` entries for the host region's designated ports (same rule as inputs);
    /// empty when none.
    pub host_port_encoding: serde_json::Map<String, Value>,
    /// Guest region id -> region id it became in the host (the host amalgamation region id
    /// for the single top-level region). Guest regions outside the planned tree are absent.
    pub region_map: HashMap<String, String>,
}

fn guest_parent_id(region: &BrainRegion) -> Option<&str> {
    region
        .properties
        .get("parent_region_id")
        .and_then(|v| v.as_str())
        .map(str::trim)
        .filter(|p| !p.is_empty())
}

fn offset_coordinate_3d(value: Option<&Value>, origin: (i32, i32, i32)) -> Value {
    let get = |i: usize| -> i64 {
        value
            .and_then(|v| v.as_array())
            .and_then(|a| a.get(i))
            .and_then(|n| n.as_i64())
            .unwrap_or(0)
    };
    serde_json::json!([
        i64::from(origin.0).saturating_add(get(0)),
        i64::from(origin.1).saturating_add(get(1)),
        i64::from(origin.2).saturating_add(get(2)),
    ])
}

fn filtered_io(region: &BrainRegion, key: &str, member_area_ids: &HashSet<String>) -> Vec<String> {
    let mut list = json_string_list(region.properties.get(key));
    list.retain(|id| member_area_ids.contains(id));
    list
}

/// The region's `port_encoding` entries kept for the imported designated ports: the key must be
/// one of `designated` (already filtered to imported areas). Keys are already remapped.
fn filtered_port_encoding(
    region: &BrainRegion,
    designated: &[&[String]],
) -> serde_json::Map<String, Value> {
    let mut kept = serde_json::Map::new();
    if let Some(Value::Object(entries)) = region.properties.get(PORT_ENCODING_KEY) {
        for (area_id, entry) in entries {
            if designated.iter().any(|list| list.contains(area_id)) {
                kept.insert(area_id.clone(), entry.clone());
            }
        }
    }
    kept
}

/// Plan the guest region tree for amalgamation. Pure: no I/O, no host state.
///
/// Call after [`remap_guest_custom_memory_cortical_ids_for_amalgamation`] so membership and IO
/// lists already use the final area ids. `member_area_ids` are the imported areas (base64) that
/// may live inside the amalgamation tree (the caller excludes IPU/OPU, modulator and
/// already-present areas). Top-level rule (as in region export): the guest regions whose parent
/// is the guest root (or that have no known parent) are the top level. Exactly one maps onto
/// `host_region_id` (its designated IO is returned for the host region); several each become a
/// child of the host region. Guest nesting is kept. Areas listed in no region are not in
/// `area_region` and fall back to the host region.
pub fn plan_amalgamation_regions(
    genome: &RuntimeGenome,
    host_region_id: &str,
    origin: (i32, i32, i32),
    member_area_ids: &HashSet<String>,
) -> AmalgamationRegionPlan {
    use feagi_structures::genomic::brain_regions::ROOT_BRAIN_REGION_NAME;

    let regions = &genome.brain_regions;
    let root_ids: HashSet<&str> = regions
        .iter()
        .filter(|(_, r)| r.name == ROOT_BRAIN_REGION_NAME)
        .map(|(id, _)| id.as_str())
        .collect();

    // Children by parent, sorted by guest id for deterministic output.
    let mut children: HashMap<&str, Vec<&str>> = HashMap::new();
    let mut top_level: Vec<&str> = Vec::new();
    for (id, region) in regions {
        if root_ids.contains(id.as_str()) {
            continue;
        }
        match guest_parent_id(region) {
            Some(p) if p != id && root_ids.contains(p) => top_level.push(id),
            Some(p) if p != id && regions.contains_key(p) => {
                children.entry(p).or_default().push(id)
            }
            _ => top_level.push(id),
        }
    }
    top_level.sort_unstable();
    for list in children.values_mut() {
        list.sort_unstable();
    }

    let mut plan = AmalgamationRegionPlan::default();
    // guest region id -> new region id (host id for the single top-level region).
    let mut mapped: HashMap<&str, String> = HashMap::new();
    // Breadth-first order from the top level keeps parents before children.
    let mut queue: std::collections::VecDeque<&str> = top_level.iter().copied().collect();
    let single_top = top_level.len() == 1;
    let mut visited: HashSet<&str> = HashSet::new();

    while let Some(gid) = queue.pop_front() {
        if !visited.insert(gid) {
            continue;
        }
        let region = &regions[gid];
        let is_host = single_top && top_level[0] == gid;
        if is_host {
            mapped.insert(gid, host_region_id.to_string());
            plan.host_designated_inputs = filtered_io(region, "designated_inputs", member_area_ids);
            plan.host_designated_outputs =
                filtered_io(region, "designated_outputs", member_area_ids);
            plan.host_port_encoding = filtered_port_encoding(
                region,
                &[
                    plan.host_designated_inputs.as_slice(),
                    plan.host_designated_outputs.as_slice(),
                ],
            );
        } else {
            let parent_region_id = match guest_parent_id(region) {
                Some(p) if mapped.contains_key(p) => mapped[p].clone(),
                _ => host_region_id.to_string(),
            };
            let new_id = feagi_structures::genomic::brain_regions::RegionID::new().to_string();
            let mut properties: HashMap<String, Value> = HashMap::new();
            for (k, v) in &region.properties {
                match k.as_str() {
                    "parent_region_id" | "areas" | "cortical_areas" | "regions"
                    | "child_regions" | "coordinate_3d" | "inputs" | "outputs"
                    | "designated_inputs" | "designated_outputs" | PORT_ENCODING_KEY => {}
                    _ => {
                        properties.insert(k.clone(), v.clone());
                    }
                }
            }
            properties.insert(
                "coordinate_3d".to_string(),
                offset_coordinate_3d(region.properties.get("coordinate_3d"), origin),
            );
            let designated_inputs = filtered_io(region, "designated_inputs", member_area_ids);
            let designated_outputs = filtered_io(region, "designated_outputs", member_area_ids);
            let port_encoding = filtered_port_encoding(
                region,
                &[designated_inputs.as_slice(), designated_outputs.as_slice()],
            );
            for (key, list) in [
                ("designated_inputs", designated_inputs),
                ("designated_outputs", designated_outputs),
            ] {
                if !list.is_empty() {
                    properties.insert(key.to_string(), serde_json::json!(list));
                }
            }
            if !port_encoding.is_empty() {
                properties.insert(PORT_ENCODING_KEY.to_string(), Value::Object(port_encoding));
            }
            mapped.insert(gid, new_id.clone());
            plan.sub_regions.push(AmalgamationRegionSpec {
                region_id: new_id,
                name: region.name.clone(),
                parent_region_id,
                properties,
            });
        }
        if let Some(kids) = children.get(gid) {
            queue.extend(kids.iter().copied());
        }
    }

    // Area membership: guest region lists first (sorted for a stable pick when an area is listed
    // twice), then the area's own `parent_region_id` property.
    let mut guest_ids: Vec<&str> = mapped.keys().copied().collect();
    guest_ids.sort_unstable();
    for gid in guest_ids {
        let target = &mapped[gid];
        if target == host_region_id {
            continue;
        }
        let mut members: Vec<String> = regions[gid]
            .cortical_areas
            .iter()
            .map(|c| c.as_base_64())
            .collect();
        members.sort_unstable();
        for m in members {
            if member_area_ids.contains(&m) {
                plan.area_region.entry(m).or_insert_with(|| target.clone());
            }
        }
    }
    for area in genome.cortical_areas.values() {
        let b64 = area.cortical_id.as_base_64();
        if !member_area_ids.contains(&b64) || plan.area_region.contains_key(&b64) {
            continue;
        }
        if let Some(target) = area
            .properties
            .get("parent_region_id")
            .and_then(|v| v.as_str())
            .and_then(|p| mapped.get(p))
        {
            if target != host_region_id {
                plan.area_region.insert(b64, target.clone());
            }
        }
    }
    plan.region_map = mapped
        .iter()
        .map(|(guest, new)| ((*guest).to_string(), new.clone()))
        .collect();
    plan
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::random::random_bytes;
    use crate::runtime::{GenomeMetadata, GenomeSignatures, GenomeStats, PhysiologyConfig};
    use crate::MorphologyRegistry;
    use crate::RuntimeGenome;
    use feagi_structures::genomic::cortical_area::descriptors::CorticalAreaDimensions;
    use feagi_structures::genomic::cortical_area::CorticalArea;
    use feagi_structures::genomic::cortical_area::CustomCorticalType;
    use feagi_structures::genomic::descriptors::GenomeCoordinate3D;

    fn sample_custom_cortical_id() -> CorticalID {
        let mut bytes = [0u8; CorticalID::CORTICAL_ID_LENGTH];
        bytes[0] = b'c';
        random_bytes(&mut bytes[1..]);
        CorticalID::try_from_bytes(&bytes).expect("valid custom id")
    }

    #[test]
    fn remap_changes_custom_ids_when_host_reserves_them() {
        let old_id = sample_custom_cortical_id();
        let area = CorticalArea::new(
            old_id,
            0,
            "test-area".to_string(),
            CorticalAreaDimensions::new(1, 1, 1).expect("dims"),
            GenomeCoordinate3D::new(0, 0, 0),
            CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire),
        )
        .expect("area");

        let mut cortical_areas = HashMap::new();
        cortical_areas.insert(old_id, area);

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

        let mut host = HashSet::new();
        let sample_custom = old_id.as_base_64();
        host.insert(sample_custom.clone());

        let pairs = remap_guest_custom_memory_cortical_ids_for_amalgamation(&mut genome, &host)
            .expect("remap");

        assert!(
            pairs.contains_key(&sample_custom),
            "expected reserved custom id to be remapped"
        );
        let new_b64 = pairs.get(&sample_custom).unwrap();
        assert_ne!(new_b64, &sample_custom);
        assert!(
            genome
                .cortical_areas
                .keys()
                .any(|k| k.as_base_64() == *new_b64),
            "new id should appear as a cortical_areas key"
        );
        assert!(
            !genome
                .cortical_areas
                .contains_key(&CorticalID::try_from_base_64(&sample_custom).unwrap()),
            "old custom id should not remain as a key when remapped"
        );
    }

    #[test]
    fn cloned_circuit_designated_io_follows_remapped_area_ids() {
        use feagi_structures::genomic::brain_regions::{
            BrainRegion, RegionID, RegionType, ROOT_BRAIN_REGION_NAME,
        };

        let old_id = sample_custom_cortical_id();
        let old_b64 = old_id.as_base_64();
        let area = CorticalArea::new(
            old_id,
            0,
            "io-area".to_string(),
            CorticalAreaDimensions::new(1, 1, 1).expect("dims"),
            GenomeCoordinate3D::new(0, 0, 0),
            CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire),
        )
        .expect("area");

        let root_id = RegionID::new();
        let circuit_id = RegionID::new();
        let root_key = root_id.to_string();
        let circuit_key = circuit_id.to_string();
        let root = BrainRegion::new(
            root_id,
            ROOT_BRAIN_REGION_NAME.to_string(),
            RegionType::Undefined,
        )
        .expect("root");
        let mut circuit_props = HashMap::new();
        circuit_props.insert(
            "parent_region_id".to_string(),
            serde_json::json!(root_key.clone()),
        );
        circuit_props.insert(
            "designated_inputs".to_string(),
            serde_json::json!([old_b64.clone()]),
        );
        circuit_props.insert("designated_outputs".to_string(), serde_json::json!([]));
        let circuit = BrainRegion::new(circuit_id, "Circuit".to_string(), RegionType::Undefined)
            .expect("circuit")
            .with_areas([old_id])
            .with_properties(circuit_props);

        let mut brain_regions = HashMap::new();
        brain_regions.insert(root_key, root);
        brain_regions.insert(circuit_key, circuit);
        let mut cortical_areas = HashMap::new();
        cortical_areas.insert(old_id, area);

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

        let (inputs_before, _) = designated_io_lists_for_cloned_circuit(&genome);
        assert_eq!(inputs_before, vec![old_b64.clone()]);

        let mut host = HashSet::new();
        host.insert(old_b64.clone());
        let pairs = remap_guest_custom_memory_cortical_ids_for_amalgamation(&mut genome, &host)
            .expect("remap");
        let new_b64 = pairs.get(&old_b64).expect("remapped id");

        let (inputs_after, outputs_after) = designated_io_lists_for_cloned_circuit(&genome);
        assert_eq!(inputs_after, vec![new_b64.clone()]);
        assert!(outputs_after.is_empty());
        assert_ne!(inputs_after[0], old_b64);
    }

    fn plan_area(prefix: u8) -> CorticalArea {
        let mut bytes = [0u8; CorticalID::CORTICAL_ID_LENGTH];
        bytes[0] = prefix;
        random_bytes(&mut bytes[1..]);
        let id = CorticalID::try_from_bytes(&bytes).expect("id");
        let ty = if prefix == b'm' {
            CorticalAreaType::Memory(
                feagi_structures::genomic::cortical_area::MemoryCorticalType::Memory,
            )
        } else {
            CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire)
        };
        CorticalArea::new(
            id,
            0,
            "a".to_string(),
            CorticalAreaDimensions::new(1, 1, 1).expect("dims"),
            GenomeCoordinate3D::new(0, 0, 0),
            ty,
        )
        .expect("area")
    }

    fn plan_genome(areas: Vec<CorticalArea>, regions: Vec<(String, BrainRegion)>) -> RuntimeGenome {
        RuntimeGenome {
            metadata: GenomeMetadata {
                genome_id: "t".to_string(),
                genome_title: "t".to_string(),
                genome_description: "".to_string(),
                version: "3.0".to_string(),
                timestamp: 0.0,
                brain_regions_root: None,
            },
            cortical_areas: areas.into_iter().map(|a| (a.cortical_id, a)).collect(),
            brain_regions: regions.into_iter().collect(),
            classifiers: HashMap::new(),
            morphologies: MorphologyRegistry::new(),
            modulators: crate::modulators::ModulatorRegistry::new(),
            physiology: PhysiologyConfig::default(),
            signatures: GenomeSignatures {
                genome: String::new(),
                blueprint: String::new(),
                physiology: String::new(),
                morphologies: None,
            },
            stats: GenomeStats::default(),
            change_history: Vec::new(),
        }
    }

    fn plan_region(
        name: &str,
        parent: Option<&str>,
        areas: &[&CorticalArea],
        props: Vec<(&str, Value)>,
    ) -> (String, BrainRegion) {
        use feagi_structures::genomic::brain_regions::{RegionID, RegionType};
        let rid = RegionID::new();
        let mut p: HashMap<String, Value> = HashMap::new();
        if let Some(par) = parent {
            p.insert("parent_region_id".to_string(), serde_json::json!(par));
        }
        for (k, v) in props {
            p.insert(k.to_string(), v);
        }
        let r = BrainRegion::new(rid, name.to_string(), RegionType::Undefined)
            .expect("region")
            .with_areas(areas.iter().map(|a| a.cortical_id))
            .with_properties(p);
        (rid.to_string(), r)
    }

    fn all_ids(areas: &[&CorticalArea]) -> HashSet<String> {
        areas.iter().map(|a| a.cortical_id.as_base_64()).collect()
    }

    #[test]
    fn plan_nested_regions_with_memory_area_and_ordering() {
        use feagi_structures::genomic::brain_regions::{
            BrainRegion, RegionID, RegionType, ROOT_BRAIN_REGION_NAME,
        };
        let c1 = plan_area(b'c');
        let m1 = plan_area(b'm');
        let root_id = RegionID::new().to_string();
        let root = BrainRegion::new(
            RegionID::from_string(&root_id).unwrap(),
            ROOT_BRAIN_REGION_NAME.to_string(),
            RegionType::Undefined,
        )
        .unwrap();
        let (top_id, top) = plan_region("top", Some(&root_id), &[&c1], vec![]);
        let (mid_id, mid) = plan_region(
            "mid",
            Some(&top_id),
            &[&m1],
            vec![("coordinate_3d", serde_json::json!([3, 4, 5]))],
        );
        let g = plan_genome(
            vec![c1.clone(), m1.clone()],
            vec![(root_id, root), (top_id, top), (mid_id, mid)],
        );
        let host = "host-region";
        let plan = plan_amalgamation_regions(&g, host, (10, 20, 30), &all_ids(&[&c1, &m1]));
        // single top-level maps onto host; one sub-region (mid) under host
        assert_eq!(plan.sub_regions.len(), 1);
        let sub = &plan.sub_regions[0];
        assert_eq!(sub.name, "mid");
        assert_eq!(sub.parent_region_id, host);
        assert_eq!(
            sub.properties["coordinate_3d"],
            serde_json::json!([13, 24, 35])
        );
        assert_eq!(
            plan.area_region[&m1.cortical_id.as_base_64()],
            sub.region_id
        );
        assert!(!plan.area_region.contains_key(&c1.cortical_id.as_base_64()));
    }

    #[test]
    fn plan_three_levels_parent_before_child() {
        let a = plan_area(b'c');
        let (t, top) = plan_region("t", None, &[], vec![]);
        let (m, mid) = plan_region("m", Some(&t), &[], vec![]);
        let (l, leaf) = plan_region("l", Some(&m), &[&a], vec![]);
        let g = plan_genome(vec![a.clone()], vec![(l, leaf), (m, mid), (t, top)]);
        let plan = plan_amalgamation_regions(&g, "h", (0, 0, 0), &all_ids(&[&a]));
        let names: Vec<&str> = plan.sub_regions.iter().map(|s| s.name.as_str()).collect();
        assert_eq!(names, vec!["m", "l"]);
        assert_eq!(
            plan.sub_regions[1].parent_region_id,
            plan.sub_regions[0].region_id
        );
        assert_eq!(
            plan.area_region[&a.cortical_id.as_base_64()],
            plan.sub_regions[1].region_id
        );
    }

    #[test]
    fn plan_multiple_top_level_regions_become_children_of_host() {
        let a = plan_area(b'c');
        let b = plan_area(b'c');
        let (id1, r1) = plan_region(
            "one",
            None,
            &[&a],
            vec![(
                "designated_inputs",
                serde_json::json!([a.cortical_id.as_base_64()]),
            )],
        );
        let (id2, r2) = plan_region("two", None, &[&b], vec![]);
        let g = plan_genome(vec![a.clone(), b.clone()], vec![(id1, r1), (id2, r2)]);
        let plan = plan_amalgamation_regions(&g, "h", (0, 0, 0), &all_ids(&[&a, &b]));
        assert_eq!(plan.sub_regions.len(), 2);
        assert!(plan.sub_regions.iter().all(|s| s.parent_region_id == "h"));
        assert!(plan.host_designated_inputs.is_empty());
        let one = plan.sub_regions.iter().find(|s| s.name == "one").unwrap();
        assert_eq!(
            one.properties["designated_inputs"],
            serde_json::json!([a.cortical_id.as_base_64()])
        );
        assert_eq!(plan.area_region[&a.cortical_id.as_base_64()], one.region_id);
        assert_ne!(
            plan.area_region[&a.cortical_id.as_base_64()],
            plan.area_region[&b.cortical_id.as_base_64()]
        );
    }

    #[test]
    fn plan_area_in_no_region_falls_back_to_host() {
        let a = plan_area(b'c');
        let loose = plan_area(b'c');
        let (id1, r1) = plan_region("one", None, &[&a], vec![]);
        let (id2, r2) = plan_region("two", None, &[], vec![]);
        let g = plan_genome(vec![a.clone(), loose.clone()], vec![(id1, r1), (id2, r2)]);
        let plan = plan_amalgamation_regions(&g, "h", (0, 0, 0), &all_ids(&[&a, &loose]));
        assert!(!plan
            .area_region
            .contains_key(&loose.cortical_id.as_base_64()));
        assert!(plan.area_region.contains_key(&a.cortical_id.as_base_64()));
    }

    #[test]
    fn plan_nested_designated_io_is_remapped_and_filtered() {
        let a = plan_area(b'c');
        let outside = plan_area(b'c');
        let (t, top) = plan_region("t", None, &[], vec![]);
        let (m, mid) = plan_region(
            "m",
            Some(&t),
            &[&a],
            vec![
                (
                    "designated_inputs",
                    serde_json::json!([
                        a.cortical_id.as_base_64(),
                        outside.cortical_id.as_base_64()
                    ]),
                ),
                (
                    "designated_outputs",
                    serde_json::json!([a.cortical_id.as_base_64()]),
                ),
            ],
        );
        let mut g = plan_genome(vec![a.clone(), outside.clone()], vec![(t, top), (m, mid)]);
        // remap through the real remap so lists follow new ids
        let mut host = HashSet::new();
        host.insert(a.cortical_id.as_base_64());
        let pairs = remap_guest_custom_memory_cortical_ids_for_amalgamation(&mut g, &host).unwrap();
        let new_a = pairs
            .get(&a.cortical_id.as_base_64())
            .cloned()
            .expect("remapped");
        let members: HashSet<String> = [new_a.clone()].into_iter().collect();
        let plan = plan_amalgamation_regions(&g, "h", (0, 0, 0), &members);
        let sub = &plan.sub_regions[0];
        assert_eq!(
            sub.properties["designated_inputs"],
            serde_json::json!([new_a.clone()])
        );
        assert_eq!(
            sub.properties["designated_outputs"],
            serde_json::json!([new_a])
        );
    }

    #[test]
    fn plan_flat_single_region_maps_to_host_without_sub_regions() {
        let a = plan_area(b'c');
        let (id1, r1) = plan_region(
            "only",
            None,
            &[&a],
            vec![(
                "designated_inputs",
                serde_json::json!([a.cortical_id.as_base_64()]),
            )],
        );
        let g = plan_genome(vec![a.clone()], vec![(id1, r1)]);
        let plan = plan_amalgamation_regions(&g, "h", (0, 0, 0), &all_ids(&[&a]));
        assert!(plan.sub_regions.is_empty());
        assert!(plan.area_region.is_empty());
        assert_eq!(
            plan.host_designated_inputs,
            vec![a.cortical_id.as_base_64()]
        );
    }

    #[test]
    fn plan_tree_survives_save_and_reload() {
        use feagi_structures::genomic::brain_regions::{
            BrainRegion, RegionID, RegionType, ROOT_BRAIN_REGION_NAME,
        };
        let a = plan_area(b'c');
        let b = plan_area(b'm');
        let (t, top) = plan_region("t", None, &[&a], vec![]);
        let (m, mid) = plan_region("m", Some(&t), &[&b], vec![]);
        let guest = plan_genome(vec![a.clone(), b.clone()], vec![(t, top), (m, mid)]);

        // Host: root -> amalgamation region, then execute the plan as the API handler does.
        let root_id = RegionID::new();
        let host_id = RegionID::new();
        let root_key = root_id.to_string();
        let host_key = host_id.to_string();
        let root = BrainRegion::new(
            root_id,
            ROOT_BRAIN_REGION_NAME.to_string(),
            RegionType::Undefined,
        )
        .unwrap();
        let mut host_props = HashMap::new();
        host_props.insert(
            "parent_region_id".to_string(),
            serde_json::json!(root_key.clone()),
        );
        let host_region = BrainRegion::new(host_id, "host".to_string(), RegionType::Undefined)
            .unwrap()
            .with_properties(host_props);
        let members = all_ids(&[&a, &b]);
        let plan = plan_amalgamation_regions(&guest, &host_key, (0, 0, 0), &members);
        let mut regions: Vec<(String, BrainRegion)> =
            vec![(root_key, root), (host_key.clone(), host_region)];
        for spec in &plan.sub_regions {
            let mut props = spec.properties.clone();
            props.insert(
                "parent_region_id".to_string(),
                serde_json::json!(spec.parent_region_id),
            );
            let r = BrainRegion::new(
                RegionID::from_string(&spec.region_id).unwrap(),
                spec.name.clone(),
                RegionType::Undefined,
            )
            .unwrap()
            .with_properties(props);
            regions.push((spec.region_id.clone(), r));
        }
        let mut host_areas = Vec::new();
        for src in [&a, &b] {
            let mut area = src.clone();
            let target = plan
                .area_region
                .get(&src.cortical_id.as_base_64())
                .cloned()
                .unwrap_or_else(|| host_key.clone());
            area.properties.insert(
                "parent_region_id".to_string(),
                serde_json::json!(target.clone()),
            );
            for (id, r) in regions.iter_mut() {
                if *id == target {
                    r.add_area(src.cortical_id);
                }
            }
            host_areas.push(area);
        }
        let genome = plan_genome(host_areas, regions);

        let json = crate::genome::runtime_saver::save_genome_to_json(&genome).expect("save");
        let reloaded = crate::load_genome_from_json(&json).expect("reload");
        let sub = &plan.sub_regions[0];
        let r = reloaded
            .brain_regions
            .get(&sub.region_id)
            .expect("sub-region persisted");
        assert_eq!(r.name, "m");
        assert_eq!(
            r.properties
                .get("parent_region_id")
                .and_then(|v| v.as_str()),
            Some(host_key.as_str())
        );
        assert!(r.contains_area(&b.cortical_id));
    }

    fn wiring_entry() -> Value {
        serde_json::json!({
            "kind": "Boolean", "signed": false, "frame": null, "positioning": null,
            "source": "wiring"
        })
    }

    #[test]
    fn remap_region_io_lists_remaps_port_encoding_keys() {
        use feagi_structures::genomic::brain_regions::{RegionID, RegionType};
        let mut region =
            BrainRegion::new(RegionID::new(), "r".to_string(), RegionType::Undefined).unwrap();
        region.properties.insert(
            PORT_ENCODING_KEY.to_string(),
            serde_json::json!({"old_a": wiring_entry(), "kept_b": wiring_entry()}),
        );
        let remap: HashMap<String, String> = [("old_a".to_string(), "new_a".to_string())].into();
        remap_region_io_lists(&mut region, &remap);
        assert_eq!(
            region.properties[PORT_ENCODING_KEY],
            serde_json::json!({"new_a": wiring_entry(), "kept_b": wiring_entry()})
        );
    }

    #[test]
    fn amalgamation_remaps_port_encoding_keys_and_plan_carries_them() {
        let a = plan_area(b'c');
        let outside = plan_area(b'c');
        let (t, top) = plan_region("t", None, &[], vec![]);
        let (m, mid) = plan_region(
            "m",
            Some(&t),
            &[&a],
            vec![
                (
                    "designated_inputs",
                    serde_json::json!([a.cortical_id.as_base_64()]),
                ),
                (
                    PORT_ENCODING_KEY,
                    serde_json::json!({
                        a.cortical_id.as_base_64(): wiring_entry(),
                        outside.cortical_id.as_base_64(): wiring_entry(),
                    }),
                ),
            ],
        );
        let mut g = plan_genome(vec![a.clone(), outside.clone()], vec![(t, top), (m, mid)]);
        let mut host = HashSet::new();
        host.insert(a.cortical_id.as_base_64());
        let pairs = remap_guest_custom_memory_cortical_ids_for_amalgamation(&mut g, &host).unwrap();
        let new_a = pairs[&a.cortical_id.as_base_64()].clone();
        let members: HashSet<String> = [new_a.clone()].into_iter().collect();
        let plan = plan_amalgamation_regions(&g, "h", (0, 0, 0), &members);
        // Sub-region copy: key remapped, entry for the non-imported area dropped.
        assert_eq!(
            plan.sub_regions[0].properties[PORT_ENCODING_KEY],
            serde_json::json!({ new_a.clone(): wiring_entry() })
        );
    }

    #[test]
    fn plan_host_region_carries_port_encoding_of_its_designated_ports() {
        let a = plan_area(b'c');
        let b = plan_area(b'c');
        let (id1, r1) = plan_region(
            "only",
            None,
            &[&a, &b],
            vec![
                (
                    "designated_inputs",
                    serde_json::json!([a.cortical_id.as_base_64()]),
                ),
                (
                    PORT_ENCODING_KEY,
                    serde_json::json!({
                        a.cortical_id.as_base_64(): wiring_entry(),
                        b.cortical_id.as_base_64(): wiring_entry(),
                    }),
                ),
            ],
        );
        let g = plan_genome(vec![a.clone(), b.clone()], vec![(id1, r1)]);
        let plan = plan_amalgamation_regions(&g, "h", (0, 0, 0), &all_ids(&[&a, &b]));
        // Only the designated port keeps an entry.
        assert_eq!(plan.host_port_encoding.len(), 1);
        assert_eq!(
            plan.host_port_encoding[&a.cortical_id.as_base_64()],
            wiring_entry()
        );
    }
}

#[cfg(test)]
mod rename_runtime_genome_areas_tests {
    use super::*;
    use crate::runtime::{GenomeMetadata, GenomeSignatures, GenomeStats, MorphologyRegistry};
    use feagi_structures::genomic::brain_regions::{RegionID, RegionType};
    use feagi_structures::genomic::cortical_area::{
        CorticalAreaDimensions, IOCorticalAreaConfigurationFlag,
    };

    fn io(group: u16) -> CorticalID {
        IOCorticalAreaConfigurationFlag::Boolean.as_io_cortical_id(
            true,
            *b"tst",
            group.into(),
            0u8.into(),
        )
    }

    fn area(id: CorticalID) -> CorticalArea {
        CorticalArea::new(
            id,
            0,
            "a".to_string(),
            CorticalAreaDimensions::new(1, 1, 1).unwrap(),
            (0, 0, 0).into(),
            CorticalAreaType::BrainInput(IOCorticalAreaConfigurationFlag::Boolean),
        )
        .unwrap()
    }

    fn genome() -> RuntimeGenome {
        let mut genome = RuntimeGenome {
            metadata: GenomeMetadata {
                genome_id: "g".to_string(),
                genome_title: "g".to_string(),
                genome_description: String::new(),
                version: "3.0".to_string(),
                timestamp: 0.0,
                brain_regions_root: None,
            },
            cortical_areas: HashMap::new(),
            brain_regions: HashMap::new(),
            classifiers: HashMap::new(),
            morphologies: MorphologyRegistry::new(),
            modulators: crate::modulators::ModulatorRegistry::new(),
            physiology: Default::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 (a, b) = (io(1), io(2));
        let mut first = area(a);
        first.properties.insert(
            "cortical_mapping_dst".to_string(),
            serde_json::json!({ b.as_base_64(): [{ "gate_source_area": a.as_base_64() }] }),
        );
        first.properties.insert(
            "memory_twin_of".to_string(),
            serde_json::json!(b.as_base_64()),
        );
        genome.cortical_areas.insert(a, first);
        genome.cortical_areas.insert(b, area(b));
        let mut region =
            BrainRegion::new(RegionID::new(), "r".to_string(), RegionType::Undefined).unwrap();
        region.cortical_areas.insert(a);
        region.properties.insert(
            "designated_inputs".to_string(),
            serde_json::json!([a.as_base_64()]),
        );
        genome.brain_regions.insert("r".to_string(), region);
        genome
    }

    #[test]
    fn occupied_target_leaves_the_genome_unchanged() {
        let mut g = genome();
        let snapshot = |g: &RuntimeGenome| {
            let mut areas: Vec<(String, String)> = g
                .cortical_areas
                .iter()
                .map(|(id, a)| {
                    (
                        id.as_base_64(),
                        format!(
                            "{:?}",
                            a.properties
                                .iter()
                                .collect::<std::collections::BTreeMap<_, _>>()
                        ),
                    )
                })
                .collect();
            areas.sort();
            (
                areas,
                format!(
                    "{:?}",
                    g.brain_regions["r"]
                        .properties
                        .iter()
                        .collect::<std::collections::BTreeMap<_, _>>()
                ),
            )
        };
        let before = snapshot(&g);
        assert!(rename_runtime_genome_areas(&mut g, &[(io(1), io(2))]).is_err());
        assert_eq!(before, snapshot(&g));
    }

    #[test]
    fn swap_rekeys_areas_and_every_reference() {
        let mut g = genome();
        rename_runtime_genome_areas(&mut g, &[(io(1), io(2)), (io(2), io(1))]).unwrap();
        // The area that carried the references is now at io(2); they point at the swapped ids.
        let moved = &g.cortical_areas[&io(2)];
        assert_eq!(moved.cortical_id, io(2));
        assert_eq!(
            moved.properties["memory_twin_of"],
            serde_json::json!(io(1).as_base_64())
        );
        assert_eq!(
            moved.properties["cortical_mapping_dst"][io(1).as_base_64()][0]["gate_source_area"],
            serde_json::json!(io(2).as_base_64())
        );
        let region = &g.brain_regions["r"];
        assert!(region.cortical_areas.contains(&io(2)) && !region.cortical_areas.contains(&io(1)));
        assert_eq!(
            region.properties["designated_inputs"],
            serde_json::json!([io(2).as_base_64()])
        );
    }
}