feagi-api 0.0.8

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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
// Copyright 2025 Neuraville Inc.
// Licensed under the Apache License, Version 2.0

//! Morphology API Endpoints - Exact port from Python `/v1/morphology/*`

// Removed - using crate::common::State instead
use crate::common::ApiState;
use crate::common::{ApiError, ApiResult, Json, Path, State};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};

const DEFAULT_MORPHOLOGY_CLASS: &str = "custom";

#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)]
pub struct MorphologyListResponse {
    pub morphology_list: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)]
pub struct RenameMorphologyRequest {
    #[serde(alias = "old_morphology_name")]
    pub old_morphology_id: String,
    #[serde(alias = "new_morphology_name")]
    pub new_morphology_id: String,
}

/// Get list of all morphology names in alphabetical order.
#[utoipa::path(get, path = "/v1/morphology/morphology_list", tag = "morphology")]
pub async fn get_morphology_list(
    State(state): State<ApiState>,
) -> ApiResult<Json<MorphologyListResponse>> {
    let connectome_service = state.connectome_service.as_ref();

    let morphologies = connectome_service
        .get_morphologies()
        .await
        .map_err(|e| ApiError::internal(format!("Failed to get morphologies: {}", e)))?;

    // Sort morphology names alphabetically for consistent UI display
    let mut names: Vec<String> = morphologies.keys().cloned().collect();
    names.sort();

    Ok(Json(MorphologyListResponse {
        morphology_list: names,
    }))
}

/// Get available morphology types (vectors, patterns, projector).
#[utoipa::path(get, path = "/v1/morphology/morphology_types", tag = "morphology")]
pub async fn get_morphology_types(State(_state): State<ApiState>) -> ApiResult<Json<Vec<String>>> {
    Ok(Json(vec![
        "vectors".to_string(),
        "patterns".to_string(),
        "projector".to_string(),
    ]))
}

/// Get morphologies categorized by type.
#[utoipa::path(get, path = "/v1/morphology/list/types", tag = "morphology")]
pub async fn get_list_types(
    State(_state): State<ApiState>,
) -> ApiResult<Json<BTreeMap<String, Vec<String>>>> {
    // TODO: Get actual morphology categorization
    // Use BTreeMap for alphabetical ordering in UI
    Ok(Json(BTreeMap::new()))
}

/// Get all morphology definitions with their complete configurations.
#[utoipa::path(
    get,
    path = "/v1/morphology/morphologies",
    tag = "morphology",
    responses(
        (status = 200, description = "All morphology definitions", body = HashMap<String, serde_json::Value>),
        (status = 500, description = "Internal server error")
    )
)]
pub async fn get_morphologies(
    State(state): State<ApiState>,
) -> ApiResult<Json<BTreeMap<String, serde_json::Value>>> {
    let connectome_service = state.connectome_service.as_ref();

    // Get morphologies from connectome
    let morphologies = connectome_service
        .get_morphologies()
        .await
        .map_err(|e| ApiError::internal(format!("Failed to get morphologies: {}", e)))?;

    // Convert to Python-compatible format
    // Use BTreeMap for alphabetical ordering in UI
    let mut result = BTreeMap::new();
    for (name, morphology_info) in morphologies.iter() {
        result.insert(
            name.clone(),
            serde_json::json!({
                "name": name,
                "type": morphology_info.morphology_type,
                "class": morphology_info.class,
                "parameters": morphology_info.parameters,
                "source": "genome"
            }),
        );
    }

    Ok(Json(result))
}

