Skip to main content

feagi_brain_development/
neuroembryogenesis.rs

1// Copyright 2025 Neuraville Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4/*!
5Neuroembryogenesis - Brain Development from Genome.
6
7This module orchestrates the development of a functional connectome (phenotype)
8from a genome blueprint (genotype). It coordinates:
9
101. **Corticogenesis**: Creating cortical area structures
112. **Voxelogenesis**: Establishing 3D spatial framework
123. **Neurogenesis**: Generating neurons within cortical areas
134. **Synaptogenesis**: Forming synaptic connections between neurons
14
15The process is biologically inspired by embryonic brain development.
16
17Copyright 2025 Neuraville Inc.
18Licensed under the Apache License, Version 2.0
19*/
20
21use crate::connectome_manager::ConnectomeManager;
22use crate::models::{CorticalArea, CorticalID};
23use crate::types::{BduError, BduResult};
24use feagi_evolutionary::{
25    apply_genome_title_to_unique_top_circuit, wrap_parentless_regions_under_named_root,
26    RuntimeGenome,
27};
28use feagi_npu_neural::types::{Precision, QuantizationSpec};
29use feagi_structures::genomic::brain_regions::ROOT_BRAIN_REGION_NAME;
30use parking_lot::RwLock;
31use std::sync::Arc;
32use tracing::{debug, error, info, trace, warn};
33
34/// Label for the CUSTOM/MEMORY subregion when the genome JSON has no `brain_regions` and
35/// neuroembryogenesis must synthesize one. Prefer `metadata.genome_title` so Hub replace/upload
36/// shows the circuit title instead of the generic "Autogen Circuit".
37fn autogen_subregion_display_name(genome_title: &str) -> String {
38    let t = genome_title.trim();
39    if t.is_empty() || t.eq_ignore_ascii_case("untitled") {
40        "Autogen Circuit".to_string()
41    } else {
42        t.to_string()
43    }
44}
45
46/// Order region IDs so every parent in `region_ids` is emitted before its children.
47///
48/// Genome `brain_regions` is a `HashMap`, so iteration order is not stable. Inserting in
49/// that order fails whenever a nested child (e.g. grandchild of root) is visited before
50/// its parent. Kahn's algorithm makes insert order independent of hashing.
51///
52/// A region's in-degree is 1 only when its parent is also in `region_ids`. Regions whose
53/// parent is the already-inserted root (or missing from this set) start ready.
54/// Cyclic leftovers are appended after the acyclic prefix so the caller still attempts
55/// insert and surfaces the existing "Parent region does not exist" error.
56fn order_regions_parent_before_child(
57    region_ids: &[String],
58    region_parent_map: &std::collections::HashMap<String, String>,
59) -> Vec<String> {
60    use std::collections::{HashMap, HashSet, VecDeque};
61
62    let id_set: HashSet<&str> = region_ids.iter().map(String::as_str).collect();
63    let mut children: HashMap<&str, Vec<&str>> = HashMap::new();
64    let mut in_degree: HashMap<&str, usize> =
65        region_ids.iter().map(|id| (id.as_str(), 0usize)).collect();
66
67    for id in region_ids {
68        if let Some(parent) = region_parent_map.get(id) {
69            if id_set.contains(parent.as_str()) {
70                if let Some(degree) = in_degree.get_mut(id.as_str()) {
71                    *degree += 1;
72                }
73                children
74                    .entry(parent.as_str())
75                    .or_default()
76                    .push(id.as_str());
77            }
78        }
79    }
80
81    let mut ready: Vec<&str> = in_degree
82        .iter()
83        .filter(|(_, degree)| **degree == 0)
84        .map(|(id, _)| *id)
85        .collect();
86    ready.sort_unstable();
87
88    let mut ordered = Vec::with_capacity(region_ids.len());
89    let mut queue: VecDeque<&str> = ready.into();
90
91    while let Some(id) = queue.pop_front() {
92        ordered.push(id.to_string());
93        if let Some(kids) = children.get_mut(id) {
94            kids.sort_unstable();
95            for child in kids.iter().copied() {
96                if let Some(degree) = in_degree.get_mut(child) {
97                    *degree -= 1;
98                    if *degree == 0 {
99                        queue.push_back(child);
100                    }
101                }
102            }
103        }
104    }
105
106    if ordered.len() < region_ids.len() {
107        let emitted: HashSet<&str> = ordered.iter().map(String::as_str).collect();
108        let mut leftovers: Vec<String> = region_ids
109            .iter()
110            .filter(|id| !emitted.contains(id.as_str()))
111            .cloned()
112            .collect();
113        leftovers.sort();
114        ordered.extend(leftovers);
115    }
116
117    ordered
118}
119
120/// Development stage tracking
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122pub enum DevelopmentStage {
123    /// Initial state, not started
124    Initialization,
125    /// Creating cortical area structures
126    Corticogenesis,
127    /// Establishing spatial framework
128    Voxelogenesis,
129    /// Generating neurons
130    Neurogenesis,
131    /// Forming synaptic connections
132    Synaptogenesis,
133    /// Development completed successfully
134    Completed,
135    /// Development failed
136    Failed,
137}
138
139/// Development progress information
140#[derive(Debug, Clone)]
141pub struct DevelopmentProgress {
142    /// Current development stage
143    pub stage: DevelopmentStage,
144    /// Progress percentage within current stage (0-100)
145    pub progress: u8,
146    /// Cortical areas created
147    pub cortical_areas_created: usize,
148    /// Neurons created
149    pub neurons_created: usize,
150    /// Synapses created
151    pub synapses_created: usize,
152    /// Duration of development in milliseconds
153    pub duration_ms: u64,
154}
155
156impl Default for DevelopmentProgress {
157    fn default() -> Self {
158        Self {
159            stage: DevelopmentStage::Initialization,
160            progress: 0,
161            cortical_areas_created: 0,
162            neurons_created: 0,
163            synapses_created: 0,
164            duration_ms: 0,
165        }
166    }
167}
168
169/// Neuroembryogenesis orchestrator
170///
171/// Manages the development of a brain from genome instructions.
172/// Uses ConnectomeManager to build the actual neural structures.
173///
174/// # Type Parameters
175/// - `T: NeuralValue`: The numeric precision for the connectome (f32, INT8Value, f16)
176pub struct Neuroembryogenesis {
177    /// Reference to ConnectomeManager for building structures
178    connectome_manager: Arc<RwLock<ConnectomeManager>>,
179
180    /// Current development progress
181    progress: Arc<RwLock<DevelopmentProgress>>,
182
183    /// Start time for duration tracking
184    start_time: std::time::Instant,
185}
186
187/// Order in which a genome's areas are registered: core areas first in reserved index order,
188/// then areas with a stored index in index order, then areas without one by id.
189///
190/// `genome.cortical_areas` is a `HashMap`, so iterating it registers areas in a different order
191/// on every load. That breaks the rule that core area `n` owns neuron `n` and gives the other
192/// areas different indices each time.
193pub fn registration_order_key(cortical_id: &CorticalID, area: &CorticalArea) -> (u8, u32, String) {
194    use feagi_structures::genomic::cortical_area::CoreCorticalType;
195
196    const CORE_ORDER: [CoreCorticalType; 7] = [
197        CoreCorticalType::Death,
198        CoreCorticalType::Power,
199        CoreCorticalType::Fatigue,
200        CoreCorticalType::Pain,
201        CoreCorticalType::Pleasure,
202        CoreCorticalType::Fear,
203        CoreCorticalType::Hope,
204    ];
205    if let Some(position) = CORE_ORDER
206        .iter()
207        .position(|core| core.to_cortical_id() == *cortical_id)
208    {
209        return (0, position as u32, String::new());
210    }
211    if area.cortical_idx != 0 {
212        return (1, area.cortical_idx, cortical_id.as_base_64());
213    }
214    (2, 0, cortical_id.as_base_64())
215}
216
217/// The genome's areas in registration order (see [`registration_order_key`]).
218fn ordered_genome_areas(genome: &RuntimeGenome) -> Vec<(&CorticalID, &CorticalArea)> {
219    let mut areas: Vec<(&CorticalID, &CorticalArea)> = genome.cortical_areas.iter().collect();
220    areas.sort_by_key(|(cortical_id, area)| registration_order_key(cortical_id, area));
221    areas
222}
223
224impl Neuroembryogenesis {
225    /// Create a new neuroembryogenesis instance
226    pub fn new(connectome_manager: Arc<RwLock<ConnectomeManager>>) -> Self {
227        Self {
228            connectome_manager,
229            progress: Arc::new(RwLock::new(DevelopmentProgress::default())),
230            start_time: std::time::Instant::now(),
231        }
232    }
233
234    /// Get current development progress
235    pub fn get_progress(&self) -> DevelopmentProgress {
236        self.progress.read().clone()
237    }
238
239    /// Sync existing core neuron parameters with cortical area properties.
240    ///
241    /// This updates neuron parameters in-place without creating new neurons.
242    fn sync_core_neuron_params(&self, cortical_idx: u32, area: &CorticalArea) -> BduResult<()> {
243        use crate::models::CorticalAreaExt;
244
245        let npu_arc = {
246            let manager = self.connectome_manager.read();
247            manager
248                .get_npu()
249                .cloned()
250                .ok_or_else(|| BduError::Internal("NPU not connected".to_string()))?
251        };
252
253        let mut npu_lock = npu_arc
254            .lock()
255            .map_err(|e| BduError::Internal(format!("Failed to lock NPU: {}", e)))?;
256
257        npu_lock.update_cortical_area_threshold_with_gradient(
258            cortical_idx,
259            area.firing_threshold(),
260            area.firing_threshold_increment_x(),
261            area.firing_threshold_increment_y(),
262            area.firing_threshold_increment_z(),
263        );
264        npu_lock.update_cortical_area_threshold_limit(cortical_idx, area.firing_threshold_limit());
265        npu_lock.update_cortical_area_leak(cortical_idx, area.leak_coefficient());
266        npu_lock.update_cortical_area_excitability(cortical_idx, area.neuron_excitability());
267        npu_lock.update_cortical_area_refractory_period(cortical_idx, area.refractory_period());
268        npu_lock.update_cortical_area_consecutive_fire_limit(
269            cortical_idx,
270            area.consecutive_fire_count() as u16,
271        );
272        npu_lock.update_cortical_area_snooze_period(cortical_idx, area.snooze_period());
273        npu_lock.update_cortical_area_mp_charge_accumulation(
274            cortical_idx,
275            area.mp_charge_accumulation(),
276        );
277
278        Ok(())
279    }
280
281    /// Incrementally add cortical areas to an existing connectome
282    ///
283    /// This is for adding new cortical areas after the initial genome has been loaded.
284    /// Unlike `develop_from_genome()`, this only processes the new areas.
285    ///
286    /// # Arguments
287    /// * `areas` - The cortical areas to add
288    /// * `genome` - The full runtime genome (needed for synaptogenesis context)
289    ///
290    /// # Returns
291    /// * Number of neurons created and synapses created
292    pub fn add_cortical_areas(
293        &mut self,
294        areas: Vec<CorticalArea>,
295        genome: &RuntimeGenome,
296    ) -> BduResult<(usize, usize)> {
297        info!(target: "feagi-bdu", "🧬 Incrementally adding {} cortical areas", areas.len());
298
299        let mut total_neurons = 0;
300        let mut total_synapses = 0;
301
302        // Stage 1: Add cortical area structures (Corticogenesis)
303        for area in &areas {
304            let mut manager = self.connectome_manager.write();
305            manager.add_cortical_area(area.clone())?;
306            info!(target: "feagi-bdu", "  ✓ Added cortical area structure: {}", area.cortical_id.as_base_64());
307        }
308
309        // Stage 2: Create neurons for each area (Neurogenesis)
310        // CRITICAL: Create core area neurons FIRST to ensure deterministic IDs
311        use feagi_structures::genomic::cortical_area::CoreCorticalType;
312        let death_id = CoreCorticalType::Death.to_cortical_id();
313        let power_id = CoreCorticalType::Power.to_cortical_id();
314        let fatigue_id = CoreCorticalType::Fatigue.to_cortical_id();
315        let pain_id = CoreCorticalType::Pain.to_cortical_id();
316        let pleasure_id = CoreCorticalType::Pleasure.to_cortical_id();
317        let fear_id = CoreCorticalType::Fear.to_cortical_id();
318        let hope_id = CoreCorticalType::Hope.to_cortical_id();
319
320        let mut core_areas = Vec::new();
321        let mut other_areas = Vec::new();
322
323        // Separate core areas from other areas
324        for area in &areas {
325            if area.cortical_id == death_id {
326                core_areas.push((0, area)); // Area 0 = _death
327            } else if area.cortical_id == power_id {
328                core_areas.push((1, area)); // Area 1 = _power
329            } else if area.cortical_id == fatigue_id {
330                core_areas.push((2, area)); // Area 2 = _fatigue
331            } else if area.cortical_id == pain_id {
332                core_areas.push((3, area)); // Area 3 = _pain
333            } else if area.cortical_id == pleasure_id {
334                core_areas.push((4, area)); // Area 4 = _pleasure
335            } else if area.cortical_id == fear_id {
336                core_areas.push((5, area)); // Area 5 = _fear
337            } else if area.cortical_id == hope_id {
338                core_areas.push((6, area)); // Area 6 = _hope
339            } else {
340                other_areas.push(area);
341            }
342        }
343
344        // Sort core areas by their deterministic index (0..=6)
345        core_areas.sort_by_key(|(idx, _)| *idx);
346
347        // STEP 1: Create core area neurons FIRST
348        if !core_areas.is_empty() {
349            info!(target: "feagi-bdu", "  🎯 Creating core area neurons FIRST ({} areas) for deterministic IDs", core_areas.len());
350            for (core_idx, area) in &core_areas {
351                let existing_core_neurons = {
352                    let manager = self.connectome_manager.read();
353                    let npu = manager.get_npu();
354                    match npu {
355                        Some(npu_arc) => {
356                            let npu_lock = npu_arc.lock();
357                            match npu_lock {
358                                Ok(npu_guard) => {
359                                    npu_guard.get_neurons_in_cortical_area(*core_idx).len()
360                                }
361                                Err(_) => 0,
362                            }
363                        }
364                        None => 0,
365                    }
366                };
367
368                if existing_core_neurons > 0 {
369                    self.sync_core_neuron_params(*core_idx, area)?;
370                    let refreshed = {
371                        let manager = self.connectome_manager.read();
372                        manager.refresh_neuron_count_for_area(&area.cortical_id)
373                    };
374                    let count = refreshed.unwrap_or(existing_core_neurons);
375                    total_neurons += count;
376                    info!(
377                        target: "feagi-bdu",
378                        "  ↪ Skipping core neuron creation for {} (existing={}, idx={})",
379                        area.cortical_id.as_base_64(),
380                        count,
381                        core_idx
382                    );
383                    continue;
384                }
385                let neurons_created = {
386                    let mut manager = self.connectome_manager.write();
387                    manager.create_neurons_for_area(&area.cortical_id)
388                };
389
390                match neurons_created {
391                    Ok(count) => {
392                        total_neurons += count as usize;
393                        info!(target: "feagi-bdu", "  ✅ Created {} neurons for core area {} (deterministic ID: neuron {})",
394                            count, area.cortical_id.as_base_64(), core_idx);
395                    }
396                    Err(e) => {
397                        error!(target: "feagi-bdu", "  ❌ FATAL: Failed to create neurons for core area {}: {}", area.cortical_id.as_base_64(), e);
398                        return Err(e);
399                    }
400                }
401            }
402        }
403
404        // STEP 2: Create neurons for other areas
405        for area in &other_areas {
406            let neurons_created = {
407                let mut manager = self.connectome_manager.write();
408                manager.create_neurons_for_area(&area.cortical_id)
409            };
410
411            match neurons_created {
412                Ok(count) => {
413                    total_neurons += count as usize;
414                    trace!(
415                        target: "feagi-bdu",
416                        "Created {} neurons for area {}",
417                        count,
418                        area.cortical_id.as_base_64()
419                    );
420                }
421                Err(e) => {
422                    error!(target: "feagi-bdu", "  ❌ FATAL: Failed to create neurons for {}: {}", area.cortical_id.as_base_64(), e);
423                    // CRITICAL: NPU capacity errors must propagate to UI
424                    return Err(e);
425                }
426            }
427        }
428
429        // Stage 3: Create synapses for each area (Synaptogenesis)
430        for area in &areas {
431            // Check if area has mappings
432            let has_dstmap = area
433                .properties
434                .get("cortical_mapping_dst")
435                .and_then(|v| v.as_object())
436                .map(|m| !m.is_empty())
437                .unwrap_or(false);
438
439            if !has_dstmap {
440                debug!(target: "feagi-bdu", "  No mappings for area {}", area.cortical_id.as_base_64());
441                continue;
442            }
443
444            let synapses_created = {
445                let mut manager = self.connectome_manager.write();
446                manager.apply_cortical_mapping(&area.cortical_id)
447            };
448
449            match synapses_created {
450                Ok(count) => {
451                    total_synapses += count as usize;
452                    trace!(
453                        target: "feagi-bdu",
454                        "Created {} synapses for area {}",
455                        count,
456                        area.cortical_id
457                    );
458                }
459                Err(e) => {
460                    warn!(target: "feagi-bdu", "  ⚠️ Failed to create synapses for {}: {}", area.cortical_id, e);
461                    let estimated = estimate_synapses_for_area(area, genome);
462                    total_synapses += estimated;
463                }
464            }
465        }
466
467        info!(target: "feagi-bdu", "✅ Incremental add complete: {} areas, {} neurons, {} synapses",
468              areas.len(), total_neurons, total_synapses);
469
470        Ok((total_neurons, total_synapses))
471    }
472
473    /// Develop the brain from a genome
474    ///
475    /// This is the main entry point that orchestrates all development stages.
476    pub fn develop_from_genome(&mut self, genome: &RuntimeGenome) -> BduResult<()> {
477        info!(target: "feagi-bdu","🧬 Starting neuroembryogenesis for genome: {}", genome.metadata.genome_id);
478
479        // Phase 5: Parse quantization precision and dispatch to type-specific builder
480        let _quantization_precision = &genome.physiology.quantization_precision;
481        // Precision parsing handled in genome loader
482        let quant_spec = QuantizationSpec::default();
483
484        info!(target: "feagi-bdu",
485            "   Quantization precision: {:?} (range: [{}, {}] for membrane potential)",
486            quant_spec.precision,
487            quant_spec.membrane_potential_min,
488            quant_spec.membrane_potential_max
489        );
490
491        // Phase 6: Type dispatch - Neuroembryogenesis is now fully generic!
492        // The precision is determined by the type T of this Neuroembryogenesis instance.
493        // All stages (corticogenesis, neurogenesis, synaptogenesis) automatically use the correct type.
494        match quant_spec.precision {
495            Precision::FP32 => {
496                info!(target: "feagi-bdu", "   ✓ Using FP32 (32-bit floating-point) - highest precision");
497                info!(target: "feagi-bdu", "   Memory usage: Baseline (4 bytes/neuron for membrane potential)");
498            }
499            Precision::INT8 => {
500                info!(target: "feagi-bdu", "   ✓ Using INT8 (8-bit integer) - memory efficient");
501                info!(target: "feagi-bdu", "   Memory reduction: 42% (1 byte/neuron for membrane potential)");
502                info!(target: "feagi-bdu", "   Quantization range: [{}, {}]",
503                    quant_spec.membrane_potential_min,
504                    quant_spec.membrane_potential_max);
505                // Note: If this Neuroembryogenesis was created with <f32>, this will warn below
506                // The caller must create Neuroembryogenesis::<INT8Value> to use INT8
507            }
508            Precision::FP16 => {
509                warn!(target: "feagi-bdu", "   FP16 quantization requested but not yet implemented.");
510                warn!(target: "feagi-bdu", "   FP16 support planned for future GPU optimization.");
511                // Note: Requires f16 type and implementation
512            }
513        }
514
515        // Type consistency is now handled by DynamicNPU at creation time
516        // The caller (main.rs) peeks at genome precision and creates the correct DynamicNPU variant
517        info!(target: "feagi-bdu", "   ✓ Quantization handled by DynamicNPU (dispatches at runtime)");
518
519        // Update stage: Initialization
520        self.update_stage(DevelopmentStage::Initialization, 0);
521
522        // Stage 1: Corticogenesis - Create cortical area structures
523        self.corticogenesis(genome)?;
524
525        // Stage 2: Voxelogenesis - Establish spatial framework
526        self.voxelogenesis(genome)?;
527
528        // Stage 3: Neurogenesis - Generate neurons
529        self.neurogenesis(genome)?;
530
531        // Stage 4: Synaptogenesis - Form synaptic connections
532        self.synaptogenesis(genome)?;
533
534        // Mark as completed
535        self.update_stage(DevelopmentStage::Completed, 100);
536
537        let progress = self.progress.read();
538        info!(target: "feagi-bdu",
539            "✅ Neuroembryogenesis completed in {}ms: {} cortical areas, {} neurons, {} synapses",
540            progress.duration_ms,
541            progress.cortical_areas_created,
542            progress.neurons_created,
543            progress.synapses_created
544        );
545
546        Ok(())
547    }
548
549    /// Stage 1: Corticogenesis - Create cortical area structures
550    fn corticogenesis(&mut self, genome: &RuntimeGenome) -> BduResult<()> {
551        self.update_stage(DevelopmentStage::Corticogenesis, 0);
552        info!(target: "feagi-bdu","🧠 Stage 1: Corticogenesis - Creating {} cortical areas", genome.cortical_areas.len());
553        info!(target: "feagi-bdu","🔍 Genome brain_regions check: is_empty={}, count={}",
554              genome.brain_regions.is_empty(), genome.brain_regions.len());
555        if !genome.brain_regions.is_empty() {
556            info!(target: "feagi-bdu","   Existing regions: {:?}", genome.brain_regions.keys().collect::<Vec<_>>());
557        }
558
559        let total_areas = genome.cortical_areas.len();
560
561        // CRITICAL: Minimize lock scope - only hold lock when actually adding areas
562        for (idx, (cortical_id, area)) in ordered_genome_areas(genome).into_iter().enumerate() {
563            // Add cortical area to connectome - lock held only during this operation
564            {
565                let mut manager = self.connectome_manager.write();
566                manager.add_cortical_area(area.clone())?;
567            } // Lock released immediately after adding
568
569            // Update progress (doesn't need lock)
570            let progress_pct = ((idx + 1) * 100 / total_areas.max(1)) as u8;
571            self.update_progress(|p| {
572                p.cortical_areas_created = idx + 1;
573                p.progress = progress_pct;
574            });
575
576            trace!(target: "feagi-bdu", "Created cortical area: {} ({})", cortical_id, area.name);
577        }
578
579        // Ensure brain regions structure exists (auto-generate if missing)
580        // This matches Python's normalize_brain_region_membership() behavior
581        info!(target: "feagi-bdu","🔍 BRAIN REGION AUTO-GEN CHECK: genome.brain_regions.is_empty() = {}", genome.brain_regions.is_empty());
582        let (brain_regions_to_add, region_parent_map) = if genome.brain_regions.is_empty() {
583            info!(target: "feagi-bdu","  ✅ TRIGGERING AUTO-GENERATION: No brain_regions in genome - auto-generating default root region");
584            info!(target: "feagi-bdu","  📊 Genome has {} cortical areas to process", genome.cortical_areas.len());
585
586            // Collect all cortical area IDs
587            let all_cortical_ids = genome.cortical_areas.keys().cloned().collect::<Vec<_>>();
588            info!(target: "feagi-bdu","  📊 Collected {} cortical area IDs: {:?}", all_cortical_ids.len(),
589            if all_cortical_ids.len() <= 5 {
590                format!("{:?}", all_cortical_ids.iter().map(|id| id.to_string()).collect::<Vec<_>>())
591            } else {
592                format!("{:?}...", all_cortical_ids[0..5].iter().map(|id| id.to_string()).collect::<Vec<_>>())
593            });
594
595            // Classify areas into inputs/outputs based on their AreaType
596            let mut auto_inputs = Vec::new();
597            let mut auto_outputs = Vec::new();
598
599            // Classify areas into categories following Python's normalize_brain_region_membership()
600            let mut ipu_areas = Vec::new(); // Sensory inputs
601            let mut opu_areas = Vec::new(); // Motor outputs
602            let mut core_areas = Vec::new(); // Core/maintenance (like _power)
603            let mut custom_memory_areas = Vec::new(); // CUSTOM/MEMORY (go to subregion)
604
605            for (area_id, area) in genome.cortical_areas.iter() {
606                // Classify following Python's logic with gradual migration to new type system:
607                // 1. Areas starting with "_" are always CORE
608                // 2. Check cortical_type_new (new strongly-typed system) - Phase 2+
609                // 3. Check cortical_group property (parsed from genome)
610                // 4. Fallback to area_type (old simple enum)
611
612                let area_id_str = area_id.to_string();
613                // Note: Core IDs are 8-byte padded and start with "___" (three underscores)
614                let category = if area_id_str.starts_with("___") {
615                    "CORE"
616                } else if let Ok(cortical_type) = area.cortical_id.as_cortical_type() {
617                    // Use cortical type from CorticalID
618                    use feagi_structures::genomic::cortical_area::CorticalAreaType;
619                    match cortical_type {
620                        CorticalAreaType::Core(_) => "CORE",
621                        CorticalAreaType::BrainInput(_) => "IPU",
622                        CorticalAreaType::BrainOutput(_) => "OPU",
623                        CorticalAreaType::Memory(_) => "MEMORY",
624                        CorticalAreaType::Custom(_) => "CUSTOM",
625                        CorticalAreaType::Modulator => "MODULATOR",
626                    }
627                } else {
628                    // Fallback to cortical_group property or area_type
629                    let cortical_group = area
630                        .properties
631                        .get("cortical_group")
632                        .and_then(|v| v.as_str())
633                        .map(|s| s.to_uppercase());
634
635                    match cortical_group.as_deref() {
636                        Some("IPU") => "IPU",
637                        Some("OPU") => "OPU",
638                        Some("CORE") => "CORE",
639                        Some("MEMORY") => "MEMORY",
640                        Some("CUSTOM") => "CUSTOM",
641                        Some("MODULATOR") => "MODULATOR",
642                        _ => "CUSTOM", // Default fallback
643                    }
644                };
645
646                // Phase 3: Enhanced logging with detailed type information
647                if ipu_areas.len() + opu_areas.len() + core_areas.len() + custom_memory_areas.len()
648                    < 5
649                {
650                    let source = if area.cortical_id.as_cortical_type().is_ok() {
651                        "cortical_id_type"
652                    } else if area.properties.contains_key("cortical_group") {
653                        "cortical_group"
654                    } else {
655                        "default_fallback"
656                    };
657
658                    // Phase 3: Show detailed type information if available
659                    if area.cortical_id.as_cortical_type().is_ok() {
660                        let type_desc = crate::cortical_type_utils::describe_cortical_type(area);
661                        let frame_handling =
662                            if crate::cortical_type_utils::uses_absolute_frames(area) {
663                                "absolute"
664                            } else if crate::cortical_type_utils::uses_incremental_frames(area) {
665                                "incremental"
666                            } else {
667                                "n/a"
668                            };
669                        info!(target: "feagi-bdu","    🔍 {}, frames={}, source={}",
670                              type_desc, frame_handling, source);
671                    } else {
672                        info!(target: "feagi-bdu","    🔍 Area {}: category={}, source={}",
673                              area_id_str, category, source);
674                    }
675                }
676
677                // Assign to appropriate list
678                match category {
679                    "IPU" => {
680                        ipu_areas.push(*area_id);
681                        auto_inputs.push(*area_id);
682                    }
683                    "OPU" => {
684                        opu_areas.push(*area_id);
685                        auto_outputs.push(*area_id);
686                    }
687                    "CORE" | "MODULATOR" => {
688                        core_areas.push(*area_id);
689                    }
690                    "MEMORY" | "CUSTOM" => {
691                        custom_memory_areas.push(*area_id);
692                    }
693                    _ => {}
694                }
695            }
696
697            info!(target: "feagi-bdu","  📊 Classification complete: IPU={}, OPU={}, CORE={}, CUSTOM/MEMORY={}",
698                  ipu_areas.len(), opu_areas.len(), core_areas.len(), custom_memory_areas.len());
699
700            // Build brain region structure following Python's normalize_brain_region_membership()
701            use feagi_structures::genomic::brain_regions::{BrainRegion, RegionID, RegionType};
702            let mut regions_map = std::collections::HashMap::new();
703
704            // Step 1: Create root region with only IPU/OPU/CORE areas
705            let mut root_area_ids = Vec::new();
706            root_area_ids.extend(ipu_areas.iter().cloned());
707            root_area_ids.extend(opu_areas.iter().cloned());
708            root_area_ids.extend(core_areas.iter().cloned());
709
710            // Analyze connections to determine actual inputs/outputs for root
711            let (root_inputs, root_outputs) =
712                Self::analyze_region_io(&root_area_ids, &genome.cortical_areas);
713
714            // Convert CorticalID to base64 for with_areas()
715            // Create a root region with a generated RegionID
716            let root_region_id = RegionID::new();
717            let root_region_id_str = root_region_id.to_string();
718
719            let mut root_region = BrainRegion::new(
720                root_region_id,
721                ROOT_BRAIN_REGION_NAME.to_string(),
722                RegionType::Undefined,
723            )
724            .expect("Failed to create root region")
725            .with_areas(root_area_ids.iter().cloned());
726
727            // Store inputs/outputs based on connection analysis
728            if !root_inputs.is_empty() {
729                root_region
730                    .add_property("inputs".to_string(), serde_json::json!(root_inputs.clone()));
731            }
732            if !root_outputs.is_empty() {
733                root_region.add_property(
734                    "outputs".to_string(),
735                    serde_json::json!(root_outputs.clone()),
736                );
737            }
738
739            info!(target: "feagi-bdu","  ✅ Created root region with {} areas (IPU={}, OPU={}, CORE={}) - analyzed: {} inputs, {} outputs",
740                  root_area_ids.len(), ipu_areas.len(), opu_areas.len(), core_areas.len(),
741                  root_inputs.len(), root_outputs.len());
742
743            // Step 2: Create subregion for CUSTOM/MEMORY areas if any exist
744            let mut subregion_id = None;
745            if !custom_memory_areas.is_empty() {
746                // Convert CorticalID to base64 for sorting and hashing
747                let mut custom_memory_strs: Vec<String> = custom_memory_areas
748                    .iter()
749                    .map(|id| id.as_base_64())
750                    .collect();
751                custom_memory_strs.sort(); // Sort for deterministic hash
752                let combined = custom_memory_strs.join("|");
753
754                // Use a simple hash (matching Python's sha1[:8])
755                use std::collections::hash_map::DefaultHasher;
756                use std::hash::{Hash, Hasher};
757                let mut hasher = DefaultHasher::new();
758                combined.hash(&mut hasher);
759                let hash = hasher.finish();
760                let hash_hex = format!("{:08x}", hash as u32);
761                let region_id = format!("region_autogen_{}", hash_hex);
762
763                // Analyze connections to determine inputs/outputs for subregion
764                let (subregion_inputs, subregion_outputs) =
765                    Self::analyze_region_io(&custom_memory_areas, &genome.cortical_areas);
766
767                // Calculate smart position: Place autogen region outside root's bounding box
768                let autogen_position =
769                    Self::calculate_autogen_region_position(&root_area_ids, genome);
770
771                // Create subregion
772                let subregion_name = autogen_subregion_display_name(&genome.metadata.genome_title);
773                let mut subregion = BrainRegion::new(
774                    RegionID::new(), // Generate new UUID instead of using string
775                    subregion_name,
776                    RegionType::Undefined, // RegionType no longer has Custom variant
777                )
778                .expect("Failed to create subregion")
779                .with_areas(custom_memory_areas.iter().cloned());
780
781                // Set 3D coordinates (place outside root's bounding box)
782                subregion.add_property(
783                    "coordinate_3d".to_string(),
784                    serde_json::json!(autogen_position),
785                );
786                subregion.add_property("coordinate_2d".to_string(), serde_json::json!([0, 0]));
787
788                // Store inputs/outputs for subregion
789                if !subregion_inputs.is_empty() {
790                    subregion.add_property(
791                        "inputs".to_string(),
792                        serde_json::json!(subregion_inputs.clone()),
793                    );
794                }
795                if !subregion_outputs.is_empty() {
796                    subregion.add_property(
797                        "outputs".to_string(),
798                        serde_json::json!(subregion_outputs.clone()),
799                    );
800                }
801
802                let subregion_id_str = subregion.region_id.to_string();
803
804                info!(target: "feagi-bdu","  ✅ Created subregion '{}' with {} CUSTOM/MEMORY areas ({} inputs, {} outputs)",
805                      region_id, custom_memory_areas.len(), subregion_inputs.len(), subregion_outputs.len());
806
807                regions_map.insert(subregion_id_str.clone(), subregion);
808                subregion_id = Some(subregion_id_str);
809            }
810
811            regions_map.insert(root_region_id_str.clone(), root_region);
812
813            // Count total inputs/outputs across all regions
814            let total_inputs = root_inputs.len()
815                + if let Some(ref sid) = subregion_id {
816                    regions_map
817                        .get(sid)
818                        .and_then(|r| r.properties.get("inputs"))
819                        .and_then(|v| v.as_array())
820                        .map(|a| a.len())
821                        .unwrap_or(0)
822                } else {
823                    0
824                };
825
826            let total_outputs = root_outputs.len()
827                + if let Some(ref sid) = subregion_id {
828                    regions_map
829                        .get(sid)
830                        .and_then(|r| r.properties.get("outputs"))
831                        .and_then(|v| v.as_array())
832                        .map(|a| a.len())
833                        .unwrap_or(0)
834                } else {
835                    0
836                };
837
838            info!(target: "feagi-bdu","  ✅ Auto-generated {} brain region(s) with {} total cortical areas ({} total inputs, {} total outputs)",
839                  regions_map.len(), all_cortical_ids.len(), total_inputs, total_outputs);
840
841            // Return (regions_map, parent_map) so we can properly link hierarchy
842            let mut parent_map = std::collections::HashMap::new();
843            if let Some(ref sub_id) = subregion_id {
844                parent_map.insert(sub_id.clone(), root_region_id_str.clone());
845                info!(target: "feagi-bdu","  🔗 Parent relationship: {} -> {}", sub_id, root_region_id_str);
846            }
847
848            (regions_map, parent_map)
849        } else {
850            info!(target: "feagi-bdu","  📋 Genome already has {} brain regions - using existing structure", genome.brain_regions.len());
851            let mut regions_map = genome.brain_regions.clone();
852            if let Some(wrapper_id) = wrap_parentless_regions_under_named_root(&mut regions_map) {
853                info!(
854                    target: "feagi-bdu",
855                    "  🔗 Wrapped parentless circuit(s) under new {} ({}); original circuit names preserved",
856                    ROOT_BRAIN_REGION_NAME,
857                    wrapper_id
858                );
859            }
860            if let Some(circuit_name) = apply_genome_title_to_unique_top_circuit(
861                &mut regions_map,
862                &genome.metadata.genome_title,
863            ) {
864                info!(
865                    target: "feagi-bdu",
866                    "  Applied genome_title to unique top-level circuit: {}",
867                    circuit_name
868                );
869            }
870            // Parent links may be stored on each region as `parent_region_id` (properties). Flat/v3
871            // exports often omit them; without parents, add_brain_region(..., None) only registers the
872            // first region as root and leaves other regions detached — BV then shows an empty tree.
873            let mut region_parent_map: std::collections::HashMap<String, String> =
874                std::collections::HashMap::new();
875            for (region_id, region) in &regions_map {
876                if let Some(pid) = region
877                    .properties
878                    .get("parent_region_id")
879                    .and_then(|v| v.as_str())
880                {
881                    region_parent_map.insert(region_id.clone(), pid.to_string());
882                }
883            }
884            if region_parent_map.is_empty() {
885                if let Some((root_id, _)) = regions_map
886                    .iter()
887                    .find(|(_, r)| r.name == ROOT_BRAIN_REGION_NAME)
888                {
889                    for (region_id, region) in &regions_map {
890                        if region.name == ROOT_BRAIN_REGION_NAME {
891                            continue;
892                        }
893                        region_parent_map.insert(region_id.clone(), root_id.clone());
894                    }
895                    if !region_parent_map.is_empty() {
896                        info!(target: "feagi-bdu",
897                            "  🔗 Inferred {} sub-region parent link(s) under root {}",
898                            region_parent_map.len(),
899                            root_id
900                        );
901                    }
902                } else {
903                    warn!(target: "feagi-bdu",
904                        "  ⚠️ brain_regions present but no '{}' and no parent_region_id — hierarchy may not load in BV",
905                        ROOT_BRAIN_REGION_NAME
906                    );
907                }
908            }
909            (regions_map, region_parent_map)
910        };
911
912        // Add brain regions with proper parent relationships - minimize lock scope
913        {
914            let mut manager = self.connectome_manager.write();
915            let brain_region_count = brain_regions_to_add.len();
916            info!(target: "feagi-bdu","  Adding {} brain regions from genome", brain_region_count);
917
918            // Named root first (parent=None). Remaining regions are inserted in
919            // parent-before-child order so nested trees do not depend on HashMap iteration.
920            let root_entry = brain_regions_to_add
921                .iter()
922                .find(|(_, region)| region.name == ROOT_BRAIN_REGION_NAME);
923            if let Some((root_id, root_region)) = root_entry {
924                manager.add_brain_region(root_region.clone(), None)?;
925                debug!(target: "feagi-bdu","    ✓ Added brain region: {} ({}) [parent=None]", root_id, ROOT_BRAIN_REGION_NAME);
926            }
927
928            let remaining_ids: Vec<String> = brain_regions_to_add
929                .iter()
930                .filter(|(_, region)| region.name != ROOT_BRAIN_REGION_NAME)
931                .map(|(region_id, _)| region_id.clone())
932                .collect();
933            let ordered_ids = order_regions_parent_before_child(&remaining_ids, &region_parent_map);
934
935            for region_id in ordered_ids {
936                let region = brain_regions_to_add.get(&region_id).ok_or_else(|| {
937                    BduError::Internal(format!(
938                        "Ordered region {} missing from genome region map",
939                        region_id
940                    ))
941                })?;
942                let parent_id = region_parent_map.get(&region_id).cloned();
943                manager.add_brain_region(region.clone(), parent_id.clone())?;
944                debug!(target: "feagi-bdu","    ✓ Added brain region: {} ({}) [parent={:?}]",
945                       region_id, region.name, parent_id);
946            }
947
948            info!(target: "feagi-bdu","  Total brain regions in ConnectomeManager: {}", manager.get_brain_region_ids().len());
949
950            manager.replace_classifiers(genome.classifiers.clone());
951            for classifier in genome.classifiers.values() {
952                if let Some(region) = manager.get_brain_region_mut(&classifier.parent_region_id) {
953                    for area_id in classifier.owned_area_ids() {
954                        if let Ok(cortical_id) =
955                            feagi_structures::genomic::cortical_area::CorticalID::try_from_base_64(
956                                &area_id,
957                            )
958                        {
959                            region.add_area(cortical_id);
960                        }
961                    }
962                }
963            }
964            manager.apply_loaded_classifier_assemblies();
965            info!(
966                target: "feagi-bdu",
967                "  Loaded {} classifier assemblies from genome",
968                genome.classifiers.len()
969            );
970
971            // Derive region IO (including each designated port's `port_encoding`) from the loaded
972            // regions and mappings, the same pass every later mapping or membership change runs.
973            manager.recompute_brain_region_io_registry()?;
974        } // Lock released
975
976        self.update_stage(DevelopmentStage::Corticogenesis, 100);
977        info!(target: "feagi-bdu","  ✅ Corticogenesis complete: {} cortical areas created", total_areas);
978
979        Ok(())
980    }
981
982    /// Stage 2: Voxelogenesis - Establish spatial framework
983    fn voxelogenesis(&mut self, _genome: &RuntimeGenome) -> BduResult<()> {
984        self.update_stage(DevelopmentStage::Voxelogenesis, 0);
985        info!(target: "feagi-bdu","📐 Stage 2: Voxelogenesis - Establishing spatial framework");
986
987        // Spatial framework is implicitly established by cortical area dimensions
988        // The Morton spatial hash in ConnectomeManager handles the actual indexing
989
990        self.update_stage(DevelopmentStage::Voxelogenesis, 100);
991        info!(target: "feagi-bdu","  ✅ Voxelogenesis complete: Spatial framework established");
992
993        Ok(())
994    }
995
996    /// Stage 3: Neurogenesis - Generate neurons within cortical areas
997    ///
998    /// This uses ConnectomeManager which delegates to NPU's SIMD-optimized batch operations.
999    /// Each cortical area is processed with `create_cortical_area_neurons()` which creates
1000    /// ALL neurons for that area in one vectorized operation (not a loop).
1001    ///
1002    /// CRITICAL: Core areas (0=_death, 1=_power, 2=_fatigue, 3=_pain, 4=_pleasure, 5=_fear, 6=_hope) are created
1003    /// FIRST to ensure deterministic neuron IDs.
1004    fn neurogenesis(&mut self, genome: &RuntimeGenome) -> BduResult<()> {
1005        self.update_stage(DevelopmentStage::Neurogenesis, 0);
1006        info!(target: "feagi-bdu","🔬 Stage 3: Neurogenesis - Generating neurons (SIMD-optimized batches)");
1007
1008        let expected_neurons = genome.stats.innate_neuron_count;
1009        info!(target: "feagi-bdu","  Expected innate neurons from genome: {}", expected_neurons);
1010
1011        // CRITICAL: Identify core areas first to ensure deterministic neuron IDs
1012        use feagi_structures::genomic::cortical_area::CoreCorticalType;
1013        let death_id = CoreCorticalType::Death.to_cortical_id();
1014        let power_id = CoreCorticalType::Power.to_cortical_id();
1015        let fatigue_id = CoreCorticalType::Fatigue.to_cortical_id();
1016        let pain_id = CoreCorticalType::Pain.to_cortical_id();
1017        let pleasure_id = CoreCorticalType::Pleasure.to_cortical_id();
1018        let fear_id = CoreCorticalType::Fear.to_cortical_id();
1019        let hope_id = CoreCorticalType::Hope.to_cortical_id();
1020
1021        let mut core_areas = Vec::new();
1022        let mut other_areas = Vec::new();
1023
1024        // Separate core areas from other areas
1025        for (cortical_id, area) in genome.cortical_areas.iter() {
1026            if *cortical_id == death_id {
1027                core_areas.push((0, *cortical_id, area)); // Area 0 = _death
1028            } else if *cortical_id == power_id {
1029                core_areas.push((1, *cortical_id, area)); // Area 1 = _power
1030            } else if *cortical_id == fatigue_id {
1031                core_areas.push((2, *cortical_id, area)); // Area 2 = _fatigue
1032            } else if *cortical_id == pain_id {
1033                core_areas.push((3, *cortical_id, area)); // Area 3 = _pain
1034            } else if *cortical_id == pleasure_id {
1035                core_areas.push((4, *cortical_id, area)); // Area 4 = _pleasure
1036            } else if *cortical_id == fear_id {
1037                core_areas.push((5, *cortical_id, area)); // Area 5 = _fear
1038            } else if *cortical_id == hope_id {
1039                core_areas.push((6, *cortical_id, area)); // Area 6 = _hope
1040            } else {
1041                other_areas.push((*cortical_id, area));
1042            }
1043        }
1044
1045        // Sort core areas by their deterministic index (0..=6); the rest in registration order
1046        core_areas.sort_by_key(|(idx, _, _)| *idx);
1047        other_areas.sort_by_key(|(cortical_id, area)| registration_order_key(cortical_id, area));
1048
1049        info!(target: "feagi-bdu","  🎯 Creating core area neurons FIRST ({} areas) for deterministic IDs", core_areas.len());
1050
1051        let mut total_neurons_created = 0;
1052        let mut processed_count = 0;
1053        let total_areas = genome.cortical_areas.len();
1054
1055        // STEP 1: Create core area neurons FIRST (in order: 0..=6)
1056        for (core_idx, cortical_id, area) in &core_areas {
1057            let existing_core_neurons = {
1058                let manager = self.connectome_manager.read();
1059                let npu = manager.get_npu();
1060                match npu {
1061                    Some(npu_arc) => {
1062                        let npu_lock = npu_arc.lock();
1063                        match npu_lock {
1064                            Ok(npu_guard) => {
1065                                npu_guard.get_neurons_in_cortical_area(*core_idx).len()
1066                            }
1067                            Err(_) => 0,
1068                        }
1069                    }
1070                    None => 0,
1071                }
1072            };
1073
1074            if existing_core_neurons > 0 {
1075                self.sync_core_neuron_params(*core_idx, area)?;
1076                let refreshed = {
1077                    let manager = self.connectome_manager.read();
1078                    manager.refresh_neuron_count_for_area(cortical_id)
1079                };
1080                let count = refreshed.unwrap_or(existing_core_neurons);
1081                total_neurons_created += count;
1082                info!(
1083                    target: "feagi-bdu",
1084                    "  ↪ Skipping core neuron creation for {} (existing={}, idx={})",
1085                    cortical_id.as_base_64(),
1086                    count,
1087                    core_idx
1088                );
1089                processed_count += 1;
1090                let progress_pct = (processed_count * 100 / total_areas.max(1)) as u8;
1091                self.update_progress(|p| {
1092                    p.neurons_created = total_neurons_created;
1093                    p.progress = progress_pct;
1094                });
1095                continue;
1096            }
1097            let per_voxel_count = area
1098                .properties
1099                .get("neurons_per_voxel")
1100                .and_then(|v| v.as_u64())
1101                .unwrap_or(1) as i64;
1102
1103            let cortical_id_str = cortical_id.to_string();
1104            info!(target: "feagi-bdu","  🔋 [CORE-AREA {}] {} - dimensions: {:?}, per_voxel: {}",
1105                core_idx, cortical_id_str, area.dimensions, per_voxel_count);
1106
1107            if per_voxel_count == 0 {
1108                warn!(target: "feagi-bdu","  ⚠️ Skipping core area {} - per_voxel_neuron_cnt is 0", cortical_id_str);
1109                continue;
1110            }
1111
1112            // Create neurons for core area (ensures deterministic ID: area 0→neuron 0, area 1→neuron 1, area 2→neuron 2)
1113            let neurons_created = {
1114                let manager_arc = self.connectome_manager.clone();
1115                let mut manager = manager_arc.write();
1116                manager.create_neurons_for_area(cortical_id)
1117            };
1118
1119            match neurons_created {
1120                Ok(count) => {
1121                    total_neurons_created += count as usize;
1122                    info!(target: "feagi-bdu","  ✅ Created {} neurons for core area {} (deterministic ID: neuron {})",
1123                        count, cortical_id_str, core_idx);
1124                }
1125                Err(e) => {
1126                    error!(target: "feagi-bdu","  ❌ FATAL: Failed to create neurons for core area {}: {}", cortical_id_str, e);
1127                    return Err(e);
1128                }
1129            }
1130
1131            processed_count += 1;
1132            let progress_pct = (processed_count * 100 / total_areas.max(1)) as u8;
1133            self.update_progress(|p| {
1134                p.neurons_created = total_neurons_created;
1135                p.progress = progress_pct;
1136            });
1137        }
1138
1139        // STEP 2: Create neurons for all other areas
1140        info!(target: "feagi-bdu","  📦 Creating neurons for {} other areas", other_areas.len());
1141        for (cortical_id, area) in &other_areas {
1142            // Get neurons_per_voxel from typed field (single source of truth)
1143            let _per_voxel_count = area
1144                .properties
1145                .get("neurons_per_voxel")
1146                .and_then(|v| v.as_u64())
1147                .unwrap_or(1) as i64;
1148
1149            let per_voxel_count = area
1150                .properties
1151                .get("neurons_per_voxel")
1152                .and_then(|v| v.as_u64())
1153                .unwrap_or(1) as i64;
1154
1155            let cortical_id_str = cortical_id.to_string();
1156
1157            if per_voxel_count == 0 {
1158                warn!(target: "feagi-bdu","  ⚠️ Skipping area {} - per_voxel_neuron_cnt is 0 (will have NO neurons!)", cortical_id_str);
1159                continue;
1160            }
1161
1162            // Call ConnectomeManager to create neurons (delegates to NPU)
1163            // CRITICAL: Minimize lock scope - only hold lock during neuron creation
1164            let neurons_created = {
1165                let manager_arc = self.connectome_manager.clone();
1166                let mut manager = manager_arc.write();
1167                manager.create_neurons_for_area(cortical_id)
1168            }; // Lock released immediately
1169
1170            match neurons_created {
1171                Ok(count) => {
1172                    total_neurons_created += count as usize;
1173                    trace!(
1174                        target: "feagi-bdu",
1175                        "Created {} neurons for area {}",
1176                        count,
1177                        cortical_id_str
1178                    );
1179                }
1180                Err(e) => {
1181                    // If NPU not connected, calculate expected count
1182                    warn!(target: "feagi-bdu","  Failed to create neurons for {}: {} (NPU may not be connected)",
1183                        cortical_id_str, e);
1184                    let total_voxels = area.dimensions.width as usize
1185                        * area.dimensions.height as usize
1186                        * area.dimensions.depth as usize;
1187                    let expected = total_voxels * per_voxel_count as usize;
1188                    total_neurons_created += expected;
1189                }
1190            }
1191
1192            processed_count += 1;
1193            // Update progress
1194            let progress_pct = (processed_count * 100 / total_areas.max(1)) as u8;
1195            self.update_progress(|p| {
1196                p.neurons_created = total_neurons_created;
1197                p.progress = progress_pct;
1198            });
1199        }
1200
1201        // Compare with genome stats (info only - stats may count only innate neurons while we create all voxels)
1202        if expected_neurons > 0 && total_neurons_created != expected_neurons {
1203            trace!(target: "feagi-bdu",
1204                created_neurons = total_neurons_created,
1205                genome_stats_innate = expected_neurons,
1206                "Neuron creation complete (genome stats may only count innate neurons)"
1207            );
1208        }
1209
1210        self.update_stage(DevelopmentStage::Neurogenesis, 100);
1211        info!(target: "feagi-bdu","  ✅ Neurogenesis complete: {} neurons created", total_neurons_created);
1212
1213        Ok(())
1214    }
1215
1216    /// Stage 4: Synaptogenesis - Form synaptic connections between neurons
1217    ///
1218    /// This uses ConnectomeManager which delegates to NPU's morphology functions.
1219    /// Each morphology application (`apply_projector_morphology`, etc.) processes ALL neurons
1220    /// from the source area and creates ALL synapses in one SIMD-optimized batch operation.
1221    fn synaptogenesis(&mut self, genome: &RuntimeGenome) -> BduResult<()> {
1222        self.update_stage(DevelopmentStage::Synaptogenesis, 0);
1223        info!(target: "feagi-bdu","🔗 Stage 4: Synaptogenesis - Forming synaptic connections (SIMD-optimized batches)");
1224
1225        let expected_synapses = genome.stats.innate_synapse_count;
1226        info!(target: "feagi-bdu","  Expected innate synapses from genome: {}", expected_synapses);
1227
1228        self.rebuild_memory_twin_mappings()?;
1229        self.connectome_manager
1230            .write()
1231            .sync_modulators_from_genome(genome)?;
1232
1233        let mut total_synapses_created = 0;
1234        let total_areas = genome.cortical_areas.len();
1235
1236        // Process each source area via ConnectomeManager (each mapping = one SIMD batch)
1237        // NOTE: Loop is over AREAS, not synapses. Each area applies all mappings in batch calls.
1238        for (idx, (_src_cortical_id, src_area)) in genome.cortical_areas.iter().enumerate() {
1239            // Check if area has mappings
1240            let has_dstmap = src_area
1241                .properties
1242                .get("cortical_mapping_dst")
1243                .and_then(|v| v.as_object())
1244                .map(|m| !m.is_empty())
1245                .unwrap_or(false);
1246
1247            if !has_dstmap {
1248                trace!(target: "feagi-bdu", "No dstmap for area {}", &src_area.cortical_id);
1249                continue;
1250            }
1251
1252            // Call ConnectomeManager to apply cortical mappings (delegates to NPU)
1253            // CRITICAL: Minimize lock scope - only hold lock during synapse creation
1254            // Use src_area.cortical_id (the actual ID stored in ConnectomeManager)
1255            let src_cortical_id = &src_area.cortical_id;
1256            let src_cortical_id_str = src_cortical_id.to_string(); // For logging
1257            let synapses_created = {
1258                let manager_arc = self.connectome_manager.clone();
1259                let mut manager = manager_arc.write();
1260                if let Some(dstmap) = src_area.properties.get("cortical_mapping_dst") {
1261                    if let Some(area) = manager.get_cortical_area_mut(src_cortical_id) {
1262                        area.properties
1263                            .insert("cortical_mapping_dst".to_string(), dstmap.clone());
1264                    }
1265                }
1266                manager.apply_cortical_mapping(src_cortical_id)
1267            }; // Lock released immediately
1268
1269            match synapses_created {
1270                Ok(count) => {
1271                    total_synapses_created += count as usize;
1272                    trace!(
1273                        target: "feagi-bdu",
1274                        "Created {} synapses for area {}",
1275                        count,
1276                        src_cortical_id_str
1277                    );
1278                }
1279                Err(e) => {
1280                    // Synapses for destinations applied before the error already exist
1281                    // but are not reported by the failing call, so nothing is added here.
1282                    warn!(target: "feagi-bdu", "  Mappings from {} were not fully applied: {}",
1283                        src_cortical_id_str, e);
1284                }
1285            }
1286
1287            // Update progress
1288            let progress_pct = ((idx + 1) * 100 / total_areas.max(1)) as u8;
1289            self.update_progress(|p| {
1290                p.synapses_created = total_synapses_created;
1291                p.progress = progress_pct;
1292            });
1293        }
1294
1295        // CRITICAL: Rebuild the NPU synapse index so newly created synapses are visible to
1296        // queries (e.g. get_outgoing_synapses / synapse counts) and propagation.
1297        //
1298        // Note: We do this once at the end for performance.
1299        let npu_arc = {
1300            let manager = self.connectome_manager.read();
1301            manager.get_npu().cloned()
1302        };
1303        if let Some(npu_arc) = npu_arc {
1304            let mut npu_lock = npu_arc
1305                .lock()
1306                .map_err(|e| BduError::Internal(format!("Failed to lock NPU: {}", e)))?;
1307            npu_lock.rebuild_synapse_index();
1308
1309            // Refresh cached counts after index rebuild.
1310            let manager = self.connectome_manager.read();
1311            manager.update_cached_synapse_count();
1312        }
1313
1314        // CRITICAL: Register memory areas with PlasticityExecutor after all mappings are created
1315        // This ensures memory areas have their complete upstream_cortical_areas lists populated.
1316        #[cfg(feature = "plasticity")]
1317        {
1318            use feagi_evolutionary::extract_memory_properties;
1319            use feagi_npu_plasticity::PlasticityExecutor;
1320
1321            let manager = self.connectome_manager.read();
1322            if let Some(executor) = manager.get_plasticity_executor() {
1323                let mut registered_count = 0;
1324
1325                // Iterate through all cortical areas and register memory areas
1326                for area_id in manager.get_cortical_area_ids() {
1327                    if let Some(area) = manager.get_cortical_area(area_id) {
1328                        if let Some(mem_props) = extract_memory_properties(&area.properties) {
1329                            let upstream_areas =
1330                                manager.get_episodic_memory_upstream_cortical_areas(area_id);
1331
1332                            // Ensure FireLedger tracks upstream areas with at least the required temporal depth.
1333                            // Dense, burst-aligned tracking is required for correct memory pattern hashing.
1334                            if let Some(npu_arc) = manager.get_npu() {
1335                                if let Ok(mut npu) = npu_arc.lock() {
1336                                    let existing_configs = npu.get_all_fire_ledger_configs();
1337                                    for &upstream_idx in &upstream_areas {
1338                                        let existing = existing_configs
1339                                            .iter()
1340                                            .find(|(idx, _)| *idx == upstream_idx)
1341                                            .map(|(_, w)| *w)
1342                                            .unwrap_or(0);
1343
1344                                        let desired = mem_props.temporal_depth as usize;
1345                                        let resolved = existing.max(desired);
1346                                        if resolved != existing {
1347                                            if let Err(e) = npu.configure_fire_ledger_window(
1348                                                upstream_idx,
1349                                                resolved,
1350                                            ) {
1351                                                warn!(
1352                                                    target: "feagi-bdu",
1353                                                    "Failed to configure FireLedger window for upstream area idx={} (requested={}): {}",
1354                                                    upstream_idx,
1355                                                    resolved,
1356                                                    e
1357                                                );
1358                                            }
1359                                        }
1360                                    }
1361                                } else {
1362                                    warn!(target: "feagi-bdu", "Failed to lock NPU for FireLedger configuration");
1363                                }
1364                            }
1365
1366                            manager.sync_memory_associative_lif_params(area_id);
1367                            if let Ok(exec) = executor.lock() {
1368                                let lifecycle_config = crate::memory_lifecycle_config(&mem_props);
1369
1370                                let mp_mode =
1371                                    match crate::memory_mp_mode(&area.properties, &mem_props) {
1372                                        Ok(mode) => mode,
1373                                        Err(e) => {
1374                                            error!(
1375                                                target: "feagi-bdu",
1376                                                "Memory area {} not registered: {}",
1377                                                area_id.as_base_64(),
1378                                                e
1379                                            );
1380                                            continue;
1381                                        }
1382                                    };
1383                                exec.register_memory_area(
1384                                    area.cortical_idx,
1385                                    area_id.as_base_64(),
1386                                    mem_props.temporal_depth,
1387                                    upstream_areas.clone(),
1388                                    Some(lifecycle_config),
1389                                    mp_mode,
1390                                );
1391                                manager.configure_memory_scan_on_executor(&*exec, area_id);
1392
1393                                registered_count += 1;
1394                            }
1395                        }
1396                    }
1397                }
1398                let _ = registered_count; // count retained for future metrics if needed
1399            }
1400        }
1401
1402        // Mapping rules reach the manager only inside the loop above, so the eligibility of
1403        // reward-trained classifiers (derived from the circuit's answer delay) can only be
1404        // recomputed now. The earlier pass in corticogenesis finds no rules and skips.
1405        self.connectome_manager
1406            .write()
1407            .refresh_classifier_reward_eligibility();
1408
1409        // Verify against genome stats
1410        if expected_synapses > 0 {
1411            let diff = (total_synapses_created as i64 - expected_synapses as i64).abs();
1412            let diff_pct = (diff as f64 / expected_synapses.max(1) as f64) * 100.0;
1413
1414            if diff_pct > 10.0 {
1415                warn!(target: "feagi-bdu",
1416                    "Synapse count variance: created {} but genome stats expected {} ({:.1}% difference)",
1417                    total_synapses_created, expected_synapses, diff_pct
1418                );
1419            } else {
1420                info!(target: "feagi-bdu",
1421                    "Synapse count matches genome stats within {:.1}% ({} vs {})",
1422                    diff_pct, total_synapses_created, expected_synapses
1423                );
1424            }
1425        }
1426
1427        self.update_stage(DevelopmentStage::Synaptogenesis, 100);
1428        info!(target: "feagi-bdu","  ✅ Synaptogenesis complete: {} synapses created", total_synapses_created);
1429
1430        Ok(())
1431    }
1432
1433    /// Rebuild memory twins with the same job list the connectome import rebind uses
1434    /// (`ConnectomeManager::rebuild_memory_twin_mappings`), so a genome load and an import of
1435    /// its export hold the same areas. That includes creating the twin of an episodic
1436    /// upstream-to-memory pair that has no saved twin. Errors propagate under one policy.
1437    fn rebuild_memory_twin_mappings(&mut self) -> BduResult<()> {
1438        let restored = self
1439            .connectome_manager
1440            .write()
1441            .rebuild_memory_twin_mappings()?;
1442        info!(
1443            target: "feagi-bdu",
1444            "Rebuilt {} memory twin mapping(s) from genome",
1445            restored
1446        );
1447        Ok(())
1448    }
1449}
1450
1451/// Estimate synapse count for an area (fallback when NPU not connected)
1452///
1453/// This is only used when NPU is not available for actual synapse creation.
1454fn estimate_synapses_for_area(
1455    src_area: &CorticalArea,
1456    genome: &feagi_evolutionary::RuntimeGenome,
1457) -> usize {
1458    let dstmap = match src_area.properties.get("cortical_mapping_dst") {
1459        Some(serde_json::Value::Object(map)) => map,
1460        _ => return 0,
1461    };
1462
1463    let mut total = 0;
1464
1465    for (dst_id, rules) in dstmap {
1466        // Convert string dst_id to CorticalID for lookup
1467        let dst_cortical_id = match feagi_evolutionary::string_to_cortical_id(dst_id) {
1468            Ok(id) => id,
1469            Err(_) => continue,
1470        };
1471        let dst_area = match genome.cortical_areas.get(&dst_cortical_id) {
1472            Some(area) => area,
1473            None => continue,
1474        };
1475
1476        let rules_array = match rules.as_array() {
1477            Some(arr) => arr,
1478            None => continue,
1479        };
1480
1481        for rule in rules_array {
1482            let morphology_id = rule
1483                .get("morphology_id")
1484                .and_then(|v| v.as_str())
1485                .unwrap_or("unknown");
1486            let scalar = rule
1487                .get("morphology_scalar")
1488                .and_then(|v| v.as_i64())
1489                .unwrap_or(1) as usize;
1490
1491            // Simplified estimation
1492            let src_per_voxel = src_area
1493                .properties
1494                .get("neurons_per_voxel")
1495                .and_then(|v| v.as_u64())
1496                .unwrap_or(1) as usize;
1497            let dst_per_voxel = dst_area
1498                .properties
1499                .get("neurons_per_voxel")
1500                .and_then(|v| v.as_u64())
1501                .unwrap_or(1) as usize;
1502
1503            let src_voxels =
1504                src_area.dimensions.width * src_area.dimensions.height * src_area.dimensions.depth;
1505            let dst_voxels =
1506                dst_area.dimensions.width * dst_area.dimensions.height * dst_area.dimensions.depth;
1507
1508            let src_neurons = src_voxels as usize * src_per_voxel;
1509            let dst_neurons = dst_voxels as usize * dst_per_voxel as usize;
1510
1511            // Basic estimation by morphology type
1512            let count = match morphology_id {
1513                "block_to_block" => src_neurons * dst_per_voxel * scalar,
1514                "projector" | "transpose_xy" | "transpose_yz" | "transpose_xz"
1515                | "centered_projector" => src_neurons * dst_neurons * scalar,
1516                _ if morphology_id.contains("lateral") => src_neurons * scalar,
1517                _ => (src_neurons * scalar).min(src_neurons * dst_neurons / 10),
1518            };
1519
1520            total += count;
1521        }
1522    }
1523
1524    total
1525}
1526
1527impl Neuroembryogenesis {
1528    /// Calculate position for autogen region based on root region's bounding box
1529    fn calculate_autogen_region_position(
1530        root_area_ids: &[CorticalID],
1531        genome: &feagi_evolutionary::RuntimeGenome,
1532    ) -> [i32; 3] {
1533        if root_area_ids.is_empty() {
1534            return [100, 0, 0];
1535        }
1536
1537        let mut min_x = i32::MAX;
1538        let mut max_x = i32::MIN;
1539        let mut min_y = i32::MAX;
1540        let mut max_y = i32::MIN;
1541        let mut min_z = i32::MAX;
1542        let mut max_z = i32::MIN;
1543
1544        for cortical_id in root_area_ids {
1545            if let Some(area) = genome.cortical_areas.get(cortical_id) {
1546                let pos: (i32, i32, i32) = area.position.into();
1547                let dims = (
1548                    area.dimensions.width as i32,
1549                    area.dimensions.height as i32,
1550                    area.dimensions.depth as i32,
1551                );
1552
1553                min_x = min_x.min(pos.0);
1554                max_x = max_x.max(pos.0 + dims.0);
1555                min_y = min_y.min(pos.1);
1556                max_y = max_y.max(pos.1 + dims.1);
1557                min_z = min_z.min(pos.2);
1558                max_z = max_z.max(pos.2 + dims.2);
1559            }
1560        }
1561
1562        let bbox_width = (max_x - min_x).max(1);
1563        let padding = (bbox_width / 5).max(50);
1564        let autogen_x = max_x + padding;
1565        let autogen_y = (min_y + max_y) / 2;
1566        let autogen_z = (min_z + max_z) / 2;
1567
1568        info!(target: "feagi-bdu",
1569              "  📐 Autogen position: ({}, {}, {}) [padding: {}]",
1570              autogen_x, autogen_y, autogen_z, padding);
1571
1572        [autogen_x, autogen_y, autogen_z]
1573    }
1574
1575    /// Analyze region inputs/outputs based on cortical connections
1576    ///
1577    /// Following Python's _auto_assign_region_io() logic:
1578    /// - OUTPUT: Any area in the region that connects to an area OUTSIDE the region
1579    /// - INPUT: Any area in the region that receives connection from OUTSIDE the region
1580    fn analyze_region_io(
1581        region_area_ids: &[feagi_structures::genomic::cortical_area::CorticalID],
1582        all_cortical_areas: &std::collections::HashMap<CorticalID, CorticalArea>,
1583    ) -> (Vec<String>, Vec<String>) {
1584        let area_set: std::collections::HashSet<_> = region_area_ids.iter().cloned().collect();
1585        let mut inputs = Vec::new();
1586        let mut outputs = Vec::new();
1587
1588        // Helper to extract destination area IDs from cortical_mapping_dst (as strings)
1589        let extract_destinations = |area: &CorticalArea| -> Vec<String> {
1590            area.properties
1591                .get("cortical_mapping_dst")
1592                .and_then(|v| v.as_object())
1593                .map(|obj| obj.keys().cloned().collect())
1594                .unwrap_or_default()
1595        };
1596
1597        // Find OUTPUTS: areas in region that connect to areas OUTSIDE region
1598        for area_id in region_area_ids {
1599            if let Some(area) = all_cortical_areas.get(area_id) {
1600                let destinations = extract_destinations(area);
1601                // Convert destination strings to CorticalID for comparison
1602                let external_destinations: Vec<_> = destinations
1603                    .iter()
1604                    .filter_map(|dest| feagi_evolutionary::string_to_cortical_id(dest).ok())
1605                    .filter(|dest_id| !area_set.contains(dest_id))
1606                    .collect();
1607
1608                if !external_destinations.is_empty() {
1609                    outputs.push(area_id.as_base_64());
1610                }
1611            }
1612        }
1613
1614        // Find INPUTS: areas in region receiving connections from OUTSIDE region
1615        for (source_area_id, source_area) in all_cortical_areas.iter() {
1616            // Skip areas that are inside the region
1617            if area_set.contains(source_area_id) {
1618                continue;
1619            }
1620
1621            let destinations = extract_destinations(source_area);
1622            for dest_str in destinations {
1623                if let Ok(dest_id) = feagi_evolutionary::string_to_cortical_id(&dest_str) {
1624                    if area_set.contains(&dest_id) {
1625                        let dest_string = dest_id.as_base_64();
1626                        if !inputs.contains(&dest_string) {
1627                            inputs.push(dest_string);
1628                        }
1629                    }
1630                }
1631            }
1632        }
1633
1634        (inputs, outputs)
1635    }
1636
1637    /// Update development stage
1638    fn update_stage(&self, stage: DevelopmentStage, progress: u8) {
1639        let mut p = self.progress.write();
1640        p.stage = stage;
1641        p.progress = progress;
1642        p.duration_ms = self.start_time.elapsed().as_millis() as u64;
1643    }
1644
1645    /// Update progress with a closure
1646    fn update_progress<F>(&self, f: F)
1647    where
1648        F: FnOnce(&mut DevelopmentProgress),
1649    {
1650        let mut p = self.progress.write();
1651        f(&mut p);
1652        p.duration_ms = self.start_time.elapsed().as_millis() as u64;
1653    }
1654}
1655
1656#[cfg(test)]
1657mod tests {
1658    use super::*;
1659    use feagi_evolutionary::create_genome_with_core_morphologies;
1660    use feagi_structures::genomic::cortical_area::CorticalAreaDimensions;
1661
1662    #[test]
1663    fn test_neuroembryogenesis_creation() {
1664        let _state_guard = crate::connectome_manager::tests::PREPARE_FOR_NEW_GENOME_TEST_LOCK
1665            .lock()
1666            .unwrap_or_else(|e| e.into_inner());
1667        let manager = ConnectomeManager::instance();
1668        let neuro = Neuroembryogenesis::new(manager);
1669
1670        let progress = neuro.get_progress();
1671        assert_eq!(progress.stage, DevelopmentStage::Initialization);
1672        assert_eq!(progress.progress, 0);
1673    }
1674
1675    #[test]
1676    fn autogen_subregion_display_name_uses_title_when_meaningful() {
1677        assert_eq!(
1678            autogen_subregion_display_name("My Shared Circuit"),
1679            "My Shared Circuit"
1680        );
1681    }
1682
1683    #[test]
1684    fn autogen_subregion_display_name_falls_back_for_untitled() {
1685        assert_eq!(
1686            autogen_subregion_display_name("Untitled"),
1687            "Autogen Circuit"
1688        );
1689        assert_eq!(
1690            autogen_subregion_display_name("untitled"),
1691            "Autogen Circuit"
1692        );
1693    }
1694
1695    #[test]
1696    fn autogen_subregion_display_name_falls_back_for_blank() {
1697        assert_eq!(autogen_subregion_display_name(""), "Autogen Circuit");
1698        assert_eq!(autogen_subregion_display_name("   "), "Autogen Circuit");
1699    }
1700
1701    #[test]
1702    fn order_regions_puts_parent_before_grandchild_even_when_child_is_listed_first() {
1703        let root = "root".to_string();
1704        let parent = "look-for-people".to_string();
1705        let grandchild = "wave".to_string();
1706        let sibling = "look-for-ball".to_string();
1707
1708        // HashMap-unlucky listing: grandchild before its parent.
1709        let remaining = vec![grandchild.clone(), sibling.clone(), parent.clone()];
1710        let mut parent_map = std::collections::HashMap::new();
1711        parent_map.insert(parent.clone(), root.clone());
1712        parent_map.insert(grandchild.clone(), parent.clone());
1713        parent_map.insert(sibling.clone(), root);
1714
1715        let ordered = order_regions_parent_before_child(&remaining, &parent_map);
1716        let parent_idx = ordered.iter().position(|id| id == &parent).unwrap();
1717        let grandchild_idx = ordered.iter().position(|id| id == &grandchild).unwrap();
1718
1719        assert_eq!(ordered.len(), 3);
1720        assert!(
1721            parent_idx < grandchild_idx,
1722            "parent must precede grandchild, got {:?}",
1723            ordered
1724        );
1725    }
1726
1727    #[test]
1728    fn order_regions_keeps_flat_children_when_parent_is_already_inserted() {
1729        let remaining = vec!["a".to_string(), "b".to_string(), "c".to_string()];
1730        let mut parent_map = std::collections::HashMap::new();
1731        parent_map.insert("a".to_string(), "root".to_string());
1732        parent_map.insert("b".to_string(), "root".to_string());
1733        parent_map.insert("c".to_string(), "root".to_string());
1734
1735        let ordered = order_regions_parent_before_child(&remaining, &parent_map);
1736        let mut sorted = ordered.clone();
1737        sorted.sort();
1738        assert_eq!(sorted, remaining);
1739    }
1740
1741    #[test]
1742    fn order_regions_appends_cycle_members_after_acyclic_prefix() {
1743        let remaining = vec!["a".to_string(), "b".to_string(), "ok".to_string()];
1744        let mut parent_map = std::collections::HashMap::new();
1745        parent_map.insert("a".to_string(), "b".to_string());
1746        parent_map.insert("b".to_string(), "a".to_string());
1747        parent_map.insert("ok".to_string(), "root".to_string());
1748
1749        let ordered = order_regions_parent_before_child(&remaining, &parent_map);
1750        assert_eq!(ordered.first().map(String::as_str), Some("ok"));
1751        assert_eq!(ordered.len(), 3);
1752        assert!(ordered.contains(&"a".to_string()));
1753        assert!(ordered.contains(&"b".to_string()));
1754    }
1755
1756    #[test]
1757    fn test_development_from_minimal_genome() {
1758        let _state_guard = crate::connectome_manager::tests::PREPARE_FOR_NEW_GENOME_TEST_LOCK
1759            .lock()
1760            .unwrap_or_else(|e| e.into_inner());
1761        ConnectomeManager::reset_for_testing(); // Ensure clean state
1762        let manager = ConnectomeManager::instance();
1763        {
1764            let runtime = feagi_npu_runtime::StdRuntime;
1765            let backend = feagi_npu_burst_engine::backend::CPUBackend::new();
1766            let npu_result =
1767                feagi_npu_burst_engine::RustNPU::new(runtime, backend, 1_000_000, 10_000_000, 10)
1768                    .expect("Failed to create NPU");
1769            let npu = std::sync::Arc::new(feagi_npu_burst_engine::TracingMutex::new(
1770                feagi_npu_burst_engine::DynamicNPU::F32(npu_result),
1771                "minimal-genome-test-npu",
1772            ));
1773            manager.write().set_npu(npu);
1774        }
1775        let mut neuro = Neuroembryogenesis::new(manager.clone());
1776
1777        // Create a minimal genome with one cortical area
1778        let mut genome = create_genome_with_core_morphologies(
1779            "test_genome".to_string(),
1780            "Test Genome".to_string(),
1781        );
1782
1783        let cortical_id = CorticalID::try_from_bytes(b"cst_neur").unwrap(); // Use valid custom cortical ID
1784        let cortical_type = cortical_id
1785            .as_cortical_type()
1786            .expect("Failed to get cortical type");
1787        let area = CorticalArea::new(
1788            cortical_id,
1789            0,
1790            "Test Area".to_string(),
1791            CorticalAreaDimensions::new(10, 10, 10).unwrap(),
1792            (0, 0, 0).into(),
1793            cortical_type,
1794        )
1795        .expect("Failed to create cortical area");
1796        genome.cortical_areas.insert(cortical_id, area);
1797
1798        // Run neuroembryogenesis
1799        let result = neuro.develop_from_genome(&genome);
1800        assert!(result.is_ok(), "Development failed: {:?}", result);
1801
1802        // Check progress
1803        let progress = neuro.get_progress();
1804        assert_eq!(progress.stage, DevelopmentStage::Completed);
1805        assert_eq!(progress.progress, 100);
1806        assert_eq!(progress.cortical_areas_created, 1);
1807
1808        // Do not assert on ConnectomeManager::instance() contents here: other tests run in parallel
1809        // and share the same singleton; the progress fields above already reflect this run's outcome.
1810
1811        println!("✅ Development completed in {}ms", progress.duration_ms);
1812    }
1813
1814    /// Core area `n` must own neuron `n` on every load, however the genome map iterates.
1815    #[test]
1816    fn core_neuron_ids_equal_area_index_on_every_load() {
1817        let _state_guard = crate::connectome_manager::tests::PREPARE_FOR_NEW_GENOME_TEST_LOCK
1818            .lock()
1819            .unwrap_or_else(|e| e.into_inner());
1820        use feagi_structures::genomic::cortical_area::{
1821            CoreCorticalType, CorticalAreaType, CustomCorticalType,
1822        };
1823
1824        let core = [
1825            CoreCorticalType::Death,
1826            CoreCorticalType::Power,
1827            CoreCorticalType::Fatigue,
1828            CoreCorticalType::Pain,
1829            CoreCorticalType::Pleasure,
1830            CoreCorticalType::Fear,
1831            CoreCorticalType::Hope,
1832        ];
1833        for load in 0..12 {
1834            let runtime = feagi_npu_runtime::StdRuntime;
1835            let backend = feagi_npu_burst_engine::backend::CPUBackend::new();
1836            let npu = feagi_npu_burst_engine::RustNPU::new(runtime, backend, 100_000, 100_000, 10)
1837                .expect("Failed to create NPU");
1838            let npu = std::sync::Arc::new(feagi_npu_burst_engine::TracingMutex::new(
1839                feagi_npu_burst_engine::DynamicNPU::F32(npu),
1840                "core-order-test-npu",
1841            ));
1842            let manager = Arc::new(RwLock::new(ConnectomeManager::new_for_testing_with_npu(
1843                npu.clone(),
1844            )));
1845            let mut neuro = Neuroembryogenesis::new(manager.clone());
1846            let mut genome = create_genome_with_core_morphologies(
1847                "core_order".to_string(),
1848                "Core Order".to_string(),
1849            );
1850            for kind in core {
1851                let id = kind.to_cortical_id();
1852                let area = CorticalArea::new(
1853                    id,
1854                    0,
1855                    format!("core-{id}"),
1856                    CorticalAreaDimensions::new(1, 1, 1).unwrap(),
1857                    (0, 0, 0).into(),
1858                    CorticalAreaType::Core(kind),
1859                )
1860                .unwrap();
1861                genome.cortical_areas.insert(id, area);
1862            }
1863            for n in 0..24u8 {
1864                let id = CorticalID::try_from_bytes(&[
1865                    b'c',
1866                    b'o',
1867                    b'r',
1868                    b'd',
1869                    b'0',
1870                    b'0',
1871                    b'0' + n / 10,
1872                    b'0' + n % 10,
1873                ])
1874                .unwrap();
1875                let area = CorticalArea::new(
1876                    id,
1877                    0,
1878                    format!("other-{n}"),
1879                    CorticalAreaDimensions::new(1, 1, 1).unwrap(),
1880                    (n as i32, 0, 0).into(),
1881                    CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire),
1882                )
1883                .unwrap();
1884                genome.cortical_areas.insert(id, area);
1885            }
1886            neuro
1887                .develop_from_genome(&genome)
1888                .expect("development must succeed");
1889
1890            let npu = npu.lock().unwrap();
1891            for index in 0..7u32 {
1892                assert_eq!(
1893                    npu.get_neurons_in_cortical_area(index),
1894                    vec![index],
1895                    "load {load}: core area {index} must own neuron {index}"
1896                );
1897            }
1898        }
1899    }
1900
1901    /// Other areas get the same indices on every load.
1902    #[test]
1903    fn registration_order_is_deterministic() {
1904        use feagi_structures::genomic::cortical_area::{CorticalAreaType, CustomCorticalType};
1905
1906        let mut genome = create_genome_with_core_morphologies("o".to_string(), "o".to_string());
1907        for n in 0..16u8 {
1908            let id = CorticalID::try_from_bytes(&[
1909                b'o',
1910                b'r',
1911                b'd',
1912                b'0',
1913                b'0',
1914                b'0',
1915                b'0' + n / 10,
1916                b'0' + n % 10,
1917            ])
1918            .unwrap();
1919            let area = CorticalArea::new(
1920                id,
1921                0,
1922                format!("a{n}"),
1923                CorticalAreaDimensions::new(1, 1, 1).unwrap(),
1924                (0, 0, 0).into(),
1925                CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire),
1926            )
1927            .unwrap();
1928            genome.cortical_areas.insert(id, area);
1929        }
1930        let expected: Vec<String> = ordered_genome_areas(&genome)
1931            .iter()
1932            .map(|(id, _)| id.as_base_64())
1933            .collect();
1934        let mut sorted = expected.clone();
1935        sorted.sort();
1936        assert_eq!(expected, sorted, "unindexed areas register by id");
1937    }
1938
1939    /// Loading a genome creates the twin of an episodic upstream-to-memory pair that has no
1940    /// saved twin, so the rebind after an import of its export has nothing left to add.
1941    #[test]
1942    fn genome_load_creates_missing_twins_like_the_import_rebind() {
1943        let _state_guard = crate::connectome_manager::tests::PREPARE_FOR_NEW_GENOME_TEST_LOCK
1944            .lock()
1945            .unwrap_or_else(|e| e.into_inner());
1946        use feagi_structures::genomic::cortical_area::{
1947            CorticalAreaType, CustomCorticalType, MemoryCorticalType,
1948        };
1949
1950        let runtime = feagi_npu_runtime::StdRuntime;
1951        let backend = feagi_npu_burst_engine::backend::CPUBackend::new();
1952        let npu = feagi_npu_burst_engine::RustNPU::new(runtime, backend, 100_000, 100_000, 10)
1953            .expect("Failed to create NPU");
1954        let npu = std::sync::Arc::new(feagi_npu_burst_engine::TracingMutex::new(
1955            feagi_npu_burst_engine::DynamicNPU::F32(npu),
1956            "twin-load-test-npu",
1957        ));
1958        let manager = Arc::new(RwLock::new(ConnectomeManager::new_for_testing_with_npu(
1959            npu,
1960        )));
1961        let mut neuro = Neuroembryogenesis::new(manager.clone());
1962        let mut genome =
1963            create_genome_with_core_morphologies("twin_load".to_string(), "Twin Load".to_string());
1964        let upstream_id = CorticalID::try_from_bytes(b"cupa0021").unwrap();
1965        let memory_id = CorticalID::try_from_bytes(b"mmem0021").unwrap();
1966        let mut upstream = CorticalArea::new(
1967            upstream_id,
1968            0,
1969            "upstream".to_string(),
1970            CorticalAreaDimensions::new(1, 1, 1).unwrap(),
1971            (0, 0, 0).into(),
1972            CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire),
1973        )
1974        .unwrap();
1975        upstream.properties.insert(
1976            "cortical_mapping_dst".to_string(),
1977            serde_json::json!({ memory_id.as_base_64(): [{ "morphology_id": "episodic_memory" }] }),
1978        );
1979        let mut memory = CorticalArea::new(
1980            memory_id,
1981            0,
1982            "memory".to_string(),
1983            CorticalAreaDimensions::new(1, 1, 1).unwrap(),
1984            (1, 0, 0).into(),
1985            CorticalAreaType::Memory(MemoryCorticalType::Memory),
1986        )
1987        .unwrap();
1988        memory
1989            .properties
1990            .insert("is_mem_type".to_string(), serde_json::json!(true));
1991        genome.cortical_areas.insert(upstream_id, upstream);
1992        genome.cortical_areas.insert(memory_id, memory);
1993
1994        neuro
1995            .develop_from_genome(&genome)
1996            .expect("development must succeed");
1997
1998        let area_count = || manager.read().get_cortical_area_ids().len();
1999        let after_load = area_count();
2000        let twin_id = {
2001            let guard = manager.read();
2002            guard
2003                .get_cortical_area(&memory_id)
2004                .and_then(|area| area.properties.get("memory_twin_areas"))
2005                .and_then(|value| value.get(upstream_id.as_base_64()))
2006                .and_then(|value| value.as_str())
2007                .and_then(|twin| CorticalID::try_from_base_64(twin).ok())
2008                .expect("load must index the twin it created")
2009        };
2010        assert!(manager.read().has_cortical_area(&twin_id));
2011        manager
2012            .write()
2013            .rebuild_memory_twin_mappings()
2014            .expect("the import rebind must succeed");
2015        assert_eq!(
2016            area_count(),
2017            after_load,
2018            "the rebind adds no area after a load"
2019        );
2020    }
2021
2022    /// Loads a genome whose explicit root region holds the given stray placement, then
2023    /// returns the manager and the ids (upstream, memory).
2024    fn develop_genome_with_strays(
2025        place_in_root: bool,
2026        place_in_circuit: bool,
2027    ) -> (Arc<RwLock<ConnectomeManager>>, CorticalID, CorticalID) {
2028        use feagi_structures::genomic::brain_regions::{BrainRegion, RegionID, RegionType};
2029        use feagi_structures::genomic::cortical_area::{
2030            CorticalAreaType, CustomCorticalType, MemoryCorticalType,
2031        };
2032        let runtime = feagi_npu_runtime::StdRuntime;
2033        let backend = feagi_npu_burst_engine::backend::CPUBackend::new();
2034        let npu = feagi_npu_burst_engine::RustNPU::new(runtime, backend, 100_000, 100_000, 10)
2035            .expect("Failed to create NPU");
2036        let npu = std::sync::Arc::new(feagi_npu_burst_engine::TracingMutex::new(
2037            feagi_npu_burst_engine::DynamicNPU::F32(npu),
2038            "stray-load-test-npu",
2039        ));
2040        let manager = Arc::new(RwLock::new(ConnectomeManager::new_for_testing_with_npu(
2041            npu,
2042        )));
2043        let mut neuro = Neuroembryogenesis::new(manager.clone());
2044        let mut genome =
2045            create_genome_with_core_morphologies("stray_load".to_string(), "Stray".to_string());
2046        let upstream_id = CorticalID::try_from_bytes(b"cupa0031").unwrap();
2047        let memory_id = CorticalID::try_from_bytes(b"mmem0031").unwrap();
2048        let mut upstream = CorticalArea::new(
2049            upstream_id,
2050            0,
2051            "upstream".to_string(),
2052            CorticalAreaDimensions::new(1, 1, 1).unwrap(),
2053            (0, 0, 0).into(),
2054            CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire),
2055        )
2056        .unwrap();
2057        upstream.properties.insert(
2058            "cortical_mapping_dst".to_string(),
2059            serde_json::json!({ memory_id.as_base_64(): [{ "morphology_id": "episodic_memory" }] }),
2060        );
2061        let mut memory = CorticalArea::new(
2062            memory_id,
2063            0,
2064            "memory".to_string(),
2065            CorticalAreaDimensions::new(1, 1, 1).unwrap(),
2066            (1, 0, 0).into(),
2067            CorticalAreaType::Memory(MemoryCorticalType::Memory),
2068        )
2069        .unwrap();
2070        memory
2071            .properties
2072            .insert("is_mem_type".to_string(), serde_json::json!(true));
2073        genome.cortical_areas.insert(upstream_id, upstream);
2074        genome.cortical_areas.insert(memory_id, memory);
2075
2076        let mut root = BrainRegion::new(
2077            RegionID::new(),
2078            ROOT_BRAIN_REGION_NAME.to_string(),
2079            RegionType::Undefined,
2080        )
2081        .unwrap();
2082        if place_in_root {
2083            root = root.with_areas([upstream_id, memory_id]);
2084        }
2085        let root_key = root.region_id.to_string();
2086        genome.brain_regions.insert(root_key.clone(), root);
2087        if place_in_circuit {
2088            let mut circuit = BrainRegion::new(
2089                RegionID::new(),
2090                "circuit".to_string(),
2091                RegionType::Undefined,
2092            )
2093            .unwrap()
2094            .with_areas([upstream_id, memory_id]);
2095            circuit.add_property("parent_region_id".to_string(), serde_json::json!(root_key));
2096            genome
2097                .brain_regions
2098                .insert(circuit.region_id.to_string(), circuit);
2099        }
2100        neuro
2101            .develop_from_genome(&genome)
2102            .expect("load must repair strays instead of failing");
2103        (manager, upstream_id, memory_id)
2104    }
2105
2106    fn recovered_region_ids(manager: &Arc<RwLock<ConnectomeManager>>) -> Vec<String> {
2107        let guard = manager.read();
2108        guard
2109            .get_brain_region_ids()
2110            .into_iter()
2111            .filter(|id| {
2112                guard.get_brain_region(id).is_some_and(|r| {
2113                    r.name == crate::connectome_manager::RECOVERED_AREAS_REGION_NAME
2114                })
2115            })
2116            .cloned()
2117            .collect()
2118    }
2119
2120    fn assert_stray_load_repaired(
2121        manager: &Arc<RwLock<ConnectomeManager>>,
2122        upstream_id: CorticalID,
2123        memory_id: CorticalID,
2124    ) {
2125        let recovered = recovered_region_ids(manager);
2126        assert_eq!(recovered.len(), 1);
2127        let guard = manager.read();
2128        let root_id = guard.get_root_region_id().unwrap();
2129        let region = guard.get_brain_region(&recovered[0]).unwrap();
2130        assert!(region.contains_area(&upstream_id) && region.contains_area(&memory_id));
2131        let root = guard.get_brain_region(&root_id).unwrap();
2132        assert!(!root.contains_area(&upstream_id) && !root.contains_area(&memory_id));
2133        let twin_id = guard
2134            .get_cortical_area(&memory_id)
2135            .and_then(|area| area.properties.get("memory_twin_areas"))
2136            .and_then(|value| value.get(upstream_id.as_base_64()))
2137            .and_then(|value| value.as_str())
2138            .and_then(|twin| CorticalID::try_from_base_64(twin).ok())
2139            .expect("twin must be created");
2140        let twin_region = guard.get_parent_region_id_for_area(&twin_id).unwrap();
2141        assert_ne!(twin_region, root_id, "twin must not sit in root");
2142    }
2143
2144    #[test]
2145    fn genome_load_moves_custom_and_memory_areas_out_of_root() {
2146        let _state_guard = crate::connectome_manager::tests::PREPARE_FOR_NEW_GENOME_TEST_LOCK
2147            .lock()
2148            .unwrap_or_else(|e| e.into_inner());
2149        let (manager, up, mem) = develop_genome_with_strays(true, false);
2150        assert_stray_load_repaired(&manager, up, mem);
2151    }
2152
2153    #[test]
2154    fn genome_load_places_custom_and_memory_areas_without_a_region() {
2155        let _state_guard = crate::connectome_manager::tests::PREPARE_FOR_NEW_GENOME_TEST_LOCK
2156            .lock()
2157            .unwrap_or_else(|e| e.into_inner());
2158        let (manager, up, mem) = develop_genome_with_strays(false, false);
2159        assert_stray_load_repaired(&manager, up, mem);
2160    }
2161
2162    #[test]
2163    fn genome_load_of_clean_regions_creates_no_recovered_areas_region() {
2164        let _state_guard = crate::connectome_manager::tests::PREPARE_FOR_NEW_GENOME_TEST_LOCK
2165            .lock()
2166            .unwrap_or_else(|e| e.into_inner());
2167        let (manager, _, _) = develop_genome_with_strays(false, true);
2168        assert!(recovered_region_ids(&manager).is_empty());
2169    }
2170
2171    /// A genome with a saved memory twin must register the twin's replay route with the NPU on
2172    /// load, without adding or regenerating anything: replay to twins is off without the route.
2173    #[test]
2174    fn genome_load_registers_saved_twin_route_with_npu() {
2175        let _state_guard = crate::connectome_manager::tests::PREPARE_FOR_NEW_GENOME_TEST_LOCK
2176            .lock()
2177            .unwrap_or_else(|e| e.into_inner());
2178        use feagi_structures::genomic::cortical_area::{
2179            CorticalAreaType, CustomCorticalType, MemoryCorticalType,
2180        };
2181
2182        let runtime = feagi_npu_runtime::StdRuntime;
2183        let backend = feagi_npu_burst_engine::backend::CPUBackend::new();
2184        let npu = feagi_npu_burst_engine::RustNPU::new(runtime, backend, 100_000, 100_000, 10)
2185            .expect("Failed to create NPU");
2186        let npu = std::sync::Arc::new(feagi_npu_burst_engine::TracingMutex::new(
2187            feagi_npu_burst_engine::DynamicNPU::F32(npu),
2188            "saved-twin-load-test-npu",
2189        ));
2190        let manager = Arc::new(RwLock::new(ConnectomeManager::new_for_testing_with_npu(
2191            npu.clone(),
2192        )));
2193        let mut neuro = Neuroembryogenesis::new(manager.clone());
2194        let mut genome = create_genome_with_core_morphologies(
2195            "saved_twin".to_string(),
2196            "Saved Twin".to_string(),
2197        );
2198        let upstream_id = CorticalID::try_from_bytes(b"cupa0031").unwrap();
2199        let memory_id = CorticalID::try_from_bytes(b"mmem0031").unwrap();
2200        // Not the hash-derived twin id, as in a genome saved by an older build.
2201        let twin_id = CorticalID::try_from_bytes(b"ctwin031").unwrap();
2202        let lif = |id: CorticalID, name: &str| {
2203            CorticalArea::new(
2204                id,
2205                0,
2206                name.to_string(),
2207                CorticalAreaDimensions::new(1, 1, 1).unwrap(),
2208                (0, 0, 0).into(),
2209                CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire),
2210            )
2211            .unwrap()
2212        };
2213        let mut upstream = lif(upstream_id, "upstream");
2214        upstream.properties.insert(
2215            "cortical_mapping_dst".to_string(),
2216            serde_json::json!({ memory_id.as_base_64(): [{ "morphology_id": "episodic_memory" }] }),
2217        );
2218        let mut memory = CorticalArea::new(
2219            memory_id,
2220            0,
2221            "memory".to_string(),
2222            CorticalAreaDimensions::new(1, 1, 1).unwrap(),
2223            (1, 0, 0).into(),
2224            CorticalAreaType::Memory(MemoryCorticalType::Memory),
2225        )
2226        .unwrap();
2227        memory
2228            .properties
2229            .insert("is_mem_type".to_string(), serde_json::json!(true));
2230        memory.properties.insert(
2231            "cortical_mapping_dst".to_string(),
2232            serde_json::json!({ twin_id.as_base_64(): [{ "morphology_id": "episodic_memory" }] }),
2233        );
2234        let mut twin = lif(twin_id, "upstream_twin");
2235        twin.properties.insert(
2236            "memory_twin_of".to_string(),
2237            serde_json::json!(upstream_id.as_base_64()),
2238        );
2239        genome.cortical_areas.insert(upstream_id, upstream);
2240        genome.cortical_areas.insert(memory_id, memory);
2241        genome.cortical_areas.insert(twin_id, twin);
2242
2243        neuro
2244            .develop_from_genome(&genome)
2245            .expect("development must succeed");
2246
2247        let (mem_idx, up_idx, twin_idx, area_count) = {
2248            let guard = manager.read();
2249            assert!(guard.has_cortical_area(&twin_id), "the saved twin is kept");
2250            (
2251                guard.get_cortical_idx(&memory_id).unwrap(),
2252                guard.get_cortical_idx(&upstream_id).unwrap(),
2253                guard.get_cortical_idx(&twin_id).unwrap(),
2254                guard.get_cortical_area_ids().len(),
2255            )
2256        };
2257        let route = npu
2258            .lock()
2259            .unwrap()
2260            .get_memory_twin_mapping(mem_idx, up_idx)
2261            .map(|(idx, _)| idx);
2262        assert_eq!(
2263            route,
2264            Some(twin_idx),
2265            "load must register the saved twin route"
2266        );
2267        assert_eq!(
2268            area_count, 3,
2269            "the saved twin is reused, no second twin is created"
2270        );
2271    }
2272
2273    /// Genome load must refresh a reward-trained classifier's stored eligibility: the mapping
2274    /// rules only exist once synaptogenesis has run.
2275    #[test]
2276    fn genome_load_refreshes_classifier_reward_eligibility() {
2277        let _state_guard = crate::connectome_manager::tests::PREPARE_FOR_NEW_GENOME_TEST_LOCK
2278            .lock()
2279            .unwrap_or_else(|e| e.into_inner());
2280        use feagi_structures::genomic::classifiers::Classifier;
2281        use feagi_structures::genomic::cortical_area::{CorticalAreaType, MemoryCorticalType};
2282
2283        let runtime = feagi_npu_runtime::StdRuntime;
2284        let backend = feagi_npu_burst_engine::backend::CPUBackend::new();
2285        let npu = feagi_npu_burst_engine::RustNPU::new(runtime, backend, 100_000, 100_000, 10)
2286            .expect("Failed to create NPU");
2287        let npu = std::sync::Arc::new(feagi_npu_burst_engine::TracingMutex::new(
2288            feagi_npu_burst_engine::DynamicNPU::F32(npu),
2289            "eligibility-load-test-npu",
2290        ));
2291        let manager = Arc::new(RwLock::new(ConnectomeManager::new_for_testing_with_npu(
2292            npu.clone(),
2293        )));
2294        let mut neuro = Neuroembryogenesis::new(manager.clone());
2295
2296        let mut genome = create_genome_with_core_morphologies(
2297            "elig_genome".to_string(),
2298            "Elig Genome".to_string(),
2299        );
2300        let memory_area = |bytes: &[u8; 8], name: &str| {
2301            let mut area = CorticalArea::new(
2302                CorticalID::try_from_bytes(bytes).unwrap(),
2303                0,
2304                name.to_string(),
2305                CorticalAreaDimensions::new(1, 1, 1).unwrap(),
2306                (0, 0, 0).into(),
2307                CorticalAreaType::Memory(MemoryCorticalType::Memory),
2308            )
2309            .unwrap();
2310            area.properties
2311                .insert("is_mem_type".to_string(), serde_json::json!(true));
2312            area
2313        };
2314        let mut sample = memory_area(b"melgsmp1", "sample");
2315        let class_mem = memory_area(b"melgcls1", "class");
2316        let (sample_id, class_id) = (sample.cortical_id, class_mem.cortical_id);
2317        sample.properties.insert(
2318            "cortical_mapping_dst".to_string(),
2319            serde_json::json!({ class_id.as_base_64(): [{
2320                "morphology_id": "associative_memory",
2321                "plasticity_flag": true,
2322                "plasticity_mode": "rstdp",
2323                "modulators": [],
2324                "eligibility_decay_bursts": 4,
2325                "plasticity_constant": 1,
2326                "ltp_multiplier": 1,
2327                "ltd_multiplier": 1,
2328                "plasticity_window": 4
2329            }]}),
2330        );
2331        genome.cortical_areas.insert(sample_id, sample);
2332        genome.cortical_areas.insert(class_id, class_mem);
2333        genome.classifiers.insert(
2334            "clf-elig".to_string(),
2335            Classifier {
2336                classifier_id: "clf-elig".to_string(),
2337                name: "elig".to_string(),
2338                parent_region_id: "root".to_string(),
2339                coordinates_3d: [0, 0, 0],
2340                sample_area_ids: Vec::new(),
2341                class_bindings: Vec::new(),
2342                sample_memory_id: sample_id.as_base_64(),
2343                class_memory_id: class_id.as_base_64(),
2344                error_area_id: "err".to_string(),
2345                reward_training: true,
2346                answer_feedback_area_id: None,
2347                correct_area_id: String::new(),
2348                reward_modulator_ids: Vec::new(),
2349                answer_latency_bursts: 0,
2350                learn_area_id: None,
2351                confidence_area_id: None,
2352                properties: std::collections::HashMap::new(),
2353            },
2354        );
2355
2356        neuro.develop_from_genome(&genome).expect("load failed");
2357
2358        let guard = manager.read();
2359        let stored = guard.get_mapping_rules(&sample_id, &class_id).unwrap()[0]
2360            ["eligibility_decay_bursts"]
2361            .as_u64()
2362            .unwrap();
2363        // Default circuit answer delay 3 gives eligibility 5.
2364        assert_eq!(stored, 5, "stored rule must follow the circuit on load");
2365        let params = npu.lock().unwrap().stdp_mapping_params(
2366            guard.get_cortical_area(&sample_id).unwrap().cortical_idx,
2367            guard.get_cortical_area(&class_id).unwrap().cortical_idx,
2368        );
2369        if let Some(params) = params {
2370            assert_eq!(params.eligibility_decay_bursts, 5);
2371        }
2372    }
2373}