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        } // Lock released
971
972        self.update_stage(DevelopmentStage::Corticogenesis, 100);
973        info!(target: "feagi-bdu","  ✅ Corticogenesis complete: {} cortical areas created", total_areas);
974
975        Ok(())
976    }
977
978    /// Stage 2: Voxelogenesis - Establish spatial framework
979    fn voxelogenesis(&mut self, _genome: &RuntimeGenome) -> BduResult<()> {
980        self.update_stage(DevelopmentStage::Voxelogenesis, 0);
981        info!(target: "feagi-bdu","📐 Stage 2: Voxelogenesis - Establishing spatial framework");
982
983        // Spatial framework is implicitly established by cortical area dimensions
984        // The Morton spatial hash in ConnectomeManager handles the actual indexing
985
986        self.update_stage(DevelopmentStage::Voxelogenesis, 100);
987        info!(target: "feagi-bdu","  ✅ Voxelogenesis complete: Spatial framework established");
988
989        Ok(())
990    }
991
992    /// Stage 3: Neurogenesis - Generate neurons within cortical areas
993    ///
994    /// This uses ConnectomeManager which delegates to NPU's SIMD-optimized batch operations.
995    /// Each cortical area is processed with `create_cortical_area_neurons()` which creates
996    /// ALL neurons for that area in one vectorized operation (not a loop).
997    ///
998    /// CRITICAL: Core areas (0=_death, 1=_power, 2=_fatigue, 3=_pain, 4=_pleasure, 5=_fear, 6=_hope) are created
999    /// FIRST to ensure deterministic neuron IDs.
1000    fn neurogenesis(&mut self, genome: &RuntimeGenome) -> BduResult<()> {
1001        self.update_stage(DevelopmentStage::Neurogenesis, 0);
1002        info!(target: "feagi-bdu","🔬 Stage 3: Neurogenesis - Generating neurons (SIMD-optimized batches)");
1003
1004        let expected_neurons = genome.stats.innate_neuron_count;
1005        info!(target: "feagi-bdu","  Expected innate neurons from genome: {}", expected_neurons);
1006
1007        // CRITICAL: Identify core areas first to ensure deterministic neuron IDs
1008        use feagi_structures::genomic::cortical_area::CoreCorticalType;
1009        let death_id = CoreCorticalType::Death.to_cortical_id();
1010        let power_id = CoreCorticalType::Power.to_cortical_id();
1011        let fatigue_id = CoreCorticalType::Fatigue.to_cortical_id();
1012        let pain_id = CoreCorticalType::Pain.to_cortical_id();
1013        let pleasure_id = CoreCorticalType::Pleasure.to_cortical_id();
1014        let fear_id = CoreCorticalType::Fear.to_cortical_id();
1015        let hope_id = CoreCorticalType::Hope.to_cortical_id();
1016
1017        let mut core_areas = Vec::new();
1018        let mut other_areas = Vec::new();
1019
1020        // Separate core areas from other areas
1021        for (cortical_id, area) in genome.cortical_areas.iter() {
1022            if *cortical_id == death_id {
1023                core_areas.push((0, *cortical_id, area)); // Area 0 = _death
1024            } else if *cortical_id == power_id {
1025                core_areas.push((1, *cortical_id, area)); // Area 1 = _power
1026            } else if *cortical_id == fatigue_id {
1027                core_areas.push((2, *cortical_id, area)); // Area 2 = _fatigue
1028            } else if *cortical_id == pain_id {
1029                core_areas.push((3, *cortical_id, area)); // Area 3 = _pain
1030            } else if *cortical_id == pleasure_id {
1031                core_areas.push((4, *cortical_id, area)); // Area 4 = _pleasure
1032            } else if *cortical_id == fear_id {
1033                core_areas.push((5, *cortical_id, area)); // Area 5 = _fear
1034            } else if *cortical_id == hope_id {
1035                core_areas.push((6, *cortical_id, area)); // Area 6 = _hope
1036            } else {
1037                other_areas.push((*cortical_id, area));
1038            }
1039        }
1040
1041        // Sort core areas by their deterministic index (0..=6); the rest in registration order
1042        core_areas.sort_by_key(|(idx, _, _)| *idx);
1043        other_areas.sort_by_key(|(cortical_id, area)| registration_order_key(cortical_id, area));
1044
1045        info!(target: "feagi-bdu","  🎯 Creating core area neurons FIRST ({} areas) for deterministic IDs", core_areas.len());
1046
1047        let mut total_neurons_created = 0;
1048        let mut processed_count = 0;
1049        let total_areas = genome.cortical_areas.len();
1050
1051        // STEP 1: Create core area neurons FIRST (in order: 0..=6)
1052        for (core_idx, cortical_id, area) in &core_areas {
1053            let existing_core_neurons = {
1054                let manager = self.connectome_manager.read();
1055                let npu = manager.get_npu();
1056                match npu {
1057                    Some(npu_arc) => {
1058                        let npu_lock = npu_arc.lock();
1059                        match npu_lock {
1060                            Ok(npu_guard) => {
1061                                npu_guard.get_neurons_in_cortical_area(*core_idx).len()
1062                            }
1063                            Err(_) => 0,
1064                        }
1065                    }
1066                    None => 0,
1067                }
1068            };
1069
1070            if existing_core_neurons > 0 {
1071                self.sync_core_neuron_params(*core_idx, area)?;
1072                let refreshed = {
1073                    let manager = self.connectome_manager.read();
1074                    manager.refresh_neuron_count_for_area(cortical_id)
1075                };
1076                let count = refreshed.unwrap_or(existing_core_neurons);
1077                total_neurons_created += count;
1078                info!(
1079                    target: "feagi-bdu",
1080                    "  ↪ Skipping core neuron creation for {} (existing={}, idx={})",
1081                    cortical_id.as_base_64(),
1082                    count,
1083                    core_idx
1084                );
1085                processed_count += 1;
1086                let progress_pct = (processed_count * 100 / total_areas.max(1)) as u8;
1087                self.update_progress(|p| {
1088                    p.neurons_created = total_neurons_created;
1089                    p.progress = progress_pct;
1090                });
1091                continue;
1092            }
1093            let per_voxel_count = area
1094                .properties
1095                .get("neurons_per_voxel")
1096                .and_then(|v| v.as_u64())
1097                .unwrap_or(1) as i64;
1098
1099            let cortical_id_str = cortical_id.to_string();
1100            info!(target: "feagi-bdu","  🔋 [CORE-AREA {}] {} - dimensions: {:?}, per_voxel: {}",
1101                core_idx, cortical_id_str, area.dimensions, per_voxel_count);
1102
1103            if per_voxel_count == 0 {
1104                warn!(target: "feagi-bdu","  ⚠️ Skipping core area {} - per_voxel_neuron_cnt is 0", cortical_id_str);
1105                continue;
1106            }
1107
1108            // Create neurons for core area (ensures deterministic ID: area 0→neuron 0, area 1→neuron 1, area 2→neuron 2)
1109            let neurons_created = {
1110                let manager_arc = self.connectome_manager.clone();
1111                let mut manager = manager_arc.write();
1112                manager.create_neurons_for_area(cortical_id)
1113            };
1114
1115            match neurons_created {
1116                Ok(count) => {
1117                    total_neurons_created += count as usize;
1118                    info!(target: "feagi-bdu","  ✅ Created {} neurons for core area {} (deterministic ID: neuron {})",
1119                        count, cortical_id_str, core_idx);
1120                }
1121                Err(e) => {
1122                    error!(target: "feagi-bdu","  ❌ FATAL: Failed to create neurons for core area {}: {}", cortical_id_str, e);
1123                    return Err(e);
1124                }
1125            }
1126
1127            processed_count += 1;
1128            let progress_pct = (processed_count * 100 / total_areas.max(1)) as u8;
1129            self.update_progress(|p| {
1130                p.neurons_created = total_neurons_created;
1131                p.progress = progress_pct;
1132            });
1133        }
1134
1135        // STEP 2: Create neurons for all other areas
1136        info!(target: "feagi-bdu","  📦 Creating neurons for {} other areas", other_areas.len());
1137        for (cortical_id, area) in &other_areas {
1138            // Get neurons_per_voxel from typed field (single source of truth)
1139            let _per_voxel_count = area
1140                .properties
1141                .get("neurons_per_voxel")
1142                .and_then(|v| v.as_u64())
1143                .unwrap_or(1) as i64;
1144
1145            let per_voxel_count = area
1146                .properties
1147                .get("neurons_per_voxel")
1148                .and_then(|v| v.as_u64())
1149                .unwrap_or(1) as i64;
1150
1151            let cortical_id_str = cortical_id.to_string();
1152
1153            if per_voxel_count == 0 {
1154                warn!(target: "feagi-bdu","  ⚠️ Skipping area {} - per_voxel_neuron_cnt is 0 (will have NO neurons!)", cortical_id_str);
1155                continue;
1156            }
1157
1158            // Call ConnectomeManager to create neurons (delegates to NPU)
1159            // CRITICAL: Minimize lock scope - only hold lock during neuron creation
1160            let neurons_created = {
1161                let manager_arc = self.connectome_manager.clone();
1162                let mut manager = manager_arc.write();
1163                manager.create_neurons_for_area(cortical_id)
1164            }; // Lock released immediately
1165
1166            match neurons_created {
1167                Ok(count) => {
1168                    total_neurons_created += count as usize;
1169                    trace!(
1170                        target: "feagi-bdu",
1171                        "Created {} neurons for area {}",
1172                        count,
1173                        cortical_id_str
1174                    );
1175                }
1176                Err(e) => {
1177                    // If NPU not connected, calculate expected count
1178                    warn!(target: "feagi-bdu","  Failed to create neurons for {}: {} (NPU may not be connected)",
1179                        cortical_id_str, e);
1180                    let total_voxels = area.dimensions.width as usize
1181                        * area.dimensions.height as usize
1182                        * area.dimensions.depth as usize;
1183                    let expected = total_voxels * per_voxel_count as usize;
1184                    total_neurons_created += expected;
1185                }
1186            }
1187
1188            processed_count += 1;
1189            // Update progress
1190            let progress_pct = (processed_count * 100 / total_areas.max(1)) as u8;
1191            self.update_progress(|p| {
1192                p.neurons_created = total_neurons_created;
1193                p.progress = progress_pct;
1194            });
1195        }
1196
1197        // Compare with genome stats (info only - stats may count only innate neurons while we create all voxels)
1198        if expected_neurons > 0 && total_neurons_created != expected_neurons {
1199            trace!(target: "feagi-bdu",
1200                created_neurons = total_neurons_created,
1201                genome_stats_innate = expected_neurons,
1202                "Neuron creation complete (genome stats may only count innate neurons)"
1203            );
1204        }
1205
1206        self.update_stage(DevelopmentStage::Neurogenesis, 100);
1207        info!(target: "feagi-bdu","  ✅ Neurogenesis complete: {} neurons created", total_neurons_created);
1208
1209        Ok(())
1210    }
1211
1212    /// Stage 4: Synaptogenesis - Form synaptic connections between neurons
1213    ///
1214    /// This uses ConnectomeManager which delegates to NPU's morphology functions.
1215    /// Each morphology application (`apply_projector_morphology`, etc.) processes ALL neurons
1216    /// from the source area and creates ALL synapses in one SIMD-optimized batch operation.
1217    fn synaptogenesis(&mut self, genome: &RuntimeGenome) -> BduResult<()> {
1218        self.update_stage(DevelopmentStage::Synaptogenesis, 0);
1219        info!(target: "feagi-bdu","🔗 Stage 4: Synaptogenesis - Forming synaptic connections (SIMD-optimized batches)");
1220
1221        let expected_synapses = genome.stats.innate_synapse_count;
1222        info!(target: "feagi-bdu","  Expected innate synapses from genome: {}", expected_synapses);
1223
1224        self.rebuild_memory_twin_mappings()?;
1225        self.connectome_manager
1226            .write()
1227            .sync_modulators_from_genome(genome)?;
1228
1229        let mut total_synapses_created = 0;
1230        let total_areas = genome.cortical_areas.len();
1231
1232        // Process each source area via ConnectomeManager (each mapping = one SIMD batch)
1233        // NOTE: Loop is over AREAS, not synapses. Each area applies all mappings in batch calls.
1234        for (idx, (_src_cortical_id, src_area)) in genome.cortical_areas.iter().enumerate() {
1235            // Check if area has mappings
1236            let has_dstmap = src_area
1237                .properties
1238                .get("cortical_mapping_dst")
1239                .and_then(|v| v.as_object())
1240                .map(|m| !m.is_empty())
1241                .unwrap_or(false);
1242
1243            if !has_dstmap {
1244                trace!(target: "feagi-bdu", "No dstmap for area {}", &src_area.cortical_id);
1245                continue;
1246            }
1247
1248            // Call ConnectomeManager to apply cortical mappings (delegates to NPU)
1249            // CRITICAL: Minimize lock scope - only hold lock during synapse creation
1250            // Use src_area.cortical_id (the actual ID stored in ConnectomeManager)
1251            let src_cortical_id = &src_area.cortical_id;
1252            let src_cortical_id_str = src_cortical_id.to_string(); // For logging
1253            let synapses_created = {
1254                let manager_arc = self.connectome_manager.clone();
1255                let mut manager = manager_arc.write();
1256                if let Some(dstmap) = src_area.properties.get("cortical_mapping_dst") {
1257                    if let Some(area) = manager.get_cortical_area_mut(src_cortical_id) {
1258                        area.properties
1259                            .insert("cortical_mapping_dst".to_string(), dstmap.clone());
1260                    }
1261                }
1262                manager.apply_cortical_mapping(src_cortical_id)
1263            }; // Lock released immediately
1264
1265            match synapses_created {
1266                Ok(count) => {
1267                    total_synapses_created += count as usize;
1268                    trace!(
1269                        target: "feagi-bdu",
1270                        "Created {} synapses for area {}",
1271                        count,
1272                        src_cortical_id_str
1273                    );
1274                }
1275                Err(e) => {
1276                    // Synapses for destinations applied before the error already exist
1277                    // but are not reported by the failing call, so nothing is added here.
1278                    warn!(target: "feagi-bdu", "  Mappings from {} were not fully applied: {}",
1279                        src_cortical_id_str, e);
1280                }
1281            }
1282
1283            // Update progress
1284            let progress_pct = ((idx + 1) * 100 / total_areas.max(1)) as u8;
1285            self.update_progress(|p| {
1286                p.synapses_created = total_synapses_created;
1287                p.progress = progress_pct;
1288            });
1289        }
1290
1291        // CRITICAL: Rebuild the NPU synapse index so newly created synapses are visible to
1292        // queries (e.g. get_outgoing_synapses / synapse counts) and propagation.
1293        //
1294        // Note: We do this once at the end for performance.
1295        let npu_arc = {
1296            let manager = self.connectome_manager.read();
1297            manager.get_npu().cloned()
1298        };
1299        if let Some(npu_arc) = npu_arc {
1300            let mut npu_lock = npu_arc
1301                .lock()
1302                .map_err(|e| BduError::Internal(format!("Failed to lock NPU: {}", e)))?;
1303            npu_lock.rebuild_synapse_index();
1304
1305            // Refresh cached counts after index rebuild.
1306            let manager = self.connectome_manager.read();
1307            manager.update_cached_synapse_count();
1308        }
1309
1310        // CRITICAL: Register memory areas with PlasticityExecutor after all mappings are created
1311        // This ensures memory areas have their complete upstream_cortical_areas lists populated.
1312        #[cfg(feature = "plasticity")]
1313        {
1314            use feagi_evolutionary::extract_memory_properties;
1315            use feagi_npu_plasticity::PlasticityExecutor;
1316
1317            let manager = self.connectome_manager.read();
1318            if let Some(executor) = manager.get_plasticity_executor() {
1319                let mut registered_count = 0;
1320
1321                // Iterate through all cortical areas and register memory areas
1322                for area_id in manager.get_cortical_area_ids() {
1323                    if let Some(area) = manager.get_cortical_area(area_id) {
1324                        if let Some(mem_props) = extract_memory_properties(&area.properties) {
1325                            let upstream_areas =
1326                                manager.get_episodic_memory_upstream_cortical_areas(area_id);
1327
1328                            // Ensure FireLedger tracks upstream areas with at least the required temporal depth.
1329                            // Dense, burst-aligned tracking is required for correct memory pattern hashing.
1330                            if let Some(npu_arc) = manager.get_npu() {
1331                                if let Ok(mut npu) = npu_arc.lock() {
1332                                    let existing_configs = npu.get_all_fire_ledger_configs();
1333                                    for &upstream_idx in &upstream_areas {
1334                                        let existing = existing_configs
1335                                            .iter()
1336                                            .find(|(idx, _)| *idx == upstream_idx)
1337                                            .map(|(_, w)| *w)
1338                                            .unwrap_or(0);
1339
1340                                        let desired = mem_props.temporal_depth as usize;
1341                                        let resolved = existing.max(desired);
1342                                        if resolved != existing {
1343                                            if let Err(e) = npu.configure_fire_ledger_window(
1344                                                upstream_idx,
1345                                                resolved,
1346                                            ) {
1347                                                warn!(
1348                                                    target: "feagi-bdu",
1349                                                    "Failed to configure FireLedger window for upstream area idx={} (requested={}): {}",
1350                                                    upstream_idx,
1351                                                    resolved,
1352                                                    e
1353                                                );
1354                                            }
1355                                        }
1356                                    }
1357                                } else {
1358                                    warn!(target: "feagi-bdu", "Failed to lock NPU for FireLedger configuration");
1359                                }
1360                            }
1361
1362                            manager.sync_memory_associative_lif_params(area_id);
1363                            if let Ok(exec) = executor.lock() {
1364                                let lifecycle_config = crate::memory_lifecycle_config(&mem_props);
1365
1366                                let mp_mode =
1367                                    match crate::memory_mp_mode(&area.properties, &mem_props) {
1368                                        Ok(mode) => mode,
1369                                        Err(e) => {
1370                                            error!(
1371                                                target: "feagi-bdu",
1372                                                "Memory area {} not registered: {}",
1373                                                area_id.as_base_64(),
1374                                                e
1375                                            );
1376                                            continue;
1377                                        }
1378                                    };
1379                                exec.register_memory_area(
1380                                    area.cortical_idx,
1381                                    area_id.as_base_64(),
1382                                    mem_props.temporal_depth,
1383                                    upstream_areas.clone(),
1384                                    Some(lifecycle_config),
1385                                    mp_mode,
1386                                );
1387                                manager.configure_memory_scan_on_executor(&*exec, area_id);
1388
1389                                registered_count += 1;
1390                            }
1391                        }
1392                    }
1393                }
1394                let _ = registered_count; // count retained for future metrics if needed
1395            }
1396        }
1397
1398        // Mapping rules reach the manager only inside the loop above, so the eligibility of
1399        // reward-trained classifiers (derived from the circuit's answer delay) can only be
1400        // recomputed now. The earlier pass in corticogenesis finds no rules and skips.
1401        self.connectome_manager
1402            .write()
1403            .refresh_classifier_reward_eligibility();
1404
1405        // Verify against genome stats
1406        if expected_synapses > 0 {
1407            let diff = (total_synapses_created as i64 - expected_synapses as i64).abs();
1408            let diff_pct = (diff as f64 / expected_synapses.max(1) as f64) * 100.0;
1409
1410            if diff_pct > 10.0 {
1411                warn!(target: "feagi-bdu",
1412                    "Synapse count variance: created {} but genome stats expected {} ({:.1}% difference)",
1413                    total_synapses_created, expected_synapses, diff_pct
1414                );
1415            } else {
1416                info!(target: "feagi-bdu",
1417                    "Synapse count matches genome stats within {:.1}% ({} vs {})",
1418                    diff_pct, total_synapses_created, expected_synapses
1419                );
1420            }
1421        }
1422
1423        self.update_stage(DevelopmentStage::Synaptogenesis, 100);
1424        info!(target: "feagi-bdu","  ✅ Synaptogenesis complete: {} synapses created", total_synapses_created);
1425
1426        Ok(())
1427    }
1428
1429    /// Rebuild memory twins with the same job list the connectome import rebind uses
1430    /// (`ConnectomeManager::rebuild_memory_twin_mappings`), so a genome load and an import of
1431    /// its export hold the same areas. That includes creating the twin of an episodic
1432    /// upstream-to-memory pair that has no saved twin. Errors propagate under one policy.
1433    fn rebuild_memory_twin_mappings(&mut self) -> BduResult<()> {
1434        let restored = self
1435            .connectome_manager
1436            .write()
1437            .rebuild_memory_twin_mappings()?;
1438        info!(
1439            target: "feagi-bdu",
1440            "Rebuilt {} memory twin mapping(s) from genome",
1441            restored
1442        );
1443        Ok(())
1444    }
1445}
1446
1447/// Estimate synapse count for an area (fallback when NPU not connected)
1448///
1449/// This is only used when NPU is not available for actual synapse creation.
1450fn estimate_synapses_for_area(
1451    src_area: &CorticalArea,
1452    genome: &feagi_evolutionary::RuntimeGenome,
1453) -> usize {
1454    let dstmap = match src_area.properties.get("cortical_mapping_dst") {
1455        Some(serde_json::Value::Object(map)) => map,
1456        _ => return 0,
1457    };
1458
1459    let mut total = 0;
1460
1461    for (dst_id, rules) in dstmap {
1462        // Convert string dst_id to CorticalID for lookup
1463        let dst_cortical_id = match feagi_evolutionary::string_to_cortical_id(dst_id) {
1464            Ok(id) => id,
1465            Err(_) => continue,
1466        };
1467        let dst_area = match genome.cortical_areas.get(&dst_cortical_id) {
1468            Some(area) => area,
1469            None => continue,
1470        };
1471
1472        let rules_array = match rules.as_array() {
1473            Some(arr) => arr,
1474            None => continue,
1475        };
1476
1477        for rule in rules_array {
1478            let morphology_id = rule
1479                .get("morphology_id")
1480                .and_then(|v| v.as_str())
1481                .unwrap_or("unknown");
1482            let scalar = rule
1483                .get("morphology_scalar")
1484                .and_then(|v| v.as_i64())
1485                .unwrap_or(1) as usize;
1486
1487            // Simplified estimation
1488            let src_per_voxel = src_area
1489                .properties
1490                .get("neurons_per_voxel")
1491                .and_then(|v| v.as_u64())
1492                .unwrap_or(1) as usize;
1493            let dst_per_voxel = dst_area
1494                .properties
1495                .get("neurons_per_voxel")
1496                .and_then(|v| v.as_u64())
1497                .unwrap_or(1) as usize;
1498
1499            let src_voxels =
1500                src_area.dimensions.width * src_area.dimensions.height * src_area.dimensions.depth;
1501            let dst_voxels =
1502                dst_area.dimensions.width * dst_area.dimensions.height * dst_area.dimensions.depth;
1503
1504            let src_neurons = src_voxels as usize * src_per_voxel;
1505            let dst_neurons = dst_voxels as usize * dst_per_voxel as usize;
1506
1507            // Basic estimation by morphology type
1508            let count = match morphology_id {
1509                "block_to_block" => src_neurons * dst_per_voxel * scalar,
1510                "projector" | "transpose_xy" | "transpose_yz" | "transpose_xz"
1511                | "centered_projector" => src_neurons * dst_neurons * scalar,
1512                _ if morphology_id.contains("lateral") => src_neurons * scalar,
1513                _ => (src_neurons * scalar).min(src_neurons * dst_neurons / 10),
1514            };
1515
1516            total += count;
1517        }
1518    }
1519
1520    total
1521}
1522
1523impl Neuroembryogenesis {
1524    /// Calculate position for autogen region based on root region's bounding box
1525    fn calculate_autogen_region_position(
1526        root_area_ids: &[CorticalID],
1527        genome: &feagi_evolutionary::RuntimeGenome,
1528    ) -> [i32; 3] {
1529        if root_area_ids.is_empty() {
1530            return [100, 0, 0];
1531        }
1532
1533        let mut min_x = i32::MAX;
1534        let mut max_x = i32::MIN;
1535        let mut min_y = i32::MAX;
1536        let mut max_y = i32::MIN;
1537        let mut min_z = i32::MAX;
1538        let mut max_z = i32::MIN;
1539
1540        for cortical_id in root_area_ids {
1541            if let Some(area) = genome.cortical_areas.get(cortical_id) {
1542                let pos: (i32, i32, i32) = area.position.into();
1543                let dims = (
1544                    area.dimensions.width as i32,
1545                    area.dimensions.height as i32,
1546                    area.dimensions.depth as i32,
1547                );
1548
1549                min_x = min_x.min(pos.0);
1550                max_x = max_x.max(pos.0 + dims.0);
1551                min_y = min_y.min(pos.1);
1552                max_y = max_y.max(pos.1 + dims.1);
1553                min_z = min_z.min(pos.2);
1554                max_z = max_z.max(pos.2 + dims.2);
1555            }
1556        }
1557
1558        let bbox_width = (max_x - min_x).max(1);
1559        let padding = (bbox_width / 5).max(50);
1560        let autogen_x = max_x + padding;
1561        let autogen_y = (min_y + max_y) / 2;
1562        let autogen_z = (min_z + max_z) / 2;
1563
1564        info!(target: "feagi-bdu",
1565              "  📐 Autogen position: ({}, {}, {}) [padding: {}]",
1566              autogen_x, autogen_y, autogen_z, padding);
1567
1568        [autogen_x, autogen_y, autogen_z]
1569    }
1570
1571    /// Analyze region inputs/outputs based on cortical connections
1572    ///
1573    /// Following Python's _auto_assign_region_io() logic:
1574    /// - OUTPUT: Any area in the region that connects to an area OUTSIDE the region
1575    /// - INPUT: Any area in the region that receives connection from OUTSIDE the region
1576    fn analyze_region_io(
1577        region_area_ids: &[feagi_structures::genomic::cortical_area::CorticalID],
1578        all_cortical_areas: &std::collections::HashMap<CorticalID, CorticalArea>,
1579    ) -> (Vec<String>, Vec<String>) {
1580        let area_set: std::collections::HashSet<_> = region_area_ids.iter().cloned().collect();
1581        let mut inputs = Vec::new();
1582        let mut outputs = Vec::new();
1583
1584        // Helper to extract destination area IDs from cortical_mapping_dst (as strings)
1585        let extract_destinations = |area: &CorticalArea| -> Vec<String> {
1586            area.properties
1587                .get("cortical_mapping_dst")
1588                .and_then(|v| v.as_object())
1589                .map(|obj| obj.keys().cloned().collect())
1590                .unwrap_or_default()
1591        };
1592
1593        // Find OUTPUTS: areas in region that connect to areas OUTSIDE region
1594        for area_id in region_area_ids {
1595            if let Some(area) = all_cortical_areas.get(area_id) {
1596                let destinations = extract_destinations(area);
1597                // Convert destination strings to CorticalID for comparison
1598                let external_destinations: Vec<_> = destinations
1599                    .iter()
1600                    .filter_map(|dest| feagi_evolutionary::string_to_cortical_id(dest).ok())
1601                    .filter(|dest_id| !area_set.contains(dest_id))
1602                    .collect();
1603
1604                if !external_destinations.is_empty() {
1605                    outputs.push(area_id.as_base_64());
1606                }
1607            }
1608        }
1609
1610        // Find INPUTS: areas in region receiving connections from OUTSIDE region
1611        for (source_area_id, source_area) in all_cortical_areas.iter() {
1612            // Skip areas that are inside the region
1613            if area_set.contains(source_area_id) {
1614                continue;
1615            }
1616
1617            let destinations = extract_destinations(source_area);
1618            for dest_str in destinations {
1619                if let Ok(dest_id) = feagi_evolutionary::string_to_cortical_id(&dest_str) {
1620                    if area_set.contains(&dest_id) {
1621                        let dest_string = dest_id.as_base_64();
1622                        if !inputs.contains(&dest_string) {
1623                            inputs.push(dest_string);
1624                        }
1625                    }
1626                }
1627            }
1628        }
1629
1630        (inputs, outputs)
1631    }
1632
1633    /// Update development stage
1634    fn update_stage(&self, stage: DevelopmentStage, progress: u8) {
1635        let mut p = self.progress.write();
1636        p.stage = stage;
1637        p.progress = progress;
1638        p.duration_ms = self.start_time.elapsed().as_millis() as u64;
1639    }
1640
1641    /// Update progress with a closure
1642    fn update_progress<F>(&self, f: F)
1643    where
1644        F: FnOnce(&mut DevelopmentProgress),
1645    {
1646        let mut p = self.progress.write();
1647        f(&mut p);
1648        p.duration_ms = self.start_time.elapsed().as_millis() as u64;
1649    }
1650}
1651
1652#[cfg(test)]
1653mod tests {
1654    use super::*;
1655    use feagi_evolutionary::create_genome_with_core_morphologies;
1656    use feagi_structures::genomic::cortical_area::CorticalAreaDimensions;
1657
1658    #[test]
1659    fn test_neuroembryogenesis_creation() {
1660        let _state_guard = crate::connectome_manager::tests::PREPARE_FOR_NEW_GENOME_TEST_LOCK
1661            .lock()
1662            .unwrap_or_else(|e| e.into_inner());
1663        let manager = ConnectomeManager::instance();
1664        let neuro = Neuroembryogenesis::new(manager);
1665
1666        let progress = neuro.get_progress();
1667        assert_eq!(progress.stage, DevelopmentStage::Initialization);
1668        assert_eq!(progress.progress, 0);
1669    }
1670
1671    #[test]
1672    fn autogen_subregion_display_name_uses_title_when_meaningful() {
1673        assert_eq!(
1674            autogen_subregion_display_name("My Shared Circuit"),
1675            "My Shared Circuit"
1676        );
1677    }
1678
1679    #[test]
1680    fn autogen_subregion_display_name_falls_back_for_untitled() {
1681        assert_eq!(
1682            autogen_subregion_display_name("Untitled"),
1683            "Autogen Circuit"
1684        );
1685        assert_eq!(
1686            autogen_subregion_display_name("untitled"),
1687            "Autogen Circuit"
1688        );
1689    }
1690
1691    #[test]
1692    fn autogen_subregion_display_name_falls_back_for_blank() {
1693        assert_eq!(autogen_subregion_display_name(""), "Autogen Circuit");
1694        assert_eq!(autogen_subregion_display_name("   "), "Autogen Circuit");
1695    }
1696
1697    #[test]
1698    fn order_regions_puts_parent_before_grandchild_even_when_child_is_listed_first() {
1699        let root = "root".to_string();
1700        let parent = "look-for-people".to_string();
1701        let grandchild = "wave".to_string();
1702        let sibling = "look-for-ball".to_string();
1703
1704        // HashMap-unlucky listing: grandchild before its parent.
1705        let remaining = vec![grandchild.clone(), sibling.clone(), parent.clone()];
1706        let mut parent_map = std::collections::HashMap::new();
1707        parent_map.insert(parent.clone(), root.clone());
1708        parent_map.insert(grandchild.clone(), parent.clone());
1709        parent_map.insert(sibling.clone(), root);
1710
1711        let ordered = order_regions_parent_before_child(&remaining, &parent_map);
1712        let parent_idx = ordered.iter().position(|id| id == &parent).unwrap();
1713        let grandchild_idx = ordered.iter().position(|id| id == &grandchild).unwrap();
1714
1715        assert_eq!(ordered.len(), 3);
1716        assert!(
1717            parent_idx < grandchild_idx,
1718            "parent must precede grandchild, got {:?}",
1719            ordered
1720        );
1721    }
1722
1723    #[test]
1724    fn order_regions_keeps_flat_children_when_parent_is_already_inserted() {
1725        let remaining = vec!["a".to_string(), "b".to_string(), "c".to_string()];
1726        let mut parent_map = std::collections::HashMap::new();
1727        parent_map.insert("a".to_string(), "root".to_string());
1728        parent_map.insert("b".to_string(), "root".to_string());
1729        parent_map.insert("c".to_string(), "root".to_string());
1730
1731        let ordered = order_regions_parent_before_child(&remaining, &parent_map);
1732        let mut sorted = ordered.clone();
1733        sorted.sort();
1734        assert_eq!(sorted, remaining);
1735    }
1736
1737    #[test]
1738    fn order_regions_appends_cycle_members_after_acyclic_prefix() {
1739        let remaining = vec!["a".to_string(), "b".to_string(), "ok".to_string()];
1740        let mut parent_map = std::collections::HashMap::new();
1741        parent_map.insert("a".to_string(), "b".to_string());
1742        parent_map.insert("b".to_string(), "a".to_string());
1743        parent_map.insert("ok".to_string(), "root".to_string());
1744
1745        let ordered = order_regions_parent_before_child(&remaining, &parent_map);
1746        assert_eq!(ordered.first().map(String::as_str), Some("ok"));
1747        assert_eq!(ordered.len(), 3);
1748        assert!(ordered.contains(&"a".to_string()));
1749        assert!(ordered.contains(&"b".to_string()));
1750    }
1751
1752    #[test]
1753    fn test_development_from_minimal_genome() {
1754        let _state_guard = crate::connectome_manager::tests::PREPARE_FOR_NEW_GENOME_TEST_LOCK
1755            .lock()
1756            .unwrap_or_else(|e| e.into_inner());
1757        ConnectomeManager::reset_for_testing(); // Ensure clean state
1758        let manager = ConnectomeManager::instance();
1759        {
1760            let runtime = feagi_npu_runtime::StdRuntime;
1761            let backend = feagi_npu_burst_engine::backend::CPUBackend::new();
1762            let npu_result =
1763                feagi_npu_burst_engine::RustNPU::new(runtime, backend, 1_000_000, 10_000_000, 10)
1764                    .expect("Failed to create NPU");
1765            let npu = std::sync::Arc::new(feagi_npu_burst_engine::TracingMutex::new(
1766                feagi_npu_burst_engine::DynamicNPU::F32(npu_result),
1767                "minimal-genome-test-npu",
1768            ));
1769            manager.write().set_npu(npu);
1770        }
1771        let mut neuro = Neuroembryogenesis::new(manager.clone());
1772
1773        // Create a minimal genome with one cortical area
1774        let mut genome = create_genome_with_core_morphologies(
1775            "test_genome".to_string(),
1776            "Test Genome".to_string(),
1777        );
1778
1779        let cortical_id = CorticalID::try_from_bytes(b"cst_neur").unwrap(); // Use valid custom cortical ID
1780        let cortical_type = cortical_id
1781            .as_cortical_type()
1782            .expect("Failed to get cortical type");
1783        let area = CorticalArea::new(
1784            cortical_id,
1785            0,
1786            "Test Area".to_string(),
1787            CorticalAreaDimensions::new(10, 10, 10).unwrap(),
1788            (0, 0, 0).into(),
1789            cortical_type,
1790        )
1791        .expect("Failed to create cortical area");
1792        genome.cortical_areas.insert(cortical_id, area);
1793
1794        // Run neuroembryogenesis
1795        let result = neuro.develop_from_genome(&genome);
1796        assert!(result.is_ok(), "Development failed: {:?}", result);
1797
1798        // Check progress
1799        let progress = neuro.get_progress();
1800        assert_eq!(progress.stage, DevelopmentStage::Completed);
1801        assert_eq!(progress.progress, 100);
1802        assert_eq!(progress.cortical_areas_created, 1);
1803
1804        // Do not assert on ConnectomeManager::instance() contents here: other tests run in parallel
1805        // and share the same singleton; the progress fields above already reflect this run's outcome.
1806
1807        println!("✅ Development completed in {}ms", progress.duration_ms);
1808    }
1809
1810    /// Core area `n` must own neuron `n` on every load, however the genome map iterates.
1811    #[test]
1812    fn core_neuron_ids_equal_area_index_on_every_load() {
1813        let _state_guard = crate::connectome_manager::tests::PREPARE_FOR_NEW_GENOME_TEST_LOCK
1814            .lock()
1815            .unwrap_or_else(|e| e.into_inner());
1816        use feagi_structures::genomic::cortical_area::{
1817            CoreCorticalType, CorticalAreaType, CustomCorticalType,
1818        };
1819
1820        let core = [
1821            CoreCorticalType::Death,
1822            CoreCorticalType::Power,
1823            CoreCorticalType::Fatigue,
1824            CoreCorticalType::Pain,
1825            CoreCorticalType::Pleasure,
1826            CoreCorticalType::Fear,
1827            CoreCorticalType::Hope,
1828        ];
1829        for load in 0..12 {
1830            let runtime = feagi_npu_runtime::StdRuntime;
1831            let backend = feagi_npu_burst_engine::backend::CPUBackend::new();
1832            let npu = feagi_npu_burst_engine::RustNPU::new(runtime, backend, 100_000, 100_000, 10)
1833                .expect("Failed to create NPU");
1834            let npu = std::sync::Arc::new(feagi_npu_burst_engine::TracingMutex::new(
1835                feagi_npu_burst_engine::DynamicNPU::F32(npu),
1836                "core-order-test-npu",
1837            ));
1838            let manager = Arc::new(RwLock::new(ConnectomeManager::new_for_testing_with_npu(
1839                npu.clone(),
1840            )));
1841            let mut neuro = Neuroembryogenesis::new(manager.clone());
1842            let mut genome = create_genome_with_core_morphologies(
1843                "core_order".to_string(),
1844                "Core Order".to_string(),
1845            );
1846            for kind in core {
1847                let id = kind.to_cortical_id();
1848                let area = CorticalArea::new(
1849                    id,
1850                    0,
1851                    format!("core-{id}"),
1852                    CorticalAreaDimensions::new(1, 1, 1).unwrap(),
1853                    (0, 0, 0).into(),
1854                    CorticalAreaType::Core(kind),
1855                )
1856                .unwrap();
1857                genome.cortical_areas.insert(id, area);
1858            }
1859            for n in 0..24u8 {
1860                let id = CorticalID::try_from_bytes(&[
1861                    b'c',
1862                    b'o',
1863                    b'r',
1864                    b'd',
1865                    b'0',
1866                    b'0',
1867                    b'0' + n / 10,
1868                    b'0' + n % 10,
1869                ])
1870                .unwrap();
1871                let area = CorticalArea::new(
1872                    id,
1873                    0,
1874                    format!("other-{n}"),
1875                    CorticalAreaDimensions::new(1, 1, 1).unwrap(),
1876                    (n as i32, 0, 0).into(),
1877                    CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire),
1878                )
1879                .unwrap();
1880                genome.cortical_areas.insert(id, area);
1881            }
1882            neuro
1883                .develop_from_genome(&genome)
1884                .expect("development must succeed");
1885
1886            let npu = npu.lock().unwrap();
1887            for index in 0..7u32 {
1888                assert_eq!(
1889                    npu.get_neurons_in_cortical_area(index),
1890                    vec![index],
1891                    "load {load}: core area {index} must own neuron {index}"
1892                );
1893            }
1894        }
1895    }
1896
1897    /// Other areas get the same indices on every load.
1898    #[test]
1899    fn registration_order_is_deterministic() {
1900        use feagi_structures::genomic::cortical_area::{CorticalAreaType, CustomCorticalType};
1901
1902        let mut genome = create_genome_with_core_morphologies("o".to_string(), "o".to_string());
1903        for n in 0..16u8 {
1904            let id = CorticalID::try_from_bytes(&[
1905                b'o',
1906                b'r',
1907                b'd',
1908                b'0',
1909                b'0',
1910                b'0',
1911                b'0' + n / 10,
1912                b'0' + n % 10,
1913            ])
1914            .unwrap();
1915            let area = CorticalArea::new(
1916                id,
1917                0,
1918                format!("a{n}"),
1919                CorticalAreaDimensions::new(1, 1, 1).unwrap(),
1920                (0, 0, 0).into(),
1921                CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire),
1922            )
1923            .unwrap();
1924            genome.cortical_areas.insert(id, area);
1925        }
1926        let expected: Vec<String> = ordered_genome_areas(&genome)
1927            .iter()
1928            .map(|(id, _)| id.as_base_64())
1929            .collect();
1930        let mut sorted = expected.clone();
1931        sorted.sort();
1932        assert_eq!(expected, sorted, "unindexed areas register by id");
1933    }
1934
1935    /// Loading a genome creates the twin of an episodic upstream-to-memory pair that has no
1936    /// saved twin, so the rebind after an import of its export has nothing left to add.
1937    #[test]
1938    fn genome_load_creates_missing_twins_like_the_import_rebind() {
1939        let _state_guard = crate::connectome_manager::tests::PREPARE_FOR_NEW_GENOME_TEST_LOCK
1940            .lock()
1941            .unwrap_or_else(|e| e.into_inner());
1942        use feagi_structures::genomic::cortical_area::{
1943            CorticalAreaType, CustomCorticalType, MemoryCorticalType,
1944        };
1945
1946        let runtime = feagi_npu_runtime::StdRuntime;
1947        let backend = feagi_npu_burst_engine::backend::CPUBackend::new();
1948        let npu = feagi_npu_burst_engine::RustNPU::new(runtime, backend, 100_000, 100_000, 10)
1949            .expect("Failed to create NPU");
1950        let npu = std::sync::Arc::new(feagi_npu_burst_engine::TracingMutex::new(
1951            feagi_npu_burst_engine::DynamicNPU::F32(npu),
1952            "twin-load-test-npu",
1953        ));
1954        let manager = Arc::new(RwLock::new(ConnectomeManager::new_for_testing_with_npu(
1955            npu,
1956        )));
1957        let mut neuro = Neuroembryogenesis::new(manager.clone());
1958        let mut genome =
1959            create_genome_with_core_morphologies("twin_load".to_string(), "Twin Load".to_string());
1960        let upstream_id = CorticalID::try_from_bytes(b"cupa0021").unwrap();
1961        let memory_id = CorticalID::try_from_bytes(b"mmem0021").unwrap();
1962        let mut upstream = CorticalArea::new(
1963            upstream_id,
1964            0,
1965            "upstream".to_string(),
1966            CorticalAreaDimensions::new(1, 1, 1).unwrap(),
1967            (0, 0, 0).into(),
1968            CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire),
1969        )
1970        .unwrap();
1971        upstream.properties.insert(
1972            "cortical_mapping_dst".to_string(),
1973            serde_json::json!({ memory_id.as_base_64(): [{ "morphology_id": "episodic_memory" }] }),
1974        );
1975        let mut memory = CorticalArea::new(
1976            memory_id,
1977            0,
1978            "memory".to_string(),
1979            CorticalAreaDimensions::new(1, 1, 1).unwrap(),
1980            (1, 0, 0).into(),
1981            CorticalAreaType::Memory(MemoryCorticalType::Memory),
1982        )
1983        .unwrap();
1984        memory
1985            .properties
1986            .insert("is_mem_type".to_string(), serde_json::json!(true));
1987        genome.cortical_areas.insert(upstream_id, upstream);
1988        genome.cortical_areas.insert(memory_id, memory);
1989
1990        neuro
1991            .develop_from_genome(&genome)
1992            .expect("development must succeed");
1993
1994        let area_count = || manager.read().get_cortical_area_ids().len();
1995        let after_load = area_count();
1996        let twin_id = {
1997            let guard = manager.read();
1998            guard
1999                .get_cortical_area(&memory_id)
2000                .and_then(|area| area.properties.get("memory_twin_areas"))
2001                .and_then(|value| value.get(upstream_id.as_base_64()))
2002                .and_then(|value| value.as_str())
2003                .and_then(|twin| CorticalID::try_from_base_64(twin).ok())
2004                .expect("load must index the twin it created")
2005        };
2006        assert!(manager.read().has_cortical_area(&twin_id));
2007        manager
2008            .write()
2009            .rebuild_memory_twin_mappings()
2010            .expect("the import rebind must succeed");
2011        assert_eq!(
2012            area_count(),
2013            after_load,
2014            "the rebind adds no area after a load"
2015        );
2016    }
2017
2018    /// Loads a genome whose explicit root region holds the given stray placement, then
2019    /// returns the manager and the ids (upstream, memory).
2020    fn develop_genome_with_strays(
2021        place_in_root: bool,
2022        place_in_circuit: bool,
2023    ) -> (Arc<RwLock<ConnectomeManager>>, CorticalID, CorticalID) {
2024        use feagi_structures::genomic::brain_regions::{BrainRegion, RegionID, RegionType};
2025        use feagi_structures::genomic::cortical_area::{
2026            CorticalAreaType, CustomCorticalType, MemoryCorticalType,
2027        };
2028        let runtime = feagi_npu_runtime::StdRuntime;
2029        let backend = feagi_npu_burst_engine::backend::CPUBackend::new();
2030        let npu = feagi_npu_burst_engine::RustNPU::new(runtime, backend, 100_000, 100_000, 10)
2031            .expect("Failed to create NPU");
2032        let npu = std::sync::Arc::new(feagi_npu_burst_engine::TracingMutex::new(
2033            feagi_npu_burst_engine::DynamicNPU::F32(npu),
2034            "stray-load-test-npu",
2035        ));
2036        let manager = Arc::new(RwLock::new(ConnectomeManager::new_for_testing_with_npu(
2037            npu,
2038        )));
2039        let mut neuro = Neuroembryogenesis::new(manager.clone());
2040        let mut genome =
2041            create_genome_with_core_morphologies("stray_load".to_string(), "Stray".to_string());
2042        let upstream_id = CorticalID::try_from_bytes(b"cupa0031").unwrap();
2043        let memory_id = CorticalID::try_from_bytes(b"mmem0031").unwrap();
2044        let mut upstream = CorticalArea::new(
2045            upstream_id,
2046            0,
2047            "upstream".to_string(),
2048            CorticalAreaDimensions::new(1, 1, 1).unwrap(),
2049            (0, 0, 0).into(),
2050            CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire),
2051        )
2052        .unwrap();
2053        upstream.properties.insert(
2054            "cortical_mapping_dst".to_string(),
2055            serde_json::json!({ memory_id.as_base_64(): [{ "morphology_id": "episodic_memory" }] }),
2056        );
2057        let mut memory = CorticalArea::new(
2058            memory_id,
2059            0,
2060            "memory".to_string(),
2061            CorticalAreaDimensions::new(1, 1, 1).unwrap(),
2062            (1, 0, 0).into(),
2063            CorticalAreaType::Memory(MemoryCorticalType::Memory),
2064        )
2065        .unwrap();
2066        memory
2067            .properties
2068            .insert("is_mem_type".to_string(), serde_json::json!(true));
2069        genome.cortical_areas.insert(upstream_id, upstream);
2070        genome.cortical_areas.insert(memory_id, memory);
2071
2072        let mut root = BrainRegion::new(
2073            RegionID::new(),
2074            ROOT_BRAIN_REGION_NAME.to_string(),
2075            RegionType::Undefined,
2076        )
2077        .unwrap();
2078        if place_in_root {
2079            root = root.with_areas([upstream_id, memory_id]);
2080        }
2081        let root_key = root.region_id.to_string();
2082        genome.brain_regions.insert(root_key.clone(), root);
2083        if place_in_circuit {
2084            let mut circuit = BrainRegion::new(
2085                RegionID::new(),
2086                "circuit".to_string(),
2087                RegionType::Undefined,
2088            )
2089            .unwrap()
2090            .with_areas([upstream_id, memory_id]);
2091            circuit.add_property("parent_region_id".to_string(), serde_json::json!(root_key));
2092            genome
2093                .brain_regions
2094                .insert(circuit.region_id.to_string(), circuit);
2095        }
2096        neuro
2097            .develop_from_genome(&genome)
2098            .expect("load must repair strays instead of failing");
2099        (manager, upstream_id, memory_id)
2100    }
2101
2102    fn recovered_region_ids(manager: &Arc<RwLock<ConnectomeManager>>) -> Vec<String> {
2103        let guard = manager.read();
2104        guard
2105            .get_brain_region_ids()
2106            .into_iter()
2107            .filter(|id| {
2108                guard.get_brain_region(id).is_some_and(|r| {
2109                    r.name == crate::connectome_manager::RECOVERED_AREAS_REGION_NAME
2110                })
2111            })
2112            .cloned()
2113            .collect()
2114    }
2115
2116    fn assert_stray_load_repaired(
2117        manager: &Arc<RwLock<ConnectomeManager>>,
2118        upstream_id: CorticalID,
2119        memory_id: CorticalID,
2120    ) {
2121        let recovered = recovered_region_ids(manager);
2122        assert_eq!(recovered.len(), 1);
2123        let guard = manager.read();
2124        let root_id = guard.get_root_region_id().unwrap();
2125        let region = guard.get_brain_region(&recovered[0]).unwrap();
2126        assert!(region.contains_area(&upstream_id) && region.contains_area(&memory_id));
2127        let root = guard.get_brain_region(&root_id).unwrap();
2128        assert!(!root.contains_area(&upstream_id) && !root.contains_area(&memory_id));
2129        let twin_id = guard
2130            .get_cortical_area(&memory_id)
2131            .and_then(|area| area.properties.get("memory_twin_areas"))
2132            .and_then(|value| value.get(upstream_id.as_base_64()))
2133            .and_then(|value| value.as_str())
2134            .and_then(|twin| CorticalID::try_from_base_64(twin).ok())
2135            .expect("twin must be created");
2136        let twin_region = guard.get_parent_region_id_for_area(&twin_id).unwrap();
2137        assert_ne!(twin_region, root_id, "twin must not sit in root");
2138    }
2139
2140    #[test]
2141    fn genome_load_moves_custom_and_memory_areas_out_of_root() {
2142        let _state_guard = crate::connectome_manager::tests::PREPARE_FOR_NEW_GENOME_TEST_LOCK
2143            .lock()
2144            .unwrap_or_else(|e| e.into_inner());
2145        let (manager, up, mem) = develop_genome_with_strays(true, false);
2146        assert_stray_load_repaired(&manager, up, mem);
2147    }
2148
2149    #[test]
2150    fn genome_load_places_custom_and_memory_areas_without_a_region() {
2151        let _state_guard = crate::connectome_manager::tests::PREPARE_FOR_NEW_GENOME_TEST_LOCK
2152            .lock()
2153            .unwrap_or_else(|e| e.into_inner());
2154        let (manager, up, mem) = develop_genome_with_strays(false, false);
2155        assert_stray_load_repaired(&manager, up, mem);
2156    }
2157
2158    #[test]
2159    fn genome_load_of_clean_regions_creates_no_recovered_areas_region() {
2160        let _state_guard = crate::connectome_manager::tests::PREPARE_FOR_NEW_GENOME_TEST_LOCK
2161            .lock()
2162            .unwrap_or_else(|e| e.into_inner());
2163        let (manager, _, _) = develop_genome_with_strays(false, true);
2164        assert!(recovered_region_ids(&manager).is_empty());
2165    }
2166
2167    /// A genome with a saved memory twin must register the twin's replay route with the NPU on
2168    /// load, without adding or regenerating anything: replay to twins is off without the route.
2169    #[test]
2170    fn genome_load_registers_saved_twin_route_with_npu() {
2171        let _state_guard = crate::connectome_manager::tests::PREPARE_FOR_NEW_GENOME_TEST_LOCK
2172            .lock()
2173            .unwrap_or_else(|e| e.into_inner());
2174        use feagi_structures::genomic::cortical_area::{
2175            CorticalAreaType, CustomCorticalType, MemoryCorticalType,
2176        };
2177
2178        let runtime = feagi_npu_runtime::StdRuntime;
2179        let backend = feagi_npu_burst_engine::backend::CPUBackend::new();
2180        let npu = feagi_npu_burst_engine::RustNPU::new(runtime, backend, 100_000, 100_000, 10)
2181            .expect("Failed to create NPU");
2182        let npu = std::sync::Arc::new(feagi_npu_burst_engine::TracingMutex::new(
2183            feagi_npu_burst_engine::DynamicNPU::F32(npu),
2184            "saved-twin-load-test-npu",
2185        ));
2186        let manager = Arc::new(RwLock::new(ConnectomeManager::new_for_testing_with_npu(
2187            npu.clone(),
2188        )));
2189        let mut neuro = Neuroembryogenesis::new(manager.clone());
2190        let mut genome = create_genome_with_core_morphologies(
2191            "saved_twin".to_string(),
2192            "Saved Twin".to_string(),
2193        );
2194        let upstream_id = CorticalID::try_from_bytes(b"cupa0031").unwrap();
2195        let memory_id = CorticalID::try_from_bytes(b"mmem0031").unwrap();
2196        // Not the hash-derived twin id, as in a genome saved by an older build.
2197        let twin_id = CorticalID::try_from_bytes(b"ctwin031").unwrap();
2198        let lif = |id: CorticalID, name: &str| {
2199            CorticalArea::new(
2200                id,
2201                0,
2202                name.to_string(),
2203                CorticalAreaDimensions::new(1, 1, 1).unwrap(),
2204                (0, 0, 0).into(),
2205                CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire),
2206            )
2207            .unwrap()
2208        };
2209        let mut upstream = lif(upstream_id, "upstream");
2210        upstream.properties.insert(
2211            "cortical_mapping_dst".to_string(),
2212            serde_json::json!({ memory_id.as_base_64(): [{ "morphology_id": "episodic_memory" }] }),
2213        );
2214        let mut memory = CorticalArea::new(
2215            memory_id,
2216            0,
2217            "memory".to_string(),
2218            CorticalAreaDimensions::new(1, 1, 1).unwrap(),
2219            (1, 0, 0).into(),
2220            CorticalAreaType::Memory(MemoryCorticalType::Memory),
2221        )
2222        .unwrap();
2223        memory
2224            .properties
2225            .insert("is_mem_type".to_string(), serde_json::json!(true));
2226        memory.properties.insert(
2227            "cortical_mapping_dst".to_string(),
2228            serde_json::json!({ twin_id.as_base_64(): [{ "morphology_id": "episodic_memory" }] }),
2229        );
2230        let mut twin = lif(twin_id, "upstream_twin");
2231        twin.properties.insert(
2232            "memory_twin_of".to_string(),
2233            serde_json::json!(upstream_id.as_base_64()),
2234        );
2235        genome.cortical_areas.insert(upstream_id, upstream);
2236        genome.cortical_areas.insert(memory_id, memory);
2237        genome.cortical_areas.insert(twin_id, twin);
2238
2239        neuro
2240            .develop_from_genome(&genome)
2241            .expect("development must succeed");
2242
2243        let (mem_idx, up_idx, twin_idx, area_count) = {
2244            let guard = manager.read();
2245            assert!(guard.has_cortical_area(&twin_id), "the saved twin is kept");
2246            (
2247                guard.get_cortical_idx(&memory_id).unwrap(),
2248                guard.get_cortical_idx(&upstream_id).unwrap(),
2249                guard.get_cortical_idx(&twin_id).unwrap(),
2250                guard.get_cortical_area_ids().len(),
2251            )
2252        };
2253        let route = npu
2254            .lock()
2255            .unwrap()
2256            .get_memory_twin_mapping(mem_idx, up_idx)
2257            .map(|(idx, _)| idx);
2258        assert_eq!(
2259            route,
2260            Some(twin_idx),
2261            "load must register the saved twin route"
2262        );
2263        assert_eq!(
2264            area_count, 3,
2265            "the saved twin is reused, no second twin is created"
2266        );
2267    }
2268
2269    /// Genome load must refresh a reward-trained classifier's stored eligibility: the mapping
2270    /// rules only exist once synaptogenesis has run.
2271    #[test]
2272    fn genome_load_refreshes_classifier_reward_eligibility() {
2273        let _state_guard = crate::connectome_manager::tests::PREPARE_FOR_NEW_GENOME_TEST_LOCK
2274            .lock()
2275            .unwrap_or_else(|e| e.into_inner());
2276        use feagi_structures::genomic::classifiers::Classifier;
2277        use feagi_structures::genomic::cortical_area::{CorticalAreaType, MemoryCorticalType};
2278
2279        let runtime = feagi_npu_runtime::StdRuntime;
2280        let backend = feagi_npu_burst_engine::backend::CPUBackend::new();
2281        let npu = feagi_npu_burst_engine::RustNPU::new(runtime, backend, 100_000, 100_000, 10)
2282            .expect("Failed to create NPU");
2283        let npu = std::sync::Arc::new(feagi_npu_burst_engine::TracingMutex::new(
2284            feagi_npu_burst_engine::DynamicNPU::F32(npu),
2285            "eligibility-load-test-npu",
2286        ));
2287        let manager = Arc::new(RwLock::new(ConnectomeManager::new_for_testing_with_npu(
2288            npu.clone(),
2289        )));
2290        let mut neuro = Neuroembryogenesis::new(manager.clone());
2291
2292        let mut genome = create_genome_with_core_morphologies(
2293            "elig_genome".to_string(),
2294            "Elig Genome".to_string(),
2295        );
2296        let memory_area = |bytes: &[u8; 8], name: &str| {
2297            let mut area = CorticalArea::new(
2298                CorticalID::try_from_bytes(bytes).unwrap(),
2299                0,
2300                name.to_string(),
2301                CorticalAreaDimensions::new(1, 1, 1).unwrap(),
2302                (0, 0, 0).into(),
2303                CorticalAreaType::Memory(MemoryCorticalType::Memory),
2304            )
2305            .unwrap();
2306            area.properties
2307                .insert("is_mem_type".to_string(), serde_json::json!(true));
2308            area
2309        };
2310        let mut sample = memory_area(b"melgsmp1", "sample");
2311        let class_mem = memory_area(b"melgcls1", "class");
2312        let (sample_id, class_id) = (sample.cortical_id, class_mem.cortical_id);
2313        sample.properties.insert(
2314            "cortical_mapping_dst".to_string(),
2315            serde_json::json!({ class_id.as_base_64(): [{
2316                "morphology_id": "associative_memory",
2317                "plasticity_flag": true,
2318                "plasticity_mode": "rstdp",
2319                "modulators": [],
2320                "eligibility_decay_bursts": 4,
2321                "plasticity_constant": 1,
2322                "ltp_multiplier": 1,
2323                "ltd_multiplier": 1,
2324                "plasticity_window": 4
2325            }]}),
2326        );
2327        genome.cortical_areas.insert(sample_id, sample);
2328        genome.cortical_areas.insert(class_id, class_mem);
2329        genome.classifiers.insert(
2330            "clf-elig".to_string(),
2331            Classifier {
2332                classifier_id: "clf-elig".to_string(),
2333                name: "elig".to_string(),
2334                parent_region_id: "root".to_string(),
2335                coordinates_3d: [0, 0, 0],
2336                sample_area_ids: Vec::new(),
2337                class_bindings: Vec::new(),
2338                sample_memory_id: sample_id.as_base_64(),
2339                class_memory_id: class_id.as_base_64(),
2340                error_area_id: "err".to_string(),
2341                reward_training: true,
2342                answer_feedback_area_id: None,
2343                correct_area_id: String::new(),
2344                reward_modulator_ids: Vec::new(),
2345                answer_latency_bursts: 0,
2346                learn_area_id: None,
2347                confidence_area_id: None,
2348                properties: std::collections::HashMap::new(),
2349            },
2350        );
2351
2352        neuro.develop_from_genome(&genome).expect("load failed");
2353
2354        let guard = manager.read();
2355        let stored = guard.get_mapping_rules(&sample_id, &class_id).unwrap()[0]
2356            ["eligibility_decay_bursts"]
2357            .as_u64()
2358            .unwrap();
2359        // Default circuit answer delay 3 gives eligibility 5.
2360        assert_eq!(stored, 5, "stored rule must follow the circuit on load");
2361        let params = npu.lock().unwrap().stdp_mapping_params(
2362            guard.get_cortical_area(&sample_id).unwrap().cortical_idx,
2363            guard.get_cortical_area(&class_id).unwrap().cortical_idx,
2364        );
2365        if let Some(params) = params {
2366            assert_eq!(params.eligibility_decay_bursts, 5);
2367        }
2368    }
2369}