vex-api 1.7.0

Industry-grade HTTP API gateway for VEX Protocol
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
//! API routes for VEX endpoints

use axum::response::sse as ax_sse;
use axum::{
    extract::{Extension, Path, State},
    routing::{get, post},
    Json, Router,
};
use futures::stream::{self, Stream};
use serde::{Deserialize, Serialize};
use std::convert::Infallible;
use uuid::Uuid;

use crate::auth::Claims;
use crate::error::{ApiError, ApiResult};
use crate::sanitize::{sanitize_name, sanitize_prompt_async, sanitize_role};
use crate::state::AppState;
use utoipa::OpenApi;
use vex_core::segment::ContinuationToken;
use vex_core::{ActorType, AuditEventType};
use vex_persist::coordination::{
    CoordinationRecord, CoordinationStatus, CoordinationStore, PersistentCoordinationStore,
};
use vex_persist::{AgentStore, AuditStore};

/// Health check response
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct HealthResponse {
    pub status: String,
    pub version: String,
    pub timestamp: chrono::DateTime<chrono::Utc>,
    /// Active persistence backend: "sqlite" or "postgres"
    pub db_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub components: Option<ComponentHealth>,
}

/// Component health status
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct ComponentHealth {
    pub database: ComponentStatus,
    pub queue: ComponentStatus,
}

/// Individual component status
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct ComponentStatus {
    pub status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub latency_ms: Option<u64>,
}

/// Basic health check handler (lightweight)
#[utoipa::path(
    get,
    path = "/health",
    responses(
        (status = 200, description = "Basic health check", body = HealthResponse)
    )
)]
pub async fn health(State(state): State<AppState>) -> Json<HealthResponse> {
    Json(HealthResponse {
        status: "healthy".to_string(),
        version: env!("CARGO_PKG_VERSION").to_string(),
        timestamp: chrono::Utc::now(),
        db_type: state.db().name().to_string(),
        components: None,
    })
}

/// Detailed health check with database connectivity
#[utoipa::path(
    get,
    path = "/health/detailed",
    responses(
        (status = 200, description = "Detailed health check with component status", body = HealthResponse)
    )
)]
pub async fn health_detailed(State(state): State<AppState>) -> Json<HealthResponse> {
    let start = std::time::Instant::now();

    // Check database
    let db_healthy = state.db().is_healthy().await;
    let db_latency = start.elapsed().as_millis() as u64;

    // Queue is always healthy (in-memory)
    let queue_status = ComponentStatus {
        status: "healthy".to_string(),
        latency_ms: Some(0),
    };

    let db_status = ComponentStatus {
        status: if db_healthy { "healthy" } else { "unhealthy" }.to_string(),
        latency_ms: Some(db_latency),
    };

    let overall_status = if db_healthy { "healthy" } else { "degraded" };

    Json(HealthResponse {
        status: overall_status.to_string(),
        version: env!("CARGO_PKG_VERSION").to_string(),
        timestamp: chrono::Utc::now(),
        db_type: state.db().name().to_string(),
        components: Some(ComponentHealth {
            database: db_status,
            queue: queue_status,
        }),
    })
}

/// Agent creation request
#[derive(Debug, Deserialize, utoipa::ToSchema)]
pub struct CreateAgentRequest {
    pub name: String,
    pub role: String,
    #[serde(default = "default_max_depth")]
    pub max_depth: u8,
    #[serde(default)]
    pub spawn_shadow: bool,
}

fn default_max_depth() -> u8 {
    3
}

/// Agent response
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct AgentResponse {
    pub id: Uuid,
    pub name: String,
    pub role: String,
    pub generation: u32,
    pub fitness: f64,
    pub created_at: chrono::DateTime<chrono::Utc>,
}

