Skip to main content

feagi_api/transports/http/
server.rs

1// Copyright 2025 Neuraville Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4// HTTP server implementation (Axum)
5//
6// This module sets up the HTTP API server with Axum, including routing,
7// middleware, and state management.
8
9use axum::{
10    body::Body,
11    extract::State,
12    http::{Request, StatusCode},
13    middleware::{self, Next},
14    response::{Html, IntoResponse, Json, Redirect, Response},
15    routing::{get, put},
16    Router,
17};
18use http_body_util::BodyExt;
19use std::sync::Arc;
20use tower_http::{
21    cors::{Any, CorsLayer},
22    trace::TraceLayer,
23};
24use utoipa::OpenApi;
25
26use crate::amalgamation;
27#[cfg(feature = "http")]
28use crate::openapi::ApiDoc;
29#[cfg(feature = "services")]
30use feagi_services::traits::{AgentService, SystemService};
31#[cfg(feature = "services")]
32use feagi_services::{
33    AnalyticsService, ConnectomeService, GenomeService, NeuronService, RuntimeService,
34};
35
36/// Application state shared across all HTTP handlers
37#[derive(Clone)]
38pub struct ApiState {
39    pub agent_service: Option<Arc<dyn AgentService + Send + Sync>>,
40    pub analytics_service: Arc<dyn AnalyticsService + Send + Sync>,
41    pub connectome_service: Arc<dyn ConnectomeService + Send + Sync>,
42    pub genome_service: Arc<dyn GenomeService + Send + Sync>,
43    pub neuron_service: Arc<dyn NeuronService + Send + Sync>,
44    pub runtime_service: Arc<dyn RuntimeService + Send + Sync>,
45    pub system_service: Arc<dyn SystemService + Send + Sync>,
46    pub snapshot_service: Option<Arc<dyn feagi_services::SnapshotService + Send + Sync>>,
47    /// FEAGI session timestamp in milliseconds (Unix timestamp when FEAGI started)
48    /// This is a unique identifier for each FEAGI instance/session
49    pub feagi_session_timestamp: i64,
50    /// Memory area stats cache (updated by plasticity service, read by health check)
51    pub memory_stats_cache: Option<feagi_npu_plasticity::MemoryStatsCache>,
52    /// In-memory amalgamation state (pending request + history), surfaced via health_check.
53    pub amalgamation_state: amalgamation::SharedAmalgamationState,
54    /// Device registration connectors per agent (for export/import functionality)
55    #[cfg(feature = "feagi-agent")]
56    pub agent_connectors: Arc<
57        parking_lot::RwLock<
58            std::collections::HashMap<
59                feagi_agent::sdk::AgentDescriptor,
60                Arc<std::sync::Mutex<feagi_agent::sdk::ConnectorAgent>>,
61            >,
62        >,
63    >,
64}
65
66impl ApiState {
67    /// Initialize agent_connectors field (empty HashMap)
68    #[cfg(feature = "feagi-agent")]
69    pub fn init_agent_connectors() -> Arc<
70        parking_lot::RwLock<
71            std::collections::HashMap<
72                feagi_agent::sdk::AgentDescriptor,
73                Arc<std::sync::Mutex<feagi_agent::sdk::ConnectorAgent>>,
74            >,
75        >,
76    > {
77        Arc::new(parking_lot::RwLock::new(std::collections::HashMap::new()))
78    }
79
80    /// Initialize amalgamation_state field (empty state).
81    pub fn init_amalgamation_state() -> amalgamation::SharedAmalgamationState {
82        amalgamation::new_shared_state()
83    }
84}
85
86/// Create the main HTTP server application
87pub fn create_http_server(state: ApiState) -> Router {
88    Router::new()
89        // Root redirect to custom Swagger UI
90        .route("/", get(root_redirect))
91
92        // Custom Swagger UI with FEAGI branding at /swagger-ui/
93        .route("/swagger-ui/", get(custom_swagger_ui))
94
95        // OpenAPI spec endpoint
96        .route("/api-docs/openapi.json", get(|| async {
97            Json(ApiDoc::openapi())
98        }))
99
100        // Python-compatible paths: /v1/* (ONLY this, matching Python exactly)
101        .nest("/v1", create_v1_router())
102
103        // Catch-all route for debugging unmatched requests
104        .fallback(|| async {
105            tracing::warn!(target: "feagi-api", "Unmatched request - 404 Not Found");
106            (StatusCode::NOT_FOUND, "404 Not Found")
107        })
108
109        // Add state
110        .with_state(state)
111
112        // Add middleware
113        .layer(middleware::from_fn(log_request_response_bodies))
114        .layer(create_cors_layer())
115        .layer(
116            TraceLayer::new_for_http()
117                .make_span_with(|request: &axum::http::Request<_>| {
118                    tracing::span!(
119                        target: "feagi-api",
120                        tracing::Level::TRACE,
121                        "request",
122                        method = %request.method(),
123                        uri = %request.uri(),
124                        version = ?request.version(),
125                    )
126                })
127                .on_request(|request: &axum::http::Request<_>, _span: &tracing::Span| {
128                    tracing::trace!(target: "feagi-api", "Incoming request: {} {}", request.method(), request.uri());
129                })
130                .on_response(|response: &axum::http::Response<_>, latency: std::time::Duration, span: &tracing::Span| {
131                    tracing::trace!(
132                        target: "feagi-api",
133                        "Response: status={}, latency={:?}",
134                        response.status(),
135                        latency
136                    );
137                    span.record("status", response.status().as_u16());
138                    span.record("latency_ms", latency.as_millis());
139                })
140                .on_body_chunk(|chunk: &axum::body::Bytes, latency: std::time::Duration, _span: &tracing::Span| {
141                    tracing::trace!(target: "feagi-api", "Response chunk: {} bytes, latency={:?}", chunk.len(), latency);
142                })
143                .on_eos(|_trailers: Option<&axum::http::HeaderMap>, stream_duration: std::time::Duration, _span: &tracing::Span| {
144                    tracing::trace!(target: "feagi-api", "Stream ended, duration={:?}", stream_duration);
145                })
146                .on_failure(|error: tower_http::classify::ServerErrorsFailureClass, latency: std::time::Duration, _span: &tracing::Span| {
147                    tracing::error!(
148                        target: "feagi-api", 
149                        "Request failed: error_class={:?}, latency={:?}", 
150                        error, latency
151                    );
152                })
153        )
154}
155
156/// Create V1 API router - Match Python structure EXACTLY
157/// Format: /v1/{module}/{snake_case_endpoint}
158fn create_v1_router() -> Router<ApiState> {
159    use crate::endpoints::agent::*; // Import agent functions for routes
160    use crate::endpoints::burst_engine;
161    use crate::endpoints::connectome;
162    use crate::endpoints::cortical_area;
163    use crate::endpoints::cortical_mapping;
164    use crate::endpoints::evolution;
165    use crate::endpoints::genome;
166    use crate::endpoints::input;
167    use crate::endpoints::insight;
168    use crate::endpoints::monitoring;
169    use crate::endpoints::morphology;
170    use crate::endpoints::network;
171    use crate::endpoints::neuroplasticity;
172    use crate::endpoints::outputs;
173    use crate::endpoints::physiology;
174    use crate::endpoints::region;
175    use crate::endpoints::simulation;
176    use crate::endpoints::training;
177    use crate::endpoints::visualization;
178    use crate::endpoints::{agent, system};
179
180    Router::new()
181        // ===== AGENT MODULE (14 endpoints) =====
182        .route("/agent/register", axum::routing::post(register_agent))
183        .route("/agent/heartbeat", axum::routing::post(heartbeat))
184        .route("/agent/list", get(list_agents))
185        .route("/agent/properties", get(get_agent_properties))
186        .route(
187            "/agent/properties/:agent_id",
188            get(agent::get_agent_properties_path),
189        )
190        .route("/agent/shared_mem", get(get_shared_memory))
191        .route("/agent/deregister", axum::routing::delete(deregister_agent))
192        .route(
193            "/agent/manual_stimulation",
194            axum::routing::post(manual_stimulation),
195        )
196        .route(
197            "/agent/fq_sampler_status",
198            get(agent::get_fq_sampler_status),
199        )
200        .route("/agent/capabilities", get(agent::get_capabilities))
201        .route("/agent/info/:agent_id", get(agent::get_agent_info))
202        .route(
203            "/agent/configure",
204            axum::routing::post(agent::post_configure),
205        )
206        .route(
207            "/agent/:agent_id/device_registrations",
208            get(agent::export_device_registrations).post(agent::import_device_registrations),
209        )
210        // ===== SYSTEM MODULE (21 endpoints) =====
211        .route("/system/health_check", get(system::get_health_check))
212        .route(
213            "/system/cortical_area_visualization_skip_rate",
214            get(system::get_cortical_area_visualization_skip_rate)
215                .put(system::set_cortical_area_visualization_skip_rate),
216        )
217        .route(
218            "/system/cortical_area_visualization_suppression_threshold",
219            get(system::get_cortical_area_visualization_suppression_threshold)
220                .put(system::set_cortical_area_visualization_suppression_threshold),
221        )
222        .route("/system/version", get(system::get_version))
223        .route("/system/versions", get(system::get_versions))
224        .route("/system/configuration", get(system::get_configuration))
225        .route(
226            "/system/user_preferences",
227            get(system::get_user_preferences).put(system::put_user_preferences),
228        )
229        .route(
230            "/system/cortical_area_types",
231            get(system::get_cortical_area_types_list),
232        )
233        .route(
234            "/system/enable_visualization_fq_sampler",
235            axum::routing::post(system::post_enable_visualization_fq_sampler),
236        )
237        .route(
238            "/system/disable_visualization_fq_sampler",
239            axum::routing::post(system::post_disable_visualization_fq_sampler),
240        )
241        .route("/system/fcl_status", get(system::get_fcl_status_system))
242        .route(
243            "/system/fcl_reset",
244            axum::routing::post(system::post_fcl_reset_system),
245        )
246        .route("/system/processes", get(system::get_processes))
247        .route("/system/unique_logs", get(system::get_unique_logs))
248        .route("/system/logs", axum::routing::post(system::post_logs))
249        .route(
250            "/system/beacon/subscribers",
251            get(system::get_beacon_subscribers),
252        )
253        .route(
254            "/system/beacon/subscribe",
255            axum::routing::post(system::post_beacon_subscribe),
256        )
257        .route(
258            "/system/beacon/unsubscribe",
259            axum::routing::delete(system::delete_beacon_unsubscribe),
260        )
261        .route(
262            "/system/global_activity_visualization",
263            get(system::get_global_activity_visualization)
264                .put(system::put_global_activity_visualization),
265        )
266        .route(
267            "/system/circuit_library_path",
268            axum::routing::post(system::post_circuit_library_path),
269        )
270        .route("/system/db/influxdb/test", get(system::get_influxdb_test))
271        .route(
272            "/system/register",
273            axum::routing::post(system::post_register_system),
274        )
275        // ===== CORTICAL_AREA MODULE (25 endpoints) =====
276        .route("/cortical_area/ipu", get(cortical_area::get_ipu))
277        .route(
278            "/cortical_area/ipu/types",
279            get(cortical_area::get_ipu_types),
280        )
281        .route("/cortical_area/opu", get(cortical_area::get_opu))
282        .route(
283            "/cortical_area/opu/types",
284            get(cortical_area::get_opu_types),
285        )
286        .route(
287            "/cortical_area/cortical_area_id_list",
288            get(cortical_area::get_cortical_area_id_list),
289        )
290        .route(
291            "/cortical_area/cortical_area_name_list",
292            get(cortical_area::get_cortical_area_name_list),
293        )
294        .route(
295            "/cortical_area/cortical_id_name_mapping",
296            get(cortical_area::get_cortical_id_name_mapping),
297        )
298        .route(
299            "/cortical_area/cortical_types",
300            get(cortical_area::get_cortical_types),
301        )
302        .route(
303            "/cortical_area/cortical_map_detailed",
304            get(cortical_area::get_cortical_map_detailed),
305        )
306        .route(
307            "/cortical_area/cortical_locations_2d",
308            get(cortical_area::get_cortical_locations_2d),
309        )
310        .route(
311            "/cortical_area/cortical_area/geometry",
312            get(cortical_area::get_cortical_area_geometry),
313        )
314        .route(
315            "/cortical_area/cortical_visibility",
316            get(cortical_area::get_cortical_visibility),
317        )
318        .route(
319            "/cortical_area/cortical_name_location",
320            axum::routing::post(cortical_area::post_cortical_name_location),
321        )
322        .route(
323            "/cortical_area/cortical_area_properties",
324            axum::routing::post(cortical_area::post_cortical_area_properties),
325        )
326        .route(
327            "/cortical_area/multi/cortical_area_properties",
328            axum::routing::post(cortical_area::post_multi_cortical_area_properties),
329        )
330        .route(
331            "/cortical_area/cortical_area",
332            axum::routing::post(cortical_area::post_cortical_area)
333                .put(cortical_area::put_cortical_area)
334                .delete(cortical_area::delete_cortical_area),
335        )
336        .route(
337            "/cortical_area/custom_cortical_area",
338            axum::routing::post(cortical_area::post_custom_cortical_area),
339        )
340        .route(
341            "/cortical_area/clone",
342            axum::routing::post(cortical_area::post_clone),
343        )
344        .route(
345            "/cortical_area/multi/cortical_area",
346            put(cortical_area::put_multi_cortical_area)
347                .delete(cortical_area::delete_multi_cortical_area),
348        )
349        .route("/cortical_area/coord_2d", put(cortical_area::put_coord_2d))
350        .route(
351            "/cortical_area/suppress_cortical_visibility",
352            put(cortical_area::put_suppress_cortical_visibility),
353        )
354        .route("/cortical_area/reset", put(cortical_area::put_reset))
355        .route(
356            "/cortical_area/visualization",
357            get(cortical_area::get_visualization),
358        )
359        .route(
360            "/cortical_area/batch_operations",
361            axum::routing::post(cortical_area::post_batch_operations),
362        )
363        .route("/cortical_area/ipu/list", get(cortical_area::get_ipu_list))
364        .route("/cortical_area/opu/list", get(cortical_area::get_opu_list))
365        .route(
366            "/cortical_area/coordinates_3d",
367            put(cortical_area::put_coordinates_3d),
368        )
369        .route(
370            "/cortical_area/bulk_delete",
371            axum::routing::delete(cortical_area::delete_bulk),
372        )
373        .route(
374            "/cortical_area/resize",
375            axum::routing::post(cortical_area::post_resize),
376        )
377        .route(
378            "/cortical_area/reposition",
379            axum::routing::post(cortical_area::post_reposition),
380        )
381        .route(
382            "/cortical_area/voxel_neurons",
383            axum::routing::post(cortical_area::post_voxel_neurons),
384        )
385        .route(
386            "/cortical_area/cortical_area_index_list",
387            get(cortical_area::get_cortical_area_index_list),
388        )
389        .route(
390            "/cortical_area/cortical_idx_mapping",
391            get(cortical_area::get_cortical_idx_mapping),
392        )
393        .route(
394            "/cortical_area/mapping_restrictions",
395            get(cortical_area::get_mapping_restrictions_query)
396                .post(cortical_area::post_mapping_restrictions),
397        )
398        .route(
399            "/cortical_area/:cortical_id/memory_usage",
400            get(cortical_area::get_memory_usage),
401        )
402        .route(
403            "/cortical_area/:cortical_id/neuron_count",
404            get(cortical_area::get_area_neuron_count),
405        )
406        .route(
407            "/cortical_area/cortical_type_options",
408            axum::routing::post(cortical_area::post_cortical_type_options),
409        )
410        .route(
411            "/cortical_area/mapping_restrictions_between_areas",
412            axum::routing::post(cortical_area::post_mapping_restrictions_between_areas),
413        )
414        .route("/cortical_area/coord_3d", put(cortical_area::put_coord_3d))
415        // ===== MORPHOLOGY MODULE (14 endpoints) =====
416        .route(
417            "/morphology/morphology_list",
418            get(morphology::get_morphology_list),
419        )
420        .route(
421            "/morphology/morphology_types",
422            get(morphology::get_morphology_types),
423        )
424        .route("/morphology/list/types", get(morphology::get_list_types))
425        .route(
426            "/morphology/morphologies",
427            get(morphology::get_morphologies),
428        )
429        .route(
430            "/morphology/morphology",
431            axum::routing::post(morphology::post_morphology)
432                .put(morphology::put_morphology)
433                .delete(morphology::delete_morphology_by_name),
434        )
435        .route(
436            "/morphology/morphology_properties",
437            axum::routing::post(morphology::post_morphology_properties),
438        )
439        .route(
440            "/morphology/morphology_usage",
441            axum::routing::post(morphology::post_morphology_usage),
442        )
443        .route("/morphology/list", get(morphology::get_list))
444        .route("/morphology/info/:morphology_id", get(morphology::get_info))
445        .route(
446            "/morphology/create",
447            axum::routing::post(morphology::post_create),
448        )
449        .route(
450            "/morphology/update",
451            axum::routing::put(morphology::put_update),
452        )
453        .route(
454            "/morphology/delete/:morphology_id",
455            axum::routing::delete(morphology::delete_morphology),
456        )
457        // ===== REGION MODULE (12 endpoints) =====
458        .route("/region/regions_members", get(region::get_regions_members))
459        .route(
460            "/region/region",
461            axum::routing::post(region::post_region)
462                .put(region::put_region)
463                .delete(region::delete_region),
464        )
465        .route("/region/clone", axum::routing::post(region::post_clone))
466        .route(
467            "/region/relocate_members",
468            put(region::put_relocate_members),
469        )
470        .route(
471            "/region/region_and_members",
472            axum::routing::delete(region::delete_region_and_members),
473        )
474        .route("/region/regions", get(region::get_regions))
475        .route("/region/region_titles", get(region::get_region_titles))
476        .route("/region/region/:region_id", get(region::get_region_detail))
477        .route(
478            "/region/change_region_parent",
479            put(region::put_change_region_parent),
480        )
481        .route(
482            "/region/change_cortical_area_region",
483            put(region::put_change_cortical_area_region),
484        )
485        // ===== CORTICAL_MAPPING MODULE (8 endpoints) =====
486        .route(
487            "/cortical_mapping/afferents",
488            axum::routing::post(cortical_mapping::post_afferents),
489        )
490        .route(
491            "/cortical_mapping/efferents",
492            axum::routing::post(cortical_mapping::post_efferents),
493        )
494        .route(
495            "/cortical_mapping/mapping_properties",
496            axum::routing::post(cortical_mapping::post_mapping_properties)
497                .put(cortical_mapping::put_mapping_properties),
498        )
499        .route(
500            "/cortical_mapping/mapping",
501            get(cortical_mapping::get_mapping).delete(cortical_mapping::delete_mapping),
502        )
503        .route(
504            "/cortical_mapping/mapping_list",
505            get(cortical_mapping::get_mapping_list),
506        )
507        .route(
508            "/cortical_mapping/batch_update",
509            axum::routing::post(cortical_mapping::post_batch_update),
510        )
511        .route(
512            "/cortical_mapping/mapping",
513            axum::routing::post(cortical_mapping::post_mapping).put(cortical_mapping::put_mapping),
514        )
515        // ===== CONNECTOME MODULE (21 endpoints) =====
516        .route(
517            "/connectome/cortical_areas/list/detailed",
518            get(connectome::get_cortical_areas_list_detailed),
519        )
520        .route(
521            "/connectome/properties/dimensions",
522            get(connectome::get_properties_dimensions),
523        )
524        .route(
525            "/connectome/properties/mappings",
526            get(connectome::get_properties_mappings),
527        )
528        .route("/connectome/snapshot", get(connectome::get_snapshot))
529        .route("/connectome/stats", get(connectome::get_stats))
530        .route(
531            "/connectome/batch_neuron_operations",
532            axum::routing::post(connectome::post_batch_neuron_operations),
533        )
534        .route(
535            "/connectome/batch_synapse_operations",
536            axum::routing::post(connectome::post_batch_synapse_operations),
537        )
538        .route(
539            "/connectome/neuron_count",
540            get(connectome::get_neuron_count),
541        )
542        .route(
543            "/connectome/synapse_count",
544            get(connectome::get_synapse_count),
545        )
546        .route("/connectome/paths", get(connectome::get_paths))
547        .route(
548            "/connectome/cumulative_stats",
549            get(connectome::get_cumulative_stats),
550        )
551        .route(
552            "/connectome/area_details",
553            get(connectome::get_area_details),
554        )
555        .route(
556            "/connectome/rebuild",
557            axum::routing::post(connectome::post_rebuild),
558        )
559        .route("/connectome/structure", get(connectome::get_structure))
560        .route(
561            "/connectome/clear",
562            axum::routing::post(connectome::post_clear),
563        )
564        .route("/connectome/validation", get(connectome::get_validation))
565        .route("/connectome/topology", get(connectome::get_topology))
566        .route(
567            "/connectome/optimize",
568            axum::routing::post(connectome::post_optimize),
569        )
570        .route(
571            "/connectome/connectivity_matrix",
572            get(connectome::get_connectivity_matrix),
573        )
574        .route(
575            "/connectome/neurons/batch",
576            axum::routing::post(connectome::post_neurons_batch),
577        )
578        .route(
579            "/connectome/synapses/batch",
580            axum::routing::post(connectome::post_synapses_batch),
581        )
582        .route(
583            "/connectome/cortical_areas/list/summary",
584            get(connectome::get_cortical_areas_list_summary),
585        )
586        .route(
587            "/connectome/cortical_areas/list/transforming",
588            get(connectome::get_cortical_areas_list_transforming),
589        )
590        .route(
591            "/connectome/cortical_area/list/types",
592            get(connectome::get_cortical_area_list_types),
593        )
594        .route(
595            "/connectome/cortical_area/:cortical_id/neurons",
596            get(connectome::get_cortical_area_neurons),
597        )
598        .route(
599            "/connectome/:cortical_area_id/synapses",
600            get(connectome::get_area_synapses),
601        )
602        .route(
603            "/connectome/cortical_info/:cortical_area",
604            get(connectome::get_cortical_info),
605        )
606        .route(
607            "/connectome/stats/cortical/cumulative/:cortical_area",
608            get(connectome::get_stats_cortical_cumulative),
609        )
610        .route(
611            "/connectome/neuron/:neuron_id/properties",
612            get(connectome::get_neuron_properties_by_id),
613        )
614        .route(
615            "/connectome/neuron_properties",
616            get(connectome::get_neuron_properties_query),
617        )
618        .route(
619            "/connectome/neuron_properties_at",
620            get(connectome::get_neuron_properties_at_query),
621        )
622        .route(
623            "/connectome/area_neurons",
624            get(connectome::get_area_neurons_query),
625        )
626        .route(
627            "/connectome/fire_queue/:cortical_area",
628            get(connectome::get_fire_queue_area),
629        )
630        .route(
631            "/connectome/plasticity",
632            get(connectome::get_plasticity_info),
633        )
634        .route("/connectome/path", get(connectome::get_path_query))
635        .route(
636            "/connectome/download",
637            get(connectome::get_download_connectome),
638        )
639        .route(
640            "/connectome/download-cortical-area/:cortical_area",
641            get(connectome::get_download_cortical_area),
642        )
643        .route(
644            "/connectome/upload",
645            axum::routing::post(connectome::post_upload_connectome),
646        )
647        .route(
648            "/connectome/upload-cortical-area",
649            axum::routing::post(connectome::post_upload_cortical_area),
650        )
651        // ===== BURST_ENGINE MODULE (14 endpoints) =====
652        .route(
653            "/burst_engine/simulation_timestep",
654            get(burst_engine::get_simulation_timestep).post(burst_engine::post_simulation_timestep),
655        )
656        .route("/burst_engine/fcl", get(burst_engine::get_fcl))
657        .route(
658            "/burst_engine/fcl/neuron",
659            get(burst_engine::get_fcl_neuron),
660        )
661        .route(
662            "/burst_engine/fire_queue",
663            get(burst_engine::get_fire_queue),
664        )
665        .route(
666            "/burst_engine/fire_queue/neuron",
667            get(burst_engine::get_fire_queue_neuron),
668        )
669        .route(
670            "/burst_engine/fcl_reset",
671            axum::routing::post(burst_engine::post_fcl_reset),
672        )
673        .route(
674            "/burst_engine/fcl_status",
675            get(burst_engine::get_fcl_status),
676        )
677        .route(
678            "/burst_engine/fcl_sampler/config",
679            get(burst_engine::get_fcl_sampler_config).post(burst_engine::post_fcl_sampler_config),
680        )
681        .route(
682            "/burst_engine/fcl_sampler/area/:area_id/sample_rate",
683            get(burst_engine::get_area_fcl_sample_rate)
684                .post(burst_engine::post_area_fcl_sample_rate),
685        )
686        .route(
687            "/burst_engine/fire_ledger/default_window_size",
688            get(burst_engine::get_fire_ledger_default_window_size)
689                .put(burst_engine::put_fire_ledger_default_window_size),
690        )
691        .route(
692            "/burst_engine/fire_ledger/areas_window_config",
693            get(burst_engine::get_fire_ledger_areas_window_config),
694        )
695        .route("/burst_engine/stats", get(burst_engine::get_stats))
696        .route("/burst_engine/status", get(burst_engine::get_status))
697        .route(
698            "/burst_engine/control",
699            axum::routing::post(burst_engine::post_control),
700        )
701        .route(
702            "/burst_engine/burst_counter",
703            get(burst_engine::get_burst_counter),
704        )
705        .route(
706            "/burst_engine/start",
707            axum::routing::post(burst_engine::post_start),
708        )
709        .route(
710            "/burst_engine/stop",
711            axum::routing::post(burst_engine::post_stop),
712        )
713        .route(
714            "/burst_engine/hold",
715            axum::routing::post(burst_engine::post_hold),
716        )
717        .route(
718            "/burst_engine/resume",
719            axum::routing::post(burst_engine::post_resume),
720        )
721        .route(
722            "/burst_engine/config",
723            get(burst_engine::get_config).put(burst_engine::put_config),
724        )
725        .route(
726            "/burst_engine/fire_ledger/area/:area_id/window_size",
727            get(burst_engine::get_fire_ledger_area_window_size)
728                .put(burst_engine::put_fire_ledger_area_window_size),
729        )
730        .route(
731            "/burst_engine/fire_ledger/area/:area_id/history",
732            get(burst_engine::get_fire_ledger_history),
733        )
734        .route(
735            "/burst_engine/membrane_potentials",
736            get(burst_engine::get_membrane_potentials).put(burst_engine::put_membrane_potentials),
737        )
738        .route(
739            "/burst_engine/frequency_status",
740            get(burst_engine::get_frequency_status),
741        )
742        .route(
743            "/burst_engine/measure_frequency",
744            axum::routing::post(burst_engine::post_measure_frequency),
745        )
746        .route(
747            "/burst_engine/frequency_history",
748            get(burst_engine::get_frequency_history),
749        )
750        .route(
751            "/burst_engine/force_connectome_integration",
752            axum::routing::post(burst_engine::post_force_connectome_integration),
753        )
754        // ===== GENOME MODULE (22 endpoints) =====
755        .route("/genome/file_name", get(genome::get_file_name))
756        .route("/genome/circuits", get(genome::get_circuits))
757        .route(
758            "/genome/amalgamation_destination",
759            axum::routing::post(genome::post_amalgamation_destination),
760        )
761        .route(
762            "/genome/amalgamation_cancellation",
763            axum::routing::delete(genome::delete_amalgamation_cancellation),
764        )
765        .route(
766            "/feagi/genome/append",
767            axum::routing::post(genome::post_genome_append),
768        )
769        .route(
770            "/genome/upload/barebones",
771            axum::routing::post(genome::post_upload_barebones_genome),
772        )
773        .route(
774            "/genome/upload/essential",
775            axum::routing::post(genome::post_upload_essential_genome),
776        )
777        .route("/genome/name", get(genome::get_name))
778        .route("/genome/timestamp", get(genome::get_timestamp))
779        .route("/genome/save", axum::routing::post(genome::post_save))
780        .route("/genome/load", axum::routing::post(genome::post_load))
781        .route("/genome/upload", axum::routing::post(genome::post_upload))
782        .route("/genome/download", get(genome::get_download))
783        .route("/genome/properties", get(genome::get_properties))
784        .route(
785            "/genome/validate",
786            axum::routing::post(genome::post_validate),
787        )
788        .route(
789            "/genome/transform",
790            axum::routing::post(genome::post_transform),
791        )
792        .route("/genome/clone", axum::routing::post(genome::post_clone))
793        .route("/genome/reset", axum::routing::post(genome::post_reset))
794        .route("/genome/metadata", get(genome::get_metadata))
795        .route("/genome/merge", axum::routing::post(genome::post_merge))
796        .route("/genome/diff", get(genome::get_diff))
797        .route(
798            "/genome/export_format",
799            axum::routing::post(genome::post_export_format),
800        )
801        .route("/genome/amalgamation", get(genome::get_amalgamation))
802        .route(
803            "/genome/amalgamation_history",
804            get(genome::get_amalgamation_history_exact),
805        )
806        .route(
807            "/genome/cortical_template",
808            get(genome::get_cortical_template),
809        )
810        .route("/genome/defaults/files", get(genome::get_defaults_files))
811        .route("/genome/download_region", get(genome::get_download_region))
812        .route("/genome/genome_number", get(genome::get_genome_number))
813        .route(
814            "/genome/amalgamation_by_filename",
815            axum::routing::post(genome::post_amalgamation_by_filename),
816        )
817        .route(
818            "/genome/amalgamation_by_payload",
819            axum::routing::post(genome::post_amalgamation_by_payload),
820        )
821        .route(
822            "/genome/amalgamation_by_upload",
823            axum::routing::post(genome::post_amalgamation_by_upload),
824        )
825        .route(
826            "/genome/append-file",
827            axum::routing::post(genome::post_append_file),
828        )
829        .route(
830            "/genome/upload/file",
831            axum::routing::post(genome::post_upload_file),
832        )
833        .route(
834            "/genome/upload/file/edit",
835            axum::routing::post(genome::post_upload_file_edit),
836        )
837        .route(
838            "/genome/upload/string",
839            axum::routing::post(genome::post_upload_string),
840        )
841        // ===== NEUROPLASTICITY MODULE (7 endpoints) =====
842        .route(
843            "/neuroplasticity/plasticity_queue_depth",
844            get(neuroplasticity::get_plasticity_queue_depth)
845                .put(neuroplasticity::put_plasticity_queue_depth),
846        )
847        .route("/neuroplasticity/status", get(neuroplasticity::get_status))
848        .route(
849            "/neuroplasticity/transforming",
850            get(neuroplasticity::get_transforming),
851        )
852        .route(
853            "/neuroplasticity/configure",
854            axum::routing::post(neuroplasticity::post_configure),
855        )
856        .route(
857            "/neuroplasticity/enable/:area_id",
858            axum::routing::post(neuroplasticity::post_enable_area),
859        )
860        .route(
861            "/neuroplasticity/disable/:area_id",
862            axum::routing::post(neuroplasticity::post_disable_area),
863        )
864        // ===== INSIGHT MODULE (6 endpoints) =====
865        .route(
866            "/insight/neurons/membrane_potential_status",
867            axum::routing::post(insight::post_neurons_membrane_potential_status),
868        )
869        .route(
870            "/insight/neuron/synaptic_potential_status",
871            axum::routing::post(insight::post_neuron_synaptic_potential_status),
872        )
873        .route(
874            "/insight/neurons/membrane_potential_set",
875            axum::routing::post(insight::post_neurons_membrane_potential_set),
876        )
877        .route(
878            "/insight/neuron/synaptic_potential_set",
879            axum::routing::post(insight::post_neuron_synaptic_potential_set),
880        )
881        .route("/insight/analytics", get(insight::get_analytics))
882        .route("/insight/data", get(insight::get_data))
883        // ===== INPUT MODULE (4 endpoints) =====
884        .route(
885            "/input/vision",
886            get(input::get_vision).post(input::post_vision),
887        )
888        .route("/input/sources", get(input::get_sources))
889        .route(
890            "/input/configure",
891            axum::routing::post(input::post_configure),
892        )
893        // ===== OUTPUTS MODULE (2 endpoints) - Python uses /v1/output (singular)
894        .route("/output/targets", get(outputs::get_targets))
895        .route(
896            "/output/configure",
897            axum::routing::post(outputs::post_configure),
898        )
899        // ===== PHYSIOLOGY MODULE (2 endpoints) =====
900        .route(
901            "/physiology/",
902            get(physiology::get_physiology).put(physiology::put_physiology),
903        )
904        // ===== SIMULATION MODULE (6 endpoints) =====
905        .route(
906            "/simulation/upload/string",
907            axum::routing::post(simulation::post_stimulation_upload),
908        )
909        .route(
910            "/simulation/reset",
911            axum::routing::post(simulation::post_reset),
912        )
913        .route("/simulation/status", get(simulation::get_status))
914        .route("/simulation/stats", get(simulation::get_stats))
915        .route(
916            "/simulation/config",
917            axum::routing::post(simulation::post_config),
918        )
919        // ===== TRAINING MODULE (25 endpoints) =====
920        .route("/training/shock", axum::routing::post(training::post_shock))
921        .route("/training/shock/options", get(training::get_shock_options))
922        .route("/training/shock/status", get(training::get_shock_status))
923        .route(
924            "/training/shock/activate",
925            axum::routing::post(training::post_shock_activate),
926        )
927        .route(
928            "/training/reward/intensity",
929            axum::routing::post(training::post_reward_intensity),
930        )
931        .route(
932            "/training/reward",
933            axum::routing::post(training::post_reward),
934        )
935        .route(
936            "/training/punishment/intensity",
937            axum::routing::post(training::post_punishment_intensity),
938        )
939        .route(
940            "/training/punishment",
941            axum::routing::post(training::post_punishment),
942        )
943        .route(
944            "/training/gameover",
945            axum::routing::post(training::post_gameover),
946        )
947        .route("/training/brain_fitness", get(training::get_brain_fitness))
948        .route(
949            "/training/fitness_criteria",
950            get(training::get_fitness_criteria)
951                .put(training::put_fitness_criteria)
952                .post(training::post_fitness_criteria),
953        )
954        .route(
955            "/training/fitness_stats",
956            get(training::get_fitness_stats)
957                .put(training::put_fitness_stats)
958                .delete(training::delete_fitness_stats),
959        )
960        .route(
961            "/training/reset_fitness_stats",
962            axum::routing::delete(training::delete_reset_fitness_stats),
963        )
964        .route(
965            "/training/training_report",
966            get(training::get_training_report),
967        )
968        .route("/training/status", get(training::get_status))
969        .route("/training/stats", get(training::get_stats))
970        .route(
971            "/training/config",
972            axum::routing::post(training::post_config),
973        )
974        // ===== VISUALIZATION MODULE (4 endpoints) =====
975        .route(
976            "/visualization/register_client",
977            axum::routing::post(visualization::post_register_client),
978        )
979        .route(
980            "/visualization/unregister_client",
981            axum::routing::post(visualization::post_unregister_client),
982        )
983        .route(
984            "/visualization/heartbeat",
985            axum::routing::post(visualization::post_heartbeat),
986        )
987        .route("/visualization/status", get(visualization::get_status))
988        // ===== MONITORING MODULE (4 endpoints) =====
989        .route("/monitoring/status", get(monitoring::get_status))
990        .route("/monitoring/metrics", get(monitoring::get_metrics))
991        .route("/monitoring/data", get(monitoring::get_data))
992        .route("/monitoring/performance", get(monitoring::get_performance))
993        // ===== EVOLUTION MODULE (3 endpoints) =====
994        .route("/evolution/status", get(evolution::get_status))
995        .route(
996            "/evolution/config",
997            axum::routing::post(evolution::post_config),
998        )
999        // ===== SNAPSHOT MODULE (12 endpoints) =====
1000        // TODO: Implement snapshot endpoints
1001        // .route("/snapshot/create", axum::routing::post(snapshot::post_create))
1002        // .route("/snapshot/restore", axum::routing::post(snapshot::post_restore))
1003        // .route("/snapshot/", get(snapshot::get_list))
1004        // .route("/snapshot/:snapshot_id", axum::routing::delete(snapshot::delete_snapshot))
1005        // .route("/snapshot/:snapshot_id/artifact/:fmt", get(snapshot::get_artifact))
1006        // .route("/snapshot/compare", axum::routing::post(snapshot::post_compare))
1007        // .route("/snapshot/upload", axum::routing::post(snapshot::post_upload))
1008        // // Python uses /v1/snapshots/* (note the S)
1009        // .route("/snapshots/connectome", axum::routing::post(snapshot::post_snapshots_connectome))
1010        // .route("/snapshots/connectome/:snapshot_id/restore", axum::routing::post(snapshot::post_snapshots_connectome_restore))
1011        // .route("/snapshots/:snapshot_id/restore", axum::routing::post(snapshot::post_snapshots_restore))
1012        // .route("/snapshots/:snapshot_id", axum::routing::delete(snapshot::delete_snapshots_by_id))
1013        // .route("/snapshots/:snapshot_id/artifact/:fmt", get(snapshot::get_snapshots_artifact))
1014        // ===== NETWORK MODULE (3 endpoints) =====
1015        .route("/network/status", get(network::get_status))
1016        .route("/network/config", axum::routing::post(network::post_config))
1017}
1018
1019/// OpenAPI spec handler
1020#[allow(dead_code)] // In development - will be wired to OpenAPI route
1021async fn openapi_spec() -> Json<utoipa::openapi::OpenApi> {
1022    Json(ApiDoc::openapi())
1023}
1024
1025// ============================================================================
1026// CORS CONFIGURATION
1027// ============================================================================
1028
1029/// Create CORS layer for the API
1030///
1031/// TODO: Configure for production:
1032/// - Restrict allowed origins
1033/// - Allowed methods restricted
1034/// - Credentials support as needed
1035fn create_cors_layer() -> CorsLayer {
1036    CorsLayer::new()
1037        .allow_origin(Any)
1038        .allow_methods(Any)
1039        .allow_headers(Any)
1040}
1041
1042/// Middleware to log request and response bodies for debugging
1043async fn log_request_response_bodies(
1044    request: Request<Body>,
1045    next: Next,
1046) -> Result<Response, StatusCode> {
1047    let (parts, body) = request.into_parts();
1048
1049    // Only log bodies for POST/PUT/PATCH/DELETE requests
1050    let should_log_request = matches!(parts.method.as_str(), "POST" | "PUT" | "PATCH" | "DELETE");
1051
1052    let body_bytes = if should_log_request {
1053        // Collect body bytes
1054        match body.collect().await {
1055            Ok(collected) => {
1056                let bytes = collected.to_bytes();
1057                // Log request body if it's JSON
1058                if let Ok(body_str) = String::from_utf8(bytes.to_vec()) {
1059                    if !body_str.is_empty() {
1060                        tracing::trace!(target: "feagi-api", "Request body: {}", body_str);
1061                    }
1062                }
1063                bytes
1064            }
1065            Err(_) => {
1066                return Err(StatusCode::INTERNAL_SERVER_ERROR);
1067            }
1068        }
1069    } else {
1070        axum::body::Bytes::new()
1071    };
1072
1073    // Reconstruct request with original body
1074    let request = Request::from_parts(parts, Body::from(body_bytes));
1075
1076    // Call the next handler
1077    let response = next.run(request).await;
1078
1079    // Log response body
1080    let (parts, body) = response.into_parts();
1081
1082    match body.collect().await {
1083        Ok(collected) => {
1084            let bytes = collected.to_bytes();
1085            // Log response body if it's JSON and not too large
1086            if bytes.len() < 10000 {
1087                // Only log responses < 10KB
1088                if let Ok(body_str) = String::from_utf8(bytes.to_vec()) {
1089                    if !body_str.is_empty() && body_str.starts_with('{') {
1090                        tracing::trace!(target: "feagi-api", "Response body: {}", body_str);
1091                    }
1092                }
1093            }
1094            // Reconstruct response
1095            Ok(Response::from_parts(parts, Body::from(bytes)))
1096        }
1097        Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
1098    }
1099}
1100
1101// ============================================================================
1102// HELPER HANDLERS
1103// ============================================================================
1104
1105/// Root redirect handler - redirects to Swagger UI
1106async fn root_redirect() -> Redirect {
1107    Redirect::permanent("/swagger-ui/")
1108}
1109
1110// Custom Swagger UI with FEAGI branding and dark/light themes
1111// Embedded from templates/custom-swagger-ui.html at compile time
1112async fn custom_swagger_ui() -> Html<&'static str> {
1113    const CUSTOM_SWAGGER_HTML: &str = include_str!("../../../templates/custom-swagger-ui.html");
1114    Html(CUSTOM_SWAGGER_HTML)
1115}
1116
1117// ============================================================================
1118// PLACEHOLDER HANDLERS (for endpoints not yet implemented)
1119// ============================================================================
1120
1121/// Placeholder handler for unimplemented endpoints
1122/// Returns 501 Not Implemented with a clear message
1123#[allow(dead_code)] // In development - will be used for placeholder routes
1124async fn placeholder_handler(State(_state): State<ApiState>) -> Response {
1125    (
1126        StatusCode::NOT_IMPLEMENTED,
1127        Json(serde_json::json!({
1128            "error": "Not yet implemented",
1129            "message": "This endpoint is registered but not yet implemented in Rust. See Python implementation."
1130        }))
1131    ).into_response()
1132}
1133
1134/// Placeholder health check - returns basic response
1135#[allow(dead_code)] // In development - will be used for basic health route
1136async fn placeholder_health_check(State(_state): State<ApiState>) -> Response {
1137    (
1138        StatusCode::OK,
1139        Json(serde_json::json!({
1140            "status": "ok",
1141            "message": "Health check placeholder - Python-compatible path structure confirmed",
1142            "burst_engine": false,
1143            "brain_readiness": false
1144        })),
1145    )
1146        .into_response()
1147}