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                            manager.sync_memory_associative_lif_params(area_id);
1326                            if let Ok(exec) = executor.lock() {
1327                                let lifecycle_config = crate::memory_lifecycle_config(&mem_props);
1328
1329                                let mp_mode =
1330                                    match crate::memory_mp_mode(&area.properties, &mem_props) {
1331                                        Ok(mode) => mode,
1332                                        Err(e) => {
1333                                            error!(
1334                                                target: "feagi-bdu",
1335                                                "Memory area {} not registered: {}",
1336                                                area_id.as_base_64(),
1337                                                e
1338                                            );
1339                                            continue;
1340                                        }
1341                                    };
1342                                exec.register_memory_area(
1343                                    area.cortical_idx,
1344                                    area_id.as_base_64(),
1345                                    mem_props.temporal_depth,
1346                                    upstream_areas.clone(),
1347                                    Some(lifecycle_config),
1348                                    mp_mode,
1349                                );
1350                                manager.configure_memory_scan_on_executor(&*exec, area_id);
1351
1352                                registered_count += 1;
1353                            }
1354                        }
1355                    }
1356                }
1357                let _ = registered_count; // count retained for future metrics if needed
1358            }
1359        }
1360
1361        // Mapping rules reach the manager only inside the loop above, so the eligibility of
1362        // reward-trained classifiers (derived from the circuit's answer delay) can only be
1363        // recomputed now. The earlier pass in corticogenesis finds no rules and skips.
1364        self.connectome_manager
1365            .write()
1366            .refresh_classifier_reward_eligibility();
1367
1368        // Verify against genome stats
1369        if expected_synapses > 0 {
1370            let diff = (total_synapses_created as i64 - expected_synapses as i64).abs();
1371            let diff_pct = (diff as f64 / expected_synapses.max(1) as f64) * 100.0;
1372
1373            if diff_pct > 10.0 {
1374                warn!(target: "feagi-bdu",
1375                    "Synapse count variance: created {} but genome stats expected {} ({:.1}% difference)",
1376                    total_synapses_created, expected_synapses, diff_pct
1377                );
1378            } else {
1379                info!(target: "feagi-bdu",
1380                    "Synapse count matches genome stats within {:.1}% ({} vs {})",
1381                    diff_pct, total_synapses_created, expected_synapses
1382                );
1383            }
1384        }
1385
1386        self.update_stage(DevelopmentStage::Synaptogenesis, 100);
1387        info!(target: "feagi-bdu","  ✅ Synaptogenesis complete: {} synapses created", total_synapses_created);
1388
1389        Ok(())
1390    }
1391
1392    fn rebuild_memory_twin_mappings_from_genome(
1393        &mut self,
1394        genome: &RuntimeGenome,
1395    ) -> BduResult<()> {
1396        use feagi_structures::genomic::cortical_area::CorticalAreaType;
1397        {
1398            let mut manager = self.connectome_manager.write();
1399            manager.purge_classifier_auto_twins()?;
1400        }
1401        let mut repaired = 0usize;
1402
1403        for (memory_id, memory_area) in genome.cortical_areas.iter() {
1404            let is_memory = matches!(
1405                memory_area.cortical_id.as_cortical_type(),
1406                Ok(CorticalAreaType::Memory(_))
1407            ) || memory_area
1408                .properties
1409                .get("is_mem_type")
1410                .and_then(|v| v.as_bool())
1411                .unwrap_or(false)
1412                || memory_area
1413                    .properties
1414                    .get("cortical_group")
1415                    .and_then(|v| v.as_str())
1416                    .is_some_and(|v| v.eq_ignore_ascii_case("MEMORY"));
1417            if !is_memory {
1418                continue;
1419            }
1420
1421            let Some(dstmap) = memory_area
1422                .properties
1423                .get("cortical_mapping_dst")
1424                .and_then(|v| v.as_object())
1425            else {
1426                continue;
1427            };
1428
1429            for (dst_id_str, rules) in dstmap {
1430                let Some(rule_array) = rules.as_array() else {
1431                    continue;
1432                };
1433                let has_twin_recall = rule_array.iter().any(|rule| {
1434                    matches!(
1435                        rule.get("morphology_id").and_then(|v| v.as_str()),
1436                        Some("memory_replay") | Some("episodic_memory")
1437                    )
1438                });
1439                if !has_twin_recall {
1440                    continue;
1441                }
1442
1443                let dst_id = match CorticalID::try_from_base_64(dst_id_str) {
1444                    Ok(id) => id,
1445                    Err(_) => {
1446                        warn!(
1447                            target: "feagi-bdu",
1448                            "Invalid twin cortical ID in memory_replay dstmap: {}",
1449                            dst_id_str
1450                        );
1451                        continue;
1452                    }
1453                };
1454
1455                let Some(twin_area) = genome.cortical_areas.get(&dst_id) else {
1456                    continue;
1457                };
1458                let owned_by_this_memory = ConnectomeManager::memory_owns_twin(
1459                    memory_id,
1460                    twin_area,
1461                    &genome.cortical_areas,
1462                );
1463                let legacy_replay = rule_array.iter().any(|rule| {
1464                    rule.get("morphology_id").and_then(|v| v.as_str()) == Some("memory_replay")
1465                });
1466                if !legacy_replay && !owned_by_this_memory {
1467                    continue;
1468                }
1469                let Some(upstream_id_str) = twin_area
1470                    .properties
1471                    .get("memory_twin_of")
1472                    .and_then(|v| v.as_str())
1473                else {
1474                    continue;
1475                };
1476                let upstream_id = match CorticalID::try_from_base_64(upstream_id_str) {
1477                    Ok(id) => id,
1478                    Err(_) => {
1479                        warn!(
1480                            target: "feagi-bdu",
1481                            "Invalid memory_twin_of value on twin area {}: {}",
1482                            dst_id.as_base_64(),
1483                            upstream_id_str
1484                        );
1485                        continue;
1486                    }
1487                };
1488
1489                let mut manager = self.connectome_manager.write();
1490                if manager.auto_memory_twin_forbidden(memory_id, Some(&dst_id)) {
1491                    continue;
1492                }
1493                // Index the saved twin first so ensure_memory_twin_area reuses it.
1494                if let Err(e) = manager.restore_memory_twin_index(memory_id, &upstream_id, &dst_id)
1495                {
1496                    warn!(
1497                        target: "feagi-bdu",
1498                        "Failed to restore memory twin index for memory {} twin {}: {}",
1499                        memory_id.as_base_64(),
1500                        dst_id.as_base_64(),
1501                        e
1502                    );
1503                    continue;
1504                }
1505                if let Err(e) = manager.ensure_memory_twin_area(memory_id, &upstream_id) {
1506                    warn!(
1507                        target: "feagi-bdu",
1508                        "Failed to rebuild memory twin mapping for memory {} upstream {}: {}",
1509                        memory_id.as_base_64(),
1510                        upstream_id.as_base_64(),
1511                        e
1512                    );
1513                    continue;
1514                }
1515                repaired += 1;
1516            }
1517        }
1518
1519        info!(
1520            target: "feagi-bdu",
1521            "Rebuilt {} memory twin mapping(s) from genome",
1522            repaired
1523        );
1524        Ok(())
1525    }
1526}
1527
1528/// Estimate synapse count for an area (fallback when NPU not connected)
1529///
1530/// This is only used when NPU is not available for actual synapse creation.
1531fn estimate_synapses_for_area(
1532    src_area: &CorticalArea,
1533    genome: &feagi_evolutionary::RuntimeGenome,
1534) -> usize {
1535    let dstmap = match src_area.properties.get("cortical_mapping_dst") {
1536        Some(serde_json::Value::Object(map)) => map,
1537        _ => return 0,
1538    };
1539
1540    let mut total = 0;
1541
1542    for (dst_id, rules) in dstmap {
1543        // Convert string dst_id to CorticalID for lookup
1544        let dst_cortical_id = match feagi_evolutionary::string_to_cortical_id(dst_id) {
1545            Ok(id) => id,
1546            Err(_) => continue,
1547        };
1548        let dst_area = match genome.cortical_areas.get(&dst_cortical_id) {
1549            Some(area) => area,
1550            None => continue,
1551        };
1552
1553        let rules_array = match rules.as_array() {
1554            Some(arr) => arr,
1555            None => continue,
1556        };
1557
1558        for rule in rules_array {
1559            let morphology_id = rule
1560                .get("morphology_id")
1561                .and_then(|v| v.as_str())
1562                .unwrap_or("unknown");
1563            let scalar = rule
1564                .get("morphology_scalar")
1565                .and_then(|v| v.as_i64())
1566                .unwrap_or(1) as usize;
1567
1568            // Simplified estimation
1569            let src_per_voxel = src_area
1570                .properties
1571                .get("neurons_per_voxel")
1572                .and_then(|v| v.as_u64())
1573                .unwrap_or(1) as usize;
1574            let dst_per_voxel = dst_area
1575                .properties
1576                .get("neurons_per_voxel")
1577                .and_then(|v| v.as_u64())
1578                .unwrap_or(1) as usize;
1579
1580            let src_voxels =
1581                src_area.dimensions.width * src_area.dimensions.height * src_area.dimensions.depth;
1582            let dst_voxels =
1583                dst_area.dimensions.width * dst_area.dimensions.height * dst_area.dimensions.depth;
1584
1585            let src_neurons = src_voxels as usize * src_per_voxel;
1586            let dst_neurons = dst_voxels as usize * dst_per_voxel as usize;
1587
1588            // Basic estimation by morphology type
1589            let count = match morphology_id {
1590                "block_to_block" => src_neurons * dst_per_voxel * scalar,
1591                "projector" | "transpose_xy" | "transpose_yz" | "transpose_xz"
1592                | "centered_projector" => src_neurons * dst_neurons * scalar,
1593                _ if morphology_id.contains("lateral") => src_neurons * scalar,
1594                _ => (src_neurons * scalar).min(src_neurons * dst_neurons / 10),
1595            };
1596
1597            total += count;
1598        }
1599    }
1600
1601    total
1602}
1603
1604impl Neuroembryogenesis {
1605    /// Calculate position for autogen region based on root region's bounding box
1606    fn calculate_autogen_region_position(
1607        root_area_ids: &[CorticalID],
1608        genome: &feagi_evolutionary::RuntimeGenome,
1609    ) -> [i32; 3] {
1610        if root_area_ids.is_empty() {
1611            return [100, 0, 0];
1612        }
1613
1614        let mut min_x = i32::MAX;
1615        let mut max_x = i32::MIN;
1616        let mut min_y = i32::MAX;
1617        let mut max_y = i32::MIN;
1618        let mut min_z = i32::MAX;
1619        let mut max_z = i32::MIN;
1620
1621        for cortical_id in root_area_ids {
1622            if let Some(area) = genome.cortical_areas.get(cortical_id) {
1623                let pos: (i32, i32, i32) = area.position.into();
1624                let dims = (
1625                    area.dimensions.width as i32,
1626                    area.dimensions.height as i32,
1627                    area.dimensions.depth as i32,
1628                );
1629
1630                min_x = min_x.min(pos.0);
1631                max_x = max_x.max(pos.0 + dims.0);
1632                min_y = min_y.min(pos.1);
1633                max_y = max_y.max(pos.1 + dims.1);
1634                min_z = min_z.min(pos.2);
1635                max_z = max_z.max(pos.2 + dims.2);
1636            }
1637        }
1638
1639        let bbox_width = (max_x - min_x).max(1);
1640        let padding = (bbox_width / 5).max(50);
1641        let autogen_x = max_x + padding;
1642        let autogen_y = (min_y + max_y) / 2;
1643        let autogen_z = (min_z + max_z) / 2;
1644
1645        info!(target: "feagi-bdu",
1646              "  📐 Autogen position: ({}, {}, {}) [padding: {}]",
1647              autogen_x, autogen_y, autogen_z, padding);
1648
1649        [autogen_x, autogen_y, autogen_z]
1650    }
1651
1652    /// Analyze region inputs/outputs based on cortical connections
1653    ///
1654    /// Following Python's _auto_assign_region_io() logic:
1655    /// - OUTPUT: Any area in the region that connects to an area OUTSIDE the region
1656    /// - INPUT: Any area in the region that receives connection from OUTSIDE the region
1657    fn analyze_region_io(
1658        region_area_ids: &[feagi_structures::genomic::cortical_area::CorticalID],
1659        all_cortical_areas: &std::collections::HashMap<CorticalID, CorticalArea>,
1660    ) -> (Vec<String>, Vec<String>) {
1661        let area_set: std::collections::HashSet<_> = region_area_ids.iter().cloned().collect();
1662        let mut inputs = Vec::new();
1663        let mut outputs = Vec::new();
1664
1665        // Helper to extract destination area IDs from cortical_mapping_dst (as strings)
1666        let extract_destinations = |area: &CorticalArea| -> Vec<String> {
1667            area.properties
1668                .get("cortical_mapping_dst")
1669                .and_then(|v| v.as_object())
1670                .map(|obj| obj.keys().cloned().collect())
1671                .unwrap_or_default()
1672        };
1673
1674        // Find OUTPUTS: areas in region that connect to areas OUTSIDE region
1675        for area_id in region_area_ids {
1676            if let Some(area) = all_cortical_areas.get(area_id) {
1677                let destinations = extract_destinations(area);
1678                // Convert destination strings to CorticalID for comparison
1679                let external_destinations: Vec<_> = destinations
1680                    .iter()
1681                    .filter_map(|dest| feagi_evolutionary::string_to_cortical_id(dest).ok())
1682                    .filter(|dest_id| !area_set.contains(dest_id))
1683                    .collect();
1684
1685                if !external_destinations.is_empty() {
1686                    outputs.push(area_id.as_base_64());
1687                }
1688            }
1689        }
1690
1691        // Find INPUTS: areas in region receiving connections from OUTSIDE region
1692        for (source_area_id, source_area) in all_cortical_areas.iter() {
1693            // Skip areas that are inside the region
1694            if area_set.contains(source_area_id) {
1695                continue;
1696            }
1697
1698            let destinations = extract_destinations(source_area);
1699            for dest_str in destinations {
1700                if let Ok(dest_id) = feagi_evolutionary::string_to_cortical_id(&dest_str) {
1701                    if area_set.contains(&dest_id) {
1702                        let dest_string = dest_id.as_base_64();
1703                        if !inputs.contains(&dest_string) {
1704                            inputs.push(dest_string);
1705                        }
1706                    }
1707                }
1708            }
1709        }
1710
1711        (inputs, outputs)
1712    }
1713
1714    /// Update development stage
1715    fn update_stage(&self, stage: DevelopmentStage, progress: u8) {
1716        let mut p = self.progress.write();
1717        p.stage = stage;
1718        p.progress = progress;
1719        p.duration_ms = self.start_time.elapsed().as_millis() as u64;
1720    }
1721
1722    /// Update progress with a closure
1723    fn update_progress<F>(&self, f: F)
1724    where
1725        F: FnOnce(&mut DevelopmentProgress),
1726    {
1727        let mut p = self.progress.write();
1728        f(&mut p);
1729        p.duration_ms = self.start_time.elapsed().as_millis() as u64;
1730    }
1731}
1732
1733#[cfg(test)]
1734mod tests {
1735    use super::*;
1736    use feagi_evolutionary::create_genome_with_core_morphologies;
1737    use feagi_structures::genomic::cortical_area::CorticalAreaDimensions;
1738
1739    #[test]
1740    fn test_neuroembryogenesis_creation() {
1741        let manager = ConnectomeManager::instance();
1742        let neuro = Neuroembryogenesis::new(manager);
1743
1744        let progress = neuro.get_progress();
1745        assert_eq!(progress.stage, DevelopmentStage::Initialization);
1746        assert_eq!(progress.progress, 0);
1747    }
1748
1749    #[test]
1750    fn autogen_subregion_display_name_uses_title_when_meaningful() {
1751        assert_eq!(
1752            autogen_subregion_display_name("My Shared Circuit"),
1753            "My Shared Circuit"
1754        );
1755    }
1756
1757    #[test]
1758    fn autogen_subregion_display_name_falls_back_for_untitled() {
1759        assert_eq!(
1760            autogen_subregion_display_name("Untitled"),
1761            "Autogen Circuit"
1762        );
1763        assert_eq!(
1764            autogen_subregion_display_name("untitled"),
1765            "Autogen Circuit"
1766        );
1767    }
1768
1769    #[test]
1770    fn autogen_subregion_display_name_falls_back_for_blank() {
1771        assert_eq!(autogen_subregion_display_name(""), "Autogen Circuit");
1772        assert_eq!(autogen_subregion_display_name("   "), "Autogen Circuit");
1773    }
1774
1775    #[test]
1776    fn order_regions_puts_parent_before_grandchild_even_when_child_is_listed_first() {
1777        let root = "root".to_string();
1778        let parent = "look-for-people".to_string();
1779        let grandchild = "wave".to_string();
1780        let sibling = "look-for-ball".to_string();
1781
1782        // HashMap-unlucky listing: grandchild before its parent.
1783        let remaining = vec![grandchild.clone(), sibling.clone(), parent.clone()];
1784        let mut parent_map = std::collections::HashMap::new();
1785        parent_map.insert(parent.clone(), root.clone());
1786        parent_map.insert(grandchild.clone(), parent.clone());
1787        parent_map.insert(sibling.clone(), root);
1788
1789        let ordered = order_regions_parent_before_child(&remaining, &parent_map);
1790        let parent_idx = ordered.iter().position(|id| id == &parent).unwrap();
1791        let grandchild_idx = ordered.iter().position(|id| id == &grandchild).unwrap();
1792
1793        assert_eq!(ordered.len(), 3);
1794        assert!(
1795            parent_idx < grandchild_idx,
1796            "parent must precede grandchild, got {:?}",
1797            ordered
1798        );
1799    }
1800
1801    #[test]
1802    fn order_regions_keeps_flat_children_when_parent_is_already_inserted() {
1803        let remaining = vec!["a".to_string(), "b".to_string(), "c".to_string()];
1804        let mut parent_map = std::collections::HashMap::new();
1805        parent_map.insert("a".to_string(), "root".to_string());
1806        parent_map.insert("b".to_string(), "root".to_string());
1807        parent_map.insert("c".to_string(), "root".to_string());
1808
1809        let ordered = order_regions_parent_before_child(&remaining, &parent_map);
1810        let mut sorted = ordered.clone();
1811        sorted.sort();
1812        assert_eq!(sorted, remaining);
1813    }
1814
1815    #[test]
1816    fn order_regions_appends_cycle_members_after_acyclic_prefix() {
1817        let remaining = vec!["a".to_string(), "b".to_string(), "ok".to_string()];
1818        let mut parent_map = std::collections::HashMap::new();
1819        parent_map.insert("a".to_string(), "b".to_string());
1820        parent_map.insert("b".to_string(), "a".to_string());
1821        parent_map.insert("ok".to_string(), "root".to_string());
1822
1823        let ordered = order_regions_parent_before_child(&remaining, &parent_map);
1824        assert_eq!(ordered.first().map(String::as_str), Some("ok"));
1825        assert_eq!(ordered.len(), 3);
1826        assert!(ordered.contains(&"a".to_string()));
1827        assert!(ordered.contains(&"b".to_string()));
1828    }
1829
1830    #[test]
1831    fn test_development_from_minimal_genome() {
1832        ConnectomeManager::reset_for_testing(); // Ensure clean state
1833        let manager = ConnectomeManager::instance();
1834        {
1835            let runtime = feagi_npu_runtime::StdRuntime;
1836            let backend = feagi_npu_burst_engine::backend::CPUBackend::new();
1837            let npu_result =
1838                feagi_npu_burst_engine::RustNPU::new(runtime, backend, 1_000_000, 10_000_000, 10)
1839                    .expect("Failed to create NPU");
1840            let npu = std::sync::Arc::new(feagi_npu_burst_engine::TracingMutex::new(
1841                feagi_npu_burst_engine::DynamicNPU::F32(npu_result),
1842                "minimal-genome-test-npu",
1843            ));
1844            manager.write().set_npu(npu);
1845        }
1846        let mut neuro = Neuroembryogenesis::new(manager.clone());
1847
1848        // Create a minimal genome with one cortical area
1849        let mut genome = create_genome_with_core_morphologies(
1850            "test_genome".to_string(),
1851            "Test Genome".to_string(),
1852        );
1853
1854        let cortical_id = CorticalID::try_from_bytes(b"cst_neur").unwrap(); // Use valid custom cortical ID
1855        let cortical_type = cortical_id
1856            .as_cortical_type()
1857            .expect("Failed to get cortical type");
1858        let area = CorticalArea::new(
1859            cortical_id,
1860            0,
1861            "Test Area".to_string(),
1862            CorticalAreaDimensions::new(10, 10, 10).unwrap(),
1863            (0, 0, 0).into(),
1864            cortical_type,
1865        )
1866        .expect("Failed to create cortical area");
1867        genome.cortical_areas.insert(cortical_id, area);
1868
1869        // Run neuroembryogenesis
1870        let result = neuro.develop_from_genome(&genome);
1871        assert!(result.is_ok(), "Development failed: {:?}", result);
1872
1873        // Check progress
1874        let progress = neuro.get_progress();
1875        assert_eq!(progress.stage, DevelopmentStage::Completed);
1876        assert_eq!(progress.progress, 100);
1877        assert_eq!(progress.cortical_areas_created, 1);
1878
1879        // Do not assert on ConnectomeManager::instance() contents here: other tests run in parallel
1880        // and share the same singleton; the progress fields above already reflect this run's outcome.
1881
1882        println!("✅ Development completed in {}ms", progress.duration_ms);
1883    }
1884
1885    /// Genome load must refresh a reward-trained classifier's stored eligibility: the mapping
1886    /// rules only exist once synaptogenesis has run.
1887    #[test]
1888    fn genome_load_refreshes_classifier_reward_eligibility() {
1889        use feagi_structures::genomic::classifiers::Classifier;
1890        use feagi_structures::genomic::cortical_area::{CorticalAreaType, MemoryCorticalType};
1891
1892        let runtime = feagi_npu_runtime::StdRuntime;
1893        let backend = feagi_npu_burst_engine::backend::CPUBackend::new();
1894        let npu = feagi_npu_burst_engine::RustNPU::new(runtime, backend, 100_000, 100_000, 10)
1895            .expect("Failed to create NPU");
1896        let npu = std::sync::Arc::new(feagi_npu_burst_engine::TracingMutex::new(
1897            feagi_npu_burst_engine::DynamicNPU::F32(npu),
1898            "eligibility-load-test-npu",
1899        ));
1900        let manager = Arc::new(RwLock::new(ConnectomeManager::new_for_testing_with_npu(
1901            npu.clone(),
1902        )));
1903        let mut neuro = Neuroembryogenesis::new(manager.clone());
1904
1905        let mut genome = create_genome_with_core_morphologies(
1906            "elig_genome".to_string(),
1907            "Elig Genome".to_string(),
1908        );
1909        let memory_area = |bytes: &[u8; 8], name: &str| {
1910            let mut area = CorticalArea::new(
1911                CorticalID::try_from_bytes(bytes).unwrap(),
1912                0,
1913                name.to_string(),
1914                CorticalAreaDimensions::new(1, 1, 1).unwrap(),
1915                (0, 0, 0).into(),
1916                CorticalAreaType::Memory(MemoryCorticalType::Memory),
1917            )
1918            .unwrap();
1919            area.properties
1920                .insert("is_mem_type".to_string(), serde_json::json!(true));
1921            area
1922        };
1923        let mut sample = memory_area(b"melgsmp1", "sample");
1924        let class_mem = memory_area(b"melgcls1", "class");
1925        let (sample_id, class_id) = (sample.cortical_id, class_mem.cortical_id);
1926        sample.properties.insert(
1927            "cortical_mapping_dst".to_string(),
1928            serde_json::json!({ class_id.as_base_64(): [{
1929                "morphology_id": "associative_memory",
1930                "plasticity_flag": true,
1931                "plasticity_mode": "rstdp",
1932                "modulators": [],
1933                "eligibility_decay_bursts": 4,
1934                "plasticity_constant": 1,
1935                "ltp_multiplier": 1,
1936                "ltd_multiplier": 1,
1937                "plasticity_window": 4
1938            }]}),
1939        );
1940        genome.cortical_areas.insert(sample_id, sample);
1941        genome.cortical_areas.insert(class_id, class_mem);
1942        genome.classifiers.insert(
1943            "clf-elig".to_string(),
1944            Classifier {
1945                classifier_id: "clf-elig".to_string(),
1946                name: "elig".to_string(),
1947                parent_region_id: "root".to_string(),
1948                coordinates_3d: [0, 0, 0],
1949                sample_area_ids: Vec::new(),
1950                class_bindings: Vec::new(),
1951                sample_memory_id: sample_id.as_base_64(),
1952                class_memory_id: class_id.as_base_64(),
1953                error_area_id: "err".to_string(),
1954                reward_training: true,
1955                answer_feedback_area_id: None,
1956                correct_area_id: String::new(),
1957                reward_modulator_ids: Vec::new(),
1958                answer_latency_bursts: 0,
1959                learn_area_id: None,
1960                confidence_area_id: None,
1961                properties: std::collections::HashMap::new(),
1962            },
1963        );
1964
1965        neuro.develop_from_genome(&genome).expect("load failed");
1966
1967        let guard = manager.read();
1968        let stored = guard.get_mapping_rules(&sample_id, &class_id).unwrap()[0]
1969            ["eligibility_decay_bursts"]
1970            .as_u64()
1971            .unwrap();
1972        // Default circuit answer delay 3 gives eligibility 5.
1973        assert_eq!(stored, 5, "stored rule must follow the circuit on load");
1974        let params = npu.lock().unwrap().stdp_mapping_params(
1975            guard.get_cortical_area(&sample_id).unwrap().cortical_idx,
1976            guard.get_cortical_area(&class_id).unwrap().cortical_idx,
1977        );
1978        if let Some(params) = params {
1979            assert_eq!(params.eligibility_decay_bursts, 5);
1980        }
1981    }
1982}