/// Create agent handler
#[utoipa::path(
    post,
    path = "/api/v1/agents",
    request_body = CreateAgentRequest,
    responses(
        (status = 200, description = "Agent created successfully", body = AgentResponse),
        (status = 403, description = "Insufficient permissions"),
        (status = 400, description = "Invalid input")
    ),
    security(
        ("jwt" = [])
    )
)]
pub async fn create_agent(
    Extension(claims): Extension<Claims>,
    State(state): State<AppState>,
    Json(req): Json<CreateAgentRequest>,
) -> ApiResult<Json<AgentResponse>> {
    // Validate role access
    if !claims.has_role("user") {
        return Err(ApiError::Forbidden("Insufficient permissions".to_string()));
    }

    // Sanitize inputs
    let name = sanitize_name(&req.name)
        .map_err(|e| ApiError::Validation(format!("Invalid name: {}", e)))?;
    let role = sanitize_role(&req.role)
        .map_err(|e| ApiError::Validation(format!("Invalid role: {}", e)))?;

    // Validate depth bounds (Fix #13)
    if req.max_depth > 10 {
        return Err(ApiError::Validation(
            "max_depth exceeds safety limit of 10".to_string(),
        ));
    }

    // Create agent with sanitized inputs
    let config = vex_core::AgentConfig {
        name: name.clone(),
        role: role.clone(),
        max_depth: req.max_depth,
        spawn_shadow: req.spawn_shadow,
    };
    let agent = vex_core::Agent::new(config);

    // Persist agent with tenant isolation
    let store = AgentStore::new(state.db());

    store
        .save(&claims.sub, &agent)
        .await
        .map_err(|e| ApiError::Internal(format!("Failed to save agent: {}", e)))?;

    // Record metrics
    state.metrics().record_agent_created();

    Ok(Json(AgentResponse {
        id: agent.id,
        name: req.name,
        role: req.role,
        generation: agent.generation,
        fitness: agent.fitness,
        created_at: chrono::Utc::now(),
    }))
}

/// Execute agent request
#[derive(Debug, Deserialize, utoipa::ToSchema)]
pub struct ExecuteRequest {
    pub prompt: String,
    pub context_id: Option<String>,
    #[serde(default)]
    pub enable_adversarial: bool,
    #[serde(default)]
    pub enable_self_correction: bool,
    #[serde(default = "default_max_rounds")]
    pub max_debate_rounds: u32,
    pub continuation_token: Option<ContinuationToken>,
}

fn default_max_rounds() -> u32 {
    3
}

/// Execute agent response
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct ExecuteResponse {
    pub agent_id: Uuid,
    pub response: String,
    pub verified: bool,
    pub confidence: f64,
    pub context_hash: String,
    pub latency_ms: u64,
    /// The CHORA Witness Receipt (v0.2.0)
    pub witness_receipt: Option<String>,
    /// Merkle Tree root of the execution trace (available when polling job result)
    pub merkle_root: Option<String>,
    /// Signed continuation artifact (Phase 2 Enforcement Loop)
    pub continuation_token: Option<ContinuationToken>,
}

