Skip to main content

feagi_evolutionary/
amalgamation_fit.rs

1// Copyright 2025 Neuraville Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4/*!
5Fit a guest genome's cortical areas to the host before any area is created, and carry the wiring
6that joins the fitted block to the rest of the brain.
7
8A [`FitPlan`] lists guest cortical ids and the dimensions each must have. [`fit_areas`] is pure: it
9returns a copy of the guest areas with those dimensions and changes nothing else. Creating the
10areas at their fitted size avoids a post-creation resize, which rebuilds an area's neurons and
11synapses.
12
13A plan may also carry an adapter (new plain areas in a new brain region), morphologies (the
14existing `patterns` type, exact coordinates only) and mappings between guest, adapter and host
15areas. [`validate_plan`] checks all of it without touching a brain; the caller applies it only
16when it passes, and again re-checks it against the live host at confirmation.
17
18The plan is body-free data (area ids, names, dimensions, coordinates and mapping rules). Whoever
19builds it knows the host and the robot; this module does not.
20
21Copyright 2025 Neuraville Inc.
22Licensed under the Apache License, Version 2.0
23*/
24
25use crate::runtime::{Morphology, MorphologyParameters, MorphologyType, PatternElement};
26use feagi_structures::genomic::cortical_area::descriptors::CorticalAreaDimensions;
27use feagi_structures::genomic::cortical_area::{CorticalArea, CorticalAreaType, CorticalID};
28use serde::{Deserialize, Serialize};
29use std::collections::{HashMap, HashSet};
30use thiserror::Error;
31
32/// One fitted area: the guest cortical id (base64, as in the guest genome) and its dimensions.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub struct AreaFit {
35    pub cortical_id: String,
36    /// `[x, y, z]`; every value must be at least 1.
37    pub dimensions: [u32; 3],
38}
39
40/// One new plain area of the adapter region.
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42pub struct AdapterArea {
43    /// Base64 cortical id of a Custom area (never IO, core, memory or modulator).
44    pub cortical_id: String,
45    pub name: String,
46    /// `[x, y, z]`; every value must be at least 1.
47    pub dimensions: [u32; 3],
48}
49
50/// New areas created in a new brain region, between the block and the host's IO areas.
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52pub struct AdapterPlan {
53    /// Name of the new region; the caller picks a default when absent.
54    #[serde(default)]
55    pub region_name: Option<String>,
56    pub areas: Vec<AdapterArea>,
57}
58
59/// A `patterns` morphology with exact coordinates: each row is `[[sx,sy,sz],[dx,dy,dz]]`, the
60/// same JSON as the existing patterns type minus wildcards.
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62pub struct PlanMorphology {
63    pub name: String,
64    pub patterns: Vec<[[i32; 3]; 2]>,
65}
66
67impl PlanMorphology {
68    /// The runtime morphology this definition creates.
69    pub fn to_morphology(&self) -> Morphology {
70        Morphology {
71            morphology_type: MorphologyType::Patterns,
72            parameters: MorphologyParameters::Patterns {
73                patterns: self
74                    .patterns
75                    .iter()
76                    .map(|[src, dst]| {
77                        [
78                            src.iter().map(|v| PatternElement::Value(*v)).collect(),
79                            dst.iter().map(|v| PatternElement::Value(*v)).collect(),
80                        ]
81                    })
82                    .collect(),
83            },
84            class: "custom".to_string(),
85        }
86    }
87}
88
89/// One mapping to create. `src` and `dst` are a guest area id (as published, before the import
90/// remaps it), an adapter area id, or an existing host area id. `rules` are mapping rules in the
91/// shape `update_cortical_mapping` takes; each names a `morphology_id`.
92#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
93pub struct PlanMapping {
94    pub src: String,
95    pub dst: String,
96    pub rules: Vec<serde_json::Value>,
97}
98
99/// What the guest's areas must look like on the host, and the wiring to add around them. Every
100/// field but `areas` is optional; an absent field changes nothing.
101#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
102pub struct FitPlan {
103    #[serde(default)]
104    pub areas: Vec<AreaFit>,
105    #[serde(default)]
106    pub adapter: Option<AdapterPlan>,
107    #[serde(default)]
108    pub morphologies: Vec<PlanMorphology>,
109    #[serde(default)]
110    pub mappings: Vec<PlanMapping>,
111}
112
113impl FitPlan {
114    /// True when the plan adds an adapter, morphologies or mappings (not only dimensions).
115    pub fn has_wiring(&self) -> bool {
116        self.adapter.is_some() || !self.morphologies.is_empty() || !self.mappings.is_empty()
117    }
118}
119
120/// Why a plan was refused. Nothing is changed when one is returned.
121#[derive(Debug, Error, PartialEq, Eq)]
122pub enum FitPlanError {
123    #[error("fit plan names guest area '{0}', which is not in the guest genome")]
124    UnknownArea(String),
125    #[error("fit plan gives area '{cortical_id}' a zero dimension {dimensions:?}")]
126    ZeroDimension {
127        cortical_id: String,
128        dimensions: [u32; 3],
129    },
130    #[error("fit plan targets IO area '{0}'; IO areas keep their size")]
131    IoArea(String),
132    #[error("fit plan names guest area '{0}' more than once")]
133    DuplicateArea(String),
134    #[error("fit plan has an invalid cortical id '{0}'")]
135    InvalidCorticalId(String),
136    #[error("adapter lists no areas")]
137    EmptyAdapter,
138    #[error("adapter area '{0}' is an IO area; adapter areas are plain custom areas")]
139    AdapterIoArea(String),
140    #[error("adapter area '{0}' is not a custom area; adapter areas are plain custom areas")]
141    AdapterNotCustom(String),
142    #[error("adapter area '{0}' has a zero dimension or an empty name")]
143    AdapterBadArea(String),
144    #[error(
145        "adapter area id '{0}' is listed twice, or is also a guest area or an existing host area"
146    )]
147    AdapterIdClash(String),
148    #[error("morphology '{0}' is defined twice in the plan")]
149    DuplicateMorphology(String),
150    #[error("morphology '{0}' has no name or no rows")]
151    EmptyMorphology(String),
152    #[error("morphology '{0}' clashes with a guest or host morphology of the same name")]
153    MorphologyClash(String),
154    #[error("mapping end '{0}' is not a guest area, an adapter area or an existing host area")]
155    UnknownEnd(String),
156    #[error("mapping end '{0}' is a guest area that is not created fresh (only custom and memory guest areas can be wired by a plan; name the host area instead)")]
157    GuestEndNotFresh(String),
158    #[error("mapping {src} -> {dst} is listed twice")]
159    DuplicateMapping { src: String, dst: String },
160    #[error("mapping {src} -> {dst} is already wired by the guest genome")]
161    GuestMappingConflict { src: String, dst: String },
162    #[error("mapping {src} -> {dst} has no rules")]
163    EmptyRules { src: String, dst: String },
164    #[error("mapping {src} -> {dst} has a bad rule: {reason}")]
165    BadRule {
166        src: String,
167        dst: String,
168        reason: String,
169    },
170    #[error("{0}")]
171    PatternOutOfBounds(Box<PatternBounds>),
172}
173
174/// A `patterns` row that falls outside the area at one of its ends.
175#[derive(Debug, PartialEq, Eq)]
176pub struct PatternBounds {
177    pub morphology: String,
178    pub row: usize,
179    /// `"source"` or `"destination"`.
180    pub end: &'static str,
181    pub coordinate: [i32; 3],
182    pub area: String,
183    pub dimensions: [u32; 3],
184    pub src: String,
185    pub dst: String,
186}
187
188impl std::fmt::Display for PatternBounds {
189    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
190        write!(
191            f,
192            "morphology '{}' row {}: {} coordinate {:?} is outside the {} area {} of size {:?} \
193             (mapping {} -> {})",
194            self.morphology,
195            self.row,
196            self.end,
197            self.coordinate,
198            self.end,
199            self.area,
200            self.dimensions,
201            self.src,
202            self.dst
203        )
204    }
205}
206
207/// Return `areas` with the plan's dimensions applied. Validates the whole plan first; on any error
208/// nothing is returned. An empty plan returns an unchanged copy.
209pub fn fit_areas(
210    areas: &HashMap<CorticalID, CorticalArea>,
211    plan: &FitPlan,
212) -> Result<HashMap<CorticalID, CorticalArea>, FitPlanError> {
213    let by_b64: HashMap<String, CorticalID> =
214        areas.keys().map(|id| (id.as_base_64(), *id)).collect();
215    let mut seen: HashSet<&str> = HashSet::new();
216    let mut resolved: Vec<(CorticalID, CorticalAreaDimensions)> = Vec::new();
217    for fit in &plan.areas {
218        let id = by_b64
219            .get(&fit.cortical_id)
220            .ok_or_else(|| FitPlanError::UnknownArea(fit.cortical_id.clone()))?;
221        if !seen.insert(fit.cortical_id.as_str()) {
222            return Err(FitPlanError::DuplicateArea(fit.cortical_id.clone()));
223        }
224        if matches!(
225            areas[id].cortical_type,
226            CorticalAreaType::BrainInput(_) | CorticalAreaType::BrainOutput(_)
227        ) {
228            return Err(FitPlanError::IoArea(fit.cortical_id.clone()));
229        }
230        let [x, y, z] = fit.dimensions;
231        let dims =
232            CorticalAreaDimensions::new(x, y, z).map_err(|_| FitPlanError::ZeroDimension {
233                cortical_id: fit.cortical_id.clone(),
234                dimensions: fit.dimensions,
235            })?;
236        resolved.push((*id, dims));
237    }
238    let mut fitted = areas.clone();
239    for (id, dims) in resolved {
240        if let Some(area) = fitted.get_mut(&id) {
241            area.dimensions = dims;
242        }
243    }
244    Ok(fitted)
245}
246
247/// Everything outside the plan that its validation reads.
248pub struct PlanContext<'a> {
249    /// Guest areas after [`fit_areas`] (fitted dimensions, published ids).
250    pub guest_areas: &'a HashMap<CorticalID, CorticalArea>,
251    /// Names of the guest genome's morphologies.
252    pub guest_morphologies: &'a HashSet<String>,
253    /// Dimensions of every id from [`plan_host_lookup_ids`] that exists on the host.
254    pub host_areas: &'a HashMap<String, [u32; 3]>,
255    /// Names of the host's morphologies.
256    pub host_morphologies: &'a HashSet<String>,
257}
258
259/// Ids the caller must look up on the host before validating: adapter ids (they must not exist)
260/// and mapping ends that are neither guest nor adapter areas (they must exist). Sorted, unique.
261pub fn plan_host_lookup_ids(
262    guest_areas: &HashMap<CorticalID, CorticalArea>,
263    plan: &FitPlan,
264) -> Vec<String> {
265    let guest: HashSet<String> = guest_areas.keys().map(CorticalID::as_base_64).collect();
266    let adapter: HashSet<&str> = plan
267        .adapter
268        .iter()
269        .flat_map(|a| a.areas.iter().map(|x| x.cortical_id.as_str()))
270        .collect();
271    let mut ids: Vec<String> = adapter.iter().map(|id| id.to_string()).collect();
272    for mapping in &plan.mappings {
273        for end in [&mapping.src, &mapping.dst] {
274            if !guest.contains(end) && !adapter.contains(end.as_str()) {
275                ids.push(end.clone());
276            }
277        }
278    }
279    ids.sort();
280    ids.dedup();
281    ids
282}
283
284/// Validate the adapter, morphologies and mappings of `plan` (not its `areas`; [`fit_areas`] does
285/// those). Pure: reads only `ctx`. Run it when the plan is queued and again at confirmation with
286/// freshly read host data.
287pub fn validate_plan(ctx: &PlanContext, plan: &FitPlan) -> Result<(), FitPlanError> {
288    let guest_ids: HashSet<String> = ctx.guest_areas.keys().map(CorticalID::as_base_64).collect();
289
290    // Adapter areas: plain custom areas with ids nobody else uses.
291    let mut adapter_dims: HashMap<&str, [u32; 3]> = HashMap::new();
292    if let Some(adapter) = &plan.adapter {
293        if adapter.areas.is_empty() {
294            return Err(FitPlanError::EmptyAdapter);
295        }
296        for area in &adapter.areas {
297            let id = CorticalID::try_from_base_64(&area.cortical_id)
298                .map_err(|_| FitPlanError::InvalidCorticalId(area.cortical_id.clone()))?;
299            match id.as_cortical_type() {
300                Ok(CorticalAreaType::Custom(_)) => {}
301                Ok(CorticalAreaType::BrainInput(_) | CorticalAreaType::BrainOutput(_)) => {
302                    return Err(FitPlanError::AdapterIoArea(area.cortical_id.clone()))
303                }
304                _ => return Err(FitPlanError::AdapterNotCustom(area.cortical_id.clone())),
305            }
306            if area.name.trim().is_empty() || area.dimensions.contains(&0) {
307                return Err(FitPlanError::AdapterBadArea(area.cortical_id.clone()));
308            }
309            if adapter_dims
310                .insert(area.cortical_id.as_str(), area.dimensions)
311                .is_some()
312                || guest_ids.contains(&area.cortical_id)
313                || ctx.host_areas.contains_key(&area.cortical_id)
314            {
315                return Err(FitPlanError::AdapterIdClash(area.cortical_id.clone()));
316            }
317        }
318    }
319
320    // Morphologies: unique names, no clash with guest or host, at least one row.
321    let mut morphologies: HashMap<&str, &PlanMorphology> = HashMap::new();
322    for morphology in &plan.morphologies {
323        if morphology.name.trim().is_empty() || morphology.patterns.is_empty() {
324            return Err(FitPlanError::EmptyMorphology(morphology.name.clone()));
325        }
326        if morphologies
327            .insert(morphology.name.as_str(), morphology)
328            .is_some()
329        {
330            return Err(FitPlanError::DuplicateMorphology(morphology.name.clone()));
331        }
332        if ctx.guest_morphologies.contains(&morphology.name)
333            || ctx.host_morphologies.contains(&morphology.name)
334        {
335            return Err(FitPlanError::MorphologyClash(morphology.name.clone()));
336        }
337    }
338
339    // Mappings: known ends, rules that name a morphology, rows inside both ends' dimensions.
340    let end_dims = |end: &str| -> Result<[u32; 3], FitPlanError> {
341        if let Some(dims) = adapter_dims.get(end) {
342            return Ok(*dims);
343        }
344        if guest_ids.contains(end) {
345            let id = CorticalID::try_from_base_64(end)
346                .map_err(|_| FitPlanError::InvalidCorticalId(end.to_string()))?;
347            let area = &ctx.guest_areas[&id];
348            if !matches!(
349                area.cortical_type,
350                CorticalAreaType::Custom(_) | CorticalAreaType::Memory(_)
351            ) {
352                return Err(FitPlanError::GuestEndNotFresh(end.to_string()));
353            }
354            let d = &area.dimensions;
355            return Ok([d.width, d.height, d.depth]);
356        }
357        ctx.host_areas
358            .get(end)
359            .copied()
360            .ok_or_else(|| FitPlanError::UnknownEnd(end.to_string()))
361    };
362    let mut pairs: HashSet<(&str, &str)> = HashSet::new();
363    for mapping in &plan.mappings {
364        let (src, dst) = (mapping.src.as_str(), mapping.dst.as_str());
365        let src_dims = end_dims(src)?;
366        let dst_dims = end_dims(dst)?;
367        let pair_err = || FitPlanError::DuplicateMapping {
368            src: mapping.src.clone(),
369            dst: mapping.dst.clone(),
370        };
371        if !pairs.insert((src, dst)) {
372            return Err(pair_err());
373        }
374        if let Ok(id) = CorticalID::try_from_base_64(src) {
375            let wired = ctx
376                .guest_areas
377                .get(&id)
378                .and_then(|a| a.properties.get("cortical_mapping_dst"))
379                .and_then(|v| v.as_object())
380                .is_some_and(|dsts| dsts.contains_key(dst));
381            if wired {
382                return Err(FitPlanError::GuestMappingConflict {
383                    src: mapping.src.clone(),
384                    dst: mapping.dst.clone(),
385                });
386            }
387        }
388        if mapping.rules.is_empty() {
389            return Err(FitPlanError::EmptyRules {
390                src: mapping.src.clone(),
391                dst: mapping.dst.clone(),
392            });
393        }
394        for rule in &mapping.rules {
395            let bad = |reason: &str| FitPlanError::BadRule {
396                src: mapping.src.clone(),
397                dst: mapping.dst.clone(),
398                reason: reason.to_string(),
399            };
400            let name = rule
401                .as_object()
402                .ok_or_else(|| bad("a rule must be an object"))?
403                .get("morphology_id")
404                .and_then(|v| v.as_str())
405                .ok_or_else(|| bad("a rule must name a string 'morphology_id'"))?;
406            // A morphology not defined by the plan is the host's or the guest's; the caller
407            // checks it exists when it applies the plan.
408            let Some(morphology) = morphologies.get(name) else {
409                continue;
410            };
411            for (row, [from, to]) in morphology.patterns.iter().enumerate() {
412                for (end, coordinate, area, dims) in [
413                    ("source", from, src, src_dims),
414                    ("destination", to, dst, dst_dims),
415                ] {
416                    let inside = coordinate
417                        .iter()
418                        .zip(dims.iter())
419                        .all(|(c, d)| *c >= 0 && (*c as i64) < i64::from(*d));
420                    if !inside {
421                        return Err(FitPlanError::PatternOutOfBounds(Box::new(PatternBounds {
422                            morphology: name.to_string(),
423                            row,
424                            end,
425                            coordinate: *coordinate,
426                            area: area.to_string(),
427                            dimensions: dims,
428                            src: mapping.src.clone(),
429                            dst: mapping.dst.clone(),
430                        })));
431                    }
432                }
433            }
434        }
435    }
436    Ok(())
437}
438
439#[cfg(test)]
440mod tests {
441    use super::*;
442    use feagi_structures::genomic::cortical_area::CustomCorticalType;
443    use feagi_structures::genomic::descriptors::GenomeCoordinate3D;
444
445    fn custom_id(tag: u8) -> CorticalID {
446        let mut bytes = [b'a'; CorticalID::CORTICAL_ID_LENGTH];
447        bytes[0] = b'c';
448        bytes[1] = tag;
449        CorticalID::try_from_bytes(&bytes).expect("custom id")
450    }
451
452    fn area(id: CorticalID, w: u32, h: u32, d: u32) -> CorticalArea {
453        CorticalArea::new(
454            id,
455            0,
456            "area".to_string(),
457            CorticalAreaDimensions::new(w, h, d).expect("dims"),
458            GenomeCoordinate3D::new(0, 0, 0),
459            CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire),
460        )
461        .expect("area")
462    }
463
464    fn areas() -> (HashMap<CorticalID, CorticalArea>, CorticalID, CorticalID) {
465        let (a, b) = (custom_id(b'a'), custom_id(b'b'));
466        (
467            HashMap::from([(a, area(a, 12, 1, 1)), (b, area(b, 3, 1, 1))]),
468            a,
469            b,
470        )
471    }
472
473    fn fit(id: &CorticalID, dimensions: [u32; 3]) -> AreaFit {
474        AreaFit {
475            cortical_id: id.as_base_64(),
476            dimensions,
477        }
478    }
479
480    #[test]
481    fn fit_applies_dimensions_and_leaves_others() {
482        let (areas, a, b) = areas();
483        let plan = FitPlan {
484            areas: vec![fit(&a, [14, 1, 1])],
485            ..Default::default()
486        };
487        let fitted = fit_areas(&areas, &plan).expect("fit");
488        assert_eq!(fitted[&a].dimensions.width, 14);
489        assert_eq!(fitted[&b].dimensions, areas[&b].dimensions);
490        assert_eq!(areas[&a].dimensions.width, 12, "input is not modified");
491    }
492
493    #[test]
494    fn fit_empty_plan_is_identity() {
495        let (areas, a, _) = areas();
496        let fitted = fit_areas(&areas, &FitPlan::default()).expect("fit");
497        assert_eq!(fitted[&a].dimensions, areas[&a].dimensions);
498        assert_eq!(fitted.len(), areas.len());
499    }
500
501    #[test]
502    fn fit_rejects_unknown_area() {
503        let (areas, _, _) = areas();
504        let ghost = custom_id(b'z');
505        let plan = FitPlan {
506            areas: vec![fit(&ghost, [2, 1, 1])],
507            ..Default::default()
508        };
509        assert_eq!(
510            fit_areas(&areas, &plan).unwrap_err(),
511            FitPlanError::UnknownArea(ghost.as_base_64())
512        );
513    }
514
515    #[test]
516    fn fit_rejects_zero_dimension_and_changes_nothing() {
517        let (areas, a, b) = areas();
518        let plan = FitPlan {
519            areas: vec![fit(&a, [14, 1, 1]), fit(&b, [0, 1, 1])],
520            ..Default::default()
521        };
522        assert!(matches!(
523            fit_areas(&areas, &plan).unwrap_err(),
524            FitPlanError::ZeroDimension { .. }
525        ));
526        assert_eq!(areas[&a].dimensions.width, 12);
527    }
528
529    #[test]
530    fn fit_rejects_duplicate_area() {
531        let (areas, a, _) = areas();
532        let plan = FitPlan {
533            areas: vec![fit(&a, [14, 1, 1]), fit(&a, [15, 1, 1])],
534            ..Default::default()
535        };
536        assert_eq!(
537            fit_areas(&areas, &plan).unwrap_err(),
538            FitPlanError::DuplicateArea(a.as_base_64())
539        );
540    }
541
542    #[test]
543    fn fit_rejects_io_area() {
544        use feagi_structures::genomic::cortical_area::IOCorticalAreaConfigurationFlag;
545        let (mut areas, _, _) = areas();
546        let io_flag = IOCorticalAreaConfigurationFlag::Boolean;
547        let io_id = io_flag.as_io_cortical_id(true, *b"tst", 0u8.into(), 0u8.into());
548        let mut io = area(io_id, 4, 1, 1);
549        io.cortical_type = CorticalAreaType::BrainOutput(io_flag);
550        areas.insert(io_id, io);
551        let plan = FitPlan {
552            areas: vec![fit(&io_id, [6, 1, 1])],
553            ..Default::default()
554        };
555        assert_eq!(
556            fit_areas(&areas, &plan).unwrap_err(),
557            FitPlanError::IoArea(io_id.as_base_64())
558        );
559    }
560
561    // ---- wiring: adapter, morphologies, mappings --------------------------------------------
562
563    fn adapter_id(tag: u8) -> String {
564        custom_id(tag).as_base_64()
565    }
566
567    fn host_id() -> String {
568        // A host area id the guest does not have.
569        custom_id(b'h').as_base_64()
570    }
571
572    fn rows(n: i32) -> Vec<[[i32; 3]; 2]> {
573        (0..n).map(|i| [[i, 0, 0], [i, 0, 0]]).collect()
574    }
575
576    fn wiring(src_dims: u32, adapter_w: u32, host_w: u32) -> (FitPlan, HashMap<String, [u32; 3]>) {
577        let (a, _) = (custom_id(b'a'), ());
578        let plan = FitPlan {
579            areas: vec![fit(&a, [src_dims, 1, 1])],
580            adapter: Some(AdapterPlan {
581                region_name: None,
582                areas: vec![AdapterArea {
583                    cortical_id: adapter_id(b'x'),
584                    name: "adapt".to_string(),
585                    dimensions: [adapter_w, 1, 1],
586                }],
587            }),
588            morphologies: vec![PlanMorphology {
589                name: "one_to_one".to_string(),
590                patterns: rows(src_dims as i32),
591            }],
592            mappings: vec![
593                PlanMapping {
594                    src: a.as_base_64(),
595                    dst: adapter_id(b'x'),
596                    rules: vec![serde_json::json!({ "morphology_id": "one_to_one" })],
597                },
598                PlanMapping {
599                    src: adapter_id(b'x'),
600                    dst: host_id(),
601                    rules: vec![serde_json::json!({ "morphology_id": "one_to_one" })],
602                },
603            ],
604        };
605        (plan, HashMap::from([(host_id(), [host_w, 1, 1])]))
606    }
607
608    fn check(plan: &FitPlan, host: &HashMap<String, [u32; 3]>) -> Result<(), FitPlanError> {
609        let (areas, a, _) = areas();
610        let fitted = fit_areas(&areas, plan).expect("fit");
611        let _ = a;
612        validate_plan(
613            &PlanContext {
614                guest_areas: &fitted,
615                guest_morphologies: &HashSet::from(["projector".to_string()]),
616                host_areas: host,
617                host_morphologies: &HashSet::from(["host_morph".to_string()]),
618            },
619            plan,
620        )
621    }
622
623    #[test]
624    fn plan_with_wiring_validates_and_lists_host_lookups() {
625        let (plan, host) = wiring(14, 14, 14);
626        check(&plan, &host).expect("valid");
627        let (areas, _, _) = areas();
628        let mut expected = vec![adapter_id(b'x'), host_id()];
629        expected.sort();
630        assert_eq!(plan_host_lookup_ids(&areas, &plan), expected);
631        assert!(plan.has_wiring() && !FitPlan::default().has_wiring());
632        let json = serde_json::to_string(&plan).expect("json");
633        assert_eq!(serde_json::from_str::<FitPlan>(&json).expect("round"), plan);
634    }
635
636    #[test]
637    fn depth_mismatch_between_strip_and_host_area_is_refused() {
638        // 14 rows against a 13-wide host area: row 13 falls outside the destination.
639        let (plan, host) = wiring(14, 14, 13);
640        match check(&plan, &host).unwrap_err() {
641            FitPlanError::PatternOutOfBounds(bounds) => {
642                assert_eq!((bounds.row, bounds.end), (13, "destination"))
643            }
644            other => panic!("{other}"),
645        }
646    }
647
648    #[test]
649    fn bad_wiring_plans_are_refused() {
650        let (good, host) = wiring(14, 14, 14);
651        let mut unknown = good.clone();
652        unknown.mappings[1].dst = adapter_id(b'q');
653        assert!(matches!(
654            check(&unknown, &host).unwrap_err(),
655            FitPlanError::UnknownEnd(_)
656        ));
657        let mut dup_morph = good.clone();
658        dup_morph
659            .morphologies
660            .push(dup_morph.morphologies[0].clone());
661        assert!(matches!(
662            check(&dup_morph, &host).unwrap_err(),
663            FitPlanError::DuplicateMorphology(_)
664        ));
665        for name in ["projector", "host_morph"] {
666            let mut clash = good.clone();
667            clash.morphologies[0].name = name.to_string();
668            assert!(matches!(
669                check(&clash, &host).unwrap_err(),
670                FitPlanError::MorphologyClash(_)
671            ));
672        }
673        let mut io = good.clone();
674        io.adapter.as_mut().unwrap().areas[0].cortical_id = {
675            use feagi_structures::genomic::cortical_area::IOCorticalAreaConfigurationFlag as F;
676            F::Boolean
677                .as_io_cortical_id(true, *b"tst", 0u8.into(), 0u8.into())
678                .as_base_64()
679        };
680        assert!(matches!(
681            check(&io, &host).unwrap_err(),
682            FitPlanError::AdapterIoArea(_)
683        ));
684        let mut on_host = good.clone();
685        on_host.adapter.as_mut().unwrap().areas[0].cortical_id = host_id();
686        assert!(matches!(
687            check(&on_host, &host).unwrap_err(),
688            FitPlanError::AdapterIdClash(_)
689        ));
690        let mut dup_map = good.clone();
691        dup_map.mappings.push(dup_map.mappings[0].clone());
692        assert!(matches!(
693            check(&dup_map, &host).unwrap_err(),
694            FitPlanError::DuplicateMapping { .. }
695        ));
696        let mut no_rules = good.clone();
697        no_rules.mappings[0].rules.clear();
698        assert!(matches!(
699            check(&no_rules, &host).unwrap_err(),
700            FitPlanError::EmptyRules { .. }
701        ));
702        let mut bad_rule = good;
703        bad_rule.mappings[0].rules = vec![serde_json::json!({ "no_morphology": 1 })];
704        assert!(matches!(
705            check(&bad_rule, &host).unwrap_err(),
706            FitPlanError::BadRule { .. }
707        ));
708    }
709
710    #[test]
711    fn wildcard_rows_do_not_parse() {
712        let bad = serde_json::json!({ "name": "w", "patterns": [[["*", 0, 0], [0, 0, 0]]] });
713        assert!(serde_json::from_value::<PlanMorphology>(bad).is_err());
714    }
715}