feagi-api 0.0.12

FEAGI REST API layer with HTTP and ZMQ transport adapters
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
// Copyright 2025 Neuraville Inc.
// SPDX-License-Identifier: Apache-2.0

//! WASM Connectome Service
//!
//! Extracts cortical area and brain region data from RuntimeGenome.

use async_trait::async_trait;
use feagi_evolutionary::RuntimeGenome;
use feagi_services::traits::connectome_service::ConnectomeService;
use feagi_services::types::errors::{ServiceError, ServiceResult};
use feagi_services::types::*;
use feagi_structures::genomic::cortical_area::CorticalID;
use std::collections::HashMap;
use std::sync::Arc;

/// WASM Connectome Service
///
/// Extracts data from RuntimeGenome to implement ConnectomeService trait.
/// Read-only operations only (no mutations).
pub struct WasmConnectomeService {
    /// Runtime genome (read-only)
    genome: Arc<RuntimeGenome>,
}

impl WasmConnectomeService {
    /// Create new WASM connectome service
    pub fn new(genome: Arc<RuntimeGenome>) -> Self {
        Self { genome }
    }

    /// Convert CorticalArea to CorticalAreaInfo
    fn area_to_info(
        &self,
        cortical_id: &CorticalID,
        area: &feagi_structures::genomic::cortical_area::CorticalArea,
    ) -> CorticalAreaInfo {
        use feagi_structures::genomic::cortical_area::CorticalArea;

        // Extract physiology parameters from properties
        let leak_coefficient = area
            .properties
            .get("leak_coefficient")
            .and_then(|v| v.as_f64())
            .unwrap_or(0.1);

        // Extract other properties
        let neurons_per_voxel = area
            .properties
            .get("neurons_per_voxel")
            .and_then(|v| v.as_u64())
            .map(|u| u as u32)
            .unwrap_or(1);

        let postsynaptic_current = area
            .properties
            .get("postsynaptic_current")
            .and_then(|v| v.as_f64())
            .unwrap_or(0.1);

        // Determine cortical group and area type from cortical_type
        // Extract area type string from properties or use default
        let area_type_str = area
            .properties
            .get("area_type")
            .and_then(|v| v.as_str())
            .map(String::from)
            .unwrap_or_else(|| "Custom".to_string());

        let cortical_group = match area_type_str.as_str() {
            "Sensory" | "IPU" => "IPU".to_string(),
            "Motor" | "OPU" => "OPU".to_string(),
            "Memory" => "MEMORY".to_string(),
            "Custom" => "CUSTOM".to_string(),
            _ => "CORE".to_string(),
        };
        let cortical_type = match cortical_group.as_str() {
            "IPU" => "sensory".to_string(),
            "OPU" => "motor".to_string(),
            "MEMORY" => "memory".to_string(),
            "CORE" => "core".to_string(),
            _ => "custom".to_string(),
        };

        let firing_threshold = area
            .properties
            .get("firing_threshold")
            .and_then(|v| v.as_f64())
            .unwrap_or(1.0);
        let firing_threshold_increment = [
            area.properties
                .get("firing_threshold_increment_x")
                .and_then(|v| v.as_f64())
                .unwrap_or(0.0),
            area.properties
                .get("firing_threshold_increment_y")
                .and_then(|v| v.as_f64())
                .unwrap_or(0.0),
            area.properties
                .get("firing_threshold_increment_z")
                .and_then(|v| v.as_f64())
                .unwrap_or(0.0),
        ];
        let postsynaptic_current_max = area
            .properties
            .get("postsynaptic_current_max")
            .and_then(|v| v.as_f64())
            .unwrap_or(postsynaptic_current);
        let mp_driven_psp = area
            .properties
            .get("mp_driven_psp")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        let mp_charge_accumulation = area
            .properties
            .get("mp_charge_accumulation")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        let neuron_excitability = area
            .properties
            .get("neuron_excitability")
            .and_then(|v| v.as_f64())
            .unwrap_or(0.0);
        let init_lifespan = area
            .properties
            .get("init_lifespan")
            .and_then(|v| v.as_u64())
            .map(|u| u as u32)
            .unwrap_or(0);
        let lifespan_growth_rate = area
            .properties
            .get("lifespan_growth_rate")
            .and_then(|v| v.as_f64())
            .unwrap_or(0.0);
        let longterm_mem_threshold = area
            .properties
            .get("longterm_mem_threshold")
            .and_then(|v| v.as_u64())
            .map(|u| u as u32)
            .unwrap_or(0);
        let temporal_depth = area
            .properties
            .get("temporal_depth")
            .and_then(|v| v.as_u64())
            .map(|u| u as u32);

        let cid_bytes = cortical_id.as_bytes();
        let is_io_area_wasm = cid_bytes.len() == 8
            && (cid_bytes.first().copied() == Some(b'i')
                || cid_bytes.first().copied() == Some(b'o'));
        let cortical_subtype_field = if is_io_area_wasm {
            String::from_utf8(cid_bytes[0..4].to_vec()).ok()
        } else {
            None
        };
        let wasm_subunit_id = if is_io_area_wasm {
            cid_bytes.get(6).copied()
        } else {
            None
        };
        let wasm_cortical_unit_index = if is_io_area_wasm {
            cid_bytes.get(7).copied()
        } else {
            None
        };

        CorticalAreaInfo {
            cortical_id: cortical_id.to_string(),
            cortical_id_s: cortical_id.to_string(), // TODO: Decode base64 if needed
            cortical_idx: area.cortical_idx,
            name: area.name.clone(),
            dimensions: (
                area.dimensions.width as usize,
                area.dimensions.height as usize,
                area.dimensions.depth as usize,
            ),
            position: (area.position.x, area.position.y, area.position.z),
            area_type: area_type_str,
            cortical_group,
            cortical_type,
            neuron_count: 0,           // TODO: Extract from NPU if available
            synapse_count: 0,          // TODO: Extract from NPU if available
            incoming_synapse_count: 0, // TODO: Extract from NPU if available
            outgoing_synapse_count: 0, // TODO: Extract from NPU if available
            visible: area
                .properties
                .get("visible")
                .and_then(|v| v.as_bool())
                .unwrap_or(true),
            sub_group: area
                .properties
                .get("cortical_sub_group")
                .and_then(|v| v.as_str())
                .map(String::from),
            neurons_per_voxel,
            postsynaptic_current,
            postsynaptic_current_max,
            plasticity_constant: area
                .properties
                .get("plasticity_constant")
                .and_then(|v| v.as_f64())
                .unwrap_or(0.0),
            degeneration: area
                .properties
                .get("degeneration")
                .and_then(|v| v.as_f64())
                .unwrap_or(0.0),
            psp_uniform_distribution: area
                .properties
                .get("psp_uniform_distribution")
                .and_then(|v| v.as_bool())
                .unwrap_or(false),
            mp_driven_psp,
            firing_threshold,
            firing_threshold_increment,
            firing_threshold_limit: area
                .properties
                .get("firing_threshold_limit")
                .and_then(|v| v.as_f64())
                .unwrap_or(1.0),
            consecutive_fire_count: area
                .properties
                .get("consecutive_fire_count")
                .and_then(|v| v.as_u64())
                .map(|u| u as u32)
                .unwrap_or(0),
            snooze_period: area
                .properties
                .get("snooze_period")
                .and_then(|v| v.as_u64())
                .map(|u| u as u32)
                .unwrap_or(0),
            refractory_period: area
                .properties
                .get("refractory_period")
                .and_then(|v| v.as_u64())
                .map(|u| u as u32)
                .unwrap_or(0),
            leak_coefficient,
            leak_variability: area
                .properties
                .get("leak_variability")
                .and_then(|v| v.as_f64())
                .unwrap_or(0.0),
            mp_charge_accumulation,
            neuron_excitability,
            burst_engine_active: true, // Always active in WASM
            init_lifespan,
            lifespan_growth_rate,
            longterm_mem_threshold,
            temporal_depth,
            properties: area.properties.clone(),
            cortical_subtype: cortical_subtype_field,
            encoding_type: None,
            encoding_format: None,
            unit_id: wasm_cortical_unit_index,
            subunit_id: wasm_subunit_id,
            group_id: wasm_cortical_unit_index,
            coding_signage: None,
            coding_behavior: None,
            coding_type: None,
            coding_options: None,
            parent_region_id: None, // TODO: Find which brain region contains this area
            dev_count: None,
            cortical_dimensions_per_device: None,
            visualization_voxel_granularity: None,
        }
    }
}