/// Execute agent handler
#[utoipa::path(
    post,
    path = "/api/v1/agents/{id}/execute",
    params(
        ("id" = Uuid, Path, description = "Agent ID")
    ),
    request_body = ExecuteRequest,
    responses(
        (status = 200, description = "Job queued successfully", body = ExecuteResponse),
        (status = 404, description = "Agent not found")
    ),
    security(
        ("jwt" = [])
    )
)]
pub async fn execute_agent(
    Extension(claims): Extension<Claims>,
    State(state): State<AppState>,
    Path(agent_id): Path<Uuid>,
    Json(req): Json<ExecuteRequest>,
) -> ApiResult<Json<ExecuteResponse>> {
    let start = std::time::Instant::now();
    // Sanitize and validate prompt with async safety judge
    let llm = state.llm();
    let prompt = sanitize_prompt_async(&req.prompt, Some(&*llm)).await?;

    // Phase 2.1: Generate IntentData and segmented commitment (trace_root)
    let trace_root_hash = vex_core::Hash::digest(prompt.as_bytes());
    let intent = vex_core::IntentData::Transparent {
        request_sha256: trace_root_hash.to_hex(),
        confidence: 1.0,
        capabilities: vec!["api-execution".to_string()],
        magpie_source: None,
        continuation_token: None,
        metadata: vex_core::segment::SchemaValue(serde_json::Value::Null),
    };
    let intent_hash = intent
        .to_jcs_hash()
        .map_err(|e| ApiError::Internal(format!("JCS Hashing error: {}", e)))?;

    tracing::info!(
        intent_hash = %intent_hash.to_hex(),
        trace_root = %trace_root_hash.to_hex(),
        "Intent segment generated for v0.2.0 Singularity"
    );

    // Phase 2.2: Continuation Authority (Enforcement Loop)
    // If the client provides a token, they are attempting to resolve an escalation.
    let mut authorized_execution = false;
    let mut escalation_id = None;

    if let Some(token) = &req.continuation_token {
        // 1. Verify Signature & Root Binding
        let verified = state
            .bridge()
            .verify_continuation_token(token, None, None, None, None, None)
            .await
            .map_err(|e| ApiError::Internal(format!("Token Verification failed: {}", e)))?;

        if !verified {
            return Err(ApiError::Forbidden(
                "Invalid or forged continuation token".to_string(),
            ));
        }

        // 2. Reconcile with Coordination Ledger
        let coordination_store = PersistentCoordinationStore::new(state.db());
        if let Some(record) = coordination_store
            .get_record(&claims.sub, &token.payload.ledger_event_id)
            .await
            .map_err(|e| ApiError::Internal(format!("Coordination Store error: {}", e)))?
        {
            // Validate that we are working on the SAME intent (source_capsule_root)
            if record.escalation_id == token.payload.ledger_event_id {
                authorized_execution = true;
                escalation_id = Some(record.escalation_id.clone());
                tracing::info!(
                    escalation_id = %record.escalation_id,
                    "Authorized execution confirmed via Continuation Token"
                );
            }
        }
    }

    // Phase 2.3: Authority Handshake (CHORA Witness)
    // If NOT already authorized by a token, perform standard handshake
    let capsule = if authorized_execution {
        // Build a "Resumption Capsule" - ideally CHORA provides this or we re-handshake with token context
        state
            .bridge()
            .perform_handshake(intent.clone(), &Uuid::new_v4().to_string())
            .await
            .map_err(|e| ApiError::Internal(format!("Authority Handshake failed: {}", e)))?
    } else {
        state
            .bridge()
            .perform_handshake(intent.clone(), &Uuid::new_v4().to_string())
            .await
            .map_err(|e| ApiError::Internal(format!("Authority Handshake failed: {}", e)))?
    };

    let witness_receipt = capsule.witness.receipt_hash.clone();

    tracing::info!(
        witness_receipt = %witness_receipt,
        chora_node = %capsule.witness.chora_node_id,
        "Authority Handshake complete: Witness-Hash secured."
    );

    // Check ownership/existence
    let store = AgentStore::new(state.db());

    let exists = store
        .exists(&claims.sub, agent_id)
        .await
        .map_err(|e| ApiError::Internal(format!("Storage error: {}", e)))?;

    if !exists {
        return Err(ApiError::NotFound("Agent not found".to_string()));
    }

    // Phase 2.2: Evidence Store - Log pre-encryption GateDecision
    let audit_store = vex_persist::AuditStore::new(state.db());

    // Check if we should escalate based on CHORA outcome
    let is_escalated = capsule.authority.outcome == "ESCALATE";
    let event_type = if is_escalated {
        vex_core::AuditEventType::Escalation
    } else {
        vex_core::AuditEventType::GateDecision
    };

    let _ = audit_store
        .log(
            &claims.sub,
            event_type,
            vex_core::ActorType::Bot(agent_id),
            Some(agent_id),
            serde_json::json!({
                "intent": intent,
                "intent_hash": intent_hash.to_hex(),
                "authority": capsule.authority,
                "witness": capsule.witness,
                "status": if is_escalated { "ESCALATED_FOR_REVIEW" } else { "APPROVED_WITNESS" },
                "escalation_id": capsule.authority.escalation_id,
                "binding_status": capsule.authority.binding_status,
                "continuation_token": capsule.authority.continuation_token,
            }),
            None,
            Some(witness_receipt.clone()),
            None,
        )
        .await;

    // If escalated, STOP execution and return the escalation details
    if is_escalated && !authorized_execution {
        // Record in Coordination Ledger for later resolution
        let coordination_store = PersistentCoordinationStore::new(state.db());
        let _ = coordination_store
            .record_escalation(
                &claims.sub,
                capsule.authority.escalation_id.clone().unwrap_or_default(),
                agent_id,
                capsule.authority.continuation_token.clone(),
            )
            .await;

        return Ok(Json(ExecuteResponse {
            agent_id,
            response: format!(
                "⚠️ Governance Intervention: Execution halted. Escalation ID: {}",
                capsule
                    .authority
                    .escalation_id
                    .as_deref()
                    .unwrap_or("unknown")
            ),
            verified: false,
            confidence: 0.0,
            context_hash: "halted".to_string(),
            latency_ms: start.elapsed().as_millis() as u64,
            witness_receipt: Some(witness_receipt),
            merkle_root: None,
            continuation_token: capsule.authority.continuation_token.clone(),
        }));
    }

    // If we're here and were authorized, update the coordination record to RESOLVED
    if authorized_execution {
        if let Some(eid) = escalation_id {
            let coordination_store = PersistentCoordinationStore::new(state.db());
            let _ = coordination_store
                .resolve_escalation(
                    &claims.sub,
                    &eid,
                    agent_id,
                    "final-resolution".to_string(), // In practice, the VEP hash
                )
                .await;
        }
    }

    // Create job payload with sanitized prompt and adversarial config
    let payload = serde_json::json!({
        "agent_id": agent_id,
        "prompt": prompt,
        "context_id": req.context_id,
        "enable_adversarial": req.enable_adversarial,
        "enable_self_correction": req.enable_self_correction,
        "max_debate_rounds": req.max_debate_rounds,
        "tenant_id": claims.sub,
        "trace_root": trace_root_hash.to_hex(),
        "intent_hash": intent_hash.to_hex(),
        "witness_receipt": witness_receipt,
        "authority_data": capsule.authority,
        "witness_data": capsule.witness,
    });

    // Enqueue job with explicit type checks
    // Enqueue job via dynamic backend
    let pool = state.queue();

    // For dynamic dispatch, we access the backend. It's Arc<dyn QueueBackend>.
    let backend = &pool.backend;

    let job_id = backend
        .enqueue(&claims.sub, "agent_execution", payload, None)
        .await
        .map_err(|e| ApiError::Internal(format!("Queue error: {}", e)))?;

    // Record metrics
    state.metrics().record_llm_call(0, false); // Just counting requests for now

    Ok(Json(ExecuteResponse {
        agent_id,
        response: format!("Job queued: {}", job_id),
        verified: false,
        confidence: 1.0,
        context_hash: "pending".to_string(),
        latency_ms: start.elapsed().as_millis() as u64,
        witness_receipt: Some(witness_receipt),
        merkle_root: None,
        continuation_token: capsule.authority.continuation_token,
    }))
}

