Skip to main content

feagi_evolutionary/
amalgamation_modulators.rs

1// Copyright 2025 Neuraville Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4/*!
5Plan the modulators and classifiers of a guest genome for amalgamation.
6
7Both plans are pure: they read the guest genome and a snapshot of the host and return what to
8create, which names and ids change, and the notices to show. They validate before the caller
9creates anything, so a bad guest fails with nothing to roll back.
10
11- Modulators: a guest instance either owns a driver area (`g` + serial id) or adopts an existing
12  area. Owned instances are created through the service (which allocates the driver id); adopted
13  instances are registered after their area exists. A name that already exists in the host is
14  reused (same-brain clone) or renamed (external genome), see [`ModulatorCollisionPolicy`].
15- Classifiers: always get a fresh `classifier_id`; every area field, reward modulator name and the
16  parent region are remapped.
17
18Copyright 2025 Neuraville Inc.
19Licensed under the Apache License, Version 2.0
20*/
21
22use crate::amalgamation_remap::remap_classifier_area_fields;
23use crate::modulators::ModulatorWrite;
24use crate::runtime::RuntimeGenome;
25use crate::types::{EvoError, EvoResult};
26use feagi_structures::genomic::classifiers::Classifier;
27use feagi_structures::genomic::cortical_area::CorticalID;
28use feagi_structures::genomic::ModulatorKind;
29use serde_json::Value;
30use std::collections::{HashMap, HashSet};
31
32/// What to do when a guest modulator name already exists in the host.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum ModulatorCollisionPolicy {
35    /// Same-brain clone: use the host modulator of that name. Host settings win.
36    ReuseHost,
37    /// External genome: rename the guest modulator to `<name> (<block_title>)`, then append
38    /// ` 2`, ` 3`, ... until the name is free.
39    RenameGuest { block_title: String },
40}
41
42/// A modulator already in the host.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct HostModulator {
45    pub kind: ModulatorKind,
46    /// Base64 id of the driver area.
47    pub driver_cortical_id: String,
48}
49
50/// One guest-owned modulator to create (the service allocates its driver area).
51#[derive(Debug, Clone, PartialEq)]
52pub struct PlannedOwnedModulator {
53    pub guest_name: String,
54    pub host_name: String,
55    /// Base64 id of the guest driver area; the key of the driver remap.
56    pub guest_driver_id: String,
57    /// Create request (never carries a driver id).
58    pub write: ModulatorWrite,
59    /// Guest driver tuning to copy onto the new driver after creation (the service creates a
60    /// driver with default values).
61    pub driver_tuning: HashMap<String, Value>,
62}
63
64/// One guest modulator that adopts an existing area as its driver.
65#[derive(Debug, Clone, PartialEq)]
66pub struct PlannedAdoptedModulator {
67    pub guest_name: String,
68    pub host_name: String,
69    /// Base64 id of the adopted area (final id after the area remap).
70    pub driver_cortical_id: String,
71    /// Create request carrying the driver id.
72    pub write: ModulatorWrite,
73}
74
75/// Modulator work for one amalgamation.
76#[derive(Debug, Clone, Default, PartialEq)]
77pub struct AmalgamationModulatorPlan {
78    /// Owned modulators to create, before the areas.
79    pub owned: Vec<PlannedOwnedModulator>,
80    /// Adopting modulators to create, after the areas.
81    pub adopted: Vec<PlannedAdoptedModulator>,
82    /// Every guest modulator name -> its name in the host (renamed, reused or unchanged).
83    pub name_map: HashMap<String, String>,
84    /// Guest driver area (base64) -> host driver area, for owned modulators that reuse a host
85    /// modulator. Created owned modulators add their own entry once the service returns the id.
86    pub reused_driver_remap: HashMap<String, String>,
87    /// Guest modulator driver areas (base64) with no guest modulator instance. They cannot be
88    /// imported.
89    pub orphan_driver_ids: Vec<String>,
90    /// One line per rename or reuse, for the response and the log.
91    pub notices: Vec<String>,
92}
93
94fn write_from(
95    instance: &crate::modulators::ModulatorInstance,
96    driver: Option<String>,
97) -> ModulatorWrite {
98    ModulatorWrite {
99        kind: instance.kind.as_str().to_string(),
100        magnitude_percent: instance.magnitude_percent,
101        effect_duration_bursts: instance.effect_duration_bursts,
102        rest_bursts: instance.rest_bursts,
103        graded: instance.graded,
104        full_scale_potential: instance.full_scale_potential,
105        driver_cortical_id: driver,
106    }
107}
108
109/// Defaults the service gives a new driver; guest values are copied only when they differ.
110const DRIVER_TUNING_DEFAULTS: [(&str, f64); 3] = [
111    ("firing_threshold", 1.0),
112    ("leak_coefficient", 0.0),
113    ("excitability", 1.0),
114];
115
116fn driver_tuning(genome: &RuntimeGenome, driver: &CorticalID) -> HashMap<String, Value> {
117    let mut tuning = HashMap::new();
118    let Some(area) = genome.cortical_areas.get(driver) else {
119        return tuning;
120    };
121    for (key, default) in DRIVER_TUNING_DEFAULTS {
122        if let Some(value) = area.properties.get(key).and_then(|v| v.as_f64()) {
123            if (value - default).abs() > f64::EPSILON {
124                tuning.insert(key.to_string(), serde_json::json!(value));
125            }
126        }
127    }
128    tuning
129}
130
131fn free_name(base: &str, title: &str, taken: &HashSet<String>) -> String {
132    let title = title.trim();
133    let title = if title.is_empty() { "imported" } else { title };
134    let first = format!("{base} ({title})");
135    if !taken.contains(&first) {
136        return first;
137    }
138    let mut n = 2u32;
139    loop {
140        let candidate = format!("{first} {n}");
141        if !taken.contains(&candidate) {
142            return candidate;
143        }
144        n += 1;
145    }
146}
147
148/// Plan the guest modulators. Call after the guest area ids were remapped
149/// (`remap_guest_custom_memory_cortical_ids_for_amalgamation`), so adopted drivers carry their
150/// final ids.
151///
152/// `host_area_ids` are the base64 ids of the host's areas. Fails, with nothing created, when an
153/// instance is invalid, a reused host modulator has another type, an adopted driver is missing,
154/// or an adopted driver already drives a host modulator.
155pub fn plan_amalgamation_modulators(
156    guest: &RuntimeGenome,
157    host_modulators: &HashMap<String, HostModulator>,
158    host_area_ids: &HashSet<String>,
159    policy: &ModulatorCollisionPolicy,
160) -> EvoResult<AmalgamationModulatorPlan> {
161    let mut plan = AmalgamationModulatorPlan::default();
162    let guest_ids = guest.modulators.ids();
163
164    // Names that stay as they are: host names and guest names that do not collide.
165    let mut taken: HashSet<String> = host_modulators.keys().cloned().collect();
166    for name in &guest_ids {
167        if !host_modulators.contains_key(name) {
168            taken.insert(name.clone());
169        }
170    }
171
172    let host_adopted_drivers: HashMap<&str, &str> = host_modulators
173        .iter()
174        .map(|(name, m)| (m.driver_cortical_id.as_str(), name.as_str()))
175        .collect();
176    let mut guest_adopted_drivers: HashSet<String> = HashSet::new();
177    let mut owned_driver_ids: HashSet<String> = HashSet::new();
178
179    for guest_name in &guest_ids {
180        let instance = guest
181            .modulators
182            .get(guest_name)
183            .ok_or_else(|| EvoError::Internal(format!("modulator '{guest_name}' vanished")))?;
184        instance
185            .validate()
186            .map_err(|err| EvoError::InvalidGenome(format!("modulator '{guest_name}': {err}")))?;
187        let host_match = host_modulators.get(guest_name);
188        let reuse = host_match.is_some() && matches!(policy, ModulatorCollisionPolicy::ReuseHost);
189        let host_name = match (host_match, policy) {
190            (None, _) => guest_name.clone(),
191            (Some(_), ModulatorCollisionPolicy::ReuseHost) => guest_name.clone(),
192            (Some(_), ModulatorCollisionPolicy::RenameGuest { block_title }) => {
193                let renamed = free_name(guest_name, block_title, &taken);
194                taken.insert(renamed.clone());
195                plan.notices.push(format!(
196                    "Renamed modulator '{guest_name}' to '{renamed}' because it already exists in this brain."
197                ));
198                renamed
199            }
200        };
201        plan.name_map.insert(guest_name.clone(), host_name.clone());
202
203        if reuse {
204            let host = &host_modulators[guest_name];
205            if host.kind != instance.kind {
206                return Err(EvoError::InvalidGenome(format!(
207                    "modulator '{guest_name}' is type {} here but {} in the imported circuit; \
208                     it cannot be reused",
209                    host.kind, instance.kind
210                )));
211            }
212            plan.notices.push(format!(
213                "Reused existing modulator '{guest_name}'; host settings apply."
214            ));
215            if !instance.adopts_driver() {
216                plan.reused_driver_remap.insert(
217                    instance.driver_cortical_id.as_base_64(),
218                    host.driver_cortical_id.clone(),
219                );
220                owned_driver_ids.insert(instance.driver_cortical_id.as_base_64());
221            }
222            continue;
223        }
224
225        let driver_b64 = instance.driver_cortical_id.as_base_64();
226        if instance.adopts_driver() {
227            let write = write_from(instance, Some(driver_b64.clone()));
228            write.validate_adopted_timing().map_err(|err| {
229                EvoError::InvalidGenome(format!("modulator '{guest_name}': {err}"))
230            })?;
231            if !host_area_ids.contains(&driver_b64)
232                && !guest
233                    .cortical_areas
234                    .contains_key(&instance.driver_cortical_id)
235            {
236                return Err(EvoError::InvalidGenome(format!(
237                    "modulator '{guest_name}' adopts area {driver_b64}, which is in neither the imported circuit nor this brain"
238                )));
239            }
240            if let Some(other) = host_adopted_drivers.get(driver_b64.as_str()) {
241                return Err(EvoError::InvalidGenome(format!(
242                    "area {driver_b64} already drives modulator '{other}', so modulator \
243                     '{guest_name}' cannot adopt it"
244                )));
245            }
246            if !guest_adopted_drivers.insert(driver_b64.clone()) {
247                return Err(EvoError::InvalidGenome(format!(
248                    "two imported modulators adopt area {driver_b64}"
249                )));
250            }
251            plan.adopted.push(PlannedAdoptedModulator {
252                guest_name: guest_name.clone(),
253                host_name,
254                driver_cortical_id: driver_b64,
255                write,
256            });
257        } else {
258            owned_driver_ids.insert(driver_b64.clone());
259            plan.owned.push(PlannedOwnedModulator {
260                guest_name: guest_name.clone(),
261                host_name,
262                guest_driver_id: driver_b64,
263                write: write_from(instance, None),
264                driver_tuning: driver_tuning(guest, &instance.driver_cortical_id),
265            });
266        }
267    }
268
269    let mut orphans: Vec<String> = guest
270        .cortical_areas
271        .keys()
272        .filter(|id| id.is_modulator_driver())
273        .map(|id| id.as_base_64())
274        .filter(|id| !owned_driver_ids.contains(id))
275        .collect();
276    orphans.sort_unstable();
277    plan.orphan_driver_ids = orphans;
278    Ok(plan)
279}
280
281fn rename_list(value: Option<&mut Value>, name_map: &HashMap<String, String>) {
282    let Some(list) = value.and_then(|value| value.as_array_mut()) else {
283        return;
284    };
285    for entry in list {
286        if let Some(new_name) = entry.as_str().and_then(|name| name_map.get(name)) {
287            *entry = Value::String(new_name.clone());
288        }
289    }
290}
291
292/// Rewrite every modulator name a guest area refers to: the area's `modulators` list and each
293/// mapping rule's `modulators` list. Classifier reward lists are handled by
294/// [`plan_amalgamation_classifiers`].
295pub fn apply_modulator_name_map(genome: &mut RuntimeGenome, name_map: &HashMap<String, String>) {
296    if name_map.iter().all(|(guest, host)| guest == host) {
297        return;
298    }
299    for area in genome.cortical_areas.values_mut() {
300        rename_list(area.properties.get_mut("modulators"), name_map);
301        let Some(dst) = area
302            .properties
303            .get_mut("cortical_mapping_dst")
304            .and_then(|value| value.as_object_mut())
305        else {
306            continue;
307        };
308        for rules in dst.values_mut() {
309            let Some(rules) = rules.as_array_mut() else {
310                continue;
311            };
312            for rule in rules {
313                if let Some(rule) = rule.as_object_mut() {
314                    rename_list(rule.get_mut("modulators"), name_map);
315                }
316            }
317        }
318    }
319}
320
321/// Plan the guest classifiers: fresh `classifier_id`, area fields through `area_remap`, reward
322/// modulators through `name_map`, and `parent_region_id` through `region_map` (the host region
323/// when the guest parent was not planned). Fails when a classifier's sample or class memory is
324/// not among `guest` areas, so a half-imported assembly is never created.
325///
326/// Call after the area remap is final (custom/memory ids and created driver ids).
327pub fn plan_amalgamation_classifiers(
328    guest: &RuntimeGenome,
329    area_remap: &HashMap<String, String>,
330    name_map: &HashMap<String, String>,
331    region_map: &HashMap<String, String>,
332    host_region_id: &str,
333) -> EvoResult<Vec<Classifier>> {
334    let mut guest_ids: Vec<&String> = guest.classifiers.keys().collect();
335    guest_ids.sort_unstable();
336    let mut planned = Vec::with_capacity(guest_ids.len());
337    for guest_id in guest_ids {
338        let mut classifier = guest.classifiers[guest_id].clone();
339        remap_classifier_area_fields(&mut classifier, area_remap);
340        for id in [&classifier.sample_memory_id, &classifier.class_memory_id] {
341            let present = CorticalID::try_from_base_64(id)
342                .map(|cid| guest.cortical_areas.contains_key(&cid))
343                .unwrap_or(false);
344            if !present {
345                return Err(EvoError::InvalidGenome(format!(
346                    "classifier '{}' refers to memory area {} that is not in the imported circuit",
347                    classifier.name, id
348                )));
349            }
350        }
351        for id in classifier.reward_modulator_ids.iter_mut() {
352            if let Some(new_name) = name_map.get(id.as_str()) {
353                *id = new_name.clone();
354            }
355        }
356        classifier.parent_region_id = region_map
357            .get(&classifier.parent_region_id)
358            .cloned()
359            .unwrap_or_else(|| host_region_id.to_string());
360        classifier.classifier_id =
361            feagi_structures::genomic::brain_regions::RegionID::new().to_string();
362        planned.push(classifier);
363    }
364    Ok(planned)
365}
366
367#[cfg(test)]
368mod tests {
369    use super::*;
370    use crate::amalgamation_remap::apply_driver_remap;
371    use crate::modulators::{ModulatorInstance, ModulatorRegistry};
372    use crate::runtime::{GenomeMetadata, GenomeSignatures, GenomeStats, PhysiologyConfig};
373    use crate::MorphologyRegistry;
374    use feagi_structures::genomic::classifiers::ClassifierClassBinding;
375    use feagi_structures::genomic::cortical_area::descriptors::CorticalAreaDimensions;
376    use feagi_structures::genomic::cortical_area::{
377        CorticalArea, CorticalAreaType, CustomCorticalType,
378    };
379    use feagi_structures::genomic::descriptors::GenomeCoordinate3D;
380
381    fn custom_id(tag: u8) -> CorticalID {
382        let mut bytes = *b"c_______";
383        bytes[1] = tag;
384        CorticalID::try_from_bytes(&bytes).expect("custom id")
385    }
386
387    fn area(id: CorticalID, kind: CorticalAreaType) -> CorticalArea {
388        CorticalArea::new(
389            id,
390            0,
391            "a".to_string(),
392            CorticalAreaDimensions::new(1, 1, 1).expect("dims"),
393            GenomeCoordinate3D::new(0, 0, 0),
394            kind,
395        )
396        .expect("area")
397    }
398
399    fn custom_area(id: CorticalID) -> CorticalArea {
400        area(
401            id,
402            CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire),
403        )
404    }
405
406    fn instance(kind: ModulatorKind, driver: CorticalID) -> ModulatorInstance {
407        ModulatorInstance {
408            kind,
409            magnitude_percent: 100.0,
410            effect_duration_bursts: 1,
411            rest_bursts: 0,
412            graded: false,
413            full_scale_potential: None,
414            driver_cortical_id: driver,
415        }
416    }
417
418    fn empty_genome(title: &str) -> RuntimeGenome {
419        RuntimeGenome {
420            metadata: GenomeMetadata {
421                genome_id: "g".to_string(),
422                genome_title: title.to_string(),
423                genome_description: String::new(),
424                version: "3.0".to_string(),
425                timestamp: 0.0,
426                brain_regions_root: None,
427            },
428            cortical_areas: HashMap::new(),
429            brain_regions: HashMap::new(),
430            classifiers: HashMap::new(),
431            morphologies: MorphologyRegistry::new(),
432            modulators: ModulatorRegistry::new(),
433            physiology: PhysiologyConfig::default(),
434            signatures: GenomeSignatures {
435                genome: String::new(),
436                blueprint: String::new(),
437                physiology: String::new(),
438                morphologies: None,
439            },
440            stats: GenomeStats::default(),
441            change_history: Vec::new(),
442        }
443    }
444
445    /// Guest with one owned reward modulator `boost` (driver serial 0), one custom area that
446    /// maps into the driver and subscribes a rule to `boost`.
447    fn guest_with_owned(name: &str) -> (RuntimeGenome, CorticalID, CorticalID) {
448        let mut genome = empty_genome("Block A");
449        let driver = CorticalID::modulator_driver(0);
450        let src = custom_id(b'a');
451        genome
452            .cortical_areas
453            .insert(driver, area(driver, CorticalAreaType::Modulator));
454        let mut src_area = custom_area(src);
455        src_area.properties.insert(
456            "cortical_mapping_dst".to_string(),
457            serde_json::json!({
458                driver.as_base_64(): [{"morphology_id": "m", "modulators": [name]}],
459                custom_id(b'b').as_base_64(): [{"morphology_id": "m", "modulators": [name, "other"]}],
460            }),
461        );
462        src_area
463            .properties
464            .insert("modulators".to_string(), serde_json::json!([name]));
465        genome.cortical_areas.insert(src, src_area);
466        genome
467            .modulators
468            .insert(name.to_string(), instance(ModulatorKind::Reward, driver));
469        (genome, driver, src)
470    }
471
472    fn host(entries: &[(&str, ModulatorKind, CorticalID)]) -> HashMap<String, HostModulator> {
473        entries
474            .iter()
475            .map(|(name, kind, driver)| {
476                (
477                    (*name).to_string(),
478                    HostModulator {
479                        kind: *kind,
480                        driver_cortical_id: driver.as_base_64(),
481                    },
482                )
483            })
484            .collect()
485    }
486
487    fn rename_policy() -> ModulatorCollisionPolicy {
488        ModulatorCollisionPolicy::RenameGuest {
489            block_title: "Block A".to_string(),
490        }
491    }
492
493    #[test]
494    fn no_collision_keeps_names_and_plans_owned_creation() {
495        let (genome, driver, _) = guest_with_owned("boost");
496        let plan = plan_amalgamation_modulators(
497            &genome,
498            &HashMap::new(),
499            &HashSet::new(),
500            &rename_policy(),
501        )
502        .expect("plan");
503        assert_eq!(plan.owned.len(), 1);
504        assert_eq!(plan.owned[0].host_name, "boost");
505        assert_eq!(plan.owned[0].guest_driver_id, driver.as_base_64());
506        assert!(plan.owned[0].write.driver_cortical_id.is_none());
507        assert_eq!(plan.name_map["boost"], "boost");
508        assert!(plan.notices.is_empty());
509        assert!(plan.orphan_driver_ids.is_empty());
510    }
511
512    #[test]
513    fn collision_renames_with_block_title_and_rewrites_every_reference() {
514        let (mut genome, _, src) = guest_with_owned("boost");
515        let host_driver = CorticalID::modulator_driver(0);
516        let plan = plan_amalgamation_modulators(
517            &genome,
518            &host(&[("boost", ModulatorKind::Reward, host_driver)]),
519            &HashSet::new(),
520            &rename_policy(),
521        )
522        .expect("plan");
523        assert_eq!(plan.name_map["boost"], "boost (Block A)");
524        assert_eq!(
525            plan.notices,
526            vec![
527                "Renamed modulator 'boost' to 'boost (Block A)' because it already exists in this brain."
528                    .to_string()
529            ]
530        );
531        apply_modulator_name_map(&mut genome, &plan.name_map);
532        let props = &genome.cortical_areas[&src].properties;
533        assert_eq!(props["modulators"], serde_json::json!(["boost (Block A)"]));
534        let dst = props["cortical_mapping_dst"].as_object().unwrap();
535        let lists: Vec<Value> = dst
536            .values()
537            .map(|rules| rules[0]["modulators"].clone())
538            .collect();
539        assert!(lists.contains(&serde_json::json!(["boost (Block A)"])));
540        assert!(lists.contains(&serde_json::json!(["boost (Block A)", "other"])));
541    }
542
543    #[test]
544    fn rename_of_rename_numbers_from_two() {
545        let (genome, _, _) = guest_with_owned("boost");
546        let d0 = CorticalID::modulator_driver(0);
547        let d1 = CorticalID::modulator_driver(1);
548        let d2 = CorticalID::modulator_driver(2);
549        let plan = plan_amalgamation_modulators(
550            &genome,
551            &host(&[
552                ("boost", ModulatorKind::Reward, d0),
553                ("boost (Block A)", ModulatorKind::Reward, d1),
554            ]),
555            &HashSet::new(),
556            &rename_policy(),
557        )
558        .expect("plan");
559        assert_eq!(plan.name_map["boost"], "boost (Block A) 2");
560
561        let plan = plan_amalgamation_modulators(
562            &genome,
563            &host(&[
564                ("boost", ModulatorKind::Reward, d0),
565                ("boost (Block A)", ModulatorKind::Reward, d1),
566                ("boost (Block A) 2", ModulatorKind::Reward, d2),
567            ]),
568            &HashSet::new(),
569            &rename_policy(),
570        )
571        .expect("plan");
572        assert_eq!(plan.name_map["boost"], "boost (Block A) 3");
573    }
574
575    #[test]
576    fn clone_reuses_host_modulator_and_redirects_driver_mappings() {
577        let (mut genome, driver, src) = guest_with_owned("boost");
578        // The host driver has the same serial as the guest driver: the ids collide.
579        let host_driver = CorticalID::modulator_driver(0);
580        let plan = plan_amalgamation_modulators(
581            &genome,
582            &host(&[("boost", ModulatorKind::Reward, host_driver)]),
583            &HashSet::new(),
584            &ModulatorCollisionPolicy::ReuseHost,
585        )
586        .expect("plan");
587        assert!(plan.owned.is_empty(), "nothing is created under reuse");
588        assert_eq!(plan.name_map["boost"], "boost");
589        assert_eq!(
590            plan.notices,
591            vec!["Reused existing modulator 'boost'; host settings apply.".to_string()]
592        );
593        assert_eq!(
594            plan.reused_driver_remap[&driver.as_base_64()],
595            host_driver.as_base_64()
596        );
597        assert!(plan.orphan_driver_ids.is_empty());
598        apply_driver_remap(&mut genome, &plan.reused_driver_remap).expect("remap");
599        assert!(genome.cortical_areas.contains_key(&src));
600    }
601
602    #[test]
603    fn reuse_with_a_different_type_is_rejected_up_front() {
604        let (genome, _, _) = guest_with_owned("boost");
605        let err = plan_amalgamation_modulators(
606            &genome,
607            &host(&[(
608                "boost",
609                ModulatorKind::Leak,
610                CorticalID::modulator_driver(0),
611            )]),
612            &HashSet::new(),
613            &ModulatorCollisionPolicy::ReuseHost,
614        )
615        .expect_err("type mismatch");
616        assert!(err.to_string().contains("cannot be reused"), "{err}");
617    }
618
619    #[test]
620    fn created_owned_driver_remap_rewrites_area_keys_and_destination_keys() {
621        let (mut genome, driver, src) = guest_with_owned("boost");
622        let new_driver = CorticalID::modulator_driver(7);
623        let remap = HashMap::from([(driver.as_base_64(), new_driver.as_base_64())]);
624        apply_driver_remap(&mut genome, &remap).expect("remap");
625        assert!(genome.cortical_areas.contains_key(&new_driver));
626        assert!(!genome.cortical_areas.contains_key(&driver));
627        let dst = genome.cortical_areas[&src].properties["cortical_mapping_dst"]
628            .as_object()
629            .unwrap();
630        assert!(dst.contains_key(&new_driver.as_base_64()));
631        assert!(!dst.contains_key(&driver.as_base_64()));
632    }
633
634    #[test]
635    fn adopted_driver_follows_the_area_remap_and_is_checked_up_front() {
636        let mut genome = empty_genome("Block A");
637        let adopted_old = custom_id(b'x');
638        let adopted_new = custom_id(b'y');
639        genome
640            .cortical_areas
641            .insert(adopted_new, custom_area(adopted_new));
642        genome.modulators.insert(
643            "calm".to_string(),
644            instance(ModulatorKind::Leak, adopted_old),
645        );
646        // The area remap moves the adopted driver from `x` to `y`.
647        let remap = HashMap::from([(adopted_old.as_base_64(), adopted_new.as_base_64())]);
648        crate::amalgamation_remap::rewrite_area_references(&mut genome, &remap);
649        assert_eq!(
650            genome.modulators.get("calm").unwrap().driver_cortical_id,
651            adopted_new
652        );
653        let plan = plan_amalgamation_modulators(
654            &genome,
655            &HashMap::new(),
656            &HashSet::new(),
657            &rename_policy(),
658        )
659        .expect("plan");
660        assert_eq!(plan.adopted.len(), 1);
661        assert_eq!(plan.adopted[0].driver_cortical_id, adopted_new.as_base_64());
662        assert_eq!(
663            plan.adopted[0].write.driver_cortical_id.as_deref(),
664            Some(adopted_new.as_base_64().as_str())
665        );
666
667        // A host modulator that already uses the area blocks the import before anything exists.
668        let err = plan_amalgamation_modulators(
669            &genome,
670            &host(&[("other", ModulatorKind::Leak, adopted_new)]),
671            &HashSet::from([adopted_new.as_base_64()]),
672            &rename_policy(),
673        )
674        .expect_err("already drives");
675        assert!(err.to_string().contains("already drives"), "{err}");
676
677        // A missing adopted area is rejected.
678        genome.cortical_areas.clear();
679        let err = plan_amalgamation_modulators(
680            &genome,
681            &HashMap::new(),
682            &HashSet::new(),
683            &rename_policy(),
684        )
685        .expect_err("missing driver");
686        assert!(err.to_string().contains("neither"), "{err}");
687    }
688
689    #[test]
690    fn guest_mapping_naming_a_modulator_has_a_defined_host_name() {
691        // Zero dropped guest mappings: every modulator id on a rule resolves in the name map.
692        let (genome, _, src) = guest_with_owned("boost");
693        let plan = plan_amalgamation_modulators(
694            &genome,
695            &host(&[(
696                "boost",
697                ModulatorKind::Reward,
698                CorticalID::modulator_driver(3),
699            )]),
700            &HashSet::new(),
701            &rename_policy(),
702        )
703        .expect("plan");
704        let created: HashSet<&str> = plan
705            .owned
706            .iter()
707            .map(|m| m.host_name.as_str())
708            .chain(plan.adopted.iter().map(|m| m.host_name.as_str()))
709            .collect();
710        let dst = genome.cortical_areas[&src].properties["cortical_mapping_dst"]
711            .as_object()
712            .unwrap();
713        for rules in dst.values() {
714            for id in rules[0]["modulators"].as_array().unwrap() {
715                let id = id.as_str().unwrap();
716                if id == "other" {
717                    continue; // not a guest modulator: validated by the host as before
718                }
719                assert!(
720                    created.contains(plan.name_map[id].as_str()),
721                    "'{id}' must exist in the host after the import"
722                );
723            }
724        }
725    }
726
727    #[test]
728    fn orphan_driver_areas_are_reported() {
729        let mut genome = empty_genome("Block A");
730        let driver = CorticalID::modulator_driver(4);
731        genome
732            .cortical_areas
733            .insert(driver, area(driver, CorticalAreaType::Modulator));
734        let plan = plan_amalgamation_modulators(
735            &genome,
736            &HashMap::new(),
737            &HashSet::new(),
738            &rename_policy(),
739        )
740        .expect("plan");
741        assert_eq!(plan.orphan_driver_ids, vec![driver.as_base_64()]);
742    }
743
744    #[test]
745    fn owned_driver_tuning_differing_from_defaults_is_carried() {
746        let (mut genome, driver, _) = guest_with_owned("boost");
747        genome
748            .cortical_areas
749            .get_mut(&driver)
750            .unwrap()
751            .properties
752            .insert("firing_threshold".to_string(), serde_json::json!(2.5));
753        genome
754            .cortical_areas
755            .get_mut(&driver)
756            .unwrap()
757            .properties
758            .insert("leak_coefficient".to_string(), serde_json::json!(0.0));
759        let plan = plan_amalgamation_modulators(
760            &genome,
761            &HashMap::new(),
762            &HashSet::new(),
763            &rename_policy(),
764        )
765        .expect("plan");
766        assert_eq!(
767            plan.owned[0].driver_tuning,
768            HashMap::from([("firing_threshold".to_string(), serde_json::json!(2.5))])
769        );
770    }
771
772    fn classifier(name: &str, parent: &str, ids: [CorticalID; 4]) -> Classifier {
773        Classifier {
774            classifier_id: "guest-clf".to_string(),
775            name: name.to_string(),
776            parent_region_id: parent.to_string(),
777            coordinates_3d: [0, 0, 0],
778            sample_area_ids: vec![ids[3].as_base_64()],
779            class_bindings: vec![ClassifierClassBinding {
780                class_area_id: ids[3].as_base_64(),
781                class_output_area_id: ids[2].as_base_64(),
782            }],
783            sample_memory_id: ids[0].as_base_64(),
784            class_memory_id: ids[1].as_base_64(),
785            error_area_id: ids[2].as_base_64(),
786            correct_area_id: String::new(),
787            reward_training: true,
788            answer_feedback_area_id: None,
789            reward_modulator_ids: vec!["boost".to_string(), "keep".to_string()],
790            answer_latency_bursts: 0,
791            learn_area_id: Some(ids[3].as_base_64()),
792            confidence_area_id: None,
793            properties: HashMap::new(),
794        }
795    }
796
797    #[test]
798    fn classifier_gets_fresh_id_and_remapped_areas_modulators_and_region() {
799        let mut genome = empty_genome("Block A");
800        let old = [
801            custom_id(b'1'),
802            custom_id(b'2'),
803            custom_id(b'3'),
804            custom_id(b'4'),
805        ];
806        let new = [
807            custom_id(b'5'),
808            custom_id(b'6'),
809            custom_id(b'7'),
810            custom_id(b'8'),
811        ];
812        for id in new {
813            genome.cortical_areas.insert(id, custom_area(id));
814        }
815        genome.classifiers.insert(
816            "guest-clf".to_string(),
817            classifier("clf", "guest-region", old),
818        );
819        let area_remap: HashMap<String, String> = old
820            .iter()
821            .zip(new.iter())
822            .map(|(o, n)| (o.as_base_64(), n.as_base_64()))
823            .collect();
824        let name_map = HashMap::from([("boost".to_string(), "boost (Block A)".to_string())]);
825        let region_map = HashMap::from([("guest-region".to_string(), "new-region".to_string())]);
826
827        let planned =
828            plan_amalgamation_classifiers(&genome, &area_remap, &name_map, &region_map, "host")
829                .expect("plan");
830        assert_eq!(planned.len(), 1);
831        let c = &planned[0];
832        assert_ne!(c.classifier_id, "guest-clf");
833        assert_eq!(c.sample_memory_id, new[0].as_base_64());
834        assert_eq!(c.class_memory_id, new[1].as_base_64());
835        assert_eq!(c.error_area_id, new[2].as_base_64());
836        assert_eq!(c.sample_area_ids, vec![new[3].as_base_64()]);
837        assert_eq!(c.class_bindings[0].class_area_id, new[3].as_base_64());
838        assert_eq!(
839            c.class_bindings[0].class_output_area_id,
840            new[2].as_base_64()
841        );
842        assert_eq!(c.learn_area_id, Some(new[3].as_base_64()));
843        assert_eq!(
844            c.reward_modulator_ids,
845            vec!["boost (Block A)".to_string(), "keep".to_string()]
846        );
847        assert_eq!(c.parent_region_id, "new-region");
848
849        // Unplanned guest parent falls back to the host region.
850        let planned =
851            plan_amalgamation_classifiers(&genome, &area_remap, &name_map, &HashMap::new(), "host")
852                .expect("plan");
853        assert_eq!(planned[0].parent_region_id, "host");
854
855        // Two plans never share an id.
856        let again =
857            plan_amalgamation_classifiers(&genome, &area_remap, &name_map, &HashMap::new(), "host")
858                .expect("plan");
859        assert_ne!(planned[0].classifier_id, again[0].classifier_id);
860    }
861
862    #[test]
863    fn classifier_with_a_missing_memory_area_is_rejected() {
864        let mut genome = empty_genome("Block A");
865        let old = [
866            custom_id(b'1'),
867            custom_id(b'2'),
868            custom_id(b'3'),
869            custom_id(b'4'),
870        ];
871        genome
872            .classifiers
873            .insert("guest-clf".to_string(), classifier("clf", "r", old));
874        let err = plan_amalgamation_classifiers(
875            &genome,
876            &HashMap::new(),
877            &HashMap::new(),
878            &HashMap::new(),
879            "host",
880        )
881        .expect_err("missing memory");
882        assert!(
883            err.to_string().contains("not in the imported circuit"),
884            "{err}"
885        );
886    }
887}