/// Create a new morphology definition.
#[utoipa::path(post, path = "/v1/morphology/morphology", tag = "morphology")]
pub async fn post_morphology(
    State(state): State<ApiState>,
    Json(req): Json<HashMap<String, serde_json::Value>>,
) -> ApiResult<Json<HashMap<String, String>>> {
    let morphology_name = req
        .get("morphology_name")
        .and_then(|v| v.as_str())
        .ok_or_else(|| ApiError::invalid_input("Missing morphology_name"))?
        .trim()
        .to_string();

    if morphology_name.is_empty() {
        return Err(ApiError::invalid_input("morphology_name must be non-empty"));
    }

    let morphology_type = req
        .get("morphology_type")
        .and_then(|v| v.as_str())
        .ok_or_else(|| ApiError::invalid_input("Missing morphology_type"))?
        .trim()
        .to_lowercase();

    let morphology_parameters = req
        .get("morphology_parameters")
        .cloned()
        .ok_or_else(|| ApiError::invalid_input("Missing morphology_parameters"))?;

    let (morphology_type_enum, params_value) = match morphology_type.as_str() {
        "vectors" => (
            feagi_evolutionary::MorphologyType::Vectors,
            morphology_parameters,
        ),
        "patterns" => (
            feagi_evolutionary::MorphologyType::Patterns,
            morphology_parameters,
        ),
        "functions" => (
            feagi_evolutionary::MorphologyType::Functions,
            morphology_parameters,
        ),
        "composite" => {
            // BV payload wraps composite fields under {"composite": {...}}.
            // Accept that exact schema (and also accept the direct flat schema).
            let composite_obj = morphology_parameters
                .get("composite")
                .cloned()
                .unwrap_or(morphology_parameters);
            (feagi_evolutionary::MorphologyType::Composite, composite_obj)
        }
        other => {
            return Err(ApiError::invalid_input(format!(
                "Unknown morphology_type '{}'",
                other
            )))
        }
    };

    let parameters: feagi_evolutionary::MorphologyParameters = serde_json::from_value(params_value)
        .map_err(|e| ApiError::invalid_input(format!("Invalid morphology_parameters: {}", e)))?;

    let morphology = feagi_evolutionary::Morphology {
        morphology_type: morphology_type_enum,
        parameters,
        class: DEFAULT_MORPHOLOGY_CLASS.to_string(),
    };

    state
        .connectome_service
        .create_morphology(morphology_name, morphology)
        .await
        .map_err(ApiError::from)?;

    Ok(Json(HashMap::from([(
        "status".to_string(),
        "success".to_string(),
    )])))
}

/// Update an existing morphology definition.
#[utoipa::path(put, path = "/v1/morphology/morphology", tag = "morphology")]
pub async fn put_morphology(
    State(state): State<ApiState>,
    Json(req): Json<HashMap<String, serde_json::Value>>,
) -> ApiResult<Json<HashMap<String, String>>> {
    tracing::info!(
        target: "feagi-api",
        "[MORPH-AUDIT][API] PUT /v1/morphology/morphology received payload keys={:?}",
        req.keys().collect::<Vec<_>>()
    );
    let morphology_name = req
        .get("morphology_name")
        .and_then(|v| v.as_str())
        .ok_or_else(|| ApiError::invalid_input("Missing morphology_name"))?
        .trim()
        .to_string();

    if morphology_name.is_empty() {
        return Err(ApiError::invalid_input("morphology_name must be non-empty"));
    }

    let morphology_type = req
        .get("morphology_type")
        .and_then(|v| v.as_str())
        .ok_or_else(|| ApiError::invalid_input("Missing morphology_type"))?
        .trim()
        .to_lowercase();

    let morphology_parameters = req
        .get("morphology_parameters")
        .cloned()
        .ok_or_else(|| ApiError::invalid_input("Missing morphology_parameters"))?;

    let (morphology_type_enum, params_value) = match morphology_type.as_str() {
        "vectors" => (
            feagi_evolutionary::MorphologyType::Vectors,
            morphology_parameters,
        ),
        "patterns" => (
            feagi_evolutionary::MorphologyType::Patterns,
            morphology_parameters,
        ),
        "functions" => (
            feagi_evolutionary::MorphologyType::Functions,
            morphology_parameters,
        ),
        "composite" => {
            let composite_obj = morphology_parameters
                .get("composite")
                .cloned()
                .unwrap_or(morphology_parameters);
            (feagi_evolutionary::MorphologyType::Composite, composite_obj)
        }
        other => {
            return Err(ApiError::invalid_input(format!(
                "Unknown morphology_type '{}'",
                other
            )))
        }
    };

    let parameters: feagi_evolutionary::MorphologyParameters = serde_json::from_value(params_value)
        .map_err(|e| ApiError::invalid_input(format!("Invalid morphology_parameters: {}", e)))?;

    let morphology = feagi_evolutionary::Morphology {
        morphology_type: morphology_type_enum,
        parameters,
        class: DEFAULT_MORPHOLOGY_CLASS.to_string(),
    };

    tracing::info!(
        target: "feagi-api",
        "[MORPH-AUDIT][API] Dispatching update_morphology name={} type={}",
        morphology_name,
        morphology_type
    );

    state
        .connectome_service
        .update_morphology(morphology_name, morphology)
        .await
        .map_err(ApiError::from)?;

    tracing::info!(
        target: "feagi-api",
        "[MORPH-AUDIT][API] update_morphology completed successfully"
    );

    Ok(Json(HashMap::from([(
        "status".to_string(),
        "success".to_string(),
    )])))
}