/// Job status response (for polling after execute)
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct JobStatusResponse {
    pub job_id: Uuid,
    pub status: String,
    pub result: Option<serde_json::Value>,
    pub error: Option<String>,
    pub queued_at: chrono::DateTime<chrono::Utc>,
    pub attempts: u32,
}

/// Get job status / result handler
#[utoipa::path(
    get,
    path = "/api/v1/jobs/{id}",
    params(
        ("id" = Uuid, Path, description = "Job ID returned from execute_agent")
    ),
    responses(
        (status = 200, description = "Job status and result", body = JobStatusResponse),
        (status = 404, description = "Job not found")
    ),
    security(
        ("jwt" = [])
    )
)]
pub async fn get_job_status(
    Extension(claims): Extension<Claims>,
    State(state): State<AppState>,
    Path(job_id): Path<Uuid>,
) -> ApiResult<Json<JobStatusResponse>> {
    let pool = state.queue();
    let backend = &pool.backend;

    let tenant_id = claims.tenant_id.as_deref().unwrap_or(&claims.sub);

    let job = backend
        .get_job(tenant_id, job_id)
        .await
        .map_err(|_| ApiError::NotFound(format!("Job {} not found", job_id)))?;

    let status_str = match job.status {
        vex_queue::JobStatus::Pending => "pending",
        vex_queue::JobStatus::Running => "running",
        vex_queue::JobStatus::Completed => "completed",
        vex_queue::JobStatus::Failed(_) => "failed",
        vex_queue::JobStatus::DeadLetter => "dead_letter",
    };

    Ok(Json(JobStatusResponse {
        job_id,
        status: status_str.to_string(),
        result: job.result,
        error: job.last_error,
        queued_at: job.created_at,
        attempts: job.attempts,
    }))
}