#[async_trait]
impl ConnectomeService for WasmConnectomeService {
    async fn create_cortical_area(
        &self,
        _params: CreateCorticalAreaParams,
    ) -> ServiceResult<CorticalAreaInfo> {
        Err(ServiceError::NotImplemented(
            "WASM mode is read-only".to_string(),
        ))
    }

    async fn update_cortical_area(
        &self,
        _cortical_id: &str,
        _params: UpdateCorticalAreaParams,
    ) -> ServiceResult<CorticalAreaInfo> {
        Err(ServiceError::NotImplemented(
            "WASM mode is read-only".to_string(),
        ))
    }

    async fn delete_cortical_area(&self, _cortical_id: &str) -> ServiceResult<()> {
        Err(ServiceError::NotImplemented(
            "WASM mode is read-only".to_string(),
        ))
    }

    async fn get_cortical_area(&self, cortical_id: &str) -> ServiceResult<CorticalAreaInfo> {
        let cortical_id_parsed = CorticalID::try_from_base_64(cortical_id).map_err(|_| {
            ServiceError::InvalidInput(format!("Invalid cortical ID format: {}", cortical_id))
        })?;
        let area = self
            .genome
            .cortical_areas
            .get(&cortical_id_parsed)
            .ok_or_else(|| ServiceError::NotFound {
                resource: "cortical_area".to_string(),
                id: cortical_id.to_string(),
            })?;

        Ok(self.area_to_info(&cortical_id_parsed, area))
    }

