Skip to main content

feagi_brain_development/
connectome_manager.rs

1// Copyright 2025 Neuraville Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4/*!
5ConnectomeManager - Core brain connectivity manager.
6
7This is the central orchestrator for the FEAGI connectome, managing:
8- Cortical areas and their metadata
9- Brain regions and hierarchy
10- Neuron/synapse queries (delegates to NPU for actual data)
11- Genome loading and persistence
12
13## Architecture
14
15The ConnectomeManager is a **metadata manager** that:
161. Stores cortical area/region definitions
172. Provides a high-level API for brain structure queries
183. Delegates neuron/synapse CRUD to the NPU (Structure of Arrays)
19
20## Design Principles
21
22- **Singleton**: One global instance per FEAGI process
23- **Thread-safe**: Uses RwLock for concurrent reads
24- **Performance**: Optimized for hot-path queries (area lookups)
25- **NPU Delegation**: Neuron/synapse data lives in NPU, not here
26
27Copyright 2025 Neuraville Inc.
28Licensed under the Apache License, Version 2.0
29*/
30
31use once_cell::sync::Lazy;
32use parking_lot::RwLock;
33use serde::{Deserialize, Serialize};
34use std::collections::{HashMap, HashSet};
35use std::hash::Hasher;
36use std::sync::atomic::{AtomicUsize, Ordering};
37use std::sync::{Arc, Mutex};
38use tracing::{debug, error, info, trace, warn};
39use xxhash_rust::xxh64::Xxh64;
40
41/// Merged region `inputs` / `outputs` (base64 cortical IDs) after `recompute_brain_region_io_registry`.
42pub type BrainRegionIoRegistry = HashMap<String, (Vec<String>, Vec<String>)>;
43
44use crate::models::{BrainRegion, BrainRegionHierarchy, CorticalArea, CorticalAreaDimensions};
45use crate::types::{BduError, BduResult};
46use feagi_npu_neural::synapse::SYNAPSE_EDGE_ASSOCIATIVE_MEMORY;
47use feagi_npu_neural::types::NeuronId;
48use feagi_structures::genomic::cortical_area::{
49    CoreCorticalType, CorticalAreaType, CorticalID, CustomCorticalType,
50};
51use feagi_structures::genomic::descriptors::GenomeCoordinate3D;
52
53// State manager access for fatigue calculation
54// Note: feagi-state-manager is always available when std is enabled (it's a default feature)
55use feagi_state_manager::StateManager;
56
57const DATA_HASH_SEED: u64 = 0;
58// JSON number precision (Godot) is limited to 53 bits; mask to keep hashes stable across transports.
59const HASH_SAFE_MASK: u64 = (1u64 << 53) - 1;
60
61// NPU integration (optional dependency)
62// use feagi_npu_burst_engine::RustNPU; // Now using DynamicNPU
63
64/// Global singleton instance of ConnectomeManager
65static INSTANCE: Lazy<Arc<RwLock<ConnectomeManager>>> =
66    Lazy::new(|| Arc::new(RwLock::new(ConnectomeManager::new())));
67
68/// Configuration for ConnectomeManager
69#[derive(Debug, Clone, Serialize, Deserialize)]
70pub struct ConnectomeConfig {
71    /// Maximum number of neurons (for NPU sizing)
72    pub max_neurons: usize,
73
74    /// Maximum number of synapses (for NPU sizing)
75    pub max_synapses: usize,
76
77    /// Backend type ("cpu", "cuda", "wgpu")
78    pub backend: String,
79}
80
81impl Default for ConnectomeConfig {
82    fn default() -> Self {
83        Self {
84            max_neurons: 10_000_000,
85            max_synapses: 100_000_000,
86            backend: "cpu".to_string(),
87        }
88    }
89}
90
91/// One-call diagnostic for memory twin creation/health on a mapping pair.
92#[derive(Debug, Clone, Serialize, Deserialize)]
93pub struct MemoryTwinDiagnostic {
94    pub src_cortical_area: String,
95    pub dst_cortical_area: String,
96    pub src_cortical_type: String,
97    pub dst_cortical_type: String,
98    pub mapping_exists: bool,
99    pub episodic_rule_count: usize,
100    pub twin_expected: bool,
101    pub twin_present: bool,
102    pub twin_cortical_area: Option<String>,
103    pub reason: Option<String>,
104    pub src_parent_region_id: Option<String>,
105    pub dst_parent_region_id: Option<String>,
106    pub twin_parent_region_id: Option<String>,
107    pub twin_parent_matches_src_parent: Option<bool>,
108}
109
110/// Central manager for the FEAGI connectome
111///
112/// ## Responsibilities
113///
114/// 1. **Cortical Area Management**: Add, remove, query cortical areas
115/// 2. **Brain Region Management**: Hierarchical organization
116/// 3. **Neuron/Synapse Queries**: High-level API (delegates to NPU)
117/// 4. **Genome I/O**: Load/save brain structure
118///
119/// ## Data Storage
120///
121/// - **Cortical areas**: Stored in HashMap for O(1) lookup
122/// - **Brain regions**: Stored in BrainRegionHierarchy
123/// - **Neuron data**: Lives in NPU (not stored here)
124/// - **Synapse data**: Lives in NPU (not stored here)
125///
126/// ## Thread Safety
127///
128/// Uses `RwLock` for concurrent reads with exclusive writes.
129/// Multiple threads can read simultaneously, but writes block.
130///
131pub struct ConnectomeManager {
132    /// Map of cortical_id -> CorticalArea metadata
133    cortical_areas: HashMap<CorticalID, CorticalArea>,
134
135    /// Map of cortical_id -> cortical_idx (fast reverse lookup)
136    cortical_id_to_idx: HashMap<CorticalID, u32>,
137
138    /// Map of cortical_idx -> cortical_id (fast reverse lookup)
139    cortical_idx_to_id: HashMap<u32, CorticalID>,
140
141    /// Next available cortical index
142    next_cortical_idx: u32,
143
144    /// Brain region hierarchy
145    brain_regions: BrainRegionHierarchy,
146
147    /// Morphology registry from loaded genome
148    morphology_registry: feagi_evolutionary::MorphologyRegistry,
149
150    /// Configuration
151    config: ConnectomeConfig,
152
153    /// Optional reference to the Rust NPU for neuron/synapse queries
154    ///
155    /// This is set by the Python process manager after NPU initialization.
156    /// All neuron/synapse data queries delegate to the NPU.
157    /// Wrapped in TracingMutex to automatically log all lock acquisitions
158    npu: Option<Arc<feagi_npu_burst_engine::TracingMutex<feagi_npu_burst_engine::DynamicNPU>>>,
159
160    /// Plasticity executor reference (optional, only when plasticity feature is enabled)
161    #[cfg(feature = "plasticity")]
162    plasticity_executor:
163        Option<Arc<std::sync::Mutex<feagi_npu_plasticity::AsyncPlasticityExecutor>>>,
164
165    /// Cached neuron count (lock-free read) - updated by burst engine
166    /// This prevents health checks from blocking on NPU lock
167    cached_neuron_count: Arc<AtomicUsize>,
168
169    /// Cached synapse count (lock-free read) - updated by burst engine
170    /// This prevents health checks from blocking on NPU lock
171    cached_synapse_count: Arc<AtomicUsize>,
172
173    /// Per-area neuron count cache (lock-free reads) - updated when neurons are created/deleted
174    /// This prevents health checks from blocking on NPU lock
175    cached_neuron_counts_per_area: Arc<RwLock<HashMap<CorticalID, AtomicUsize>>>,
176
177    /// Per-area synapse count cache (lock-free reads) - updated when synapses are created/deleted
178    /// This prevents health checks from blocking on NPU lock
179    cached_synapse_counts_per_area: Arc<RwLock<HashMap<CorticalID, AtomicUsize>>>,
180
181    /// Is the connectome initialized (has cortical areas)?
182    initialized: bool,
183
184    /// Last fatigue index calculation time (for rate limiting)
185    last_fatigue_calculation: Arc<Mutex<std::time::Instant>>,
186}
187
188/// Type alias for neuron batch data: (x, y, z, threshold, threshold_limit, leak, resting, neuron_type, refractory_period, excitability, consecutive_fire_limit, snooze_period, mp_charge_accumulation)
189type NeuronData = (
190    u32,
191    u32,
192    u32,
193    f32,
194    f32,
195    f32,
196    f32,
197    i32,
198    u16,
199    f32,
200    u16,
201    u16,
202    bool,
203);
204
205impl ConnectomeManager {
206    fn get_mapping_rules_for_destination<'a>(
207        mapping_dst: &'a serde_json::Map<String, serde_json::Value>,
208        dst_area_id: &CorticalID,
209    ) -> Option<&'a Vec<serde_json::Value>> {
210        if let Some(rules) = mapping_dst
211            .get(&dst_area_id.as_base_64())
212            .and_then(|value| value.as_array())
213        {
214            return Some(rules);
215        }
216
217        // Compatibility path: some legacy genomes may still store destination IDs
218        // as 6/8-char ASCII keys instead of base64. Resolve by semantic ID equality.
219        for (raw_dst_key, rules_value) in mapping_dst {
220            let parsed_dst = CorticalID::try_from_base_64(raw_dst_key)
221                .or_else(|_| CorticalID::try_from_legacy_ascii(raw_dst_key));
222            if parsed_dst.as_ref().ok() != Some(dst_area_id) {
223                continue;
224            }
225            if let Some(rules) = rules_value.as_array() {
226                return Some(rules);
227            }
228        }
229
230        None
231    }
232
233    /// Create a new ConnectomeManager (private - use `instance()`)
234    fn new() -> Self {
235        Self {
236            cortical_areas: HashMap::new(),
237            cortical_id_to_idx: HashMap::new(),
238            cortical_idx_to_id: HashMap::new(),
239            // CRITICAL: Reserve indices for invariant core areas (0..=6).
240            next_cortical_idx: 7, // Reserve 0=_death, 1=_power, 2=_fatigue, 3=_pain, 4=_pleasure, 5=_fear, 6=_hope
241            brain_regions: BrainRegionHierarchy::new(),
242            morphology_registry: feagi_evolutionary::MorphologyRegistry::new(),
243            config: ConnectomeConfig::default(),
244            npu: None,
245            #[cfg(feature = "plasticity")]
246            plasticity_executor: None,
247            cached_neuron_count: Arc::new(AtomicUsize::new(0)),
248            cached_synapse_count: Arc::new(AtomicUsize::new(0)),
249            cached_neuron_counts_per_area: Arc::new(RwLock::new(HashMap::new())),
250            cached_synapse_counts_per_area: Arc::new(RwLock::new(HashMap::new())),
251            initialized: false,
252            last_fatigue_calculation: Arc::new(Mutex::new(
253                std::time::Instant::now() - std::time::Duration::from_secs(10),
254            )), // Initialize to allow first calculation
255        }
256    }
257
258    /// Get the global singleton instance
259    ///
260    /// # Returns
261    ///
262    /// Arc to the ConnectomeManager wrapped in RwLock
263    ///
264    /// # Example
265    ///
266    /// ```ignore
267    /// use feagi_brain_development::ConnectomeManager;
268    ///
269    /// let manager = ConnectomeManager::instance();
270    /// let read_lock = manager.read();
271    /// let area_count = read_lock.get_cortical_area_count();
272    /// ```
273    ///
274    pub fn instance() -> Arc<RwLock<ConnectomeManager>> {
275        // Note: Singleton is always f32 for backward compatibility
276        // New code should use ConnectomeManager::<T>::new_for_testing_with_npu() for custom types
277        Arc::clone(&*INSTANCE)
278    }
279
280    /// Calculate optimal visualization voxel granularity for a cortical area
281    ///
282    /// This function determines the granularity for aggregated rendering based on:
283    /// - Total voxel count (larger areas get larger chunks)
284    /// - Aspect ratio (handles thin dimensions like 1024×900×3)
285    /// - Target chunk count (~2k-10k chunks for manageable message size)
286    ///
287    /// # Arguments
288    ///
289    /// * `dimensions` - The cortical area dimensions (width, height, depth)
290    ///
291    /// # Returns
292    ///
293    /// Tuple of (chunk_x, chunk_y, chunk_z) that divides evenly into dimensions
294    ///
295    ///
296    /// Create a new isolated instance for testing
297    ///
298    /// This bypasses the singleton pattern and creates a fresh instance.
299    /// Use this in tests to avoid conflicts between parallel test runs.
300    ///
301    /// # Example
302    ///
303    /// ```rust
304    /// let manager = ConnectomeManager::new_for_testing();
305    /// // Use manager in isolated test
306    /// ```
307    pub fn new_for_testing() -> Self {
308        Self {
309            cortical_areas: HashMap::new(),
310            cortical_id_to_idx: HashMap::new(),
311            cortical_idx_to_id: HashMap::new(),
312            next_cortical_idx: 0,
313            brain_regions: BrainRegionHierarchy::new(),
314            morphology_registry: feagi_evolutionary::MorphologyRegistry::new(),
315            config: ConnectomeConfig::default(),
316            npu: None,
317            #[cfg(feature = "plasticity")]
318            plasticity_executor: None,
319            cached_neuron_count: Arc::new(AtomicUsize::new(0)),
320            cached_synapse_count: Arc::new(AtomicUsize::new(0)),
321            cached_neuron_counts_per_area: Arc::new(RwLock::new(HashMap::new())),
322            cached_synapse_counts_per_area: Arc::new(RwLock::new(HashMap::new())),
323            initialized: false,
324            last_fatigue_calculation: Arc::new(Mutex::new(
325                std::time::Instant::now() - std::time::Duration::from_secs(10),
326            )),
327        }
328    }
329
330    /// Create a new isolated instance for testing with NPU
331    ///
332    /// This bypasses the singleton pattern and creates a fresh instance with NPU connected.
333    /// Use this in tests to avoid conflicts between parallel test runs.
334    ///
335    /// # Arguments
336    ///
337    /// * `npu` - Arc<TracingMutex<DynamicNPU>> to connect to this manager
338    ///
339    /// # Example
340    ///
341    /// ```rust
342    /// let npu = Arc::new(TracingMutex::new(RustNPU::new(1_000_000, 10_000_000, 10), "NPU"));
343    /// let manager = ConnectomeManager::new_for_testing_with_npu(npu);
344    /// ```
345    pub fn new_for_testing_with_npu(
346        npu: Arc<feagi_npu_burst_engine::TracingMutex<feagi_npu_burst_engine::DynamicNPU>>,
347    ) -> Self {
348        Self {
349            cortical_areas: HashMap::new(),
350            cortical_id_to_idx: HashMap::new(),
351            cortical_idx_to_id: HashMap::new(),
352            next_cortical_idx: 7,
353            brain_regions: BrainRegionHierarchy::new(),
354            morphology_registry: feagi_evolutionary::MorphologyRegistry::new(),
355            config: ConnectomeConfig::default(),
356            npu: Some(npu),
357            #[cfg(feature = "plasticity")]
358            plasticity_executor: None,
359            cached_neuron_count: Arc::new(AtomicUsize::new(0)),
360            cached_synapse_count: Arc::new(AtomicUsize::new(0)),
361            cached_neuron_counts_per_area: Arc::new(RwLock::new(HashMap::new())),
362            cached_synapse_counts_per_area: Arc::new(RwLock::new(HashMap::new())),
363            initialized: false,
364            last_fatigue_calculation: Arc::new(Mutex::new(
365                std::time::Instant::now() - std::time::Duration::from_secs(10),
366            )),
367        }
368    }
369
370    /// Set up core morphologies in the registry (for testing only)
371    ///
372    /// This is a test helper to set up core morphologies (projector, block_to_block, etc.)
373    /// in the morphology registry so that synaptogenesis tests can run.
374    ///
375    /// # Note
376    ///
377    /// This should only be called in tests. Morphologies are typically loaded from genome files.
378    /// This method is public to allow integration tests to access it.
379    pub fn setup_core_morphologies_for_testing(&mut self) {
380        feagi_evolutionary::add_core_morphologies(&mut self.morphology_registry);
381    }
382
383    /// Reset the singleton (for testing only)
384    ///
385    /// # Safety
386    ///
387    /// This should only be called in tests to reset state between test runs.
388    /// Calling this in production code will cause all references to the old
389    /// instance to become stale.
390    ///
391    #[cfg(test)]
392    pub fn reset_for_testing() {
393        let mut instance = INSTANCE.write();
394        *instance = Self::new();
395    }
396
397    // ======================================================================
398    // Data Hashing (event-driven updates for health_check)
399    // ======================================================================
400
401    /// Update stored hashes for data types that have changed.
402    fn update_state_hashes(
403        &self,
404        brain_regions: Option<u64>,
405        cortical_areas: Option<u64>,
406        brain_geometry: Option<u64>,
407        morphologies: Option<u64>,
408        cortical_mappings: Option<u64>,
409    ) {
410        let state_manager = StateManager::instance();
411        let state_manager = state_manager.read();
412        if let Some(value) = brain_regions {
413            state_manager.set_brain_regions_hash(value);
414        }
415        if let Some(value) = cortical_areas {
416            state_manager.set_cortical_areas_hash(value);
417        }
418        if let Some(value) = brain_geometry {
419            state_manager.set_brain_geometry_hash(value);
420        }
421        if let Some(value) = morphologies {
422            state_manager.set_morphologies_hash(value);
423        }
424        if let Some(value) = cortical_mappings {
425            state_manager.set_cortical_mappings_hash(value);
426        }
427    }
428
429    /// Refresh the brain regions hash (hierarchy, membership, and properties).
430    fn refresh_brain_regions_hash(&self) {
431        let hash = self.compute_brain_regions_hash();
432        self.update_state_hashes(Some(hash), None, None, None, None);
433    }
434
435    #[allow(dead_code)]
436    /// Refresh the cortical areas hash (metadata and properties).
437    fn refresh_cortical_areas_hash(&self) {
438        let hash = self.compute_cortical_areas_hash();
439        self.update_state_hashes(None, Some(hash), None, None, None);
440    }
441
442    #[allow(dead_code)]
443    /// Refresh the brain geometry hash (positions, dimensions, 2D coordinates).
444    fn refresh_brain_geometry_hash(&self) {
445        let hash = self.compute_brain_geometry_hash();
446        self.update_state_hashes(None, None, Some(hash), None, None);
447    }
448
449    /// Refresh the morphologies hash.
450    fn refresh_morphologies_hash(&self) {
451        let hash = self.compute_morphologies_hash();
452        self.update_state_hashes(None, None, None, Some(hash), None);
453    }
454
455    /// Refresh the cortical mappings hash.
456    pub fn refresh_cortical_mappings_hash(&self) {
457        let hash = self.compute_cortical_mappings_hash();
458        self.update_state_hashes(None, None, None, None, Some(hash));
459    }
460
461    /// Recompute every connectome hash published on health_check.
462    ///
463    /// Connectome import replaces areas/regions/mappings in place, which does not
464    /// go through add/remove helpers. Brain Visualizer polls these hashes.
465    pub fn refresh_all_connectome_hashes(&self) {
466        self.update_state_hashes(
467            Some(self.compute_brain_regions_hash()),
468            Some(self.compute_cortical_areas_hash()),
469            Some(self.compute_brain_geometry_hash()),
470            Some(self.compute_morphologies_hash()),
471            Some(self.compute_cortical_mappings_hash()),
472        );
473    }
474
475    /// Refresh cortical area-related hashes based on the affected data.
476    pub fn refresh_cortical_area_hashes(&self, properties_changed: bool, geometry_changed: bool) {
477        let cortical_hash = if properties_changed {
478            Some(self.compute_cortical_areas_hash())
479        } else {
480            None
481        };
482        let geometry_hash = if geometry_changed {
483            Some(self.compute_brain_geometry_hash())
484        } else {
485            None
486        };
487        self.update_state_hashes(None, cortical_hash, geometry_hash, None, None);
488    }
489
490    /// Compute hash for brain regions (hierarchy, membership, and properties).
491    fn compute_brain_regions_hash(&self) -> u64 {
492        let mut hasher = Xxh64::new(DATA_HASH_SEED);
493        let mut region_ids: Vec<String> = self
494            .brain_regions
495            .get_all_region_ids()
496            .into_iter()
497            .cloned()
498            .collect();
499        region_ids.sort();
500
501        for region_id in region_ids {
502            let Some(region) = self.brain_regions.get_region(&region_id) else {
503                continue;
504            };
505            Self::hash_str(&mut hasher, &region_id);
506            Self::hash_str(&mut hasher, &region.name);
507            Self::hash_str(&mut hasher, &region.region_type.to_string());
508            let parent_id = self.brain_regions.get_parent(&region_id);
509            match parent_id {
510                Some(parent) => Self::hash_str(&mut hasher, parent),
511                None => Self::hash_str(&mut hasher, "null"),
512            }
513
514            let mut cortical_ids: Vec<String> = region
515                .cortical_areas
516                .iter()
517                .map(|id| id.as_base_64())
518                .collect();
519            cortical_ids.sort();
520            for cortical_id in cortical_ids {
521                Self::hash_str(&mut hasher, &cortical_id);
522            }
523
524            Self::hash_properties_filtered(&mut hasher, &region.properties, &[]);
525        }
526
527        hasher.finish() & HASH_SAFE_MASK
528    }
529
530    /// Compute hash for cortical areas and properties (excluding mappings).
531    fn compute_cortical_areas_hash(&self) -> u64 {
532        let mut hasher = Xxh64::new(DATA_HASH_SEED);
533        let mut areas: Vec<&CorticalArea> = self.cortical_areas.values().collect();
534        areas.sort_by_key(|area| area.cortical_id.as_base_64());
535
536        for area in areas {
537            let cortical_id = area.cortical_id.as_base_64();
538            Self::hash_str(&mut hasher, &cortical_id);
539            hasher.write_u32(area.cortical_idx);
540            Self::hash_str(&mut hasher, &area.name);
541            Self::hash_str(&mut hasher, &area.cortical_type.to_string());
542
543            let excluded = ["cortical_mapping_dst", "upstream_cortical_areas"];
544            Self::hash_properties_filtered(&mut hasher, &area.properties, &excluded);
545        }
546
547        hasher.finish() & HASH_SAFE_MASK
548    }
549
550    /// Compute hash for brain geometry (area positions, dimensions, and 2D coordinates).
551    fn compute_brain_geometry_hash(&self) -> u64 {
552        let mut hasher = Xxh64::new(DATA_HASH_SEED);
553        let mut areas: Vec<&CorticalArea> = self.cortical_areas.values().collect();
554        areas.sort_by_key(|area| area.cortical_id.as_base_64());
555
556        for area in areas {
557            let cortical_id = area.cortical_id.as_base_64();
558            Self::hash_str(&mut hasher, &cortical_id);
559
560            Self::hash_i32(&mut hasher, area.position.x);
561            Self::hash_i32(&mut hasher, area.position.y);
562            Self::hash_i32(&mut hasher, area.position.z);
563
564            Self::hash_u32(&mut hasher, area.dimensions.width);
565            Self::hash_u32(&mut hasher, area.dimensions.height);
566            Self::hash_u32(&mut hasher, area.dimensions.depth);
567
568            let coord_2d = area
569                .properties
570                .get("coordinate_2d")
571                .or_else(|| area.properties.get("coordinates_2d"));
572            match coord_2d {
573                Some(value) => Self::hash_json_value(&mut hasher, value),
574                None => Self::hash_str(&mut hasher, "null"),
575            }
576        }
577
578        hasher.finish() & HASH_SAFE_MASK
579    }
580
581    /// Compute hash for morphologies.
582    fn compute_morphologies_hash(&self) -> u64 {
583        let mut hasher = Xxh64::new(DATA_HASH_SEED);
584        let mut morphology_ids = self.morphology_registry.morphology_ids();
585        morphology_ids.sort();
586
587        for morphology_id in morphology_ids {
588            if let Some(morphology) = self.morphology_registry.get(&morphology_id) {
589                Self::hash_str(&mut hasher, &morphology_id);
590                Self::hash_str(&mut hasher, &format!("{:?}", morphology.morphology_type));
591                Self::hash_str(&mut hasher, &morphology.class);
592                if let Ok(value) = serde_json::to_value(&morphology.parameters) {
593                    Self::hash_json_value(&mut hasher, &value);
594                }
595            }
596        }
597
598        hasher.finish() & HASH_SAFE_MASK
599    }
600
601    /// Compute hash for cortical mappings (cortical_mapping_dst).
602    fn compute_cortical_mappings_hash(&self) -> u64 {
603        let mut hasher = Xxh64::new(DATA_HASH_SEED);
604        let mut areas: Vec<&CorticalArea> = self.cortical_areas.values().collect();
605        areas.sort_by_key(|area| area.cortical_id.as_base_64());
606
607        for area in areas {
608            let cortical_id = area.cortical_id.as_base_64();
609            Self::hash_str(&mut hasher, &cortical_id);
610            if let Some(serde_json::Value::Object(map)) =
611                area.properties.get("cortical_mapping_dst")
612            {
613                let mut dest_ids: Vec<&String> = map.keys().collect();
614                dest_ids.sort();
615                for dest_id in dest_ids {
616                    Self::hash_str(&mut hasher, dest_id);
617                    if let Some(value) = map.get(dest_id) {
618                        Self::hash_json_value(&mut hasher, value);
619                    }
620                }
621            } else {
622                Self::hash_str(&mut hasher, "null");
623            }
624        }
625
626        hasher.finish() & HASH_SAFE_MASK
627    }
628
629    /// Hash a string with a separator to avoid concatenation collisions.
630    fn hash_str(hasher: &mut Xxh64, value: &str) {
631        hasher.write(value.as_bytes());
632        hasher.write_u8(0);
633    }
634
635    /// Hash a signed 32-bit integer deterministically.
636    fn hash_i32(hasher: &mut Xxh64, value: i32) {
637        hasher.write(&value.to_le_bytes());
638    }
639
640    /// Hash an unsigned 32-bit integer deterministically.
641    fn hash_u32(hasher: &mut Xxh64, value: u32) {
642        hasher.write(&value.to_le_bytes());
643    }
644
645    /// Hash JSON values deterministically with sorted object keys.
646    fn hash_json_value(hasher: &mut Xxh64, value: &serde_json::Value) {
647        match value {
648            serde_json::Value::Null => {
649                hasher.write_u8(0);
650            }
651            serde_json::Value::Bool(val) => {
652                hasher.write_u8(1);
653                hasher.write_u8(*val as u8);
654            }
655            serde_json::Value::Number(num) => {
656                hasher.write_u8(2);
657                Self::hash_str(hasher, &num.to_string());
658            }
659            serde_json::Value::String(val) => {
660                hasher.write_u8(3);
661                Self::hash_str(hasher, val);
662            }
663            serde_json::Value::Array(items) => {
664                hasher.write_u8(4);
665                for item in items {
666                    Self::hash_json_value(hasher, item);
667                }
668            }
669            serde_json::Value::Object(map) => {
670                hasher.write_u8(5);
671                let mut keys: Vec<&String> = map.keys().collect();
672                keys.sort();
673                for key in keys {
674                    Self::hash_str(hasher, key);
675                    if let Some(val) = map.get(key) {
676                        Self::hash_json_value(hasher, val);
677                    }
678                }
679            }
680        }
681    }
682
683    /// Hash JSON properties deterministically, excluding specific keys.
684    fn hash_properties_filtered(
685        hasher: &mut Xxh64,
686        properties: &HashMap<String, serde_json::Value>,
687        excluded_keys: &[&str],
688    ) {
689        let mut keys: Vec<&String> = properties.keys().collect();
690        keys.sort();
691        for key in keys {
692            if excluded_keys.contains(&key.as_str()) {
693                continue;
694            }
695            Self::hash_str(hasher, key);
696            if let Some(value) = properties.get(key) {
697                Self::hash_json_value(hasher, value);
698            }
699        }
700    }
701
702    // ======================================================================
703    // Cortical Area Management
704    // ======================================================================
705
706    /// Add a new cortical area
707    ///
708    /// # Arguments
709    ///
710    /// * `area` - The cortical area to add
711    ///
712    /// # Returns
713    ///
714    /// The assigned cortical index
715    ///
716    /// # Errors
717    ///
718    /// Returns error if:
719    /// - An area with the same cortical_id already exists
720    /// - The area's cortical_idx conflicts with an existing area
721    ///
722    pub fn add_cortical_area(&mut self, mut area: CorticalArea) -> BduResult<u32> {
723        // Check if area already exists
724        if self.cortical_areas.contains_key(&area.cortical_id) {
725            return Err(BduError::InvalidArea(format!(
726                "Cortical area {} already exists",
727                area.cortical_id
728            )));
729        }
730
731        // CRITICAL: Reserve cortical_idx 0..=6 for invariant core areas.
732        // Use feagi-data-processing types as single source of truth
733        use feagi_structures::genomic::cortical_area::CoreCorticalType;
734
735        let death_id = CoreCorticalType::Death.to_cortical_id();
736        let power_id = CoreCorticalType::Power.to_cortical_id();
737        let fatigue_id = CoreCorticalType::Fatigue.to_cortical_id();
738        let pain_id = CoreCorticalType::Pain.to_cortical_id();
739        let pleasure_id = CoreCorticalType::Pleasure.to_cortical_id();
740        let fear_id = CoreCorticalType::Fear.to_cortical_id();
741        let hope_id = CoreCorticalType::Hope.to_cortical_id();
742
743        let is_death_area = area.cortical_id == death_id;
744        let is_power_area = area.cortical_id == power_id;
745        let is_fatigue_area = area.cortical_id == fatigue_id;
746        let is_pain_area = area.cortical_id == pain_id;
747        let is_pleasure_area = area.cortical_id == pleasure_id;
748        let is_fear_area = area.cortical_id == fear_id;
749        let is_hope_area = area.cortical_id == hope_id;
750
751        if is_death_area {
752            trace!(
753                target: "feagi-bdu",
754                "[CORE-AREA] Assigning RESERVED cortical_idx=0 to _death area (id={})",
755                area.cortical_id
756            );
757            area.cortical_idx = 0;
758        } else if is_power_area {
759            trace!(
760                target: "feagi-bdu",
761                "[CORE-AREA] Assigning RESERVED cortical_idx=1 to _power area (id={})",
762                area.cortical_id
763            );
764            area.cortical_idx = 1;
765        } else if is_fatigue_area {
766            trace!(
767                target: "feagi-bdu",
768                "[CORE-AREA] Assigning RESERVED cortical_idx=2 to _fatigue area (id={})",
769                area.cortical_id
770            );
771            area.cortical_idx = 2;
772        } else if is_pain_area {
773            trace!(
774                target: "feagi-bdu",
775                "[CORE-AREA] Assigning RESERVED cortical_idx=3 to _pain area (id={})",
776                area.cortical_id
777            );
778            area.cortical_idx = 3;
779        } else if is_pleasure_area {
780            trace!(
781                target: "feagi-bdu",
782                "[CORE-AREA] Assigning RESERVED cortical_idx=4 to _pleasure area (id={})",
783                area.cortical_id
784            );
785            area.cortical_idx = 4;
786        } else if is_fear_area {
787            trace!(
788                target: "feagi-bdu",
789                "[CORE-AREA] Assigning RESERVED cortical_idx=5 to _fear area (id={})",
790                area.cortical_id
791            );
792            area.cortical_idx = 5;
793        } else if is_hope_area {
794            trace!(
795                target: "feagi-bdu",
796                "[CORE-AREA] Assigning RESERVED cortical_idx=6 to _hope area (id={})",
797                area.cortical_id
798            );
799            area.cortical_idx = 6;
800        } else {
801            // Regular areas: assign cortical_idx if not set (will be >=7 due to reservation)
802            if area.cortical_idx == 0 {
803                area.cortical_idx = self.next_cortical_idx;
804                self.next_cortical_idx += 1;
805                trace!(
806                    target: "feagi-bdu",
807                    "[REGULAR-AREA] Assigned cortical_idx={} to area '{}' (should be >=7)",
808                    area.cortical_idx,
809                    area.cortical_id.as_base_64()
810                );
811            } else {
812                // Check for reserved index collision
813                if area.cortical_idx <= 6 {
814                    warn!(
815                        "Regular area '{}' attempted to use RESERVED cortical_idx={}! Reassigning to next available.",
816                        area.cortical_id, area.cortical_idx);
817                    area.cortical_idx = self.next_cortical_idx;
818                    self.next_cortical_idx += 1;
819                    info!(
820                        "   Reassigned '{}' to cortical_idx={}",
821                        area.cortical_id, area.cortical_idx
822                    );
823                } else if self.cortical_idx_to_id.contains_key(&area.cortical_idx) {
824                    return Err(BduError::InvalidArea(format!(
825                        "Cortical index {} is already in use",
826                        area.cortical_idx
827                    )));
828                }
829
830                // Update next_cortical_idx if needed
831                if area.cortical_idx >= self.next_cortical_idx {
832                    self.next_cortical_idx = area.cortical_idx + 1;
833                }
834            }
835        }
836
837        let cortical_id = area.cortical_id;
838        let cortical_idx = area.cortical_idx;
839
840        // Update lookup maps
841        self.cortical_id_to_idx.insert(cortical_id, cortical_idx);
842        self.cortical_idx_to_id.insert(cortical_idx, cortical_id);
843
844        // Initialize upstream_cortical_areas property (empty array for O(1) lookup)
845        area.properties
846            .insert("upstream_cortical_areas".to_string(), serde_json::json!([]));
847
848        // Default visualization voxel granularity is 1x1x1 (assumed, not stored)
849        // User overrides are stored in properties["visualization_voxel_granularity"] only if != 1x1x1
850
851        // If the caller provided a parent brain region ID, persist the association in the
852        // BrainRegionHierarchy membership set (this drives /v1/region/regions_members).
853        //
854        // IMPORTANT: This is separate from storing "parent_region_id" in the cortical area's
855        // properties. BV may show that property even if the hierarchy isn't updated.
856        let parent_region_id = area
857            .properties
858            .get("parent_region_id")
859            .and_then(|v| v.as_str())
860            .map(|s| s.to_string());
861
862        // Store area
863        self.cortical_areas.insert(cortical_id, area);
864
865        // Update region membership (source of truth for region->areas listing)
866        if let Some(region_id) = parent_region_id {
867            let region = self
868                .brain_regions
869                .get_region_mut(&region_id)
870                .ok_or_else(|| {
871                    BduError::InvalidArea(format!(
872                        "Unknown parent_region_id '{}' for cortical area {}",
873                        region_id,
874                        cortical_id.as_base_64()
875                    ))
876                })?;
877            region.add_area(cortical_id);
878        }
879
880        // CRITICAL: Initialize per-area count caches to 0 (lock-free for readers)
881        // This allows healthcheck endpoints to read counts without NPU lock
882        {
883            let mut neuron_cache = self.cached_neuron_counts_per_area.write();
884            neuron_cache.insert(cortical_id, AtomicUsize::new(0));
885            let mut synapse_cache = self.cached_synapse_counts_per_area.write();
886            synapse_cache.insert(cortical_id, AtomicUsize::new(0));
887        }
888        // @cursor:critical-path - BV pulls per-area stats from StateManager without NPU lock.
889        let state_manager = StateManager::instance();
890        let state_manager = state_manager.read();
891        state_manager.init_cortical_area_stats(&cortical_id.as_base_64());
892
893        // CRITICAL: Register cortical area in NPU during corticogenesis
894        // This must happen BEFORE neurogenesis so neurons can look up their cortical IDs
895        // Use base64 format for proper CorticalID conversion
896        if let Some(ref npu) = self.npu {
897            trace!(target: "feagi-bdu", "[LOCK-TRACE] add_cortical_area: attempting NPU lock for registration");
898            if let Ok(mut npu_lock) = npu.lock() {
899                trace!(target: "feagi-bdu", "[LOCK-TRACE] add_cortical_area: acquired NPU lock for registration");
900                npu_lock.register_cortical_area(cortical_idx, cortical_id.as_base_64());
901                trace!(
902                    target: "feagi-bdu",
903                    "Registered cortical area idx={} -> '{}' in NPU",
904                    cortical_idx,
905                    cortical_id.as_base_64()
906                );
907            }
908        }
909
910        // Synchronize cortical area flags with NPU (psp_uniform_distribution, mp_driven_psp, etc.)
911        self.sync_cortical_area_flags_to_npu()?;
912
913        self.initialized = true;
914
915        self.refresh_cortical_area_hashes(true, true);
916        self.refresh_brain_regions_hash();
917
918        Ok(cortical_idx)
919    }
920
921    /// Remove a cortical area by ID
922    ///
923    /// # Arguments
924    ///
925    /// * `cortical_id` - ID of the cortical area to remove
926    ///
927    /// # Returns
928    ///
929    /// `Ok(())` if removed, error if area doesn't exist
930    ///
931    /// # Note
932    ///
933    /// This does NOT remove neurons from the NPU - that must be done separately.
934    ///
935    pub fn remove_cortical_area(&mut self, cortical_id: &CorticalID) -> BduResult<()> {
936        let area = self.cortical_areas.remove(cortical_id).ok_or_else(|| {
937            BduError::InvalidArea(format!("Cortical area {} does not exist", cortical_id))
938        })?;
939
940        // Remove from lookup maps
941        self.cortical_id_to_idx.remove(cortical_id);
942        self.cortical_idx_to_id.remove(&area.cortical_idx);
943
944        self.refresh_cortical_area_hashes(true, true);
945        Ok(())
946    }
947
948    /// Update a cortical area ID without changing its cortical_idx.
949    ///
950    /// This remaps internal lookup tables, brain-region membership, and mapping keys.
951    pub fn rename_cortical_area_id(
952        &mut self,
953        old_id: &CorticalID,
954        new_id: CorticalID,
955        new_cortical_type: CorticalAreaType,
956    ) -> BduResult<()> {
957        self.rename_cortical_area_id_with_options(old_id, new_id, new_cortical_type, true)
958    }
959
960    /// Update a cortical area ID without changing its cortical_idx, with optional NPU registry update.
961    pub fn rename_cortical_area_id_with_options(
962        &mut self,
963        old_id: &CorticalID,
964        new_id: CorticalID,
965        new_cortical_type: CorticalAreaType,
966        update_npu_registry: bool,
967    ) -> BduResult<()> {
968        if !self.cortical_areas.contains_key(old_id) {
969            return Err(BduError::InvalidArea(format!(
970                "Cortical area {} does not exist",
971                old_id
972            )));
973        }
974        if self.cortical_areas.contains_key(&new_id) {
975            return Err(BduError::InvalidArea(format!(
976                "Cortical area {} already exists",
977                new_id
978            )));
979        }
980
981        let mut area = self.cortical_areas.remove(old_id).ok_or_else(|| {
982            BduError::InvalidArea(format!("Cortical area {} does not exist", old_id))
983        })?;
984        let cortical_idx = area.cortical_idx;
985        area.cortical_id = new_id;
986        area.cortical_type = new_cortical_type;
987
988        self.cortical_areas.insert(new_id, area);
989        self.cortical_id_to_idx.remove(old_id);
990        self.cortical_id_to_idx.insert(new_id, cortical_idx);
991        self.cortical_idx_to_id.insert(cortical_idx, new_id);
992
993        // Update per-area count caches
994        {
995            let mut neuron_cache = self.cached_neuron_counts_per_area.write();
996            if let Some(value) = neuron_cache.remove(old_id) {
997                neuron_cache.insert(new_id, value);
998            }
999            let mut synapse_cache = self.cached_synapse_counts_per_area.write();
1000            if let Some(value) = synapse_cache.remove(old_id) {
1001                synapse_cache.insert(new_id, value);
1002            }
1003        }
1004
1005        // Update brain-region membership
1006        self.brain_regions.rename_cortical_area_id(old_id, new_id);
1007
1008        // Update cortical mapping properties referencing the old ID
1009        let old_id_str = old_id.as_base_64();
1010        let new_id_str = new_id.as_base_64();
1011        for area in self.cortical_areas.values_mut() {
1012            if let Some(mapping) = area
1013                .properties
1014                .get_mut("cortical_mapping_dst")
1015                .and_then(|v| v.as_object_mut())
1016            {
1017                if let Some(value) = mapping.remove(&old_id_str) {
1018                    mapping.insert(new_id_str.clone(), value);
1019                }
1020            }
1021        }
1022
1023        // Update NPU cortical_id registry if requested
1024        if update_npu_registry {
1025            if let Some(ref npu) = self.npu {
1026                if let Ok(mut npu_lock) = npu.lock() {
1027                    npu_lock.register_cortical_area(cortical_idx, new_id.as_base_64());
1028                }
1029            }
1030        }
1031
1032        self.refresh_cortical_area_hashes(true, true);
1033        self.refresh_brain_regions_hash();
1034        self.refresh_cortical_mappings_hash();
1035
1036        Ok(())
1037    }
1038
1039    /// Get a cortical area by ID
1040    pub fn get_cortical_area(&self, cortical_id: &CorticalID) -> Option<&CorticalArea> {
1041        self.cortical_areas.get(cortical_id)
1042    }
1043
1044    /// Get a mutable reference to a cortical area
1045    pub fn get_cortical_area_mut(&mut self, cortical_id: &CorticalID) -> Option<&mut CorticalArea> {
1046        self.cortical_areas.get_mut(cortical_id)
1047    }
1048
1049    /// Get cortical index by ID
1050    pub fn get_cortical_idx(&self, cortical_id: &CorticalID) -> Option<u32> {
1051        self.cortical_id_to_idx.get(cortical_id).copied()
1052    }
1053
1054    /// Find which brain region contains a cortical area
1055    ///
1056    /// This is used to populate `parent_region_id` in API responses for Brain Visualizer.
1057    /// Delegates to BrainRegionHierarchy for the actual search.
1058    ///
1059    /// # Arguments
1060    /// * `cortical_id` - Cortical area to search for
1061    ///
1062    /// # Returns
1063    /// * `Option<String>` - Parent region ID (UUID string) if found
1064    ///
1065    pub fn get_parent_region_id_for_area(&self, cortical_id: &CorticalID) -> Option<String> {
1066        self.brain_regions.find_region_containing_area(cortical_id)
1067    }
1068
1069    /// True if `area` has at least one efferent mapping to a cortical area outside its brain region
1070    /// (including destinations not assigned to any region).
1071    pub fn has_cross_region_outgoing(&self, area: &CorticalID) -> bool {
1072        let Some(my_region) = self.brain_regions.find_region_containing_area(area) else {
1073            return false;
1074        };
1075        let Some(src_area) = self.cortical_areas.get(area) else {
1076            return false;
1077        };
1078        let Some(dst_obj) = src_area
1079            .properties
1080            .get("cortical_mapping_dst")
1081            .and_then(|v| v.as_object())
1082        else {
1083            return false;
1084        };
1085        for dst_key in dst_obj.keys() {
1086            let Ok(dst_id) = CorticalID::try_from_base_64(dst_key) else {
1087                continue;
1088            };
1089            match self.brain_regions.find_region_containing_area(&dst_id) {
1090                None => return true,
1091                Some(rid) if rid != my_region => return true,
1092                _ => {}
1093            }
1094        }
1095        false
1096    }
1097
1098    /// True if `area` has at least one afferent mapping from a cortical area outside its brain region.
1099    pub fn has_cross_region_incoming(&self, area: &CorticalID) -> bool {
1100        let Some(my_region) = self.brain_regions.find_region_containing_area(area) else {
1101            return false;
1102        };
1103        let my_b64 = area.as_base_64();
1104        for (src_id, src_area) in &self.cortical_areas {
1105            if src_id == area {
1106                continue;
1107            }
1108            let Some(dst_map) = src_area
1109                .properties
1110                .get("cortical_mapping_dst")
1111                .and_then(|v| v.as_object())
1112            else {
1113                continue;
1114            };
1115            if !dst_map.contains_key(&my_b64) {
1116                continue;
1117            }
1118            match self.brain_regions.find_region_containing_area(src_id) {
1119                None => return true,
1120                Some(rid) if rid != my_region => return true,
1121                _ => {}
1122            }
1123        }
1124        false
1125    }
1126
1127    /// Recompute brain-region `inputs`/`outputs` registries from current cortical mappings.
1128    ///
1129    /// This drives `/v1/region/regions_members` (via `BrainRegion.properties["inputs"/"outputs"]`).
1130    ///
1131    /// Semantics (matches Python `_auto_assign_region_io()` and BV expectations):
1132    /// - **outputs**: Any cortical area *in the region* that connects to an area outside the region
1133    /// - **inputs**: Any cortical area *in the region* that receives a connection from outside the region
1134    ///
1135    /// This function updates the hierarchy in-place and returns the computed base64 ID lists
1136    /// for downstream persistence into `RuntimeGenome`.
1137    pub fn recompute_brain_region_io_registry(&mut self) -> BduResult<BrainRegionIoRegistry> {
1138        use std::collections::HashSet;
1139
1140        let region_ids: Vec<String> = self
1141            .brain_regions
1142            .get_all_region_ids()
1143            .into_iter()
1144            .cloned()
1145            .collect();
1146
1147        let mut inputs_by_region: HashMap<String, HashSet<String>> = HashMap::new();
1148        let mut outputs_by_region: HashMap<String, HashSet<String>> = HashMap::new();
1149
1150        // Initialize so regions with no IO still get cleared deterministically.
1151        for rid in &region_ids {
1152            inputs_by_region.insert(rid.clone(), HashSet::new());
1153            outputs_by_region.insert(rid.clone(), HashSet::new());
1154        }
1155
1156        for (src_id, src_area) in &self.cortical_areas {
1157            let Some(dstmap) = src_area
1158                .properties
1159                .get("cortical_mapping_dst")
1160                .and_then(|v| v.as_object())
1161            else {
1162                continue;
1163            };
1164
1165            let Some(src_region_id) = self.brain_regions.find_region_containing_area(src_id) else {
1166                debug!(
1167                    target: "feagi-bdu",
1168                    "Skipping region IO for source area {} (not in any region)",
1169                    src_id.as_base_64()
1170                );
1171                continue;
1172            };
1173
1174            for dst_id_str in dstmap.keys() {
1175                let dst_id = CorticalID::try_from_base_64(dst_id_str).map_err(|e| {
1176                    BduError::InvalidArea(format!(
1177                        "Unable to recompute region IO: invalid destination cortical id '{}' in cortical_mapping_dst for {}: {}",
1178                        dst_id_str,
1179                        src_id.as_base_64(),
1180                        e
1181                    ))
1182                })?;
1183
1184                let Some(dst_region_id) = self.brain_regions.find_region_containing_area(&dst_id)
1185                else {
1186                    warn!(
1187                        target: "feagi-bdu",
1188                        "Skipping region IO for destination area {} (not in any region)",
1189                        dst_id.as_base_64()
1190                    );
1191                    continue;
1192                };
1193
1194                if src_region_id == dst_region_id {
1195                    continue;
1196                }
1197
1198                outputs_by_region
1199                    .entry(src_region_id.clone())
1200                    .or_default()
1201                    .insert(src_id.as_base_64());
1202                inputs_by_region
1203                    .entry(dst_region_id.clone())
1204                    .or_default()
1205                    .insert(dst_id.as_base_64());
1206            }
1207        }
1208
1209        // Union in declared interface lists so export/import and pre-wired regions show IO without edges.
1210        for rid in &region_ids {
1211            let Some(region) = self.brain_regions.get_region(rid) else {
1212                continue;
1213            };
1214            let in_ids = crate::region_io_designation::parse_designated_id_list(
1215                region
1216                    .properties
1217                    .get(crate::region_io_designation::DESIGNATED_INPUTS_KEY),
1218            )?;
1219            let out_ids = crate::region_io_designation::parse_designated_id_list(
1220                region
1221                    .properties
1222                    .get(crate::region_io_designation::DESIGNATED_OUTPUTS_KEY),
1223            )?;
1224            for id in in_ids {
1225                inputs_by_region
1226                    .entry(rid.clone())
1227                    .or_default()
1228                    .insert(id.as_base_64());
1229            }
1230            for id in out_ids {
1231                outputs_by_region
1232                    .entry(rid.clone())
1233                    .or_default()
1234                    .insert(id.as_base_64());
1235            }
1236        }
1237
1238        let mut computed: HashMap<String, (Vec<String>, Vec<String>)> = HashMap::new();
1239        for rid in region_ids {
1240            let mut inputs: Vec<String> = inputs_by_region
1241                .remove(&rid)
1242                .unwrap_or_default()
1243                .into_iter()
1244                .collect();
1245            let mut outputs: Vec<String> = outputs_by_region
1246                .remove(&rid)
1247                .unwrap_or_default()
1248                .into_iter()
1249                .collect();
1250
1251            inputs.sort();
1252            outputs.sort();
1253
1254            let region = self.brain_regions.get_region_mut(&rid).ok_or_else(|| {
1255                BduError::InvalidArea(format!(
1256                    "Unable to recompute region IO: region '{}' not found in hierarchy",
1257                    rid
1258                ))
1259            })?;
1260
1261            if inputs.is_empty() {
1262                region.properties.remove("inputs");
1263            } else {
1264                region
1265                    .properties
1266                    .insert("inputs".to_string(), serde_json::json!(inputs.clone()));
1267            }
1268
1269            if outputs.is_empty() {
1270                region.properties.remove("outputs");
1271            } else {
1272                region
1273                    .properties
1274                    .insert("outputs".to_string(), serde_json::json!(outputs.clone()));
1275            }
1276
1277            computed.insert(rid, (inputs, outputs));
1278        }
1279
1280        self.refresh_brain_regions_hash();
1281
1282        Ok(computed)
1283    }
1284
1285    /// Get the root brain region ID (region with no parent)
1286    ///
1287    /// # Returns
1288    /// * `Option<String>` - Root region ID (UUID string) if found
1289    ///
1290    pub fn get_root_region_id(&self) -> Option<String> {
1291        self.brain_regions.get_root_region_id()
1292    }
1293
1294    /// Get cortical ID by index
1295    pub fn get_cortical_id(&self, cortical_idx: u32) -> Option<&CorticalID> {
1296        self.cortical_idx_to_id.get(&cortical_idx)
1297    }
1298
1299    /// Get all cortical_idx -> cortical_id mappings (for burst loop caching)
1300    /// Returns a HashMap of cortical_idx -> cortical_id (base64 string)
1301    pub fn get_all_cortical_idx_to_id_mappings(&self) -> ahash::AHashMap<u32, String> {
1302        self.cortical_idx_to_id
1303            .iter()
1304            .map(|(idx, id)| (*idx, id.as_base_64()))
1305            .collect()
1306    }
1307
1308    /// Get all cortical_idx -> visualization_voxel_granularity mappings
1309    ///
1310    /// Returns a map of cortical_idx to (granularity_x, granularity_y, granularity_z) for areas that have
1311    /// visualization voxel granularity configured.
1312    pub fn get_all_visualization_granularities(&self) -> ahash::AHashMap<u32, (u32, u32, u32)> {
1313        let mut granularities = ahash::AHashMap::new();
1314        for (cortical_id, area) in &self.cortical_areas {
1315            let cortical_idx = self
1316                .cortical_id_to_idx
1317                .get(cortical_id)
1318                .copied()
1319                .unwrap_or(0);
1320
1321            // Extract visualization granularity overrides from properties.
1322            // Default is 1x1x1 (assumed, not stored) so we only include non-default overrides.
1323            if let Some(granularity_json) = area.properties.get("visualization_voxel_granularity") {
1324                if let Some(arr) = granularity_json.as_array() {
1325                    if arr.len() == 3 {
1326                        let x_opt = arr[0]
1327                            .as_u64()
1328                            .or_else(|| arr[0].as_f64().map(|f| f as u64));
1329                        let y_opt = arr[1]
1330                            .as_u64()
1331                            .or_else(|| arr[1].as_f64().map(|f| f as u64));
1332                        let z_opt = arr[2]
1333                            .as_u64()
1334                            .or_else(|| arr[2].as_f64().map(|f| f as u64));
1335
1336                        if let (Some(x), Some(y), Some(z)) = (x_opt, y_opt, z_opt) {
1337                            let granularity = (x as u32, y as u32, z as u32);
1338                            // Only include overrides (non-default)
1339                            if granularity != (1, 1, 1) {
1340                                granularities.insert(cortical_idx, granularity);
1341                            }
1342                        }
1343                    }
1344                }
1345            }
1346        }
1347        granularities
1348    }
1349
1350    /// Get all cortical area IDs
1351    pub fn get_cortical_area_ids(&self) -> Vec<&CorticalID> {
1352        self.cortical_areas.keys().collect()
1353    }
1354
1355    /// Get the number of cortical areas
1356    pub fn get_cortical_area_count(&self) -> usize {
1357        self.cortical_areas.len()
1358    }
1359
1360    /// Get all cortical areas that have synapses targeting the specified area (upstream/afferent areas)
1361    ///
1362    /// Reads from the `upstream_cortical_areas` property stored on the cortical area.
1363    /// This property is maintained by `add_upstream_area()` and `remove_upstream_area()`.
1364    ///
1365    /// # Arguments
1366    ///
1367    /// * `target_cortical_id` - The cortical area ID to find upstream connections for
1368    ///
1369    /// # Returns
1370    ///
1371    /// Vec of cortical_idx values for all upstream areas
1372    ///
1373    pub fn get_upstream_cortical_areas(&self, target_cortical_id: &CorticalID) -> Vec<u32> {
1374        if let Some(area) = self.cortical_areas.get(target_cortical_id) {
1375            if let Some(upstream_prop) = area.properties.get("upstream_cortical_areas") {
1376                if let Some(upstream_array) = upstream_prop.as_array() {
1377                    return upstream_array
1378                        .iter()
1379                        .filter_map(|v| v.as_u64().map(|n| n as u32))
1380                        .collect();
1381                }
1382            }
1383
1384            // Property missing - data integrity issue
1385            warn!(target: "feagi-bdu",
1386                "Cortical area '{}' missing 'upstream_cortical_areas' property - treating as empty",
1387                target_cortical_id.as_base_64()
1388            );
1389        }
1390
1391        Vec::new()
1392    }
1393
1394    /// Get only episodic-memory upstream cortical indices for a target memory area.
1395    ///
1396    /// Reads `cortical_mapping_dst` rules directly. The cached
1397    /// `upstream_cortical_areas` list is a derived index and can be empty after
1398    /// connectome import even when the episodic mapping rule is present.
1399    pub fn get_episodic_memory_upstream_cortical_areas(
1400        &self,
1401        target_cortical_id: &CorticalID,
1402    ) -> Vec<u32> {
1403        let mut episodic_upstream = Vec::new();
1404        for (src_id, src_area) in &self.cortical_areas {
1405            if src_id == target_cortical_id {
1406                continue;
1407            }
1408            let Some(mapping_dst) = src_area
1409                .properties
1410                .get("cortical_mapping_dst")
1411                .and_then(|v| v.as_object())
1412            else {
1413                continue;
1414            };
1415            let Some(rules) =
1416                Self::get_mapping_rules_for_destination(mapping_dst, target_cortical_id)
1417            else {
1418                continue;
1419            };
1420            if !Self::mapping_has_episodic_rule(rules) {
1421                continue;
1422            }
1423            let Some(&src_idx) = self.cortical_id_to_idx.get(src_id) else {
1424                continue;
1425            };
1426            episodic_upstream.push(src_idx);
1427        }
1428
1429        episodic_upstream.sort_unstable();
1430        episodic_upstream.dedup();
1431        episodic_upstream
1432    }
1433
1434    fn mapping_has_episodic_rule(rules: &[serde_json::Value]) -> bool {
1435        rules.iter().any(|rule| {
1436            let morphology_id = rule
1437                .as_object()
1438                .and_then(|obj| obj.get("morphology_id"))
1439                .and_then(|v| v.as_str())
1440                .or_else(|| {
1441                    rule.as_array()
1442                        .and_then(|arr| arr.first())
1443                        .and_then(|v| v.as_str())
1444                });
1445            morphology_id == Some("episodic_memory")
1446        })
1447    }
1448
1449    /// Filter upstream cortical indices to exclude memory areas.
1450    pub fn filter_non_memory_upstream_areas(&self, upstream: &[u32]) -> Vec<u32> {
1451        upstream
1452            .iter()
1453            .filter_map(|idx| {
1454                let cortical_id = self.cortical_idx_to_id.get(idx)?;
1455                let area = self.cortical_areas.get(cortical_id)?;
1456                if matches!(area.cortical_type, CorticalAreaType::Memory(_)) {
1457                    None
1458                } else {
1459                    Some(*idx)
1460                }
1461            })
1462            .collect()
1463    }
1464
1465    /// Recompute and persist upstream_cortical_areas for a target area from mapping properties.
1466    ///
1467    /// This is a recovery path for stale upstream tracking after connectome or mapping edits.
1468    pub fn refresh_upstream_cortical_areas_from_mappings(
1469        &mut self,
1470        target_cortical_id: &CorticalID,
1471    ) -> Vec<u32> {
1472        use std::collections::HashSet;
1473        let target_id_str = target_cortical_id.as_base_64();
1474        let mut upstream_idxs = HashSet::new();
1475        for (src_id, src_area) in &self.cortical_areas {
1476            if src_id == target_cortical_id {
1477                continue;
1478            }
1479            if let Some(mapping) = src_area
1480                .properties
1481                .get("cortical_mapping_dst")
1482                .and_then(|v| v.as_object())
1483            {
1484                if mapping.contains_key(&target_id_str) {
1485                    if let Some(&src_idx) = self.cortical_id_to_idx.get(src_id) {
1486                        upstream_idxs.insert(src_idx);
1487                    }
1488                }
1489            }
1490        }
1491
1492        let mut upstream_list: Vec<u32> = upstream_idxs.into_iter().collect();
1493        upstream_list.sort_unstable();
1494
1495        if let Some(target_area) = self.cortical_areas.get_mut(target_cortical_id) {
1496            target_area.properties.insert(
1497                "upstream_cortical_areas".to_string(),
1498                serde_json::json!(upstream_list),
1499            );
1500        }
1501
1502        self.get_upstream_cortical_areas(target_cortical_id)
1503    }
1504
1505    /// Add an upstream cortical area to a target area's upstream list
1506    ///
1507    /// This should be called when synapses are created from src_cortical_idx to target_cortical_id.
1508    ///
1509    /// # Arguments
1510    ///
1511    /// * `target_cortical_id` - The cortical area receiving connections
1512    /// * `src_cortical_idx` - The cortical index of the source area
1513    ///
1514    pub fn add_upstream_area(&mut self, target_cortical_id: &CorticalID, src_cortical_idx: u32) {
1515        if let Some(area) = self.cortical_areas.get_mut(target_cortical_id) {
1516            let upstream_array = area
1517                .properties
1518                .entry("upstream_cortical_areas".to_string())
1519                .or_insert_with(|| serde_json::json!([]));
1520
1521            if let Some(arr) = upstream_array.as_array_mut() {
1522                let src_value = serde_json::json!(src_cortical_idx);
1523                if !arr.contains(&src_value) {
1524                    arr.push(src_value);
1525                    debug!(target: "feagi-bdu",
1526                        "Added upstream area idx={} to cortical area '{}'",
1527                        src_cortical_idx, target_cortical_id.as_base_64()
1528                    );
1529                }
1530            }
1531        }
1532    }
1533
1534    /// Get the memory twin cortical ID for a given memory area and upstream area.
1535    pub fn get_memory_twin_for_upstream_idx(
1536        &self,
1537        memory_area_idx: u32,
1538        upstream_idx: u32,
1539    ) -> Option<CorticalID> {
1540        let memory_id = self.cortical_idx_to_id.get(&memory_area_idx)?;
1541        let upstream_id = self.cortical_idx_to_id.get(&upstream_idx)?;
1542        let area = self.cortical_areas.get(memory_id)?;
1543        let mapping = area
1544            .properties
1545            .get("memory_twin_areas")
1546            .and_then(|v| v.as_object())?;
1547        let twin_b64 = mapping.get(&upstream_id.as_base_64())?.as_str()?;
1548        CorticalID::try_from_base_64(twin_b64).ok()
1549    }
1550
1551    /// Diagnose memory-twin eligibility and status for a specific mapping pair.
1552    ///
1553    /// This gives API/MCP a one-call answer to:
1554    /// - whether a twin is expected,
1555    /// - whether one exists,
1556    /// - and the precise blocker when it does not.
1557    pub fn diagnose_memory_twin_for_mapping(
1558        &self,
1559        src_area_id: &CorticalID,
1560        dst_area_id: &CorticalID,
1561    ) -> BduResult<MemoryTwinDiagnostic> {
1562        let src_area = self.cortical_areas.get(src_area_id).ok_or_else(|| {
1563            BduError::InvalidArea(format!(
1564                "Source area not found: {}",
1565                src_area_id.as_base_64()
1566            ))
1567        })?;
1568        let dst_area = self.cortical_areas.get(dst_area_id).ok_or_else(|| {
1569            BduError::InvalidArea(format!(
1570                "Destination area not found: {}",
1571                dst_area_id.as_base_64()
1572            ))
1573        })?;
1574
1575        let src_is_memory = matches!(src_area.cortical_type, CorticalAreaType::Memory(_));
1576        let dst_is_memory = matches!(dst_area.cortical_type, CorticalAreaType::Memory(_));
1577
1578        let rules_opt = src_area
1579            .properties
1580            .get("cortical_mapping_dst")
1581            .and_then(|v| v.as_object())
1582            .and_then(|mapping_dst| {
1583                Self::get_mapping_rules_for_destination(mapping_dst, dst_area_id)
1584            });
1585        let mapping_exists = rules_opt.is_some();
1586        let episodic_rule_count = rules_opt
1587            .map(|rules| {
1588                rules
1589                    .iter()
1590                    .filter(|rule| {
1591                        let morphology_id = rule
1592                            .as_object()
1593                            .and_then(|obj| obj.get("morphology_id"))
1594                            .and_then(|v| v.as_str())
1595                            .or_else(|| {
1596                                rule.as_array()
1597                                    .and_then(|arr| arr.first())
1598                                    .and_then(|v| v.as_str())
1599                            });
1600                        morphology_id == Some("episodic_memory")
1601                    })
1602                    .count()
1603            })
1604            .unwrap_or(0);
1605
1606        let twin_expected =
1607            mapping_exists && episodic_rule_count > 0 && dst_is_memory && !src_is_memory;
1608        let twin_cortical_area = dst_area
1609            .properties
1610            .get("memory_twin_areas")
1611            .and_then(|v| v.as_object())
1612            .and_then(|map| map.get(&src_area_id.as_base_64()))
1613            .and_then(|v| v.as_str())
1614            .map(ToString::to_string);
1615        let twin_present = twin_cortical_area.is_some();
1616
1617        let twin_parent_region_id = twin_cortical_area.as_ref().and_then(|twin_b64| {
1618            CorticalID::try_from_base_64(twin_b64)
1619                .ok()
1620                .and_then(|twin_id| {
1621                    self.cortical_areas.get(&twin_id).and_then(|area| {
1622                        area.properties
1623                            .get("parent_region_id")
1624                            .and_then(|v| v.as_str())
1625                            .map(ToString::to_string)
1626                    })
1627                })
1628        });
1629        let src_parent_region_id = src_area
1630            .properties
1631            .get("parent_region_id")
1632            .and_then(|v| v.as_str())
1633            .map(ToString::to_string);
1634        let dst_parent_region_id = dst_area
1635            .properties
1636            .get("parent_region_id")
1637            .and_then(|v| v.as_str())
1638            .map(ToString::to_string);
1639        let twin_parent_matches_src_parent = match (&twin_parent_region_id, &src_parent_region_id) {
1640            (Some(twin_parent), Some(src_parent)) => Some(twin_parent == src_parent),
1641            (None, None) if twin_present => Some(true),
1642            _ if twin_present => Some(false),
1643            _ => None,
1644        };
1645
1646        let reason = if !mapping_exists {
1647            Some("no_mapping_rule_between_src_and_dst".to_string())
1648        } else if episodic_rule_count == 0 {
1649            Some("mapping_exists_but_not_episodic_memory".to_string())
1650        } else if !dst_is_memory {
1651            Some("destination_is_not_memory_area".to_string())
1652        } else if src_is_memory {
1653            Some("upstream_is_memory_area_twin_not_supported".to_string())
1654        } else if !twin_present {
1655            Some("twin_expected_but_missing".to_string())
1656        } else if twin_parent_matches_src_parent == Some(false) {
1657            Some("twin_parent_region_mismatch_with_source".to_string())
1658        } else {
1659            None
1660        };
1661
1662        Ok(MemoryTwinDiagnostic {
1663            src_cortical_area: src_area_id.as_base_64(),
1664            dst_cortical_area: dst_area_id.as_base_64(),
1665            src_cortical_type: src_area.cortical_type.to_string(),
1666            dst_cortical_type: dst_area.cortical_type.to_string(),
1667            mapping_exists,
1668            episodic_rule_count,
1669            twin_expected,
1670            twin_present,
1671            twin_cortical_area,
1672            reason,
1673            src_parent_region_id,
1674            dst_parent_region_id,
1675            twin_parent_region_id,
1676            twin_parent_matches_src_parent,
1677        })
1678    }
1679
1680    /// Ensure a memory twin area exists for the given upstream and memory areas.
1681    pub fn ensure_memory_twin_area(
1682        &mut self,
1683        memory_area_id: &CorticalID,
1684        upstream_area_id: &CorticalID,
1685    ) -> BduResult<CorticalID> {
1686        use crate::models::CorticalAreaExt;
1687
1688        let register_replay_mapping = |manager: &mut ConnectomeManager,
1689                                       twin_id: &CorticalID|
1690         -> BduResult<()> {
1691            let Some(npu) = manager.npu.as_ref() else {
1692                return Ok(());
1693            };
1694            let memory_area_idx =
1695                *manager
1696                    .cortical_id_to_idx
1697                    .get(memory_area_id)
1698                    .ok_or_else(|| {
1699                        BduError::InvalidArea(format!(
1700                            "Memory area idx missing for {}",
1701                            memory_area_id.as_base_64()
1702                        ))
1703                    })?;
1704            let upstream_area_idx = *manager
1705                .cortical_id_to_idx
1706                .get(upstream_area_id)
1707                .ok_or_else(|| {
1708                    BduError::InvalidArea(format!(
1709                        "Upstream area idx missing for {}",
1710                        upstream_area_id.as_base_64()
1711                    ))
1712                })?;
1713            let twin_area_idx = *manager.cortical_id_to_idx.get(twin_id).ok_or_else(|| {
1714                BduError::InvalidArea(format!(
1715                    "Twin area idx missing for {}",
1716                    twin_id.as_base_64()
1717                ))
1718            })?;
1719            let twin_area = manager.cortical_areas.get(twin_id).ok_or_else(|| {
1720                BduError::InvalidArea(format!("Twin area {} not found", twin_id.as_base_64()))
1721            })?;
1722            let potential = twin_area.firing_threshold() + twin_area.firing_threshold_increment();
1723            if let Ok(mut npu_lock) = npu.lock() {
1724                npu_lock.register_memory_twin_mapping(
1725                    memory_area_idx,
1726                    upstream_area_idx,
1727                    twin_area_idx,
1728                    potential,
1729                );
1730            }
1731            Ok(())
1732        };
1733
1734        let memory_area = self.cortical_areas.get(memory_area_id).ok_or_else(|| {
1735            BduError::InvalidArea(format!(
1736                "Memory area {} not found",
1737                memory_area_id.as_base_64()
1738            ))
1739        })?;
1740        let upstream_area = self.cortical_areas.get(upstream_area_id).ok_or_else(|| {
1741            BduError::InvalidArea(format!(
1742                "Upstream area {} not found",
1743                upstream_area_id.as_base_64()
1744            ))
1745        })?;
1746
1747        if matches!(upstream_area.cortical_type, CorticalAreaType::Memory(_)) {
1748            return Err(BduError::InvalidArea(format!(
1749                "Upstream area {} is memory type; twin creation is only for non-memory areas",
1750                upstream_area_id.as_base_64()
1751            )));
1752        }
1753
1754        if let Some(existing) = memory_area
1755            .properties
1756            .get("memory_twin_areas")
1757            .and_then(|v| v.as_object())
1758            .and_then(|map| map.get(&upstream_area_id.as_base_64()))
1759            .and_then(|v| v.as_str())
1760            .and_then(|s| CorticalID::try_from_base_64(s).ok())
1761        {
1762            self.ensure_memory_replay_mapping(memory_area_id, &existing)?;
1763            register_replay_mapping(self, &existing)?;
1764            self.refresh_cortical_mappings_hash();
1765            return Ok(existing);
1766        }
1767
1768        let twin_id = self.build_memory_twin_id(memory_area_id, upstream_area_id)?;
1769        if self.cortical_areas.contains_key(&twin_id) {
1770            if let Some(existing) = self.cortical_areas.get_mut(&twin_id) {
1771                let expected_source = upstream_area_id.as_base_64();
1772                let expected_target = memory_area_id.as_base_64();
1773                let existing_source = existing
1774                    .properties
1775                    .get("memory_twin_of")
1776                    .and_then(|v| v.as_str());
1777                let existing_target = existing
1778                    .properties
1779                    .get("memory_twin_for")
1780                    .and_then(|v| v.as_str());
1781                if existing_source != Some(expected_source.as_str())
1782                    || existing_target != Some(expected_target.as_str())
1783                {
1784                    warn!(
1785                        target: "feagi-bdu",
1786                        "Twin cortical ID properties missing/mismatched for {} -> {}; repairing",
1787                        upstream_area_id.as_base_64(),
1788                        memory_area_id.as_base_64()
1789                    );
1790                    existing.properties.insert(
1791                        "memory_twin_of".to_string(),
1792                        serde_json::json!(expected_source),
1793                    );
1794                    existing.properties.insert(
1795                        "memory_twin_for".to_string(),
1796                        serde_json::json!(expected_target),
1797                    );
1798                }
1799            }
1800            self.set_memory_twin_mapping(memory_area_id, upstream_area_id, &twin_id);
1801            self.ensure_memory_replay_mapping(memory_area_id, &twin_id)?;
1802            register_replay_mapping(self, &twin_id)?;
1803            self.refresh_cortical_mappings_hash();
1804            return Ok(twin_id);
1805        }
1806
1807        let twin_name = format!("{}_twin", upstream_area.name.replace(' ', "_"));
1808        let twin_type = CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire);
1809        let twin_position = self.build_memory_twin_position(memory_area, upstream_area);
1810        let mut twin_area = CorticalArea::new(
1811            twin_id,
1812            0,
1813            twin_name,
1814            upstream_area.dimensions,
1815            twin_position,
1816            twin_type,
1817        )?;
1818        twin_area.properties = self.build_memory_twin_properties(
1819            memory_area,
1820            upstream_area,
1821            memory_area_id,
1822            upstream_area_id,
1823        );
1824
1825        let _twin_idx = self.add_cortical_area(twin_area)?;
1826        let _ = self.create_neurons_for_area(&twin_id);
1827
1828        self.set_memory_twin_mapping(memory_area_id, upstream_area_id, &twin_id);
1829        self.ensure_memory_replay_mapping(memory_area_id, &twin_id)?;
1830        register_replay_mapping(self, &twin_id)?;
1831        self.refresh_cortical_mappings_hash();
1832        Ok(twin_id)
1833    }
1834
1835    fn build_memory_twin_position(
1836        &self,
1837        _memory_area: &CorticalArea,
1838        upstream_area: &CorticalArea,
1839    ) -> GenomeCoordinate3D {
1840        let width = upstream_area.dimensions.width as f32;
1841        let margin = (width * 0.25).ceil() as i32;
1842        let offset = upstream_area.dimensions.width as i32 + margin;
1843        GenomeCoordinate3D::new(
1844            upstream_area.position.x + offset,
1845            upstream_area.position.y,
1846            upstream_area.position.z,
1847        )
1848    }
1849
1850    fn build_memory_twin_id(
1851        &self,
1852        memory_area_id: &CorticalID,
1853        upstream_area_id: &CorticalID,
1854    ) -> BduResult<CorticalID> {
1855        let mut hasher = Xxh64::new(DATA_HASH_SEED);
1856        hasher.write(memory_area_id.as_base_64().as_bytes());
1857        hasher.write(upstream_area_id.as_base_64().as_bytes());
1858        hasher.write(b"memory_twin");
1859        let hash = hasher.finish();
1860        let mut bytes = hash.to_be_bytes();
1861        bytes[0] = b'c';
1862        CorticalID::try_from_bytes(&bytes)
1863            .map_err(|e| BduError::Internal(format!("Failed to build twin cortical ID: {}", e)))
1864    }
1865
1866    fn build_memory_twin_properties(
1867        &self,
1868        _memory_area: &CorticalArea,
1869        upstream_area: &CorticalArea,
1870        memory_area_id: &CorticalID,
1871        upstream_area_id: &CorticalID,
1872    ) -> HashMap<String, serde_json::Value> {
1873        let mut props = upstream_area.properties.clone();
1874        props.remove("cortical_mapping_dst");
1875        props.remove("upstream_cortical_areas");
1876        props.remove("parent_region_id");
1877        props.insert("cortical_group".to_string(), serde_json::json!("CUSTOM"));
1878        props.insert("is_mem_type".to_string(), serde_json::json!(false));
1879        props.insert(
1880            "memory_twin_of".to_string(),
1881            serde_json::json!(upstream_area_id.as_base_64()),
1882        );
1883        props.insert(
1884            "memory_twin_for".to_string(),
1885            serde_json::json!(memory_area_id.as_base_64()),
1886        );
1887        if let Some(parent_region_id) = upstream_area
1888            .properties
1889            .get("parent_region_id")
1890            .and_then(|v| v.as_str())
1891        {
1892            props.insert(
1893                "parent_region_id".to_string(),
1894                serde_json::json!(parent_region_id),
1895            );
1896        }
1897        props
1898    }
1899
1900    fn set_memory_twin_mapping(
1901        &mut self,
1902        memory_area_id: &CorticalID,
1903        upstream_area_id: &CorticalID,
1904        twin_id: &CorticalID,
1905    ) {
1906        if let Some(memory_area) = self.cortical_areas.get_mut(memory_area_id) {
1907            let mapping = memory_area
1908                .properties
1909                .entry("memory_twin_areas".to_string())
1910                .or_insert_with(|| serde_json::json!({}));
1911            if let Some(map) = mapping.as_object_mut() {
1912                map.insert(
1913                    upstream_area_id.as_base_64(),
1914                    serde_json::json!(twin_id.as_base_64()),
1915                );
1916            }
1917        }
1918    }
1919
1920    fn ensure_memory_replay_mapping(
1921        &mut self,
1922        memory_area_id: &CorticalID,
1923        twin_id: &CorticalID,
1924    ) -> BduResult<()> {
1925        if !self.morphology_registry.contains("memory_replay") {
1926            feagi_evolutionary::add_core_morphologies(&mut self.morphology_registry);
1927        }
1928        self.refresh_morphologies_hash();
1929        let mapping_data = vec![serde_json::json!({
1930            "morphology_id": "memory_replay",
1931            "morphology_scalar": [1, 1, 1],
1932            "postSynapticCurrent_multiplier": 1,
1933            "plasticity_flag": false,
1934            "plasticity_constant": 0,
1935            "ltp_multiplier": 0,
1936            "ltd_multiplier": 0,
1937            "plasticity_window": 0,
1938        })];
1939        self.update_cortical_mapping(memory_area_id, twin_id, mapping_data)?;
1940        let _ = self.regenerate_synapses_for_mapping(memory_area_id, twin_id)?;
1941        // Update cortical area hash so BV refreshes area details (outgoing mappings).
1942        self.refresh_cortical_area_hashes(true, false);
1943        Ok(())
1944    }
1945
1946    /// Remove the generated replay twin exclusively owned by one upstream-to-memory mapping.
1947    ///
1948    /// The ownership backreferences must match the requested pair before the twin is deleted.
1949    /// This prevents teardown for one upstream from affecting sibling twins of the same memory area.
1950    pub fn teardown_owned_memory_twin_for_mapping(
1951        &mut self,
1952        memory_area_id: &CorticalID,
1953        upstream_area_id: &CorticalID,
1954    ) -> BduResult<Option<CorticalID>> {
1955        let upstream_id = upstream_area_id.as_base_64();
1956        let twin_id = self
1957            .cortical_areas
1958            .get(memory_area_id)
1959            .and_then(|memory_area| memory_area.properties.get("memory_twin_areas"))
1960            .and_then(|value| value.as_object())
1961            .and_then(|twins| twins.get(&upstream_id))
1962            .and_then(|value| value.as_str())
1963            .map(CorticalID::try_from_base_64)
1964            .transpose()
1965            .map_err(|error| {
1966                BduError::InvalidArea(format!(
1967                    "Invalid owned memory twin ID for {} -> {}: {}",
1968                    upstream_area_id.as_base_64(),
1969                    memory_area_id.as_base_64(),
1970                    error
1971                ))
1972            })?;
1973        let Some(twin_id) = twin_id else {
1974            return Ok(None);
1975        };
1976
1977        let twin = self.cortical_areas.get(&twin_id).ok_or_else(|| {
1978            BduError::InvalidArea(format!(
1979                "Owned memory twin {} for {} -> {} does not exist",
1980                twin_id.as_base_64(),
1981                upstream_area_id.as_base_64(),
1982                memory_area_id.as_base_64()
1983            ))
1984        })?;
1985        let owned_by_source = twin
1986            .properties
1987            .get("memory_twin_of")
1988            .and_then(|value| value.as_str())
1989            == Some(upstream_id.as_str());
1990        let owned_by_memory = twin
1991            .properties
1992            .get("memory_twin_for")
1993            .and_then(|value| value.as_str())
1994            == Some(memory_area_id.as_base_64().as_str());
1995        if !owned_by_source || !owned_by_memory {
1996            return Err(BduError::InvalidArea(format!(
1997                "Cortical area {} is not the generated twin owned by {} -> {}",
1998                twin_id.as_base_64(),
1999                upstream_area_id.as_base_64(),
2000                memory_area_id.as_base_64()
2001            )));
2002        }
2003
2004        let memory_idx = *self.cortical_id_to_idx.get(memory_area_id).ok_or_else(|| {
2005            BduError::InvalidArea(format!(
2006                "Memory area idx missing for {}",
2007                memory_area_id.as_base_64()
2008            ))
2009        })?;
2010        let upstream_idx = *self
2011            .cortical_id_to_idx
2012            .get(upstream_area_id)
2013            .ok_or_else(|| {
2014                BduError::InvalidArea(format!(
2015                    "Upstream area idx missing for {}",
2016                    upstream_area_id.as_base_64()
2017                ))
2018            })?;
2019
2020        self.update_cortical_mapping(memory_area_id, &twin_id, Vec::new())?;
2021        let _ = self.regenerate_synapses_for_mapping(memory_area_id, &twin_id)?;
2022        if let Some(npu) = &self.npu {
2023            npu.lock()
2024                .unwrap()
2025                .unregister_memory_twin_mapping(memory_idx, upstream_idx);
2026        }
2027
2028        let memory_area = self.cortical_areas.get_mut(memory_area_id).ok_or_else(|| {
2029            BduError::InvalidArea(format!(
2030                "Memory area {} not found",
2031                memory_area_id.as_base_64()
2032            ))
2033        })?;
2034        let twins = memory_area
2035            .properties
2036            .get_mut("memory_twin_areas")
2037            .and_then(|value| value.as_object_mut())
2038            .ok_or_else(|| {
2039                BduError::InvalidArea(format!(
2040                    "Memory area {} has invalid memory_twin_areas metadata",
2041                    memory_area_id.as_base_64()
2042                ))
2043            })?;
2044        twins.remove(&upstream_id);
2045        if twins.is_empty() {
2046            memory_area.properties.remove("memory_twin_areas");
2047        }
2048
2049        for region_id in self
2050            .get_brain_region_ids()
2051            .into_iter()
2052            .cloned()
2053            .collect::<Vec<_>>()
2054        {
2055            if let Some(region) = self.get_brain_region_mut(&region_id) {
2056                region.remove_area(&twin_id);
2057            }
2058        }
2059        self.remove_cortical_area(&twin_id)?;
2060        self.refresh_cortical_mappings_hash();
2061        Ok(Some(twin_id))
2062    }
2063
2064    /// Remove an upstream cortical area from a target area's upstream list
2065    ///
2066    /// This should be called when all synapses from src_cortical_idx to target_cortical_id are deleted.
2067    ///
2068    /// # Arguments
2069    ///
2070    /// * `target_cortical_id` - The cortical area that had connections
2071    /// * `src_cortical_idx` - The cortical index of the source area to remove
2072    ///
2073    pub fn remove_upstream_area(&mut self, target_cortical_id: &CorticalID, src_cortical_idx: u32) {
2074        if let Some(area) = self.cortical_areas.get_mut(target_cortical_id) {
2075            if let Some(upstream_prop) = area.properties.get_mut("upstream_cortical_areas") {
2076                if let Some(arr) = upstream_prop.as_array_mut() {
2077                    let src_value = serde_json::json!(src_cortical_idx);
2078                    if let Some(pos) = arr.iter().position(|v| v == &src_value) {
2079                        arr.remove(pos);
2080                        debug!(target: "feagi-bdu",
2081                            "Removed upstream area idx={} from cortical area '{}'",
2082                            src_cortical_idx, target_cortical_id.as_base_64()
2083                        );
2084                    }
2085                }
2086            }
2087        }
2088    }
2089
2090    /// Check if a cortical area exists
2091    pub fn has_cortical_area(&self, cortical_id: &CorticalID) -> bool {
2092        self.cortical_areas.contains_key(cortical_id)
2093    }
2094
2095    /// Check if the connectome is initialized (has areas)
2096    pub fn is_initialized(&self) -> bool {
2097        self.initialized && !self.cortical_areas.is_empty()
2098    }
2099
2100    // ======================================================================
2101    // Brain Region Management
2102    // ======================================================================
2103
2104    /// Add a brain region
2105    pub fn add_brain_region(
2106        &mut self,
2107        region: BrainRegion,
2108        parent_id: Option<String>,
2109    ) -> BduResult<()> {
2110        self.brain_regions.add_region(region, parent_id)?;
2111        self.refresh_brain_regions_hash();
2112        Ok(())
2113    }
2114
2115    /// Remove a brain region
2116    pub fn remove_brain_region(&mut self, region_id: &str) -> BduResult<()> {
2117        self.brain_regions.remove_region(region_id)?;
2118        self.refresh_brain_regions_hash();
2119        Ok(())
2120    }
2121
2122    /// Drop the entire brain-region hierarchy.
2123    ///
2124    /// Connectome import uses this instead of deleting regions one-by-one because
2125    /// `remove_brain_region` refuses to delete the live root.
2126    pub fn clear_brain_regions(&mut self) {
2127        self.brain_regions.clear();
2128        self.refresh_brain_regions_hash();
2129    }
2130
2131    /// Change the parent of an existing brain region.
2132    pub fn change_brain_region_parent(
2133        &mut self,
2134        region_id: &str,
2135        new_parent_id: &str,
2136    ) -> BduResult<()> {
2137        self.brain_regions.change_parent(region_id, new_parent_id)?;
2138        self.refresh_brain_regions_hash();
2139        Ok(())
2140    }
2141
2142    /// Get a brain region by ID
2143    pub fn get_brain_region(&self, region_id: &str) -> Option<&BrainRegion> {
2144        self.brain_regions.get_region(region_id)
2145    }
2146
2147    /// Get a mutable reference to a brain region
2148    pub fn get_brain_region_mut(&mut self, region_id: &str) -> Option<&mut BrainRegion> {
2149        self.brain_regions.get_region_mut(region_id)
2150    }
2151
2152    /// Get all brain region IDs
2153    pub fn get_brain_region_ids(&self) -> Vec<&String> {
2154        self.brain_regions.get_all_region_ids()
2155    }
2156
2157    /// Get the brain region hierarchy
2158    pub fn get_brain_region_hierarchy(&self) -> &BrainRegionHierarchy {
2159        &self.brain_regions
2160    }
2161
2162    // ========================================================================
2163    // MORPHOLOGY ACCESS
2164    // ========================================================================
2165
2166    /// Get all morphologies from the loaded genome
2167    pub fn get_morphologies(&self) -> &feagi_evolutionary::MorphologyRegistry {
2168        &self.morphology_registry
2169    }
2170
2171    /// Get morphology count
2172    pub fn get_morphology_count(&self) -> usize {
2173        self.morphology_registry.count()
2174    }
2175
2176    /// Insert or overwrite a morphology definition in the in-memory registry.
2177    ///
2178    /// NOTE: This updates the runtime registry used by mapping/synapse generation.
2179    /// Callers that also maintain a RuntimeGenome (source of truth) MUST update it too.
2180    pub fn upsert_morphology(
2181        &mut self,
2182        morphology_id: String,
2183        morphology: feagi_evolutionary::Morphology,
2184    ) {
2185        self.morphology_registry
2186            .add_morphology(morphology_id, morphology);
2187        self.refresh_morphologies_hash();
2188    }
2189
2190    /// Remove a morphology definition from the in-memory registry.
2191    ///
2192    /// Returns true if the morphology existed and was removed.
2193    ///
2194    /// NOTE: Callers that also maintain a RuntimeGenome (source of truth) MUST update it too.
2195    pub fn remove_morphology(&mut self, morphology_id: &str) -> bool {
2196        let removed = self.morphology_registry.remove_morphology(morphology_id);
2197        if removed {
2198            self.refresh_morphologies_hash();
2199        }
2200        removed
2201    }
2202
2203    // ========================================================================
2204    // CORTICAL MAPPING UPDATES
2205    // ========================================================================
2206
2207    /// Update cortical mapping properties between two cortical areas
2208    ///
2209    /// Updates only the source area's `cortical_mapping_dst` entry for this destination.
2210    /// Associative memory mappings are **directed**: a reverse edge (if any) is stored only when
2211    /// the client updates that pair explicitly (separate PUT).
2212    ///
2213    /// # Arguments
2214    /// * `src_area_id` - Source cortical area ID
2215    /// * `dst_area_id` - Destination cortical area ID
2216    /// * `mapping_data` - List of connection specifications
2217    ///
2218    /// # Returns
2219    /// * `BduResult<()>` - Ok if successful, Err otherwise
2220    pub fn update_cortical_mapping(
2221        &mut self,
2222        src_area_id: &CorticalID,
2223        dst_area_id: &CorticalID,
2224        mapping_data: Vec<serde_json::Value>,
2225    ) -> BduResult<()> {
2226        use tracing::info;
2227
2228        self.validate_memory_outbound_mapping_contract(src_area_id, dst_area_id, &mapping_data)?;
2229        crate::region_io_designation::validate_cross_region_mapping_proposal(
2230            self,
2231            src_area_id,
2232            dst_area_id,
2233            &mapping_data,
2234        )?;
2235
2236        debug!(target: "feagi-bdu", "Updating cortical mapping: {} -> {}", src_area_id, dst_area_id);
2237
2238        {
2239            // Get source area (must exist)
2240            let src_area = self.cortical_areas.get_mut(src_area_id).ok_or_else(|| {
2241                crate::types::BduError::InvalidArea(format!(
2242                    "Source area not found: {}",
2243                    src_area_id
2244                ))
2245            })?;
2246
2247            // Get or create cortical_mapping_dst property
2248            let cortical_mapping_dst =
2249                if let Some(existing) = src_area.properties.get_mut("cortical_mapping_dst") {
2250                    existing.as_object_mut().ok_or_else(|| {
2251                        crate::types::BduError::InvalidMorphology(
2252                            "cortical_mapping_dst is not an object".to_string(),
2253                        )
2254                    })?
2255                } else {
2256                    // Create new cortical_mapping_dst
2257                    src_area
2258                        .properties
2259                        .insert("cortical_mapping_dst".to_string(), serde_json::json!({}));
2260                    src_area
2261                        .properties
2262                        .get_mut("cortical_mapping_dst")
2263                        .unwrap()
2264                        .as_object_mut()
2265                        .unwrap()
2266                };
2267
2268            // Update or add the mapping for this destination
2269            if mapping_data.is_empty() {
2270                // Empty mapping_data = delete the connection
2271                cortical_mapping_dst.remove(&dst_area_id.as_base_64());
2272                info!(target: "feagi-bdu", "Removed mapping from {} to {}", src_area_id, dst_area_id);
2273            } else {
2274                cortical_mapping_dst.insert(
2275                    dst_area_id.as_base_64(),
2276                    serde_json::Value::Array(mapping_data.clone()),
2277                );
2278                debug!(target: "feagi-bdu", "Updated mapping from {} to {} with {} connections",
2279                      src_area_id, dst_area_id, mapping_data.len());
2280            }
2281        }
2282
2283        self.refresh_cortical_mappings_hash();
2284
2285        Ok(())
2286    }
2287
2288    /// Enforce the directed memory retrieval contract for outbound memory mappings.
2289    ///
2290    /// A memory area can connect to a non-memory area only through associative plasticity,
2291    /// except for its server-managed `memory_replay` edge to one of its replay twins.
2292    /// Associative rules start without physical synapses; the NPU creates directed synapses
2293    /// only when source and destination neurons co-fire within the configured plasticity window.
2294    pub fn validate_memory_outbound_mapping_contract(
2295        &self,
2296        src_area_id: &CorticalID,
2297        dst_area_id: &CorticalID,
2298        mapping_data: &[serde_json::Value],
2299    ) -> BduResult<()> {
2300        if mapping_data.is_empty() {
2301            return Ok(());
2302        }
2303        let src_area = self.cortical_areas.get(src_area_id).ok_or_else(|| {
2304            BduError::InvalidArea(format!("Source area not found: {}", src_area_id))
2305        })?;
2306        let dst_area = self.cortical_areas.get(dst_area_id).ok_or_else(|| {
2307            BduError::InvalidArea(format!("Destination area not found: {}", dst_area_id))
2308        })?;
2309        if !matches!(src_area.cortical_type, CorticalAreaType::Memory(_))
2310            || matches!(dst_area.cortical_type, CorticalAreaType::Memory(_))
2311        {
2312            return Ok(());
2313        }
2314
2315        for rule in mapping_data {
2316            let morphology_id = rule
2317                .as_object()
2318                .and_then(|rule_obj| rule_obj.get("morphology_id"))
2319                .and_then(|value| value.as_str())
2320                .or_else(|| {
2321                    rule.as_array()
2322                        .and_then(|rule_array| rule_array.first())
2323                        .and_then(|value| value.as_str())
2324                });
2325            let is_replay_edge_to_own_twin = morphology_id == Some("memory_replay")
2326                && dst_area
2327                    .properties
2328                    .get("memory_twin_for")
2329                    .and_then(|value| value.as_str())
2330                    == Some(src_area_id.as_base_64().as_str());
2331            if morphology_id != Some("associative_memory") && !is_replay_edge_to_own_twin {
2332                return Err(BduError::InvalidMorphology(format!(
2333                    "Memory-to-non-memory mapping {} -> {} only supports associative_memory \
2334                     (or memory_replay to its own twin)",
2335                    src_area_id, dst_area_id
2336                )));
2337            }
2338        }
2339        Ok(())
2340    }
2341
2342    /// Regenerate synapses for a specific cortical mapping
2343    ///
2344    /// Creates new synapses based on mapping rules. Only removes existing synapses if
2345    /// a mapping already existed (update case), not for new mappings (allows multiple
2346    /// synapses between the same neurons).
2347    ///
2348    /// # Arguments
2349    /// * `src_area_id` - Source cortical area ID
2350    /// * `dst_area_id` - Destination cortical area ID
2351    ///
2352    /// # Returns
2353    /// * `BduResult<usize>` - Number of synapses created
2354    pub fn regenerate_synapses_for_mapping(
2355        &mut self,
2356        src_area_id: &CorticalID,
2357        dst_area_id: &CorticalID,
2358    ) -> BduResult<usize> {
2359        use tracing::info;
2360
2361        debug!(target: "feagi-bdu", "Regenerating synapses: {} -> {}", src_area_id, dst_area_id);
2362
2363        let mapping_rules_len = self
2364            .cortical_areas
2365            .get(src_area_id)
2366            .and_then(|area| area.properties.get("cortical_mapping_dst"))
2367            .and_then(|v| v.as_object())
2368            .and_then(|map| map.get(&dst_area_id.as_base_64()))
2369            .and_then(|v| v.as_array())
2370            .map(|arr| arr.len())
2371            .unwrap_or(0);
2372        tracing::debug!(
2373            target: "feagi-bdu",
2374            "Mapping rules for {} -> {}: {}",
2375            src_area_id,
2376            dst_area_id,
2377            mapping_rules_len
2378        );
2379
2380        // If NPU is available, regenerate synapses
2381        let Some(npu_arc) = self.npu.clone() else {
2382            info!(target: "feagi-bdu", "NPU not available - skipping synapse regeneration");
2383            return Ok(0);
2384        };
2385
2386        // Mapping regeneration must be deterministic:
2387        // - On mapping deletion: prune all synapses from A→B, then attempt synaptogenesis (which yields 0).
2388        // - On rule removal/updates: prune all synapses from A→B, then re-run synaptogenesis using the *current*
2389        //   mapping rules. This guarantees stale synapses from removed rules do not persist, while preserving
2390        //   other A→B mappings by re-creating them from the remaining rules.
2391        //
2392        // NOTE: This pruning requires retrieving neuron IDs in each area. Today, that can be O(all_neurons)
2393        // via `get_neurons_in_cortical_area()`. This is the safest correctness-first behavior.
2394
2395        let src_idx = *self.cortical_id_to_idx.get(src_area_id).ok_or_else(|| {
2396            BduError::InvalidArea(format!("No cortical idx for source area {}", src_area_id))
2397        })?;
2398        let dst_idx = *self.cortical_id_to_idx.get(dst_area_id).ok_or_else(|| {
2399            BduError::InvalidArea(format!(
2400                "No cortical idx for destination area {}",
2401                dst_area_id
2402            ))
2403        })?;
2404
2405        // Prune all existing synapses from src_area→dst_area before (re)creating based on current rules.
2406        // This prevents stale synapses when rules are removed/edited.
2407        let mut pruned_synapse_count: usize = 0;
2408        use std::time::Instant;
2409        let start = Instant::now();
2410
2411        // Get neuron lists (may be slow; see note above).
2412        //
2413        // IMPORTANT: Do not rely on per-area cached neuron counts here. Pruning must be correct even if
2414        // caches are stale (e.g., in tests or during partial initialization). If either side is empty,
2415        // pruning is a no-op anyway.
2416        let (sources, targets) = {
2417            let lock_start = std::time::Instant::now();
2418            let npu = npu_arc.lock().unwrap();
2419            let lock_wait = lock_start.elapsed();
2420            tracing::debug!(
2421                target: "feagi-bdu",
2422                "[NPU-LOCK] prune list lock wait {:.2}ms for {} -> {}",
2423                lock_wait.as_secs_f64() * 1000.0,
2424                src_area_id,
2425                dst_area_id
2426            );
2427            let sources: Vec<NeuronId> = npu
2428                .get_neurons_in_cortical_area(src_idx)
2429                .into_iter()
2430                .map(NeuronId)
2431                .collect();
2432            let targets: Vec<NeuronId> = npu
2433                .get_neurons_in_cortical_area(dst_idx)
2434                .into_iter()
2435                .map(NeuronId)
2436                .collect();
2437            (sources, targets)
2438        };
2439
2440        tracing::debug!(
2441            target: "feagi-bdu",
2442            "Prune synapses: {} sources, {} targets",
2443            sources.len(),
2444            targets.len()
2445        );
2446
2447        if !sources.is_empty() && !targets.is_empty() {
2448            let remove_start = Instant::now();
2449            pruned_synapse_count = {
2450                let lock_start = std::time::Instant::now();
2451                let mut npu = npu_arc.lock().unwrap();
2452                let lock_wait = lock_start.elapsed();
2453                tracing::debug!(
2454                    target: "feagi-bdu",
2455                    "[NPU-LOCK] prune remove lock wait {:.2}ms for {} -> {}",
2456                    lock_wait.as_secs_f64() * 1000.0,
2457                    src_area_id,
2458                    dst_area_id
2459                );
2460                // Use direct source-target batch removal here rather than index-based removal.
2461                // This avoids false "Pruned 0" outcomes when propagation synapse_index is stale
2462                // during repeated rapid remap operations.
2463                npu.remove_synapses_between(sources, targets)
2464            };
2465            let remove_time = remove_start.elapsed();
2466            let total_time = start.elapsed();
2467
2468            info!(
2469                target: "feagi-bdu",
2470                "Pruned {} existing synapses for mapping {} -> {} (total={}ms, remove={}ms)",
2471                pruned_synapse_count,
2472                src_area_id,
2473                dst_area_id,
2474                total_time.as_millis(),
2475                remove_time.as_millis()
2476            );
2477
2478            // Update StateManager synapse count (health_check endpoint)
2479            if pruned_synapse_count > 0 {
2480                let pruned_u32 = u32::try_from(pruned_synapse_count).map_err(|_| {
2481                    BduError::Internal(format!(
2482                        "Pruned synapse count overflow (usize -> u32): {}",
2483                        pruned_synapse_count
2484                    ))
2485                })?;
2486                let state_manager = StateManager::instance();
2487                let state_manager = state_manager.read();
2488                let core_state = state_manager.get_core_state();
2489                core_state.subtract_synapse_count(pruned_u32);
2490                state_manager.subtract_cortical_area_outgoing_synapses(
2491                    &src_area_id.as_base_64(),
2492                    pruned_synapse_count,
2493                );
2494                state_manager.subtract_cortical_area_incoming_synapses(
2495                    &dst_area_id.as_base_64(),
2496                    pruned_synapse_count,
2497                );
2498
2499                // Best-effort: adjust per-area outgoing synapse count cache for the source area.
2500                // (Cache is used for lock-free health-check reads; correctness is eventually
2501                // consistent via periodic refresh of global count from NPU.)
2502                {
2503                    let mut cache = self.cached_synapse_counts_per_area.write();
2504                    let entry = cache
2505                        .entry(*src_area_id)
2506                        .or_insert_with(|| AtomicUsize::new(0));
2507                    let mut current = entry.load(Ordering::Relaxed);
2508                    loop {
2509                        let next = current.saturating_sub(pruned_synapse_count);
2510                        match entry.compare_exchange(
2511                            current,
2512                            next,
2513                            Ordering::Relaxed,
2514                            Ordering::Relaxed,
2515                        ) {
2516                            Ok(_) => break,
2517                            Err(v) => current = v,
2518                        }
2519                    }
2520                }
2521            }
2522        }
2523
2524        // Apply cortical mapping rules to create synapses (may be 0 for memory areas).
2525        //
2526        // IMPORTANT:
2527        // - We already pruned A→B synapses above to ensure no stale synapses remain after a rule removal/update.
2528        // - `apply_cortical_mapping_for_pair()` returns the created synapse count but does not update
2529        //   StateManager/caches; we do that immediately after the call.
2530        let synapse_count = self.apply_cortical_mapping_for_pair(src_area_id, dst_area_id)?;
2531        tracing::debug!(
2532            target: "feagi-bdu",
2533            "Synaptogenesis created {} synapses for {} -> {}",
2534            synapse_count,
2535            src_area_id,
2536            dst_area_id
2537        );
2538
2539        // Update synapse count caches and StateManager based on synapses created.
2540        // NOTE: apply_cortical_mapping_for_pair() does not touch caches/StateManager.
2541        if synapse_count > 0 {
2542            let created_u32 = u32::try_from(synapse_count).map_err(|_| {
2543                BduError::Internal(format!(
2544                    "Created synapse count overflow (usize -> u32): {}",
2545                    synapse_count
2546                ))
2547            })?;
2548
2549            // Update per-area outgoing synapse count cache (source area)
2550            {
2551                let mut cache = self.cached_synapse_counts_per_area.write();
2552                cache
2553                    .entry(*src_area_id)
2554                    .or_insert_with(|| AtomicUsize::new(0))
2555                    .fetch_add(synapse_count, Ordering::Relaxed);
2556            }
2557
2558            // Update StateManager synapse count (health_check endpoint)
2559            let state_manager = StateManager::instance();
2560            let state_manager = state_manager.read();
2561            let core_state = state_manager.get_core_state();
2562            core_state.add_synapse_count(created_u32);
2563            state_manager
2564                .add_cortical_area_outgoing_synapses(&src_area_id.as_base_64(), synapse_count);
2565            state_manager
2566                .add_cortical_area_incoming_synapses(&dst_area_id.as_base_64(), synapse_count);
2567        }
2568
2569        // Update upstream area tracking based on MAPPING existence, not synapse count
2570        // Memory areas have 0 synapses but still need upstream tracking for pattern detection
2571        let src_idx_for_upstream = src_idx;
2572
2573        // Check if mapping exists by looking at cortical_mapping_dst property (after update)
2574        let has_mapping = self
2575            .cortical_areas
2576            .get(src_area_id)
2577            .and_then(|area| area.properties.get("cortical_mapping_dst"))
2578            .and_then(|v| v.as_object())
2579            .and_then(|map| map.get(&dst_area_id.as_base_64()))
2580            .is_some();
2581
2582        debug!(target: "feagi-bdu",
2583            "Mapping result: {} synapses, {} -> {} (mapping_exists={}, will {}update upstream)",
2584            synapse_count,
2585            src_area_id.as_base_64(),
2586            dst_area_id.as_base_64(),
2587            has_mapping,
2588            if has_mapping { "" } else { "NOT " }
2589        );
2590
2591        if has_mapping {
2592            // Mapping exists - add to upstream tracking (for both memory and regular areas)
2593            self.add_upstream_area(dst_area_id, src_idx_for_upstream);
2594
2595            if let Some(dst_area) = self.cortical_areas.get(dst_area_id) {
2596                if matches!(dst_area.cortical_type, CorticalAreaType::Memory(_)) {
2597                    if let Err(e) = self.ensure_memory_twin_area(dst_area_id, src_area_id) {
2598                        warn!(
2599                            target: "feagi-bdu",
2600                            "Failed to ensure memory twin for {} -> {}: {}",
2601                            src_area_id.as_base_64(),
2602                            dst_area_id.as_base_64(),
2603                            e
2604                        );
2605                    }
2606                }
2607            }
2608
2609            // If destination is a memory area, register it with PlasticityExecutor (automatic)
2610            #[cfg(feature = "plasticity")]
2611            if let Some(ref executor) = self.plasticity_executor {
2612                use feagi_evolutionary::extract_memory_properties;
2613
2614                if let Some(dst_area) = self.cortical_areas.get(dst_area_id) {
2615                    if let Some(mem_props) = extract_memory_properties(&dst_area.properties) {
2616                        let upstream_areas =
2617                            self.get_episodic_memory_upstream_cortical_areas(dst_area_id);
2618                        debug!(
2619                            target: "feagi-bdu",
2620                            "Registering memory area idx={} id={} upstream={} depth={}",
2621                            dst_area.cortical_idx,
2622                            dst_area_id.as_base_64(),
2623                            upstream_areas.len(),
2624                            mem_props.temporal_depth
2625                        );
2626
2627                        // Ensure FireLedger tracks the upstream areas with at least the required temporal depth.
2628                        // Dense, burst-aligned tracking is required for correct memory pattern hashing.
2629                        if let Some(ref npu_arc) = self.npu {
2630                            if let Ok(mut npu) = npu_arc.lock() {
2631                                let existing_configs = npu.get_all_fire_ledger_configs();
2632                                for &upstream_idx in &upstream_areas {
2633                                    let existing = existing_configs
2634                                        .iter()
2635                                        .find(|(idx, _)| *idx == upstream_idx)
2636                                        .map(|(_, w)| *w)
2637                                        .unwrap_or(0);
2638
2639                                    let desired = mem_props.temporal_depth as usize;
2640                                    let resolved = existing.max(desired);
2641                                    if resolved != existing {
2642                                        if let Err(e) =
2643                                            npu.configure_fire_ledger_window(upstream_idx, resolved)
2644                                        {
2645                                            warn!(
2646                                                target: "feagi-bdu",
2647                                                "Failed to configure FireLedger window for upstream area idx={} (requested={}): {}",
2648                                                upstream_idx,
2649                                                resolved,
2650                                                e
2651                                            );
2652                                        }
2653                                    }
2654                                }
2655                            } else {
2656                                warn!(target: "feagi-bdu", "Failed to lock NPU for FireLedger configuration");
2657                            }
2658                        }
2659
2660                        if let Ok(exec) = executor.lock() {
2661                            use feagi_npu_plasticity::{
2662                                MemoryNeuronLifecycleConfig, PlasticityExecutor,
2663                            };
2664
2665                            let lifecycle_config = MemoryNeuronLifecycleConfig {
2666                                initial_lifespan: mem_props.init_lifespan,
2667                                lifespan_growth_rate: mem_props.lifespan_growth_rate,
2668                                longterm_threshold: mem_props.longterm_threshold,
2669                                max_reactivations: 1000,
2670                            };
2671
2672                            exec.register_memory_area(
2673                                dst_area.cortical_idx,
2674                                dst_area_id.as_base_64(),
2675                                mem_props.temporal_depth,
2676                                upstream_areas.clone(),
2677                                Some(lifecycle_config),
2678                                mem_props.mp_learning_enabled,
2679                            );
2680                        } else {
2681                            warn!(target: "feagi-bdu", "Failed to lock PlasticityExecutor");
2682                        }
2683                    } else {
2684                        debug!(
2685                            target: "feagi-bdu",
2686                            "Skipping plasticity registration: no memory properties for area {}",
2687                            dst_area_id.as_base_64()
2688                        );
2689                    }
2690                } else {
2691                    warn!(target: "feagi-bdu", "Destination area {} not found in cortical_areas", dst_area_id.as_base_64());
2692                }
2693            } else {
2694                warn!(
2695                    target: "feagi-bdu",
2696                    "PlasticityExecutor not available; memory area {} not registered",
2697                    dst_area_id.as_base_64()
2698                );
2699            }
2700
2701            #[cfg(not(feature = "plasticity"))]
2702            {
2703                info!(target: "feagi-bdu", "Plasticity feature disabled at compile time");
2704            }
2705        } else {
2706            // Mapping deleted - remove from upstream tracking
2707            self.remove_upstream_area(dst_area_id, src_idx_for_upstream);
2708
2709            let destination_is_memory = self
2710                .cortical_areas
2711                .get(dst_area_id)
2712                .is_some_and(|area| matches!(area.cortical_type, CorticalAreaType::Memory(_)));
2713            if destination_is_memory {
2714                self.teardown_owned_memory_twin_for_mapping(dst_area_id, src_area_id)?;
2715            }
2716
2717            // Ensure any STDP mapping parameters for this pair are removed when the mapping is gone.
2718            let mut npu = npu_arc.lock().unwrap();
2719            let _was_registered = npu.unregister_stdp_mapping(src_idx, dst_idx);
2720        }
2721
2722        debug!(
2723            target: "feagi-bdu",
2724            "Created {} new synapses: {} -> {}",
2725            synapse_count,
2726            src_area_id,
2727            dst_area_id
2728        );
2729
2730        // CRITICAL: Rebuild synapse index so removals are reflected in propagation and query paths.
2731        // Many morphology paths rebuild the index after creation, but pruning requires an explicit rebuild.
2732        if pruned_synapse_count > 0 || synapse_count == 0 {
2733            let mut npu = npu_arc.lock().unwrap();
2734            npu.rebuild_synapse_index();
2735            info!(
2736                target: "feagi-bdu",
2737                "Rebuilt synapse index after regenerating {} -> {} (pruned={}, created={})",
2738                src_area_id,
2739                dst_area_id,
2740                pruned_synapse_count,
2741                synapse_count
2742            );
2743        } else {
2744            debug!(
2745                target: "feagi-bdu",
2746                "Skipped synapse index rebuild for mapping {} -> {} (created={}, pruned=0; index rebuilt during synaptogenesis)",
2747                src_area_id,
2748                dst_area_id,
2749                synapse_count
2750            );
2751        }
2752
2753        // Refresh the global synapse count cache from NPU (deterministic after prune/create).
2754        {
2755            let npu = npu_arc.lock().unwrap();
2756            let fresh_count = npu.get_synapse_count();
2757            self.cached_synapse_count
2758                .store(fresh_count, Ordering::Relaxed);
2759        }
2760
2761        Ok(synapse_count)
2762    }
2763
2764    /// Whole numbers often arrive as JSON floats (e.g. `1.0`); `as_i64`/`as_u64` return None for those.
2765    fn json_number_as_i64_for_stdp(v: &serde_json::Value) -> Option<i64> {
2766        v.as_i64().or_else(|| v.as_f64().map(|f| f as i64))
2767    }
2768
2769    fn json_number_as_usize_for_stdp(v: &serde_json::Value) -> Option<usize> {
2770        v.as_u64()
2771            .map(|n| n as usize)
2772            .or_else(|| v.as_f64().map(|f| f as usize))
2773    }
2774
2775    /// Register STDP mapping parameters for a plastic rule
2776    #[allow(clippy::too_many_arguments)]
2777    fn register_stdp_mapping_for_rule(
2778        npu: &Arc<feagi_npu_burst_engine::TracingMutex<feagi_npu_burst_engine::DynamicNPU>>,
2779        src_area_id: &CorticalID,
2780        dst_area_id: &CorticalID,
2781        src_cortical_idx: u32,
2782        dst_cortical_idx: u32,
2783        rule_obj: &serde_json::Map<String, serde_json::Value>,
2784        bidirectional_stdp: bool,
2785        synapse_psp: f32,
2786        synapse_type: feagi_npu_neural::SynapseType,
2787    ) -> BduResult<()> {
2788        let plasticity_window = rule_obj
2789            .get("plasticity_window")
2790            .and_then(Self::json_number_as_usize_for_stdp)
2791            .ok_or_else(|| {
2792                BduError::Internal(format!(
2793                    "Missing plasticity_window in plastic mapping rule {} -> {}",
2794                    src_area_id, dst_area_id
2795                ))
2796            })?;
2797        let plasticity_constant = rule_obj
2798            .get("plasticity_constant")
2799            .and_then(Self::json_number_as_i64_for_stdp)
2800            .ok_or_else(|| {
2801                BduError::Internal(format!(
2802                    "Missing plasticity_constant in plastic mapping rule {} -> {}",
2803                    src_area_id, dst_area_id
2804                ))
2805            })?;
2806        let ltp_i64 = rule_obj
2807            .get("ltp_multiplier")
2808            .and_then(Self::json_number_as_i64_for_stdp)
2809            .ok_or_else(|| {
2810                BduError::Internal(format!(
2811                    "Missing ltp_multiplier in plastic mapping rule {} -> {}",
2812                    src_area_id, dst_area_id
2813                ))
2814            })?;
2815        let ltp_multiplier = i8::try_from(ltp_i64).map_err(|_| {
2816            BduError::Internal(format!(
2817                "ltp_multiplier must fit in i8 range {}..={} (got {}) on mapping {} -> {}",
2818                i8::MIN,
2819                i8::MAX,
2820                ltp_i64,
2821                src_area_id,
2822                dst_area_id
2823            ))
2824        })?;
2825        let ltd_i64 = rule_obj
2826            .get("ltd_multiplier")
2827            .and_then(Self::json_number_as_i64_for_stdp)
2828            .ok_or_else(|| {
2829                BduError::Internal(format!(
2830                    "Missing ltd_multiplier in plastic mapping rule {} -> {}",
2831                    src_area_id, dst_area_id
2832                ))
2833            })?;
2834        let ltd_multiplier = i8::try_from(ltd_i64).map_err(|_| {
2835            BduError::Internal(format!(
2836                "ltd_multiplier must fit in i8 range {}..={} (got {}) on mapping {} -> {}",
2837                i8::MIN,
2838                i8::MAX,
2839                ltd_i64,
2840                src_area_id,
2841                dst_area_id
2842            ))
2843        })?;
2844
2845        // Resolve plasticity_mode with legacy fallback (auto-migrate strategy):
2846        //   - new genomes set `plasticity_mode: "off" | "stdp" | "rstdp"` directly;
2847        //   - legacy genomes only have `plasticity_flag: bool` -> Stdp / Off mapping.
2848        let plasticity_mode = match rule_obj.get("plasticity_mode").and_then(|v| v.as_str()) {
2849            Some(s) if s.eq_ignore_ascii_case("rstdp") || s.eq_ignore_ascii_case("r-stdp") => {
2850                feagi_npu_burst_engine::npu::PlasticityMode::RStdp
2851            }
2852            Some(s) if s.eq_ignore_ascii_case("stdp") => {
2853                feagi_npu_burst_engine::npu::PlasticityMode::Stdp
2854            }
2855            Some(s) if s.eq_ignore_ascii_case("off") => {
2856                feagi_npu_burst_engine::npu::PlasticityMode::Off
2857            }
2858            Some(other) => {
2859                return Err(BduError::Internal(format!(
2860                    "Unknown plasticity_mode '{}' in mapping rule {} -> {}",
2861                    other, src_area_id, dst_area_id
2862                )));
2863            }
2864            None => feagi_npu_burst_engine::npu::PlasticityMode::Stdp,
2865        };
2866
2867        // R-STDP-only fields. Strings name cortical areas by 6-char base-64 ID; resolve via NPU.
2868        let eligibility_decay_bursts = rule_obj
2869            .get("eligibility_decay_bursts")
2870            .and_then(|v| v.as_u64())
2871            .map(|n| n as u32)
2872            .unwrap_or(0);
2873        let reward_source_area_id = rule_obj
2874            .get("reward_source_area")
2875            .and_then(|v| v.as_str())
2876            .map(str::to_string);
2877        let punishment_source_area_id = rule_obj
2878            .get("punishment_source_area")
2879            .and_then(|v| v.as_str())
2880            .map(str::to_string);
2881
2882        // Optional upper-bound clamp for plasticity weight commits. Absent / null means no
2883        // clamp (legacy unbounded behaviour). When provided, must be a strictly positive
2884        // f32 (finite or `+inf`); `NaN`, zero, and negatives are rejected so the runtime
2885        // never sees a malformed sentinel.
2886        let max_weight_provided = rule_obj.get("max_weight").is_some()
2887            && !rule_obj
2888                .get("max_weight")
2889                .map(|v| v.is_null())
2890                .unwrap_or(true);
2891        let max_weight: f32 = if max_weight_provided {
2892            let raw = rule_obj
2893                .get("max_weight")
2894                .and_then(|v| v.as_f64())
2895                .ok_or_else(|| {
2896                    BduError::Internal(format!(
2897                        "max_weight must be a number on mapping {} -> {}",
2898                        src_area_id, dst_area_id
2899                    ))
2900                })?;
2901            if raw.is_nan() || raw <= 0.0 {
2902                return Err(BduError::Internal(format!(
2903                    "max_weight must be strictly positive (got {}) on mapping {} -> {}",
2904                    raw, src_area_id, dst_area_id
2905                )));
2906            }
2907            raw as f32
2908        } else {
2909            f32::INFINITY
2910        };
2911
2912        // Optional f32 learning-rate scale on the end-of-burst weight commit: w += eta * R * e.
2913        // Omitted / null → 1.0. Must be finite, strictly positive, and not +inf.
2914        let plasticity_eta_provided = rule_obj.get("plasticity_eta").is_some()
2915            && !rule_obj
2916                .get("plasticity_eta")
2917                .map(|v| v.is_null())
2918                .unwrap_or(true);
2919        let plasticity_eta: f32 = if plasticity_eta_provided {
2920            let raw = rule_obj
2921                .get("plasticity_eta")
2922                .and_then(|v| v.as_f64())
2923                .ok_or_else(|| {
2924                    BduError::Internal(format!(
2925                        "plasticity_eta must be a number on mapping {} -> {}",
2926                        src_area_id, dst_area_id
2927                    ))
2928                })?;
2929            if raw.is_nan() || raw <= 0.0 || !raw.is_finite() {
2930                return Err(BduError::Internal(format!(
2931                    "plasticity_eta must be finite and strictly positive (got {}) on mapping {} -> {}",
2932                    raw, src_area_id, dst_area_id
2933                )));
2934            }
2935            raw as f32
2936        } else {
2937            1.0
2938        };
2939
2940        // Validate R-STDP fields are absent when not in RStdp mode (catches genome typos early).
2941        if !matches!(
2942            plasticity_mode,
2943            feagi_npu_burst_engine::npu::PlasticityMode::RStdp
2944        ) && (reward_source_area_id.is_some()
2945            || punishment_source_area_id.is_some()
2946            || eligibility_decay_bursts != 0)
2947        {
2948            return Err(BduError::Internal(format!(
2949                "R-STDP fields (reward_source_area / punishment_source_area / eligibility_decay_bursts) \
2950                 only valid when plasticity_mode='rstdp' on mapping {} -> {}",
2951                src_area_id, dst_area_id
2952            )));
2953        }
2954
2955        // `max_weight` is only meaningful when plasticity is active. Reject explicit values
2956        // on Off-mode mappings to surface genome typos early; an absent field silently
2957        // resolves to `f32::INFINITY` above and is fine.
2958        if matches!(
2959            plasticity_mode,
2960            feagi_npu_burst_engine::npu::PlasticityMode::Off
2961        ) && max_weight_provided
2962        {
2963            return Err(BduError::Internal(format!(
2964                "max_weight is only valid when plasticity_mode is 'stdp' or 'rstdp' (got off) on mapping {} -> {}",
2965                src_area_id, dst_area_id
2966            )));
2967        }
2968
2969        if matches!(
2970            plasticity_mode,
2971            feagi_npu_burst_engine::npu::PlasticityMode::Off
2972        ) && plasticity_eta_provided
2973        {
2974            return Err(BduError::Internal(format!(
2975                "plasticity_eta is only valid when plasticity_mode is 'stdp' or 'rstdp' (got off) on mapping {} -> {}",
2976                src_area_id, dst_area_id
2977            )));
2978        }
2979
2980        trace!(target: "feagi-bdu", "[LOCK-TRACE] create_neurons_for_area: attempting NPU lock");
2981        let mut npu_lock = npu
2982            .lock()
2983            .map_err(|e| BduError::Internal(format!("Failed to lock NPU: {}", e)))?;
2984        trace!(target: "feagi-bdu", "[LOCK-TRACE] create_neurons_for_area: acquired NPU lock");
2985
2986        // Resolve reward/punishment area names to cortical_idx (R-STDP only). The detector
2987        // areas must already be registered with the NPU before this mapping is parsed; the
2988        // genome ordering normally handles this because cortical areas are processed before
2989        // their cross-area mapping rules.
2990        let resolve_optional_area =
2991            |label: &str, name_opt: &Option<String>| -> BduResult<Option<u32>> {
2992                let Some(name) = name_opt else {
2993                    return Ok(None);
2994                };
2995                match npu_lock.get_cortical_area_id(name.as_str()) {
2996                    Some(idx) => Ok(Some(idx)),
2997                    None => Err(BduError::Internal(format!(
2998                        "Unknown {} cortical area '{}' on R-STDP mapping {} -> {}",
2999                        label, name, src_area_id, dst_area_id
3000                    ))),
3001                }
3002            };
3003        let reward_source_area =
3004            resolve_optional_area("reward_source_area", &reward_source_area_id)?;
3005        let punishment_source_area =
3006            resolve_optional_area("punishment_source_area", &punishment_source_area_id)?;
3007
3008        // Off-mode mappings are skipped (no NPU registration, no fire-ledger tracking).
3009        if matches!(
3010            plasticity_mode,
3011            feagi_npu_burst_engine::npu::PlasticityMode::Off
3012        ) {
3013            return Ok(());
3014        }
3015
3016        let params = feagi_npu_burst_engine::npu::StdpMappingParams {
3017            plasticity_window,
3018            plasticity_constant,
3019            ltp_multiplier,
3020            ltd_multiplier,
3021            bidirectional_stdp,
3022            associative_memory_mapping: rule_obj
3023                .get("morphology_id")
3024                .and_then(|value| value.as_str())
3025                == Some("associative_memory"),
3026            synapse_psp,
3027            synapse_type,
3028            plasticity_mode,
3029            eligibility_decay_bursts,
3030            reward_source_area,
3031            punishment_source_area,
3032            max_weight,
3033            plasticity_eta,
3034        };
3035
3036        npu_lock
3037            .register_stdp_mapping(src_cortical_idx, dst_cortical_idx, params)
3038            .map_err(|e| {
3039                BduError::Internal(format!(
3040                    "Failed to register STDP mapping {} -> {}: {}",
3041                    src_area_id, dst_area_id, e
3042                ))
3043            })?;
3044
3045        // FireLedger tracking. Plain STDP needs depth=plasticity_window on src+dst. R-STDP
3046        // additionally needs depth>=1 on reward/punishment source areas so `activity_density`
3047        // can sample current-burst firing.
3048        let mut areas_to_track: Vec<(u32, usize)> = vec![
3049            (src_cortical_idx, plasticity_window),
3050            (dst_cortical_idx, plasticity_window),
3051        ];
3052        if let Some(area) = reward_source_area {
3053            areas_to_track.push((area, 1));
3054        }
3055        if let Some(area) = punishment_source_area {
3056            areas_to_track.push((area, 1));
3057        }
3058
3059        let existing_configs = npu_lock.get_all_fire_ledger_configs();
3060        for (area_idx, required_depth) in areas_to_track {
3061            let existing = existing_configs
3062                .iter()
3063                .find(|(idx, _)| *idx == area_idx)
3064                .map(|(_, w)| *w)
3065                .unwrap_or(0);
3066            let resolved = existing.max(required_depth);
3067            if resolved != existing {
3068                npu_lock
3069                    .configure_fire_ledger_window(area_idx, resolved)
3070                    .map_err(|e| {
3071                        BduError::Internal(format!(
3072                            "Failed to configure FireLedger window for area idx={} (requested={}): {}",
3073                            area_idx, resolved, e
3074                        ))
3075                    })?;
3076            }
3077        }
3078
3079        Ok(())
3080    }
3081
3082    /// Resolve synapse weight, PSP, type, and per-synapse delay (bursts) from a mapping rule.
3083    fn resolve_synapse_params_for_rule(
3084        &self,
3085        src_area_id: &CorticalID,
3086        rule: &serde_json::Value,
3087    ) -> BduResult<(f32, f32, feagi_npu_neural::SynapseType, u8)> {
3088        // Get source area to access PSP property
3089        let src_area = self.cortical_areas.get(src_area_id).ok_or_else(|| {
3090            crate::types::BduError::InvalidArea(format!("Source area not found: {}", src_area_id))
3091        })?;
3092
3093        // Extract weight from rule (`postSynapticCurrent_multiplier`) as full-precision float.
3094        let (weight, synapse_type) = {
3095            let parse_f64 = |v: &serde_json::Value| -> Option<f64> {
3096                if let Some(i) = v.as_i64() {
3097                    return Some(i as f64);
3098                }
3099                v.as_f64()
3100            };
3101
3102            let mult: f64 = if let Some(obj) = rule.as_object() {
3103                obj.get("postSynapticCurrent_multiplier")
3104                    .and_then(parse_f64)
3105                    .unwrap_or(1.0)
3106            } else if let Some(arr) = rule.as_array() {
3107                arr.get(2).and_then(parse_f64).unwrap_or(1.0)
3108            } else {
3109                128.0
3110            };
3111
3112            if mult < 0.0 {
3113                (mult.abs() as f32, feagi_npu_neural::SynapseType::Inhibitory)
3114            } else {
3115                (mult as f32, feagi_npu_neural::SynapseType::Excitatory)
3116            }
3117        };
3118
3119        // PSP from source cortical area (float; stored as f32 on synapses)
3120        use crate::models::cortical_area::CorticalAreaExt;
3121        let psp_f32 = src_area.postsynaptic_current();
3122
3123        let delay_bursts: u8 = if let Some(obj) = rule.as_object() {
3124            obj.get("synaptic_delay_bursts")
3125                .and_then(|v| v.as_u64())
3126                .map(|d| u8::try_from(d).unwrap_or(1))
3127                .unwrap_or(1)
3128        } else if let Some(arr) = rule.as_array() {
3129            arr.get(8)
3130                .and_then(|v| v.as_u64())
3131                .map(|d| u8::try_from(d).unwrap_or(1))
3132                .unwrap_or(1)
3133        } else {
3134            1
3135        };
3136        if delay_bursts < 1 {
3137            return Err(crate::types::BduError::Internal(format!(
3138                "synaptic_delay_bursts must be >= 1 (src area {})",
3139                src_area_id.as_base_64()
3140            )));
3141        }
3142
3143        tracing::debug!(
3144            target: "feagi-bdu",
3145            "Resolved synapse params src={} weight={} psp={} type={:?} delay_bursts={}",
3146            src_area_id.as_base_64(),
3147            weight,
3148            psp_f32,
3149            synapse_type,
3150            delay_bursts
3151        );
3152
3153        Ok((weight, psp_f32, synapse_type, delay_bursts))
3154    }
3155
3156    /// Apply cortical mapping for a specific area pair
3157    fn apply_cortical_mapping_for_pair(
3158        &mut self,
3159        src_area_id: &CorticalID,
3160        dst_area_id: &CorticalID,
3161    ) -> BduResult<usize> {
3162        // Clone the rules to avoid borrow checker issues.
3163        //
3164        // IMPORTANT: absence of mapping rules is a valid state (e.g. mapping deletion).
3165        // In that case, return Ok(0) rather than an error so API callers can treat
3166        // "deleted mapping" as success (and BV can update its cache/UI).
3167        let rules = {
3168            let src_area = self.cortical_areas.get(src_area_id).ok_or_else(|| {
3169                crate::types::BduError::InvalidArea(format!(
3170                    "Source area not found: {}",
3171                    src_area_id
3172                ))
3173            })?;
3174
3175            let Some(mapping_dst) = src_area
3176                .properties
3177                .get("cortical_mapping_dst")
3178                .and_then(|v| v.as_object())
3179            else {
3180                return Ok(0);
3181            };
3182
3183            let Some(rules) = Self::get_mapping_rules_for_destination(mapping_dst, dst_area_id)
3184            else {
3185                return Ok(0);
3186            };
3187
3188            rules.clone()
3189        }; // Borrow ends here
3190
3191        if rules.is_empty() {
3192            return Ok(0);
3193        }
3194
3195        // Get indices for STDP handling
3196        let src_cortical_idx = *self.cortical_id_to_idx.get(src_area_id).ok_or_else(|| {
3197            crate::types::BduError::InvalidArea(format!("No index for {}", src_area_id))
3198        })?;
3199        let dst_cortical_idx = *self.cortical_id_to_idx.get(dst_area_id).ok_or_else(|| {
3200            crate::types::BduError::InvalidArea(format!("No index for {}", dst_area_id))
3201        })?;
3202
3203        // Clone NPU Arc for STDP handling (Arc::clone is cheap - just increments ref count)
3204        let npu_arc = self
3205            .npu
3206            .as_ref()
3207            .ok_or_else(|| crate::types::BduError::Internal("NPU not connected".to_string()))?
3208            .clone();
3209
3210        tracing::debug!(
3211            target: "feagi-bdu",
3212            "Applying {} mapping rule(s) for {} -> {}",
3213            rules.len(),
3214            src_area_id,
3215            dst_area_id
3216        );
3217        // Apply each morphology rule
3218        let mut total_synapses = 0;
3219        for rule in &rules {
3220            let morphology_id = if let Some(rule_obj) = rule.as_object() {
3221                rule_obj
3222                    .get("morphology_id")
3223                    .and_then(|v| v.as_str())
3224                    .unwrap_or("unknown")
3225                    .to_string()
3226            } else if let Some(rule_arr) = rule.as_array() {
3227                rule_arr
3228                    .first()
3229                    .and_then(|v| v.as_str())
3230                    .unwrap_or("unknown")
3231                    .to_string()
3232            } else {
3233                "unknown".to_string()
3234            };
3235
3236            let rule_keys: Vec<String> = rule
3237                .as_object()
3238                .map(|obj| obj.keys().cloned().collect())
3239                .unwrap_or_default();
3240
3241            // Handle STDP/plasticity configuration if needed
3242            let mut plasticity_flag = rule
3243                .as_object()
3244                .and_then(|obj| obj.get("plasticity_flag"))
3245                .and_then(|v| v.as_bool())
3246                .unwrap_or(false);
3247            if morphology_id == "associative_memory" {
3248                plasticity_flag = true;
3249            }
3250            if plasticity_flag {
3251                let Some(rule_obj) = rule.as_object() else {
3252                    return Err(crate::types::BduError::InvalidMorphology(
3253                        "Plasticity mapping rule must be an object format".to_string(),
3254                    ));
3255                };
3256                let (_weight, psp, synapse_type, _delay_bursts) =
3257                    self.resolve_synapse_params_for_rule(src_area_id, rule)?;
3258                // Associative-memory mappings are directional.
3259                // Bidirectional behavior requires two explicit mappings (A->B and B->A).
3260                let bidirectional_stdp = false;
3261                if let Err(e) = Self::register_stdp_mapping_for_rule(
3262                    &npu_arc,
3263                    src_area_id,
3264                    dst_area_id,
3265                    src_cortical_idx,
3266                    dst_cortical_idx,
3267                    rule_obj,
3268                    bidirectional_stdp,
3269                    psp,
3270                    synapse_type,
3271                ) {
3272                    tracing::error!(
3273                        target: "feagi-bdu",
3274                        "STDP mapping registration failed for {} -> {} (morphology={}, keys={:?}): {}",
3275                        src_area_id,
3276                        dst_area_id,
3277                        morphology_id,
3278                        rule_keys,
3279                        e
3280                    );
3281                    return Err(e);
3282                }
3283            }
3284
3285            // Handle conditional gate (transistor synapse) configuration if present.
3286            // The gate_source_area field specifies a cortical area whose firing activity
3287            // gates propagation through all synapses created by this mapping rule.
3288            if let Some(gate_area_str) = rule
3289                .as_object()
3290                .and_then(|obj| obj.get("gate_source_area"))
3291                .and_then(|v| v.as_str())
3292            {
3293                let gate_area_id = CorticalID::try_from_base_64(gate_area_str).map_err(|_| {
3294                    crate::types::BduError::Internal(format!(
3295                        "Invalid gate_source_area '{}' on mapping {} -> {}",
3296                        gate_area_str, src_area_id, dst_area_id
3297                    ))
3298                })?;
3299                let gate_cortical_idx =
3300                    self.cortical_id_to_idx.get(&gate_area_id).ok_or_else(|| {
3301                        crate::types::BduError::Internal(format!(
3302                            "Unknown gate_source_area '{}' on mapping {} -> {}",
3303                            gate_area_str, src_area_id, dst_area_id
3304                        ))
3305                    })?;
3306
3307                let mut npu_lock = npu_arc.lock().map_err(|_| {
3308                    crate::types::BduError::Internal(
3309                        "Failed to acquire NPU lock for gate registration".to_string(),
3310                    )
3311                })?;
3312                if let Err(e) = npu_lock.register_gate_mapping(
3313                    src_cortical_idx,
3314                    dst_cortical_idx,
3315                    *gate_cortical_idx,
3316                ) {
3317                    tracing::error!(
3318                        target: "feagi-bdu",
3319                        "Gate mapping registration failed for {} -> {} (gate={}): {}",
3320                        src_area_id,
3321                        dst_area_id,
3322                        gate_area_str,
3323                        e
3324                    );
3325                    return Err(crate::types::BduError::Internal(format!(
3326                        "Gate registration failed: {}",
3327                        e
3328                    )));
3329                }
3330            }
3331
3332            // Apply the morphology rule
3333            let synapse_count = match self.apply_single_morphology_rule(
3334                src_area_id,
3335                dst_area_id,
3336                rule,
3337            ) {
3338                Ok(count) => count,
3339                Err(e) => {
3340                    tracing::error!(
3341                        target: "feagi-bdu",
3342                        "Mapping rule application failed for {} -> {} (morphology={}, keys={:?}): {}",
3343                        src_area_id,
3344                        dst_area_id,
3345                        morphology_id,
3346                        rule_keys,
3347                        e
3348                    );
3349                    return Err(e);
3350                }
3351            };
3352            total_synapses += synapse_count;
3353            tracing::debug!(
3354                target: "feagi-bdu",
3355                "Rule {} created {} synapses for {} -> {}",
3356                morphology_id,
3357                synapse_count,
3358                src_area_id,
3359                dst_area_id
3360            );
3361        }
3362
3363        Ok(total_synapses)
3364    }
3365
3366    /// Apply a function-type morphology (projector, memory, block_to_block, etc.)
3367    ///
3368    /// This helper consolidates all function-type morphology logic in one place.
3369    /// Function-type morphologies are code-driven and require code changes to add new ones.
3370    ///
3371    /// # Arguments
3372    /// * `morphology_id` - The morphology ID string (e.g., "projector", "block_to_block")
3373    /// * `rule` - The morphology rule JSON value
3374    /// * `npu_arc` - Arc to the NPU (for batched operations)
3375    /// * `npu` - Locked NPU reference
3376    /// * `src_area_id`, `dst_area_id` - Source and destination area IDs
3377    /// * `src_idx`, `dst_idx` - Source and destination area indices
3378    /// * `weight`, `psp`, `synapse_attractivity` - Synapse parameters
3379    #[allow(clippy::too_many_arguments)]
3380    fn apply_function_morphology(
3381        &self,
3382        morphology_id: &str,
3383        rule: &serde_json::Value,
3384        npu_arc: &Arc<feagi_npu_burst_engine::TracingMutex<feagi_npu_burst_engine::DynamicNPU>>,
3385        npu: &mut feagi_npu_burst_engine::DynamicNPU,
3386        src_area_id: &CorticalID,
3387        dst_area_id: &CorticalID,
3388        src_idx: u32,
3389        dst_idx: u32,
3390        weight: f32,
3391        psp: f32,
3392        synapse_attractivity: u8,
3393        synapse_type: feagi_npu_neural::SynapseType,
3394        delay_bursts: u8,
3395    ) -> BduResult<usize> {
3396        match morphology_id {
3397            "projector" | "transpose_xy" | "transpose_yz" | "transpose_xz" => {
3398                // Get dimensions from cortical areas (no neuron scanning!)
3399                let src_area = self.cortical_areas.get(src_area_id).ok_or_else(|| {
3400                    crate::types::BduError::InvalidArea(format!(
3401                        "Source area not found: {}",
3402                        src_area_id
3403                    ))
3404                })?;
3405                let dst_area = self.cortical_areas.get(dst_area_id).ok_or_else(|| {
3406                    crate::types::BduError::InvalidArea(format!(
3407                        "Destination area not found: {}",
3408                        dst_area_id
3409                    ))
3410                })?;
3411
3412                let src_dimensions = (
3413                    src_area.dimensions.width as usize,
3414                    src_area.dimensions.height as usize,
3415                    src_area.dimensions.depth as usize,
3416                );
3417                let dst_dimensions = (
3418                    dst_area.dimensions.width as usize,
3419                    dst_area.dimensions.height as usize,
3420                    dst_area.dimensions.depth as usize,
3421                );
3422
3423                // Legacy-compatible transpose mappings from Python FEAGI:
3424                // projector_xy -> (y, x, z), projector_yz -> (x, z, y), projector_xz -> (z, y, x)
3425                let transpose = match morphology_id {
3426                    "transpose_xy" => Some((1, 0, 2)),
3427                    "transpose_yz" => Some((0, 2, 1)),
3428                    "transpose_xz" => Some((2, 1, 0)),
3429                    _ => None,
3430                };
3431
3432                use crate::connectivity::core_morphologies::apply_projector_morphology_with_dimensions;
3433                let count = apply_projector_morphology_with_dimensions(
3434                    npu,
3435                    src_idx,
3436                    dst_idx,
3437                    src_dimensions,
3438                    dst_dimensions,
3439                    transpose,
3440                    None, // project_last_layer_of
3441                    weight,
3442                    psp,
3443                    synapse_attractivity,
3444                    synapse_type,
3445                    0,
3446                    delay_bursts,
3447                )?;
3448                // Ensure the propagation engine sees the newly created synapses immediately
3449                npu.rebuild_synapse_index();
3450                Ok(count as usize)
3451            }
3452            "centered_projector" => {
3453                let src_area = self.cortical_areas.get(src_area_id).ok_or_else(|| {
3454                    crate::types::BduError::InvalidArea(format!(
3455                        "Source area not found: {}",
3456                        src_area_id
3457                    ))
3458                })?;
3459                let dst_area = self.cortical_areas.get(dst_area_id).ok_or_else(|| {
3460                    crate::types::BduError::InvalidArea(format!(
3461                        "Destination area not found: {}",
3462                        dst_area_id
3463                    ))
3464                })?;
3465
3466                let src_dimensions = (
3467                    src_area.dimensions.width as usize,
3468                    src_area.dimensions.height as usize,
3469                    src_area.dimensions.depth as usize,
3470                );
3471                let dst_dimensions = (
3472                    dst_area.dimensions.width as usize,
3473                    dst_area.dimensions.height as usize,
3474                    dst_area.dimensions.depth as usize,
3475                );
3476
3477                let count = crate::connectivity::core_morphologies::apply_centered_projector_morphology_with_dimensions(
3478                    npu,
3479                    src_idx,
3480                    dst_idx,
3481                    src_dimensions,
3482                    dst_dimensions,
3483                    weight,
3484                    psp,
3485                    synapse_attractivity,
3486                    synapse_type,
3487                    delay_bursts,
3488                )?;
3489                if count > 0 {
3490                    npu.rebuild_synapse_index();
3491                }
3492                Ok(count as usize)
3493            }
3494            "episodic_memory" => {
3495                // Episodic memory morphology: No physical synapses created
3496                // Pattern detection and memory neuron creation handled by PlasticityService
3497                use tracing::trace;
3498                trace!(
3499                    target: "feagi-bdu",
3500                    "Episodic memory morphology: {} -> {} (no physical synapses, plasticity-driven)",
3501                    src_idx, dst_idx
3502                );
3503                Ok(0)
3504            }
3505            "memory_replay" => {
3506                // Replay mapping: semantic only, no physical synapses
3507                use tracing::trace;
3508                trace!(
3509                    target: "feagi-bdu",
3510                    "Memory replay morphology: {} -> {} (no physical synapses)",
3511                    src_idx, dst_idx
3512                );
3513                Ok(0)
3514            }
3515            "associative_memory" => {
3516                // Associative memory (bi-directional STDP) mapping:
3517                // If both ends are memory areas, create synapses between LIF twins to enable associations.
3518                // Otherwise, no initial synapses are created (STDP will update existing synapses).
3519                let src_area = self.cortical_areas.get(src_area_id).ok_or_else(|| {
3520                    crate::types::BduError::InvalidArea(format!(
3521                        "Source area not found: {}",
3522                        src_area_id
3523                    ))
3524                })?;
3525                let dst_area = self.cortical_areas.get(dst_area_id).ok_or_else(|| {
3526                    crate::types::BduError::InvalidArea(format!(
3527                        "Destination area not found: {}",
3528                        dst_area_id
3529                    ))
3530                })?;
3531
3532                if matches!(src_area.cortical_type, CorticalAreaType::Memory(_))
3533                    && matches!(dst_area.cortical_type, CorticalAreaType::Memory(_))
3534                {
3535                    let src_dimensions = (
3536                        src_area.dimensions.width as usize,
3537                        src_area.dimensions.height as usize,
3538                        src_area.dimensions.depth as usize,
3539                    );
3540                    let dst_dimensions = (
3541                        dst_area.dimensions.width as usize,
3542                        dst_area.dimensions.height as usize,
3543                        dst_area.dimensions.depth as usize,
3544                    );
3545                    use crate::connectivity::core_morphologies::apply_projector_morphology_with_dimensions;
3546                    let count = apply_projector_morphology_with_dimensions(
3547                        npu,
3548                        src_idx,
3549                        dst_idx,
3550                        src_dimensions,
3551                        dst_dimensions,
3552                        None,
3553                        None,
3554                        weight,
3555                        psp,
3556                        synapse_attractivity,
3557                        synapse_type,
3558                        SYNAPSE_EDGE_ASSOCIATIVE_MEMORY,
3559                        delay_bursts,
3560                    )?;
3561                    npu.rebuild_synapse_index();
3562                    Ok(count as usize)
3563                } else {
3564                    Ok(0)
3565                }
3566            }
3567            "block_to_block" => {
3568                tracing::warn!(
3569                    target: "feagi-bdu",
3570                    "🔍 DEBUG apply_function_morphology: block_to_block case reached with src_idx={}, dst_idx={}",
3571                    src_idx, dst_idx
3572                );
3573                // Get dimensions from cortical areas (no neuron scanning!)
3574                let src_area = self.cortical_areas.get(src_area_id).ok_or_else(|| {
3575                    crate::types::BduError::InvalidArea(format!(
3576                        "Source area not found: {}",
3577                        src_area_id
3578                    ))
3579                })?;
3580                let dst_area = self.cortical_areas.get(dst_area_id).ok_or_else(|| {
3581                    crate::types::BduError::InvalidArea(format!(
3582                        "Destination area not found: {}",
3583                        dst_area_id
3584                    ))
3585                })?;
3586
3587                let src_dimensions = (
3588                    src_area.dimensions.width as usize,
3589                    src_area.dimensions.height as usize,
3590                    src_area.dimensions.depth as usize,
3591                );
3592                let dst_dimensions = (
3593                    dst_area.dimensions.width as usize,
3594                    dst_area.dimensions.height as usize,
3595                    dst_area.dimensions.depth as usize,
3596                );
3597
3598                // Extract scalar from rule (morphology_scalar)
3599                let scalar = if let Some(obj) = rule.as_object() {
3600                    // Object format: get from morphology_scalar array
3601                    if let Some(scalar_arr) =
3602                        obj.get("morphology_scalar").and_then(|v| v.as_array())
3603                    {
3604                        // Use first element as scalar (or default to 1)
3605                        scalar_arr.first().and_then(|v| v.as_i64()).unwrap_or(1) as u32
3606                    } else {
3607                        1 // @architecture:acceptable - default scalar
3608                    }
3609                } else if let Some(arr) = rule.as_array() {
3610                    // Array format: [morphology_id, scalar, multiplier, ...]
3611                    arr.get(1).and_then(|v| v.as_i64()).unwrap_or(1) as u32
3612                } else {
3613                    1 // @architecture:acceptable - default scalar
3614                };
3615
3616                // CRITICAL: Do NOT call get_neurons_in_cortical_area to check neuron count!
3617                // Use dimensions to estimate: if area is large, use batched version
3618                let estimated_neurons = src_dimensions.0 * src_dimensions.1 * src_dimensions.2;
3619                let count = if estimated_neurons > 100_000 {
3620                    // Release lock and use batched version
3621                    let _ = npu;
3622
3623                    crate::connectivity::synaptogenesis::apply_block_connection_morphology_batched(
3624                        npu_arc,
3625                        src_idx,
3626                        dst_idx,
3627                        src_dimensions,
3628                        dst_dimensions,
3629                        scalar, // scaling_factor
3630                        weight,
3631                        psp,
3632                        synapse_attractivity,
3633                        synapse_type,
3634                        delay_bursts,
3635                    )? as usize
3636                } else {
3637                    // Small area: use regular version (faster for small counts)
3638                    tracing::warn!(
3639                        target: "feagi-bdu",
3640                        "🔍 DEBUG connectome_manager: Calling apply_block_connection_morphology with src_idx={}, dst_idx={}, src_dim={:?}, dst_dim={:?}",
3641                        src_idx, dst_idx, src_dimensions, dst_dimensions
3642                    );
3643                    let count =
3644                        crate::connectivity::synaptogenesis::apply_block_connection_morphology(
3645                            npu,
3646                            src_idx,
3647                            dst_idx,
3648                            src_dimensions,
3649                            dst_dimensions,
3650                            scalar, // scaling_factor
3651                            weight,
3652                            psp,
3653                            synapse_attractivity,
3654                            synapse_type,
3655                            delay_bursts,
3656                        )? as usize;
3657                    tracing::warn!(
3658                        target: "feagi-bdu",
3659                        "🔍 DEBUG connectome_manager: apply_block_connection_morphology returned count={}",
3660                        count
3661                    );
3662                    // Rebuild synapse index while we still have the lock
3663                    if count > 0 {
3664                        npu.rebuild_synapse_index();
3665                    }
3666                    count
3667                };
3668
3669                // Ensure the propagation engine sees the newly created synapses immediately (batched version only)
3670                if count > 0 && estimated_neurons > 100_000 {
3671                    let mut npu_lock = npu_arc.lock().unwrap();
3672                    npu_lock.rebuild_synapse_index();
3673                }
3674
3675                Ok(count)
3676            }
3677            "bitmask_encoder_x" | "bitmask_encoder_y" | "bitmask_encoder_z"
3678            | "bitmask_decoder_x" | "bitmask_decoder_y" | "bitmask_decoder_z" => {
3679                let src_area = self.cortical_areas.get(src_area_id).ok_or_else(|| {
3680                    crate::types::BduError::InvalidArea(format!(
3681                        "Source area not found: {}",
3682                        src_area_id
3683                    ))
3684                })?;
3685                let dst_area = self.cortical_areas.get(dst_area_id).ok_or_else(|| {
3686                    crate::types::BduError::InvalidArea(format!(
3687                        "Destination area not found: {}",
3688                        dst_area_id
3689                    ))
3690                })?;
3691
3692                let src_dimensions = (
3693                    src_area.dimensions.width as usize,
3694                    src_area.dimensions.height as usize,
3695                    src_area.dimensions.depth as usize,
3696                );
3697                let dst_dimensions = (
3698                    dst_area.dimensions.width as usize,
3699                    dst_area.dimensions.height as usize,
3700                    dst_area.dimensions.depth as usize,
3701                );
3702
3703                let (axis, mode) = match morphology_id {
3704                    "bitmask_encoder_x" => (
3705                        crate::connectivity::core_morphologies::BitmaskAxis::X,
3706                        crate::connectivity::core_morphologies::BitmaskMode::Encoder,
3707                    ),
3708                    "bitmask_encoder_y" => (
3709                        crate::connectivity::core_morphologies::BitmaskAxis::Y,
3710                        crate::connectivity::core_morphologies::BitmaskMode::Encoder,
3711                    ),
3712                    "bitmask_encoder_z" => (
3713                        crate::connectivity::core_morphologies::BitmaskAxis::Z,
3714                        crate::connectivity::core_morphologies::BitmaskMode::Encoder,
3715                    ),
3716                    "bitmask_decoder_x" => (
3717                        crate::connectivity::core_morphologies::BitmaskAxis::X,
3718                        crate::connectivity::core_morphologies::BitmaskMode::Decoder,
3719                    ),
3720                    "bitmask_decoder_y" => (
3721                        crate::connectivity::core_morphologies::BitmaskAxis::Y,
3722                        crate::connectivity::core_morphologies::BitmaskMode::Decoder,
3723                    ),
3724                    "bitmask_decoder_z" => (
3725                        crate::connectivity::core_morphologies::BitmaskAxis::Z,
3726                        crate::connectivity::core_morphologies::BitmaskMode::Decoder,
3727                    ),
3728                    _ => unreachable!("matched bitmask morphology above"),
3729                };
3730
3731                let count =
3732                    crate::connectivity::core_morphologies::apply_bitmask_morphology_with_dimensions(
3733                        npu,
3734                        src_idx,
3735                        dst_idx,
3736                        src_dimensions,
3737                        dst_dimensions,
3738                        axis,
3739                        mode,
3740                        weight,
3741                        psp,
3742                        synapse_attractivity,
3743                        synapse_type,
3744                        delay_bursts,
3745                    )?;
3746                if count > 0 {
3747                    npu.rebuild_synapse_index();
3748                }
3749                Ok(count as usize)
3750            }
3751            "sweeper" => {
3752                let dst_area = self.cortical_areas.get(dst_area_id).ok_or_else(|| {
3753                    crate::types::BduError::InvalidArea(format!(
3754                        "Destination area not found: {}",
3755                        dst_area_id
3756                    ))
3757                })?;
3758                let dst_dimensions = (
3759                    dst_area.dimensions.width as usize,
3760                    dst_area.dimensions.height as usize,
3761                    dst_area.dimensions.depth as usize,
3762                );
3763
3764                let count =
3765                    crate::connectivity::core_morphologies::apply_sweeper_morphology_with_dimensions(
3766                        npu,
3767                        src_idx,
3768                        dst_idx,
3769                        dst_dimensions,
3770                        weight,
3771                        psp,
3772                        synapse_attractivity,
3773                        synapse_type,
3774                        delay_bursts,
3775                    )?;
3776                if count > 0 {
3777                    npu.rebuild_synapse_index();
3778                }
3779                Ok(count as usize)
3780            }
3781            "last_to_first" => {
3782                let src_area = self.cortical_areas.get(src_area_id).ok_or_else(|| {
3783                    crate::types::BduError::InvalidArea(format!(
3784                        "Source area not found: {}",
3785                        src_area_id
3786                    ))
3787                })?;
3788                let dst_area = self.cortical_areas.get(dst_area_id).ok_or_else(|| {
3789                    crate::types::BduError::InvalidArea(format!(
3790                        "Destination area not found: {}",
3791                        dst_area_id
3792                    ))
3793                })?;
3794                let src_dimensions = (
3795                    src_area.dimensions.width as usize,
3796                    src_area.dimensions.height as usize,
3797                    src_area.dimensions.depth as usize,
3798                );
3799                let dst_dimensions = (
3800                    dst_area.dimensions.width as usize,
3801                    dst_area.dimensions.height as usize,
3802                    dst_area.dimensions.depth as usize,
3803                );
3804
3805                let count = crate::connectivity::core_morphologies::apply_last_to_first_morphology_with_dimensions(
3806                    npu,
3807                    src_idx,
3808                    dst_idx,
3809                    src_dimensions,
3810                    dst_dimensions,
3811                    weight,
3812                    psp,
3813                    synapse_attractivity,
3814                    synapse_type,
3815                    delay_bursts,
3816                )?;
3817                if count > 0 {
3818                    npu.rebuild_synapse_index();
3819                }
3820                Ok(count as usize)
3821            }
3822            "first_to_last" => {
3823                let src_area = self.cortical_areas.get(src_area_id).ok_or_else(|| {
3824                    crate::types::BduError::InvalidArea(format!(
3825                        "Source area not found: {}",
3826                        src_area_id
3827                    ))
3828                })?;
3829                let dst_area = self.cortical_areas.get(dst_area_id).ok_or_else(|| {
3830                    crate::types::BduError::InvalidArea(format!(
3831                        "Destination area not found: {}",
3832                        dst_area_id
3833                    ))
3834                })?;
3835                let src_dimensions = (
3836                    src_area.dimensions.width as usize,
3837                    src_area.dimensions.height as usize,
3838                    src_area.dimensions.depth as usize,
3839                );
3840                let dst_dimensions = (
3841                    dst_area.dimensions.width as usize,
3842                    dst_area.dimensions.height as usize,
3843                    dst_area.dimensions.depth as usize,
3844                );
3845
3846                let count = crate::connectivity::core_morphologies::apply_first_to_last_morphology_with_dimensions(
3847                    npu,
3848                    src_idx,
3849                    dst_idx,
3850                    src_dimensions,
3851                    dst_dimensions,
3852                    weight,
3853                    psp,
3854                    synapse_attractivity,
3855                    synapse_type,
3856                    delay_bursts,
3857                )?;
3858                if count > 0 {
3859                    npu.rebuild_synapse_index();
3860                }
3861                Ok(count as usize)
3862            }
3863            "rotator_z" => {
3864                let src_area = self.cortical_areas.get(src_area_id).ok_or_else(|| {
3865                    crate::types::BduError::InvalidArea(format!(
3866                        "Source area not found: {}",
3867                        src_area_id
3868                    ))
3869                })?;
3870                let dst_area = self.cortical_areas.get(dst_area_id).ok_or_else(|| {
3871                    crate::types::BduError::InvalidArea(format!(
3872                        "Destination area not found: {}",
3873                        dst_area_id
3874                    ))
3875                })?;
3876                let src_dimensions = (
3877                    src_area.dimensions.width as usize,
3878                    src_area.dimensions.height as usize,
3879                    src_area.dimensions.depth as usize,
3880                );
3881                let dst_dimensions = (
3882                    dst_area.dimensions.width as usize,
3883                    dst_area.dimensions.height as usize,
3884                    dst_area.dimensions.depth as usize,
3885                );
3886
3887                let count = crate::connectivity::core_morphologies::apply_rotator_z_morphology_with_dimensions(
3888                    npu,
3889                    src_idx,
3890                    dst_idx,
3891                    src_dimensions,
3892                    dst_dimensions,
3893                    weight,
3894                    psp,
3895                    synapse_attractivity,
3896                    synapse_type,
3897                    delay_bursts,
3898                )?;
3899                if count > 0 {
3900                    npu.rebuild_synapse_index();
3901                }
3902                Ok(count as usize)
3903            }
3904            _ => {
3905                // Other function morphologies not yet implemented
3906                // NOTE: To add a new function-type morphology, add a case here
3907                use tracing::debug;
3908                debug!(target: "feagi-bdu", "Function morphology {} not yet implemented", morphology_id);
3909                Ok(0)
3910            }
3911        }
3912    }
3913
3914    /// Apply a single morphology rule
3915    fn apply_single_morphology_rule(
3916        &mut self,
3917        src_area_id: &CorticalID,
3918        dst_area_id: &CorticalID,
3919        rule: &serde_json::Value,
3920    ) -> BduResult<usize> {
3921        // Extract morphology_id from rule (array or dict format)
3922        let morphology_id = if let Some(arr) = rule.as_array() {
3923            arr.first().and_then(|v| v.as_str()).unwrap_or("")
3924        } else if let Some(obj) = rule.as_object() {
3925            obj.get("morphology_id")
3926                .and_then(|v| v.as_str())
3927                .unwrap_or("")
3928        } else {
3929            return Ok(0);
3930        };
3931
3932        if morphology_id.is_empty() {
3933            return Ok(0);
3934        }
3935
3936        // Get morphology from registry
3937        let morphology = self.morphology_registry.get(morphology_id).ok_or_else(|| {
3938            crate::types::BduError::InvalidMorphology(format!(
3939                "Morphology not found: {}",
3940                morphology_id
3941            ))
3942        })?;
3943
3944        // Convert area IDs to cortical indices (required by NPU functions)
3945        let src_idx = self.cortical_id_to_idx.get(src_area_id).ok_or_else(|| {
3946            crate::types::BduError::InvalidArea(format!(
3947                "Source area ID not found: {}",
3948                src_area_id
3949            ))
3950        })?;
3951        let dst_idx = self.cortical_id_to_idx.get(dst_area_id).ok_or_else(|| {
3952            crate::types::BduError::InvalidArea(format!(
3953                "Destination area ID not found: {}",
3954                dst_area_id
3955            ))
3956        })?;
3957
3958        // Apply morphology based on type
3959        if let Some(ref npu_arc) = self.npu {
3960            let lock_start = std::time::Instant::now();
3961            let mut npu = npu_arc.lock().unwrap();
3962            let lock_wait = lock_start.elapsed();
3963            tracing::debug!(
3964                target: "feagi-bdu",
3965                "[NPU-LOCK] synaptogenesis lock wait {:.2}ms for {} -> {} (morphology={})",
3966                lock_wait.as_secs_f64() * 1000.0,
3967                src_area_id,
3968                dst_area_id,
3969                morphology_id
3970            );
3971
3972            let (weight, psp, synapse_type, delay_bursts) =
3973                self.resolve_synapse_params_for_rule(src_area_id, rule)?;
3974
3975            // Extract synapse_attractivity from rule (probability 0-100)
3976            let synapse_attractivity = if let Some(obj) = rule.as_object() {
3977                obj.get("synapse_attractivity")
3978                    .and_then(|v| v.as_u64())
3979                    .unwrap_or(100) as u8
3980            } else {
3981                100 // @architecture:acceptable - default to always create when not specified
3982            };
3983
3984            match morphology.morphology_type {
3985                feagi_evolutionary::MorphologyType::Functions => {
3986                    tracing::debug!(
3987                        target: "feagi-bdu",
3988                        "apply_single_morphology_rule: Functions type, morphology_id={}, calling apply_function_morphology",
3989                        morphology_id
3990                    );
3991                    // Function-based morphologies (projector, memory, block_to_block, etc.)
3992                    // Delegate to helper function to consolidate all function-type logic
3993                    self.apply_function_morphology(
3994                        morphology_id,
3995                        rule,
3996                        npu_arc,
3997                        &mut npu,
3998                        src_area_id,
3999                        dst_area_id,
4000                        *src_idx,
4001                        *dst_idx,
4002                        weight,
4003                        psp,
4004                        synapse_attractivity,
4005                        synapse_type,
4006                        delay_bursts,
4007                    )
4008                }
4009                feagi_evolutionary::MorphologyType::Vectors => {
4010                    use crate::connectivity::synaptogenesis::apply_vectors_morphology_with_dimensions;
4011
4012                    // Get dimensions from cortical areas (no neuron scanning!)
4013                    let dst_area = self.cortical_areas.get(dst_area_id).ok_or_else(|| {
4014                        crate::types::BduError::InvalidArea(format!(
4015                            "Destination area not found: {}",
4016                            dst_area_id
4017                        ))
4018                    })?;
4019
4020                    let dst_dimensions = (
4021                        dst_area.dimensions.width as usize,
4022                        dst_area.dimensions.height as usize,
4023                        dst_area.dimensions.depth as usize,
4024                    );
4025
4026                    if let feagi_evolutionary::MorphologyParameters::Vectors { ref vectors } =
4027                        morphology.parameters
4028                    {
4029                        // Convert Vec<[i32; 3]> to Vec<(i32, i32, i32)>
4030                        let vectors_tuples: Vec<(i32, i32, i32)> =
4031                            vectors.iter().map(|v| (v[0], v[1], v[2])).collect();
4032
4033                        let count = apply_vectors_morphology_with_dimensions(
4034                            &mut npu,
4035                            *src_idx,
4036                            *dst_idx,
4037                            vectors_tuples,
4038                            dst_dimensions,
4039                            weight,               // From rule, not hardcoded
4040                            psp,                  // PSP from source area, NOT hardcoded!
4041                            synapse_attractivity, // From rule, not hardcoded
4042                            synapse_type,
4043                            delay_bursts,
4044                        )?;
4045                        // Ensure the propagation engine sees the newly created synapses immediately,
4046                        // and avoid a second outer NPU mutex acquisition later in the mapping update path.
4047                        npu.rebuild_synapse_index();
4048                        Ok(count as usize)
4049                    } else {
4050                        Ok(0)
4051                    }
4052                }
4053                feagi_evolutionary::MorphologyType::Patterns => {
4054                    use crate::connectivity::core_morphologies::apply_patterns_morphology;
4055                    use crate::connectivity::rules::patterns::{
4056                        Pattern3D, PatternElement as RulePatternElement,
4057                    };
4058                    use feagi_evolutionary::PatternElement as EvoPatternElement;
4059
4060                    let feagi_evolutionary::MorphologyParameters::Patterns { ref patterns } =
4061                        morphology.parameters
4062                    else {
4063                        return Ok(0);
4064                    };
4065
4066                    let convert_element =
4067                        |element: &EvoPatternElement|
4068                         -> crate::types::BduResult<RulePatternElement> {
4069                            match element {
4070                                EvoPatternElement::Value(value) => {
4071                                    if *value < 0 {
4072                                        return Err(crate::types::BduError::InvalidMorphology(
4073                                            format!(
4074                                                "Pattern morphology {} contains negative voxel coordinate {}",
4075                                                morphology_id, value
4076                                            ),
4077                                        ));
4078                                    }
4079                                    Ok(RulePatternElement::Exact(*value))
4080                                }
4081                                EvoPatternElement::Wildcard => Ok(RulePatternElement::Wildcard),
4082                                EvoPatternElement::Skip => Ok(RulePatternElement::Skip),
4083                                EvoPatternElement::Exclude => Ok(RulePatternElement::Exclude),
4084                                EvoPatternElement::DirectionPositive => {
4085                                    Ok(RulePatternElement::DirectionExclusive(
4086                                        crate::connectivity::rules::patterns::Direction::Positive,
4087                                    ))
4088                                }
4089                                EvoPatternElement::DirectionNegative => {
4090                                    Ok(RulePatternElement::DirectionExclusive(
4091                                        crate::connectivity::rules::patterns::Direction::Negative,
4092                                    ))
4093                                }
4094                                EvoPatternElement::DirectionPositiveInclusive => {
4095                                    Ok(RulePatternElement::DirectionInclusive(
4096                                        crate::connectivity::rules::patterns::Direction::Positive,
4097                                    ))
4098                                }
4099                                EvoPatternElement::DirectionNegativeInclusive => {
4100                                    Ok(RulePatternElement::DirectionInclusive(
4101                                        crate::connectivity::rules::patterns::Direction::Negative,
4102                                    ))
4103                                }
4104                                EvoPatternElement::Offset(off) => {
4105                                    Ok(RulePatternElement::Offset(*off))
4106                                }
4107                                EvoPatternElement::Range(lo, hi) => {
4108                                    Ok(RulePatternElement::Range(*lo, *hi))
4109                                }
4110                                EvoPatternElement::AbsoluteRange(lo, hi) => {
4111                                    Ok(RulePatternElement::AbsoluteRange(*lo, *hi))
4112                                }
4113                            }
4114                        };
4115
4116                    let mut converted_patterns = Vec::with_capacity(patterns.len());
4117                    for pattern_pair in patterns {
4118                        if pattern_pair.len() != 2 {
4119                            return Err(crate::types::BduError::InvalidMorphology(format!(
4120                                "Pattern morphology {} must contain [src, dst] pairs",
4121                                morphology_id
4122                            )));
4123                        }
4124
4125                        let src_pattern = &pattern_pair[0];
4126                        let dst_pattern = &pattern_pair[1];
4127
4128                        if src_pattern.len() != 3 || dst_pattern.len() != 3 {
4129                            return Err(crate::types::BduError::InvalidMorphology(format!(
4130                                "Pattern morphology {} requires 3-axis patterns",
4131                                morphology_id
4132                            )));
4133                        }
4134
4135                        let src: Pattern3D = (
4136                            convert_element(&src_pattern[0])?,
4137                            convert_element(&src_pattern[1])?,
4138                            convert_element(&src_pattern[2])?,
4139                        );
4140                        let dst: Pattern3D = (
4141                            convert_element(&dst_pattern[0])?,
4142                            convert_element(&dst_pattern[1])?,
4143                            convert_element(&dst_pattern[2])?,
4144                        );
4145
4146                        converted_patterns.push((src, dst));
4147                    }
4148
4149                    let count = apply_patterns_morphology(
4150                        &mut npu,
4151                        *src_idx,
4152                        *dst_idx,
4153                        converted_patterns,
4154                        weight,
4155                        psp,
4156                        synapse_attractivity,
4157                        synapse_type,
4158                        delay_bursts,
4159                    )?;
4160                    if count > 0 {
4161                        npu.rebuild_synapse_index();
4162                    }
4163                    Ok(count as usize)
4164                }
4165                feagi_evolutionary::MorphologyType::Composite => {
4166                    let feagi_evolutionary::MorphologyParameters::Composite { .. } =
4167                        morphology.parameters
4168                    else {
4169                        return Ok(0);
4170                    };
4171
4172                    if morphology_id != "tile" {
4173                        use tracing::debug;
4174                        debug!(
4175                            target: "feagi-bdu",
4176                            "Composite morphology {} not yet implemented",
4177                            morphology_id
4178                        );
4179                        return Ok(0);
4180                    }
4181
4182                    let src_area = self.cortical_areas.get(src_area_id).ok_or_else(|| {
4183                        crate::types::BduError::InvalidArea(format!(
4184                            "Source area not found: {}",
4185                            src_area_id
4186                        ))
4187                    })?;
4188                    let dst_area = self.cortical_areas.get(dst_area_id).ok_or_else(|| {
4189                        crate::types::BduError::InvalidArea(format!(
4190                            "Destination area not found: {}",
4191                            dst_area_id
4192                        ))
4193                    })?;
4194                    let src_dimensions = (
4195                        src_area.dimensions.width as usize,
4196                        src_area.dimensions.height as usize,
4197                        src_area.dimensions.depth as usize,
4198                    );
4199                    let dst_dimensions = (
4200                        dst_area.dimensions.width as usize,
4201                        dst_area.dimensions.height as usize,
4202                        dst_area.dimensions.depth as usize,
4203                    );
4204
4205                    let count =
4206                        crate::connectivity::core_morphologies::apply_tile_morphology_with_dimensions(
4207                            &mut npu,
4208                            *src_idx,
4209                            *dst_idx,
4210                            src_dimensions,
4211                            dst_dimensions,
4212                            weight,
4213                            psp,
4214                            synapse_attractivity,
4215                            synapse_type,
4216                            delay_bursts,
4217                        )?;
4218                    if count > 0 {
4219                        npu.rebuild_synapse_index();
4220                    }
4221                    Ok(count as usize)
4222                }
4223            }
4224        } else {
4225            Ok(0) // NPU not available
4226        }
4227    }
4228
4229    // ======================================================================
4230    // NPU Integration
4231    // ======================================================================
4232
4233    /// Set the NPU reference for neuron/synapse queries
4234    ///
4235    /// This should be called once during FEAGI initialization after the NPU is created.
4236    ///
4237    /// # Arguments
4238    ///
4239    /// * `npu` - Arc to the Rust NPU (wrapped in TracingMutex for automatic lock tracing)
4240    ///
4241    pub fn set_npu(
4242        &mut self,
4243        npu: Arc<feagi_npu_burst_engine::TracingMutex<feagi_npu_burst_engine::DynamicNPU>>,
4244    ) {
4245        self.npu = Some(Arc::clone(&npu));
4246        info!(target: "feagi-bdu","🔗 ConnectomeManager: NPU reference set");
4247
4248        // CRITICAL: Update State Manager with capacity values (from config, never changes)
4249        // This ensures health check endpoint can read capacity without acquiring NPU lock
4250        #[cfg(not(feature = "wasm"))]
4251        {
4252            use feagi_state_manager::StateManager;
4253            let state_manager = StateManager::instance();
4254            let state_manager = state_manager.read();
4255            let core_state = state_manager.get_core_state();
4256            // Capacity comes from config (set at initialization, never changes)
4257            core_state.set_neuron_capacity(self.config.max_neurons as u32);
4258            core_state.set_synapse_capacity(self.config.max_synapses as u32);
4259            info!(
4260                target: "feagi-bdu",
4261                "📊 Updated State Manager with capacity: {} neurons, {} synapses",
4262                self.config.max_neurons, self.config.max_synapses
4263            );
4264        }
4265
4266        // CRITICAL: Backfill cortical area registrations into NPU.
4267        //
4268        // Cortical areas can be created/loaded before the NPU is attached (startup ordering).
4269        // Those areas won't be registered via `add_cortical_area()` (it registers only if NPU is present),
4270        // which causes visualization encoding to fall back to "area_{idx}" and subsequently drop the area
4271        // (base64 decode fails), making BV appear to "miss" firing activity for that cortical area.
4272        let existing_area_count = self.cortical_id_to_idx.len();
4273        if existing_area_count > 0 {
4274            match npu.lock() {
4275                Ok(mut npu_lock) => {
4276                    for (cortical_id, cortical_idx) in self.cortical_id_to_idx.iter() {
4277                        npu_lock.register_cortical_area(*cortical_idx, cortical_id.as_base_64());
4278                    }
4279                    info!(
4280                        target: "feagi-bdu",
4281                        "🔁 Backfilled {} cortical area registrations into NPU",
4282                        existing_area_count
4283                    );
4284                }
4285                Err(e) => {
4286                    warn!(
4287                        target: "feagi-bdu",
4288                        "⚠️ Failed to lock NPU for cortical area backfill registration: {}",
4289                        e
4290                    );
4291                }
4292            }
4293        }
4294
4295        // Initialize cached stats immediately
4296        self.update_all_cached_stats();
4297        info!(target: "feagi-bdu","📊 Initialized cached stats: {} neurons, {} synapses",
4298            self.get_neuron_count(), self.get_synapse_count());
4299    }
4300
4301    /// Check if NPU is connected
4302    pub fn has_npu(&self) -> bool {
4303        self.npu.is_some()
4304    }
4305
4306    /// Get NPU reference (read-only access for queries)
4307    ///
4308    /// # Returns
4309    ///
4310    /// * `Option<&Arc<Mutex<RustNPU>>>` - Reference to NPU if connected
4311    ///
4312    pub fn get_npu(
4313        &self,
4314    ) -> Option<&Arc<feagi_npu_burst_engine::TracingMutex<feagi_npu_burst_engine::DynamicNPU>>>
4315    {
4316        self.npu.as_ref()
4317    }
4318
4319    /// Re-register NPU runtime that `apply_connectome_snapshot` clears.
4320    ///
4321    /// Neurons, synapses, and LTM rows are restored from the snapshot. Twin routes,
4322    /// STDP mapping parameters, and memory-area fire-ledger *windows* come from the
4323    /// live genome/manager. Fire-ledger *contents* are not restored.
4324    pub fn rebind_npu_runtime_after_connectome_apply(&mut self) -> BduResult<()> {
4325        #[cfg(feature = "plasticity")]
4326        if let Some(executor) = self.plasticity_executor.as_ref() {
4327            executor
4328                .lock()
4329                .map_err(|_| {
4330                    BduError::Internal(
4331                        "Failed to lock PlasticityExecutor for registration reset".to_string(),
4332                    )
4333                })?
4334                .clear_memory_area_registrations()
4335                .map_err(BduError::Internal)?;
4336        }
4337        self.refresh_all_upstream_cortical_areas_from_mappings();
4338        self.rebuild_memory_twin_mappings()?;
4339        self.rebind_memory_twin_mappings_to_npu()?;
4340        self.rebind_stdp_mappings_to_npu()?;
4341        #[cfg(feature = "plasticity")]
4342        self.reregister_memory_areas_with_plasticity()?;
4343        Ok(())
4344    }
4345
4346    /// Rebuild `upstream_cortical_areas` for every area from live mapping rules.
4347    ///
4348    /// Connectome import copies `cortical_mapping_dst` but not the derived
4349    /// upstream index. Plasticity registration and STDP both read that index.
4350    /// Fire-ledger *contents* are not restored; only the watch list is.
4351    pub fn refresh_all_upstream_cortical_areas_from_mappings(&mut self) {
4352        let area_ids: Vec<CorticalID> = self.cortical_areas.keys().copied().collect();
4353        for area_id in area_ids {
4354            self.refresh_upstream_cortical_areas_from_mappings(&area_id);
4355        }
4356    }
4357
4358    /// Rebuild `memory_twin_areas` from existing twins and episodic mappings.
4359    ///
4360    /// Connectome import copies twin cortical areas and `memory_replay` rules but
4361    /// often omits the reverse index on the memory area. NPU rebind, twin
4362    /// diagnostics, and replay injection all key off that index, so recall cannot
4363    /// target the saved twin neurons until it is restored.
4364    ///
4365    /// Existing twins are re-indexed in place. Synapses are not regenerated when
4366    /// a `memory_replay` mapping is already present.
4367    pub fn rebuild_memory_twin_mappings(&mut self) -> BduResult<usize> {
4368        let jobs = self.collect_memory_twin_rebuild_jobs()?;
4369        let mut restored = 0usize;
4370        for (memory_id, upstream_id, known_twin) in jobs {
4371            match known_twin {
4372                Some(twin_id) => {
4373                    self.restore_memory_twin_index(&memory_id, &upstream_id, &twin_id)?;
4374                    restored += 1;
4375                }
4376                None => {
4377                    self.ensure_memory_twin_area(&memory_id, &upstream_id)?;
4378                    restored += 1;
4379                }
4380            }
4381        }
4382        if restored > 0 {
4383            info!(
4384                target: "feagi-bdu",
4385                "Rebuilt {} memory twin mapping(s) after connectome apply",
4386                restored
4387            );
4388            self.refresh_cortical_mappings_hash();
4389        }
4390        Ok(restored)
4391    }
4392
4393    fn collect_memory_twin_rebuild_jobs(
4394        &self,
4395    ) -> BduResult<Vec<(CorticalID, CorticalID, Option<CorticalID>)>> {
4396        let mut jobs: Vec<(CorticalID, CorticalID, Option<CorticalID>)> = Vec::new();
4397        let mut seen: HashSet<(CorticalID, CorticalID)> = HashSet::new();
4398
4399        for (memory_id, memory_area) in &self.cortical_areas {
4400            if !Self::area_is_memory(memory_area) {
4401                continue;
4402            }
4403            let Some(dstmap) = memory_area
4404                .properties
4405                .get("cortical_mapping_dst")
4406                .and_then(|value| value.as_object())
4407            else {
4408                continue;
4409            };
4410            for (dst_b64, rules) in dstmap {
4411                if !Self::mapping_rules_use_morphology(rules, "memory_replay") {
4412                    continue;
4413                }
4414                let twin_id = match CorticalID::try_from_base_64(dst_b64) {
4415                    Ok(id) => id,
4416                    Err(_) => continue,
4417                };
4418                let Some(twin_area) = self.cortical_areas.get(&twin_id) else {
4419                    continue;
4420                };
4421                let Some(upstream_b64) = twin_area
4422                    .properties
4423                    .get("memory_twin_of")
4424                    .and_then(|value| value.as_str())
4425                else {
4426                    continue;
4427                };
4428                let upstream_id = CorticalID::try_from_base_64(upstream_b64).map_err(|error| {
4429                    BduError::InvalidArea(format!(
4430                        "Invalid memory_twin_of '{}' on {}: {}",
4431                        upstream_b64,
4432                        twin_id.as_base_64(),
4433                        error
4434                    ))
4435                })?;
4436                if seen.insert((*memory_id, upstream_id)) {
4437                    jobs.push((*memory_id, upstream_id, Some(twin_id)));
4438                }
4439            }
4440        }
4441
4442        for (twin_id, twin_area) in &self.cortical_areas {
4443            let Some(upstream_b64) = twin_area
4444                .properties
4445                .get("memory_twin_of")
4446                .and_then(|value| value.as_str())
4447            else {
4448                continue;
4449            };
4450            let Some(memory_b64) = twin_area
4451                .properties
4452                .get("memory_twin_for")
4453                .and_then(|value| value.as_str())
4454            else {
4455                continue;
4456            };
4457            let upstream_id = CorticalID::try_from_base_64(upstream_b64).map_err(|error| {
4458                BduError::InvalidArea(format!(
4459                    "Invalid memory_twin_of '{}' on {}: {}",
4460                    upstream_b64,
4461                    twin_id.as_base_64(),
4462                    error
4463                ))
4464            })?;
4465            let memory_id = CorticalID::try_from_base_64(memory_b64).map_err(|error| {
4466                BduError::InvalidArea(format!(
4467                    "Invalid memory_twin_for '{}' on {}: {}",
4468                    memory_b64,
4469                    twin_id.as_base_64(),
4470                    error
4471                ))
4472            })?;
4473            if !self.cortical_areas.contains_key(&memory_id)
4474                || !self.cortical_areas.contains_key(&upstream_id)
4475            {
4476                continue;
4477            }
4478            if seen.insert((memory_id, upstream_id)) {
4479                jobs.push((memory_id, upstream_id, Some(*twin_id)));
4480            }
4481        }
4482
4483        let mut episodic_pairs: Vec<(CorticalID, CorticalID)> = Vec::new();
4484        for (src_id, src_area) in &self.cortical_areas {
4485            if Self::area_is_memory(src_area) {
4486                continue;
4487            }
4488            let Some(dstmap) = src_area
4489                .properties
4490                .get("cortical_mapping_dst")
4491                .and_then(|value| value.as_object())
4492            else {
4493                continue;
4494            };
4495            for (dst_b64, rules) in dstmap {
4496                if !Self::mapping_rules_use_morphology(rules, "episodic_memory") {
4497                    continue;
4498                }
4499                let Ok(memory_id) = CorticalID::try_from_base_64(dst_b64) else {
4500                    continue;
4501                };
4502                let Some(memory_area) = self.cortical_areas.get(&memory_id) else {
4503                    continue;
4504                };
4505                if !Self::area_is_memory(memory_area) {
4506                    continue;
4507                }
4508                episodic_pairs.push((memory_id, *src_id));
4509            }
4510        }
4511
4512        for (memory_id, upstream_id) in episodic_pairs {
4513            if !seen.insert((memory_id, upstream_id)) {
4514                continue;
4515            }
4516            let indexed_twin = self
4517                .cortical_areas
4518                .get(&memory_id)
4519                .and_then(|area| area.properties.get("memory_twin_areas"))
4520                .and_then(|value| value.as_object())
4521                .and_then(|map| map.get(&upstream_id.as_base_64()))
4522                .and_then(|value| value.as_str())
4523                .and_then(|twin_b64| CorticalID::try_from_base_64(twin_b64).ok());
4524            if let Some(twin_id) = indexed_twin {
4525                jobs.push((memory_id, upstream_id, Some(twin_id)));
4526                continue;
4527            }
4528            if let Ok(hash_twin_id) = self.build_memory_twin_id(&memory_id, &upstream_id) {
4529                if self.cortical_areas.contains_key(&hash_twin_id) {
4530                    jobs.push((memory_id, upstream_id, Some(hash_twin_id)));
4531                    continue;
4532                }
4533            }
4534            jobs.push((memory_id, upstream_id, None));
4535        }
4536
4537        Ok(jobs)
4538    }
4539
4540    fn restore_memory_twin_index(
4541        &mut self,
4542        memory_area_id: &CorticalID,
4543        upstream_area_id: &CorticalID,
4544        twin_id: &CorticalID,
4545    ) -> BduResult<()> {
4546        let expected_source = upstream_area_id.as_base_64();
4547        let expected_target = memory_area_id.as_base_64();
4548        let Some(existing) = self.cortical_areas.get_mut(twin_id) else {
4549            return Err(BduError::InvalidArea(format!(
4550                "Twin area {} not found while restoring memory twin index",
4551                twin_id.as_base_64()
4552            )));
4553        };
4554        let existing_source = existing
4555            .properties
4556            .get("memory_twin_of")
4557            .and_then(|value| value.as_str())
4558            .map(ToString::to_string);
4559        let existing_target = existing
4560            .properties
4561            .get("memory_twin_for")
4562            .and_then(|value| value.as_str())
4563            .map(ToString::to_string);
4564        if existing_source.as_deref() != Some(expected_source.as_str())
4565            || existing_target.as_deref() != Some(expected_target.as_str())
4566        {
4567            existing.properties.insert(
4568                "memory_twin_of".to_string(),
4569                serde_json::json!(expected_source),
4570            );
4571            existing.properties.insert(
4572                "memory_twin_for".to_string(),
4573                serde_json::json!(expected_target),
4574            );
4575        }
4576        self.set_memory_twin_mapping(memory_area_id, upstream_area_id, twin_id);
4577
4578        let has_replay = self
4579            .cortical_areas
4580            .get(memory_area_id)
4581            .and_then(|area| area.properties.get("cortical_mapping_dst"))
4582            .and_then(|value| value.as_object())
4583            .and_then(|map| map.get(&twin_id.as_base_64()))
4584            .is_some_and(|rules| Self::mapping_rules_use_morphology(rules, "memory_replay"));
4585        if !has_replay {
4586            self.ensure_memory_replay_mapping(memory_area_id, twin_id)?;
4587        }
4588        Ok(())
4589    }
4590
4591    fn area_is_memory(area: &CorticalArea) -> bool {
4592        matches!(area.cortical_type, CorticalAreaType::Memory(_))
4593            || area
4594                .properties
4595                .get("is_mem_type")
4596                .and_then(|value| value.as_bool())
4597                == Some(true)
4598    }
4599
4600    fn mapping_rules_use_morphology(rules: &serde_json::Value, morphology_id: &str) -> bool {
4601        rules.as_array().is_some_and(|arr| {
4602            arr.iter().any(|rule| {
4603                rule.as_object()
4604                    .and_then(|obj| obj.get("morphology_id"))
4605                    .and_then(|value| value.as_str())
4606                    == Some(morphology_id)
4607            })
4608        })
4609    }
4610
4611    fn rebind_memory_twin_mappings_to_npu(&mut self) -> BduResult<()> {
4612        use crate::models::CorticalAreaExt;
4613
4614        let Some(npu_arc) = self.npu.clone() else {
4615            return Ok(());
4616        };
4617        let mut bindings: Vec<(u32, u32, u32, f32)> = Vec::new();
4618        for (memory_id, area) in &self.cortical_areas {
4619            if !matches!(area.cortical_type, CorticalAreaType::Memory(_)) {
4620                continue;
4621            }
4622            let Some(twins) = area
4623                .properties
4624                .get("memory_twin_areas")
4625                .and_then(|value| value.as_object())
4626            else {
4627                continue;
4628            };
4629            let Some(&memory_idx) = self.cortical_id_to_idx.get(memory_id) else {
4630                continue;
4631            };
4632            for (upstream_b64, twin_val) in twins {
4633                let Some(twin_b64) = twin_val.as_str() else {
4634                    return Err(BduError::InvalidArea(format!(
4635                        "memory_twin_areas entry for {} is not a string",
4636                        upstream_b64
4637                    )));
4638                };
4639                let upstream_id = CorticalID::try_from_base_64(upstream_b64).map_err(|error| {
4640                    BduError::InvalidArea(format!(
4641                        "Invalid upstream cortical ID {}: {}",
4642                        upstream_b64, error
4643                    ))
4644                })?;
4645                let twin_id = CorticalID::try_from_base_64(twin_b64).map_err(|error| {
4646                    BduError::InvalidArea(format!(
4647                        "Invalid twin cortical ID {}: {}",
4648                        twin_b64, error
4649                    ))
4650                })?;
4651                let Some(&upstream_idx) = self.cortical_id_to_idx.get(&upstream_id) else {
4652                    continue;
4653                };
4654                let Some(&twin_idx) = self.cortical_id_to_idx.get(&twin_id) else {
4655                    continue;
4656                };
4657                let Some(twin_area) = self.cortical_areas.get(&twin_id) else {
4658                    continue;
4659                };
4660                let potential =
4661                    twin_area.firing_threshold() + twin_area.firing_threshold_increment();
4662                bindings.push((memory_idx, upstream_idx, twin_idx, potential));
4663            }
4664        }
4665        let mut npu = npu_arc.lock().unwrap();
4666        for (memory_idx, upstream_idx, twin_idx, potential) in bindings {
4667            npu.register_memory_twin_mapping(memory_idx, upstream_idx, twin_idx, potential);
4668        }
4669        Ok(())
4670    }
4671
4672    fn rebind_stdp_mappings_to_npu(&mut self) -> BduResult<()> {
4673        let Some(npu_arc) = self.npu.clone() else {
4674            return Ok(());
4675        };
4676        let mut jobs: Vec<(CorticalID, CorticalID, u32, u32, Vec<serde_json::Value>)> = Vec::new();
4677        for (src_id, src_area) in &self.cortical_areas {
4678            let Some(dst_map) = src_area
4679                .properties
4680                .get("cortical_mapping_dst")
4681                .and_then(|value| value.as_object())
4682            else {
4683                continue;
4684            };
4685            let Some(&src_idx) = self.cortical_id_to_idx.get(src_id) else {
4686                continue;
4687            };
4688            for (dst_b64, rules) in dst_map {
4689                let dst_id = CorticalID::try_from_base_64(dst_b64).map_err(|error| {
4690                    BduError::InvalidArea(format!(
4691                        "Invalid destination cortical ID {}: {}",
4692                        dst_b64, error
4693                    ))
4694                })?;
4695                let Some(&dst_idx) = self.cortical_id_to_idx.get(&dst_id) else {
4696                    continue;
4697                };
4698                let Some(rules_arr) = rules.as_array() else {
4699                    continue;
4700                };
4701                jobs.push((*src_id, dst_id, src_idx, dst_idx, rules_arr.clone()));
4702            }
4703        }
4704
4705        for (src_id, dst_id, src_idx, dst_idx, rules) in jobs {
4706            for rule in &rules {
4707                let morphology_id = rule
4708                    .as_object()
4709                    .and_then(|obj| obj.get("morphology_id"))
4710                    .and_then(|value| value.as_str())
4711                    .unwrap_or("");
4712                let mut plasticity_flag = rule
4713                    .as_object()
4714                    .and_then(|obj| obj.get("plasticity_flag"))
4715                    .and_then(|value| value.as_bool())
4716                    .unwrap_or(false);
4717                if morphology_id == "associative_memory" {
4718                    plasticity_flag = true;
4719                }
4720                if !plasticity_flag {
4721                    continue;
4722                }
4723                let Some(rule_obj) = rule.as_object() else {
4724                    return Err(BduError::InvalidMorphology(
4725                        "Plasticity mapping rule must be an object format".to_string(),
4726                    ));
4727                };
4728                let (_weight, psp, synapse_type, _delay) =
4729                    self.resolve_synapse_params_for_rule(&src_id, rule)?;
4730                Self::register_stdp_mapping_for_rule(
4731                    &npu_arc,
4732                    &src_id,
4733                    &dst_id,
4734                    src_idx,
4735                    dst_idx,
4736                    rule_obj,
4737                    false,
4738                    psp,
4739                    synapse_type,
4740                )?;
4741            }
4742        }
4743        Ok(())
4744    }
4745
4746    #[cfg(feature = "plasticity")]
4747    fn reregister_memory_areas_with_plasticity(&mut self) -> BduResult<()> {
4748        use feagi_evolutionary::extract_memory_properties;
4749        use feagi_npu_plasticity::{MemoryNeuronLifecycleConfig, PlasticityExecutor};
4750
4751        let Some(executor) = self.plasticity_executor.clone() else {
4752            return Ok(());
4753        };
4754        let memory_ids: Vec<CorticalID> = self
4755            .cortical_areas
4756            .iter()
4757            .filter(|(_, area)| matches!(area.cortical_type, CorticalAreaType::Memory(_)))
4758            .map(|(id, _)| *id)
4759            .collect();
4760
4761        for memory_id in memory_ids {
4762            let Some(area) = self.cortical_areas.get(&memory_id) else {
4763                continue;
4764            };
4765            let Some(mem_props) = extract_memory_properties(&area.properties) else {
4766                continue;
4767            };
4768            let Some(&area_idx) = self.cortical_id_to_idx.get(&memory_id) else {
4769                continue;
4770            };
4771            let area_name = memory_id.as_base_64();
4772            let upstream_areas = self.get_episodic_memory_upstream_cortical_areas(&memory_id);
4773            let lifecycle_config = MemoryNeuronLifecycleConfig {
4774                initial_lifespan: mem_props.init_lifespan,
4775                lifespan_growth_rate: mem_props.lifespan_growth_rate,
4776                longterm_threshold: mem_props.longterm_threshold,
4777                max_reactivations: 1000,
4778            };
4779            let exec = executor.lock().map_err(|_| {
4780                BduError::Internal(
4781                    "Failed to lock PlasticityExecutor for memory-area rebind".to_string(),
4782                )
4783            })?;
4784            exec.register_memory_area(
4785                area_idx,
4786                area_name,
4787                mem_props.temporal_depth,
4788                upstream_areas,
4789                Some(lifecycle_config),
4790                mem_props.mp_learning_enabled,
4791            );
4792        }
4793        Ok(())
4794    }
4795
4796    /// Set the PlasticityExecutor reference (optional, only if plasticity feature enabled)
4797    /// The executor is passed as Arc<Mutex<dyn Any>> for feature-gating compatibility
4798    #[cfg(feature = "plasticity")]
4799    pub fn set_plasticity_executor(
4800        &mut self,
4801        executor: Arc<std::sync::Mutex<feagi_npu_plasticity::AsyncPlasticityExecutor>>,
4802    ) {
4803        if let Ok(mut exec) = executor.lock() {
4804            use feagi_npu_plasticity::executor::PlasticityExecutor;
4805            if !exec.is_running() {
4806                exec.start();
4807            }
4808        } else {
4809            warn!(target: "feagi-bdu", "⚠️ Failed to lock PlasticityExecutor for startup");
4810        }
4811        self.plasticity_executor = Some(executor);
4812        info!(target: "feagi-bdu", "🔗 ConnectomeManager: PlasticityExecutor reference set");
4813    }
4814
4815    /// Get the PlasticityExecutor reference (if plasticity feature enabled)
4816    #[cfg(feature = "plasticity")]
4817    pub fn get_plasticity_executor(
4818        &self,
4819    ) -> Option<&Arc<std::sync::Mutex<feagi_npu_plasticity::AsyncPlasticityExecutor>>> {
4820        self.plasticity_executor.as_ref()
4821    }
4822
4823    /// Get neuron capacity from config (lock-free, never acquires NPU lock)
4824    ///
4825    /// # Returns
4826    ///
4827    /// * `usize` - Maximum neuron capacity from config (single source of truth)
4828    ///
4829    /// # Performance
4830    ///
4831    /// This is a lock-free read from config that never blocks, even during burst processing.
4832    /// Capacity values are set at NPU initialization and never change.
4833    ///
4834    pub fn get_neuron_capacity(&self) -> usize {
4835        // CRITICAL: Read from config, NOT NPU - capacity never changes and should not acquire locks
4836        self.config.max_neurons
4837    }
4838
4839    /// Get synapse capacity from config (lock-free, never acquires NPU lock)
4840    ///
4841    /// # Returns
4842    ///
4843    /// * `usize` - Maximum synapse capacity from config (single source of truth)
4844    ///
4845    /// # Performance
4846    ///
4847    /// This is a lock-free read from config that never blocks, even during burst processing.
4848    /// Capacity values are set at NPU initialization and never change.
4849    ///
4850    pub fn get_synapse_capacity(&self) -> usize {
4851        // CRITICAL: Read from config, NOT NPU - capacity never changes and should not acquire locks
4852        self.config.max_synapses
4853    }
4854
4855    /// Update fatigue index based on utilization of neuron and synapse arrays
4856    ///
4857    /// Calculates fatigue index as max(regular_neuron_util%, memory_neuron_util%, synapse_util%)
4858    /// Applies hysteresis: triggers at 85%, clears at 80%
4859    /// Rate limited to max once per 2 seconds to protect against rapid changes
4860    ///
4861    /// # Safety
4862    ///
4863    /// This method is completely non-blocking and safe to call during genome loading.
4864    /// If StateManager is unavailable or locked, it will skip the calculation gracefully.
4865    ///
4866    /// # Returns
4867    ///
4868    /// * `Option<u8>` - New fatigue index (0-100) if calculation was performed, None if rate limited or StateManager unavailable
4869    pub fn update_fatigue_index(&self) -> Option<u8> {
4870        // Rate limiting: max once per 2 seconds
4871        let mut last_calc = match self.last_fatigue_calculation.lock() {
4872            Ok(guard) => guard,
4873            Err(_) => return None, // Lock poisoned, skip calculation
4874        };
4875
4876        let now = std::time::Instant::now();
4877        if now.duration_since(*last_calc).as_secs() < 2 {
4878            return None; // Rate limited
4879        }
4880        *last_calc = now;
4881        drop(last_calc);
4882
4883        // Get regular neuron utilization
4884        let regular_neuron_count = self.get_neuron_count();
4885        let regular_neuron_capacity = self.get_neuron_capacity();
4886        let regular_neuron_util = if regular_neuron_capacity > 0 {
4887            ((regular_neuron_count as f64 / regular_neuron_capacity as f64) * 100.0).round() as u8
4888        } else {
4889            0
4890        };
4891
4892        // Get memory neuron utilization from state manager
4893        // Use try_read() to avoid blocking during neurogenesis
4894        // If StateManager singleton initialization fails or is locked, skip calculation entirely
4895        let memory_neuron_util = match StateManager::instance().try_read() {
4896            Some(state_manager) => state_manager.get_core_state().get_memory_neuron_util(),
4897            None => {
4898                // StateManager is locked or not ready - skip fatigue calculation
4899                return None;
4900            }
4901        };
4902
4903        // Get synapse utilization
4904        let synapse_count = self.get_synapse_count();
4905        let synapse_capacity = self.get_synapse_capacity();
4906        let synapse_util = if synapse_capacity > 0 {
4907            ((synapse_count as f64 / synapse_capacity as f64) * 100.0).round() as u8
4908        } else {
4909            0
4910        };
4911
4912        // Calculate fatigue index as max of all utilizations
4913        let fatigue_index = regular_neuron_util
4914            .max(memory_neuron_util)
4915            .max(synapse_util);
4916
4917        // Apply hysteresis: trigger at 85%, clear at 80%
4918        let current_fatigue_active = {
4919            // Try to read current state - if unavailable, assume false
4920            StateManager::instance()
4921                .try_read()
4922                .map(|m| m.get_core_state().is_fatigue_active())
4923                .unwrap_or(false)
4924        };
4925
4926        let new_fatigue_active = if fatigue_index >= 85 {
4927            true
4928        } else if fatigue_index < 80 {
4929            false
4930        } else {
4931            current_fatigue_active // Keep current state in hysteresis zone
4932        };
4933
4934        // Update state manager with all values
4935        // Use try_write() to avoid blocking during neurogenesis
4936        // If StateManager is unavailable, skip update (non-blocking)
4937        if let Some(state_manager) = StateManager::instance().try_write() {
4938            let core_state = state_manager.get_core_state();
4939            core_state.set_fatigue_index(fatigue_index);
4940            core_state.set_fatigue_active(new_fatigue_active);
4941            core_state.set_regular_neuron_util(regular_neuron_util);
4942            core_state.set_memory_neuron_util(memory_neuron_util);
4943            core_state.set_synapse_util(synapse_util);
4944        } else {
4945            // StateManager is locked or not ready - skip update (non-blocking)
4946            trace!(target: "feagi-bdu", "[FATIGUE] StateManager unavailable, skipping update");
4947        }
4948
4949        // Update NPU's atomic boolean
4950        if let Some(ref npu) = self.npu {
4951            if let Ok(mut npu_lock) = npu.lock() {
4952                npu_lock.set_fatigue_active(new_fatigue_active);
4953            }
4954        }
4955
4956        trace!(
4957            target: "feagi-bdu",
4958            "[FATIGUE] Index={}, Active={}, Regular={}%, Memory={}%, Synapse={}%",
4959            fatigue_index, new_fatigue_active, regular_neuron_util, memory_neuron_util, synapse_util
4960        );
4961
4962        Some(fatigue_index)
4963    }
4964
4965    // ======================================================================
4966    // Neuron/Synapse Creation Methods (Delegates to NPU)
4967    // ======================================================================
4968
4969    /// Create neurons for a cortical area
4970    ///
4971    /// This delegates to the NPU's optimized batch creation function.
4972    ///
4973    /// # Arguments
4974    ///
4975    /// * `cortical_id` - Cortical area ID (6-character string)
4976    ///
4977    /// # Returns
4978    ///
4979    /// Number of neurons created
4980    ///
4981    pub fn create_neurons_for_area(&mut self, cortical_id: &CorticalID) -> BduResult<u32> {
4982        // Get cortical area
4983        let area = self
4984            .cortical_areas
4985            .get(cortical_id)
4986            .ok_or_else(|| {
4987                BduError::InvalidArea(format!("Cortical area {} not found", cortical_id))
4988            })?
4989            .clone();
4990
4991        // Get cortical index
4992        let cortical_idx = self.cortical_id_to_idx.get(cortical_id).ok_or_else(|| {
4993            BduError::InvalidArea(format!("No index for cortical area {}", cortical_id))
4994        })?;
4995
4996        // Get NPU
4997        let npu = self
4998            .npu
4999            .as_ref()
5000            .ok_or_else(|| BduError::Internal("NPU not connected".to_string()))?;
5001
5002        // Extract neural parameters from area properties using CorticalAreaExt trait
5003        // This ensures consistent defaults across the codebase
5004        use crate::models::CorticalAreaExt;
5005        let per_voxel_cnt = area.neurons_per_voxel();
5006        let firing_threshold = area.firing_threshold();
5007        let firing_threshold_increment_x = area.firing_threshold_increment_x();
5008        let firing_threshold_increment_y = area.firing_threshold_increment_y();
5009        let firing_threshold_increment_z = area.firing_threshold_increment_z();
5010        // SIMD-friendly encoding: 0.0 means no limit, convert to MAX
5011        let firing_threshold_limit_raw = area.firing_threshold_limit();
5012        let firing_threshold_limit = if firing_threshold_limit_raw == 0.0 {
5013            f32::MAX // SIMD-friendly encoding: MAX = no limit
5014        } else {
5015            firing_threshold_limit_raw
5016        };
5017
5018        // DEBUG: Log the increment values
5019        if firing_threshold_increment_x != 0.0
5020            || firing_threshold_increment_y != 0.0
5021            || firing_threshold_increment_z != 0.0
5022        {
5023            info!(
5024                target: "feagi-bdu",
5025                "🔍 [DEBUG] Area {}: firing_threshold_increment = [{}, {}, {}]",
5026                cortical_id.as_base_64(),
5027                firing_threshold_increment_x,
5028                firing_threshold_increment_y,
5029                firing_threshold_increment_z
5030            );
5031        } else {
5032            // Check if properties exist but are just 0
5033            if area.properties.contains_key("firing_threshold_increment_x")
5034                || area.properties.contains_key("firing_threshold_increment_y")
5035                || area.properties.contains_key("firing_threshold_increment_z")
5036            {
5037                info!(
5038                    target: "feagi-bdu",
5039                    "🔍 [DEBUG] Area {}: INCREMENT PROPERTIES FOUND: x={:?}, y={:?}, z={:?}",
5040                    cortical_id.as_base_64(),
5041                    area.properties.get("firing_threshold_increment_x"),
5042                    area.properties.get("firing_threshold_increment_y"),
5043                    area.properties.get("firing_threshold_increment_z")
5044                );
5045            }
5046        }
5047
5048        let leak_coefficient = area.leak_coefficient();
5049        let excitability = area.neuron_excitability();
5050        let refractory_period = area.refractory_period();
5051        // SIMD-friendly encoding: 0 means no limit, convert to MAX
5052        let consecutive_fire_limit_raw = area.consecutive_fire_count() as u16;
5053        let consecutive_fire_limit = if consecutive_fire_limit_raw == 0 {
5054            u16::MAX // SIMD-friendly encoding: MAX = no limit
5055        } else {
5056            consecutive_fire_limit_raw
5057        };
5058        let snooze_length = area.snooze_period();
5059        let mp_charge_accumulation = area.mp_charge_accumulation();
5060
5061        // Calculate expected neuron count for logging
5062        let voxels = area.dimensions.width as usize
5063            * area.dimensions.height as usize
5064            * area.dimensions.depth as usize;
5065        let expected_neurons = voxels * per_voxel_cnt as usize;
5066
5067        trace!(
5068            target: "feagi-bdu",
5069            "Creating neurons for area {}: {}x{}x{} voxels × {} neurons/voxel = {} total neurons",
5070            cortical_id.as_base_64(),
5071            area.dimensions.width,
5072            area.dimensions.height,
5073            area.dimensions.depth,
5074            per_voxel_cnt,
5075            expected_neurons
5076        );
5077
5078        // Call NPU to create neurons
5079        // NOTE: Cortical area should already be registered in NPU during corticogenesis
5080        // Scope the lock so it is released before the rate_modulated_leak block below, which
5081        // must take the same NPU mutex again (second lock while npu_lock lived = deadlock).
5082        let neuron_count: u32 = {
5083            let mut npu_lock = npu
5084                .lock()
5085                .map_err(|e| BduError::Internal(format!("Failed to lock NPU: {}", e)))?;
5086            npu_lock
5087                .create_cortical_area_neurons(
5088                    *cortical_idx,
5089                    area.dimensions.width,
5090                    area.dimensions.height,
5091                    area.dimensions.depth,
5092                    per_voxel_cnt,
5093                    firing_threshold,
5094                    firing_threshold_increment_x,
5095                    firing_threshold_increment_y,
5096                    firing_threshold_increment_z,
5097                    firing_threshold_limit,
5098                    leak_coefficient,
5099                    0.0, // resting_potential (LIF default)
5100                    0,   // neuron_type (excitatory)
5101                    refractory_period,
5102                    excitability,
5103                    consecutive_fire_limit,
5104                    snooze_length,
5105                    mp_charge_accumulation,
5106                )
5107                .map_err(|e| BduError::Internal(format!("NPU neuron creation failed: {}", e)))?
5108        };
5109
5110        trace!(
5111            target: "feagi-bdu",
5112            "Created {} neurons for area {} via NPU",
5113            neuron_count,
5114            cortical_id.as_base_64()
5115        );
5116
5117        // CRITICAL: Update per-area neuron count cache (lock-free for readers)
5118        // This allows healthcheck endpoints to read counts without NPU lock
5119        {
5120            let mut cache = self.cached_neuron_counts_per_area.write();
5121            cache
5122                .entry(*cortical_id)
5123                .or_insert_with(|| AtomicUsize::new(0))
5124                .store(neuron_count as usize, Ordering::Relaxed);
5125        }
5126
5127        // @cursor:critical-path - Keep BV-facing stats in StateManager.
5128        let state_manager = StateManager::instance();
5129        let state_manager = state_manager.read();
5130        state_manager
5131            .set_cortical_area_neuron_count(&cortical_id.as_base_64(), neuron_count as usize);
5132
5133        // Update total neuron count cache
5134        self.cached_neuron_count
5135            .fetch_add(neuron_count as usize, Ordering::Relaxed);
5136
5137        // CRITICAL: Update StateManager neuron count (for health_check endpoint)
5138        let state_manager = StateManager::instance();
5139        let state_manager = state_manager.read();
5140        let core_state = state_manager.get_core_state();
5141        core_state.add_neuron_count(neuron_count);
5142        core_state.add_regular_neuron_count(neuron_count);
5143
5144        // Opt-in homeostatic leak: register on NPU (cold pass only when enabled; see `neural/docs/rate_modulated_leak.md`).
5145        if let Some(npu) = &self.npu {
5146            if let Ok(mut npl) = npu.lock() {
5147                if let Some(v) = area.properties.get("rate_modulated_leak") {
5148                    use crate::models::CorticalAreaExt;
5149                    let idxs: Vec<usize> = npl
5150                        .get_neurons_in_cortical_area(*cortical_idx)
5151                        .into_iter()
5152                        .map(|id| id as usize)
5153                        .collect();
5154                    npl.sync_rate_modulated_leak_from_cortical_property(
5155                        *cortical_idx,
5156                        v,
5157                        area.leak_coefficient(),
5158                        idxs,
5159                    );
5160                } else {
5161                    npl.remove_rate_modulated_leak(*cortical_idx);
5162                }
5163            }
5164        }
5165
5166        // Trigger fatigue index recalculation after neuron creation
5167        // NOTE: Disabled during genome loading to prevent blocking
5168        // Fatigue calculation will be enabled after genome loading completes
5169        // if neuron_count > 0 {
5170        //     let _ = self.update_fatigue_index();
5171        // }
5172
5173        Ok(neuron_count)
5174    }
5175
5176    /// Add a single neuron to a cortical area
5177    ///
5178    /// # Arguments
5179    ///
5180    /// * `cortical_id` - Cortical area ID
5181    /// * `x` - X coordinate
5182    /// * `y` - Y coordinate
5183    /// * `z` - Z coordinate
5184    /// * `firing_threshold` - Firing threshold (minimum MP to fire)
5185    /// * `firing_threshold_limit` - Firing threshold limit (maximum MP to fire, 0 = no limit)
5186    /// * `leak_coefficient` - Leak coefficient
5187    /// * `resting_potential` - Resting membrane potential
5188    /// * `neuron_type` - Neuron type (0=excitatory, 1=inhibitory)
5189    /// * `refractory_period` - Refractory period
5190    /// * `excitability` - Excitability multiplier
5191    /// * `consecutive_fire_limit` - Maximum consecutive fires
5192    /// * `snooze_length` - Snooze duration after consecutive fire limit
5193    /// * `mp_charge_accumulation` - Whether membrane potential accumulates
5194    ///
5195    /// # Returns
5196    ///
5197    /// The newly created neuron ID
5198    ///
5199    #[allow(clippy::too_many_arguments)]
5200    pub fn add_neuron(
5201        &mut self,
5202        cortical_id: &CorticalID,
5203        x: u32,
5204        y: u32,
5205        z: u32,
5206        firing_threshold: f32,
5207        firing_threshold_limit: f32,
5208        leak_coefficient: f32,
5209        resting_potential: f32,
5210        neuron_type: u8,
5211        refractory_period: u16,
5212        excitability: f32,
5213        consecutive_fire_limit: u16,
5214        snooze_length: u16,
5215        mp_charge_accumulation: bool,
5216    ) -> BduResult<u64> {
5217        self.add_neuron_with_area_stats(
5218            cortical_id,
5219            x,
5220            y,
5221            z,
5222            firing_threshold,
5223            firing_threshold_limit,
5224            leak_coefficient,
5225            resting_potential,
5226            neuron_type,
5227            refractory_period,
5228            excitability,
5229            consecutive_fire_limit,
5230            snooze_length,
5231            mp_charge_accumulation,
5232            true,
5233        )
5234    }
5235
5236    /// Add an NPU neuron that participates in global capacity accounting but does not
5237    /// increment per-cortical-area stats.
5238    ///
5239    /// Used for LTM bridge twins in memory areas: the plasticity-layer memory neuron is
5240    /// already counted in `MemoryNeuronArray`; the twin is auxiliary NPU infrastructure.
5241    #[allow(clippy::too_many_arguments)]
5242    pub fn add_auxiliary_neuron(
5243        &mut self,
5244        cortical_id: &CorticalID,
5245        x: u32,
5246        y: u32,
5247        z: u32,
5248        firing_threshold: f32,
5249        firing_threshold_limit: f32,
5250        leak_coefficient: f32,
5251        resting_potential: f32,
5252        neuron_type: u8,
5253        refractory_period: u16,
5254        excitability: f32,
5255        consecutive_fire_limit: u16,
5256        snooze_length: u16,
5257        mp_charge_accumulation: bool,
5258    ) -> BduResult<u64> {
5259        self.add_neuron_with_area_stats(
5260            cortical_id,
5261            x,
5262            y,
5263            z,
5264            firing_threshold,
5265            firing_threshold_limit,
5266            leak_coefficient,
5267            resting_potential,
5268            neuron_type,
5269            refractory_period,
5270            excitability,
5271            consecutive_fire_limit,
5272            snooze_length,
5273            mp_charge_accumulation,
5274            false,
5275        )
5276    }
5277
5278    #[allow(clippy::too_many_arguments)]
5279    fn add_neuron_with_area_stats(
5280        &mut self,
5281        cortical_id: &CorticalID,
5282        x: u32,
5283        y: u32,
5284        z: u32,
5285        firing_threshold: f32,
5286        firing_threshold_limit: f32,
5287        leak_coefficient: f32,
5288        resting_potential: f32,
5289        neuron_type: u8,
5290        refractory_period: u16,
5291        excitability: f32,
5292        consecutive_fire_limit: u16,
5293        snooze_length: u16,
5294        mp_charge_accumulation: bool,
5295        update_area_stats: bool,
5296    ) -> BduResult<u64> {
5297        // Validate cortical area exists
5298        if !self.cortical_areas.contains_key(cortical_id) {
5299            return Err(BduError::InvalidArea(format!(
5300                "Cortical area {} not found",
5301                cortical_id
5302            )));
5303        }
5304
5305        let cortical_idx = *self
5306            .cortical_id_to_idx
5307            .get(cortical_id)
5308            .ok_or_else(|| BduError::InvalidArea(format!("No index for {}", cortical_id)))?;
5309
5310        // Get NPU
5311        let npu = self
5312            .npu
5313            .as_ref()
5314            .ok_or_else(|| BduError::Internal("NPU not connected".to_string()))?;
5315
5316        let mut npu_lock = npu
5317            .lock()
5318            .map_err(|e| BduError::Internal(format!("Failed to lock NPU: {}", e)))?;
5319
5320        // Add neuron via NPU
5321        let neuron_id = npu_lock
5322            .add_neuron(
5323                firing_threshold,
5324                firing_threshold_limit,
5325                leak_coefficient,
5326                resting_potential,
5327                neuron_type as i32,
5328                refractory_period,
5329                excitability,
5330                consecutive_fire_limit,
5331                snooze_length,
5332                mp_charge_accumulation,
5333                cortical_idx,
5334                x,
5335                y,
5336                z,
5337            )
5338            .map_err(|e| BduError::Internal(format!("Failed to add neuron: {}", e)))?;
5339
5340        trace!(
5341            target: "feagi-bdu",
5342            "Created neuron {} in area {} at ({}, {}, {})",
5343            neuron_id.0,
5344            cortical_id,
5345            x,
5346            y,
5347            z
5348        );
5349
5350        // CRITICAL: Update StateManager neuron count (for health_check endpoint)
5351        let state_manager = StateManager::instance();
5352        let state_manager = state_manager.read();
5353        let core_state = state_manager.get_core_state();
5354        core_state.add_neuron_count(1);
5355        core_state.add_regular_neuron_count(1);
5356        if update_area_stats {
5357            state_manager.add_cortical_area_neuron_count(&cortical_id.as_base_64(), 1);
5358        }
5359
5360        Ok(neuron_id.0 as u64)
5361    }
5362
5363    /// Delete a neuron by ID
5364    ///
5365    /// # Arguments
5366    ///
5367    /// * `neuron_id` - Global neuron ID
5368    ///
5369    /// # Returns
5370    ///
5371    /// `true` if the neuron was deleted, `false` if it didn't exist
5372    ///
5373    pub fn delete_neuron(&mut self, neuron_id: u64) -> BduResult<bool> {
5374        // Get NPU
5375        let npu = self
5376            .npu
5377            .as_ref()
5378            .ok_or_else(|| BduError::Internal("NPU not connected".to_string()))?;
5379
5380        let mut npu_lock = npu
5381            .lock()
5382            .map_err(|e| BduError::Internal(format!("Failed to lock NPU: {}", e)))?;
5383
5384        let cortical_idx = npu_lock.get_neuron_cortical_area(neuron_id as u32);
5385        let cortical_id = cortical_idx.and_then(|idx| self.cortical_idx_to_id.get(&idx).cloned());
5386
5387        let deleted = npu_lock.delete_neuron(neuron_id as u32);
5388
5389        if deleted {
5390            trace!(target: "feagi-bdu", "Deleted neuron {}", neuron_id);
5391
5392            // CRITICAL: Update StateManager neuron count (for health_check endpoint)
5393            let state_manager = StateManager::instance();
5394            let state_manager = state_manager.read();
5395            let core_state = state_manager.get_core_state();
5396            core_state.subtract_neuron_count(1);
5397            core_state.subtract_regular_neuron_count(1);
5398            if let Some(cortical_id) = cortical_id {
5399                state_manager.subtract_cortical_area_neuron_count(&cortical_id.as_base_64(), 1);
5400            }
5401
5402            // Trigger fatigue index recalculation after neuron deletion
5403            // NOTE: Disabled during genome loading to prevent blocking
5404            // let _ = self.update_fatigue_index();
5405        }
5406
5407        Ok(deleted)
5408    }
5409
5410    /// Apply cortical mapping rules (dstmap) to create synapses
5411    ///
5412    /// This parses the destination mapping rules from a source area and
5413    /// creates synapses using the NPU's synaptogenesis functions.
5414    ///
5415    /// # Arguments
5416    ///
5417    /// * `src_cortical_id` - Source cortical area ID
5418    ///
5419    /// # Returns
5420    ///
5421    /// Number of synapses created
5422    ///
5423    pub fn apply_cortical_mapping(&mut self, src_cortical_id: &CorticalID) -> BduResult<u32> {
5424        // Get source area
5425        let src_area = self
5426            .cortical_areas
5427            .get(src_cortical_id)
5428            .ok_or_else(|| {
5429                BduError::InvalidArea(format!("Source area {} not found", src_cortical_id))
5430            })?
5431            .clone();
5432
5433        // Get dstmap from area properties
5434        let dstmap = match src_area.properties.get("cortical_mapping_dst") {
5435            Some(serde_json::Value::Object(map)) if !map.is_empty() => map,
5436            _ => return Ok(0), // No mappings
5437        };
5438
5439        let src_cortical_idx = *self
5440            .cortical_id_to_idx
5441            .get(src_cortical_id)
5442            .ok_or_else(|| BduError::InvalidArea(format!("No index for {}", src_cortical_id)))?;
5443
5444        let mut total_synapses = 0u32;
5445        let mut upstream_updates: Vec<(CorticalID, u32)> = Vec::new(); // Collect updates to apply later
5446
5447        // Process each destination area using the unified path
5448        for (dst_cortical_id_str, _rules) in dstmap {
5449            // Convert string to CorticalID
5450            let dst_cortical_id = match CorticalID::try_from_base_64(dst_cortical_id_str) {
5451                Ok(id) => id,
5452                Err(_) => {
5453                    warn!(target: "feagi-bdu","Invalid cortical ID format: {}, skipping", dst_cortical_id_str);
5454                    continue;
5455                }
5456            };
5457
5458            // Verify destination area exists
5459            if !self.cortical_id_to_idx.contains_key(&dst_cortical_id) {
5460                warn!(target: "feagi-bdu","Destination area {} not found, skipping", dst_cortical_id);
5461                continue;
5462            }
5463
5464            // Apply cortical mapping for this pair (handles STDP and all morphology rules)
5465            let synapse_count =
5466                self.apply_cortical_mapping_for_pair(src_cortical_id, &dst_cortical_id)?;
5467            total_synapses += synapse_count as u32;
5468
5469            // Queue upstream area update for ANY mapping (even if no synapses created)
5470            // This is critical for memory areas which have mappings but no physical synapses
5471            upstream_updates.push((dst_cortical_id, src_cortical_idx));
5472        }
5473
5474        // Apply all upstream area updates now that NPU borrows are complete
5475        for (dst_id, src_idx) in upstream_updates {
5476            self.add_upstream_area(&dst_id, src_idx);
5477        }
5478
5479        trace!(
5480            target: "feagi-bdu",
5481            "Created {} synapses for area {} via NPU",
5482            total_synapses,
5483            src_cortical_id
5484        );
5485
5486        // CRITICAL: Update per-area synapse count cache (lock-free for readers)
5487        // This allows healthcheck endpoints to read counts without NPU lock
5488        if total_synapses > 0 {
5489            let mut cache = self.cached_synapse_counts_per_area.write();
5490            cache
5491                .entry(*src_cortical_id)
5492                .or_insert_with(|| AtomicUsize::new(0))
5493                .fetch_add(total_synapses as usize, Ordering::Relaxed);
5494        }
5495
5496        // Update total synapse count cache
5497        self.cached_synapse_count
5498            .fetch_add(total_synapses as usize, Ordering::Relaxed);
5499
5500        // CRITICAL: Update StateManager synapse count (for health_check endpoint)
5501        if total_synapses > 0 {
5502            let state_manager = StateManager::instance();
5503            let state_manager = state_manager.read();
5504            let core_state = state_manager.get_core_state();
5505            core_state.add_synapse_count(total_synapses);
5506        }
5507
5508        Ok(total_synapses)
5509    }
5510
5511    // ======================================================================
5512    // Neuron Query Methods (Delegates to NPU)
5513    // ======================================================================
5514
5515    /// Check if a neuron exists
5516    ///
5517    /// # Arguments
5518    ///
5519    /// * `neuron_id` - The neuron ID to check
5520    ///
5521    /// # Returns
5522    ///
5523    /// `true` if the neuron exists in the NPU, `false` otherwise
5524    ///
5525    /// # Note
5526    ///
5527    /// Returns `false` if NPU is not connected
5528    ///
5529    pub fn has_neuron(&self, neuron_id: u64) -> bool {
5530        if let Some(ref npu) = self.npu {
5531            if let Ok(npu_lock) = npu.lock() {
5532                // Check if neuron exists AND is valid (not deleted)
5533                npu_lock.is_neuron_valid(neuron_id as u32)
5534            } else {
5535                false
5536            }
5537        } else {
5538            false
5539        }
5540    }
5541
5542    /// Get total number of active neurons (lock-free cached read with opportunistic update)
5543    ///
5544    /// # Returns
5545    ///
5546    /// The total number of neurons (from cache)
5547    ///
5548    /// # Performance
5549    ///
5550    /// This is a lock-free atomic read that never blocks, even during burst processing.
5551    /// Opportunistically updates cache if NPU is available (non-blocking try_lock).
5552    ///
5553    pub fn get_neuron_count(&self) -> usize {
5554        // Opportunistically update cache if NPU is available (non-blocking)
5555        if let Some(ref npu) = self.npu {
5556            if let Ok(npu_lock) = npu.try_lock() {
5557                let fresh_count = npu_lock.get_neuron_count();
5558                self.cached_neuron_count
5559                    .store(fresh_count, Ordering::Relaxed);
5560            }
5561            // If NPU is busy, just use cached value
5562        }
5563
5564        // Always return cached value (never blocks)
5565        self.cached_neuron_count.load(Ordering::Relaxed)
5566    }
5567
5568    /// Update the cached neuron count (explicit update)
5569    ///
5570    /// Use this if you want to force a cache update. Most callers should just
5571    /// use get_neuron_count() which updates opportunistically.
5572    ///
5573    pub fn update_cached_neuron_count(&self) {
5574        if let Some(ref npu) = self.npu {
5575            if let Ok(npu_lock) = npu.try_lock() {
5576                let count = npu_lock.get_neuron_count();
5577                self.cached_neuron_count.store(count, Ordering::Relaxed);
5578            }
5579        }
5580    }
5581
5582    /// Refresh cached neuron count for a single cortical area from the NPU.
5583    ///
5584    /// Returns the refreshed count if successful.
5585    pub fn refresh_neuron_count_for_area(&self, cortical_id: &CorticalID) -> Option<usize> {
5586        let npu = self.npu.as_ref()?;
5587        let cortical_idx = *self.cortical_id_to_idx.get(cortical_id)?;
5588        let npu_lock = npu.lock().ok()?;
5589        let count = npu_lock.get_neurons_in_cortical_area(cortical_idx).len();
5590        drop(npu_lock);
5591
5592        let mut cache = self.cached_neuron_counts_per_area.write();
5593        cache
5594            .entry(*cortical_id)
5595            .or_insert_with(|| AtomicUsize::new(0))
5596            .store(count, Ordering::Relaxed);
5597
5598        // @cursor:critical-path - Keep BV-facing stats in StateManager.
5599        let state_manager = StateManager::instance();
5600        let state_manager = state_manager.read();
5601        state_manager.set_cortical_area_neuron_count(&cortical_id.as_base_64(), count);
5602
5603        self.update_cached_neuron_count();
5604
5605        Some(count)
5606    }
5607
5608    /// Get total number of synapses (lock-free cached read with opportunistic update)
5609    ///
5610    /// # Returns
5611    ///
5612    /// The total number of synapses (from cache)
5613    ///
5614    /// # Performance
5615    ///
5616    /// This is a lock-free atomic read that never blocks, even during burst processing.
5617    /// Opportunistically updates cache if NPU is available (non-blocking try_lock).
5618    ///
5619    pub fn get_synapse_count(&self) -> usize {
5620        // Opportunistically update cache if NPU is available (non-blocking)
5621        if let Some(ref npu) = self.npu {
5622            if let Ok(npu_lock) = npu.try_lock() {
5623                let fresh_count = npu_lock.get_synapse_count();
5624                self.cached_synapse_count
5625                    .store(fresh_count, Ordering::Relaxed);
5626            }
5627            // If NPU is busy, just use cached value
5628        }
5629
5630        // Always return cached value (never blocks)
5631        self.cached_synapse_count.load(Ordering::Relaxed)
5632    }
5633
5634    /// Update the cached synapse count (explicit update)
5635    ///
5636    /// Use this if you want to force a cache update. Most callers should just
5637    /// use get_synapse_count() which updates opportunistically.
5638    ///
5639    pub fn update_cached_synapse_count(&self) {
5640        if let Some(ref npu) = self.npu {
5641            if let Ok(npu_lock) = npu.try_lock() {
5642                let count = npu_lock.get_synapse_count();
5643                self.cached_synapse_count.store(count, Ordering::Relaxed);
5644            }
5645        }
5646    }
5647
5648    /// Update all cached stats (neuron and synapse counts)
5649    ///
5650    /// This is called automatically when NPU is connected and can be called
5651    /// explicitly if you want to force a cache refresh.
5652    ///
5653    pub fn update_all_cached_stats(&self) {
5654        self.update_cached_neuron_count();
5655        self.update_cached_synapse_count();
5656    }
5657
5658    /// Get neuron coordinates (x, y, z)
5659    ///
5660    /// # Arguments
5661    ///
5662    /// * `neuron_id` - The neuron ID to query
5663    ///
5664    /// # Returns
5665    ///
5666    /// Coordinates as (x, y, z), or (0, 0, 0) if neuron doesn't exist or NPU not connected
5667    ///
5668    pub fn get_neuron_coordinates(&self, neuron_id: u64) -> (u32, u32, u32) {
5669        // Memory neurons live in the plasticity MemoryNeuronArray, not the NPU dense neuron array.
5670        // Do not take the NPU mutex here: synapse inspector paths (`peer_cortical_voxel_fields`)
5671        // resolve cortical idx via the plasticity lock first, then coordinates. The burst thread
5672        // holds NPU while notifying plasticity — taking NPU after plasticity would deadlock.
5673        #[cfg(feature = "plasticity")]
5674        {
5675            if feagi_npu_plasticity::NeuronIdManager::is_memory_neuron_id(neuron_id as u32) {
5676                return (0, 0, 0);
5677            }
5678        }
5679        if let Some(ref npu) = self.npu {
5680            if let Ok(npu_lock) = npu.lock() {
5681                npu_lock
5682                    .get_neuron_coordinates(neuron_id as u32)
5683                    .unwrap_or((0, 0, 0))
5684            } else {
5685                (0, 0, 0)
5686            }
5687        } else {
5688            (0, 0, 0)
5689        }
5690    }
5691
5692    /// Get the cortical area index for a neuron
5693    ///
5694    /// # Arguments
5695    ///
5696    /// * `neuron_id` - The neuron ID to query
5697    ///
5698    /// # Returns
5699    ///
5700    /// Cortical area index, or 0 if neuron doesn't exist or NPU not connected
5701    ///
5702    pub fn get_neuron_cortical_idx(&self, neuron_id: u64) -> u32 {
5703        self.get_neuron_cortical_idx_opt(neuron_id).unwrap_or(0)
5704    }
5705
5706    /// Cortical area index for a neuron, or `None` if the neuron slot is invalid / NPU unavailable.
5707    ///
5708    /// Memory neurons (global ids in `50_000_000..=99_999_999`) are not stored in the dense
5709    /// [`NeuronArray`] index space; their cortical membership is resolved via the plasticity
5710    /// [`MemoryNeuronArray`] when the plasticity feature is enabled.
5711    pub fn get_neuron_cortical_idx_opt(&self, neuron_id: u64) -> Option<u32> {
5712        #[cfg(feature = "plasticity")]
5713        {
5714            if feagi_npu_plasticity::NeuronIdManager::is_memory_neuron_id(neuron_id as u32) {
5715                return self.memory_neuron_cortical_idx_opt(neuron_id as u32);
5716            }
5717        }
5718        if let Some(ref npu) = self.npu {
5719            if let Ok(npu_lock) = npu.lock() {
5720                npu_lock.get_neuron_cortical_area(neuron_id as u32)
5721            } else {
5722                None
5723            }
5724        } else {
5725            None
5726        }
5727    }
5728
5729    /// Resolve cortical index for a memory-neuron global id through the plasticity executor.
5730    #[cfg(feature = "plasticity")]
5731    fn memory_neuron_cortical_idx_opt(&self, neuron_id: u32) -> Option<u32> {
5732        let exec = self.get_plasticity_executor()?;
5733        let guard = exec.lock().ok()?;
5734        guard
5735            .memory_neuron_detail(neuron_id)
5736            .map(|d| d.cortical_area_idx)
5737    }
5738
5739    /// Get all neuron IDs in a specific cortical area
5740    ///
5741    /// # Arguments
5742    ///
5743    /// * `cortical_id` - The cortical area ID (string)
5744    ///
5745    /// # Returns
5746    ///
5747    /// Vec of neuron IDs in the area, or empty vec if area doesn't exist or NPU not connected
5748    ///
5749    pub fn get_neurons_in_area(&self, cortical_id: &CorticalID) -> Vec<u64> {
5750        // Get cortical_idx from cortical_id
5751        let cortical_idx = match self.cortical_id_to_idx.get(cortical_id) {
5752            Some(idx) => *idx,
5753            None => return Vec::new(),
5754        };
5755
5756        if let Some(ref npu) = self.npu {
5757            if let Ok(npu_lock) = npu.lock() {
5758                // Convert Vec<u32> to Vec<u64>
5759                npu_lock
5760                    .get_neurons_in_cortical_area(cortical_idx)
5761                    .into_iter()
5762                    .map(|id| id as u64)
5763                    .collect()
5764            } else {
5765                Vec::new()
5766            }
5767        } else {
5768            Vec::new()
5769        }
5770    }
5771
5772    /// Get all outgoing synapses from a source neuron
5773    ///
5774    /// # Arguments
5775    ///
5776    /// * `source_neuron_id` - The source neuron ID
5777    ///
5778    /// # Returns
5779    ///
5780    /// Vec of (target_neuron_id, weight, psp, synapse_type), or empty if NPU not connected
5781    ///
5782    pub fn get_outgoing_synapses(&self, source_neuron_id: u64) -> Vec<(u32, f32, f32, u8)> {
5783        if let Some(ref npu) = self.npu {
5784            if let Ok(npu_lock) = npu.lock() {
5785                npu_lock.get_outgoing_synapses(source_neuron_id as u32)
5786            } else {
5787                Vec::new()
5788            }
5789        } else {
5790            Vec::new()
5791        }
5792    }
5793
5794    /// Get all incoming synapses to a target neuron
5795    ///
5796    /// # Arguments
5797    ///
5798    /// * `target_neuron_id` - The target neuron ID
5799    ///
5800    /// # Returns
5801    ///
5802    /// Vec of (source_neuron_id, weight, psp, synapse_type), or empty if NPU not connected
5803    ///
5804    pub fn get_incoming_synapses(&self, target_neuron_id: u64) -> Vec<(u32, f32, f32, u8)> {
5805        if let Some(ref npu) = self.npu {
5806            if let Ok(npu_lock) = npu.lock() {
5807                npu_lock.get_incoming_synapses(target_neuron_id as u32)
5808            } else {
5809                Vec::new()
5810            }
5811        } else {
5812            Vec::new()
5813        }
5814    }
5815
5816    /// Get neuron count for a specific cortical area
5817    ///
5818    /// # Arguments
5819    ///
5820    /// * `cortical_id` - The cortical area ID (string)
5821    ///
5822    /// # Returns
5823    ///
5824    /// Number of neurons in the area, or 0 if area doesn't exist or NPU not connected
5825    ///
5826    /// Get neuron count for a specific cortical area (lock-free cached read)
5827    ///
5828    /// # Arguments
5829    ///
5830    /// * `cortical_id` - The cortical area ID
5831    ///
5832    /// # Returns
5833    ///
5834    /// The number of neurons in the area (from cache, never blocks on NPU lock)
5835    ///
5836    /// # Performance
5837    ///
5838    /// This is a lock-free atomic read that never blocks, even during burst processing.
5839    /// Count is maintained in ConnectomeManager and updated when neurons are created/deleted.
5840    ///
5841    pub fn get_neuron_count_in_area(&self, cortical_id: &CorticalID) -> usize {
5842        let is_memory_area = self
5843            .cortical_areas
5844            .get(cortical_id)
5845            .and_then(|area| feagi_evolutionary::extract_memory_properties(&area.properties))
5846            .is_some();
5847
5848        if is_memory_area {
5849            // @cursor:critical-path - MemoryNeuronArray is the single source of truth for
5850            // per-area memory neuron counts (ST + LT). LTM bridge twins live in the NPU but are
5851            // auxiliary and must not inflate this count.
5852            #[cfg(feature = "plasticity")]
5853            if let Some(count) = self.active_memory_neuron_count_from_plasticity(cortical_id) {
5854                return count;
5855            }
5856
5857            // Plasticity unavailable: use event-driven StateManager cache only.
5858            return StateManager::instance()
5859                .try_read()
5860                .and_then(|state_manager| {
5861                    state_manager
5862                        .get_cortical_area_stats(&cortical_id.as_base_64())
5863                        .map(|stats| stats.neuron_count)
5864                })
5865                .unwrap_or(0);
5866        }
5867
5868        // CRITICAL: Read from cache (lock-free) - never query NPU for healthcheck endpoints
5869        let cache = self.cached_neuron_counts_per_area.read();
5870        cache
5871            .get(cortical_id)
5872            .map(|count| count.load(Ordering::Relaxed))
5873            .unwrap_or(0)
5874    }
5875
5876    /// Active memory-neuron count for a memory cortical area from the plasticity layer.
5877    #[cfg(feature = "plasticity")]
5878    fn active_memory_neuron_count_from_plasticity(
5879        &self,
5880        cortical_id: &CorticalID,
5881    ) -> Option<usize> {
5882        let cortical_idx = self.cortical_id_to_idx.get(cortical_id)?;
5883        let exec = self.get_plasticity_executor()?;
5884        let guard = exec.lock().ok()?;
5885        let runtime = guard.memory_cortical_area_runtime_info(*cortical_idx)?;
5886        Some(runtime.active_memory_neuron_count())
5887    }
5888
5889    /// Get all cortical areas that have neurons
5890    ///
5891    /// # Returns
5892    ///
5893    /// Vec of (cortical_id, neuron_count) for areas with at least one neuron
5894    ///
5895    pub fn get_populated_areas(&self) -> Vec<(String, usize)> {
5896        let mut result = Vec::new();
5897
5898        for cortical_id in self.cortical_areas.keys() {
5899            let count = self.get_neuron_count_in_area(cortical_id);
5900            if count > 0 {
5901                result.push((cortical_id.to_string(), count));
5902            }
5903        }
5904
5905        result
5906    }
5907
5908    /// Check if a cortical area has any neurons
5909    ///
5910    /// # Arguments
5911    ///
5912    /// * `cortical_id` - The cortical area ID
5913    ///
5914    /// # Returns
5915    ///
5916    /// `true` if the area has at least one neuron, `false` otherwise
5917    ///
5918    pub fn is_area_populated(&self, cortical_id: &CorticalID) -> bool {
5919        self.get_neuron_count_in_area(cortical_id) > 0
5920    }
5921
5922    /// Get total synapse count for a specific cortical area (outgoing only) - lock-free cached read
5923    ///
5924    /// # Arguments
5925    ///
5926    /// * `cortical_id` - The cortical area ID
5927    ///
5928    /// # Returns
5929    ///
5930    /// Total number of outgoing synapses from neurons in this area (from cache, never blocks on NPU lock)
5931    ///
5932    /// # Performance
5933    ///
5934    /// This is a lock-free atomic read that never blocks, even during burst processing.
5935    /// Count is maintained in ConnectomeManager and updated when synapses are created/deleted.
5936    ///
5937    pub fn get_synapse_count_in_area(&self, cortical_id: &CorticalID) -> usize {
5938        // CRITICAL: Read from cache (lock-free) - never query NPU for healthcheck endpoints
5939        let cache = self.cached_synapse_counts_per_area.read();
5940        cache
5941            .get(cortical_id)
5942            .map(|count| count.load(Ordering::Relaxed))
5943            .unwrap_or(0)
5944    }
5945
5946    /// Get total incoming synapse count for a specific cortical area.
5947    ///
5948    /// # Arguments
5949    ///
5950    /// * `cortical_id` - The cortical area ID
5951    ///
5952    /// # Returns
5953    ///
5954    /// Total number of incoming synapses targeting neurons in this area.
5955    pub fn get_incoming_synapse_count_in_area(&self, cortical_id: &CorticalID) -> usize {
5956        if !self.cortical_id_to_idx.contains_key(cortical_id) {
5957            return 0;
5958        }
5959
5960        if let Some(state_manager) = StateManager::instance().try_read() {
5961            if let Some(stats) = state_manager.get_cortical_area_stats(&cortical_id.as_base_64()) {
5962                return stats.incoming_synapse_count;
5963            }
5964        }
5965
5966        0
5967    }
5968
5969    /// Get total outgoing synapse count for a specific cortical area.
5970    ///
5971    /// # Arguments
5972    ///
5973    /// * `cortical_id` - The cortical area ID
5974    ///
5975    /// # Returns
5976    ///
5977    /// Total number of outgoing synapses originating from neurons in this area.
5978    pub fn get_outgoing_synapse_count_in_area(&self, cortical_id: &CorticalID) -> usize {
5979        if !self.cortical_id_to_idx.contains_key(cortical_id) {
5980            return 0;
5981        }
5982
5983        if let Some(state_manager) = StateManager::instance().try_read() {
5984            if let Some(stats) = state_manager.get_cortical_area_stats(&cortical_id.as_base_64()) {
5985                return stats.outgoing_synapse_count;
5986            }
5987        }
5988
5989        0
5990    }
5991
5992    /// Check if two neurons are connected (source → target)
5993    ///
5994    /// # Arguments
5995    ///
5996    /// * `source_neuron_id` - The source neuron ID
5997    /// * `target_neuron_id` - The target neuron ID
5998    ///
5999    /// # Returns
6000    ///
6001    /// `true` if there is a synapse from source to target, `false` otherwise
6002    ///
6003    pub fn are_neurons_connected(&self, source_neuron_id: u64, target_neuron_id: u64) -> bool {
6004        let synapses = self.get_outgoing_synapses(source_neuron_id);
6005        synapses
6006            .iter()
6007            .any(|(target, _, _, _)| *target == target_neuron_id as u32)
6008    }
6009
6010    /// Get connection strength (weight) between two neurons
6011    ///
6012    /// # Arguments
6013    ///
6014    /// * `source_neuron_id` - The source neuron ID
6015    /// * `target_neuron_id` - The target neuron ID
6016    ///
6017    /// # Returns
6018    ///
6019    /// Synapse weight (`f32`), or None if no connection exists
6020    ///
6021    pub fn get_connection_weight(
6022        &self,
6023        source_neuron_id: u64,
6024        target_neuron_id: u64,
6025    ) -> Option<f32> {
6026        let synapses = self.get_outgoing_synapses(source_neuron_id);
6027        synapses
6028            .iter()
6029            .find(|(target, _, _, _)| *target == target_neuron_id as u32)
6030            .map(|(_, weight, _, _)| *weight)
6031    }
6032
6033    /// Get connectivity statistics for a cortical area
6034    ///
6035    /// # Arguments
6036    ///
6037    /// * `cortical_id` - The cortical area ID
6038    ///
6039    /// # Returns
6040    ///
6041    /// (neuron_count, total_synapses, avg_synapses_per_neuron)
6042    ///
6043    pub fn get_area_connectivity_stats(&self, cortical_id: &CorticalID) -> (usize, usize, f32) {
6044        let neurons = self.get_neurons_in_area(cortical_id);
6045        let neuron_count = neurons.len();
6046
6047        if neuron_count == 0 {
6048            return (0, 0, 0.0);
6049        }
6050
6051        let mut total_synapses = 0;
6052        for neuron_id in neurons {
6053            total_synapses += self.get_outgoing_synapses(neuron_id).len();
6054        }
6055
6056        let avg_synapses = total_synapses as f32 / neuron_count as f32;
6057
6058        (neuron_count, total_synapses, avg_synapses)
6059    }
6060
6061    /// Get the cortical area ID (string) for a neuron
6062    ///
6063    /// # Arguments
6064    ///
6065    /// * `neuron_id` - The neuron ID
6066    ///
6067    /// # Returns
6068    ///
6069    /// The cortical area ID, or None if neuron doesn't exist
6070    ///
6071    pub fn get_neuron_cortical_id(&self, neuron_id: u64) -> Option<CorticalID> {
6072        let cortical_idx = self.get_neuron_cortical_idx_opt(neuron_id)?;
6073        self.cortical_idx_to_id.get(&cortical_idx).copied()
6074    }
6075
6076    /// Get neuron density (neurons per voxel) for a cortical area
6077    ///
6078    /// # Arguments
6079    ///
6080    /// * `cortical_id` - The cortical area ID
6081    ///
6082    /// # Returns
6083    ///
6084    /// Neuron density (neurons per voxel), or 0.0 if area doesn't exist
6085    ///
6086    pub fn get_neuron_density(&self, cortical_id: &CorticalID) -> f32 {
6087        let area = match self.cortical_areas.get(cortical_id) {
6088            Some(a) => a,
6089            None => return 0.0,
6090        };
6091
6092        let neuron_count = self.get_neuron_count_in_area(cortical_id);
6093        let volume = area.dimensions.width * area.dimensions.height * area.dimensions.depth;
6094
6095        if volume == 0 {
6096            return 0.0;
6097        }
6098
6099        neuron_count as f32 / volume as f32
6100    }
6101
6102    /// Get all cortical areas with connectivity statistics
6103    ///
6104    /// # Returns
6105    ///
6106    /// Vec of (cortical_id, neuron_count, synapse_count, density)
6107    ///
6108    pub fn get_all_area_stats(&self) -> Vec<(String, usize, usize, f32)> {
6109        let mut stats = Vec::new();
6110
6111        for cortical_id in self.cortical_areas.keys() {
6112            let neuron_count = self.get_neuron_count_in_area(cortical_id);
6113            let synapse_count = self.get_synapse_count_in_area(cortical_id);
6114            let density = self.get_neuron_density(cortical_id);
6115
6116            stats.push((
6117                cortical_id.to_string(),
6118                neuron_count,
6119                synapse_count,
6120                density,
6121            ));
6122        }
6123
6124        stats
6125    }
6126
6127    // ======================================================================
6128    // Configuration
6129    // ======================================================================
6130
6131    /// Get the configuration
6132    pub fn get_config(&self) -> &ConnectomeConfig {
6133        &self.config
6134    }
6135
6136    /// Update configuration
6137    pub fn set_config(&mut self, config: ConnectomeConfig) {
6138        self.config = config;
6139    }
6140
6141    // ======================================================================
6142    // Genome I/O
6143    // ======================================================================
6144
6145    /// Ensure core cortical areas (_death, _power, _fatigue, _pain, _pleasure, _fear, _hope) exist
6146    ///
6147    /// Core areas are required for brain operation:
6148    /// - `_death` (cortical_idx=0): Manages neuron death and cleanup
6149    /// - `_power` (cortical_idx=1): Provides power injection for burst engine
6150    /// - `_fatigue` (cortical_idx=2): Monitors brain fatigue and triggers sleep mode
6151    /// - `_pain` (cortical_idx=3): Pain signal processing
6152    /// - `_pleasure` (cortical_idx=4): Pleasure signal processing
6153    /// - `_fear` (cortical_idx=5): Fear signal processing
6154    /// - `_hope` (cortical_idx=6): Hope signal processing
6155    ///
6156    /// If any core area is missing from the genome, it will be automatically created
6157    /// with default properties (1x1x1 dimensions, minimal configuration).
6158    ///
6159    /// # Returns
6160    ///
6161    /// * `Ok(())` if all core areas exist or were successfully created
6162    /// * `Err(BduError)` if creation fails
6163    pub fn ensure_core_cortical_areas(&mut self) -> BduResult<()> {
6164        info!(target: "feagi-bdu", "🔧 [CORE-AREA] Ensuring core cortical areas exist...");
6165
6166        use feagi_structures::genomic::cortical_area::{
6167            CoreCorticalType, CorticalArea, CorticalAreaDimensions, CorticalAreaType,
6168        };
6169
6170        // Core areas are always 1x1x1 as per requirements
6171        let core_dimensions = CorticalAreaDimensions::new(1, 1, 1).map_err(|e| {
6172            BduError::Internal(format!("Failed to create core area dimensions: {}", e))
6173        })?;
6174
6175        // Default position for core areas (origin)
6176        let core_position = (0, 0, 0).into();
6177
6178        // Check and create _death (cortical_idx=0)
6179        let death_id = CoreCorticalType::Death.to_cortical_id();
6180        if !self.cortical_areas.contains_key(&death_id) {
6181            info!(target: "feagi-bdu", "🔧 [CORE-AREA] Creating missing _death area (cortical_idx=0)");
6182            let death_area = CorticalArea::new(
6183                death_id,
6184                0, // Will be overridden by add_cortical_area to 0
6185                "_death".to_string(),
6186                core_dimensions,
6187                core_position,
6188                CorticalAreaType::Core(CoreCorticalType::Death),
6189            )
6190            .map_err(|e| BduError::Internal(format!("Failed to create _death area: {}", e)))?;
6191            match self.add_cortical_area(death_area) {
6192                Ok(idx) => {
6193                    info!(target: "feagi-bdu", "  ✅ Created _death area with cortical_idx={}", idx);
6194                }
6195                Err(e) => {
6196                    error!(target: "feagi-bdu", "  ❌ Failed to add _death area: {}", e);
6197                    return Err(e);
6198                }
6199            }
6200        } else {
6201            info!(target: "feagi-bdu", "  ✓ _death area already exists");
6202        }
6203
6204        // Check and create _power (cortical_idx=1)
6205        let power_id = CoreCorticalType::Power.to_cortical_id();
6206        if !self.cortical_areas.contains_key(&power_id) {
6207            info!(target: "feagi-bdu", "🔧 [CORE-AREA] Creating missing _power area (cortical_idx=1)");
6208            let power_area = CorticalArea::new(
6209                power_id,
6210                1, // Will be overridden by add_cortical_area to 1
6211                "_power".to_string(),
6212                core_dimensions,
6213                core_position,
6214                CorticalAreaType::Core(CoreCorticalType::Power),
6215            )
6216            .map_err(|e| BduError::Internal(format!("Failed to create _power area: {}", e)))?;
6217            match self.add_cortical_area(power_area) {
6218                Ok(idx) => {
6219                    info!(target: "feagi-bdu", "  ✅ Created _power area with cortical_idx={}", idx);
6220                }
6221                Err(e) => {
6222                    error!(target: "feagi-bdu", "  ❌ Failed to add _power area: {}", e);
6223                    return Err(e);
6224                }
6225            }
6226        } else {
6227            info!(target: "feagi-bdu", "  ✓ _power area already exists");
6228        }
6229
6230        // Check and create _fatigue (cortical_idx=2)
6231        let fatigue_id = CoreCorticalType::Fatigue.to_cortical_id();
6232        let pain_id = CoreCorticalType::Pain.to_cortical_id();
6233        let pleasure_id = CoreCorticalType::Pleasure.to_cortical_id();
6234        let fear_id = CoreCorticalType::Fear.to_cortical_id();
6235        let hope_id = CoreCorticalType::Hope.to_cortical_id();
6236        if !self.cortical_areas.contains_key(&fatigue_id) {
6237            info!(target: "feagi-bdu", "🔧 [CORE-AREA] Creating missing _fatigue area (cortical_idx=2)");
6238            let fatigue_area = CorticalArea::new(
6239                fatigue_id,
6240                2, // Will be overridden by add_cortical_area to 2
6241                "_fatigue".to_string(),
6242                core_dimensions,
6243                core_position,
6244                CorticalAreaType::Core(CoreCorticalType::Fatigue),
6245            )
6246            .map_err(|e| BduError::Internal(format!("Failed to create _fatigue area: {}", e)))?;
6247            match self.add_cortical_area(fatigue_area) {
6248                Ok(idx) => {
6249                    info!(target: "feagi-bdu", "  ✅ Created _fatigue area with cortical_idx={}", idx);
6250                }
6251                Err(e) => {
6252                    error!(target: "feagi-bdu", "  ❌ Failed to add _fatigue area: {}", e);
6253                    return Err(e);
6254                }
6255            }
6256        } else {
6257            info!(target: "feagi-bdu", "  ✓ _fatigue area already exists");
6258        }
6259
6260        // Check and create _pain (cortical_idx=3)
6261        if !self.cortical_areas.contains_key(&pain_id) {
6262            info!(target: "feagi-bdu", "🔧 [CORE-AREA] Creating missing _pain area (cortical_idx=3)");
6263            let pain_area = CorticalArea::new(
6264                pain_id,
6265                3, // Will be overridden by add_cortical_area to 3
6266                "_pain".to_string(),
6267                core_dimensions,
6268                core_position,
6269                CorticalAreaType::Core(CoreCorticalType::Pain),
6270            )
6271            .map_err(|e| BduError::Internal(format!("Failed to create _pain area: {}", e)))?;
6272            match self.add_cortical_area(pain_area) {
6273                Ok(idx) => {
6274                    info!(target: "feagi-bdu", "  ✅ Created _pain area with cortical_idx={}", idx);
6275                }
6276                Err(e) => {
6277                    error!(target: "feagi-bdu", "  ❌ Failed to add _pain area: {}", e);
6278                    return Err(e);
6279                }
6280            }
6281        } else {
6282            info!(target: "feagi-bdu", "  ✓ _pain area already exists");
6283        }
6284
6285        // Check and create _pleasure (cortical_idx=4)
6286        if !self.cortical_areas.contains_key(&pleasure_id) {
6287            info!(target: "feagi-bdu", "🔧 [CORE-AREA] Creating missing _pleasure area (cortical_idx=4)");
6288            let pleasure_area = CorticalArea::new(
6289                pleasure_id,
6290                4, // Will be overridden by add_cortical_area to 4
6291                "_pleasure".to_string(),
6292                core_dimensions,
6293                core_position,
6294                CorticalAreaType::Core(CoreCorticalType::Pleasure),
6295            )
6296            .map_err(|e| BduError::Internal(format!("Failed to create _pleasure area: {}", e)))?;
6297            match self.add_cortical_area(pleasure_area) {
6298                Ok(idx) => {
6299                    info!(target: "feagi-bdu", "  ✅ Created _pleasure area with cortical_idx={}", idx);
6300                }
6301                Err(e) => {
6302                    error!(target: "feagi-bdu", "  ❌ Failed to add _pleasure area: {}", e);
6303                    return Err(e);
6304                }
6305            }
6306        } else {
6307            info!(target: "feagi-bdu", "  ✓ _pleasure area already exists");
6308        }
6309
6310        // Check and create _fear (cortical_idx=5)
6311        if !self.cortical_areas.contains_key(&fear_id) {
6312            info!(target: "feagi-bdu", "🔧 [CORE-AREA] Creating missing _fear area (cortical_idx=5)");
6313            let fear_area = CorticalArea::new(
6314                fear_id,
6315                5, // Will be overridden by add_cortical_area to 5
6316                "_fear".to_string(),
6317                core_dimensions,
6318                core_position,
6319                CorticalAreaType::Core(CoreCorticalType::Fear),
6320            )
6321            .map_err(|e| BduError::Internal(format!("Failed to create _fear area: {}", e)))?;
6322            match self.add_cortical_area(fear_area) {
6323                Ok(idx) => {
6324                    info!(target: "feagi-bdu", "  ✅ Created _fear area with cortical_idx={}", idx);
6325                }
6326                Err(e) => {
6327                    error!(target: "feagi-bdu", "  ❌ Failed to add _fear area: {}", e);
6328                    return Err(e);
6329                }
6330            }
6331        } else {
6332            info!(target: "feagi-bdu", "  ✓ _fear area already exists");
6333        }
6334
6335        // Check and create _hope (cortical_idx=6)
6336        if !self.cortical_areas.contains_key(&hope_id) {
6337            info!(target: "feagi-bdu", "🔧 [CORE-AREA] Creating missing _hope area (cortical_idx=6)");
6338            let hope_area = CorticalArea::new(
6339                hope_id,
6340                6, // Will be overridden by add_cortical_area to 6
6341                "_hope".to_string(),
6342                core_dimensions,
6343                core_position,
6344                CorticalAreaType::Core(CoreCorticalType::Hope),
6345            )
6346            .map_err(|e| BduError::Internal(format!("Failed to create _hope area: {}", e)))?;
6347            match self.add_cortical_area(hope_area) {
6348                Ok(idx) => {
6349                    info!(target: "feagi-bdu", "  ✅ Created _hope area with cortical_idx={}", idx);
6350                }
6351                Err(e) => {
6352                    error!(target: "feagi-bdu", "  ❌ Failed to add _hope area: {}", e);
6353                    return Err(e);
6354                }
6355            }
6356        } else {
6357            info!(target: "feagi-bdu", "  ✓ _hope area already exists");
6358        }
6359
6360        info!(target: "feagi-bdu", "🔧 [CORE-AREA] Core area check complete");
6361        Ok(())
6362    }
6363
6364    /// Save the connectome as a genome JSON
6365    ///
6366    /// **DEPRECATED**: This method produces incomplete hierarchical format v2.1 without morphologies/physiology.
6367    /// Use `GenomeService::save_genome()` instead, which produces complete flat format v3.0.
6368    ///
6369    /// This method is kept only for legacy tests. Production code MUST use GenomeService.
6370    ///
6371    /// # Arguments
6372    ///
6373    /// * `genome_id` - Optional custom genome ID (generates timestamp-based ID if None)
6374    /// * `genome_title` - Optional custom genome title
6375    ///
6376    /// # Returns
6377    ///
6378    /// JSON string representation of the genome (hierarchical v2.1, incomplete)
6379    ///
6380    #[deprecated(
6381        note = "Use GenomeService::save_genome() instead. This produces incomplete v2.1 format without morphologies/physiology."
6382    )]
6383    #[allow(deprecated)]
6384    pub fn save_genome_to_json(
6385        &self,
6386        genome_id: Option<String>,
6387        genome_title: Option<String>,
6388    ) -> BduResult<String> {
6389        // Build parent map from brain region hierarchy
6390        let mut brain_regions_with_parents = std::collections::HashMap::new();
6391
6392        for region_id in self.brain_regions.get_all_region_ids() {
6393            if let Some(region) = self.brain_regions.get_region(region_id) {
6394                let parent_id = self
6395                    .brain_regions
6396                    .get_parent(region_id)
6397                    .map(|s| s.to_string());
6398                brain_regions_with_parents
6399                    .insert(region_id.to_string(), (region.clone(), parent_id));
6400            }
6401        }
6402
6403        // Generate and return JSON
6404        Ok(feagi_evolutionary::GenomeSaver::save_to_json(
6405            &self.cortical_areas,
6406            &brain_regions_with_parents,
6407            genome_id,
6408            genome_title,
6409        )?)
6410    }
6411
6412    // Load genome from file and develop brain
6413    //
6414    // This was a high-level convenience method that:
6415    // 1. Loads genome from JSON file
6416    // 2. Prepares for new genome (clears existing state)
6417    // 3. Runs neuroembryogenesis to develop the brain
6418    //
6419    // # Arguments
6420    //
6421    // * `genome_path` - Path to genome JSON file
6422    //
6423    // # Returns
6424    //
6425    // Development progress information
6426    //
6427    // NOTE: load_from_genome_file() and load_from_genome() have been REMOVED.
6428    // All genome loading must now go through GenomeService::load_genome() which:
6429    // - Stores RuntimeGenome for persistence
6430    // - Updates genome metadata
6431    // - Provides async/await support
6432    // - Includes timeout protection
6433    // - Ensures core cortical areas exist
6434    //
6435    // See: feagi-services/src/impls/genome_service_impl.rs::load_genome()
6436
6437    /// Prepare for loading a new genome
6438    ///
6439    /// Clears all existing cortical areas, brain regions, and resets state.
6440    /// This is typically called before loading a new genome.
6441    ///
6442    pub fn prepare_for_new_genome(&mut self) -> BduResult<()> {
6443        info!(target: "feagi-bdu","Preparing for new genome (clearing existing state)");
6444
6445        // Clear cortical areas
6446        self.cortical_areas.clear();
6447        self.cortical_id_to_idx.clear();
6448        self.cortical_idx_to_id.clear();
6449        // CRITICAL: Reserve 0..=6 for invariant core areas.
6450        self.next_cortical_idx = 7;
6451        info!("🔧 [BRAIN-RESET] Cortical mapping cleared, next_cortical_idx reset to 7 (reserves 0=_death, 1=_power, 2=_fatigue, 3=_pain, 4=_pleasure, 5=_fear, 6=_hope)");
6452
6453        // Clear brain regions
6454        self.brain_regions = BrainRegionHierarchy::new();
6455
6456        // Drop memory neurons and memory-area registrations. Their cortical indexes belong
6457        // to the previous index map, which the reset above invalidates.
6458        #[cfg(feature = "plasticity")]
6459        if let Some(executor) = self.plasticity_executor.as_ref() {
6460            executor
6461                .lock()
6462                .map_err(|_| {
6463                    BduError::Internal(
6464                        "Failed to lock PlasticityExecutor for memory state reset".to_string(),
6465                    )
6466                })?
6467                .reset_all_memory_state()
6468                .map_err(BduError::Internal)?;
6469        }
6470
6471        // Reset NPU runtime state to prevent old neurons/synapses from leaking into the next genome.
6472        if let Some(ref npu) = self.npu {
6473            let mut npu_lock = npu
6474                .lock()
6475                .map_err(|e| BduError::Internal(format!("Failed to lock NPU: {}", e)))?;
6476            npu_lock
6477                .reset_for_new_genome()
6478                .map_err(|e| BduError::Internal(format!("Failed to reset NPU: {}", e)))?;
6479        }
6480
6481        info!(target: "feagi-bdu","✅ Connectome cleared and ready for new genome");
6482        Ok(())
6483    }
6484
6485    /// Calculate and resize memory for a genome
6486    ///
6487    /// Analyzes the genome to determine memory requirements and
6488    /// prepares the NPU for the expected neuron/synapse counts.
6489    ///
6490    /// # Arguments
6491    ///
6492    /// * `genome` - Genome to analyze for memory requirements
6493    ///
6494    pub fn resize_for_genome(
6495        &mut self,
6496        genome: &feagi_evolutionary::RuntimeGenome,
6497    ) -> BduResult<()> {
6498        // Store morphologies from genome
6499        self.morphology_registry = genome.morphologies.clone();
6500        info!(target: "feagi-bdu", "Stored {} morphologies from genome", self.morphology_registry.count());
6501
6502        // Calculate required capacity from genome stats
6503        let required_neurons = genome.stats.innate_neuron_count;
6504        let required_synapses = genome.stats.innate_synapse_count;
6505
6506        info!(target: "feagi-bdu",
6507            "Genome requires: {} neurons, {} synapses",
6508            required_neurons,
6509            required_synapses
6510        );
6511
6512        // Calculate total voxels from all cortical areas
6513        let mut total_voxels = 0;
6514        for area in genome.cortical_areas.values() {
6515            total_voxels += area.dimensions.width * area.dimensions.height * area.dimensions.depth;
6516        }
6517
6518        info!(target: "feagi-bdu",
6519            "Genome has {} cortical areas with {} total voxels",
6520            genome.cortical_areas.len(),
6521            total_voxels
6522        );
6523
6524        // TODO: Resize NPU if needed
6525        // For now, we assume NPU has sufficient capacity
6526        // In the future, we may want to dynamically resize the NPU based on genome requirements
6527
6528        Ok(())
6529    }
6530
6531    // ========================================================================
6532    // SYNAPSE OPERATIONS
6533    // ========================================================================
6534
6535    /// Create a synapse between two neurons
6536    ///
6537    /// # Arguments
6538    ///
6539    /// * `source_neuron_id` - Source neuron ID
6540    /// * `target_neuron_id` - Target neuron ID
6541    /// * `weight` - Synapse weight (`f32`)
6542    /// * `psp` - Synapse PSP (`f32`)
6543    /// * `synapse_type` - Synapse type (0=excitatory, 1=inhibitory)
6544    ///
6545    /// # Returns
6546    ///
6547    /// `Ok(())` if synapse created successfully
6548    ///
6549    pub fn create_synapse(
6550        &mut self,
6551        source_neuron_id: u64,
6552        target_neuron_id: u64,
6553        weight: f32,
6554        psp: f32,
6555        synapse_type: u8,
6556    ) -> BduResult<()> {
6557        // Get NPU
6558        let npu = self
6559            .npu
6560            .as_ref()
6561            .ok_or_else(|| BduError::Internal("NPU not connected".to_string()))?;
6562
6563        let mut npu_lock = npu
6564            .lock()
6565            .map_err(|e| BduError::Internal(format!("Failed to lock NPU: {}", e)))?;
6566
6567        // Verify both neurons exist
6568        let source_exists = (source_neuron_id as u32) < npu_lock.get_neuron_count() as u32;
6569        let target_exists = (target_neuron_id as u32) < npu_lock.get_neuron_count() as u32;
6570
6571        if !source_exists {
6572            return Err(BduError::InvalidNeuron(format!(
6573                "Source neuron {} not found",
6574                source_neuron_id
6575            )));
6576        }
6577        if !target_exists {
6578            return Err(BduError::InvalidNeuron(format!(
6579                "Target neuron {} not found",
6580                target_neuron_id
6581            )));
6582        }
6583
6584        // Create synapse via NPU
6585        let syn_type = if synapse_type == 0 {
6586            feagi_npu_neural::synapse::SynapseType::Excitatory
6587        } else {
6588            feagi_npu_neural::synapse::SynapseType::Inhibitory
6589        };
6590
6591        let synapse_idx = npu_lock
6592            .add_synapse(
6593                NeuronId(source_neuron_id as u32),
6594                NeuronId(target_neuron_id as u32),
6595                feagi_npu_neural::types::SynapticWeight(weight),
6596                feagi_npu_neural::types::SynapticPsp(psp),
6597                syn_type,
6598                0,
6599                1,
6600            )
6601            .map_err(|e| BduError::Internal(format!("Failed to create synapse: {}", e)))?;
6602
6603        debug!(target: "feagi-bdu", "Created synapse: {} -> {} (weight: {}, psp: {}, type: {}, idx: {})",
6604            source_neuron_id, target_neuron_id, weight, psp, synapse_type, synapse_idx);
6605
6606        let source_cortical_idx = npu_lock.get_neuron_cortical_area(source_neuron_id as u32);
6607        let target_cortical_idx = npu_lock.get_neuron_cortical_area(target_neuron_id as u32);
6608        let source_cortical_id =
6609            source_cortical_idx.and_then(|idx| self.cortical_idx_to_id.get(&idx).cloned());
6610        let target_cortical_id =
6611            target_cortical_idx.and_then(|idx| self.cortical_idx_to_id.get(&idx).cloned());
6612
6613        let state_manager = StateManager::instance();
6614        let state_manager = state_manager.read();
6615        let core_state = state_manager.get_core_state();
6616        core_state.add_synapse_count(1);
6617        if let Some(cortical_id) = source_cortical_id {
6618            state_manager.add_cortical_area_outgoing_synapses(&cortical_id.as_base_64(), 1);
6619        }
6620        if let Some(cortical_id) = target_cortical_id {
6621            state_manager.add_cortical_area_incoming_synapses(&cortical_id.as_base_64(), 1);
6622        }
6623
6624        // Trigger fatigue index recalculation after synapse creation
6625        // NOTE: Disabled during genome loading to prevent blocking
6626        // let _ = self.update_fatigue_index();
6627
6628        Ok(())
6629    }
6630
6631    /// Synchronize cortical area flags with NPU
6632    /// This should be called after adding/updating cortical areas
6633    fn sync_cortical_area_flags_to_npu(&mut self) -> BduResult<()> {
6634        if let Some(ref npu) = self.npu {
6635            if let Ok(mut npu_lock) = npu.lock() {
6636                // Build psp_uniform_distribution flags map
6637                let mut psp_uniform_flags = ahash::AHashMap::new();
6638                let mut mp_driven_psp_flags = ahash::AHashMap::new();
6639                let mut postsynaptic_current_flags = ahash::AHashMap::new();
6640                let mut degeneration_flags = ahash::AHashMap::new();
6641
6642                for (cortical_id, area) in &self.cortical_areas {
6643                    // When the property is absent: Power and Memory cortical areas default to uniform
6644                    // PSP (full PSP per synapse); other areas default to divided PSP.
6645                    let default_psp_uniform = *cortical_id
6646                        == CoreCorticalType::Power.to_cortical_id()
6647                        || matches!(area.cortical_type, CorticalAreaType::Memory(_));
6648                    let psp_uniform = area
6649                        .get_property("psp_uniform_distribution")
6650                        .and_then(|v| v.as_bool())
6651                        .unwrap_or(default_psp_uniform);
6652                    psp_uniform_flags.insert(*cortical_id, psp_uniform);
6653
6654                    // Get mp_driven_psp flag (default to false)
6655                    let mp_driven_psp = area
6656                        .get_property("mp_driven_psp")
6657                        .and_then(|v| v.as_bool())
6658                        .unwrap_or(false);
6659                    mp_driven_psp_flags.insert(*cortical_id, mp_driven_psp);
6660
6661                    // Store configured baseline PSP for reset-time restoration.
6662                    let postsynaptic_current = area
6663                        .get_property("postsynaptic_current")
6664                        .and_then(|v| v.as_f64())
6665                        .unwrap_or(1.0) as f32;
6666                    postsynaptic_current_flags.insert(*cortical_id, postsynaptic_current);
6667
6668                    // Get degeneration coefficient (default 0.0 = disabled)
6669                    let degeneration = area
6670                        .get_property("degeneration")
6671                        .and_then(|v| v.as_f64())
6672                        .unwrap_or(0.0) as f32;
6673                    if degeneration > 0.0 {
6674                        degeneration_flags.insert(*cortical_id, degeneration);
6675                    }
6676                }
6677
6678                // Update NPU with flags
6679                npu_lock.set_psp_uniform_distribution_flags(psp_uniform_flags);
6680                npu_lock.set_mp_driven_psp_flags(mp_driven_psp_flags);
6681                npu_lock.set_postsynaptic_current_flags(postsynaptic_current_flags);
6682                npu_lock.set_degeneration_flags(degeneration_flags);
6683
6684                trace!(
6685                    target: "feagi-bdu",
6686                    "Synchronized cortical area flags to NPU ({} areas)",
6687                    self.cortical_areas.len()
6688                );
6689            }
6690        }
6691
6692        Ok(())
6693    }
6694
6695    /// Get synapse information between two neurons
6696    ///
6697    /// # Arguments
6698    ///
6699    /// * `source_neuron_id` - Source neuron ID
6700    /// * `target_neuron_id` - Target neuron ID
6701    ///
6702    /// # Returns
6703    ///
6704    /// `Some((weight, psp, type))` if synapse exists, `None` otherwise
6705    ///
6706    pub fn get_synapse(
6707        &self,
6708        source_neuron_id: u64,
6709        target_neuron_id: u64,
6710    ) -> Option<(f32, f32, u8)> {
6711        // Get NPU
6712        let npu = self.npu.as_ref()?;
6713        let npu_lock = npu.lock().ok()?;
6714
6715        // Use get_incoming_synapses and filter by source
6716        // (This does O(n) scan of synapse_array, but works even when propagation engine isn't updated)
6717        let incoming = npu_lock.get_incoming_synapses(target_neuron_id as u32);
6718
6719        // Find the synapse from our specific source
6720        for (source_id, weight, psp, synapse_type) in incoming {
6721            if source_id == source_neuron_id as u32 {
6722                return Some((weight, psp, synapse_type));
6723            }
6724        }
6725
6726        None
6727    }
6728
6729    /// Update the weight of an existing synapse
6730    ///
6731    /// # Arguments
6732    ///
6733    /// * `source_neuron_id` - Source neuron ID
6734    /// * `target_neuron_id` - Target neuron ID
6735    /// * `new_weight` - New synapse weight (0-255)
6736    ///
6737    /// # Returns
6738    ///
6739    /// `Ok(())` if synapse updated, `Err` if synapse not found
6740    ///
6741    pub fn update_synapse_weight(
6742        &mut self,
6743        source_neuron_id: u64,
6744        target_neuron_id: u64,
6745        new_weight: f32,
6746    ) -> BduResult<()> {
6747        // Get NPU
6748        let npu = self
6749            .npu
6750            .as_ref()
6751            .ok_or_else(|| BduError::Internal("NPU not connected".to_string()))?;
6752
6753        let mut npu_lock = npu
6754            .lock()
6755            .map_err(|e| BduError::Internal(format!("Failed to lock NPU: {}", e)))?;
6756
6757        // Update synapse weight via NPU
6758        let updated = npu_lock.update_synapse_weight(
6759            NeuronId(source_neuron_id as u32),
6760            NeuronId(target_neuron_id as u32),
6761            feagi_npu_neural::types::SynapticWeight(new_weight),
6762        );
6763
6764        if updated {
6765            debug!(target: "feagi-bdu","Updated synapse weight: {} -> {} = {}", source_neuron_id, target_neuron_id, new_weight);
6766            Ok(())
6767        } else {
6768            Err(BduError::InvalidSynapse(format!(
6769                "Synapse {} -> {} not found",
6770                source_neuron_id, target_neuron_id
6771            )))
6772        }
6773    }
6774
6775    /// Remove a synapse between two neurons
6776    ///
6777    /// # Arguments
6778    ///
6779    /// * `source_neuron_id` - Source neuron ID
6780    /// * `target_neuron_id` - Target neuron ID
6781    ///
6782    /// # Returns
6783    ///
6784    /// `Ok(true)` if synapse removed, `Ok(false)` if synapse didn't exist
6785    ///
6786    pub fn remove_synapse(
6787        &mut self,
6788        source_neuron_id: u64,
6789        target_neuron_id: u64,
6790    ) -> BduResult<bool> {
6791        // Get NPU
6792        let npu = self
6793            .npu
6794            .as_ref()
6795            .ok_or_else(|| BduError::Internal("NPU not connected".to_string()))?;
6796
6797        let mut npu_lock = npu
6798            .lock()
6799            .map_err(|e| BduError::Internal(format!("Failed to lock NPU: {}", e)))?;
6800
6801        let source_cortical_idx = npu_lock.get_neuron_cortical_area(source_neuron_id as u32);
6802        let target_cortical_idx = npu_lock.get_neuron_cortical_area(target_neuron_id as u32);
6803        let source_cortical_id =
6804            source_cortical_idx.and_then(|idx| self.cortical_idx_to_id.get(&idx).cloned());
6805        let target_cortical_id =
6806            target_cortical_idx.and_then(|idx| self.cortical_idx_to_id.get(&idx).cloned());
6807
6808        // Remove synapse via NPU
6809        let removed = npu_lock.remove_synapse(
6810            NeuronId(source_neuron_id as u32),
6811            NeuronId(target_neuron_id as u32),
6812        );
6813
6814        if removed {
6815            debug!(target: "feagi-bdu","Removed synapse: {} -> {}", source_neuron_id, target_neuron_id);
6816
6817            // CRITICAL: Update StateManager synapse count (for health_check endpoint)
6818            let state_manager = StateManager::instance();
6819            let state_manager = state_manager.read();
6820            let core_state = state_manager.get_core_state();
6821            core_state.subtract_synapse_count(1);
6822            if let Some(cortical_id) = source_cortical_id {
6823                state_manager
6824                    .subtract_cortical_area_outgoing_synapses(&cortical_id.as_base_64(), 1);
6825            }
6826            if let Some(cortical_id) = target_cortical_id {
6827                state_manager
6828                    .subtract_cortical_area_incoming_synapses(&cortical_id.as_base_64(), 1);
6829            }
6830        }
6831
6832        Ok(removed)
6833    }
6834
6835    // ========================================================================
6836    // BATCH OPERATIONS
6837    // ========================================================================
6838
6839    /// Batch create multiple neurons at once (SIMD-optimized)
6840    ///
6841    /// This is significantly faster than calling `add_neuron()` in a loop
6842    ///
6843    /// # Arguments
6844    ///
6845    /// * `cortical_id` - Target cortical area
6846    /// * `neurons` - Vector of neuron parameters (x, y, z, firing_threshold, leak, resting_potential, etc.)
6847    ///
6848    /// # Returns
6849    ///
6850    /// Vector of created neuron IDs
6851    ///
6852    pub fn batch_create_neurons(
6853        &mut self,
6854        cortical_id: &CorticalID,
6855        neurons: Vec<NeuronData>,
6856    ) -> BduResult<Vec<u64>> {
6857        // Get NPU
6858        let npu = self
6859            .npu
6860            .as_ref()
6861            .ok_or_else(|| BduError::Internal("NPU not connected".to_string()))?;
6862
6863        let mut npu_lock = npu
6864            .lock()
6865            .map_err(|e| BduError::Internal(format!("Failed to lock NPU: {}", e)))?;
6866
6867        // Get cortical area to verify it exists and get its index
6868        let area = self.get_cortical_area(cortical_id).ok_or_else(|| {
6869            BduError::InvalidArea(format!("Cortical area {} not found", cortical_id))
6870        })?;
6871        let cortical_idx = area.cortical_idx;
6872
6873        let count = neurons.len();
6874
6875        // Extract parameters into separate vectors for batch operation
6876        let mut x_coords = Vec::with_capacity(count);
6877        let mut y_coords = Vec::with_capacity(count);
6878        let mut z_coords = Vec::with_capacity(count);
6879        let mut firing_thresholds = Vec::with_capacity(count);
6880        let mut threshold_limits = Vec::with_capacity(count);
6881        let mut leak_coeffs = Vec::with_capacity(count);
6882        let mut resting_potentials = Vec::with_capacity(count);
6883        let mut neuron_types = Vec::with_capacity(count);
6884        let mut refractory_periods = Vec::with_capacity(count);
6885        let mut excitabilities = Vec::with_capacity(count);
6886        let mut consec_fire_limits = Vec::with_capacity(count);
6887        let mut snooze_lengths = Vec::with_capacity(count);
6888        let mut mp_accums = Vec::with_capacity(count);
6889        let mut cortical_areas = Vec::with_capacity(count);
6890
6891        for (
6892            x,
6893            y,
6894            z,
6895            threshold,
6896            threshold_limit,
6897            leak,
6898            resting,
6899            ntype,
6900            refract,
6901            excit,
6902            consec_limit,
6903            snooze,
6904            mp_accum,
6905        ) in neurons
6906        {
6907            x_coords.push(x);
6908            y_coords.push(y);
6909            z_coords.push(z);
6910            firing_thresholds.push(threshold);
6911            threshold_limits.push(threshold_limit);
6912            leak_coeffs.push(leak);
6913            resting_potentials.push(resting);
6914            neuron_types.push(ntype);
6915            refractory_periods.push(refract);
6916            excitabilities.push(excit);
6917            consec_fire_limits.push(consec_limit);
6918            snooze_lengths.push(snooze);
6919            mp_accums.push(mp_accum);
6920            cortical_areas.push(cortical_idx);
6921        }
6922
6923        // Get the current neuron count - this will be the first ID of our batch
6924        let first_neuron_id = npu_lock.get_neuron_count() as u32;
6925
6926        // Call NPU batch creation (SIMD-optimized)
6927        // Signature: (thresholds, threshold_limits, leak_coeffs, resting_pots, neuron_types, refract, excit, consec_limits, snooze, mp_accums, cortical_areas, x, y, z)
6928        // Convert f32 vectors to T
6929        // DynamicNPU will handle f32 inputs and convert internally based on its precision
6930        let firing_thresholds_t = firing_thresholds;
6931        let threshold_limits_t = threshold_limits;
6932        let resting_potentials_t = resting_potentials;
6933        let (neurons_created, _indices) = npu_lock.add_neurons_batch(
6934            firing_thresholds_t,
6935            threshold_limits_t,
6936            leak_coeffs,
6937            resting_potentials_t,
6938            neuron_types,
6939            refractory_periods,
6940            excitabilities,
6941            consec_fire_limits,
6942            snooze_lengths,
6943            mp_accums,
6944            cortical_areas,
6945            x_coords,
6946            y_coords,
6947            z_coords,
6948        );
6949
6950        // Generate neuron IDs (they are sequential starting from first_neuron_id)
6951        let mut neuron_ids = Vec::with_capacity(count);
6952        for i in 0..neurons_created {
6953            neuron_ids.push((first_neuron_id + i) as u64);
6954        }
6955
6956        info!(target: "feagi-bdu","Batch created {} neurons in cortical area {}", count, cortical_id);
6957
6958        // CRITICAL: Update StateManager neuron count (for health_check endpoint)
6959        let state_manager = StateManager::instance();
6960        let state_manager = state_manager.read();
6961        let core_state = state_manager.get_core_state();
6962        core_state.add_neuron_count(neurons_created);
6963        core_state.add_regular_neuron_count(neurons_created);
6964        state_manager.add_cortical_area_neuron_count(&cortical_id.as_base_64(), count);
6965
6966        // Best-effort: keep per-area cache in sync for lock-free reads.
6967        {
6968            let mut cache = self.cached_neuron_counts_per_area.write();
6969            cache
6970                .entry(*cortical_id)
6971                .or_insert_with(|| AtomicUsize::new(0))
6972                .fetch_add(count, Ordering::Relaxed);
6973        }
6974
6975        Ok(neuron_ids)
6976    }
6977
6978    /// Delete multiple neurons at once (batch operation)
6979    ///
6980    /// # Arguments
6981    ///
6982    /// * `neuron_ids` - Vector of neuron IDs to delete
6983    ///
6984    /// # Returns
6985    ///
6986    /// Number of neurons actually deleted
6987    ///
6988    pub fn delete_neurons_batch(&mut self, neuron_ids: Vec<u64>) -> BduResult<usize> {
6989        // Get NPU
6990        let npu = self
6991            .npu
6992            .as_ref()
6993            .ok_or_else(|| BduError::Internal("NPU not connected".to_string()))?;
6994
6995        let mut npu_lock = npu
6996            .lock()
6997            .map_err(|e| BduError::Internal(format!("Failed to lock NPU: {}", e)))?;
6998
6999        let mut deleted_count = 0;
7000        let mut per_area_deleted: std::collections::HashMap<String, usize> =
7001            std::collections::HashMap::new();
7002
7003        // Delete each neuron
7004        // Note: Could be optimized with a batch delete method in NPU if needed
7005        for neuron_id in neuron_ids {
7006            let cortical_idx = npu_lock.get_neuron_cortical_area(neuron_id as u32);
7007            let cortical_id =
7008                cortical_idx.and_then(|idx| self.cortical_idx_to_id.get(&idx).cloned());
7009
7010            if npu_lock.delete_neuron(neuron_id as u32) {
7011                deleted_count += 1;
7012                if let Some(cortical_id) = cortical_id {
7013                    let key = cortical_id.as_base_64();
7014                    *per_area_deleted.entry(key).or_insert(0) += 1;
7015                }
7016            }
7017        }
7018
7019        info!(target: "feagi-bdu","Batch deleted {} neurons", deleted_count);
7020
7021        // CRITICAL: Update StateManager neuron count (for health_check endpoint)
7022        if deleted_count > 0 {
7023            let state_manager = StateManager::instance();
7024            let state_manager = state_manager.read();
7025            let core_state = state_manager.get_core_state();
7026            core_state.subtract_neuron_count(deleted_count as u32);
7027            core_state.subtract_regular_neuron_count(deleted_count as u32);
7028            for (cortical_id, count) in per_area_deleted {
7029                state_manager.subtract_cortical_area_neuron_count(&cortical_id, count);
7030            }
7031        }
7032
7033        // Trigger fatigue index recalculation after batch neuron deletion
7034        // NOTE: Disabled during genome loading to prevent blocking
7035        // if deleted_count > 0 {
7036        //     let _ = self.update_fatigue_index();
7037        // }
7038
7039        Ok(deleted_count)
7040    }
7041
7042    // ========================================================================
7043    // NEURON UPDATE OPERATIONS
7044    // ========================================================================
7045
7046    /// Update properties of an existing neuron
7047    ///
7048    /// # Arguments
7049    ///
7050    /// * `neuron_id` - Target neuron ID
7051    /// * `firing_threshold` - Optional new firing threshold
7052    /// * `leak_coefficient` - Optional new leak coefficient
7053    /// * `resting_potential` - Optional new resting potential
7054    /// * `excitability` - Optional new excitability
7055    ///
7056    /// # Returns
7057    ///
7058    /// `Ok(())` if neuron updated successfully
7059    ///
7060    pub fn update_neuron_properties(
7061        &mut self,
7062        neuron_id: u64,
7063        firing_threshold: Option<f32>,
7064        leak_coefficient: Option<f32>,
7065        resting_potential: Option<f32>,
7066        excitability: Option<f32>,
7067    ) -> BduResult<()> {
7068        // Get NPU
7069        let npu = self
7070            .npu
7071            .as_ref()
7072            .ok_or_else(|| BduError::Internal("NPU not connected".to_string()))?;
7073
7074        let mut npu_lock = npu
7075            .lock()
7076            .map_err(|e| BduError::Internal(format!("Failed to lock NPU: {}", e)))?;
7077
7078        let neuron_id_u32 = neuron_id as u32;
7079
7080        // Verify neuron exists by trying to update at least one property
7081        let mut updated = false;
7082
7083        // Update properties if provided
7084        if let Some(threshold) = firing_threshold {
7085            if npu_lock.update_neuron_threshold(neuron_id_u32, threshold) {
7086                updated = true;
7087                debug!(target: "feagi-bdu","Updated neuron {} firing_threshold = {}", neuron_id, threshold);
7088            } else if !updated {
7089                return Err(BduError::InvalidNeuron(format!(
7090                    "Neuron {} not found",
7091                    neuron_id
7092                )));
7093            }
7094        }
7095
7096        if let Some(leak) = leak_coefficient {
7097            if npu_lock.update_neuron_leak(neuron_id_u32, leak) {
7098                updated = true;
7099                debug!(target: "feagi-bdu","Updated neuron {} leak_coefficient = {}", neuron_id, leak);
7100            } else if !updated {
7101                return Err(BduError::InvalidNeuron(format!(
7102                    "Neuron {} not found",
7103                    neuron_id
7104                )));
7105            }
7106        }
7107
7108        if let Some(resting) = resting_potential {
7109            if npu_lock.update_neuron_resting_potential(neuron_id_u32, resting) {
7110                updated = true;
7111                debug!(target: "feagi-bdu","Updated neuron {} resting_potential = {}", neuron_id, resting);
7112            } else if !updated {
7113                return Err(BduError::InvalidNeuron(format!(
7114                    "Neuron {} not found",
7115                    neuron_id
7116                )));
7117            }
7118        }
7119
7120        if let Some(excit) = excitability {
7121            if npu_lock.update_neuron_excitability(neuron_id_u32, excit) {
7122                updated = true;
7123                debug!(target: "feagi-bdu","Updated neuron {} excitability = {}", neuron_id, excit);
7124            } else if !updated {
7125                return Err(BduError::InvalidNeuron(format!(
7126                    "Neuron {} not found",
7127                    neuron_id
7128                )));
7129            }
7130        }
7131
7132        if !updated {
7133            return Err(BduError::Internal(
7134                "No properties provided for update".to_string(),
7135            ));
7136        }
7137
7138        info!(target: "feagi-bdu","Updated properties for neuron {}", neuron_id);
7139
7140        Ok(())
7141    }
7142
7143    /// Update the firing threshold of a specific neuron
7144    ///
7145    /// # Arguments
7146    ///
7147    /// * `neuron_id` - Target neuron ID
7148    /// * `new_threshold` - New firing threshold value
7149    ///
7150    /// # Returns
7151    ///
7152    /// `Ok(())` if threshold updated successfully
7153    ///
7154    pub fn set_neuron_firing_threshold(
7155        &mut self,
7156        neuron_id: u64,
7157        new_threshold: f32,
7158    ) -> BduResult<()> {
7159        // Get NPU
7160        let npu = self
7161            .npu
7162            .as_ref()
7163            .ok_or_else(|| BduError::Internal("NPU not connected".to_string()))?;
7164
7165        let mut npu_lock = npu
7166            .lock()
7167            .map_err(|e| BduError::Internal(format!("Failed to lock NPU: {}", e)))?;
7168
7169        // Update threshold via NPU
7170        if npu_lock.update_neuron_threshold(neuron_id as u32, new_threshold) {
7171            debug!(target: "feagi-bdu","Set neuron {} firing threshold = {}", neuron_id, new_threshold);
7172            Ok(())
7173        } else {
7174            Err(BduError::InvalidNeuron(format!(
7175                "Neuron {} not found",
7176                neuron_id
7177            )))
7178        }
7179    }
7180
7181    // ========================================================================
7182    // AREA MANAGEMENT & QUERIES
7183    // ========================================================================
7184
7185    /// Get cortical area by name (alternative to ID lookup)
7186    ///
7187    /// # Arguments
7188    ///
7189    /// * `name` - Human-readable area name
7190    ///
7191    /// # Returns
7192    ///
7193    /// `Some(CorticalArea)` if found, `None` otherwise
7194    ///
7195    pub fn get_cortical_area_by_name(&self, name: &str) -> Option<CorticalArea> {
7196        self.cortical_areas
7197            .values()
7198            .find(|area| area.name == name)
7199            .cloned()
7200    }
7201
7202    /// Resize a cortical area (changes dimensions, may require neuron reallocation)
7203    ///
7204    /// # Arguments
7205    ///
7206    /// * `cortical_id` - Target cortical area ID
7207    /// * `new_dimensions` - New dimensions (width, height, depth)
7208    ///
7209    /// # Returns
7210    ///
7211    /// `Ok(())` if resized successfully
7212    ///
7213    /// # Note
7214    ///
7215    /// This does NOT automatically create/delete neurons. It only updates metadata.
7216    /// Caller must handle neuron population separately.
7217    ///
7218    pub fn resize_cortical_area(
7219        &mut self,
7220        cortical_id: &CorticalID,
7221        new_dimensions: CorticalAreaDimensions,
7222    ) -> BduResult<()> {
7223        // Validate dimensions
7224        if new_dimensions.width == 0 || new_dimensions.height == 0 || new_dimensions.depth == 0 {
7225            return Err(BduError::InvalidArea(format!(
7226                "Invalid dimensions: {:?} (all must be > 0)",
7227                new_dimensions
7228            )));
7229        }
7230
7231        // Get and update area
7232        let area = self.cortical_areas.get_mut(cortical_id).ok_or_else(|| {
7233            BduError::InvalidArea(format!("Cortical area {} not found", cortical_id))
7234        })?;
7235
7236        let old_dimensions = area.dimensions;
7237        area.dimensions = new_dimensions;
7238
7239        // Note: Visualization voxel granularity is user-driven, not recalculated on resize
7240        // If user had set a custom value, it remains; otherwise defaults to 1x1x1
7241
7242        info!(target: "feagi-bdu",
7243            "Resized cortical area {} from {:?} to {:?}",
7244            cortical_id,
7245            old_dimensions,
7246            new_dimensions
7247        );
7248
7249        self.refresh_cortical_area_hashes(false, true);
7250
7251        Ok(())
7252    }
7253
7254    /// Get all cortical areas in a brain region
7255    ///
7256    /// # Arguments
7257    ///
7258    /// * `region_id` - Brain region ID
7259    ///
7260    /// # Returns
7261    ///
7262    /// Vector of cortical area IDs in the region
7263    ///
7264    pub fn get_areas_in_region(&self, region_id: &str) -> BduResult<Vec<String>> {
7265        let region = self.brain_regions.get_region(region_id).ok_or_else(|| {
7266            BduError::InvalidArea(format!("Brain region {} not found", region_id))
7267        })?;
7268
7269        // Convert CorticalID to base64 strings
7270        Ok(region
7271            .cortical_areas
7272            .iter()
7273            .map(|id| id.as_base_64())
7274            .collect())
7275    }
7276
7277    /// Update brain region properties
7278    ///
7279    /// # Arguments
7280    ///
7281    /// * `region_id` - Target region ID
7282    /// * `new_name` - Optional new name
7283    /// * `new_description` - Optional new description
7284    ///
7285    /// # Returns
7286    ///
7287    /// `Ok(())` if updated successfully
7288    ///
7289    pub fn update_brain_region(
7290        &mut self,
7291        region_id: &str,
7292        new_name: Option<String>,
7293        new_description: Option<String>,
7294    ) -> BduResult<()> {
7295        let region = self
7296            .brain_regions
7297            .get_region_mut(region_id)
7298            .ok_or_else(|| {
7299                BduError::InvalidArea(format!("Brain region {} not found", region_id))
7300            })?;
7301
7302        if let Some(name) = new_name {
7303            region.name = name;
7304            debug!(target: "feagi-bdu","Updated brain region {} name", region_id);
7305        }
7306
7307        if let Some(desc) = new_description {
7308            // BrainRegion doesn't have a description field in the struct, so we'll store it in properties
7309            region
7310                .properties
7311                .insert("description".to_string(), serde_json::json!(desc));
7312            debug!(target: "feagi-bdu","Updated brain region {} description", region_id);
7313        }
7314
7315        info!(target: "feagi-bdu","Updated brain region {}", region_id);
7316
7317        self.refresh_brain_regions_hash();
7318
7319        Ok(())
7320    }
7321
7322    /// Update brain region properties with generic property map
7323    ///
7324    /// Supports updating any brain region property including coordinates, title, description, etc.
7325    ///
7326    /// # Arguments
7327    ///
7328    /// * `region_id` - Target region ID
7329    /// * `properties` - Map of property names to new values
7330    ///
7331    /// # Returns
7332    ///
7333    /// `Ok(())` if updated successfully
7334    ///
7335    pub fn update_brain_region_properties(
7336        &mut self,
7337        region_id: &str,
7338        properties: std::collections::HashMap<String, serde_json::Value>,
7339    ) -> BduResult<Option<BrainRegionIoRegistry>> {
7340        use tracing::{debug, info};
7341
7342        let should_recompute_io = properties
7343            .contains_key(crate::region_io_designation::DESIGNATED_INPUTS_KEY)
7344            || properties.contains_key(crate::region_io_designation::DESIGNATED_OUTPUTS_KEY);
7345
7346        if properties.contains_key(crate::region_io_designation::DESIGNATED_INPUTS_KEY)
7347            || properties.contains_key(crate::region_io_designation::DESIGNATED_OUTPUTS_KEY)
7348        {
7349            let region_snapshot = self
7350                .brain_regions
7351                .get_region(region_id)
7352                .ok_or_else(|| {
7353                    BduError::InvalidArea(format!("Brain region {} not found", region_id))
7354                })?
7355                .clone();
7356            let (merged_in, merged_out) = crate::region_io_designation::merged_designated_lists(
7357                &region_snapshot,
7358                &properties,
7359            )?;
7360            crate::region_io_designation::validate_merged_designations_against_connectivity(
7361                self,
7362                &region_snapshot,
7363                &merged_in,
7364                &merged_out,
7365            )?;
7366        }
7367
7368        let region = self
7369            .brain_regions
7370            .get_region_mut(region_id)
7371            .ok_or_else(|| {
7372                BduError::InvalidArea(format!("Brain region {} not found", region_id))
7373            })?;
7374
7375        for (key, value) in properties {
7376            match key.as_str() {
7377                // BV (FEAGIRequests.edit_region_object) sends `region_title`; other clients use `title` / `name`.
7378                "title" | "name" | "region_title" => {
7379                    if let Some(name) = value.as_str() {
7380                        region.name = name.to_string();
7381                        debug!(target: "feagi-bdu", "Updated brain region {} name = {}", region_id, name);
7382                    }
7383                }
7384                "coordinate_3d" | "coordinates_3d" => {
7385                    region
7386                        .properties
7387                        .insert("coordinate_3d".to_string(), value.clone());
7388                    debug!(target: "feagi-bdu", "Updated brain region {} coordinate_3d = {:?}", region_id, value);
7389                }
7390                "coordinate_2d" | "coordinates_2d" => {
7391                    region
7392                        .properties
7393                        .insert("coordinate_2d".to_string(), value.clone());
7394                    debug!(target: "feagi-bdu", "Updated brain region {} coordinate_2d = {:?}", region_id, value);
7395                }
7396                "description" => {
7397                    region
7398                        .properties
7399                        .insert("description".to_string(), value.clone());
7400                    debug!(target: "feagi-bdu", "Updated brain region {} description", region_id);
7401                }
7402                "region_type" => {
7403                    if let Some(type_str) = value.as_str() {
7404                        // Note: RegionType is currently a placeholder (Undefined only)
7405                        // Specific region types will be added in the future
7406                        region.region_type = feagi_structures::genomic::RegionType::Undefined;
7407                        debug!(target: "feagi-bdu", "Updated brain region {} type = {}", region_id, type_str);
7408                    }
7409                }
7410                // Store any other properties in the properties map
7411                _ => {
7412                    region.properties.insert(key.clone(), value.clone());
7413                    debug!(target: "feagi-bdu", "Updated brain region {} property {} = {:?}", region_id, key, value);
7414                }
7415            }
7416        }
7417
7418        info!(target: "feagi-bdu", "Updated brain region {} properties", region_id);
7419
7420        // Designated IO affects merged inputs/outputs used by regions_members and BV plates; recompute
7421        // so connectivity-derived and declared lists stay merged in region.properties.
7422        if should_recompute_io {
7423            let registry = self.recompute_brain_region_io_registry()?;
7424            return Ok(Some(registry));
7425        }
7426
7427        // Keep StateManager health hashes in sync so clients (e.g. Brain Visualizer) detect changes via
7428        // brain_regions_hash on the next health poll. Without this, PUT /v1/region/region updates
7429        // (coordinates, title, etc.) do not bump the hash — same as update_brain_region for name/description.
7430        self.refresh_brain_regions_hash();
7431
7432        Ok(None)
7433    }
7434
7435    // ========================================================================
7436    // NEURON QUERY METHODS (P6)
7437    // ========================================================================
7438
7439    /// Get neuron by 3D coordinates within a cortical area
7440    ///
7441    /// # Arguments
7442    ///
7443    /// * `cortical_id` - Cortical area ID
7444    /// * `x` - X coordinate
7445    /// * `y` - Y coordinate
7446    /// * `z` - Z coordinate
7447    ///
7448    /// # Returns
7449    ///
7450    /// `Some(neuron_id)` if found, `None` otherwise
7451    ///
7452    pub fn get_neuron_by_coordinates(
7453        &self,
7454        cortical_id: &CorticalID,
7455        x: u32,
7456        y: u32,
7457        z: u32,
7458    ) -> Option<u64> {
7459        // Get cortical area to get its index
7460        let area = self.get_cortical_area(cortical_id)?;
7461        let cortical_idx = area.cortical_idx;
7462
7463        // Query NPU via public method
7464        let npu = self.npu.as_ref()?;
7465        let npu_lock = npu.lock().ok()?;
7466
7467        npu_lock
7468            .get_neuron_id_at_coordinate(cortical_idx, x, y, z)
7469            .map(|id| id as u64)
7470    }
7471
7472    /// Get the position (coordinates) of a neuron
7473    ///
7474    /// # Arguments
7475    ///
7476    /// * `neuron_id` - Neuron ID
7477    ///
7478    /// # Returns
7479    ///
7480    /// `Some((x, y, z))` if found, `None` otherwise
7481    ///
7482    pub fn get_neuron_position(&self, neuron_id: u64) -> Option<(u32, u32, u32)> {
7483        let npu = self.npu.as_ref()?;
7484        let npu_lock = npu.lock().ok()?;
7485
7486        // Verify neuron exists and get coordinates
7487        let neuron_count = npu_lock.get_neuron_count();
7488        if (neuron_id as usize) >= neuron_count {
7489            return None;
7490        }
7491
7492        Some(
7493            npu_lock
7494                .get_neuron_coordinates(neuron_id as u32)
7495                .unwrap_or((0, 0, 0)),
7496        )
7497    }
7498
7499    /// Get which cortical area contains a specific neuron
7500    ///
7501    /// # Arguments
7502    ///
7503    /// * `neuron_id` - Neuron ID
7504    ///
7505    /// # Returns
7506    ///
7507    /// `Some(cortical_id)` if found, `None` otherwise
7508    ///
7509    pub fn get_cortical_area_for_neuron(&self, neuron_id: u64) -> Option<CorticalID> {
7510        let npu = self.npu.as_ref()?;
7511        let npu_lock = npu.lock().ok()?;
7512
7513        // Verify neuron exists
7514        let neuron_count = npu_lock.get_neuron_count();
7515        if (neuron_id as usize) >= neuron_count {
7516            return None;
7517        }
7518
7519        let cortical_idx = npu_lock.get_neuron_cortical_area(neuron_id as u32)?;
7520
7521        // Look up cortical_id from index
7522        self.cortical_areas
7523            .values()
7524            .find(|area| area.cortical_idx == cortical_idx)
7525            .map(|area| area.cortical_id)
7526    }
7527
7528    /// Get all properties of a neuron
7529    ///
7530    /// # Arguments
7531    ///
7532    /// * `neuron_id` - Neuron ID
7533    ///
7534    /// # Returns
7535    ///
7536    /// `Some(properties)` if found, `None` otherwise
7537    ///
7538    pub fn get_neuron_properties(
7539        &self,
7540        neuron_id: u64,
7541    ) -> Option<std::collections::HashMap<String, serde_json::Value>> {
7542        let npu = self.npu.as_ref()?;
7543        let npu_lock = npu.lock().ok()?;
7544
7545        let neuron_id_u32 = neuron_id as u32;
7546        let idx = neuron_id as usize;
7547
7548        // Verify neuron exists
7549        let neuron_count = npu_lock.get_neuron_count();
7550        if idx >= neuron_count {
7551            return None;
7552        }
7553
7554        let mut properties = std::collections::HashMap::new();
7555
7556        // Basic info
7557        properties.insert("neuron_id".to_string(), serde_json::json!(neuron_id));
7558
7559        // Get coordinates
7560        let (x, y, z) = npu_lock.get_neuron_coordinates(neuron_id_u32)?;
7561        properties.insert("x".to_string(), serde_json::json!(x));
7562        properties.insert("y".to_string(), serde_json::json!(y));
7563        properties.insert("z".to_string(), serde_json::json!(z));
7564
7565        // Get cortical area
7566        let cortical_idx = npu_lock.get_neuron_cortical_area(neuron_id_u32)?;
7567        properties.insert("cortical_area".to_string(), serde_json::json!(cortical_idx));
7568
7569        // Per-neuron dynamics flags + cortical-level propagation flags (synaptic engine).
7570        properties.insert(
7571            "mp_charge_accumulation".to_string(),
7572            serde_json::json!(npu_lock.get_mp_charge_accumulation_at(idx).unwrap_or(false)),
7573        );
7574        properties.insert(
7575            "neuron_type".to_string(),
7576            serde_json::json!(npu_lock.get_neuron_type_at(idx).unwrap_or(0)),
7577        );
7578        let (mp_drv, psp_uni) = self
7579            .cortical_idx_to_id
7580            .get(&cortical_idx)
7581            .map(|cid| {
7582                (
7583                    npu_lock.get_mp_driven_psp_for_cortical(cid),
7584                    npu_lock.get_psp_uniform_distribution_for_cortical(cid),
7585                )
7586            })
7587            .unwrap_or((false, false));
7588        properties.insert("mp_driven_psp".to_string(), serde_json::json!(mp_drv));
7589        properties.insert(
7590            "psp_uniform_distribution".to_string(),
7591            serde_json::json!(psp_uni),
7592        );
7593
7594        // Neuron state: always expose the same keys (stable JSON for clients) even when
7595        // `get_neuron_state` is unavailable (e.g. invalid mask / edge indexing).
7596        let (consec_count, consec_limit, snooze, mp, threshold, refract_countdown) = npu_lock
7597            .get_neuron_state(NeuronId(neuron_id_u32))
7598            .unwrap_or((0u16, 0u16, 0u16, 0.0f32, 0.0f32, 0u16));
7599        properties.insert(
7600            "consecutive_fire_count".to_string(),
7601            serde_json::json!(consec_count),
7602        );
7603        properties.insert(
7604            "consecutive_fire_limit".to_string(),
7605            serde_json::json!(consec_limit),
7606        );
7607        properties.insert("snooze_period".to_string(), serde_json::json!(snooze));
7608        properties.insert("membrane_potential".to_string(), serde_json::json!(mp));
7609        properties.insert("threshold".to_string(), serde_json::json!(threshold));
7610        properties.insert(
7611            "refractory_countdown".to_string(),
7612            serde_json::json!(refract_countdown),
7613        );
7614
7615        // Scalar neuron parameters (stable keys; default when storage omits a value).
7616        properties.insert(
7617            "leak_coefficient".to_string(),
7618            serde_json::json!(npu_lock
7619                .get_neuron_property_by_index(idx, "leak_coefficient")
7620                .unwrap_or(0.0)),
7621        );
7622        properties.insert(
7623            "resting_potential".to_string(),
7624            serde_json::json!(npu_lock
7625                .get_neuron_property_by_index(idx, "resting_potential")
7626                .unwrap_or(0.0)),
7627        );
7628        properties.insert(
7629            "excitability".to_string(),
7630            serde_json::json!(npu_lock
7631                .get_neuron_property_by_index(idx, "excitability")
7632                .unwrap_or(0.0)),
7633        );
7634        properties.insert(
7635            "threshold_limit".to_string(),
7636            serde_json::json!(npu_lock
7637                .get_neuron_property_by_index(idx, "threshold_limit")
7638                .unwrap_or(0.0)),
7639        );
7640        properties.insert(
7641            "refractory_period".to_string(),
7642            serde_json::json!(npu_lock
7643                .get_neuron_property_u16_by_index(idx, "refractory_period")
7644                .unwrap_or(0)),
7645        );
7646
7647        Some(properties)
7648    }
7649
7650    /// Get a specific property of a neuron
7651    ///
7652    /// # Arguments
7653    ///
7654    /// * `neuron_id` - Neuron ID
7655    /// * `property_name` - Name of the property to retrieve
7656    ///
7657    /// # Returns
7658    ///
7659    /// `Some(value)` if found, `None` otherwise
7660    ///
7661    pub fn get_neuron_property(
7662        &self,
7663        neuron_id: u64,
7664        property_name: &str,
7665    ) -> Option<serde_json::Value> {
7666        self.get_neuron_properties(neuron_id)?
7667            .get(property_name)
7668            .cloned()
7669    }
7670
7671    // ========================================================================
7672    // CORTICAL AREA LIST/QUERY METHODS (P6)
7673    // ========================================================================
7674
7675    /// Get all cortical area IDs
7676    ///
7677    /// # Returns
7678    ///
7679    /// Vector of all cortical area IDs
7680    ///
7681    pub fn get_all_cortical_ids(&self) -> Vec<CorticalID> {
7682        self.cortical_areas.keys().copied().collect()
7683    }
7684
7685    /// Get all cortical area indices
7686    ///
7687    /// # Returns
7688    ///
7689    /// Vector of all cortical area indices
7690    ///
7691    pub fn get_all_cortical_indices(&self) -> Vec<u32> {
7692        self.cortical_areas
7693            .values()
7694            .map(|area| area.cortical_idx)
7695            .collect()
7696    }
7697
7698    /// Get all cortical area names
7699    ///
7700    /// # Returns
7701    ///
7702    /// Vector of all cortical area names
7703    ///
7704    pub fn get_cortical_area_names(&self) -> Vec<String> {
7705        self.cortical_areas
7706            .values()
7707            .map(|area| area.name.clone())
7708            .collect()
7709    }
7710
7711    /// List all input (IPU/sensory) cortical areas
7712    ///
7713    /// # Returns
7714    ///
7715    /// Vector of IPU/sensory area IDs
7716    ///
7717    pub fn list_ipu_areas(&self) -> Vec<CorticalID> {
7718        use crate::models::CorticalAreaExt;
7719        self.cortical_areas
7720            .values()
7721            .filter(|area| area.is_input_area())
7722            .map(|area| area.cortical_id)
7723            .collect()
7724    }
7725
7726    /// List all output (OPU/motor) cortical areas
7727    ///
7728    /// # Returns
7729    ///
7730    /// Vector of OPU/motor area IDs
7731    ///
7732    pub fn list_opu_areas(&self) -> Vec<CorticalID> {
7733        use crate::models::CorticalAreaExt;
7734        self.cortical_areas
7735            .values()
7736            .filter(|area| area.is_output_area())
7737            .map(|area| area.cortical_id)
7738            .collect()
7739    }
7740
7741    /// Get maximum dimensions across all cortical areas
7742    ///
7743    /// # Returns
7744    ///
7745    /// (max_width, max_height, max_depth)
7746    ///
7747    pub fn get_max_cortical_area_dimensions(&self) -> (usize, usize, usize) {
7748        self.cortical_areas
7749            .values()
7750            .fold((0, 0, 0), |(max_w, max_h, max_d), area| {
7751                (
7752                    max_w.max(area.dimensions.width as usize),
7753                    max_h.max(area.dimensions.height as usize),
7754                    max_d.max(area.dimensions.depth as usize),
7755                )
7756            })
7757    }
7758
7759    /// Get all properties of a cortical area as a JSON-serializable map
7760    ///
7761    /// # Arguments
7762    ///
7763    /// * `cortical_id` - Cortical area ID
7764    ///
7765    /// # Returns
7766    ///
7767    /// `Some(properties)` if found, `None` otherwise
7768    ///
7769    pub fn get_cortical_area_properties(
7770        &self,
7771        cortical_id: &CorticalID,
7772    ) -> Option<std::collections::HashMap<String, serde_json::Value>> {
7773        let area = self.get_cortical_area(cortical_id)?;
7774
7775        let mut properties = std::collections::HashMap::new();
7776        properties.insert(
7777            "cortical_id".to_string(),
7778            serde_json::json!(area.cortical_id),
7779        );
7780        properties.insert(
7781            "cortical_id_s".to_string(),
7782            serde_json::json!(area.cortical_id.to_string()),
7783        );
7784        properties.insert(
7785            "cortical_idx".to_string(),
7786            serde_json::json!(area.cortical_idx),
7787        );
7788        properties.insert("name".to_string(), serde_json::json!(area.name));
7789        use crate::models::CorticalAreaExt;
7790        properties.insert(
7791            "area_type".to_string(),
7792            serde_json::json!(area.get_cortical_group()),
7793        );
7794        properties.insert(
7795            "dimensions".to_string(),
7796            serde_json::json!({
7797                "width": area.dimensions.width,
7798                "height": area.dimensions.height,
7799                "depth": area.dimensions.depth,
7800            }),
7801        );
7802        properties.insert("position".to_string(), serde_json::json!(area.position));
7803
7804        // Copy all properties from area.properties to the response
7805        for (key, value) in &area.properties {
7806            properties.insert(key.clone(), value.clone());
7807        }
7808
7809        // Add custom properties
7810        properties.extend(area.properties.clone());
7811
7812        Some(properties)
7813    }
7814
7815    /// Get properties of all cortical areas
7816    ///
7817    /// # Returns
7818    ///
7819    /// Vector of property maps for all areas
7820    ///
7821    pub fn get_all_cortical_area_properties(
7822        &self,
7823    ) -> Vec<std::collections::HashMap<String, serde_json::Value>> {
7824        self.cortical_areas
7825            .keys()
7826            .filter_map(|id| self.get_cortical_area_properties(id))
7827            .collect()
7828    }
7829
7830    // ========================================================================
7831    // BRAIN REGION QUERY METHODS (P6)
7832    // ========================================================================
7833
7834    /// Get all brain region IDs
7835    ///
7836    /// # Returns
7837    ///
7838    /// Vector of all brain region IDs
7839    ///
7840    pub fn get_all_brain_region_ids(&self) -> Vec<String> {
7841        self.brain_regions
7842            .get_all_region_ids()
7843            .into_iter()
7844            .cloned()
7845            .collect()
7846    }
7847
7848    /// Get all brain region names
7849    ///
7850    /// # Returns
7851    ///
7852    /// Vector of all brain region names
7853    ///
7854    pub fn get_brain_region_names(&self) -> Vec<String> {
7855        self.brain_regions
7856            .get_all_region_ids()
7857            .iter()
7858            .filter_map(|id| {
7859                self.brain_regions
7860                    .get_region(id)
7861                    .map(|region| region.name.clone())
7862            })
7863            .collect()
7864    }
7865
7866    /// Get properties of a brain region
7867    ///
7868    /// # Arguments
7869    ///
7870    /// * `region_id` - Brain region ID
7871    ///
7872    /// # Returns
7873    ///
7874    /// `Some(properties)` if found, `None` otherwise
7875    ///
7876    pub fn get_brain_region_properties(
7877        &self,
7878        region_id: &str,
7879    ) -> Option<std::collections::HashMap<String, serde_json::Value>> {
7880        let region = self.brain_regions.get_region(region_id)?;
7881
7882        let mut properties = std::collections::HashMap::new();
7883        properties.insert("region_id".to_string(), serde_json::json!(region.region_id));
7884        properties.insert("name".to_string(), serde_json::json!(region.name));
7885        properties.insert(
7886            "region_type".to_string(),
7887            serde_json::json!(format!("{:?}", region.region_type)),
7888        );
7889        properties.insert(
7890            "cortical_areas".to_string(),
7891            serde_json::json!(region.cortical_areas.iter().collect::<Vec<_>>()),
7892        );
7893
7894        // Add custom properties
7895        properties.extend(region.properties.clone());
7896
7897        Some(properties)
7898    }
7899
7900    /// Check if a cortical area exists
7901    ///
7902    /// # Arguments
7903    ///
7904    /// * `cortical_id` - Cortical area ID to check
7905    ///
7906    /// # Returns
7907    ///
7908    /// `true` if area exists, `false` otherwise
7909    ///
7910    pub fn cortical_area_exists(&self, cortical_id: &CorticalID) -> bool {
7911        self.cortical_areas.contains_key(cortical_id)
7912    }
7913
7914    /// Check if a brain region exists
7915    ///
7916    /// # Arguments
7917    ///
7918    /// * `region_id` - Brain region ID to check
7919    ///
7920    /// # Returns
7921    ///
7922    /// `true` if region exists, `false` otherwise
7923    ///
7924    pub fn brain_region_exists(&self, region_id: &str) -> bool {
7925        self.brain_regions.get_region(region_id).is_some()
7926    }
7927
7928    /// Get the total number of brain regions
7929    ///
7930    /// # Returns
7931    ///
7932    /// Number of brain regions
7933    ///
7934    pub fn get_brain_region_count(&self) -> usize {
7935        self.brain_regions.region_count()
7936    }
7937
7938    /// Get neurons by cortical area (alias for get_neurons_in_area for API compatibility)
7939    ///
7940    /// # Arguments
7941    ///
7942    /// * `cortical_id` - Cortical area ID
7943    ///
7944    /// # Returns
7945    ///
7946    /// Vector of neuron IDs in the area
7947    ///
7948    pub fn get_neurons_by_cortical_area(&self, cortical_id: &CorticalID) -> Vec<u64> {
7949        // This is an alias for get_neurons_in_area, which already exists
7950        // Keeping it for Python API compatibility
7951        // Note: The signature says Vec<NeuronId> but implementation returns Vec<u64>
7952        self.get_neurons_in_area(cortical_id)
7953    }
7954}
7955
7956// Manual Debug implementation (RustNPU doesn't implement Debug)
7957impl std::fmt::Debug for ConnectomeManager {
7958    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7959        f.debug_struct("ConnectomeManager")
7960            .field("cortical_areas", &self.cortical_areas.len())
7961            .field("next_cortical_idx", &self.next_cortical_idx)
7962            .field("brain_regions", &self.brain_regions)
7963            .field(
7964                "npu",
7965                &if self.npu.is_some() {
7966                    "Connected"
7967                } else {
7968                    "Not connected"
7969                },
7970            )
7971            .field("initialized", &self.initialized)
7972            .finish()
7973    }
7974}
7975
7976#[cfg(test)]
7977mod tests {
7978    use super::*;
7979    use feagi_structures::genomic::cortical_area::CoreCorticalType;
7980
7981    /// Genome load renumbers every non-core cortical index, so any memory neuron left
7982    /// behind by the previous brain would keep an index that now resolves to an unrelated
7983    /// cortical area and would be written into the next exported connectome.
7984    #[cfg(feature = "plasticity")]
7985    #[test]
7986    fn prepare_for_new_genome_discards_memory_neurons_from_previous_brain() {
7987        use feagi_npu_burst_engine::{DynamicNPU, TracingMutex};
7988        use feagi_npu_plasticity::executor::PlasticityExecutor;
7989        use feagi_npu_plasticity::{
7990            create_memory_stats_cache, AsyncPlasticityExecutor, MemoryNeuronDetail,
7991            PlasticityConfig,
7992        };
7993        use feagi_npu_runtime::StdRuntime;
7994
7995        let npu = Arc::new(TracingMutex::new(
7996            DynamicNPU::new_f32(
7997                StdRuntime::new(),
7998                feagi_npu_burst_engine::backend::CPUBackend::new(),
7999                16,
8000                16,
8001                8,
8002            )
8003            .unwrap(),
8004            "prepare-for-new-genome-test-npu",
8005        ));
8006        let executor = Arc::new(std::sync::Mutex::new(AsyncPlasticityExecutor::new(
8007            PlasticityConfig::default(),
8008            create_memory_stats_cache(),
8009            npu.clone(),
8010        )));
8011
8012        let mut manager = ConnectomeManager::new_for_testing();
8013        manager.set_npu(npu);
8014        manager.set_plasticity_executor(executor.clone());
8015
8016        let previous_brain_memory_idx = 8;
8017        {
8018            let exec = executor.lock().expect("plasticity executor");
8019            PlasticityExecutor::register_memory_area(
8020                &*exec,
8021                previous_brain_memory_idx,
8022                "previous_brain_memory".to_string(),
8023                1,
8024                vec![7],
8025                None,
8026                false,
8027            );
8028            exec.restore_long_term_memory_neurons(&[MemoryNeuronDetail {
8029                neuron_id: 50_000_003,
8030                cortical_area_idx: previous_brain_memory_idx,
8031                pattern_hash: Some(9_631_261_403_772_054_764),
8032                is_longterm_memory: true,
8033                is_active: true,
8034                lifespan_current: 120,
8035                lifespan_initial: 20,
8036                lifespan_growth_rate: 3.0,
8037                creation_burst: 0,
8038                last_activation_burst: 0,
8039                activation_count: 5,
8040            }])
8041            .expect("seeded long-term memory neuron");
8042            assert_eq!(
8043                exec.export_long_term_memory_neurons()
8044                    .expect("plasticity service is initialized")
8045                    .len(),
8046                1
8047            );
8048        }
8049
8050        manager
8051            .prepare_for_new_genome()
8052            .expect("genome preparation must succeed");
8053
8054        let exec = executor.lock().expect("plasticity executor");
8055        assert!(
8056            exec.export_long_term_memory_neurons()
8057                .expect("plasticity service is initialized")
8058                .is_empty(),
8059            "memory neurons from the previous brain must not survive a genome load"
8060        );
8061        assert_eq!(
8062            exec.paginated_memory_neuron_ids_in_area(previous_brain_memory_idx, 0, 10),
8063            Some((Vec::new(), 0)),
8064            "the previous brain's memory area must no longer report any memory neurons"
8065        );
8066    }
8067
8068    #[test]
8069    fn test_singleton_instance() {
8070        let instance1 = ConnectomeManager::instance();
8071        let instance2 = ConnectomeManager::instance();
8072
8073        // Both should point to the same instance
8074        assert_eq!(Arc::strong_count(&instance1), Arc::strong_count(&instance2));
8075    }
8076
8077    #[test]
8078    fn test_add_cortical_area() {
8079        ConnectomeManager::reset_for_testing();
8080
8081        let instance = ConnectomeManager::instance();
8082        let mut manager = instance.write();
8083
8084        use feagi_structures::genomic::cortical_area::{
8085            CorticalAreaType, IOCorticalAreaConfigurationFlag,
8086        };
8087        let cortical_id = CorticalID::try_from_bytes(b"cst_add_").unwrap(); // Use unique custom ID
8088        let cortical_type = CorticalAreaType::BrainInput(IOCorticalAreaConfigurationFlag::Boolean);
8089        let area = CorticalArea::new(
8090            cortical_id,
8091            0,
8092            "Visual Input".to_string(),
8093            CorticalAreaDimensions::new(128, 128, 20).unwrap(),
8094            (0, 0, 0).into(),
8095            cortical_type,
8096        )
8097        .unwrap();
8098
8099        let initial_count = manager.get_cortical_area_count();
8100        let _cortical_idx = manager.add_cortical_area(area).unwrap();
8101
8102        assert_eq!(manager.get_cortical_area_count(), initial_count + 1);
8103        assert!(manager.has_cortical_area(&cortical_id));
8104        assert!(manager.is_initialized());
8105    }
8106
8107    #[test]
8108    fn refresh_all_connectome_hashes_publishes_mappings() {
8109        use feagi_structures::genomic::cortical_area::{
8110            CorticalArea, CorticalAreaDimensions, CorticalAreaType, CustomCorticalType,
8111        };
8112
8113        let src_id = CorticalID::try_from_bytes(b"chashsrc").unwrap();
8114        let dst_id = CorticalID::try_from_bytes(b"chashdst").unwrap();
8115        let mut src = CorticalArea::new(
8116            src_id,
8117            1,
8118            "src".to_string(),
8119            CorticalAreaDimensions::new(1, 1, 1).unwrap(),
8120            (0, 0, 0).into(),
8121            CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire),
8122        )
8123        .unwrap();
8124        src.properties.insert(
8125            "cortical_mapping_dst".to_string(),
8126            serde_json::json!({
8127                dst_id.as_base_64(): [{ "morphology_id": "projector" }]
8128            }),
8129        );
8130        let mut manager = ConnectomeManager::new_for_testing();
8131        manager.add_cortical_area(src).unwrap();
8132        manager.refresh_all_connectome_hashes();
8133        let mappings_hash = feagi_state_manager::StateManager::instance()
8134            .read()
8135            .get_cortical_mappings_hash();
8136        assert_ne!(
8137            mappings_hash, 0,
8138            "refresh_all_connectome_hashes must publish cortical_mappings_hash"
8139        );
8140    }
8141
8142    #[test]
8143    fn test_cortical_area_lookups() {
8144        ConnectomeManager::reset_for_testing();
8145
8146        let instance = ConnectomeManager::instance();
8147        let mut manager = instance.write();
8148
8149        use feagi_structures::genomic::cortical_area::{
8150            CorticalAreaType, IOCorticalAreaConfigurationFlag,
8151        };
8152        let cortical_id = CorticalID::try_from_bytes(b"cst_look").unwrap(); // Use unique custom ID
8153        let cortical_type = CorticalAreaType::BrainInput(IOCorticalAreaConfigurationFlag::Boolean);
8154        let area = CorticalArea::new(
8155            cortical_id,
8156            0,
8157            "Test Area".to_string(),
8158            CorticalAreaDimensions::new(10, 10, 10).unwrap(),
8159            (0, 0, 0).into(),
8160            cortical_type,
8161        )
8162        .unwrap();
8163
8164        let cortical_idx = manager.add_cortical_area(area).unwrap();
8165
8166        // ID -> idx lookup
8167        assert_eq!(manager.get_cortical_idx(&cortical_id), Some(cortical_idx));
8168
8169        // idx -> ID lookup
8170        assert_eq!(manager.get_cortical_id(cortical_idx), Some(&cortical_id));
8171
8172        // Get area
8173        let retrieved_area = manager.get_cortical_area(&cortical_id).unwrap();
8174        assert_eq!(retrieved_area.name, "Test Area");
8175    }
8176
8177    #[test]
8178    fn test_remove_cortical_area() {
8179        ConnectomeManager::reset_for_testing();
8180
8181        let instance = ConnectomeManager::instance();
8182        let mut manager = instance.write();
8183
8184        use feagi_structures::genomic::cortical_area::{
8185            CorticalAreaType, IOCorticalAreaConfigurationFlag,
8186        };
8187        let cortical_id = CoreCorticalType::Power.to_cortical_id();
8188
8189        // Remove area if it already exists from previous tests
8190        if manager.has_cortical_area(&cortical_id) {
8191            manager.remove_cortical_area(&cortical_id).unwrap();
8192        }
8193
8194        let cortical_type = CorticalAreaType::BrainInput(IOCorticalAreaConfigurationFlag::Boolean);
8195        let area = CorticalArea::new(
8196            cortical_id,
8197            0,
8198            "Test".to_string(),
8199            CorticalAreaDimensions::new(10, 10, 10).unwrap(),
8200            (0, 0, 0).into(),
8201            cortical_type,
8202        )
8203        .unwrap();
8204
8205        let initial_count = manager.get_cortical_area_count();
8206        manager.add_cortical_area(area).unwrap();
8207        assert_eq!(manager.get_cortical_area_count(), initial_count + 1);
8208
8209        let areas_hash_before = feagi_state_manager::StateManager::instance()
8210            .read()
8211            .get_cortical_areas_hash();
8212        let geometry_hash_before = feagi_state_manager::StateManager::instance()
8213            .read()
8214            .get_brain_geometry_hash();
8215
8216        manager.remove_cortical_area(&cortical_id).unwrap();
8217        assert_eq!(manager.get_cortical_area_count(), initial_count);
8218        assert!(!manager.has_cortical_area(&cortical_id));
8219
8220        let areas_hash_after = feagi_state_manager::StateManager::instance()
8221            .read()
8222            .get_cortical_areas_hash();
8223        let geometry_hash_after = feagi_state_manager::StateManager::instance()
8224            .read()
8225            .get_brain_geometry_hash();
8226        assert_ne!(
8227            areas_hash_before, areas_hash_after,
8228            "remove_cortical_area must publish a new cortical_areas_hash"
8229        );
8230        assert_ne!(
8231            geometry_hash_before, geometry_hash_after,
8232            "remove_cortical_area must publish a new brain_geometry_hash"
8233        );
8234    }
8235
8236    #[test]
8237    fn test_duplicate_area_error() {
8238        ConnectomeManager::reset_for_testing();
8239
8240        let instance = ConnectomeManager::instance();
8241        let mut manager = instance.write();
8242
8243        use feagi_structures::genomic::cortical_area::{
8244            CorticalAreaType, IOCorticalAreaConfigurationFlag,
8245        };
8246        // Use a unique ID only for this test to avoid collisions with other tests (e.g. Power)
8247        // when tests run in parallel; we still test duplicate by adding the same ID twice.
8248        let cortical_id = CorticalID::try_from_bytes(b"cst_dup1").unwrap();
8249        let cortical_type = CorticalAreaType::BrainInput(IOCorticalAreaConfigurationFlag::Boolean);
8250        let area1 = CorticalArea::new(
8251            cortical_id,
8252            0,
8253            "First".to_string(),
8254            CorticalAreaDimensions::new(10, 10, 10).unwrap(),
8255            (0, 0, 0).into(),
8256            cortical_type,
8257        )
8258        .unwrap();
8259
8260        let area2 = CorticalArea::new(
8261            cortical_id, // Same ID - duplicate
8262            1,
8263            "Second".to_string(),
8264            CorticalAreaDimensions::new(10, 10, 10).unwrap(),
8265            (0, 0, 0).into(),
8266            cortical_type,
8267        )
8268        .unwrap();
8269
8270        manager.add_cortical_area(area1).unwrap();
8271        let result = manager.add_cortical_area(area2);
8272
8273        assert!(result.is_err());
8274    }
8275
8276    #[test]
8277    fn test_brain_region_management() {
8278        ConnectomeManager::reset_for_testing();
8279
8280        let instance = ConnectomeManager::instance();
8281        let mut manager = instance.write();
8282
8283        let region_id = feagi_structures::genomic::brain_regions::RegionID::new();
8284        let region_id_str = region_id.to_string();
8285        let root = BrainRegion::new(
8286            region_id,
8287            "Root".to_string(),
8288            feagi_structures::genomic::brain_regions::RegionType::Undefined,
8289        )
8290        .unwrap();
8291
8292        let initial_count = manager.get_brain_region_ids().len();
8293        manager.add_brain_region(root, None).unwrap();
8294
8295        assert_eq!(manager.get_brain_region_ids().len(), initial_count + 1);
8296        assert!(manager.get_brain_region(&region_id_str).is_some());
8297    }
8298
8299    #[test]
8300    fn test_synapse_operations() {
8301        use feagi_npu_burst_engine::npu::RustNPU;
8302        use feagi_npu_burst_engine::TracingMutex;
8303        use std::sync::Arc;
8304
8305        // Create NPU and manager for isolated test state
8306        use feagi_npu_burst_engine::backend::CPUBackend;
8307        use feagi_npu_burst_engine::DynamicNPU;
8308        use feagi_npu_runtime::StdRuntime;
8309
8310        let runtime = StdRuntime;
8311        let backend = CPUBackend::new();
8312        let npu_result =
8313            RustNPU::new(runtime, backend, 100, 1000, 10).expect("Failed to create NPU");
8314        let npu = Arc::new(TracingMutex::new(DynamicNPU::F32(npu_result), "TestNPU"));
8315        let mut manager = ConnectomeManager::new_for_testing_with_npu(npu.clone());
8316
8317        // First create a cortical area to add neurons to
8318        use feagi_structures::genomic::cortical_area::{
8319            CorticalAreaType, IOCorticalAreaConfigurationFlag,
8320        };
8321        let cortical_id = CorticalID::try_from_bytes(b"cst_syn_").unwrap(); // Use unique custom ID
8322        let cortical_type = CorticalAreaType::BrainInput(IOCorticalAreaConfigurationFlag::Boolean);
8323        let area = CorticalArea::new(
8324            cortical_id,
8325            0, // cortical_idx
8326            "Test Area".to_string(),
8327            CorticalAreaDimensions::new(10, 10, 1).unwrap(),
8328            (0, 0, 0).into(), // position
8329            cortical_type,
8330        )
8331        .unwrap();
8332        let cortical_idx = manager.add_cortical_area(area).unwrap();
8333
8334        // Register the cortical area with the NPU using the cortical ID's base64 representation
8335        if let Some(npu_arc) = manager.get_npu() {
8336            if let Ok(mut npu_guard) = npu_arc.try_lock() {
8337                if let DynamicNPU::F32(ref mut npu) = *npu_guard {
8338                    npu.register_cortical_area(cortical_idx, cortical_id.as_base_64());
8339                }
8340            }
8341        }
8342
8343        // Create two neurons
8344        let neuron1_id = manager
8345            .add_neuron(
8346                &cortical_id,
8347                0,
8348                0,
8349                0,     // coordinates
8350                100.0, // firing_threshold
8351                0.0,   // firing_threshold_limit (0 = no limit)
8352                0.1,   // leak_coefficient
8353                -60.0, // resting_potential
8354                0,     // neuron_type
8355                2,     // refractory_period
8356                1.0,   // excitability
8357                5,     // consecutive_fire_limit
8358                10,    // snooze_length
8359                false, // mp_charge_accumulation
8360            )
8361            .unwrap();
8362
8363        let neuron2_id = manager
8364            .add_neuron(
8365                &cortical_id,
8366                1,
8367                0,
8368                0, // coordinates
8369                100.0,
8370                f32::MAX, // firing_threshold_limit (MAX = no limit, SIMD-friendly encoding)
8371                0.1,
8372                -60.0,
8373                0,
8374                2,
8375                1.0,
8376                5,
8377                10,
8378                false,
8379            )
8380            .unwrap();
8381
8382        // Test create_synapse (creation should succeed)
8383        manager
8384            .create_synapse(
8385                neuron1_id, neuron2_id, 128.0, // weight
8386                64.0,  // psp
8387                0,     // excitatory
8388            )
8389            .unwrap();
8390
8391        // Note: Synapse retrieval/update/removal tests require full NPU propagation engine initialization
8392        // which is beyond the scope of this unit test. The important part is that create_synapse succeeds.
8393        println!("✅ Synapse creation test passed");
8394    }
8395
8396    #[test]
8397    fn test_apply_cortical_mapping_missing_rules_is_ok() {
8398        // This guards against a regression where deleting a mapping causes a 500 because
8399        // synapse regeneration treats "no mapping rules" as an error.
8400        let mut manager = ConnectomeManager::new_for_testing();
8401
8402        use feagi_structures::genomic::cortical_area::{
8403            CorticalAreaType, IOCorticalAreaConfigurationFlag,
8404        };
8405
8406        let src_id = CorticalID::try_from_bytes(b"map_src_").unwrap();
8407        let dst_id = CorticalID::try_from_bytes(b"map_dst_").unwrap();
8408
8409        let src_area = CorticalArea::new(
8410            src_id,
8411            0,
8412            "src".to_string(),
8413            CorticalAreaDimensions::new(2, 2, 1).unwrap(),
8414            (0, 0, 0).into(),
8415            CorticalAreaType::BrainInput(IOCorticalAreaConfigurationFlag::Boolean),
8416        )
8417        .unwrap();
8418
8419        let dst_area = CorticalArea::new(
8420            dst_id,
8421            1,
8422            "dst".to_string(),
8423            CorticalAreaDimensions::new(2, 2, 1).unwrap(),
8424            (0, 0, 0).into(),
8425            CorticalAreaType::BrainOutput(IOCorticalAreaConfigurationFlag::Boolean),
8426        )
8427        .unwrap();
8428
8429        manager.add_cortical_area(src_area).unwrap();
8430        manager.add_cortical_area(dst_area).unwrap();
8431
8432        // No cortical_mapping_dst property set -> should be Ok(0), not an error
8433        let count = manager
8434            .apply_cortical_mapping_for_pair(&src_id, &dst_id)
8435            .unwrap();
8436        assert_eq!(count, 0);
8437
8438        // Now create then delete mapping; missing destination rules should still be Ok(0)
8439        manager
8440            .update_cortical_mapping(
8441                &src_id,
8442                &dst_id,
8443                vec![serde_json::json!({"morphology_id":"m1"})],
8444            )
8445            .unwrap();
8446        manager
8447            .update_cortical_mapping(&src_id, &dst_id, vec![])
8448            .unwrap();
8449
8450        let count2 = manager
8451            .apply_cortical_mapping_for_pair(&src_id, &dst_id)
8452            .unwrap();
8453        assert_eq!(count2, 0);
8454    }
8455
8456    #[test]
8457    fn test_get_mapping_rules_for_destination_supports_legacy_key() {
8458        let dst_id = CorticalID::try_from_bytes(b"csrc0002").unwrap();
8459        let mapping_dst = serde_json::json!({
8460            "csrc0002": [
8461                {"morphology_id": "m1"}
8462            ]
8463        });
8464        let mapping_obj = mapping_dst.as_object().expect("mapping must be an object");
8465
8466        let rules = ConnectomeManager::get_mapping_rules_for_destination(mapping_obj, &dst_id)
8467            .expect("legacy destination key should resolve");
8468        assert_eq!(rules.len(), 1);
8469        assert_eq!(
8470            rules[0].get("morphology_id").and_then(|v| v.as_str()),
8471            Some("m1")
8472        );
8473    }
8474
8475    #[test]
8476    fn test_get_neuron_properties_always_includes_neuron_state_keys() {
8477        use feagi_npu_burst_engine::backend::CPUBackend;
8478        use feagi_npu_burst_engine::RustNPU;
8479        use feagi_npu_burst_engine::TracingMutex;
8480        use feagi_npu_runtime::StdRuntime;
8481        use feagi_structures::genomic::cortical_area::{
8482            CorticalAreaDimensions, CorticalAreaType, IOCorticalAreaConfigurationFlag,
8483        };
8484        use std::sync::Arc;
8485
8486        let runtime = StdRuntime;
8487        let backend = CPUBackend::new();
8488        let npu = RustNPU::new(runtime, backend, 10_000, 10_000, 10).expect("Failed to create NPU");
8489        let dyn_npu = Arc::new(TracingMutex::new(
8490            feagi_npu_burst_engine::DynamicNPU::F32(npu),
8491            "TestNPU",
8492        ));
8493        let mut manager = ConnectomeManager::new_for_testing_with_npu(dyn_npu.clone());
8494
8495        let area_id = CorticalID::try_from_bytes(b"cst_nsp_").unwrap();
8496        let area = CorticalArea::new(
8497            area_id,
8498            0,
8499            "n".to_string(),
8500            CorticalAreaDimensions::new(2, 2, 1).unwrap(),
8501            (0, 0, 0).into(),
8502            CorticalAreaType::BrainInput(IOCorticalAreaConfigurationFlag::Boolean),
8503        )
8504        .unwrap();
8505
8506        manager.add_cortical_area(area).unwrap();
8507        let nid = manager
8508            .add_neuron(
8509                &area_id, 0, 0, 0, 1.0, 0.0, 0.1, 0.0, 0, 1, 1.0, 3, 1, false,
8510            )
8511            .unwrap();
8512
8513        let props = manager
8514            .get_neuron_properties(nid)
8515            .expect("neuron properties");
8516        for key in [
8517            "consecutive_fire_count",
8518            "consecutive_fire_limit",
8519            "snooze_period",
8520            "membrane_potential",
8521            "threshold",
8522            "refractory_countdown",
8523            "mp_charge_accumulation",
8524            "neuron_type",
8525            "mp_driven_psp",
8526            "psp_uniform_distribution",
8527            "leak_coefficient",
8528            "resting_potential",
8529            "excitability",
8530            "threshold_limit",
8531            "refractory_period",
8532        ] {
8533            assert!(props.contains_key(key), "missing neuron state key: {key}");
8534        }
8535    }
8536
8537    #[test]
8538    fn test_mapping_deletion_prunes_synapses_between_areas() {
8539        use feagi_npu_burst_engine::backend::CPUBackend;
8540        use feagi_npu_burst_engine::RustNPU;
8541        use feagi_npu_burst_engine::TracingMutex;
8542        use feagi_npu_runtime::StdRuntime;
8543        use feagi_structures::genomic::cortical_area::{
8544            CorticalAreaDimensions, CorticalAreaType, IOCorticalAreaConfigurationFlag,
8545        };
8546        use std::sync::Arc;
8547
8548        // Create NPU and manager (small capacities for a deterministic unit test)
8549        let runtime = StdRuntime;
8550        let backend = CPUBackend::new();
8551        let npu = RustNPU::new(runtime, backend, 10_000, 10_000, 10).expect("Failed to create NPU");
8552        let dyn_npu = Arc::new(TracingMutex::new(
8553            feagi_npu_burst_engine::DynamicNPU::F32(npu),
8554            "TestNPU",
8555        ));
8556        let mut manager = ConnectomeManager::new_for_testing_with_npu(dyn_npu.clone());
8557
8558        // Create two cortical areas
8559        let src_id = CorticalID::try_from_bytes(b"cst_src_").unwrap();
8560        let dst_id = CorticalID::try_from_bytes(b"cst_dst_").unwrap();
8561
8562        let src_area = CorticalArea::new(
8563            src_id,
8564            0,
8565            "src".to_string(),
8566            CorticalAreaDimensions::new(2, 2, 1).unwrap(),
8567            (0, 0, 0).into(),
8568            CorticalAreaType::BrainInput(IOCorticalAreaConfigurationFlag::Boolean),
8569        )
8570        .unwrap();
8571        let dst_area = CorticalArea::new(
8572            dst_id,
8573            1,
8574            "dst".to_string(),
8575            CorticalAreaDimensions::new(2, 2, 1).unwrap(),
8576            (0, 0, 0).into(),
8577            CorticalAreaType::BrainOutput(IOCorticalAreaConfigurationFlag::Boolean),
8578        )
8579        .unwrap();
8580
8581        manager.add_cortical_area(src_area).unwrap();
8582        manager.add_cortical_area(dst_area).unwrap();
8583
8584        // Add a couple neurons to each area
8585        let s0 = manager
8586            .add_neuron(&src_id, 0, 0, 0, 1.0, 0.0, 0.1, 0.0, 0, 1, 1.0, 3, 1, false)
8587            .unwrap();
8588        let s1 = manager
8589            .add_neuron(&src_id, 1, 0, 0, 1.0, 0.0, 0.1, 0.0, 0, 1, 1.0, 3, 1, false)
8590            .unwrap();
8591        let t0 = manager
8592            .add_neuron(&dst_id, 0, 0, 0, 1.0, 0.0, 0.1, 0.0, 0, 1, 1.0, 3, 1, false)
8593            .unwrap();
8594        let t1 = manager
8595            .add_neuron(&dst_id, 1, 0, 0, 1.0, 0.0, 0.1, 0.0, 0, 1, 1.0, 3, 1, false)
8596            .unwrap();
8597
8598        // Create synapses that represent an established mapping between the two areas
8599        manager.create_synapse(s0, t0, 128.0, 200.0, 0).unwrap();
8600        manager.create_synapse(s1, t1, 128.0, 200.0, 0).unwrap();
8601
8602        // Build index once before pruning
8603        {
8604            let mut npu = dyn_npu.lock().unwrap();
8605            npu.rebuild_synapse_index();
8606            assert_eq!(npu.get_synapse_count(), 2);
8607        }
8608
8609        // Simulate mapping deletion and regeneration: should prune synapses and not re-add any
8610        manager
8611            .update_cortical_mapping(&src_id, &dst_id, vec![])
8612            .unwrap();
8613        let created = manager
8614            .regenerate_synapses_for_mapping(&src_id, &dst_id)
8615            .unwrap();
8616        assert_eq!(created, 0);
8617
8618        // Verify synapses are gone (invalidated) and no outgoing synapses remain from the sources
8619        {
8620            let mut npu = dyn_npu.lock().unwrap();
8621            // Pruning invalidates synapses; rebuild the index so counts/outgoing queries reflect the current state.
8622            npu.rebuild_synapse_index();
8623            assert_eq!(npu.get_synapse_count(), 0);
8624            assert!(npu.get_outgoing_synapses(s0 as u32).is_empty());
8625            assert!(npu.get_outgoing_synapses(s1 as u32).is_empty());
8626        }
8627    }
8628
8629    #[test]
8630    fn test_mapping_update_prunes_synapses_between_areas() {
8631        use feagi_npu_burst_engine::backend::CPUBackend;
8632        use feagi_npu_burst_engine::RustNPU;
8633        use feagi_npu_burst_engine::TracingMutex;
8634        use feagi_npu_runtime::StdRuntime;
8635        use feagi_structures::genomic::cortical_area::{
8636            CorticalAreaDimensions, CorticalAreaType, IOCorticalAreaConfigurationFlag,
8637        };
8638        use std::sync::Arc;
8639
8640        // Create NPU and manager (small capacities for a deterministic unit test)
8641        let runtime = StdRuntime;
8642        let backend = CPUBackend::new();
8643        let npu = RustNPU::new(runtime, backend, 10_000, 10_000, 10).expect("Failed to create NPU");
8644        let dyn_npu = Arc::new(TracingMutex::new(
8645            feagi_npu_burst_engine::DynamicNPU::F32(npu),
8646            "TestNPU",
8647        ));
8648        let mut manager = ConnectomeManager::new_for_testing_with_npu(dyn_npu.clone());
8649
8650        // Seed core morphologies so mapping regeneration can resolve function morphologies (e.g. "episodic_memory").
8651        feagi_evolutionary::templates::add_core_morphologies(&mut manager.morphology_registry);
8652
8653        // Create two cortical areas
8654        // Use valid custom cortical IDs (the `cst...` namespace).
8655        let src_id = CorticalID::try_from_bytes(b"cstupds1").unwrap();
8656        let dst_id = CorticalID::try_from_bytes(b"cstupdt1").unwrap();
8657
8658        let src_area = CorticalArea::new(
8659            src_id,
8660            0,
8661            "src".to_string(),
8662            CorticalAreaDimensions::new(2, 2, 1).unwrap(),
8663            (0, 0, 0).into(),
8664            CorticalAreaType::BrainInput(IOCorticalAreaConfigurationFlag::Boolean),
8665        )
8666        .unwrap();
8667        let dst_area = CorticalArea::new(
8668            dst_id,
8669            0,
8670            "dst".to_string(),
8671            CorticalAreaDimensions::new(2, 2, 1).unwrap(),
8672            (0, 0, 0).into(),
8673            CorticalAreaType::BrainOutput(IOCorticalAreaConfigurationFlag::Boolean),
8674        )
8675        .unwrap();
8676
8677        manager.add_cortical_area(src_area).unwrap();
8678        manager.add_cortical_area(dst_area).unwrap();
8679
8680        // Add a couple neurons to each area
8681        let s0 = manager
8682            .add_neuron(&src_id, 0, 0, 0, 1.0, 0.0, 0.1, 0.0, 0, 1, 1.0, 3, 1, false)
8683            .unwrap();
8684        let s1 = manager
8685            .add_neuron(&src_id, 1, 0, 0, 1.0, 0.0, 0.1, 0.0, 0, 1, 1.0, 3, 1, false)
8686            .unwrap();
8687        let t0 = manager
8688            .add_neuron(&dst_id, 0, 0, 0, 1.0, 0.0, 0.1, 0.0, 0, 1, 1.0, 3, 1, false)
8689            .unwrap();
8690        let t1 = manager
8691            .add_neuron(&dst_id, 1, 0, 0, 1.0, 0.0, 0.1, 0.0, 0, 1, 1.0, 3, 1, false)
8692            .unwrap();
8693
8694        // Create synapses that represent an established mapping between the two areas
8695        manager.create_synapse(s0, t0, 128.0, 200.0, 0).unwrap();
8696        manager.create_synapse(s1, t1, 128.0, 200.0, 0).unwrap();
8697
8698        // Build index once before pruning
8699        {
8700            let mut npu = dyn_npu.lock().unwrap();
8701            npu.rebuild_synapse_index();
8702            assert_eq!(npu.get_synapse_count(), 2);
8703        }
8704
8705        // Update mapping rules (non-empty) and regenerate.
8706        // This should prune the existing A→B synapses before re-applying the mapping.
8707        //
8708        // Use "episodic_memory" morphology to avoid creating physical synapses; the key assertion is that
8709        // the pre-existing synapses were pruned on update.
8710        manager
8711            .update_cortical_mapping(
8712                &src_id,
8713                &dst_id,
8714                vec![serde_json::json!({
8715                    "morphology_id": "episodic_memory",
8716                    "morphology_scalar": [1],
8717                    "postSynapticCurrent_multiplier": 1,
8718                    "plasticity_flag": false,
8719                    "plasticity_constant": 0,
8720                    "ltp_multiplier": 0,
8721                    "ltd_multiplier": 0,
8722                    "plasticity_window": 0,
8723                })],
8724            )
8725            .unwrap();
8726        let created = manager
8727            .regenerate_synapses_for_mapping(&src_id, &dst_id)
8728            .unwrap();
8729        assert_eq!(created, 0);
8730
8731        // Verify synapses are gone and no outgoing synapses remain from the sources
8732        {
8733            let mut npu = dyn_npu.lock().unwrap();
8734            // Pruning invalidates synapses; rebuild the index so counts/outgoing queries reflect the current state.
8735            npu.rebuild_synapse_index();
8736            assert_eq!(npu.get_synapse_count(), 0);
8737            assert!(npu.get_outgoing_synapses(s0 as u32).is_empty());
8738            assert!(npu.get_outgoing_synapses(s1 as u32).is_empty());
8739        }
8740    }
8741
8742    #[test]
8743    fn test_upstream_area_tracking() {
8744        // Test that upstream_cortical_areas property is maintained correctly
8745        use crate::models::cortical_area::CorticalArea;
8746        use feagi_npu_burst_engine::backend::CPUBackend;
8747        use feagi_npu_burst_engine::TracingMutex;
8748        use feagi_npu_burst_engine::{DynamicNPU, RustNPU};
8749        use feagi_npu_runtime::StdRuntime;
8750        use feagi_structures::genomic::cortical_area::{
8751            CorticalAreaDimensions, CorticalAreaType, CorticalID,
8752        };
8753
8754        // Create test manager with NPU
8755        let runtime = StdRuntime;
8756        let backend = CPUBackend::new();
8757        let npu = RustNPU::new(runtime, backend, 10_000, 10_000, 10).expect("Failed to create NPU");
8758        let dyn_npu = Arc::new(TracingMutex::new(DynamicNPU::F32(npu), "TestNPU"));
8759        let mut manager = ConnectomeManager::new_for_testing_with_npu(dyn_npu.clone());
8760
8761        // Seed the morphology registry with core morphologies so mapping regeneration can run.
8762        // (new_for_testing_with_npu() intentionally starts empty.)
8763        feagi_evolutionary::templates::add_core_morphologies(&mut manager.morphology_registry);
8764
8765        // Create source area
8766        let src_id = CorticalID::try_from_bytes(b"csrc0000").unwrap();
8767        let src_area = CorticalArea::new(
8768            src_id,
8769            0,
8770            "Source Area".to_string(),
8771            CorticalAreaDimensions::new(2, 2, 1).unwrap(),
8772            (0, 0, 0).into(),
8773            CorticalAreaType::Custom(
8774                feagi_structures::genomic::cortical_area::CustomCorticalType::LeakyIntegrateFire,
8775            ),
8776        )
8777        .unwrap();
8778        let src_idx = manager.add_cortical_area(src_area).unwrap();
8779
8780        // Create destination area (memory area)
8781        let dst_id = CorticalID::try_from_bytes(b"cdst0000").unwrap();
8782        let dst_area = CorticalArea::new(
8783            dst_id,
8784            0,
8785            "Dest Area".to_string(),
8786            CorticalAreaDimensions::new(2, 2, 1).unwrap(),
8787            (0, 0, 0).into(),
8788            CorticalAreaType::Custom(
8789                feagi_structures::genomic::cortical_area::CustomCorticalType::LeakyIntegrateFire,
8790            ),
8791        )
8792        .unwrap();
8793        manager.add_cortical_area(dst_area).unwrap();
8794
8795        // Verify upstream_cortical_areas property was initialized to empty array
8796        {
8797            let dst_area = manager.get_cortical_area(&dst_id).unwrap();
8798            let upstream = dst_area.properties.get("upstream_cortical_areas").unwrap();
8799            assert!(
8800                upstream.as_array().unwrap().is_empty(),
8801                "Upstream areas should be empty initially"
8802            );
8803        }
8804
8805        // Create a mapping from src to dst
8806        let mapping_data = vec![serde_json::json!({
8807            "morphology_id": "episodic_memory",
8808            "morphology_scalar": 1,
8809            "postSynapticCurrent_multiplier": 1.0,
8810        })];
8811        manager
8812            .update_cortical_mapping(&src_id, &dst_id, mapping_data)
8813            .unwrap();
8814        manager
8815            .regenerate_synapses_for_mapping(&src_id, &dst_id)
8816            .unwrap();
8817
8818        // Verify src_idx was added to dst's upstream_cortical_areas
8819        {
8820            let upstream_areas = manager.get_upstream_cortical_areas(&dst_id);
8821            assert_eq!(upstream_areas.len(), 1, "Should have 1 upstream area");
8822            assert_eq!(
8823                upstream_areas[0], src_idx,
8824                "Upstream area should be src_idx"
8825            );
8826        }
8827
8828        // Delete the mapping
8829        manager
8830            .update_cortical_mapping(&src_id, &dst_id, vec![])
8831            .unwrap();
8832        manager
8833            .regenerate_synapses_for_mapping(&src_id, &dst_id)
8834            .unwrap();
8835
8836        // Verify src_idx was removed from dst's upstream_cortical_areas
8837        {
8838            let upstream_areas = manager.get_upstream_cortical_areas(&dst_id);
8839            assert_eq!(
8840                upstream_areas.len(),
8841                0,
8842                "Should have 0 upstream areas after deletion"
8843            );
8844        }
8845    }
8846
8847    #[test]
8848    fn test_refresh_upstream_areas_for_associative_memory_pairs() {
8849        use crate::models::cortical_area::CorticalArea;
8850        use feagi_npu_burst_engine::backend::CPUBackend;
8851        use feagi_npu_burst_engine::TracingMutex;
8852        use feagi_npu_burst_engine::{DynamicNPU, RustNPU};
8853        use feagi_npu_runtime::StdRuntime;
8854        use feagi_structures::genomic::cortical_area::{
8855            CorticalAreaDimensions, CorticalAreaType, CorticalID, MemoryCorticalType,
8856        };
8857        use std::sync::Arc;
8858
8859        let runtime = StdRuntime;
8860        let backend = CPUBackend::new();
8861        let npu = RustNPU::new(runtime, backend, 10_000, 10_000, 10).expect("Failed to create NPU");
8862        let dyn_npu = Arc::new(TracingMutex::new(DynamicNPU::F32(npu), "TestNPU"));
8863        let mut manager = ConnectomeManager::new_for_testing_with_npu(dyn_npu.clone());
8864        feagi_evolutionary::templates::add_core_morphologies(&mut manager.morphology_registry);
8865
8866        let a1_id = CorticalID::try_from_bytes(b"csrc0002").unwrap();
8867        let a2_id = CorticalID::try_from_bytes(b"csrc0003").unwrap();
8868        let m1_id = CorticalID::try_from_bytes(b"mmem0002").unwrap();
8869        let m2_id = CorticalID::try_from_bytes(b"mmem0003").unwrap();
8870
8871        let a1_area = CorticalArea::new(
8872            a1_id,
8873            0,
8874            "A1".to_string(),
8875            CorticalAreaDimensions::new(1, 1, 1).unwrap(),
8876            (0, 0, 0).into(),
8877            CorticalAreaType::Custom(
8878                feagi_structures::genomic::cortical_area::CustomCorticalType::LeakyIntegrateFire,
8879            ),
8880        )
8881        .unwrap();
8882        let a2_area = CorticalArea::new(
8883            a2_id,
8884            0,
8885            "A2".to_string(),
8886            CorticalAreaDimensions::new(1, 1, 1).unwrap(),
8887            (0, 0, 0).into(),
8888            CorticalAreaType::Custom(
8889                feagi_structures::genomic::cortical_area::CustomCorticalType::LeakyIntegrateFire,
8890            ),
8891        )
8892        .unwrap();
8893
8894        let mut m1_area = CorticalArea::new(
8895            m1_id,
8896            0,
8897            "M1".to_string(),
8898            CorticalAreaDimensions::new(1, 1, 1).unwrap(),
8899            (0, 0, 0).into(),
8900            CorticalAreaType::Memory(MemoryCorticalType::Memory),
8901        )
8902        .unwrap();
8903        m1_area
8904            .properties
8905            .insert("is_mem_type".to_string(), serde_json::json!(true));
8906        m1_area
8907            .properties
8908            .insert("temporal_depth".to_string(), serde_json::json!(1));
8909
8910        let mut m2_area = CorticalArea::new(
8911            m2_id,
8912            0,
8913            "M2".to_string(),
8914            CorticalAreaDimensions::new(1, 1, 1).unwrap(),
8915            (0, 0, 0).into(),
8916            CorticalAreaType::Memory(MemoryCorticalType::Memory),
8917        )
8918        .unwrap();
8919        m2_area
8920            .properties
8921            .insert("is_mem_type".to_string(), serde_json::json!(true));
8922        m2_area
8923            .properties
8924            .insert("temporal_depth".to_string(), serde_json::json!(1));
8925
8926        let a1_idx = manager.add_cortical_area(a1_area).unwrap();
8927        let a2_idx = manager.add_cortical_area(a2_area).unwrap();
8928        let m1_idx = manager.add_cortical_area(m1_area).unwrap();
8929        let m2_idx = manager.add_cortical_area(m2_area).unwrap();
8930
8931        manager
8932            .add_neuron(&a1_id, 0, 0, 0, 1.0, 0.0, 0.1, 0.0, 0, 1, 1.0, 3, 1, false)
8933            .unwrap();
8934        manager
8935            .add_neuron(&a2_id, 0, 0, 0, 1.0, 0.0, 0.1, 0.0, 0, 1, 1.0, 3, 1, false)
8936            .unwrap();
8937
8938        let episodic_mapping = vec![serde_json::json!({
8939            "morphology_id": "episodic_memory",
8940            "morphology_scalar": 1,
8941            "postSynapticCurrent_multiplier": 1.0,
8942        })];
8943        manager
8944            .update_cortical_mapping(&a1_id, &m1_id, episodic_mapping.clone())
8945            .unwrap();
8946        manager
8947            .regenerate_synapses_for_mapping(&a1_id, &m1_id)
8948            .unwrap();
8949        manager
8950            .update_cortical_mapping(&a2_id, &m2_id, episodic_mapping)
8951            .unwrap();
8952        manager
8953            .regenerate_synapses_for_mapping(&a2_id, &m2_id)
8954            .unwrap();
8955
8956        let assoc_mapping = vec![serde_json::json!({
8957            "morphology_id": "associative_memory",
8958            "morphology_scalar": 1,
8959            "postSynapticCurrent_multiplier": 1.0,
8960            "plasticity_flag": true,
8961            "plasticity_constant": 1,
8962            "ltp_multiplier": 1,
8963            "ltd_multiplier": 1,
8964            "plasticity_window": 5,
8965        })];
8966        manager
8967            .update_cortical_mapping(&m1_id, &m2_id, assoc_mapping.clone())
8968            .unwrap();
8969        manager
8970            .regenerate_synapses_for_mapping(&m1_id, &m2_id)
8971            .unwrap();
8972        // Second directed edge (bidirectional link is two explicit mappings, not auto-mirror).
8973        manager
8974            .update_cortical_mapping(&m2_id, &m1_id, assoc_mapping)
8975            .unwrap();
8976        manager
8977            .regenerate_synapses_for_mapping(&m2_id, &m1_id)
8978            .unwrap();
8979
8980        let upstream_m1 = manager.get_upstream_cortical_areas(&m1_id);
8981        let upstream_m2 = manager.get_upstream_cortical_areas(&m2_id);
8982        assert_eq!(
8983            upstream_m1.len(),
8984            2,
8985            "M1 should have A1 and M2 as upstreams once both directed associative edges exist"
8986        );
8987        assert_eq!(
8988            upstream_m2.len(),
8989            2,
8990            "M2 should have A2 and M1 as upstreams"
8991        );
8992
8993        manager.refresh_upstream_cortical_areas_from_mappings(&m1_id);
8994        manager.refresh_upstream_cortical_areas_from_mappings(&m2_id);
8995
8996        let upstream_m1 = manager.get_upstream_cortical_areas(&m1_id);
8997        let upstream_m2 = manager.get_upstream_cortical_areas(&m2_id);
8998        assert_eq!(upstream_m1.len(), 2, "M1 upstreams unchanged after refresh");
8999        assert_eq!(upstream_m2.len(), 2, "M2 upstreams unchanged after refresh");
9000        assert!(upstream_m1.contains(&a1_idx));
9001        assert!(upstream_m1.contains(&m2_idx));
9002        assert!(upstream_m2.contains(&a2_idx));
9003        assert!(upstream_m2.contains(&m1_idx));
9004
9005        // Fire upstream neurons and ensure burst processing works without altering upstream tracking.
9006        {
9007            let mut npu_lock = dyn_npu.lock().unwrap();
9008            let injected_a1 = npu_lock.inject_sensory_xyzp_by_id(&a1_id, &[(0, 0, 0, 1.0)]);
9009            let injected_a2 = npu_lock.inject_sensory_xyzp_by_id(&a2_id, &[(0, 0, 0, 1.0)]);
9010            assert_eq!(injected_a1, 1, "Expected A1 injection to match one neuron");
9011            assert_eq!(injected_a2, 1, "Expected A2 injection to match one neuron");
9012            npu_lock.process_burst().expect("Burst processing failed");
9013        }
9014
9015        let upstream_m1 = manager.get_upstream_cortical_areas(&m1_id);
9016        let upstream_m2 = manager.get_upstream_cortical_areas(&m2_id);
9017        assert_eq!(
9018            upstream_m1.len(),
9019            2,
9020            "M1 should keep 2 upstreams after firing"
9021        );
9022        assert_eq!(
9023            upstream_m2.len(),
9024            2,
9025            "M2 should keep 2 upstreams after firing"
9026        );
9027
9028        let episodic_upstream_m1 = manager.get_episodic_memory_upstream_cortical_areas(&m1_id);
9029        let episodic_upstream_m2 = manager.get_episodic_memory_upstream_cortical_areas(&m2_id);
9030        assert_eq!(
9031            episodic_upstream_m1,
9032            vec![a1_idx],
9033            "Episodic upstream list for M1 should exclude associative-only memory source M2"
9034        );
9035        assert_eq!(
9036            episodic_upstream_m2,
9037            vec![a2_idx],
9038            "Episodic upstream list for M2 should exclude associative-only memory source M1"
9039        );
9040    }
9041
9042    #[test]
9043    fn test_memory_to_non_memory_requires_associative_morphology() {
9044        use crate::models::cortical_area::CorticalArea;
9045        use feagi_structures::genomic::cortical_area::{
9046            CorticalAreaDimensions, CorticalAreaType, CorticalID, IOCorticalAreaConfigurationFlag,
9047            MemoryCorticalType,
9048        };
9049
9050        let mut manager = ConnectomeManager::new_for_testing();
9051        let memory_id = CorticalID::try_from_bytes(b"mmem0001").unwrap();
9052        let destination_id = CorticalID::try_from_bytes(b"csrc0001").unwrap();
9053        let memory_area = CorticalArea::new(
9054            memory_id,
9055            0,
9056            "Memory Area".to_string(),
9057            CorticalAreaDimensions::new(1, 1, 1).unwrap(),
9058            (0, 0, 0).into(),
9059            CorticalAreaType::Memory(MemoryCorticalType::Memory),
9060        )
9061        .unwrap();
9062        let destination_area = CorticalArea::new(
9063            destination_id,
9064            0,
9065            "Destination Area".to_string(),
9066            CorticalAreaDimensions::new(1, 1, 1).unwrap(),
9067            (1, 0, 0).into(),
9068            CorticalAreaType::BrainInput(IOCorticalAreaConfigurationFlag::Boolean),
9069        )
9070        .unwrap();
9071        manager.add_cortical_area(memory_area).unwrap();
9072        manager.add_cortical_area(destination_area).unwrap();
9073
9074        let invalid = manager.update_cortical_mapping(
9075            &memory_id,
9076            &destination_id,
9077            vec![serde_json::json!({"morphology_id": "episodic_memory"})],
9078        );
9079        assert!(matches!(invalid, Err(BduError::InvalidMorphology(_))));
9080
9081        manager
9082            .update_cortical_mapping(
9083                &memory_id,
9084                &destination_id,
9085                vec![serde_json::json!({"morphology_id": "associative_memory"})],
9086            )
9087            .unwrap();
9088    }
9089
9090    #[test]
9091    fn test_memory_twin_created_for_memory_mapping() {
9092        use crate::models::cortical_area::CorticalArea;
9093        use feagi_npu_burst_engine::backend::CPUBackend;
9094        use feagi_npu_burst_engine::TracingMutex;
9095        use feagi_npu_burst_engine::{DynamicNPU, RustNPU};
9096        use feagi_npu_runtime::StdRuntime;
9097        use feagi_structures::genomic::cortical_area::{
9098            CorticalAreaDimensions, CorticalAreaType, CorticalID, IOCorticalAreaConfigurationFlag,
9099            MemoryCorticalType,
9100        };
9101        use std::sync::Arc;
9102
9103        let runtime = StdRuntime;
9104        let backend = CPUBackend::new();
9105        let npu = RustNPU::new(runtime, backend, 10_000, 10_000, 10).expect("Failed to create NPU");
9106        let dyn_npu = Arc::new(TracingMutex::new(DynamicNPU::F32(npu), "TestNPU"));
9107        let mut manager = ConnectomeManager::new_for_testing_with_npu(dyn_npu.clone());
9108        feagi_evolutionary::templates::add_core_morphologies(&mut manager.morphology_registry);
9109
9110        let src_id = CorticalID::try_from_bytes(b"csrc0001").unwrap();
9111        let dst_id = CorticalID::try_from_bytes(b"mmem0001").unwrap();
9112
9113        let src_area = CorticalArea::new(
9114            src_id,
9115            0,
9116            "Source Area".to_string(),
9117            CorticalAreaDimensions::new(2, 2, 1).unwrap(),
9118            (0, 0, 0).into(),
9119            CorticalAreaType::BrainInput(IOCorticalAreaConfigurationFlag::Boolean),
9120        )
9121        .unwrap();
9122        let mut dst_area = CorticalArea::new(
9123            dst_id,
9124            0,
9125            "Memory Area".to_string(),
9126            CorticalAreaDimensions::new(2, 2, 1).unwrap(),
9127            (0, 0, 0).into(),
9128            CorticalAreaType::Memory(MemoryCorticalType::Memory),
9129        )
9130        .unwrap();
9131        dst_area
9132            .properties
9133            .insert("is_mem_type".to_string(), serde_json::json!(true));
9134        dst_area
9135            .properties
9136            .insert("temporal_depth".to_string(), serde_json::json!(1));
9137
9138        manager.add_cortical_area(src_area).unwrap();
9139        manager.add_cortical_area(dst_area).unwrap();
9140
9141        let mapping_data = vec![serde_json::json!({
9142            "morphology_id": "episodic_memory",
9143            "morphology_scalar": 1,
9144            "postSynapticCurrent_multiplier": 1.0,
9145        })];
9146        manager
9147            .update_cortical_mapping(&src_id, &dst_id, mapping_data)
9148            .unwrap();
9149        manager
9150            .regenerate_synapses_for_mapping(&src_id, &dst_id)
9151            .unwrap();
9152
9153        let memory_area = manager.get_cortical_area(&dst_id).unwrap();
9154        let twin_map = memory_area
9155            .properties
9156            .get("memory_twin_areas")
9157            .and_then(|v| v.as_object())
9158            .expect("memory_twin_areas should be set");
9159        let twin_id_str = twin_map
9160            .get(&src_id.as_base_64())
9161            .and_then(|v| v.as_str())
9162            .expect("Missing twin entry for upstream area");
9163        let twin_id = CorticalID::try_from_base_64(twin_id_str).unwrap();
9164        let mapping = memory_area
9165            .properties
9166            .get("cortical_mapping_dst")
9167            .and_then(|v| v.as_object())
9168            .and_then(|map| map.get(&twin_id.as_base_64()))
9169            .and_then(|v| v.as_array())
9170            .expect("Missing memory replay mapping for twin area");
9171        let uses_replay = mapping.iter().any(|rule| {
9172            rule.get("morphology_id")
9173                .and_then(|v| v.as_str())
9174                .is_some_and(|id| id == "memory_replay")
9175        });
9176        assert!(uses_replay, "Expected memory_replay mapping for twin area");
9177
9178        let twin_area = manager.get_cortical_area(&twin_id).unwrap();
9179        assert!(matches!(
9180            twin_area.cortical_type,
9181            CorticalAreaType::Custom(_)
9182        ));
9183        assert_eq!(
9184            twin_area
9185                .properties
9186                .get("memory_twin_of")
9187                .and_then(|v| v.as_str()),
9188            Some(src_id.as_base_64().as_str())
9189        );
9190        assert_eq!(
9191            twin_area
9192                .properties
9193                .get("memory_twin_for")
9194                .and_then(|v| v.as_str()),
9195            Some(dst_id.as_base_64().as_str())
9196        );
9197    }
9198
9199    #[test]
9200    fn test_associative_memory_between_memory_areas_creates_synapses() {
9201        use crate::models::cortical_area::CorticalArea;
9202        use feagi_npu_burst_engine::backend::CPUBackend;
9203        use feagi_npu_burst_engine::TracingMutex;
9204        use feagi_npu_burst_engine::{DynamicNPU, RustNPU};
9205        use feagi_npu_runtime::StdRuntime;
9206        use feagi_structures::genomic::cortical_area::{
9207            CorticalAreaDimensions, CorticalAreaType, CorticalID, MemoryCorticalType,
9208        };
9209        use std::sync::Arc;
9210
9211        let runtime = StdRuntime;
9212        let backend = CPUBackend::new();
9213        let npu = RustNPU::new(runtime, backend, 10_000, 10_000, 10).expect("Failed to create NPU");
9214        let dyn_npu = Arc::new(TracingMutex::new(DynamicNPU::F32(npu), "TestNPU"));
9215        let mut manager = ConnectomeManager::new_for_testing_with_npu(dyn_npu.clone());
9216        feagi_evolutionary::templates::add_core_morphologies(&mut manager.morphology_registry);
9217
9218        let m1_id = CorticalID::try_from_bytes(b"mmem0402").unwrap();
9219        let m2_id = CorticalID::try_from_bytes(b"mmem0403").unwrap();
9220
9221        let mut m1_area = CorticalArea::new(
9222            m1_id,
9223            0,
9224            "Memory M1".to_string(),
9225            CorticalAreaDimensions::new(1, 1, 1).unwrap(),
9226            (0, 0, 0).into(),
9227            CorticalAreaType::Memory(MemoryCorticalType::Memory),
9228        )
9229        .unwrap();
9230        m1_area
9231            .properties
9232            .insert("is_mem_type".to_string(), serde_json::json!(true));
9233        m1_area
9234            .properties
9235            .insert("temporal_depth".to_string(), serde_json::json!(1));
9236
9237        let mut m2_area = CorticalArea::new(
9238            m2_id,
9239            0,
9240            "Memory M2".to_string(),
9241            CorticalAreaDimensions::new(1, 1, 1).unwrap(),
9242            (0, 0, 0).into(),
9243            CorticalAreaType::Memory(MemoryCorticalType::Memory),
9244        )
9245        .unwrap();
9246        m2_area
9247            .properties
9248            .insert("is_mem_type".to_string(), serde_json::json!(true));
9249        m2_area
9250            .properties
9251            .insert("temporal_depth".to_string(), serde_json::json!(1));
9252
9253        manager.add_cortical_area(m1_area).unwrap();
9254        manager.add_cortical_area(m2_area).unwrap();
9255
9256        manager
9257            .add_neuron(&m1_id, 0, 0, 0, 1.0, 0.0, 0.1, 0.0, 0, 1, 1.0, 3, 1, false)
9258            .unwrap();
9259        manager
9260            .add_neuron(&m2_id, 0, 0, 0, 1.0, 0.0, 0.1, 0.0, 0, 1, 1.0, 3, 1, false)
9261            .unwrap();
9262
9263        let mapping_data = vec![serde_json::json!({
9264            "morphology_id": "associative_memory",
9265            "morphology_scalar": 1,
9266            "postSynapticCurrent_multiplier": 1.0,
9267            "plasticity_flag": true,
9268            "plasticity_constant": 1,
9269            "ltp_multiplier": 1,
9270            "ltd_multiplier": 1,
9271            "plasticity_window": 5,
9272        })];
9273        manager
9274            .update_cortical_mapping(&m1_id, &m2_id, mapping_data)
9275            .unwrap();
9276        let created = manager
9277            .regenerate_synapses_for_mapping(&m1_id, &m2_id)
9278            .unwrap();
9279        assert!(
9280            created > 0,
9281            "Expected associative memory mapping between memory areas to create synapses"
9282        );
9283        let npu_guard = dyn_npu.lock().unwrap();
9284        let assoc_tagged =
9285            npu_guard.count_synapses_with_edge_flag_bits(SYNAPSE_EDGE_ASSOCIATIVE_MEMORY);
9286        assert!(
9287            assoc_tagged >= 1,
9288            "associative_memory connectome path should stamp SYNAPSE_EDGE_ASSOCIATIVE_MEMORY on created synapses"
9289        );
9290    }
9291
9292    #[test]
9293    fn test_memory_twin_repair_on_load_preserves_replay_mapping() {
9294        use crate::models::cortical_area::CorticalArea;
9295        use feagi_npu_burst_engine::backend::CPUBackend;
9296        use feagi_npu_burst_engine::TracingMutex;
9297        use feagi_npu_burst_engine::{DynamicNPU, RustNPU};
9298        use feagi_npu_runtime::StdRuntime;
9299        use feagi_structures::genomic::cortical_area::{
9300            CorticalAreaDimensions, CorticalAreaType, CorticalID, IOCorticalAreaConfigurationFlag,
9301            MemoryCorticalType,
9302        };
9303        use std::sync::Arc;
9304
9305        let runtime = StdRuntime;
9306        let backend = CPUBackend::new();
9307        let npu = RustNPU::new(runtime, backend, 10_000, 10_000, 10).expect("Failed to create NPU");
9308        let dyn_npu = Arc::new(TracingMutex::new(DynamicNPU::F32(npu), "TestNPU"));
9309        let mut manager = ConnectomeManager::new_for_testing_with_npu(dyn_npu.clone());
9310        feagi_evolutionary::templates::add_core_morphologies(&mut manager.morphology_registry);
9311
9312        let src_id = CorticalID::try_from_bytes(b"csrc0002").unwrap();
9313        let mem_id = CorticalID::try_from_bytes(b"mmem0002").unwrap();
9314
9315        let src_area = CorticalArea::new(
9316            src_id,
9317            0,
9318            "Source Area".to_string(),
9319            CorticalAreaDimensions::new(2, 2, 1).unwrap(),
9320            (0, 0, 0).into(),
9321            CorticalAreaType::BrainInput(IOCorticalAreaConfigurationFlag::Boolean),
9322        )
9323        .unwrap();
9324        let mut mem_area = CorticalArea::new(
9325            mem_id,
9326            0,
9327            "Memory Area".to_string(),
9328            CorticalAreaDimensions::new(2, 2, 1).unwrap(),
9329            (0, 0, 0).into(),
9330            CorticalAreaType::Memory(MemoryCorticalType::Memory),
9331        )
9332        .unwrap();
9333        mem_area
9334            .properties
9335            .insert("is_mem_type".to_string(), serde_json::json!(true));
9336        mem_area
9337            .properties
9338            .insert("temporal_depth".to_string(), serde_json::json!(1));
9339
9340        manager.add_cortical_area(src_area).unwrap();
9341        manager.add_cortical_area(mem_area).unwrap();
9342
9343        let twin_id = manager
9344            .build_memory_twin_id(&mem_id, &src_id)
9345            .expect("Failed to build twin id");
9346        let twin_area = CorticalArea::new(
9347            twin_id,
9348            0,
9349            "Source Area_twin".to_string(),
9350            CorticalAreaDimensions::new(2, 2, 1).unwrap(),
9351            (0, 0, 0).into(),
9352            CorticalAreaType::Custom(
9353                feagi_structures::genomic::cortical_area::CustomCorticalType::LeakyIntegrateFire,
9354            ),
9355        )
9356        .unwrap();
9357        manager.add_cortical_area(twin_area).unwrap();
9358
9359        let repaired = manager
9360            .ensure_memory_twin_area(&mem_id, &src_id)
9361            .expect("Failed to repair twin");
9362        assert_eq!(repaired, twin_id);
9363
9364        let mem_area = manager.get_cortical_area(&mem_id).unwrap();
9365        let twin_map = mem_area
9366            .properties
9367            .get("memory_twin_areas")
9368            .and_then(|v| v.as_object())
9369            .expect("memory_twin_areas should be set");
9370        let twin_id_str = twin_map
9371            .get(&src_id.as_base_64())
9372            .and_then(|v| v.as_str())
9373            .expect("Missing twin entry for upstream area");
9374        assert_eq!(twin_id_str, twin_id.as_base_64());
9375
9376        let replay_map = mem_area
9377            .properties
9378            .get("cortical_mapping_dst")
9379            .and_then(|v| v.as_object())
9380            .and_then(|map| map.get(&twin_id.as_base_64()))
9381            .and_then(|v| v.as_array())
9382            .expect("Missing memory replay mapping for twin area");
9383        let uses_replay = replay_map.iter().any(|rule| {
9384            rule.get("morphology_id")
9385                .and_then(|v| v.as_str())
9386                .is_some_and(|id| id == "memory_replay")
9387        });
9388        assert!(uses_replay, "Expected memory_replay mapping for twin area");
9389
9390        let twin_area = manager.get_cortical_area(&twin_id).unwrap();
9391        assert_eq!(
9392            twin_area
9393                .properties
9394                .get("memory_twin_of")
9395                .and_then(|v| v.as_str()),
9396            Some(src_id.as_base_64().as_str())
9397        );
9398        assert_eq!(
9399            twin_area
9400                .properties
9401                .get("memory_twin_for")
9402                .and_then(|v| v.as_str()),
9403            Some(mem_id.as_base_64().as_str())
9404        );
9405    }
9406}