/// Job update event for SSE
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct JobUpdate {
    pub job_id: Uuid,
    pub status: String,
    pub result: Option<serde_json::Value>,
    pub error: Option<String>,
}

/// SSE Stream handler for job updates
#[utoipa::path(
    get,
    path = "/api/v1/jobs/{id}/stream",
    params(
        ("id" = Uuid, Path, description = "Job ID")
    ),
    responses(
        (status = 200, description = "SSE stream of job updates")
    ),
    security(
        ("jwt" = [])
    )
)]
pub async fn get_job_stream(
    Extension(claims): Extension<Claims>,
    State(state): State<AppState>,
    Path(job_id): Path<Uuid>,
) -> ax_sse::Sse<impl Stream<Item = Result<ax_sse::Event, Infallible>>> {
    let tenant_id = claims
        .tenant_id
        .as_deref()
        .unwrap_or(&claims.sub)
        .to_string();
    let backend = state.queue().backend.clone();

    let stream = stream::unfold(
        (backend, tenant_id, job_id, false),
        |(backend, tid, jid, finished)| async move {
            if finished {
                return None;
            }

            match backend.get_job(&tid, jid).await {
                Ok(job) => {
                    let status_str = match job.status {
                        vex_queue::JobStatus::Pending => "pending",
                        vex_queue::JobStatus::Running => "running",
                        vex_queue::JobStatus::Completed => "completed",
                        vex_queue::JobStatus::Failed(_) => "failed",
                        vex_queue::JobStatus::DeadLetter => "dead_letter",
                    };

                    let is_final = matches!(
                        job.status,
                        vex_queue::JobStatus::Completed
                            | vex_queue::JobStatus::Failed(_)
                            | vex_queue::JobStatus::DeadLetter
                    );

                    let data = JobUpdate {
                        job_id: jid,
                        status: status_str.to_string(),
                        result: job.result,
                        error: job.last_error,
                    };

                    let event = ax_sse::Event::default()
                        .json_data(data)
                        .unwrap_or_else(|_| ax_sse::Event::default().data("error"));

                    if !is_final {
                        // Poll interval for non-finished jobs
                        tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
                    }

                    Some((Ok(event), (backend, tid, jid, is_final)))
                }
                Err(_) => {
                    let event = ax_sse::Event::default().data("job_not_found");
                    Some((Ok(event), (backend, tid, jid, true)))
                }
            }
        },
    );

    ax_sse::Sse::new(stream).keep_alive(ax_sse::KeepAlive::default())
}

/// Metrics response
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct MetricsResponse {
    pub llm_calls: u64,
    pub llm_errors: u64,
    pub tokens_used: u64,
    pub debates: u64,
    pub agents_created: u64,
    pub verifications: u64,
    pub verification_rate: f64,
    pub error_rate: f64,
}

/// Get metrics handler
#[utoipa::path(
    get,
    path = "/api/v1/metrics",
    responses(
        (status = 200, description = "Current system metrics", body = MetricsResponse),
        (status = 403, description = "Forbidden")
    ),
    security(
        ("jwt" = [])
    )
)]
pub async fn get_metrics(
    Extension(claims): Extension<Claims>,
    State(state): State<AppState>,
) -> ApiResult<Json<MetricsResponse>> {
    // Only admins can view metrics
    if !claims.has_role("admin") {
        return Err(ApiError::Forbidden("Admin access required".to_string()));
    }

    let snapshot = state.metrics().snapshot();

    Ok(Json(MetricsResponse {
        llm_calls: snapshot.llm_calls,
        llm_errors: snapshot.llm_errors,
        tokens_used: snapshot.tokens_used,
        debates: snapshot.debates,
        agents_created: snapshot.agents_created,
        verifications: snapshot.verifications,
        verification_rate: state.metrics().verification_rate(),
        error_rate: state.metrics().llm_error_rate(),
    }))
}

