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
187impl Neuroembryogenesis {
188    /// Create a new neuroembryogenesis instance
189    pub fn new(connectome_manager: Arc<RwLock<ConnectomeManager>>) -> Self {
190        Self {
191            connectome_manager,
192            progress: Arc::new(RwLock::new(DevelopmentProgress::default())),
193            start_time: std::time::Instant::now(),
194        }
195    }
196
197    /// Get current development progress
198    pub fn get_progress(&self) -> DevelopmentProgress {
199        self.progress.read().clone()
200    }
201
202    /// Sync existing core neuron parameters with cortical area properties.
203    ///
204    /// This updates neuron parameters in-place without creating new neurons.
205    fn sync_core_neuron_params(&self, cortical_idx: u32, area: &CorticalArea) -> BduResult<()> {
206        use crate::models::CorticalAreaExt;
207
208        let npu_arc = {
209            let manager = self.connectome_manager.read();
210            manager
211                .get_npu()
212                .cloned()
213                .ok_or_else(|| BduError::Internal("NPU not connected".to_string()))?
214        };
215
216        let mut npu_lock = npu_arc
217            .lock()
218            .map_err(|e| BduError::Internal(format!("Failed to lock NPU: {}", e)))?;
219
220        npu_lock.update_cortical_area_threshold_with_gradient(
221            cortical_idx,
222            area.firing_threshold(),
223            area.firing_threshold_increment_x(),
224            area.firing_threshold_increment_y(),
225            area.firing_threshold_increment_z(),
226        );
227        npu_lock.update_cortical_area_threshold_limit(cortical_idx, area.firing_threshold_limit());
228        npu_lock.update_cortical_area_leak(cortical_idx, area.leak_coefficient());
229        npu_lock.update_cortical_area_excitability(cortical_idx, area.neuron_excitability());
230        npu_lock.update_cortical_area_refractory_period(cortical_idx, area.refractory_period());
231        npu_lock.update_cortical_area_consecutive_fire_limit(
232            cortical_idx,
233            area.consecutive_fire_count() as u16,
234        );
235        npu_lock.update_cortical_area_snooze_period(cortical_idx, area.snooze_period());
236        npu_lock.update_cortical_area_mp_charge_accumulation(
237            cortical_idx,
238            area.mp_charge_accumulation(),
239        );
240
241        Ok(())
242    }
243
244    /// Incrementally add cortical areas to an existing connectome
245    ///
246    /// This is for adding new cortical areas after the initial genome has been loaded.
247    /// Unlike `develop_from_genome()`, this only processes the new areas.
248    ///
249    /// # Arguments
250    /// * `areas` - The cortical areas to add
251    /// * `genome` - The full runtime genome (needed for synaptogenesis context)
252    ///
253    /// # Returns
254    /// * Number of neurons created and synapses created
255    pub fn add_cortical_areas(
256        &mut self,
257        areas: Vec<CorticalArea>,
258        genome: &RuntimeGenome,
259    ) -> BduResult<(usize, usize)> {
260        info!(target: "feagi-bdu", "🧬 Incrementally adding {} cortical areas", areas.len());
261
262        let mut total_neurons = 0;
263        let mut total_synapses = 0;
264
265        // Stage 1: Add cortical area structures (Corticogenesis)
266        for area in &areas {
267            let mut manager = self.connectome_manager.write();
268            manager.add_cortical_area(area.clone())?;
269            info!(target: "feagi-bdu", "  ✓ Added cortical area structure: {}", area.cortical_id.as_base_64());
270        }
271
272        // Stage 2: Create neurons for each area (Neurogenesis)
273        // CRITICAL: Create core area neurons FIRST to ensure deterministic IDs
274        use feagi_structures::genomic::cortical_area::CoreCorticalType;
275        let death_id = CoreCorticalType::Death.to_cortical_id();
276        let power_id = CoreCorticalType::Power.to_cortical_id();
277        let fatigue_id = CoreCorticalType::Fatigue.to_cortical_id();
278        let pain_id = CoreCorticalType::Pain.to_cortical_id();
279        let pleasure_id = CoreCorticalType::Pleasure.to_cortical_id();
280        let fear_id = CoreCorticalType::Fear.to_cortical_id();
281        let hope_id = CoreCorticalType::Hope.to_cortical_id();
282
283        let mut core_areas = Vec::new();
284        let mut other_areas = Vec::new();
285
286        // Separate core areas from other areas
287        for area in &areas {
288            if area.cortical_id == death_id {
289                core_areas.push((0, area)); // Area 0 = _death
290            } else if area.cortical_id == power_id {
291                core_areas.push((1, area)); // Area 1 = _power
292            } else if area.cortical_id == fatigue_id {
293                core_areas.push((2, area)); // Area 2 = _fatigue
294            } else if area.cortical_id == pain_id {
295                core_areas.push((3, area)); // Area 3 = _pain
296            } else if area.cortical_id == pleasure_id {
297                core_areas.push((4, area)); // Area 4 = _pleasure
298            } else if area.cortical_id == fear_id {
299                core_areas.push((5, area)); // Area 5 = _fear
300            } else if area.cortical_id == hope_id {
301                core_areas.push((6, area)); // Area 6 = _hope
302            } else {
303                other_areas.push(area);
304            }
305        }
306
307        // Sort core areas by their deterministic index (0..=6)
308        core_areas.sort_by_key(|(idx, _)| *idx);
309
310        // STEP 1: Create core area neurons FIRST
311        if !core_areas.is_empty() {
312            info!(target: "feagi-bdu", "  🎯 Creating core area neurons FIRST ({} areas) for deterministic IDs", core_areas.len());
313            for (core_idx, area) in &core_areas {
314                let existing_core_neurons = {
315                    let manager = self.connectome_manager.read();
316                    let npu = manager.get_npu();
317                    match npu {
318                        Some(npu_arc) => {
319                            let npu_lock = npu_arc.lock();
320                            match npu_lock {
321                                Ok(npu_guard) => {
322                                    npu_guard.get_neurons_in_cortical_area(*core_idx).len()
323                                }
324                                Err(_) => 0,
325                            }
326                        }
327                        None => 0,
328                    }
329                };
330
331                if existing_core_neurons > 0 {
332                    self.sync_core_neuron_params(*core_idx, area)?;
333                    let refreshed = {
334                        let manager = self.connectome_manager.read();
335                        manager.refresh_neuron_count_for_area(&area.cortical_id)
336                    };
337                    let count = refreshed.unwrap_or(existing_core_neurons);
338                    total_neurons += count;
339                    info!(
340                        target: "feagi-bdu",
341                        "  ↪ Skipping core neuron creation for {} (existing={}, idx={})",
342                        area.cortical_id.as_base_64(),
343                        count,
344                        core_idx
345                    );
346                    continue;
347                }
348                let neurons_created = {
349                    let mut manager = self.connectome_manager.write();
350                    manager.create_neurons_for_area(&area.cortical_id)
351                };
352
353                match neurons_created {
354                    Ok(count) => {
355                        total_neurons += count as usize;
356                        info!(target: "feagi-bdu", "  ✅ Created {} neurons for core area {} (deterministic ID: neuron {})",
357                            count, area.cortical_id.as_base_64(), core_idx);
358                    }
359                    Err(e) => {
360                        error!(target: "feagi-bdu", "  ❌ FATAL: Failed to create neurons for core area {}: {}", area.cortical_id.as_base_64(), e);
361                        return Err(e);
362                    }
363                }
364            }
365        }
366
367        // STEP 2: Create neurons for other areas
368        for area in &other_areas {
369            let neurons_created = {
370                let mut manager = self.connectome_manager.write();
371                manager.create_neurons_for_area(&area.cortical_id)
372            };
373
374            match neurons_created {
375                Ok(count) => {
376                    total_neurons += count as usize;
377                    trace!(
378                        target: "feagi-bdu",
379                        "Created {} neurons for area {}",
380                        count,
381                        area.cortical_id.as_base_64()
382                    );
383                }
384                Err(e) => {
385                    error!(target: "feagi-bdu", "  ❌ FATAL: Failed to create neurons for {}: {}", area.cortical_id.as_base_64(), e);
386                    // CRITICAL: NPU capacity errors must propagate to UI
387                    return Err(e);
388                }
389            }
390        }
391
392        // Stage 3: Create synapses for each area (Synaptogenesis)
393        for area in &areas {
394            // Check if area has mappings
395            let has_dstmap = area
396                .properties
397                .get("cortical_mapping_dst")
398                .and_then(|v| v.as_object())
399                .map(|m| !m.is_empty())
400                .unwrap_or(false);
401
402            if !has_dstmap {
403                debug!(target: "feagi-bdu", "  No mappings for area {}", area.cortical_id.as_base_64());
404                continue;
405            }
406
407            let synapses_created = {
408                let mut manager = self.connectome_manager.write();
409                manager.apply_cortical_mapping(&area.cortical_id)
410            };
411
412            match synapses_created {
413                Ok(count) => {
414                    total_synapses += count as usize;
415                    trace!(
416                        target: "feagi-bdu",
417                        "Created {} synapses for area {}",
418                        count,
419                        area.cortical_id
420                    );
421                }
422                Err(e) => {
423                    warn!(target: "feagi-bdu", "  ⚠️ Failed to create synapses for {}: {}", area.cortical_id, e);
424                    let estimated = estimate_synapses_for_area(area, genome);
425                    total_synapses += estimated;
426                }
427            }
428        }
429
430        info!(target: "feagi-bdu", "✅ Incremental add complete: {} areas, {} neurons, {} synapses",
431              areas.len(), total_neurons, total_synapses);
432
433        Ok((total_neurons, total_synapses))
434    }
435
436    /// Develop the brain from a genome
437    ///
438    /// This is the main entry point that orchestrates all development stages.
439    pub fn develop_from_genome(&mut self, genome: &RuntimeGenome) -> BduResult<()> {
440        info!(target: "feagi-bdu","🧬 Starting neuroembryogenesis for genome: {}", genome.metadata.genome_id);
441
442        // Phase 5: Parse quantization precision and dispatch to type-specific builder
443        let _quantization_precision = &genome.physiology.quantization_precision;
444        // Precision parsing handled in genome loader
445        let quant_spec = QuantizationSpec::default();
446
447        info!(target: "feagi-bdu",
448            "   Quantization precision: {:?} (range: [{}, {}] for membrane potential)",
449            quant_spec.precision,
450            quant_spec.membrane_potential_min,
451            quant_spec.membrane_potential_max
452        );
453
454        // Phase 6: Type dispatch - Neuroembryogenesis is now fully generic!
455        // The precision is determined by the type T of this Neuroembryogenesis instance.
456        // All stages (corticogenesis, neurogenesis, synaptogenesis) automatically use the correct type.
457        match quant_spec.precision {
458            Precision::FP32 => {
459                info!(target: "feagi-bdu", "   ✓ Using FP32 (32-bit floating-point) - highest precision");
460                info!(target: "feagi-bdu", "   Memory usage: Baseline (4 bytes/neuron for membrane potential)");
461            }
462            Precision::INT8 => {
463                info!(target: "feagi-bdu", "   ✓ Using INT8 (8-bit integer) - memory efficient");
464                info!(target: "feagi-bdu", "   Memory reduction: 42% (1 byte/neuron for membrane potential)");
465                info!(target: "feagi-bdu", "   Quantization range: [{}, {}]",
466                    quant_spec.membrane_potential_min,
467                    quant_spec.membrane_potential_max);
468                // Note: If this Neuroembryogenesis was created with <f32>, this will warn below
469                // The caller must create Neuroembryogenesis::<INT8Value> to use INT8
470            }
471            Precision::FP16 => {
472                warn!(target: "feagi-bdu", "   FP16 quantization requested but not yet implemented.");
473                warn!(target: "feagi-bdu", "   FP16 support planned for future GPU optimization.");
474                // Note: Requires f16 type and implementation
475            }
476        }
477
478        // Type consistency is now handled by DynamicNPU at creation time
479        // The caller (main.rs) peeks at genome precision and creates the correct DynamicNPU variant
480        info!(target: "feagi-bdu", "   ✓ Quantization handled by DynamicNPU (dispatches at runtime)");
481
482        // Update stage: Initialization
483        self.update_stage(DevelopmentStage::Initialization, 0);
484
485        // Stage 1: Corticogenesis - Create cortical area structures
486        self.corticogenesis(genome)?;
487
488        // Stage 2: Voxelogenesis - Establish spatial framework
489        self.voxelogenesis(genome)?;
490
491        // Stage 3: Neurogenesis - Generate neurons
492        self.neurogenesis(genome)?;
493
494        // Stage 4: Synaptogenesis - Form synaptic connections
495        self.synaptogenesis(genome)?;
496
497        // Mark as completed
498        self.update_stage(DevelopmentStage::Completed, 100);
499
500        let progress = self.progress.read();
501        info!(target: "feagi-bdu",
502            "✅ Neuroembryogenesis completed in {}ms: {} cortical areas, {} neurons, {} synapses",
503            progress.duration_ms,
504            progress.cortical_areas_created,
505            progress.neurons_created,
506            progress.synapses_created
507        );
508
509        Ok(())
510    }
511
512    /// Stage 1: Corticogenesis - Create cortical area structures
513    fn corticogenesis(&mut self, genome: &RuntimeGenome) -> BduResult<()> {
514        self.update_stage(DevelopmentStage::Corticogenesis, 0);
515        info!(target: "feagi-bdu","🧠 Stage 1: Corticogenesis - Creating {} cortical areas", genome.cortical_areas.len());
516        info!(target: "feagi-bdu","🔍 Genome brain_regions check: is_empty={}, count={}",
517              genome.brain_regions.is_empty(), genome.brain_regions.len());
518        if !genome.brain_regions.is_empty() {
519            info!(target: "feagi-bdu","   Existing regions: {:?}", genome.brain_regions.keys().collect::<Vec<_>>());
520        }
521
522        let total_areas = genome.cortical_areas.len();
523
524        // CRITICAL: Minimize lock scope - only hold lock when actually adding areas
525        for (idx, (cortical_id, area)) in genome.cortical_areas.iter().enumerate() {
526            // Add cortical area to connectome - lock held only during this operation
527            {
528                let mut manager = self.connectome_manager.write();
529                manager.add_cortical_area(area.clone())?;
530            } // Lock released immediately after adding
531
532            // Update progress (doesn't need lock)
533            let progress_pct = ((idx + 1) * 100 / total_areas.max(1)) as u8;
534            self.update_progress(|p| {
535                p.cortical_areas_created = idx + 1;
536                p.progress = progress_pct;
537            });
538
539            trace!(target: "feagi-bdu", "Created cortical area: {} ({})", cortical_id, area.name);
540        }
541
542        // Ensure brain regions structure exists (auto-generate if missing)
543        // This matches Python's normalize_brain_region_membership() behavior
544        info!(target: "feagi-bdu","🔍 BRAIN REGION AUTO-GEN CHECK: genome.brain_regions.is_empty() = {}", genome.brain_regions.is_empty());
545        let (brain_regions_to_add, region_parent_map) = if genome.brain_regions.is_empty() {
546            info!(target: "feagi-bdu","  ✅ TRIGGERING AUTO-GENERATION: No brain_regions in genome - auto-generating default root region");
547            info!(target: "feagi-bdu","  📊 Genome has {} cortical areas to process", genome.cortical_areas.len());
548
549            // Collect all cortical area IDs
550            let all_cortical_ids = genome.cortical_areas.keys().cloned().collect::<Vec<_>>();
551            info!(target: "feagi-bdu","  📊 Collected {} cortical area IDs: {:?}", all_cortical_ids.len(),
552            if all_cortical_ids.len() <= 5 {
553                format!("{:?}", all_cortical_ids.iter().map(|id| id.to_string()).collect::<Vec<_>>())
554            } else {
555                format!("{:?}...", all_cortical_ids[0..5].iter().map(|id| id.to_string()).collect::<Vec<_>>())
556            });
557
558            // Classify areas into inputs/outputs based on their AreaType
559            let mut auto_inputs = Vec::new();
560            let mut auto_outputs = Vec::new();
561
562            // Classify areas into categories following Python's normalize_brain_region_membership()
563            let mut ipu_areas = Vec::new(); // Sensory inputs
564            let mut opu_areas = Vec::new(); // Motor outputs
565            let mut core_areas = Vec::new(); // Core/maintenance (like _power)
566            let mut custom_memory_areas = Vec::new(); // CUSTOM/MEMORY (go to subregion)
567
568            for (area_id, area) in genome.cortical_areas.iter() {
569                // Classify following Python's logic with gradual migration to new type system:
570                // 1. Areas starting with "_" are always CORE
571                // 2. Check cortical_type_new (new strongly-typed system) - Phase 2+
572                // 3. Check cortical_group property (parsed from genome)
573                // 4. Fallback to area_type (old simple enum)
574
575                let area_id_str = area_id.to_string();
576                // Note: Core IDs are 8-byte padded and start with "___" (three underscores)
577                let category = if area_id_str.starts_with("___") {
578                    "CORE"
579                } else if let Ok(cortical_type) = area.cortical_id.as_cortical_type() {
580                    // Use cortical type from CorticalID
581                    use feagi_structures::genomic::cortical_area::CorticalAreaType;
582                    match cortical_type {
583                        CorticalAreaType::Core(_) => "CORE",
584                        CorticalAreaType::BrainInput(_) => "IPU",
585                        CorticalAreaType::BrainOutput(_) => "OPU",
586                        CorticalAreaType::Memory(_) => "MEMORY",
587                        CorticalAreaType::Custom(_) => "CUSTOM",
588                        CorticalAreaType::Modulator => "MODULATOR",
589                    }
590                } else {
591                    // Fallback to cortical_group property or area_type
592                    let cortical_group = area
593                        .properties
594                        .get("cortical_group")
595                        .and_then(|v| v.as_str())
596                        .map(|s| s.to_uppercase());
597
598                    match cortical_group.as_deref() {
599                        Some("IPU") => "IPU",
600                        Some("OPU") => "OPU",
601                        Some("CORE") => "CORE",
602                        Some("MEMORY") => "MEMORY",
603                        Some("CUSTOM") => "CUSTOM",
604                        Some("MODULATOR") => "MODULATOR",
605                        _ => "CUSTOM", // Default fallback
606                    }
607                };
608
609                // Phase 3: Enhanced logging with detailed type information
610                if ipu_areas.len() + opu_areas.len() + core_areas.len() + custom_memory_areas.len()
611                    < 5
612                {
613                    let source = if area.cortical_id.as_cortical_type().is_ok() {
614                        "cortical_id_type"
615                    } else if area.properties.contains_key("cortical_group") {
616                        "cortical_group"
617                    } else {
618                        "default_fallback"
619                    };
620
621                    // Phase 3: Show detailed type information if available
622                    if area.cortical_id.as_cortical_type().is_ok() {
623                        let type_desc = crate::cortical_type_utils::describe_cortical_type(area);
624                        let frame_handling =
625                            if crate::cortical_type_utils::uses_absolute_frames(area) {
626                                "absolute"
627                            } else if crate::cortical_type_utils::uses_incremental_frames(area) {
628                                "incremental"
629                            } else {
630                                "n/a"
631                            };
632                        info!(target: "feagi-bdu","    🔍 {}, frames={}, source={}",
633                              type_desc, frame_handling, source);
634                    } else {
635                        info!(target: "feagi-bdu","    🔍 Area {}: category={}, source={}",
636                              area_id_str, category, source);
637                    }
638                }
639
640                // Assign to appropriate list
641                match category {
642                    "IPU" => {
643                        ipu_areas.push(*area_id);
644                        auto_inputs.push(*area_id);
645                    }
646                    "OPU" => {
647                        opu_areas.push(*area_id);
648                        auto_outputs.push(*area_id);
649                    }
650                    "CORE" | "MODULATOR" => {
651                        core_areas.push(*area_id);
652                    }
653                    "MEMORY" | "CUSTOM" => {
654                        custom_memory_areas.push(*area_id);
655                    }
656                    _ => {}
657                }
658            }
659
660            info!(target: "feagi-bdu","  📊 Classification complete: IPU={}, OPU={}, CORE={}, CUSTOM/MEMORY={}",
661                  ipu_areas.len(), opu_areas.len(), core_areas.len(), custom_memory_areas.len());
662
663            // Build brain region structure following Python's normalize_brain_region_membership()
664            use feagi_structures::genomic::brain_regions::{BrainRegion, RegionID, RegionType};
665            let mut regions_map = std::collections::HashMap::new();
666
667            // Step 1: Create root region with only IPU/OPU/CORE areas
668            let mut root_area_ids = Vec::new();
669            root_area_ids.extend(ipu_areas.iter().cloned());
670            root_area_ids.extend(opu_areas.iter().cloned());
671            root_area_ids.extend(core_areas.iter().cloned());
672
673            // Analyze connections to determine actual inputs/outputs for root
674            let (root_inputs, root_outputs) =
675                Self::analyze_region_io(&root_area_ids, &genome.cortical_areas);
676
677            // Convert CorticalID to base64 for with_areas()
678            // Create a root region with a generated RegionID
679            let root_region_id = RegionID::new();
680            let root_region_id_str = root_region_id.to_string();
681
682            let mut root_region = BrainRegion::new(
683                root_region_id,
684                ROOT_BRAIN_REGION_NAME.to_string(),
685                RegionType::Undefined,
686            )
687            .expect("Failed to create root region")
688            .with_areas(root_area_ids.iter().cloned());
689
690            // Store inputs/outputs based on connection analysis
691            if !root_inputs.is_empty() {
692                root_region
693                    .add_property("inputs".to_string(), serde_json::json!(root_inputs.clone()));
694            }
695            if !root_outputs.is_empty() {
696                root_region.add_property(
697                    "outputs".to_string(),
698                    serde_json::json!(root_outputs.clone()),
699                );
700            }
701
702            info!(target: "feagi-bdu","  ✅ Created root region with {} areas (IPU={}, OPU={}, CORE={}) - analyzed: {} inputs, {} outputs",
703                  root_area_ids.len(), ipu_areas.len(), opu_areas.len(), core_areas.len(),
704                  root_inputs.len(), root_outputs.len());
705
706            // Step 2: Create subregion for CUSTOM/MEMORY areas if any exist
707            let mut subregion_id = None;
708            if !custom_memory_areas.is_empty() {
709                // Convert CorticalID to base64 for sorting and hashing
710                let mut custom_memory_strs: Vec<String> = custom_memory_areas
711                    .iter()
712                    .map(|id| id.as_base_64())
713                    .collect();
714                custom_memory_strs.sort(); // Sort for deterministic hash
715                let combined = custom_memory_strs.join("|");
716
717                // Use a simple hash (matching Python's sha1[:8])
718                use std::collections::hash_map::DefaultHasher;
719                use std::hash::{Hash, Hasher};
720                let mut hasher = DefaultHasher::new();
721                combined.hash(&mut hasher);
722                let hash = hasher.finish();
723                let hash_hex = format!("{:08x}", hash as u32);
724                let region_id = format!("region_autogen_{}", hash_hex);
725
726                // Analyze connections to determine inputs/outputs for subregion
727                let (subregion_inputs, subregion_outputs) =
728                    Self::analyze_region_io(&custom_memory_areas, &genome.cortical_areas);
729
730                // Calculate smart position: Place autogen region outside root's bounding box
731                let autogen_position =
732                    Self::calculate_autogen_region_position(&root_area_ids, genome);
733
734                // Create subregion
735                let subregion_name = autogen_subregion_display_name(&genome.metadata.genome_title);
736                let mut subregion = BrainRegion::new(
737                    RegionID::new(), // Generate new UUID instead of using string
738                    subregion_name,
739                    RegionType::Undefined, // RegionType no longer has Custom variant
740                )
741                .expect("Failed to create subregion")
742                .with_areas(custom_memory_areas.iter().cloned());
743
744                // Set 3D coordinates (place outside root's bounding box)
745                subregion.add_property(
746                    "coordinate_3d".to_string(),
747                    serde_json::json!(autogen_position),
748                );
749                subregion.add_property("coordinate_2d".to_string(), serde_json::json!([0, 0]));
750
751                // Store inputs/outputs for subregion
752                if !subregion_inputs.is_empty() {
753                    subregion.add_property(
754                        "inputs".to_string(),
755                        serde_json::json!(subregion_inputs.clone()),
756                    );
757                }
758                if !subregion_outputs.is_empty() {
759                    subregion.add_property(
760                        "outputs".to_string(),
761                        serde_json::json!(subregion_outputs.clone()),
762                    );
763                }
764
765                let subregion_id_str = subregion.region_id.to_string();
766
767                info!(target: "feagi-bdu","  ✅ Created subregion '{}' with {} CUSTOM/MEMORY areas ({} inputs, {} outputs)",
768                      region_id, custom_memory_areas.len(), subregion_inputs.len(), subregion_outputs.len());
769
770                regions_map.insert(subregion_id_str.clone(), subregion);
771                subregion_id = Some(subregion_id_str);
772            }
773
774            regions_map.insert(root_region_id_str.clone(), root_region);
775
776            // Count total inputs/outputs across all regions
777            let total_inputs = root_inputs.len()
778                + if let Some(ref sid) = subregion_id {
779                    regions_map
780                        .get(sid)
781                        .and_then(|r| r.properties.get("inputs"))
782                        .and_then(|v| v.as_array())
783                        .map(|a| a.len())
784                        .unwrap_or(0)
785                } else {
786                    0
787                };
788
789            let total_outputs = root_outputs.len()
790                + if let Some(ref sid) = subregion_id {
791                    regions_map
792                        .get(sid)
793                        .and_then(|r| r.properties.get("outputs"))
794                        .and_then(|v| v.as_array())
795                        .map(|a| a.len())
796                        .unwrap_or(0)
797                } else {
798                    0
799                };
800
801            info!(target: "feagi-bdu","  ✅ Auto-generated {} brain region(s) with {} total cortical areas ({} total inputs, {} total outputs)",
802                  regions_map.len(), all_cortical_ids.len(), total_inputs, total_outputs);
803
804            // Return (regions_map, parent_map) so we can properly link hierarchy
805            let mut parent_map = std::collections::HashMap::new();
806            if let Some(ref sub_id) = subregion_id {
807                parent_map.insert(sub_id.clone(), root_region_id_str.clone());
808                info!(target: "feagi-bdu","  🔗 Parent relationship: {} -> {}", sub_id, root_region_id_str);
809            }
810
811            (regions_map, parent_map)
812        } else {
813            info!(target: "feagi-bdu","  📋 Genome already has {} brain regions - using existing structure", genome.brain_regions.len());
814            let mut regions_map = genome.brain_regions.clone();
815            if let Some(wrapper_id) = wrap_parentless_regions_under_named_root(&mut regions_map) {
816                info!(
817                    target: "feagi-bdu",
818                    "  🔗 Wrapped parentless circuit(s) under new {} ({}); original circuit names preserved",
819                    ROOT_BRAIN_REGION_NAME,
820                    wrapper_id
821                );
822            }
823            if let Some(circuit_name) = apply_genome_title_to_unique_top_circuit(
824                &mut regions_map,
825                &genome.metadata.genome_title,
826            ) {
827                info!(
828                    target: "feagi-bdu",
829                    "  Applied genome_title to unique top-level circuit: {}",
830                    circuit_name
831                );
832            }
833            // Parent links may be stored on each region as `parent_region_id` (properties). Flat/v3
834            // exports often omit them; without parents, add_brain_region(..., None) only registers the
835            // first region as root and leaves other regions detached — BV then shows an empty tree.
836            let mut region_parent_map: std::collections::HashMap<String, String> =
837                std::collections::HashMap::new();
838            for (region_id, region) in &regions_map {
839                if let Some(pid) = region
840                    .properties
841                    .get("parent_region_id")
842                    .and_then(|v| v.as_str())
843                {
844                    region_parent_map.insert(region_id.clone(), pid.to_string());
845                }
846            }
847            if region_parent_map.is_empty() {
848                if let Some((root_id, _)) = regions_map
849                    .iter()
850                    .find(|(_, r)| r.name == ROOT_BRAIN_REGION_NAME)
851                {
852                    for (region_id, region) in &regions_map {
853                        if region.name == ROOT_BRAIN_REGION_NAME {
854                            continue;
855                        }
856                        region_parent_map.insert(region_id.clone(), root_id.clone());
857                    }
858                    if !region_parent_map.is_empty() {
859                        info!(target: "feagi-bdu",
860                            "  🔗 Inferred {} sub-region parent link(s) under root {}",
861                            region_parent_map.len(),
862                            root_id
863                        );
864                    }
865                } else {
866                    warn!(target: "feagi-bdu",
867                        "  ⚠️ brain_regions present but no '{}' and no parent_region_id — hierarchy may not load in BV",
868                        ROOT_BRAIN_REGION_NAME
869                    );
870                }
871            }
872            (regions_map, region_parent_map)
873        };
874
875        // Add brain regions with proper parent relationships - minimize lock scope
876        {
877            let mut manager = self.connectome_manager.write();
878            let brain_region_count = brain_regions_to_add.len();
879            info!(target: "feagi-bdu","  Adding {} brain regions from genome", brain_region_count);
880
881            // Named root first (parent=None). Remaining regions are inserted in
882            // parent-before-child order so nested trees do not depend on HashMap iteration.
883            let root_entry = brain_regions_to_add
884                .iter()
885                .find(|(_, region)| region.name == ROOT_BRAIN_REGION_NAME);
886            if let Some((root_id, root_region)) = root_entry {
887                manager.add_brain_region(root_region.clone(), None)?;
888                debug!(target: "feagi-bdu","    ✓ Added brain region: {} ({}) [parent=None]", root_id, ROOT_BRAIN_REGION_NAME);
889            }
890
891            let remaining_ids: Vec<String> = brain_regions_to_add
892                .iter()
893                .filter(|(_, region)| region.name != ROOT_BRAIN_REGION_NAME)
894                .map(|(region_id, _)| region_id.clone())
895                .collect();
896            let ordered_ids = order_regions_parent_before_child(&remaining_ids, &region_parent_map);
897
898            for region_id in ordered_ids {
899                let region = brain_regions_to_add.get(&region_id).ok_or_else(|| {
900                    BduError::Internal(format!(
901                        "Ordered region {} missing from genome region map",
902                        region_id
903                    ))
904                })?;
905                let parent_id = region_parent_map.get(&region_id).cloned();
906                manager.add_brain_region(region.clone(), parent_id.clone())?;
907                debug!(target: "feagi-bdu","    ✓ Added brain region: {} ({}) [parent={:?}]",
908                       region_id, region.name, parent_id);
909            }
910
911            info!(target: "feagi-bdu","  Total brain regions in ConnectomeManager: {}", manager.get_brain_region_ids().len());
912
913            manager.replace_classifiers(genome.classifiers.clone());
914            for classifier in genome.classifiers.values() {
915                if let Some(region) = manager.get_brain_region_mut(&classifier.parent_region_id) {
916                    for area_id in classifier.owned_area_ids() {
917                        if let Ok(cortical_id) =
918                            feagi_structures::genomic::cortical_area::CorticalID::try_from_base_64(
919                                &area_id,
920                            )
921                        {
922                            region.add_area(cortical_id);
923                        }
924                    }
925                }
926            }
927            manager.apply_loaded_classifier_assemblies();
928            info!(
929                target: "feagi-bdu",
930                "  Loaded {} classifier assemblies from genome",
931                genome.classifiers.len()
932            );
933        } // Lock released
934
935        self.update_stage(DevelopmentStage::Corticogenesis, 100);
936        info!(target: "feagi-bdu","  ✅ Corticogenesis complete: {} cortical areas created", total_areas);
937
938        Ok(())
939    }
940
941    /// Stage 2: Voxelogenesis - Establish spatial framework
942    fn voxelogenesis(&mut self, _genome: &RuntimeGenome) -> BduResult<()> {
943        self.update_stage(DevelopmentStage::Voxelogenesis, 0);
944        info!(target: "feagi-bdu","📐 Stage 2: Voxelogenesis - Establishing spatial framework");
945
946        // Spatial framework is implicitly established by cortical area dimensions
947        // The Morton spatial hash in ConnectomeManager handles the actual indexing
948
949        self.update_stage(DevelopmentStage::Voxelogenesis, 100);
950        info!(target: "feagi-bdu","  ✅ Voxelogenesis complete: Spatial framework established");
951
952        Ok(())
953    }
954
955    /// Stage 3: Neurogenesis - Generate neurons within cortical areas
956    ///
957    /// This uses ConnectomeManager which delegates to NPU's SIMD-optimized batch operations.
958    /// Each cortical area is processed with `create_cortical_area_neurons()` which creates
959    /// ALL neurons for that area in one vectorized operation (not a loop).
960    ///
961    /// CRITICAL: Core areas (0=_death, 1=_power, 2=_fatigue, 3=_pain, 4=_pleasure, 5=_fear, 6=_hope) are created
962    /// FIRST to ensure deterministic neuron IDs.
963    fn neurogenesis(&mut self, genome: &RuntimeGenome) -> BduResult<()> {
964        self.update_stage(DevelopmentStage::Neurogenesis, 0);
965        info!(target: "feagi-bdu","🔬 Stage 3: Neurogenesis - Generating neurons (SIMD-optimized batches)");
966
967        let expected_neurons = genome.stats.innate_neuron_count;
968        info!(target: "feagi-bdu","  Expected innate neurons from genome: {}", expected_neurons);
969
970        // CRITICAL: Identify core areas first to ensure deterministic neuron IDs
971        use feagi_structures::genomic::cortical_area::CoreCorticalType;
972        let death_id = CoreCorticalType::Death.to_cortical_id();
973        let power_id = CoreCorticalType::Power.to_cortical_id();
974        let fatigue_id = CoreCorticalType::Fatigue.to_cortical_id();
975        let pain_id = CoreCorticalType::Pain.to_cortical_id();
976        let pleasure_id = CoreCorticalType::Pleasure.to_cortical_id();
977        let fear_id = CoreCorticalType::Fear.to_cortical_id();
978        let hope_id = CoreCorticalType::Hope.to_cortical_id();
979
980        let mut core_areas = Vec::new();
981        let mut other_areas = Vec::new();
982
983        // Separate core areas from other areas
984        for (cortical_id, area) in genome.cortical_areas.iter() {
985            if *cortical_id == death_id {
986                core_areas.push((0, *cortical_id, area)); // Area 0 = _death
987            } else if *cortical_id == power_id {
988                core_areas.push((1, *cortical_id, area)); // Area 1 = _power
989            } else if *cortical_id == fatigue_id {
990                core_areas.push((2, *cortical_id, area)); // Area 2 = _fatigue
991            } else if *cortical_id == pain_id {
992                core_areas.push((3, *cortical_id, area)); // Area 3 = _pain
993            } else if *cortical_id == pleasure_id {
994                core_areas.push((4, *cortical_id, area)); // Area 4 = _pleasure
995            } else if *cortical_id == fear_id {
996                core_areas.push((5, *cortical_id, area)); // Area 5 = _fear
997            } else if *cortical_id == hope_id {
998                core_areas.push((6, *cortical_id, area)); // Area 6 = _hope
999            } else {
1000                other_areas.push((*cortical_id, area));
1001            }
1002        }
1003
1004        // Sort core areas by their deterministic index (0..=6)
1005        core_areas.sort_by_key(|(idx, _, _)| *idx);
1006
1007        info!(target: "feagi-bdu","  🎯 Creating core area neurons FIRST ({} areas) for deterministic IDs", core_areas.len());
1008
1009        let mut total_neurons_created = 0;
1010        let mut processed_count = 0;
1011        let total_areas = genome.cortical_areas.len();
1012
1013        // STEP 1: Create core area neurons FIRST (in order: 0..=6)
1014        for (core_idx, cortical_id, area) in &core_areas {
1015            let existing_core_neurons = {
1016                let manager = self.connectome_manager.read();
1017                let npu = manager.get_npu();
1018                match npu {
1019                    Some(npu_arc) => {
1020                        let npu_lock = npu_arc.lock();
1021                        match npu_lock {
1022                            Ok(npu_guard) => {
1023                                npu_guard.get_neurons_in_cortical_area(*core_idx).len()
1024                            }
1025                            Err(_) => 0,
1026                        }
1027                    }
1028                    None => 0,
1029                }
1030            };
1031
1032            if existing_core_neurons > 0 {
1033                self.sync_core_neuron_params(*core_idx, area)?;
1034                let refreshed = {
1035                    let manager = self.connectome_manager.read();
1036                    manager.refresh_neuron_count_for_area(cortical_id)
1037                };
1038                let count = refreshed.unwrap_or(existing_core_neurons);
1039                total_neurons_created += count;
1040                info!(
1041                    target: "feagi-bdu",
1042                    "  ↪ Skipping core neuron creation for {} (existing={}, idx={})",
1043                    cortical_id.as_base_64(),
1044                    count,
1045                    core_idx
1046                );
1047                processed_count += 1;
1048                let progress_pct = (processed_count * 100 / total_areas.max(1)) as u8;
1049                self.update_progress(|p| {
1050                    p.neurons_created = total_neurons_created;
1051                    p.progress = progress_pct;
1052                });
1053                continue;
1054            }
1055            let per_voxel_count = area
1056                .properties
1057                .get("neurons_per_voxel")
1058                .and_then(|v| v.as_u64())
1059                .unwrap_or(1) as i64;
1060
1061            let cortical_id_str = cortical_id.to_string();
1062            info!(target: "feagi-bdu","  🔋 [CORE-AREA {}] {} - dimensions: {:?}, per_voxel: {}",
1063                core_idx, cortical_id_str, area.dimensions, per_voxel_count);
1064
1065            if per_voxel_count == 0 {
1066                warn!(target: "feagi-bdu","  ⚠️ Skipping core area {} - per_voxel_neuron_cnt is 0", cortical_id_str);
1067                continue;
1068            }
1069
1070            // Create neurons for core area (ensures deterministic ID: area 0→neuron 0, area 1→neuron 1, area 2→neuron 2)
1071            let neurons_created = {
1072                let manager_arc = self.connectome_manager.clone();
1073                let mut manager = manager_arc.write();
1074                manager.create_neurons_for_area(cortical_id)
1075            };
1076
1077            match neurons_created {
1078                Ok(count) => {
1079                    total_neurons_created += count as usize;
1080                    info!(target: "feagi-bdu","  ✅ Created {} neurons for core area {} (deterministic ID: neuron {})",
1081                        count, cortical_id_str, core_idx);
1082                }
1083                Err(e) => {
1084                    error!(target: "feagi-bdu","  ❌ FATAL: Failed to create neurons for core area {}: {}", cortical_id_str, e);
1085                    return Err(e);
1086                }
1087            }
1088
1089            processed_count += 1;
1090            let progress_pct = (processed_count * 100 / total_areas.max(1)) as u8;
1091            self.update_progress(|p| {
1092                p.neurons_created = total_neurons_created;
1093                p.progress = progress_pct;
1094            });
1095        }
1096
1097        // STEP 2: Create neurons for all other areas
1098        info!(target: "feagi-bdu","  📦 Creating neurons for {} other areas", other_areas.len());
1099        for (cortical_id, area) in &other_areas {
1100            // Get neurons_per_voxel from typed field (single source of truth)
1101            let _per_voxel_count = area
1102                .properties
1103                .get("neurons_per_voxel")
1104                .and_then(|v| v.as_u64())
1105                .unwrap_or(1) as i64;
1106
1107            let per_voxel_count = area
1108                .properties
1109                .get("neurons_per_voxel")
1110                .and_then(|v| v.as_u64())
1111                .unwrap_or(1) as i64;
1112
1113            let cortical_id_str = cortical_id.to_string();
1114
1115            if per_voxel_count == 0 {
1116                warn!(target: "feagi-bdu","  ⚠️ Skipping area {} - per_voxel_neuron_cnt is 0 (will have NO neurons!)", cortical_id_str);
1117                continue;
1118            }
1119
1120            // Call ConnectomeManager to create neurons (delegates to NPU)
1121            // CRITICAL: Minimize lock scope - only hold lock during neuron creation
1122            let neurons_created = {
1123                let manager_arc = self.connectome_manager.clone();
1124                let mut manager = manager_arc.write();
1125                manager.create_neurons_for_area(cortical_id)
1126            }; // Lock released immediately
1127
1128            match neurons_created {
1129                Ok(count) => {
1130                    total_neurons_created += count as usize;
1131                    trace!(
1132                        target: "feagi-bdu",
1133                        "Created {} neurons for area {}",
1134                        count,
1135                        cortical_id_str
1136                    );
1137                }
1138                Err(e) => {
1139                    // If NPU not connected, calculate expected count
1140                    warn!(target: "feagi-bdu","  Failed to create neurons for {}: {} (NPU may not be connected)",
1141                        cortical_id_str, e);
1142                    let total_voxels = area.dimensions.width as usize
1143                        * area.dimensions.height as usize
1144                        * area.dimensions.depth as usize;
1145                    let expected = total_voxels * per_voxel_count as usize;
1146                    total_neurons_created += expected;
1147                }
1148            }
1149
1150            processed_count += 1;
1151            // Update progress
1152            let progress_pct = (processed_count * 100 / total_areas.max(1)) as u8;
1153            self.update_progress(|p| {
1154                p.neurons_created = total_neurons_created;
1155                p.progress = progress_pct;
1156            });
1157        }
1158
1159        // Compare with genome stats (info only - stats may count only innate neurons while we create all voxels)
1160        if expected_neurons > 0 && total_neurons_created != expected_neurons {
1161            trace!(target: "feagi-bdu",
1162                created_neurons = total_neurons_created,
1163                genome_stats_innate = expected_neurons,
1164                "Neuron creation complete (genome stats may only count innate neurons)"
1165            );
1166        }
1167
1168        self.update_stage(DevelopmentStage::Neurogenesis, 100);
1169        info!(target: "feagi-bdu","  ✅ Neurogenesis complete: {} neurons created", total_neurons_created);
1170
1171        Ok(())
1172    }
1173
1174    /// Stage 4: Synaptogenesis - Form synaptic connections between neurons
1175    ///
1176    /// This uses ConnectomeManager which delegates to NPU's morphology functions.
1177    /// Each morphology application (`apply_projector_morphology`, etc.) processes ALL neurons
1178    /// from the source area and creates ALL synapses in one SIMD-optimized batch operation.
1179    fn synaptogenesis(&mut self, genome: &RuntimeGenome) -> BduResult<()> {
1180        self.update_stage(DevelopmentStage::Synaptogenesis, 0);
1181        info!(target: "feagi-bdu","🔗 Stage 4: Synaptogenesis - Forming synaptic connections (SIMD-optimized batches)");
1182
1183        let expected_synapses = genome.stats.innate_synapse_count;
1184        info!(target: "feagi-bdu","  Expected innate synapses from genome: {}", expected_synapses);
1185
1186        self.rebuild_memory_twin_mappings_from_genome(genome)?;
1187        self.connectome_manager
1188            .write()
1189            .sync_modulators_from_genome(genome)?;
1190
1191        let mut total_synapses_created = 0;
1192        let total_areas = genome.cortical_areas.len();
1193
1194        // Process each source area via ConnectomeManager (each mapping = one SIMD batch)
1195        // NOTE: Loop is over AREAS, not synapses. Each area applies all mappings in batch calls.
1196        for (idx, (_src_cortical_id, src_area)) in genome.cortical_areas.iter().enumerate() {
1197            // Check if area has mappings
1198            let has_dstmap = src_area
1199                .properties
1200                .get("cortical_mapping_dst")
1201                .and_then(|v| v.as_object())
1202                .map(|m| !m.is_empty())
1203                .unwrap_or(false);
1204
1205            if !has_dstmap {
1206                trace!(target: "feagi-bdu", "No dstmap for area {}", &src_area.cortical_id);
1207                continue;
1208            }
1209
1210            // Call ConnectomeManager to apply cortical mappings (delegates to NPU)
1211            // CRITICAL: Minimize lock scope - only hold lock during synapse creation
1212            // Use src_area.cortical_id (the actual ID stored in ConnectomeManager)
1213            let src_cortical_id = &src_area.cortical_id;
1214            let src_cortical_id_str = src_cortical_id.to_string(); // For logging
1215            let synapses_created = {
1216                let manager_arc = self.connectome_manager.clone();
1217                let mut manager = manager_arc.write();
1218                if let Some(dstmap) = src_area.properties.get("cortical_mapping_dst") {
1219                    if let Some(area) = manager.get_cortical_area_mut(src_cortical_id) {
1220                        area.properties
1221                            .insert("cortical_mapping_dst".to_string(), dstmap.clone());
1222                    }
1223                }
1224                manager.apply_cortical_mapping(src_cortical_id)
1225            }; // Lock released immediately
1226
1227            match synapses_created {
1228                Ok(count) => {
1229                    total_synapses_created += count as usize;
1230                    trace!(
1231                        target: "feagi-bdu",
1232                        "Created {} synapses for area {}",
1233                        count,
1234                        src_cortical_id_str
1235                    );
1236                }
1237                Err(e) => {
1238                    // If NPU not connected, estimate count
1239                    warn!(target: "feagi-bdu","  Failed to create synapses for {}: {} (NPU may not be connected)",
1240                        src_cortical_id_str, e);
1241                    let estimated = estimate_synapses_for_area(src_area, genome);
1242                    total_synapses_created += estimated;
1243                }
1244            }
1245
1246            // Update progress
1247            let progress_pct = ((idx + 1) * 100 / total_areas.max(1)) as u8;
1248            self.update_progress(|p| {
1249                p.synapses_created = total_synapses_created;
1250                p.progress = progress_pct;
1251            });
1252        }
1253
1254        // CRITICAL: Rebuild the NPU synapse index so newly created synapses are visible to
1255        // queries (e.g. get_outgoing_synapses / synapse counts) and propagation.
1256        //
1257        // Note: We do this once at the end for performance.
1258        let npu_arc = {
1259            let manager = self.connectome_manager.read();
1260            manager.get_npu().cloned()
1261        };
1262        if let Some(npu_arc) = npu_arc {
1263            let mut npu_lock = npu_arc
1264                .lock()
1265                .map_err(|e| BduError::Internal(format!("Failed to lock NPU: {}", e)))?;
1266            npu_lock.rebuild_synapse_index();
1267
1268            // Refresh cached counts after index rebuild.
1269            let manager = self.connectome_manager.read();
1270            manager.update_cached_synapse_count();
1271        }
1272
1273        // CRITICAL: Register memory areas with PlasticityExecutor after all mappings are created
1274        // This ensures memory areas have their complete upstream_cortical_areas lists populated.
1275        #[cfg(feature = "plasticity")]
1276        {
1277            use feagi_evolutionary::extract_memory_properties;
1278            use feagi_npu_plasticity::PlasticityExecutor;
1279
1280            let manager = self.connectome_manager.read();
1281            if let Some(executor) = manager.get_plasticity_executor() {
1282                let mut registered_count = 0;
1283
1284                // Iterate through all cortical areas and register memory areas
1285                for area_id in manager.get_cortical_area_ids() {
1286                    if let Some(area) = manager.get_cortical_area(area_id) {
1287                        if let Some(mem_props) = extract_memory_properties(&area.properties) {
1288                            let upstream_areas =
1289                                manager.get_episodic_memory_upstream_cortical_areas(area_id);
1290
1291                            // Ensure FireLedger tracks upstream areas with at least the required temporal depth.
1292                            // Dense, burst-aligned tracking is required for correct memory pattern hashing.
1293                            if let Some(npu_arc) = manager.get_npu() {
1294                                if let Ok(mut npu) = npu_arc.lock() {
1295                                    let existing_configs = npu.get_all_fire_ledger_configs();
1296                                    for &upstream_idx in &upstream_areas {
1297                                        let existing = existing_configs
1298                                            .iter()
1299                                            .find(|(idx, _)| *idx == upstream_idx)
1300                                            .map(|(_, w)| *w)
1301                                            .unwrap_or(0);
1302
1303                                        let desired = mem_props.temporal_depth as usize;
1304                                        let resolved = existing.max(desired);
1305                                        if resolved != existing {
1306                                            if let Err(e) = npu.configure_fire_ledger_window(
1307                                                upstream_idx,
1308                                                resolved,
1309                                            ) {
1310                                                warn!(
1311                                                    target: "feagi-bdu",
1312                                                    "Failed to configure FireLedger window for upstream area idx={} (requested={}): {}",
1313                                                    upstream_idx,
1314                                                    resolved,
1315                                                    e
1316                                                );
1317                                            }
1318                                        }
1319                                    }
1320                                } else {
1321                                    warn!(target: "feagi-bdu", "Failed to lock NPU for FireLedger configuration");
1322                                }
1323                            }
1324
1325                            if let Ok(exec) = executor.lock() {
1326                                let lifecycle_config = crate::memory_lifecycle_config(&mem_props);
1327
1328                                let mp_mode =
1329                                    match crate::memory_mp_mode(&area.properties, &mem_props) {
1330                                        Ok(mode) => mode,
1331                                        Err(e) => {
1332                                            error!(
1333                                                target: "feagi-bdu",
1334                                                "Memory area {} not registered: {}",
1335                                                area_id.as_base_64(),
1336                                                e
1337                                            );
1338                                            continue;
1339                                        }
1340                                    };
1341                                exec.register_memory_area(
1342                                    area.cortical_idx,
1343                                    area_id.as_base_64(),
1344                                    mem_props.temporal_depth,
1345                                    upstream_areas.clone(),
1346                                    Some(lifecycle_config),
1347                                    mp_mode,
1348                                );
1349                                manager.configure_memory_scan_on_executor(&*exec, area_id);
1350
1351                                registered_count += 1;
1352                            }
1353                        }
1354                    }
1355                }
1356                let _ = registered_count; // count retained for future metrics if needed
1357            }
1358        }
1359
1360        // Verify against genome stats
1361        if expected_synapses > 0 {
1362            let diff = (total_synapses_created as i64 - expected_synapses as i64).abs();
1363            let diff_pct = (diff as f64 / expected_synapses.max(1) as f64) * 100.0;
1364
1365            if diff_pct > 10.0 {
1366                warn!(target: "feagi-bdu",
1367                    "Synapse count variance: created {} but genome stats expected {} ({:.1}% difference)",
1368                    total_synapses_created, expected_synapses, diff_pct
1369                );
1370            } else {
1371                info!(target: "feagi-bdu",
1372                    "Synapse count matches genome stats within {:.1}% ({} vs {})",
1373                    diff_pct, total_synapses_created, expected_synapses
1374                );
1375            }
1376        }
1377
1378        self.update_stage(DevelopmentStage::Synaptogenesis, 100);
1379        info!(target: "feagi-bdu","  ✅ Synaptogenesis complete: {} synapses created", total_synapses_created);
1380
1381        Ok(())
1382    }
1383
1384    fn rebuild_memory_twin_mappings_from_genome(
1385        &mut self,
1386        genome: &RuntimeGenome,
1387    ) -> BduResult<()> {
1388        use feagi_structures::genomic::cortical_area::CorticalAreaType;
1389        {
1390            let mut manager = self.connectome_manager.write();
1391            manager.purge_classifier_auto_twins()?;
1392        }
1393        let mut repaired = 0usize;
1394
1395        for (memory_id, memory_area) in genome.cortical_areas.iter() {
1396            let is_memory = matches!(
1397                memory_area.cortical_id.as_cortical_type(),
1398                Ok(CorticalAreaType::Memory(_))
1399            ) || memory_area
1400                .properties
1401                .get("is_mem_type")
1402                .and_then(|v| v.as_bool())
1403                .unwrap_or(false)
1404                || memory_area
1405                    .properties
1406                    .get("cortical_group")
1407                    .and_then(|v| v.as_str())
1408                    .is_some_and(|v| v.eq_ignore_ascii_case("MEMORY"));
1409            if !is_memory {
1410                continue;
1411            }
1412
1413            let Some(dstmap) = memory_area
1414                .properties
1415                .get("cortical_mapping_dst")
1416                .and_then(|v| v.as_object())
1417            else {
1418                continue;
1419            };
1420
1421            for (dst_id_str, rules) in dstmap {
1422                let Some(rule_array) = rules.as_array() else {
1423                    continue;
1424                };
1425                let has_twin_recall = rule_array.iter().any(|rule| {
1426                    matches!(
1427                        rule.get("morphology_id").and_then(|v| v.as_str()),
1428                        Some("memory_replay") | Some("episodic_memory")
1429                    )
1430                });
1431                if !has_twin_recall {
1432                    continue;
1433                }
1434
1435                let dst_id = match CorticalID::try_from_base_64(dst_id_str) {
1436                    Ok(id) => id,
1437                    Err(_) => {
1438                        warn!(
1439                            target: "feagi-bdu",
1440                            "Invalid twin cortical ID in memory_replay dstmap: {}",
1441                            dst_id_str
1442                        );
1443                        continue;
1444                    }
1445                };
1446
1447                let Some(twin_area) = genome.cortical_areas.get(&dst_id) else {
1448                    continue;
1449                };
1450                let owned_by_this_memory = ConnectomeManager::memory_owns_twin(
1451                    memory_id,
1452                    twin_area,
1453                    &genome.cortical_areas,
1454                );
1455                let legacy_replay = rule_array.iter().any(|rule| {
1456                    rule.get("morphology_id").and_then(|v| v.as_str()) == Some("memory_replay")
1457                });
1458                if !legacy_replay && !owned_by_this_memory {
1459                    continue;
1460                }
1461                let Some(upstream_id_str) = twin_area
1462                    .properties
1463                    .get("memory_twin_of")
1464                    .and_then(|v| v.as_str())
1465                else {
1466                    continue;
1467                };
1468                let upstream_id = match CorticalID::try_from_base_64(upstream_id_str) {
1469                    Ok(id) => id,
1470                    Err(_) => {
1471                        warn!(
1472                            target: "feagi-bdu",
1473                            "Invalid memory_twin_of value on twin area {}: {}",
1474                            dst_id.as_base_64(),
1475                            upstream_id_str
1476                        );
1477                        continue;
1478                    }
1479                };
1480
1481                let mut manager = self.connectome_manager.write();
1482                if manager.auto_memory_twin_forbidden(memory_id, Some(&dst_id)) {
1483                    continue;
1484                }
1485                // Index the saved twin first so ensure_memory_twin_area reuses it.
1486                if let Err(e) = manager.restore_memory_twin_index(memory_id, &upstream_id, &dst_id)
1487                {
1488                    warn!(
1489                        target: "feagi-bdu",
1490                        "Failed to restore memory twin index for memory {} twin {}: {}",
1491                        memory_id.as_base_64(),
1492                        dst_id.as_base_64(),
1493                        e
1494                    );
1495                    continue;
1496                }
1497                if let Err(e) = manager.ensure_memory_twin_area(memory_id, &upstream_id) {
1498                    warn!(
1499                        target: "feagi-bdu",
1500                        "Failed to rebuild memory twin mapping for memory {} upstream {}: {}",
1501                        memory_id.as_base_64(),
1502                        upstream_id.as_base_64(),
1503                        e
1504                    );
1505                    continue;
1506                }
1507                repaired += 1;
1508            }
1509        }
1510
1511        info!(
1512            target: "feagi-bdu",
1513            "Rebuilt {} memory twin mapping(s) from genome",
1514            repaired
1515        );
1516        Ok(())
1517    }
1518}
1519
1520/// Estimate synapse count for an area (fallback when NPU not connected)
1521///
1522/// This is only used when NPU is not available for actual synapse creation.
1523fn estimate_synapses_for_area(
1524    src_area: &CorticalArea,
1525    genome: &feagi_evolutionary::RuntimeGenome,
1526) -> usize {
1527    let dstmap = match src_area.properties.get("cortical_mapping_dst") {
1528        Some(serde_json::Value::Object(map)) => map,
1529        _ => return 0,
1530    };
1531
1532    let mut total = 0;
1533
1534    for (dst_id, rules) in dstmap {
1535        // Convert string dst_id to CorticalID for lookup
1536        let dst_cortical_id = match feagi_evolutionary::string_to_cortical_id(dst_id) {
1537            Ok(id) => id,
1538            Err(_) => continue,
1539        };
1540        let dst_area = match genome.cortical_areas.get(&dst_cortical_id) {
1541            Some(area) => area,
1542            None => continue,
1543        };
1544
1545        let rules_array = match rules.as_array() {
1546            Some(arr) => arr,
1547            None => continue,
1548        };
1549
1550        for rule in rules_array {
1551            let morphology_id = rule
1552                .get("morphology_id")
1553                .and_then(|v| v.as_str())
1554                .unwrap_or("unknown");
1555            let scalar = rule
1556                .get("morphology_scalar")
1557                .and_then(|v| v.as_i64())
1558                .unwrap_or(1) as usize;
1559
1560            // Simplified estimation
1561            let src_per_voxel = src_area
1562                .properties
1563                .get("neurons_per_voxel")
1564                .and_then(|v| v.as_u64())
1565                .unwrap_or(1) as usize;
1566            let dst_per_voxel = dst_area
1567                .properties
1568                .get("neurons_per_voxel")
1569                .and_then(|v| v.as_u64())
1570                .unwrap_or(1) as usize;
1571
1572            let src_voxels =
1573                src_area.dimensions.width * src_area.dimensions.height * src_area.dimensions.depth;
1574            let dst_voxels =
1575                dst_area.dimensions.width * dst_area.dimensions.height * dst_area.dimensions.depth;
1576
1577            let src_neurons = src_voxels as usize * src_per_voxel;
1578            let dst_neurons = dst_voxels as usize * dst_per_voxel as usize;
1579
1580            // Basic estimation by morphology type
1581            let count = match morphology_id {
1582                "block_to_block" => src_neurons * dst_per_voxel * scalar,
1583                "projector" | "transpose_xy" | "transpose_yz" | "transpose_xz"
1584                | "centered_projector" => src_neurons * dst_neurons * scalar,
1585                _ if morphology_id.contains("lateral") => src_neurons * scalar,
1586                _ => (src_neurons * scalar).min(src_neurons * dst_neurons / 10),
1587            };
1588
1589            total += count;
1590        }
1591    }
1592
1593    total
1594}
1595
1596impl Neuroembryogenesis {
1597    /// Calculate position for autogen region based on root region's bounding box
1598    fn calculate_autogen_region_position(
1599        root_area_ids: &[CorticalID],
1600        genome: &feagi_evolutionary::RuntimeGenome,
1601    ) -> [i32; 3] {
1602        if root_area_ids.is_empty() {
1603            return [100, 0, 0];
1604        }
1605
1606        let mut min_x = i32::MAX;
1607        let mut max_x = i32::MIN;
1608        let mut min_y = i32::MAX;
1609        let mut max_y = i32::MIN;
1610        let mut min_z = i32::MAX;
1611        let mut max_z = i32::MIN;
1612
1613        for cortical_id in root_area_ids {
1614            if let Some(area) = genome.cortical_areas.get(cortical_id) {
1615                let pos: (i32, i32, i32) = area.position.into();
1616                let dims = (
1617                    area.dimensions.width as i32,
1618                    area.dimensions.height as i32,
1619                    area.dimensions.depth as i32,
1620                );
1621
1622                min_x = min_x.min(pos.0);
1623                max_x = max_x.max(pos.0 + dims.0);
1624                min_y = min_y.min(pos.1);
1625                max_y = max_y.max(pos.1 + dims.1);
1626                min_z = min_z.min(pos.2);
1627                max_z = max_z.max(pos.2 + dims.2);
1628            }
1629        }
1630
1631        let bbox_width = (max_x - min_x).max(1);
1632        let padding = (bbox_width / 5).max(50);
1633        let autogen_x = max_x + padding;
1634        let autogen_y = (min_y + max_y) / 2;
1635        let autogen_z = (min_z + max_z) / 2;
1636
1637        info!(target: "feagi-bdu",
1638              "  📐 Autogen position: ({}, {}, {}) [padding: {}]",
1639              autogen_x, autogen_y, autogen_z, padding);
1640
1641        [autogen_x, autogen_y, autogen_z]
1642    }
1643
1644    /// Analyze region inputs/outputs based on cortical connections
1645    ///
1646    /// Following Python's _auto_assign_region_io() logic:
1647    /// - OUTPUT: Any area in the region that connects to an area OUTSIDE the region
1648    /// - INPUT: Any area in the region that receives connection from OUTSIDE the region
1649    fn analyze_region_io(
1650        region_area_ids: &[feagi_structures::genomic::cortical_area::CorticalID],
1651        all_cortical_areas: &std::collections::HashMap<CorticalID, CorticalArea>,
1652    ) -> (Vec<String>, Vec<String>) {
1653        let area_set: std::collections::HashSet<_> = region_area_ids.iter().cloned().collect();
1654        let mut inputs = Vec::new();
1655        let mut outputs = Vec::new();
1656
1657        // Helper to extract destination area IDs from cortical_mapping_dst (as strings)
1658        let extract_destinations = |area: &CorticalArea| -> Vec<String> {
1659            area.properties
1660                .get("cortical_mapping_dst")
1661                .and_then(|v| v.as_object())
1662                .map(|obj| obj.keys().cloned().collect())
1663                .unwrap_or_default()
1664        };
1665
1666        // Find OUTPUTS: areas in region that connect to areas OUTSIDE region
1667        for area_id in region_area_ids {
1668            if let Some(area) = all_cortical_areas.get(area_id) {
1669                let destinations = extract_destinations(area);
1670                // Convert destination strings to CorticalID for comparison
1671                let external_destinations: Vec<_> = destinations
1672                    .iter()
1673                    .filter_map(|dest| feagi_evolutionary::string_to_cortical_id(dest).ok())
1674                    .filter(|dest_id| !area_set.contains(dest_id))
1675                    .collect();
1676
1677                if !external_destinations.is_empty() {
1678                    outputs.push(area_id.as_base_64());
1679                }
1680            }
1681        }
1682
1683        // Find INPUTS: areas in region receiving connections from OUTSIDE region
1684        for (source_area_id, source_area) in all_cortical_areas.iter() {
1685            // Skip areas that are inside the region
1686            if area_set.contains(source_area_id) {
1687                continue;
1688            }
1689
1690            let destinations = extract_destinations(source_area);
1691            for dest_str in destinations {
1692                if let Ok(dest_id) = feagi_evolutionary::string_to_cortical_id(&dest_str) {
1693                    if area_set.contains(&dest_id) {
1694                        let dest_string = dest_id.as_base_64();
1695                        if !inputs.contains(&dest_string) {
1696                            inputs.push(dest_string);
1697                        }
1698                    }
1699                }
1700            }
1701        }
1702
1703        (inputs, outputs)
1704    }
1705
1706    /// Update development stage
1707    fn update_stage(&self, stage: DevelopmentStage, progress: u8) {
1708        let mut p = self.progress.write();
1709        p.stage = stage;
1710        p.progress = progress;
1711        p.duration_ms = self.start_time.elapsed().as_millis() as u64;
1712    }
1713
1714    /// Update progress with a closure
1715    fn update_progress<F>(&self, f: F)
1716    where
1717        F: FnOnce(&mut DevelopmentProgress),
1718    {
1719        let mut p = self.progress.write();
1720        f(&mut p);
1721        p.duration_ms = self.start_time.elapsed().as_millis() as u64;
1722    }
1723}
1724
1725#[cfg(test)]
1726mod tests {
1727    use super::*;
1728    use feagi_evolutionary::create_genome_with_core_morphologies;
1729    use feagi_structures::genomic::cortical_area::CorticalAreaDimensions;
1730
1731    #[test]
1732    fn test_neuroembryogenesis_creation() {
1733        let manager = ConnectomeManager::instance();
1734        let neuro = Neuroembryogenesis::new(manager);
1735
1736        let progress = neuro.get_progress();
1737        assert_eq!(progress.stage, DevelopmentStage::Initialization);
1738        assert_eq!(progress.progress, 0);
1739    }
1740
1741    #[test]
1742    fn autogen_subregion_display_name_uses_title_when_meaningful() {
1743        assert_eq!(
1744            autogen_subregion_display_name("My Shared Circuit"),
1745            "My Shared Circuit"
1746        );
1747    }
1748
1749    #[test]
1750    fn autogen_subregion_display_name_falls_back_for_untitled() {
1751        assert_eq!(
1752            autogen_subregion_display_name("Untitled"),
1753            "Autogen Circuit"
1754        );
1755        assert_eq!(
1756            autogen_subregion_display_name("untitled"),
1757            "Autogen Circuit"
1758        );
1759    }
1760
1761    #[test]
1762    fn autogen_subregion_display_name_falls_back_for_blank() {
1763        assert_eq!(autogen_subregion_display_name(""), "Autogen Circuit");
1764        assert_eq!(autogen_subregion_display_name("   "), "Autogen Circuit");
1765    }
1766
1767    #[test]
1768    fn order_regions_puts_parent_before_grandchild_even_when_child_is_listed_first() {
1769        let root = "root".to_string();
1770        let parent = "look-for-people".to_string();
1771        let grandchild = "wave".to_string();
1772        let sibling = "look-for-ball".to_string();
1773
1774        // HashMap-unlucky listing: grandchild before its parent.
1775        let remaining = vec![grandchild.clone(), sibling.clone(), parent.clone()];
1776        let mut parent_map = std::collections::HashMap::new();
1777        parent_map.insert(parent.clone(), root.clone());
1778        parent_map.insert(grandchild.clone(), parent.clone());
1779        parent_map.insert(sibling.clone(), root);
1780
1781        let ordered = order_regions_parent_before_child(&remaining, &parent_map);
1782        let parent_idx = ordered.iter().position(|id| id == &parent).unwrap();
1783        let grandchild_idx = ordered.iter().position(|id| id == &grandchild).unwrap();
1784
1785        assert_eq!(ordered.len(), 3);
1786        assert!(
1787            parent_idx < grandchild_idx,
1788            "parent must precede grandchild, got {:?}",
1789            ordered
1790        );
1791    }
1792
1793    #[test]
1794    fn order_regions_keeps_flat_children_when_parent_is_already_inserted() {
1795        let remaining = vec!["a".to_string(), "b".to_string(), "c".to_string()];
1796        let mut parent_map = std::collections::HashMap::new();
1797        parent_map.insert("a".to_string(), "root".to_string());
1798        parent_map.insert("b".to_string(), "root".to_string());
1799        parent_map.insert("c".to_string(), "root".to_string());
1800
1801        let ordered = order_regions_parent_before_child(&remaining, &parent_map);
1802        let mut sorted = ordered.clone();
1803        sorted.sort();
1804        assert_eq!(sorted, remaining);
1805    }
1806
1807    #[test]
1808    fn order_regions_appends_cycle_members_after_acyclic_prefix() {
1809        let remaining = vec!["a".to_string(), "b".to_string(), "ok".to_string()];
1810        let mut parent_map = std::collections::HashMap::new();
1811        parent_map.insert("a".to_string(), "b".to_string());
1812        parent_map.insert("b".to_string(), "a".to_string());
1813        parent_map.insert("ok".to_string(), "root".to_string());
1814
1815        let ordered = order_regions_parent_before_child(&remaining, &parent_map);
1816        assert_eq!(ordered.first().map(String::as_str), Some("ok"));
1817        assert_eq!(ordered.len(), 3);
1818        assert!(ordered.contains(&"a".to_string()));
1819        assert!(ordered.contains(&"b".to_string()));
1820    }
1821
1822    #[test]
1823    fn test_development_from_minimal_genome() {
1824        ConnectomeManager::reset_for_testing(); // Ensure clean state
1825        let manager = ConnectomeManager::instance();
1826        {
1827            let runtime = feagi_npu_runtime::StdRuntime;
1828            let backend = feagi_npu_burst_engine::backend::CPUBackend::new();
1829            let npu_result =
1830                feagi_npu_burst_engine::RustNPU::new(runtime, backend, 1_000_000, 10_000_000, 10)
1831                    .expect("Failed to create NPU");
1832            let npu = std::sync::Arc::new(feagi_npu_burst_engine::TracingMutex::new(
1833                feagi_npu_burst_engine::DynamicNPU::F32(npu_result),
1834                "minimal-genome-test-npu",
1835            ));
1836            manager.write().set_npu(npu);
1837        }
1838        let mut neuro = Neuroembryogenesis::new(manager.clone());
1839
1840        // Create a minimal genome with one cortical area
1841        let mut genome = create_genome_with_core_morphologies(
1842            "test_genome".to_string(),
1843            "Test Genome".to_string(),
1844        );
1845
1846        let cortical_id = CorticalID::try_from_bytes(b"cst_neur").unwrap(); // Use valid custom cortical ID
1847        let cortical_type = cortical_id
1848            .as_cortical_type()
1849            .expect("Failed to get cortical type");
1850        let area = CorticalArea::new(
1851            cortical_id,
1852            0,
1853            "Test Area".to_string(),
1854            CorticalAreaDimensions::new(10, 10, 10).unwrap(),
1855            (0, 0, 0).into(),
1856            cortical_type,
1857        )
1858        .expect("Failed to create cortical area");
1859        genome.cortical_areas.insert(cortical_id, area);
1860
1861        // Run neuroembryogenesis
1862        let result = neuro.develop_from_genome(&genome);
1863        assert!(result.is_ok(), "Development failed: {:?}", result);
1864
1865        // Check progress
1866        let progress = neuro.get_progress();
1867        assert_eq!(progress.stage, DevelopmentStage::Completed);
1868        assert_eq!(progress.progress, 100);
1869        assert_eq!(progress.cortical_areas_created, 1);
1870
1871        // Do not assert on ConnectomeManager::instance() contents here: other tests run in parallel
1872        // and share the same singleton; the progress fields above already reflect this run's outcome.
1873
1874        println!("✅ Development completed in {}ms", progress.duration_ms);
1875    }
1876}