    async fn list_cortical_areas(&self) -> ServiceResult<Vec<CorticalAreaInfo>> {
        let areas: Vec<CorticalAreaInfo> = self
            .genome
            .cortical_areas
            .iter()
            .map(|(id, area)| self.area_to_info(id, area))
            .collect();

        Ok(areas)
    }

    async fn get_cortical_area_ids(&self) -> ServiceResult<Vec<String>> {
        Ok(self
            .genome
            .cortical_areas
            .keys()
            .map(|id| id.to_string())
            .collect::<Vec<_>>())
    }

    async fn cortical_area_exists(&self, cortical_id: &str) -> ServiceResult<bool> {
        let cortical_id_parsed = CorticalID::try_from_base_64(cortical_id).map_err(|_| {
            ServiceError::InvalidInput(format!("Invalid cortical ID format: {}", cortical_id))
        })?;
        Ok(self.genome.cortical_areas.contains_key(&cortical_id_parsed))
    }

    async fn get_cortical_area_properties(
        &self,
        cortical_id: &str,
    ) -> ServiceResult<std::collections::HashMap<String, serde_json::Value>> {
        let cortical_id_parsed = CorticalID::try_from_base_64(cortical_id).map_err(|_| {
            ServiceError::InvalidInput(format!("Invalid cortical ID format: {}", cortical_id))
        })?;
        let area = self
            .genome
            .cortical_areas
            .get(&cortical_id_parsed)
            .ok_or_else(|| ServiceError::NotFound {
                resource: "cortical_area".to_string(),
                id: cortical_id.to_string(),
            })?;

        Ok(area.properties.clone())
    }