/// Routing statistics response
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct RoutingStatsResponse {
    pub summary: vex_router::ObservabilitySummary,
    pub savings: vex_router::SavingsReport,
}

/// Get routing statistics handler
#[utoipa::path(
    get,
    path = "/api/v1/routing/stats",
    responses(
        (status = 200, description = "Current routing statistics and cost savings", body = RoutingStatsResponse),
        (status = 404, description = "Router not enabled"),
        (status = 403, description = "Forbidden")
    ),
    security(
        ("jwt" = [])
    )
)]
pub async fn get_routing_stats(
    Extension(claims): Extension<Claims>,
    State(state): State<AppState>,
) -> ApiResult<Json<RoutingStatsResponse>> {
    // Only admins can view deep stats
    if !claims.has_role("admin") {
        return Err(ApiError::Forbidden("Admin access required".to_string()));
    }

    let router = state
        .router()
        .ok_or_else(|| ApiError::NotFound("Router not enabled".to_string()))?;
    let obs = router.observability();

    Ok(Json(RoutingStatsResponse {
        summary: obs.get_summary(),
        savings: obs.get_savings(),
    }))
}

/// Routing configuration request
#[derive(Debug, Deserialize, utoipa::ToSchema)]
pub struct UpdateRoutingConfigRequest {
    pub strategy: String,
    pub cache_enabled: bool,
    pub compression_level: String,
}

/// Update routing configuration handler
#[utoipa::path(
    put,
    path = "/api/v1/routing/config",
    request_body = UpdateRoutingConfigRequest,
    responses(
        (status = 200, description = "Routing configuration updated successfully"),
        (status = 404, description = "Router not enabled"),
        (status = 400, description = "Invalid configuration"),
        (status = 403, description = "Forbidden")
    ),
    security(
        ("jwt" = [])
    )
)]
pub async fn update_routing_config(
    Extension(claims): Extension<Claims>,
    State(state): State<AppState>,
    Json(req): Json<UpdateRoutingConfigRequest>,
) -> ApiResult<Json<HealthResponse>> {
    // Only admins can change system config
    if !claims.has_role("admin") {
        return Err(ApiError::Forbidden("Admin access required".to_string()));
    }

    let _router = state
        .router()
        .ok_or_else(|| ApiError::NotFound("Router not enabled".to_string()))?;

    // In a real implementation, we would update the router state here.
    // For now, we return a success status.

    Ok(Json(HealthResponse {
        status: format!("Routing strategy updated to {}", req.strategy),
        version: env!("CARGO_PKG_VERSION").to_string(),
        timestamp: chrono::Utc::now(),
        db_type: state.db().name().to_string(),
        components: None,
    }))
}

/// Evolve agent response
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct EvolveResponse {
    pub agent_id: Uuid,
    pub suggestions: Vec<SuggestionDTO>,
    pub message: String,
}

#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct SuggestionDTO {
    pub trait_name: String,
    pub current_value: f64,
    pub suggested_value: f64,
    pub confidence: f64,
}

