Skip to main content

feagi_evolutionary/
amalgamation_remap.rs

1// Copyright 2025 Neuraville Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4/*!
5Remap **Custom** and **Memory** cortical IDs on an imported guest genome so they do not collide
6with the host connectome.
7
8Core (`___death`, `___power`, `___fatig`, `___pain_`, `___pleas`, `___fear_`, `___hope_`) and IPU/OPU identifiers are **not** remapped: they are
9canonical and must continue to match the host’s shared IO and core regions.
10
11Copyright 2025 Neuraville Inc.
12Licensed under the Apache License, Version 2.0
13*/
14
15use crate::random::random_bytes;
16use crate::runtime::RuntimeGenome;
17use feagi_structures::genomic::brain_regions::PORT_ENCODING_KEY;
18use feagi_structures::genomic::cortical_area::CorticalArea;
19use feagi_structures::genomic::cortical_area::CorticalAreaType;
20use feagi_structures::genomic::cortical_area::CorticalID;
21use feagi_structures::genomic::BrainRegion;
22use feagi_structures::FeagiDataError;
23use serde_json::Value;
24use std::collections::{HashMap, HashSet};
25
26const MAX_ID_ALLOC_ATTEMPTS: u32 = 100_000;
27
28/// Allocate a new cortical ID with the given first-byte prefix (`c` or `m`), distinct from
29/// `reserved` (inserts the chosen ID into `reserved`).
30fn allocate_unique_typed_id(
31    prefix: u8,
32    reserved: &mut HashSet<String>,
33) -> Result<CorticalID, FeagiDataError> {
34    for _ in 0..MAX_ID_ALLOC_ATTEMPTS {
35        let mut bytes = [0u8; CorticalID::CORTICAL_ID_LENGTH];
36        bytes[0] = prefix;
37        random_bytes(&mut bytes[1..]);
38        if let Ok(id) = CorticalID::try_from_bytes(&bytes) {
39            let s = id.as_base_64();
40            if !reserved.contains(&s) {
41                reserved.insert(s);
42                return Ok(id);
43            }
44        }
45    }
46    Err(FeagiDataError::InternalError(
47        "Failed to allocate a unique cortical ID for amalgamation remapping".into(),
48    ))
49}
50
51/// Rewrite the base64 area ids in a region's `inputs`, `outputs`, `designated_inputs` and
52/// `designated_outputs` property lists, and the keys of its `port_encoding` map.
53pub fn remap_region_io_lists(region: &mut BrainRegion, b64_remap: &HashMap<String, String>) {
54    if let Some(Value::Object(entries)) = region.properties.get_mut(PORT_ENCODING_KEY) {
55        let taken = std::mem::take(entries);
56        for (area_id, entry) in taken {
57            let new_id = b64_remap.get(&area_id).cloned().unwrap_or(area_id);
58            entries.insert(new_id, entry);
59        }
60    }
61    for key in [
62        "inputs",
63        "outputs",
64        "designated_inputs",
65        "designated_outputs",
66    ] {
67        let Some(val) = region.properties.get_mut(key) else {
68            continue;
69        };
70        let Some(arr) = val.as_array_mut() else {
71            continue;
72        };
73        for item in arr.iter_mut() {
74            if let Some(s) = item.as_str() {
75                if let Some(n) = b64_remap.get(s) {
76                    *item = Value::String(n.clone());
77                }
78            }
79        }
80    }
81}
82
83/// Mapping-rule fields that hold another area's base64 id.
84const RULE_AREA_ID_KEYS: [&str; 3] = [
85    "gate_source_area",
86    "reward_source_area",
87    "punishment_source_area",
88];
89
90fn remap_cortical_mapping_dst_keys(
91    properties: &mut HashMap<String, Value>,
92    b64_remap: &HashMap<String, String>,
93) {
94    let Some(Value::Object(dstmap)) = properties.get_mut("cortical_mapping_dst") else {
95        return;
96    };
97    let taken = std::mem::take(dstmap);
98    let mut new_map = serde_json::Map::new();
99    for (k, mut v) in taken {
100        let nk = b64_remap.get(&k).cloned().unwrap_or(k);
101        if let Value::Array(rules) = &mut v {
102            for rule in rules.iter_mut() {
103                let Value::Object(rule) = rule else { continue };
104                for key in RULE_AREA_ID_KEYS {
105                    if let Some(Value::String(id)) = rule.get_mut(key) {
106                        remap_id(id, b64_remap);
107                    }
108                }
109            }
110        }
111        new_map.insert(nk, v);
112    }
113    properties.insert("cortical_mapping_dst".to_string(), Value::Object(new_map));
114}
115
116/// Remap guest **Custom** and **Memory** cortical IDs to fresh values not present in
117/// `host_reserved_base64_ids` or elsewhere in this guest genome. Updates cortical area keys,
118/// `cortical_mapping_dst` destination keys, brain region membership, and region IO lists.
119///
120/// Returns `(old_base64, new_base64)` pairs only for IDs that changed.
121pub fn remap_guest_custom_memory_cortical_ids_for_amalgamation(
122    genome: &mut RuntimeGenome,
123    host_reserved_base64_ids: &HashSet<String>,
124) -> Result<HashMap<String, String>, FeagiDataError> {
125    let mut reserved: HashSet<String> = host_reserved_base64_ids.clone();
126    for id in genome.cortical_areas.keys() {
127        reserved.insert(id.as_base_64());
128    }
129
130    let mut id_remap: HashMap<CorticalID, CorticalID> = HashMap::new();
131
132    for (old_id, area) in genome.cortical_areas.iter() {
133        let needs_remapping = matches!(
134            &area.cortical_type,
135            CorticalAreaType::Custom(_) | CorticalAreaType::Memory(_)
136        );
137        if !needs_remapping {
138            continue;
139        }
140        let prefix = old_id.as_bytes()[0];
141        let new_id = allocate_unique_typed_id(prefix, &mut reserved)?;
142        id_remap.insert(*old_id, new_id);
143    }
144
145    let mut b64_remap: HashMap<String, String> = HashMap::new();
146    for (old_id, new_id) in &id_remap {
147        let ob = old_id.as_base_64();
148        let nb = new_id.as_base_64();
149        if ob != nb {
150            b64_remap.insert(ob, nb);
151        }
152    }
153
154    if id_remap.is_empty() {
155        return Ok(b64_remap);
156    }
157
158    // Re-key cortical_areas and refresh each area's `cortical_id`.
159    let mut new_areas: HashMap<CorticalID, CorticalArea> =
160        HashMap::with_capacity(genome.cortical_areas.len());
161    for (old_id, mut area) in std::mem::take(&mut genome.cortical_areas) {
162        let new_id = id_remap.get(&old_id).copied().unwrap_or(old_id);
163        area.cortical_id = new_id;
164        new_areas.insert(new_id, area);
165    }
166    genome.cortical_areas = new_areas;
167
168    for region in genome.brain_regions.values_mut() {
169        let mut new_set: HashSet<CorticalID> = HashSet::with_capacity(region.cortical_areas.len());
170        for cid in region.cortical_areas.drain() {
171            let nid = id_remap.get(&cid).copied().unwrap_or(cid);
172            new_set.insert(nid);
173        }
174        region.cortical_areas = new_set;
175        remap_region_io_lists(region, &b64_remap);
176    }
177
178    rewrite_area_references(genome, &b64_remap);
179
180    Ok(b64_remap)
181}
182
183/// Area property keys whose string value is another area id (classifier assembly links).
184const AREA_ID_PROPERTY_KEYS: [&str; 3] = [
185    "classifier_class_memory_id",
186    "classifier_sample_memory_id",
187    "classifier_error_area_id",
188];
189
190fn remap_id(id: &mut String, b64_remap: &HashMap<String, String>) {
191    if let Some(new_id) = b64_remap.get(id.as_str()) {
192        *id = new_id.clone();
193    }
194}
195
196/// Rewrite every area id held inside one area's properties (`old base64 -> new base64`):
197/// `cortical_mapping_dst` destination keys and the `*_source_area` fields of their rules,
198/// classifier assembly links, and the memory-twin properties (`memory_twin_areas` keys and
199/// values, `memory_twin_of`, `memory_twin_for`).
200///
201/// This is the one place that knows which area properties carry area ids; the genome store and
202/// the live connectome both call it.
203pub fn rewrite_area_properties(
204    properties: &mut HashMap<String, Value>,
205    b64_remap: &HashMap<String, String>,
206) {
207    if b64_remap.is_empty() {
208        return;
209    }
210    remap_cortical_mapping_dst_keys(properties, b64_remap);
211    for key in AREA_ID_PROPERTY_KEYS
212        .iter()
213        .chain(["memory_twin_of", "memory_twin_for"].iter())
214    {
215        if let Some(Value::String(id)) = properties.get_mut(*key) {
216            remap_id(id, b64_remap);
217        }
218    }
219    if let Some(Value::Object(twins)) = properties.get_mut("memory_twin_areas") {
220        let taken = std::mem::take(twins);
221        for (source, twin) in taken {
222            let new_source = b64_remap.get(&source).cloned().unwrap_or(source);
223            let new_twin = match twin {
224                Value::String(id) => Value::String(b64_remap.get(&id).cloned().unwrap_or(id)),
225                other => other,
226            };
227            twins.insert(new_source, new_twin);
228        }
229    }
230}
231
232/// Rename areas in a genome in place: area keys, `cortical_id` fields, region membership and
233/// region IO lists, and every id-bearing property (see [`rewrite_area_properties`]), classifier
234/// fields and modulator drivers. `renames` is a set of simultaneous `(old, new)` pairs, so a swap
235/// of two ids is allowed. Neuron data is not touched.
236///
237/// Fails, leaving the genome unchanged, when an old id is missing, a new id repeats, or a new id
238/// is taken by an area that is not itself renamed.
239pub fn rename_runtime_genome_areas(
240    genome: &mut RuntimeGenome,
241    renames: &[(CorticalID, CorticalID)],
242) -> Result<(), FeagiDataError> {
243    let id_remap: HashMap<CorticalID, CorticalID> = renames.iter().copied().collect();
244    if id_remap.len() != renames.len() {
245        return Err(FeagiDataError::BadParameters(
246            "rename lists the same source area twice".into(),
247        ));
248    }
249    let mut targets: HashSet<CorticalID> = HashSet::new();
250    for (old, new) in renames {
251        if !genome.cortical_areas.contains_key(old) {
252            return Err(FeagiDataError::BadParameters(format!(
253                "cortical area {} does not exist",
254                old.as_base_64()
255            )));
256        }
257        if !targets.insert(*new) {
258            return Err(FeagiDataError::BadParameters(format!(
259                "target id {} is used twice",
260                new.as_base_64()
261            )));
262        }
263        if genome.cortical_areas.contains_key(new) && !id_remap.contains_key(new) {
264            return Err(FeagiDataError::BadParameters(format!(
265                "target id {} is already taken",
266                new.as_base_64()
267            )));
268        }
269    }
270    let b64_remap: HashMap<String, String> = renames
271        .iter()
272        .filter(|(old, new)| old != new)
273        .map(|(old, new)| (old.as_base_64(), new.as_base_64()))
274        .collect();
275    if b64_remap.is_empty() {
276        return Ok(());
277    }
278    // Phase 1 removes every renamed area, phase 2 inserts them under the new ids.
279    let mut moved: Vec<CorticalArea> = Vec::with_capacity(renames.len());
280    for (old, new) in renames {
281        if let Some(mut area) = genome.cortical_areas.remove(old) {
282            area.cortical_id = *new;
283            moved.push(area);
284        }
285    }
286    for area in moved {
287        genome.cortical_areas.insert(area.cortical_id, area);
288    }
289    for region in genome.brain_regions.values_mut() {
290        let members: Vec<CorticalID> = region.cortical_areas.drain().collect();
291        for cid in members {
292            region
293                .cortical_areas
294                .insert(id_remap.get(&cid).copied().unwrap_or(cid));
295        }
296        remap_region_io_lists(region, &b64_remap);
297    }
298    rewrite_area_references(genome, &b64_remap);
299    Ok(())
300}
301
302/// Apply an area-id remap (`old base64 -> new base64`) to every place a guest genome refers to
303/// an area by id other than the area key itself: `cortical_mapping_dst` destination keys, area
304/// properties that link classifier assembly areas and memory twins, adopted modulator drivers
305/// and classifier area fields.
306pub(crate) fn rewrite_area_references(
307    genome: &mut RuntimeGenome,
308    b64_remap: &HashMap<String, String>,
309) {
310    if b64_remap.is_empty() {
311        return;
312    }
313    for area in genome.cortical_areas.values_mut() {
314        rewrite_area_properties(&mut area.properties, b64_remap);
315    }
316    for id in genome.modulators.ids() {
317        let Some(instance) = genome.modulators.get_mut(&id) else {
318            continue;
319        };
320        if let Some(new_id) = b64_remap
321            .get(&instance.driver_cortical_id.as_base_64())
322            .and_then(|new_id| CorticalID::try_from_base_64(new_id).ok())
323        {
324            instance.driver_cortical_id = new_id;
325        }
326    }
327    for classifier in genome.classifiers.values_mut() {
328        remap_classifier_area_fields(classifier, b64_remap);
329    }
330}
331
332/// Remap every area id a classifier record holds.
333pub fn remap_classifier_area_fields(
334    classifier: &mut feagi_structures::genomic::classifiers::Classifier,
335    b64_remap: &HashMap<String, String>,
336) {
337    remap_id(&mut classifier.sample_memory_id, b64_remap);
338    remap_id(&mut classifier.class_memory_id, b64_remap);
339    remap_id(&mut classifier.error_area_id, b64_remap);
340    remap_id(&mut classifier.correct_area_id, b64_remap);
341    for id in classifier.sample_area_ids.iter_mut() {
342        remap_id(id, b64_remap);
343    }
344    for binding in classifier.class_bindings.iter_mut() {
345        remap_id(&mut binding.class_area_id, b64_remap);
346        remap_id(&mut binding.class_output_area_id, b64_remap);
347    }
348    for id in [
349        &mut classifier.answer_feedback_area_id,
350        &mut classifier.learn_area_id,
351        &mut classifier.confidence_area_id,
352    ]
353    .into_iter()
354    .flatten()
355    {
356        remap_id(id, b64_remap);
357    }
358}
359
360/// Re-key guest modulator driver areas after their instances were created in the host
361/// (`old base64 -> new base64`, including drivers of reused host modulators), and rewrite every
362/// reference to them (mapping destinations, classifier fields, region membership).
363pub fn apply_driver_remap(
364    genome: &mut RuntimeGenome,
365    driver_remap: &HashMap<String, String>,
366) -> Result<(), FeagiDataError> {
367    if driver_remap.is_empty() {
368        return Ok(());
369    }
370    let mut id_remap: HashMap<CorticalID, CorticalID> = HashMap::new();
371    for (old, new) in driver_remap {
372        id_remap.insert(
373            CorticalID::try_from_base_64(old)?,
374            CorticalID::try_from_base_64(new)?,
375        );
376    }
377    let mut new_areas: HashMap<CorticalID, CorticalArea> =
378        HashMap::with_capacity(genome.cortical_areas.len());
379    for (old_id, mut area) in std::mem::take(&mut genome.cortical_areas) {
380        let new_id = id_remap.get(&old_id).copied().unwrap_or(old_id);
381        area.cortical_id = new_id;
382        new_areas.insert(new_id, area);
383    }
384    genome.cortical_areas = new_areas;
385    for region in genome.brain_regions.values_mut() {
386        let members: Vec<CorticalID> = region.cortical_areas.drain().collect();
387        for cid in members {
388            region
389                .cortical_areas
390                .insert(id_remap.get(&cid).copied().unwrap_or(cid));
391        }
392        remap_region_io_lists(region, driver_remap);
393    }
394    rewrite_area_references(genome, driver_remap);
395    Ok(())
396}
397
398fn json_string_list(value: Option<&Value>) -> Vec<String> {
399    value
400        .and_then(|v| v.as_array())
401        .map(|arr| {
402            arr.iter()
403                .filter_map(|item| item.as_str().map(str::to_string))
404                .collect()
405        })
406        .unwrap_or_default()
407}
408
409/// Declared region IO on the circuit that region-export wrapped under `Root Brain Region`.
410///
411/// Amalgamation hosts that circuit in a new region. These lists are already remapped to the
412/// guest cortical IDs and must be copied onto that new region or the clone drops input/output roles.
413pub fn designated_io_lists_for_cloned_circuit(
414    genome: &RuntimeGenome,
415) -> (Vec<String>, Vec<String>) {
416    use feagi_structures::genomic::brain_regions::ROOT_BRAIN_REGION_NAME;
417
418    let root_ids: HashSet<String> = genome
419        .brain_regions
420        .iter()
421        .filter(|(_, region)| region.name == ROOT_BRAIN_REGION_NAME)
422        .map(|(id, _)| id.clone())
423        .collect();
424
425    let circuit = genome.brain_regions.values().find(|region| {
426        let parent = region
427            .properties
428            .get("parent_region_id")
429            .and_then(|v| v.as_str())
430            .unwrap_or("");
431        if !root_ids.is_empty() {
432            root_ids.contains(parent)
433        } else {
434            parent.is_empty() && region.name != ROOT_BRAIN_REGION_NAME
435        }
436    });
437
438    let Some(region) = circuit else {
439        return (Vec::new(), Vec::new());
440    };
441    (
442        json_string_list(region.properties.get("designated_inputs")),
443        json_string_list(region.properties.get("designated_outputs")),
444    )
445}
446
447/// One sub-region to create under the amalgamation host region.
448#[derive(Debug, Clone, PartialEq)]
449pub struct AmalgamationRegionSpec {
450    /// Fresh region id (UUID string) for the new region.
451    pub region_id: String,
452    /// Guest region name.
453    pub name: String,
454    /// Parent region id: another planned region, or the host amalgamation region.
455    pub parent_region_id: String,
456    /// Guest region properties to carry over (coordinate offset, designated IO remapped and
457    /// filtered to imported areas). Never contains parent or membership keys.
458    pub properties: HashMap<String, Value>,
459}
460
461/// Region tree to build for an amalgamated guest genome.
462#[derive(Debug, Clone, Default, PartialEq)]
463pub struct AmalgamationRegionPlan {
464    /// Sub-regions in parent-before-child order.
465    pub sub_regions: Vec<AmalgamationRegionSpec>,
466    /// Imported area (base64 id) -> region id it joins. Areas absent here belong to the host
467    /// amalgamation region.
468    pub area_region: HashMap<String, String>,
469    /// Designated inputs for the host region (set only when exactly one guest top-level region
470    /// maps onto it).
471    pub host_designated_inputs: Vec<String>,
472    /// Designated outputs for the host region (same rule as inputs).
473    pub host_designated_outputs: Vec<String>,
474    /// `port_encoding` entries for the host region's designated ports (same rule as inputs);
475    /// empty when none.
476    pub host_port_encoding: serde_json::Map<String, Value>,
477    /// Guest region id -> region id it became in the host (the host amalgamation region id
478    /// for the single top-level region). Guest regions outside the planned tree are absent.
479    pub region_map: HashMap<String, String>,
480}
481
482fn guest_parent_id(region: &BrainRegion) -> Option<&str> {
483    region
484        .properties
485        .get("parent_region_id")
486        .and_then(|v| v.as_str())
487        .map(str::trim)
488        .filter(|p| !p.is_empty())
489}
490
491fn offset_coordinate_3d(value: Option<&Value>, origin: (i32, i32, i32)) -> Value {
492    let get = |i: usize| -> i64 {
493        value
494            .and_then(|v| v.as_array())
495            .and_then(|a| a.get(i))
496            .and_then(|n| n.as_i64())
497            .unwrap_or(0)
498    };
499    serde_json::json!([
500        i64::from(origin.0).saturating_add(get(0)),
501        i64::from(origin.1).saturating_add(get(1)),
502        i64::from(origin.2).saturating_add(get(2)),
503    ])
504}
505
506fn filtered_io(region: &BrainRegion, key: &str, member_area_ids: &HashSet<String>) -> Vec<String> {
507    let mut list = json_string_list(region.properties.get(key));
508    list.retain(|id| member_area_ids.contains(id));
509    list
510}
511
512/// The region's `port_encoding` entries kept for the imported designated ports: the key must be
513/// one of `designated` (already filtered to imported areas). Keys are already remapped.
514fn filtered_port_encoding(
515    region: &BrainRegion,
516    designated: &[&[String]],
517) -> serde_json::Map<String, Value> {
518    let mut kept = serde_json::Map::new();
519    if let Some(Value::Object(entries)) = region.properties.get(PORT_ENCODING_KEY) {
520        for (area_id, entry) in entries {
521            if designated.iter().any(|list| list.contains(area_id)) {
522                kept.insert(area_id.clone(), entry.clone());
523            }
524        }
525    }
526    kept
527}
528
529/// Plan the guest region tree for amalgamation. Pure: no I/O, no host state.
530///
531/// Call after [`remap_guest_custom_memory_cortical_ids_for_amalgamation`] so membership and IO
532/// lists already use the final area ids. `member_area_ids` are the imported areas (base64) that
533/// may live inside the amalgamation tree (the caller excludes IPU/OPU, modulator and
534/// already-present areas). Top-level rule (as in region export): the guest regions whose parent
535/// is the guest root (or that have no known parent) are the top level. Exactly one maps onto
536/// `host_region_id` (its designated IO is returned for the host region); several each become a
537/// child of the host region. Guest nesting is kept. Areas listed in no region are not in
538/// `area_region` and fall back to the host region.
539pub fn plan_amalgamation_regions(
540    genome: &RuntimeGenome,
541    host_region_id: &str,
542    origin: (i32, i32, i32),
543    member_area_ids: &HashSet<String>,
544) -> AmalgamationRegionPlan {
545    use feagi_structures::genomic::brain_regions::ROOT_BRAIN_REGION_NAME;
546
547    let regions = &genome.brain_regions;
548    let root_ids: HashSet<&str> = regions
549        .iter()
550        .filter(|(_, r)| r.name == ROOT_BRAIN_REGION_NAME)
551        .map(|(id, _)| id.as_str())
552        .collect();
553
554    // Children by parent, sorted by guest id for deterministic output.
555    let mut children: HashMap<&str, Vec<&str>> = HashMap::new();
556    let mut top_level: Vec<&str> = Vec::new();
557    for (id, region) in regions {
558        if root_ids.contains(id.as_str()) {
559            continue;
560        }
561        match guest_parent_id(region) {
562            Some(p) if p != id && root_ids.contains(p) => top_level.push(id),
563            Some(p) if p != id && regions.contains_key(p) => {
564                children.entry(p).or_default().push(id)
565            }
566            _ => top_level.push(id),
567        }
568    }
569    top_level.sort_unstable();
570    for list in children.values_mut() {
571        list.sort_unstable();
572    }
573
574    let mut plan = AmalgamationRegionPlan::default();
575    // guest region id -> new region id (host id for the single top-level region).
576    let mut mapped: HashMap<&str, String> = HashMap::new();
577    // Breadth-first order from the top level keeps parents before children.
578    let mut queue: std::collections::VecDeque<&str> = top_level.iter().copied().collect();
579    let single_top = top_level.len() == 1;
580    let mut visited: HashSet<&str> = HashSet::new();
581
582    while let Some(gid) = queue.pop_front() {
583        if !visited.insert(gid) {
584            continue;
585        }
586        let region = &regions[gid];
587        let is_host = single_top && top_level[0] == gid;
588        if is_host {
589            mapped.insert(gid, host_region_id.to_string());
590            plan.host_designated_inputs = filtered_io(region, "designated_inputs", member_area_ids);
591            plan.host_designated_outputs =
592                filtered_io(region, "designated_outputs", member_area_ids);
593            plan.host_port_encoding = filtered_port_encoding(
594                region,
595                &[
596                    plan.host_designated_inputs.as_slice(),
597                    plan.host_designated_outputs.as_slice(),
598                ],
599            );
600        } else {
601            let parent_region_id = match guest_parent_id(region) {
602                Some(p) if mapped.contains_key(p) => mapped[p].clone(),
603                _ => host_region_id.to_string(),
604            };
605            let new_id = feagi_structures::genomic::brain_regions::RegionID::new().to_string();
606            let mut properties: HashMap<String, Value> = HashMap::new();
607            for (k, v) in &region.properties {
608                match k.as_str() {
609                    "parent_region_id" | "areas" | "cortical_areas" | "regions"
610                    | "child_regions" | "coordinate_3d" | "inputs" | "outputs"
611                    | "designated_inputs" | "designated_outputs" | PORT_ENCODING_KEY => {}
612                    _ => {
613                        properties.insert(k.clone(), v.clone());
614                    }
615                }
616            }
617            properties.insert(
618                "coordinate_3d".to_string(),
619                offset_coordinate_3d(region.properties.get("coordinate_3d"), origin),
620            );
621            let designated_inputs = filtered_io(region, "designated_inputs", member_area_ids);
622            let designated_outputs = filtered_io(region, "designated_outputs", member_area_ids);
623            let port_encoding = filtered_port_encoding(
624                region,
625                &[designated_inputs.as_slice(), designated_outputs.as_slice()],
626            );
627            for (key, list) in [
628                ("designated_inputs", designated_inputs),
629                ("designated_outputs", designated_outputs),
630            ] {
631                if !list.is_empty() {
632                    properties.insert(key.to_string(), serde_json::json!(list));
633                }
634            }
635            if !port_encoding.is_empty() {
636                properties.insert(PORT_ENCODING_KEY.to_string(), Value::Object(port_encoding));
637            }
638            mapped.insert(gid, new_id.clone());
639            plan.sub_regions.push(AmalgamationRegionSpec {
640                region_id: new_id,
641                name: region.name.clone(),
642                parent_region_id,
643                properties,
644            });
645        }
646        if let Some(kids) = children.get(gid) {
647            queue.extend(kids.iter().copied());
648        }
649    }
650
651    // Area membership: guest region lists first (sorted for a stable pick when an area is listed
652    // twice), then the area's own `parent_region_id` property.
653    let mut guest_ids: Vec<&str> = mapped.keys().copied().collect();
654    guest_ids.sort_unstable();
655    for gid in guest_ids {
656        let target = &mapped[gid];
657        if target == host_region_id {
658            continue;
659        }
660        let mut members: Vec<String> = regions[gid]
661            .cortical_areas
662            .iter()
663            .map(|c| c.as_base_64())
664            .collect();
665        members.sort_unstable();
666        for m in members {
667            if member_area_ids.contains(&m) {
668                plan.area_region.entry(m).or_insert_with(|| target.clone());
669            }
670        }
671    }
672    for area in genome.cortical_areas.values() {
673        let b64 = area.cortical_id.as_base_64();
674        if !member_area_ids.contains(&b64) || plan.area_region.contains_key(&b64) {
675            continue;
676        }
677        if let Some(target) = area
678            .properties
679            .get("parent_region_id")
680            .and_then(|v| v.as_str())
681            .and_then(|p| mapped.get(p))
682        {
683            if target != host_region_id {
684                plan.area_region.insert(b64, target.clone());
685            }
686        }
687    }
688    plan.region_map = mapped
689        .iter()
690        .map(|(guest, new)| ((*guest).to_string(), new.clone()))
691        .collect();
692    plan
693}
694
695#[cfg(test)]
696mod tests {
697    use super::*;
698    use crate::random::random_bytes;
699    use crate::runtime::{GenomeMetadata, GenomeSignatures, GenomeStats, PhysiologyConfig};
700    use crate::MorphologyRegistry;
701    use crate::RuntimeGenome;
702    use feagi_structures::genomic::cortical_area::descriptors::CorticalAreaDimensions;
703    use feagi_structures::genomic::cortical_area::CorticalArea;
704    use feagi_structures::genomic::cortical_area::CustomCorticalType;
705    use feagi_structures::genomic::descriptors::GenomeCoordinate3D;
706
707    fn sample_custom_cortical_id() -> CorticalID {
708        let mut bytes = [0u8; CorticalID::CORTICAL_ID_LENGTH];
709        bytes[0] = b'c';
710        random_bytes(&mut bytes[1..]);
711        CorticalID::try_from_bytes(&bytes).expect("valid custom id")
712    }
713
714    #[test]
715    fn remap_changes_custom_ids_when_host_reserves_them() {
716        let old_id = sample_custom_cortical_id();
717        let area = CorticalArea::new(
718            old_id,
719            0,
720            "test-area".to_string(),
721            CorticalAreaDimensions::new(1, 1, 1).expect("dims"),
722            GenomeCoordinate3D::new(0, 0, 0),
723            CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire),
724        )
725        .expect("area");
726
727        let mut cortical_areas = HashMap::new();
728        cortical_areas.insert(old_id, area);
729
730        let mut genome = RuntimeGenome {
731            metadata: GenomeMetadata {
732                genome_id: "t".to_string(),
733                genome_title: "t".to_string(),
734                genome_description: "".to_string(),
735                version: "3.0".to_string(),
736                timestamp: 0.0,
737                brain_regions_root: None,
738            },
739            cortical_areas,
740            brain_regions: HashMap::new(),
741            classifiers: HashMap::new(),
742            morphologies: MorphologyRegistry::new(),
743            modulators: crate::modulators::ModulatorRegistry::new(),
744            physiology: PhysiologyConfig::default(),
745            signatures: GenomeSignatures {
746                genome: String::new(),
747                blueprint: String::new(),
748                physiology: String::new(),
749                morphologies: None,
750            },
751            stats: GenomeStats::default(),
752            change_history: Vec::new(),
753        };
754
755        let mut host = HashSet::new();
756        let sample_custom = old_id.as_base_64();
757        host.insert(sample_custom.clone());
758
759        let pairs = remap_guest_custom_memory_cortical_ids_for_amalgamation(&mut genome, &host)
760            .expect("remap");
761
762        assert!(
763            pairs.contains_key(&sample_custom),
764            "expected reserved custom id to be remapped"
765        );
766        let new_b64 = pairs.get(&sample_custom).unwrap();
767        assert_ne!(new_b64, &sample_custom);
768        assert!(
769            genome
770                .cortical_areas
771                .keys()
772                .any(|k| k.as_base_64() == *new_b64),
773            "new id should appear as a cortical_areas key"
774        );
775        assert!(
776            !genome
777                .cortical_areas
778                .contains_key(&CorticalID::try_from_base_64(&sample_custom).unwrap()),
779            "old custom id should not remain as a key when remapped"
780        );
781    }
782
783    #[test]
784    fn cloned_circuit_designated_io_follows_remapped_area_ids() {
785        use feagi_structures::genomic::brain_regions::{
786            BrainRegion, RegionID, RegionType, ROOT_BRAIN_REGION_NAME,
787        };
788
789        let old_id = sample_custom_cortical_id();
790        let old_b64 = old_id.as_base_64();
791        let area = CorticalArea::new(
792            old_id,
793            0,
794            "io-area".to_string(),
795            CorticalAreaDimensions::new(1, 1, 1).expect("dims"),
796            GenomeCoordinate3D::new(0, 0, 0),
797            CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire),
798        )
799        .expect("area");
800
801        let root_id = RegionID::new();
802        let circuit_id = RegionID::new();
803        let root_key = root_id.to_string();
804        let circuit_key = circuit_id.to_string();
805        let root = BrainRegion::new(
806            root_id,
807            ROOT_BRAIN_REGION_NAME.to_string(),
808            RegionType::Undefined,
809        )
810        .expect("root");
811        let mut circuit_props = HashMap::new();
812        circuit_props.insert(
813            "parent_region_id".to_string(),
814            serde_json::json!(root_key.clone()),
815        );
816        circuit_props.insert(
817            "designated_inputs".to_string(),
818            serde_json::json!([old_b64.clone()]),
819        );
820        circuit_props.insert("designated_outputs".to_string(), serde_json::json!([]));
821        let circuit = BrainRegion::new(circuit_id, "Circuit".to_string(), RegionType::Undefined)
822            .expect("circuit")
823            .with_areas([old_id])
824            .with_properties(circuit_props);
825
826        let mut brain_regions = HashMap::new();
827        brain_regions.insert(root_key, root);
828        brain_regions.insert(circuit_key, circuit);
829        let mut cortical_areas = HashMap::new();
830        cortical_areas.insert(old_id, area);
831
832        let mut genome = RuntimeGenome {
833            metadata: GenomeMetadata {
834                genome_id: "t".to_string(),
835                genome_title: "t".to_string(),
836                genome_description: "".to_string(),
837                version: "3.0".to_string(),
838                timestamp: 0.0,
839                brain_regions_root: None,
840            },
841            cortical_areas,
842            brain_regions,
843            classifiers: HashMap::new(),
844            morphologies: MorphologyRegistry::new(),
845            modulators: crate::modulators::ModulatorRegistry::new(),
846            physiology: PhysiologyConfig::default(),
847            signatures: GenomeSignatures {
848                genome: String::new(),
849                blueprint: String::new(),
850                physiology: String::new(),
851                morphologies: None,
852            },
853            stats: GenomeStats::default(),
854            change_history: Vec::new(),
855        };
856
857        let (inputs_before, _) = designated_io_lists_for_cloned_circuit(&genome);
858        assert_eq!(inputs_before, vec![old_b64.clone()]);
859
860        let mut host = HashSet::new();
861        host.insert(old_b64.clone());
862        let pairs = remap_guest_custom_memory_cortical_ids_for_amalgamation(&mut genome, &host)
863            .expect("remap");
864        let new_b64 = pairs.get(&old_b64).expect("remapped id");
865
866        let (inputs_after, outputs_after) = designated_io_lists_for_cloned_circuit(&genome);
867        assert_eq!(inputs_after, vec![new_b64.clone()]);
868        assert!(outputs_after.is_empty());
869        assert_ne!(inputs_after[0], old_b64);
870    }
871
872    fn plan_area(prefix: u8) -> CorticalArea {
873        let mut bytes = [0u8; CorticalID::CORTICAL_ID_LENGTH];
874        bytes[0] = prefix;
875        random_bytes(&mut bytes[1..]);
876        let id = CorticalID::try_from_bytes(&bytes).expect("id");
877        let ty = if prefix == b'm' {
878            CorticalAreaType::Memory(
879                feagi_structures::genomic::cortical_area::MemoryCorticalType::Memory,
880            )
881        } else {
882            CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire)
883        };
884        CorticalArea::new(
885            id,
886            0,
887            "a".to_string(),
888            CorticalAreaDimensions::new(1, 1, 1).expect("dims"),
889            GenomeCoordinate3D::new(0, 0, 0),
890            ty,
891        )
892        .expect("area")
893    }
894
895    fn plan_genome(areas: Vec<CorticalArea>, regions: Vec<(String, BrainRegion)>) -> RuntimeGenome {
896        RuntimeGenome {
897            metadata: GenomeMetadata {
898                genome_id: "t".to_string(),
899                genome_title: "t".to_string(),
900                genome_description: "".to_string(),
901                version: "3.0".to_string(),
902                timestamp: 0.0,
903                brain_regions_root: None,
904            },
905            cortical_areas: areas.into_iter().map(|a| (a.cortical_id, a)).collect(),
906            brain_regions: regions.into_iter().collect(),
907            classifiers: HashMap::new(),
908            morphologies: MorphologyRegistry::new(),
909            modulators: crate::modulators::ModulatorRegistry::new(),
910            physiology: PhysiologyConfig::default(),
911            signatures: GenomeSignatures {
912                genome: String::new(),
913                blueprint: String::new(),
914                physiology: String::new(),
915                morphologies: None,
916            },
917            stats: GenomeStats::default(),
918            change_history: Vec::new(),
919        }
920    }
921
922    fn plan_region(
923        name: &str,
924        parent: Option<&str>,
925        areas: &[&CorticalArea],
926        props: Vec<(&str, Value)>,
927    ) -> (String, BrainRegion) {
928        use feagi_structures::genomic::brain_regions::{RegionID, RegionType};
929        let rid = RegionID::new();
930        let mut p: HashMap<String, Value> = HashMap::new();
931        if let Some(par) = parent {
932            p.insert("parent_region_id".to_string(), serde_json::json!(par));
933        }
934        for (k, v) in props {
935            p.insert(k.to_string(), v);
936        }
937        let r = BrainRegion::new(rid, name.to_string(), RegionType::Undefined)
938            .expect("region")
939            .with_areas(areas.iter().map(|a| a.cortical_id))
940            .with_properties(p);
941        (rid.to_string(), r)
942    }
943
944    fn all_ids(areas: &[&CorticalArea]) -> HashSet<String> {
945        areas.iter().map(|a| a.cortical_id.as_base_64()).collect()
946    }
947
948    #[test]
949    fn plan_nested_regions_with_memory_area_and_ordering() {
950        use feagi_structures::genomic::brain_regions::{
951            BrainRegion, RegionID, RegionType, ROOT_BRAIN_REGION_NAME,
952        };
953        let c1 = plan_area(b'c');
954        let m1 = plan_area(b'm');
955        let root_id = RegionID::new().to_string();
956        let root = BrainRegion::new(
957            RegionID::from_string(&root_id).unwrap(),
958            ROOT_BRAIN_REGION_NAME.to_string(),
959            RegionType::Undefined,
960        )
961        .unwrap();
962        let (top_id, top) = plan_region("top", Some(&root_id), &[&c1], vec![]);
963        let (mid_id, mid) = plan_region(
964            "mid",
965            Some(&top_id),
966            &[&m1],
967            vec![("coordinate_3d", serde_json::json!([3, 4, 5]))],
968        );
969        let g = plan_genome(
970            vec![c1.clone(), m1.clone()],
971            vec![(root_id, root), (top_id, top), (mid_id, mid)],
972        );
973        let host = "host-region";
974        let plan = plan_amalgamation_regions(&g, host, (10, 20, 30), &all_ids(&[&c1, &m1]));
975        // single top-level maps onto host; one sub-region (mid) under host
976        assert_eq!(plan.sub_regions.len(), 1);
977        let sub = &plan.sub_regions[0];
978        assert_eq!(sub.name, "mid");
979        assert_eq!(sub.parent_region_id, host);
980        assert_eq!(
981            sub.properties["coordinate_3d"],
982            serde_json::json!([13, 24, 35])
983        );
984        assert_eq!(
985            plan.area_region[&m1.cortical_id.as_base_64()],
986            sub.region_id
987        );
988        assert!(!plan.area_region.contains_key(&c1.cortical_id.as_base_64()));
989    }
990
991    #[test]
992    fn plan_three_levels_parent_before_child() {
993        let a = plan_area(b'c');
994        let (t, top) = plan_region("t", None, &[], vec![]);
995        let (m, mid) = plan_region("m", Some(&t), &[], vec![]);
996        let (l, leaf) = plan_region("l", Some(&m), &[&a], vec![]);
997        let g = plan_genome(vec![a.clone()], vec![(l, leaf), (m, mid), (t, top)]);
998        let plan = plan_amalgamation_regions(&g, "h", (0, 0, 0), &all_ids(&[&a]));
999        let names: Vec<&str> = plan.sub_regions.iter().map(|s| s.name.as_str()).collect();
1000        assert_eq!(names, vec!["m", "l"]);
1001        assert_eq!(
1002            plan.sub_regions[1].parent_region_id,
1003            plan.sub_regions[0].region_id
1004        );
1005        assert_eq!(
1006            plan.area_region[&a.cortical_id.as_base_64()],
1007            plan.sub_regions[1].region_id
1008        );
1009    }
1010
1011    #[test]
1012    fn plan_multiple_top_level_regions_become_children_of_host() {
1013        let a = plan_area(b'c');
1014        let b = plan_area(b'c');
1015        let (id1, r1) = plan_region(
1016            "one",
1017            None,
1018            &[&a],
1019            vec![(
1020                "designated_inputs",
1021                serde_json::json!([a.cortical_id.as_base_64()]),
1022            )],
1023        );
1024        let (id2, r2) = plan_region("two", None, &[&b], vec![]);
1025        let g = plan_genome(vec![a.clone(), b.clone()], vec![(id1, r1), (id2, r2)]);
1026        let plan = plan_amalgamation_regions(&g, "h", (0, 0, 0), &all_ids(&[&a, &b]));
1027        assert_eq!(plan.sub_regions.len(), 2);
1028        assert!(plan.sub_regions.iter().all(|s| s.parent_region_id == "h"));
1029        assert!(plan.host_designated_inputs.is_empty());
1030        let one = plan.sub_regions.iter().find(|s| s.name == "one").unwrap();
1031        assert_eq!(
1032            one.properties["designated_inputs"],
1033            serde_json::json!([a.cortical_id.as_base_64()])
1034        );
1035        assert_eq!(plan.area_region[&a.cortical_id.as_base_64()], one.region_id);
1036        assert_ne!(
1037            plan.area_region[&a.cortical_id.as_base_64()],
1038            plan.area_region[&b.cortical_id.as_base_64()]
1039        );
1040    }
1041
1042    #[test]
1043    fn plan_area_in_no_region_falls_back_to_host() {
1044        let a = plan_area(b'c');
1045        let loose = plan_area(b'c');
1046        let (id1, r1) = plan_region("one", None, &[&a], vec![]);
1047        let (id2, r2) = plan_region("two", None, &[], vec![]);
1048        let g = plan_genome(vec![a.clone(), loose.clone()], vec![(id1, r1), (id2, r2)]);
1049        let plan = plan_amalgamation_regions(&g, "h", (0, 0, 0), &all_ids(&[&a, &loose]));
1050        assert!(!plan
1051            .area_region
1052            .contains_key(&loose.cortical_id.as_base_64()));
1053        assert!(plan.area_region.contains_key(&a.cortical_id.as_base_64()));
1054    }
1055
1056    #[test]
1057    fn plan_nested_designated_io_is_remapped_and_filtered() {
1058        let a = plan_area(b'c');
1059        let outside = plan_area(b'c');
1060        let (t, top) = plan_region("t", None, &[], vec![]);
1061        let (m, mid) = plan_region(
1062            "m",
1063            Some(&t),
1064            &[&a],
1065            vec![
1066                (
1067                    "designated_inputs",
1068                    serde_json::json!([
1069                        a.cortical_id.as_base_64(),
1070                        outside.cortical_id.as_base_64()
1071                    ]),
1072                ),
1073                (
1074                    "designated_outputs",
1075                    serde_json::json!([a.cortical_id.as_base_64()]),
1076                ),
1077            ],
1078        );
1079        let mut g = plan_genome(vec![a.clone(), outside.clone()], vec![(t, top), (m, mid)]);
1080        // remap through the real remap so lists follow new ids
1081        let mut host = HashSet::new();
1082        host.insert(a.cortical_id.as_base_64());
1083        let pairs = remap_guest_custom_memory_cortical_ids_for_amalgamation(&mut g, &host).unwrap();
1084        let new_a = pairs
1085            .get(&a.cortical_id.as_base_64())
1086            .cloned()
1087            .expect("remapped");
1088        let members: HashSet<String> = [new_a.clone()].into_iter().collect();
1089        let plan = plan_amalgamation_regions(&g, "h", (0, 0, 0), &members);
1090        let sub = &plan.sub_regions[0];
1091        assert_eq!(
1092            sub.properties["designated_inputs"],
1093            serde_json::json!([new_a.clone()])
1094        );
1095        assert_eq!(
1096            sub.properties["designated_outputs"],
1097            serde_json::json!([new_a])
1098        );
1099    }
1100
1101    #[test]
1102    fn plan_flat_single_region_maps_to_host_without_sub_regions() {
1103        let a = plan_area(b'c');
1104        let (id1, r1) = plan_region(
1105            "only",
1106            None,
1107            &[&a],
1108            vec![(
1109                "designated_inputs",
1110                serde_json::json!([a.cortical_id.as_base_64()]),
1111            )],
1112        );
1113        let g = plan_genome(vec![a.clone()], vec![(id1, r1)]);
1114        let plan = plan_amalgamation_regions(&g, "h", (0, 0, 0), &all_ids(&[&a]));
1115        assert!(plan.sub_regions.is_empty());
1116        assert!(plan.area_region.is_empty());
1117        assert_eq!(
1118            plan.host_designated_inputs,
1119            vec![a.cortical_id.as_base_64()]
1120        );
1121    }
1122
1123    #[test]
1124    fn plan_tree_survives_save_and_reload() {
1125        use feagi_structures::genomic::brain_regions::{
1126            BrainRegion, RegionID, RegionType, ROOT_BRAIN_REGION_NAME,
1127        };
1128        let a = plan_area(b'c');
1129        let b = plan_area(b'm');
1130        let (t, top) = plan_region("t", None, &[&a], vec![]);
1131        let (m, mid) = plan_region("m", Some(&t), &[&b], vec![]);
1132        let guest = plan_genome(vec![a.clone(), b.clone()], vec![(t, top), (m, mid)]);
1133
1134        // Host: root -> amalgamation region, then execute the plan as the API handler does.
1135        let root_id = RegionID::new();
1136        let host_id = RegionID::new();
1137        let root_key = root_id.to_string();
1138        let host_key = host_id.to_string();
1139        let root = BrainRegion::new(
1140            root_id,
1141            ROOT_BRAIN_REGION_NAME.to_string(),
1142            RegionType::Undefined,
1143        )
1144        .unwrap();
1145        let mut host_props = HashMap::new();
1146        host_props.insert(
1147            "parent_region_id".to_string(),
1148            serde_json::json!(root_key.clone()),
1149        );
1150        let host_region = BrainRegion::new(host_id, "host".to_string(), RegionType::Undefined)
1151            .unwrap()
1152            .with_properties(host_props);
1153        let members = all_ids(&[&a, &b]);
1154        let plan = plan_amalgamation_regions(&guest, &host_key, (0, 0, 0), &members);
1155        let mut regions: Vec<(String, BrainRegion)> =
1156            vec![(root_key, root), (host_key.clone(), host_region)];
1157        for spec in &plan.sub_regions {
1158            let mut props = spec.properties.clone();
1159            props.insert(
1160                "parent_region_id".to_string(),
1161                serde_json::json!(spec.parent_region_id),
1162            );
1163            let r = BrainRegion::new(
1164                RegionID::from_string(&spec.region_id).unwrap(),
1165                spec.name.clone(),
1166                RegionType::Undefined,
1167            )
1168            .unwrap()
1169            .with_properties(props);
1170            regions.push((spec.region_id.clone(), r));
1171        }
1172        let mut host_areas = Vec::new();
1173        for src in [&a, &b] {
1174            let mut area = src.clone();
1175            let target = plan
1176                .area_region
1177                .get(&src.cortical_id.as_base_64())
1178                .cloned()
1179                .unwrap_or_else(|| host_key.clone());
1180            area.properties.insert(
1181                "parent_region_id".to_string(),
1182                serde_json::json!(target.clone()),
1183            );
1184            for (id, r) in regions.iter_mut() {
1185                if *id == target {
1186                    r.add_area(src.cortical_id);
1187                }
1188            }
1189            host_areas.push(area);
1190        }
1191        let genome = plan_genome(host_areas, regions);
1192
1193        let json = crate::genome::runtime_saver::save_genome_to_json(&genome).expect("save");
1194        let reloaded = crate::load_genome_from_json(&json).expect("reload");
1195        let sub = &plan.sub_regions[0];
1196        let r = reloaded
1197            .brain_regions
1198            .get(&sub.region_id)
1199            .expect("sub-region persisted");
1200        assert_eq!(r.name, "m");
1201        assert_eq!(
1202            r.properties
1203                .get("parent_region_id")
1204                .and_then(|v| v.as_str()),
1205            Some(host_key.as_str())
1206        );
1207        assert!(r.contains_area(&b.cortical_id));
1208    }
1209
1210    fn wiring_entry() -> Value {
1211        serde_json::json!({
1212            "kind": "Boolean", "signed": false, "frame": null, "positioning": null,
1213            "source": "wiring"
1214        })
1215    }
1216
1217    #[test]
1218    fn remap_region_io_lists_remaps_port_encoding_keys() {
1219        use feagi_structures::genomic::brain_regions::{RegionID, RegionType};
1220        let mut region =
1221            BrainRegion::new(RegionID::new(), "r".to_string(), RegionType::Undefined).unwrap();
1222        region.properties.insert(
1223            PORT_ENCODING_KEY.to_string(),
1224            serde_json::json!({"old_a": wiring_entry(), "kept_b": wiring_entry()}),
1225        );
1226        let remap: HashMap<String, String> = [("old_a".to_string(), "new_a".to_string())].into();
1227        remap_region_io_lists(&mut region, &remap);
1228        assert_eq!(
1229            region.properties[PORT_ENCODING_KEY],
1230            serde_json::json!({"new_a": wiring_entry(), "kept_b": wiring_entry()})
1231        );
1232    }
1233
1234    #[test]
1235    fn amalgamation_remaps_port_encoding_keys_and_plan_carries_them() {
1236        let a = plan_area(b'c');
1237        let outside = plan_area(b'c');
1238        let (t, top) = plan_region("t", None, &[], vec![]);
1239        let (m, mid) = plan_region(
1240            "m",
1241            Some(&t),
1242            &[&a],
1243            vec![
1244                (
1245                    "designated_inputs",
1246                    serde_json::json!([a.cortical_id.as_base_64()]),
1247                ),
1248                (
1249                    PORT_ENCODING_KEY,
1250                    serde_json::json!({
1251                        a.cortical_id.as_base_64(): wiring_entry(),
1252                        outside.cortical_id.as_base_64(): wiring_entry(),
1253                    }),
1254                ),
1255            ],
1256        );
1257        let mut g = plan_genome(vec![a.clone(), outside.clone()], vec![(t, top), (m, mid)]);
1258        let mut host = HashSet::new();
1259        host.insert(a.cortical_id.as_base_64());
1260        let pairs = remap_guest_custom_memory_cortical_ids_for_amalgamation(&mut g, &host).unwrap();
1261        let new_a = pairs[&a.cortical_id.as_base_64()].clone();
1262        let members: HashSet<String> = [new_a.clone()].into_iter().collect();
1263        let plan = plan_amalgamation_regions(&g, "h", (0, 0, 0), &members);
1264        // Sub-region copy: key remapped, entry for the non-imported area dropped.
1265        assert_eq!(
1266            plan.sub_regions[0].properties[PORT_ENCODING_KEY],
1267            serde_json::json!({ new_a.clone(): wiring_entry() })
1268        );
1269    }
1270
1271    #[test]
1272    fn plan_host_region_carries_port_encoding_of_its_designated_ports() {
1273        let a = plan_area(b'c');
1274        let b = plan_area(b'c');
1275        let (id1, r1) = plan_region(
1276            "only",
1277            None,
1278            &[&a, &b],
1279            vec![
1280                (
1281                    "designated_inputs",
1282                    serde_json::json!([a.cortical_id.as_base_64()]),
1283                ),
1284                (
1285                    PORT_ENCODING_KEY,
1286                    serde_json::json!({
1287                        a.cortical_id.as_base_64(): wiring_entry(),
1288                        b.cortical_id.as_base_64(): wiring_entry(),
1289                    }),
1290                ),
1291            ],
1292        );
1293        let g = plan_genome(vec![a.clone(), b.clone()], vec![(id1, r1)]);
1294        let plan = plan_amalgamation_regions(&g, "h", (0, 0, 0), &all_ids(&[&a, &b]));
1295        // Only the designated port keeps an entry.
1296        assert_eq!(plan.host_port_encoding.len(), 1);
1297        assert_eq!(
1298            plan.host_port_encoding[&a.cortical_id.as_base_64()],
1299            wiring_entry()
1300        );
1301    }
1302}
1303
1304#[cfg(test)]
1305mod rename_runtime_genome_areas_tests {
1306    use super::*;
1307    use crate::runtime::{GenomeMetadata, GenomeSignatures, GenomeStats, MorphologyRegistry};
1308    use feagi_structures::genomic::brain_regions::{RegionID, RegionType};
1309    use feagi_structures::genomic::cortical_area::{
1310        CorticalAreaDimensions, IOCorticalAreaConfigurationFlag,
1311    };
1312
1313    fn io(group: u16) -> CorticalID {
1314        IOCorticalAreaConfigurationFlag::Boolean.as_io_cortical_id(
1315            true,
1316            *b"tst",
1317            group.into(),
1318            0u8.into(),
1319        )
1320    }
1321
1322    fn area(id: CorticalID) -> CorticalArea {
1323        CorticalArea::new(
1324            id,
1325            0,
1326            "a".to_string(),
1327            CorticalAreaDimensions::new(1, 1, 1).unwrap(),
1328            (0, 0, 0).into(),
1329            CorticalAreaType::BrainInput(IOCorticalAreaConfigurationFlag::Boolean),
1330        )
1331        .unwrap()
1332    }
1333
1334    fn genome() -> RuntimeGenome {
1335        let mut genome = RuntimeGenome {
1336            metadata: GenomeMetadata {
1337                genome_id: "g".to_string(),
1338                genome_title: "g".to_string(),
1339                genome_description: String::new(),
1340                version: "3.0".to_string(),
1341                timestamp: 0.0,
1342                brain_regions_root: None,
1343            },
1344            cortical_areas: HashMap::new(),
1345            brain_regions: HashMap::new(),
1346            classifiers: HashMap::new(),
1347            morphologies: MorphologyRegistry::new(),
1348            modulators: crate::modulators::ModulatorRegistry::new(),
1349            physiology: Default::default(),
1350            signatures: GenomeSignatures {
1351                genome: "0".to_string(),
1352                blueprint: "0".to_string(),
1353                physiology: "0".to_string(),
1354                morphologies: None,
1355            },
1356            stats: GenomeStats::default(),
1357            change_history: Vec::new(),
1358        };
1359        let (a, b) = (io(1), io(2));
1360        let mut first = area(a);
1361        first.properties.insert(
1362            "cortical_mapping_dst".to_string(),
1363            serde_json::json!({ b.as_base_64(): [{ "gate_source_area": a.as_base_64() }] }),
1364        );
1365        first.properties.insert(
1366            "memory_twin_of".to_string(),
1367            serde_json::json!(b.as_base_64()),
1368        );
1369        genome.cortical_areas.insert(a, first);
1370        genome.cortical_areas.insert(b, area(b));
1371        let mut region =
1372            BrainRegion::new(RegionID::new(), "r".to_string(), RegionType::Undefined).unwrap();
1373        region.cortical_areas.insert(a);
1374        region.properties.insert(
1375            "designated_inputs".to_string(),
1376            serde_json::json!([a.as_base_64()]),
1377        );
1378        genome.brain_regions.insert("r".to_string(), region);
1379        genome
1380    }
1381
1382    #[test]
1383    fn occupied_target_leaves_the_genome_unchanged() {
1384        let mut g = genome();
1385        let snapshot = |g: &RuntimeGenome| {
1386            let mut areas: Vec<(String, String)> = g
1387                .cortical_areas
1388                .iter()
1389                .map(|(id, a)| {
1390                    (
1391                        id.as_base_64(),
1392                        format!(
1393                            "{:?}",
1394                            a.properties
1395                                .iter()
1396                                .collect::<std::collections::BTreeMap<_, _>>()
1397                        ),
1398                    )
1399                })
1400                .collect();
1401            areas.sort();
1402            (
1403                areas,
1404                format!(
1405                    "{:?}",
1406                    g.brain_regions["r"]
1407                        .properties
1408                        .iter()
1409                        .collect::<std::collections::BTreeMap<_, _>>()
1410                ),
1411            )
1412        };
1413        let before = snapshot(&g);
1414        assert!(rename_runtime_genome_areas(&mut g, &[(io(1), io(2))]).is_err());
1415        assert_eq!(before, snapshot(&g));
1416    }
1417
1418    #[test]
1419    fn swap_rekeys_areas_and_every_reference() {
1420        let mut g = genome();
1421        rename_runtime_genome_areas(&mut g, &[(io(1), io(2)), (io(2), io(1))]).unwrap();
1422        // The area that carried the references is now at io(2); they point at the swapped ids.
1423        let moved = &g.cortical_areas[&io(2)];
1424        assert_eq!(moved.cortical_id, io(2));
1425        assert_eq!(
1426            moved.properties["memory_twin_of"],
1427            serde_json::json!(io(1).as_base_64())
1428        );
1429        assert_eq!(
1430            moved.properties["cortical_mapping_dst"][io(1).as_base_64()][0]["gate_source_area"],
1431            serde_json::json!(io(2).as_base_64())
1432        );
1433        let region = &g.brain_regions["r"];
1434        assert!(region.cortical_areas.contains(&io(2)) && !region.cortical_areas.contains(&io(1)));
1435        assert_eq!(
1436            region.properties["designated_inputs"],
1437            serde_json::json!([io(2).as_base_64()])
1438        );
1439    }
1440}