    async fn get_all_cortical_area_properties(
        &self,
    ) -> ServiceResult<Vec<std::collections::HashMap<String, serde_json::Value>>> {
        Ok(self
            .genome
            .cortical_areas
            .values()
            .map(|area| area.properties.clone())
            .collect())
    }

    async fn create_brain_region(
        &self,
        _params: CreateBrainRegionParams,
    ) -> ServiceResult<BrainRegionInfo> {
        Err(ServiceError::NotImplemented(
            "WASM mode is read-only".to_string(),
        ))
    }

    async fn delete_brain_region(&self, _region_id: &str) -> ServiceResult<()> {
        Err(ServiceError::NotImplemented(
            "WASM mode is read-only".to_string(),
        ))
    }

    async fn update_brain_region(
        &self,
        _region_id: &str,
        _properties: std::collections::HashMap<String, serde_json::Value>,
    ) -> ServiceResult<BrainRegionInfo> {
        Err(ServiceError::NotImplemented(
            "WASM mode is read-only".to_string(),
        ))
    }

    async fn get_brain_region(&self, region_id: &str) -> ServiceResult<BrainRegionInfo> {
        let _region =
            self.genome
                .brain_regions
                .get(region_id)
                .ok_or_else(|| ServiceError::NotFound {
                    resource: "brain_region".to_string(),
                    id: region_id.to_string(),
                })?;

        // Convert BrainRegion to BrainRegionInfo
        // TODO: Implement full conversion
        Err(ServiceError::NotImplemented(
            "Brain region conversion not yet implemented".to_string(),
        ))
    }

    async fn list_brain_regions(&self) -> ServiceResult<Vec<BrainRegionInfo>> {
        // TODO: Convert all brain regions to BrainRegionInfo
        Err(ServiceError::NotImplemented(
            "Brain region listing not yet implemented".to_string(),
        ))
    }

    async fn get_brain_region_ids(&self) -> ServiceResult<Vec<String>> {
        Ok(self.genome.brain_regions.keys().cloned().collect())
    }

    async fn brain_region_exists(&self, region_id: &str) -> ServiceResult<bool> {
        Ok(self.genome.brain_regions.contains_key(region_id))
    }

    async fn get_root_region_id(&self) -> ServiceResult<Option<String>> {
        Ok(self.genome.brain_regions_root.clone())
    }

    async fn get_morphologies(
        &self,
    ) -> ServiceResult<std::collections::HashMap<String, MorphologyInfo>> {
        // TODO: Convert MorphologyRegistry to HashMap<String, MorphologyInfo>
        Err(ServiceError::NotImplemented(
            "Morphology extraction not yet implemented".to_string(),
        ))
    }

    async fn create_morphology(
        &self,
        _morphology_id: String,
        _morphology: feagi_evolutionary::Morphology,
    ) -> ServiceResult<()> {
        Err(ServiceError::NotImplemented(
            "WASM mode is read-only".to_string(),
        ))
    }

    async fn update_morphology(
        &self,
        _morphology_id: String,
        _morphology: feagi_evolutionary::Morphology,
    ) -> ServiceResult<()> {
        Err(ServiceError::NotImplemented(
            "WASM mode is read-only".to_string(),
        ))
    }

    async fn delete_morphology(&self, _morphology_id: &str) -> ServiceResult<()> {
        Err(ServiceError::NotImplemented(
            "WASM mode is read-only".to_string(),
        ))
    }

    async fn rename_morphology(&self, _old_id: &str, _new_id: &str) -> ServiceResult<()> {
        Err(ServiceError::NotImplemented(
            "WASM mode is read-only".to_string(),
        ))
    }

    async fn update_cortical_mapping(
        &self,
        _src_area_id: String,
        _dst_area_id: String,
        _mapping_data: Vec<serde_json::Value>,
    ) -> ServiceResult<usize> {
        Err(ServiceError::NotImplemented(
            "WASM mode is read-only".to_string(),
        ))
    }
}