/// Evolve agent handler
#[utoipa::path(
    post,
    path = "/api/v1/agents/{id}/evolve",
    params(
        ("id" = Uuid, Path, description = "Agent ID")
    ),
    responses(
        (status = 200, description = "Reflection complete", body = EvolveResponse),
        (status = 404, description = "Agent not found")
    ),
    security(
        ("jwt" = [])
    )
)]
pub async fn evolve_agent(
    Extension(claims): Extension<Claims>,
    State(state): State<AppState>,
    Path(agent_id): Path<Uuid>,
) -> ApiResult<Json<EvolveResponse>> {
    let store = AgentStore::new(state.db());
    let agent = store
        .load(&claims.sub, agent_id)
        .await
        .map_err(|e| ApiError::Internal(e.to_string()))?
        .ok_or_else(|| ApiError::NotFound("Agent not found".to_string()))?;

    let evo_store = state.evolution_store();

    let experiments = evo_store
        .load_recent(&claims.sub, 20)
        .await
        .unwrap_or_default();

    if experiments.is_empty() {
        return Ok(Json(EvolveResponse {
            agent_id,
            suggestions: vec![],
            message: "No experiments yet — run some tasks first".to_string(),
        }));
    }

    let reflection_agent = vex_adversarial::ReflectionAgent::new(state.llm());
    let mut evo_memory = vex_core::EvolutionMemory::new();
    for exp in experiments.clone() {
        evo_memory.record(exp);
    }

    // Use the latest experiment for context, but memory for stats
    let latest_exp = experiments.first().unwrap();

    let reflection_result = reflection_agent
        .reflect(
            &agent,
            &latest_exp.task_summary,
            "Retrospective evolution analysis",
            latest_exp.overall_fitness,
            &evo_memory,
        )
        .await;

    let adjustments_len = reflection_result.adjustments.len();
    Ok(Json(EvolveResponse {
        agent_id,
        suggestions: reflection_result
            .adjustments
            .into_iter()
            .map(|(t, c, s)| SuggestionDTO {
                trait_name: t,
                current_value: c,
                suggested_value: s,
                confidence: reflection_result.expected_improvement,
            })
            .collect(),
        message: format!(
            "Reflection complete. {} suggestions generated.",
            adjustments_len
        ),
    }))
}

/// Prometheus metrics handler
#[utoipa::path(
    get,
    path = "/metrics",
    responses(
        (status = 200, description = "Prometheus formatted metrics", body = String)
    )
)]
pub async fn get_prometheus_metrics(
    Extension(claims): Extension<Claims>,
    State(state): State<AppState>,
) -> ApiResult<String> {
    // Only admins can view metrics
    if !claims.has_role("admin") {
        return Err(ApiError::Forbidden("Admin access required".to_string()));
    }

    let snapshot = state.metrics().snapshot();
    Ok(snapshot.to_prometheus())
}

/// Escalation resolution request
#[derive(Debug, Deserialize, utoipa::ToSchema)]
pub struct ResolveEscalationRequest {
    pub escalation_id: String,
    pub resolution_vep_hash: String,
    pub rationale: String,
}

/// List active escalations handler
#[utoipa::path(
    get,
    path = "/api/v1/governance/escalations",
    responses(
        (status = 200, description = "List of active escalations", body = [CoordinationRecord]),
        (status = 403, description = "Forbidden")
    ),
    security(
        ("jwt" = [])
    )
)]
pub async fn list_escalations(
    Extension(claims): Extension<Claims>,
    State(state): State<AppState>,
) -> ApiResult<Json<Vec<CoordinationRecord>>> {
    let coordination = PersistentCoordinationStore::new(state.db());
    let active = coordination
        .list_active(&claims.sub)
        .await
        .map_err(|e| ApiError::Internal(format!("Coordination Ledger error: {}", e)))?;
    Ok(Json(active))
}

/// Resolve escalation handler
#[utoipa::path(
    post,
    path = "/api/v1/governance/resolve",
    request_body = ResolveEscalationRequest,
    responses(
        (status = 200, description = "Escalation resolved successfully"),
        (status = 404, description = "Escalation not found"),
        (status = 403, description = "Forbidden")
    ),
    security(
        ("jwt" = [])
    )
)]
pub async fn resolve_escalation(
    Extension(claims): Extension<Claims>,
    State(state): State<AppState>,
    Json(req): Json<ResolveEscalationRequest>,
) -> ApiResult<Json<serde_json::Value>> {
    // Only admins or authorized human reviewers can resolve escalations
    if !claims.has_role("user") {
        return Err(ApiError::Forbidden("Reviewer access required".to_string()));
    }

    // 1. Log the HumanOverride event in AuditStore
    // This will trigger the Auto-Resolve logic in AuditStore::log
    let audit_store = AuditStore::new(state.db());

    let data = serde_json::json!({
        "resolves_escalation_id": req.escalation_id,
        "rationale": req.rationale,
    });

    // Log the resolution event
    // The AuditStore::log implementation we modified will catch "HumanOverride"
    // and "resolves_escalation_id" to update the CoordinationLedger.
    let event = audit_store
        .log(
            &claims.sub,
            AuditEventType::HumanOverride,
            ActorType::Human(claims.sub.clone()),
            None,
            data,
            None,
            None,
            None,
        )
        .await
        .map_err(|e| ApiError::Internal(format!("Audit logging failed: {}", e)))?;

    // Phase 2.2: Link the resolution hash explicitly if provided
    let mut event = event;
    if let Some(capsule) = &mut event.evidence_capsule {
        capsule.resolution_vep_hash = Some(req.resolution_vep_hash.clone());
    }

    Ok(Json(serde_json::json!({
        "status": "resolved",
        "event_id": event.id,
        "escalation_id": req.escalation_id,
        "resolution_vep_hash": req.resolution_vep_hash
    })))
}