/// Delete a morphology by name provided in request body.
#[utoipa::path(delete, path = "/v1/morphology/morphology", tag = "morphology")]
pub async fn delete_morphology_by_name(
    State(state): State<ApiState>,
    Json(req): Json<HashMap<String, String>>,
) -> ApiResult<Json<HashMap<String, String>>> {
    let morphology_name = req
        .get("morphology_name")
        .ok_or_else(|| ApiError::invalid_input("Missing morphology_name"))?
        .trim();

    if morphology_name.is_empty() {
        return Err(ApiError::invalid_input("morphology_name must be non-empty"));
    }

    state
        .connectome_service
        .delete_morphology(morphology_name)
        .await
        .map_err(ApiError::from)?;

    Ok(Json(HashMap::from([(
        "status".to_string(),
        "success".to_string(),
    )])))
}

/// Rename a morphology and update all references in the genome.
#[utoipa::path(
    put,
    path = "/v1/morphology/rename",
    tag = "morphology",
    request_body = RenameMorphologyRequest,
    responses(
        (status = 200, description = "Morphology renamed", body = HashMap<String, String>),
        (status = 404, description = "Morphology not found"),
        (status = 409, description = "New morphology ID already exists"),
        (status = 500, description = "Internal server error")
    )
)]
pub async fn put_rename_morphology(
    State(state): State<ApiState>,
    Json(req): Json<RenameMorphologyRequest>,
) -> ApiResult<Json<HashMap<String, String>>> {
    let old_id = req.old_morphology_id.trim();
    let new_id = req.new_morphology_id.trim();

    if old_id.is_empty() {
        return Err(ApiError::invalid_input(
            "old_morphology_id must be non-empty",
        ));
    }
    if new_id.is_empty() {
        return Err(ApiError::invalid_input(
            "new_morphology_id must be non-empty",
        ));
    }

    state
        .connectome_service
        .rename_morphology(old_id, new_id)
        .await
        .map_err(ApiError::from)?;

    Ok(Json(HashMap::from([
        ("status".to_string(), "success".to_string()),
        ("old_morphology_id".to_string(), old_id.to_string()),
        ("new_morphology_id".to_string(), new_id.to_string()),
    ])))
}

/// Get detailed properties for a specific morphology by name.
#[utoipa::path(
    post,
    path = "/v1/morphology/morphology_properties",
    tag = "morphology",
    responses(
        (status = 200, description = "Morphology properties", body = HashMap<String, serde_json::Value>),
        (status = 404, description = "Morphology not found"),
        (status = 500, description = "Internal server error")
    )
)]
pub async fn post_morphology_properties(
    State(state): State<ApiState>,
    Json(req): Json<HashMap<String, String>>,
) -> ApiResult<Json<BTreeMap<String, serde_json::Value>>> {
    use tracing::debug;

    let morphology_name = req
        .get("morphology_name")
        .ok_or_else(|| ApiError::invalid_input("Missing morphology_name"))?;

    debug!(target: "feagi-api", "Getting properties for morphology: {}", morphology_name);

    let connectome_service = state.connectome_service.as_ref();
    let morphologies = connectome_service
        .get_morphologies()
        .await
        .map_err(|e| ApiError::internal(format!("Failed to get morphologies: {}", e)))?;

    let morphology_info = morphologies
        .get(morphology_name)
        .ok_or_else(|| ApiError::not_found("Morphology", morphology_name))?;

    // Return properties in expected format
    // Use BTreeMap for alphabetical ordering in UI
    let mut result = BTreeMap::new();
    result.insert(
        "morphology_name".to_string(),
        serde_json::json!(morphology_name),
    );
    result.insert(
        "type".to_string(),
        serde_json::json!(morphology_info.morphology_type),
    );
    result.insert(
        "class".to_string(),
        serde_json::json!(morphology_info.class),
    );
    result.insert("parameters".to_string(), morphology_info.parameters.clone());
    result.insert("source".to_string(), serde_json::json!("genome"));

    Ok(Json(result))
}