#[derive(OpenApi)]
#[openapi(
    paths(
        health,
        health_detailed,
        create_agent,
        execute_agent,
        evolve_agent,
        get_job_status,
        get_job_stream,
        get_metrics,
        get_prometheus_metrics,
        get_routing_stats,
        update_routing_config,
        list_escalations,
        resolve_escalation,
        crate::a2a::handler::agent_card_handler,
        crate::a2a::handler::create_task_handler,
        crate::a2a::handler::get_task_handler,
    ),
    components(
        schemas(
            HealthResponse, ComponentHealth, ComponentStatus,
            CreateAgentRequest, AgentResponse,
            ExecuteRequest, ExecuteResponse,
            EvolveResponse, SuggestionDTO,
            JobStatusResponse, JobUpdate,
            MetricsResponse,
            RoutingStatsResponse,
            UpdateRoutingConfigRequest,
            crate::a2a::agent_card::AgentCard,
            crate::a2a::agent_card::AuthConfig,
            crate::a2a::agent_card::Skill,
            crate::a2a::task::TaskRequest,
            crate::a2a::task::TaskResponse,
            crate::a2a::task::TaskStatus,
            CoordinationRecord,
            CoordinationStatus,
            ResolveEscalationRequest,
        )
    ),
    modifiers(&SecurityAddon)
)]
pub struct ApiDoc;

struct SecurityAddon;

impl utoipa::Modify for SecurityAddon {
    fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) {
        if let Some(components) = openapi.components.as_mut() {
            components.add_security_scheme(
                "jwt",
                utoipa::openapi::security::SecurityScheme::Http(
                    utoipa::openapi::security::HttpBuilder::new()
                        .scheme(utoipa::openapi::security::HttpAuthScheme::Bearer)
                        .bearer_format("JWT")
                        .build(),
                ),
            )
        }
    }
}

/// Build the API router
pub fn api_router(state: AppState) -> Router {
    use utoipa_swagger_ui::SwaggerUi;

    Router::new()
        // Documentation endpoints
        .merge(SwaggerUi::new("/swagger-ui").url("/api-docs/openapi.json", ApiDoc::openapi()))
        // A2A Protocol endpoints
        .merge(crate::a2a::handler::a2a_routes().with_state(state.a2a_state()))
        // Public endpoints
        .route("/health", get(health))
        .route("/health/detailed", get(health_detailed))
        // Agent endpoints
        .route("/api/v1/agents", post(create_agent))
        .route("/api/v1/agents/{id}/execute", post(execute_agent))
        .route("/api/v1/agents/{id}/evolve", post(evolve_agent))
        // Job polling endpoint
        .route("/api/v1/jobs/{id}", get(get_job_status))
        .route("/api/v1/jobs/{id}/stream", get(get_job_stream))
        // Admin endpoints
        .route("/api/v1/metrics", get(get_metrics))
        .route("/api/v1/routing/stats", get(get_routing_stats))
        .route(
            "/api/v1/routing/config",
            axum::routing::put(update_routing_config),
        )
        // Governance endpoints
        .route("/api/v1/governance/escalations", get(list_escalations))
        .route("/api/v1/governance/resolve", post(resolve_escalation))
        .route("/metrics", get(get_prometheus_metrics))
        // State
        .with_state(state)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_health_response() {
        let health = HealthResponse {
            status: "healthy".to_string(),
            version: "0.1.0".to_string(),
            timestamp: chrono::Utc::now(),
            db_type: "sqlite".to_string(),
            components: None,
        };
        assert_eq!(health.status, "healthy");
    }
}