/// Get all cortical area pairs that use a specific morphology.
#[utoipa::path(
    post,
    path = "/v1/morphology/morphology_usage",
    tag = "morphology",
    responses(
        (status = 200, description = "Morphology usage pairs", body = Vec<Vec<String>>),
        (status = 500, description = "Internal server error")
    )
)]
pub async fn post_morphology_usage(
    State(state): State<ApiState>,
    Json(req): Json<HashMap<String, String>>,
) -> ApiResult<Json<Vec<Vec<String>>>> {
    use tracing::debug;

    let morphology_name = req
        .get("morphology_name")
        .ok_or_else(|| ApiError::invalid_input("Missing morphology_name"))?;

    debug!(target: "feagi-api", "Getting usage for morphology: {}", morphology_name);

    let connectome_service = state.connectome_service.as_ref();

    // Get all cortical areas
    let areas = connectome_service
        .list_cortical_areas()
        .await
        .map_err(|e| ApiError::internal(format!("Failed to list areas: {}", e)))?;

    // Find all [src, dst] pairs that use this morphology
    let mut usage_pairs = Vec::new();

    for area_info in areas {
        if let Some(mapping_dst) = area_info.properties.get("cortical_mapping_dst") {
            if let Some(dst_map) = mapping_dst.as_object() {
                for (dst_id, connections) in dst_map {
                    if let Some(conn_array) = connections.as_array() {
                        for conn in conn_array {
                            let morph_id = if let Some(arr) = conn.as_array() {
                                arr.first().and_then(|v| v.as_str())
                            } else if let Some(obj) = conn.as_object() {
                                obj.get("morphology_id").and_then(|v| v.as_str())
                            } else {
                                None
                            };

                            if morph_id == Some(morphology_name.as_str()) {
                                usage_pairs
                                    .push(vec![area_info.cortical_id.clone(), dst_id.clone()]);
                            }
                        }
                    }
                }
            }
        }
    }

    debug!(target: "feagi-api", "Found {} usage pairs for morphology: {}", usage_pairs.len(), morphology_name);
    Ok(Json(usage_pairs))
}

/// Get list of all morphology names.
#[utoipa::path(
    get,
    path = "/v1/morphology/list",
    tag = "morphology",
    responses(
        (status = 200, description = "List of morphology names", body = Vec<String>)
    )
)]
pub async fn get_list(State(state): State<ApiState>) -> ApiResult<Json<Vec<String>>> {
    let connectome_service = state.connectome_service.as_ref();

    let morphologies = connectome_service
        .get_morphologies()
        .await
        .map_err(|e| ApiError::internal(format!("Failed to get morphologies: {}", e)))?;

    // Sort morphology names alphabetically for consistent UI display
    let mut names: Vec<String> = morphologies.keys().cloned().collect();
    names.sort();
    Ok(Json(names))
}

/// Get detailed information about a specific morphology using path parameter.
#[utoipa::path(
    get,
    path = "/v1/morphology/info/{morphology_id}",
    tag = "morphology",
    params(
        ("morphology_id" = String, Path, description = "Morphology name")
    ),
    responses(
        (status = 200, description = "Morphology info", body = BTreeMap<String, serde_json::Value>)
    )
)]
pub async fn get_info(
    State(state): State<ApiState>,
    Path(morphology_id): Path<String>,
) -> ApiResult<Json<BTreeMap<String, serde_json::Value>>> {
    // Delegate to post_morphology_properties (same logic)
    post_morphology_properties(
        State(state),
        Json(HashMap::from([(
            "morphology_name".to_string(),
            morphology_id,
        )])),
    )
    .await
}

/// Create a new morphology with specified parameters.
#[utoipa::path(
    post,
    path = "/v1/morphology/create",
    tag = "morphology",
    responses(
        (status = 200, description = "Morphology created", body = HashMap<String, String>)
    )
)]
pub async fn post_create(
    State(_state): State<ApiState>,
    Json(_request): Json<HashMap<String, serde_json::Value>>,
) -> ApiResult<Json<HashMap<String, String>>> {
    // TODO: Implement morphology creation
    Ok(Json(HashMap::from([(
        "message".to_string(),
        "Morphology creation not yet implemented".to_string(),
    )])))
}

/// Update an existing morphology's parameters.
#[utoipa::path(
    put,
    path = "/v1/morphology/update",
    tag = "morphology",
    responses(
        (status = 200, description = "Morphology updated", body = HashMap<String, String>)
    )
)]
pub async fn put_update(
    State(_state): State<ApiState>,
    Json(_request): Json<HashMap<String, serde_json::Value>>,
) -> ApiResult<Json<HashMap<String, String>>> {
    // TODO: Implement morphology update
    Ok(Json(HashMap::from([(
        "message".to_string(),
        "Morphology update not yet implemented".to_string(),
    )])))
}

/// Delete a morphology using path parameter.
#[utoipa::path(
    delete,
    path = "/v1/morphology/delete/{morphology_id}",
    tag = "morphology",
    params(
        ("morphology_id" = String, Path, description = "Morphology name")
    ),
    responses(
        (status = 200, description = "Morphology deleted", body = HashMap<String, String>)
    )
)]
pub async fn delete_morphology(
    State(_state): State<ApiState>,
    Path(morphology_id): Path<String>,
) -> ApiResult<Json<HashMap<String, String>>> {
    // TODO: Implement morphology deletion
    tracing::info!(target: "feagi-api", "Delete morphology requested: {}", morphology_id);

    Ok(Json(HashMap::from([(
        "message".to_string(),
        format!("Morphology {} deletion not yet implemented", morphology_id),
    )])))
}