agentd 0.1.2

Agent daemon for secure capability execution with pluggable isolation backends
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
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
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
// api.rs - NATS-based API integration for planner-executor communication

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use serde::{Deserialize, Serialize};
use tokio::sync::{mpsc, RwLock};
use tracing::{debug, error, info, warn};

use smith_bus::{subjects::*, Consumer, Publisher, SmithBus};
use smith_protocol::{ExecutionStatus, Intent, IntentResult};

use crate::runners::planner_exec::{
    schemas::{
        ActionResult, ExecutionSummary, PlannerExecParams, ResourceUsage, WorkflowAction,
        WorkflowStatus, WorkflowType,
    },
    state_machine::{StateMachine, WorkflowState},
    telemetry::{EventType, ResourceUtilization, Severity, TelemetryCollector},
};

/// NATS-based API for planner-executor communication
pub struct PlannerExecAPI {
    bus: Arc<SmithBus>,
    publisher: Arc<Publisher>,
    active_workflows: Arc<RwLock<HashMap<String, WorkflowSession>>>,
    event_sender: mpsc::UnboundedSender<APIEvent>,
    config: APIConfig,
}

/// Configuration for the planner-executor API
#[derive(Debug, Clone)]
pub struct APIConfig {
    pub max_concurrent_workflows: usize,
    pub workflow_timeout: Duration,
    pub heartbeat_interval: Duration,
    pub result_retention: Duration,
    pub enable_streaming: bool,
    pub compression_enabled: bool,
}

/// Active workflow session
#[derive(Debug)]
struct WorkflowSession {
    session_id: String,
    workflow_type: WorkflowType,
    state_machine: StateMachine,
    telemetry: TelemetryCollector,
    created_at: std::time::Instant,
    last_activity: std::time::Instant,
    result_channel: mpsc::UnboundedSender<WorkflowUpdate>,
}

/// API events for internal communication
#[derive(Debug, Clone, Serialize)]
pub enum APIEvent {
    WorkflowStarted {
        session_id: String,
        workflow_type: WorkflowType,
    },
    WorkflowCompleted {
        session_id: String,
        summary: ExecutionSummary,
    },
    WorkflowFailed {
        session_id: String,
        error: String,
    },
    ActionExecuted {
        session_id: String,
        action_id: String,
        result: ActionResult,
    },
    StateTransition {
        session_id: String,
        from_state: WorkflowState,
        to_state: WorkflowState,
    },
    UserIntervention {
        session_id: String,
        intervention_type: String,
    },
    SystemError {
        session_id: String,
        error: String,
    },
    HealthCheck {
        component: String,
        status: HealthStatus,
    },
}

/// Health status for system components
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum HealthStatus {
    Healthy,
    Degraded,
    Unhealthy,
    Unknown,
}

/// Workflow update for streaming
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowUpdate {
    pub session_id: String,
    pub timestamp: u64,
    pub update_type: UpdateType,
    pub payload: serde_json::Value,
}

/// Types of workflow updates
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum UpdateType {
    StateChanged,
    ActionStarted,
    ActionCompleted,
    ProgressUpdate,
    ErrorOccurred,
    UserRequired,
    MetricsUpdate,
    LogMessage,
}

/// API request types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum APIRequest {
    StartWorkflow {
        session_id: String,
        params: PlannerExecParams,
        streaming: bool,
    },
    StopWorkflow {
        session_id: String,
        force: bool,
    },
    PauseWorkflow {
        session_id: String,
    },
    ResumeWorkflow {
        session_id: String,
    },
    GetWorkflowStatus {
        session_id: String,
    },
    ListActiveWorkflows,
    GetWorkflowHistory {
        session_id: String,
        include_telemetry: bool,
    },
    HealthCheck {
        component: Option<String>,
    },
    GetMetrics {
        session_id: Option<String>,
        format: String,
    },
    UserIntervention {
        session_id: String,
        action: String,
        parameters: HashMap<String, String>,
    },
}

/// API response types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum APIResponse {
    WorkflowStarted {
        session_id: String,
        stream_subject: Option<String>,
    },
    WorkflowStopped {
        session_id: String,
        summary: Option<ExecutionSummary>,
    },
    WorkflowStatus {
        session_id: String,
        state: WorkflowState,
        progress: f64,
        current_action: Option<String>,
        metadata: HashMap<String, String>,
    },
    ActiveWorkflows {
        workflows: Vec<WorkflowInfo>,
    },
    WorkflowHistory {
        session_id: String,
        events: Vec<serde_json::Value>,
        telemetry: Option<serde_json::Value>,
    },
    HealthStatus {
        component: String,
        status: HealthStatus,
        details: HashMap<String, String>,
    },
    Metrics {
        data: String,
        format: String,
    },
    InterventionResult {
        session_id: String,
        success: bool,
        message: String,
    },
    Error {
        code: String,
        message: String,
        details: Option<HashMap<String, String>>,
    },
}

/// Workflow information for listing
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowInfo {
    pub session_id: String,
    pub workflow_type: WorkflowType,
    pub state: WorkflowState,
    pub progress: f64,
    pub created_at: u64,
    pub last_activity: u64,
    pub duration_ms: u64,
}

impl Default for APIConfig {
    fn default() -> Self {
        Self {
            max_concurrent_workflows: 100,
            workflow_timeout: Duration::from_secs(3600), // 1 hour
            heartbeat_interval: Duration::from_secs(30),
            result_retention: Duration::from_secs(86400), // 24 hours
            enable_streaming: true,
            compression_enabled: true,
        }
    }
}

/// Convert telemetry ResourceUtilization to schemas ResourceUsage
fn convert_resource_utilization(util: &ResourceUtilization) -> ResourceUsage {
    ResourceUsage {
        cpu_ms: (util.avg_cpu_percent * 1000.0) as u64, // Rough approximation
        memory_bytes: (util.peak_memory_mb * 1024.0 * 1024.0) as u64,
        fs_operations: 0, // Not tracked in ResourceUtilization
        network_requests: (util.network_io_mb * 10.0) as u64, // Rough approximation
    }
}

impl PlannerExecAPI {
    /// Create a new planner-executor API instance
    pub async fn new(
        bus: Arc<SmithBus>,
        config: APIConfig,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        let publisher = Arc::new(bus.publisher());
        let (event_sender, event_receiver) = mpsc::unbounded_channel();

        let api = Self {
            bus: bus.clone(),
            publisher,
            active_workflows: Arc::new(RwLock::new(HashMap::new())),
            event_sender,
            config,
        };

        // Start background tasks
        api.start_background_tasks(event_receiver).await?;

        info!(
            "Planner-Executor API initialized with config: {:?}",
            api.config
        );
        Ok(api)
    }

    /// Start the API request handler
    pub async fn start_request_handler(&self) -> Result<(), Box<dyn std::error::Error>> {
        let consumer = self
            .bus
            .consumer(
                "planner_exec_requests",
                smith_bus::ConsumerConfig {
                    name: "planner_exec_api".to_string(),
                    consumer_group: None,
                    max_deliver: 3,
                    ack_wait: Duration::from_secs(30),
                    max_age: None,
                    start_sequence: smith_bus::ConsumerStartSequence::Latest,
                    worker_count: 1,
                },
            )
            .await?;

        let api = self.clone();
        tokio::spawn(async move {
            api.handle_requests(consumer).await;
        });

        info!("Started planner-executor API request handler");
        Ok(())
    }

    /// Handle incoming API requests
    async fn handle_requests(&self, mut consumer: Consumer) {
        loop {
            match consumer.next_message::<serde_json::Value>().await {
                Ok(Some(message)) => {
                    let api = self.clone();
                    tokio::spawn(async move {
                        if let Err(e) = api.process_request_message(message).await {
                            error!("Failed to process API request: {}", e);
                        }
                    });
                }
                Ok(None) => {
                    tokio::time::sleep(Duration::from_millis(100)).await;
                    continue;
                }
                Err(e) => {
                    error!("Error receiving message: {}", e);
                    tokio::time::sleep(Duration::from_secs(1)).await;
                }
            }
        }
    }

    /// Process a single API request message
    async fn process_request_message(
        &self,
        message: smith_bus::Message<serde_json::Value>,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let request: APIRequest = serde_json::from_value(message.payload.clone())?;
        let response = self.handle_api_request(request).await;

        // Send response - reply handling would need to be implemented
        // through request/response pattern or additional message headers

        // Acknowledge message
        message.ack().await?;
        Ok(())
    }

    /// Handle an API request and generate response
    async fn handle_api_request(&self, request: APIRequest) -> APIResponse {
        debug!("Handling API request: {:?}", request);

        match request {
            APIRequest::StartWorkflow {
                session_id,
                params,
                streaming,
            } => {
                match self
                    .start_workflow(session_id.clone(), params, streaming)
                    .await
                {
                    Ok(stream_subject) => APIResponse::WorkflowStarted {
                        session_id,
                        stream_subject,
                    },
                    Err(e) => APIResponse::Error {
                        code: "WORKFLOW_START_FAILED".to_string(),
                        message: e.to_string(),
                        details: None,
                    },
                }
            }

            APIRequest::StopWorkflow { session_id, force } => {
                match self.stop_workflow(&session_id, force).await {
                    Ok(summary) => APIResponse::WorkflowStopped {
                        session_id,
                        summary,
                    },
                    Err(e) => APIResponse::Error {
                        code: "WORKFLOW_STOP_FAILED".to_string(),
                        message: e.to_string(),
                        details: None,
                    },
                }
            }

            APIRequest::PauseWorkflow { session_id } => {
                match self.pause_workflow(&session_id).await {
                    Ok(_) => APIResponse::WorkflowStatus {
                        session_id: session_id.clone(),
                        state: WorkflowState::Paused,
                        progress: 0.0, // Will be updated by actual implementation
                        current_action: None,
                        metadata: HashMap::new(),
                    },
                    Err(e) => APIResponse::Error {
                        code: "WORKFLOW_PAUSE_FAILED".to_string(),
                        message: e.to_string(),
                        details: None,
                    },
                }
            }

            APIRequest::ResumeWorkflow { session_id } => {
                match self.resume_workflow(&session_id).await {
                    Ok(_) => APIResponse::WorkflowStatus {
                        session_id: session_id.clone(),
                        state: WorkflowState::Executing,
                        progress: 0.0, // Will be updated by actual implementation
                        current_action: None,
                        metadata: HashMap::new(),
                    },
                    Err(e) => APIResponse::Error {
                        code: "WORKFLOW_RESUME_FAILED".to_string(),
                        message: e.to_string(),
                        details: None,
                    },
                }
            }

            APIRequest::GetWorkflowStatus { session_id } => {
                match self.get_workflow_status(&session_id).await {
                    Ok(status) => status,
                    Err(e) => APIResponse::Error {
                        code: "WORKFLOW_STATUS_FAILED".to_string(),
                        message: e.to_string(),
                        details: None,
                    },
                }
            }

            APIRequest::ListActiveWorkflows => match self.list_active_workflows().await {
                Ok(workflows) => APIResponse::ActiveWorkflows { workflows },
                Err(e) => APIResponse::Error {
                    code: "LIST_WORKFLOWS_FAILED".to_string(),
                    message: e.to_string(),
                    details: None,
                },
            },

            APIRequest::GetWorkflowHistory {
                session_id,
                include_telemetry,
            } => {
                match self
                    .get_workflow_history(&session_id, include_telemetry)
                    .await
                {
                    Ok((events, telemetry)) => APIResponse::WorkflowHistory {
                        session_id,
                        events,
                        telemetry,
                    },
                    Err(e) => APIResponse::Error {
                        code: "WORKFLOW_HISTORY_FAILED".to_string(),
                        message: e.to_string(),
                        details: None,
                    },
                }
            }

            APIRequest::HealthCheck { component } => self.get_health_status(component).await,

            APIRequest::GetMetrics { session_id, format } => {
                match self.get_metrics(session_id, &format).await {
                    Ok(data) => APIResponse::Metrics { data, format },
                    Err(e) => APIResponse::Error {
                        code: "METRICS_FAILED".to_string(),
                        message: e.to_string(),
                        details: None,
                    },
                }
            }

            APIRequest::UserIntervention {
                session_id,
                action,
                parameters,
            } => {
                match self
                    .handle_user_intervention(&session_id, &action, parameters)
                    .await
                {
                    Ok(message) => APIResponse::InterventionResult {
                        session_id,
                        success: true,
                        message,
                    },
                    Err(e) => APIResponse::InterventionResult {
                        session_id,
                        success: false,
                        message: e.to_string(),
                    },
                }
            }
        }
    }

    /// Start a new workflow
    async fn start_workflow(
        &self,
        session_id: String,
        params: PlannerExecParams,
        streaming: bool,
    ) -> Result<Option<String>, Box<dyn std::error::Error>> {
        // Check concurrent workflow limit
        let workflows = self.active_workflows.read().await;
        if workflows.len() >= self.config.max_concurrent_workflows {
            return Err("Maximum concurrent workflows exceeded".into());
        }
        drop(workflows);

        // Create state machine and telemetry
        let state_machine = StateMachine::new(params.workflow_id.clone(), params.clone())?;
        let telemetry =
            TelemetryCollector::new(session_id.clone(), Some(params.workflow_type.clone()));

        // Create result channel for streaming
        let (result_sender, mut result_receiver) = mpsc::unbounded_channel();
        let stream_subject = if streaming {
            Some(format!("smith.planner_exec.streams.{}", session_id))
        } else {
            None
        };

        // Create workflow session
        let session = WorkflowSession {
            session_id: session_id.clone(),
            workflow_type: params.workflow_type.clone(),
            state_machine,
            telemetry,
            created_at: std::time::Instant::now(),
            last_activity: std::time::Instant::now(),
            result_channel: result_sender,
        };

        // Add to active workflows
        let mut workflows = self.active_workflows.write().await;
        workflows.insert(session_id.clone(), session);
        drop(workflows);

        // Start streaming task if enabled
        if let Some(subject) = &stream_subject {
            let publisher = self.publisher.clone();
            let subject = subject.clone();
            tokio::spawn(async move {
                while let Some(update) = result_receiver.recv().await {
                    if let Ok(data) = serde_json::to_vec(&update) {
                        if let Err(e) = publisher.publish(subject.clone(), &update).await {
                            error!("Failed to publish workflow update: {}", e);
                        }
                    }
                }
            });
        }

        // Emit workflow started event
        let _ = self.event_sender.send(APIEvent::WorkflowStarted {
            session_id: session_id.clone(),
            workflow_type: params.workflow_type,
        });

        info!(
            "Started workflow {} with streaming: {}",
            session_id, streaming
        );
        Ok(stream_subject)
    }

    /// Stop a workflow
    async fn stop_workflow(
        &self,
        session_id: &str,
        force: bool,
    ) -> Result<Option<ExecutionSummary>, Box<dyn std::error::Error>> {
        let mut workflows = self.active_workflows.write().await;

        if let Some(session) = workflows.remove(session_id) {
            drop(workflows);

            // Generate final summary from telemetry
            let telemetry_report = session.telemetry.generate_report().await;
            let summary = ExecutionSummary {
                workflow_id: session.state_machine.workflow_id.clone(),
                session_id: session.session_id.clone(),
                workflow_type: session.workflow_type,
                goal: session.state_machine.params.goal.clone(),
                status: match session.state_machine.current_state() {
                    WorkflowState::Completed => WorkflowStatus::Completed,
                    WorkflowState::Failed(_) => WorkflowStatus::Failed,
                    _ => WorkflowStatus::Cancelled,
                },
                actions: session.state_machine.completed_actions.clone(),
                duration_ms: session.created_at.elapsed().as_millis() as u64,
                total_duration: session.created_at.elapsed(),
                total_actions: telemetry_report.total_actions as u32,
                successful_actions: telemetry_report.successful_actions as u32,
                failed_actions: telemetry_report.failed_actions as u32,
                final_state: match session.state_machine.current_state() {
                    WorkflowState::Completed => WorkflowStatus::Completed,
                    WorkflowState::Failed(_) => WorkflowStatus::Failed,
                    WorkflowState::Paused => WorkflowStatus::Paused,
                    WorkflowState::Executing => WorkflowStatus::Executing,
                    WorkflowState::Planning => WorkflowStatus::Planning,
                    WorkflowState::Initializing => WorkflowStatus::Initializing,
                },
                error_message: None,
                resource_usage: convert_resource_utilization(
                    &telemetry_report.resource_utilization,
                ),
                success_criteria_met: vec![], // TODO: Extract from state machine
                lessons_learned: session.state_machine.lessons_learned.clone(),
                recommendations: telemetry_report.recommendations,
                final_output: None, // TODO: Extract final output if available
            };

            // Emit workflow completed event
            let _ = self.event_sender.send(APIEvent::WorkflowCompleted {
                session_id: session_id.to_string(),
                summary: summary.clone(),
            });

            info!("Stopped workflow {} (force: {})", session_id, force);
            Ok(Some(summary))
        } else {
            Err(format!("Workflow {} not found", session_id).into())
        }
    }

    /// Pause a workflow
    async fn pause_workflow(&self, session_id: &str) -> Result<(), Box<dyn std::error::Error>> {
        let workflows = self.active_workflows.read().await;

        if let Some(session) = workflows.get(session_id) {
            // In a real implementation, this would pause the state machine
            info!("Paused workflow {}", session_id);
            Ok(())
        } else {
            Err(format!("Workflow {} not found", session_id).into())
        }
    }

    /// Resume a workflow
    async fn resume_workflow(&self, session_id: &str) -> Result<(), Box<dyn std::error::Error>> {
        let workflows = self.active_workflows.read().await;

        if let Some(session) = workflows.get(session_id) {
            // In a real implementation, this would resume the state machine
            info!("Resumed workflow {}", session_id);
            Ok(())
        } else {
            Err(format!("Workflow {} not found", session_id).into())
        }
    }

    /// Get workflow status
    async fn get_workflow_status(
        &self,
        session_id: &str,
    ) -> Result<APIResponse, Box<dyn std::error::Error>> {
        let workflows = self.active_workflows.read().await;

        if let Some(session) = workflows.get(session_id) {
            let mut metadata = HashMap::new();
            metadata.insert(
                "created_at".to_string(),
                session.created_at.elapsed().as_secs().to_string(),
            );
            metadata.insert(
                "last_activity".to_string(),
                session.last_activity.elapsed().as_secs().to_string(),
            );

            Ok(APIResponse::WorkflowStatus {
                session_id: session_id.to_string(),
                state: session.state_machine.current_state().clone(),
                progress: session.state_machine.progress(),
                current_action: session.state_machine.current_action().map(|a| a.id.clone()),
                metadata,
            })
        } else {
            Err(format!("Workflow {} not found", session_id).into())
        }
    }

    /// List active workflows
    async fn list_active_workflows(&self) -> Result<Vec<WorkflowInfo>, Box<dyn std::error::Error>> {
        let workflows = self.active_workflows.read().await;
        let mut result = Vec::new();

        for (session_id, session) in workflows.iter() {
            let info = WorkflowInfo {
                session_id: session_id.clone(),
                workflow_type: session.workflow_type.clone(),
                state: session.state_machine.current_state().clone(),
                progress: session.state_machine.progress(),
                created_at: std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_secs()
                    - session.created_at.elapsed().as_secs(),
                last_activity: std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_secs()
                    - session.last_activity.elapsed().as_secs(),
                duration_ms: session.created_at.elapsed().as_millis() as u64,
            };
            result.push(info);
        }

        Ok(result)
    }

    /// Get workflow history
    async fn get_workflow_history(
        &self,
        session_id: &str,
        include_telemetry: bool,
    ) -> Result<(Vec<serde_json::Value>, Option<serde_json::Value>), Box<dyn std::error::Error>>
    {
        let workflows = self.active_workflows.read().await;

        if let Some(session) = workflows.get(session_id) {
            let events = session
                .state_machine
                .get_execution_history()
                .iter()
                .map(|event| serde_json::to_value(event).unwrap_or_default())
                .collect();

            let telemetry = if include_telemetry {
                let report = session.telemetry.generate_report().await;
                Some(serde_json::to_value(&report)?)
            } else {
                None
            };

            Ok((events, telemetry))
        } else {
            Err(format!("Workflow {} not found", session_id).into())
        }
    }

    /// Get health status
    async fn get_health_status(&self, component: Option<String>) -> APIResponse {
        let mut details = HashMap::new();
        details.insert(
            "active_workflows".to_string(),
            self.active_workflows.read().await.len().to_string(),
        );
        details.insert("uptime".to_string(), "healthy".to_string());

        APIResponse::HealthStatus {
            component: component.unwrap_or_else(|| "planner_exec_api".to_string()),
            status: HealthStatus::Healthy,
            details,
        }
    }

    /// Get metrics
    async fn get_metrics(
        &self,
        session_id: Option<String>,
        format: &str,
    ) -> Result<String, Box<dyn std::error::Error>> {
        let workflows = self.active_workflows.read().await;

        if let Some(sid) = session_id {
            // Get metrics for specific workflow
            if let Some(session) = workflows.get(&sid) {
                match format {
                    "json" => {
                        let report = session.telemetry.generate_report().await;
                        Ok(serde_json::to_string_pretty(&report)?)
                    }
                    "prometheus" => {
                        session
                            .telemetry
                            .export_telemetry(
                                crate::runners::planner_exec::telemetry::ExportFormat::Prometheus,
                            )
                            .await
                    }
                    _ => Err("Unsupported format".into()),
                }
            } else {
                Err(format!("Workflow {} not found", sid).into())
            }
        } else {
            // Get aggregate metrics
            let total_workflows = workflows.len();
            let aggregate_metrics = serde_json::json!({
                "total_active_workflows": total_workflows,
                "api_status": "healthy",
                "timestamp": std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_secs()
            });

            Ok(serde_json::to_string_pretty(&aggregate_metrics)?)
        }
    }

    /// Handle user intervention
    async fn handle_user_intervention(
        &self,
        session_id: &str,
        action: &str,
        parameters: HashMap<String, String>,
    ) -> Result<String, Box<dyn std::error::Error>> {
        let workflows = self.active_workflows.read().await;

        if let Some(_session) = workflows.get(session_id) {
            // Emit user intervention event
            let _ = self.event_sender.send(APIEvent::UserIntervention {
                session_id: session_id.to_string(),
                intervention_type: action.to_string(),
            });

            info!(
                "User intervention {} applied to workflow {}",
                action, session_id
            );
            Ok(format!("Intervention '{}' applied successfully", action))
        } else {
            Err(format!("Workflow {} not found", session_id).into())
        }
    }

    /// Start background tasks
    async fn start_background_tasks(
        &self,
        mut event_receiver: mpsc::UnboundedReceiver<APIEvent>,
    ) -> Result<(), Box<dyn std::error::Error>> {
        // Event processing task
        let publisher = self.publisher.clone();
        tokio::spawn(async move {
            while let Some(event) = event_receiver.recv().await {
                if let Ok(data) = serde_json::to_vec(&event) {
                    let subject = "smith.planner_exec.events";
                    if let Err(e) = publisher.publish(subject.to_string(), &event).await {
                        error!("Failed to publish API event: {}", e);
                    }
                }
            }
        });

        // Cleanup task for expired workflows
        let workflows = self.active_workflows.clone();
        let timeout = self.config.workflow_timeout;
        tokio::spawn(async move {
            let mut interval = tokio::time::interval(Duration::from_secs(60));
            loop {
                interval.tick().await;

                let mut to_remove = Vec::new();
                {
                    let workflows_read = workflows.read().await;
                    for (session_id, session) in workflows_read.iter() {
                        if session.last_activity.elapsed() > timeout {
                            to_remove.push(session_id.clone());
                        }
                    }
                }

                if !to_remove.is_empty() {
                    let mut workflows_write = workflows.write().await;
                    for session_id in to_remove {
                        workflows_write.remove(&session_id);
                        warn!("Removed expired workflow: {}", session_id);
                    }
                }
            }
        });

        Ok(())
    }
}

impl Clone for PlannerExecAPI {
    fn clone(&self) -> Self {
        Self {
            bus: self.bus.clone(),
            publisher: self.publisher.clone(),
            active_workflows: self.active_workflows.clone(),
            event_sender: self.event_sender.clone(),
            config: self.config.clone(),
        }
    }
}

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

    // ==================== APIConfig Tests ====================

    #[test]
    fn test_api_config_default() {
        let config = APIConfig::default();
        assert_eq!(config.max_concurrent_workflows, 100);
        assert_eq!(config.workflow_timeout, Duration::from_secs(3600));
        assert_eq!(config.heartbeat_interval, Duration::from_secs(30));
        assert_eq!(config.result_retention, Duration::from_secs(86400));
        assert!(config.enable_streaming);
        assert!(config.compression_enabled);
    }

    #[test]
    fn test_api_config_clone() {
        let config = APIConfig {
            max_concurrent_workflows: 50,
            workflow_timeout: Duration::from_secs(1800),
            heartbeat_interval: Duration::from_secs(15),
            result_retention: Duration::from_secs(43200),
            enable_streaming: false,
            compression_enabled: false,
        };
        let cloned = config.clone();
        assert_eq!(cloned.max_concurrent_workflows, 50);
        assert_eq!(cloned.workflow_timeout, Duration::from_secs(1800));
        assert!(!cloned.enable_streaming);
    }

    #[test]
    fn test_api_config_debug() {
        let config = APIConfig::default();
        let debug_str = format!("{:?}", config);
        assert!(debug_str.contains("max_concurrent_workflows"));
        assert!(debug_str.contains("workflow_timeout"));
    }

    // ==================== HealthStatus Tests ====================

    #[test]
    fn test_health_status_healthy() {
        let status = HealthStatus::Healthy;
        let serialized = serde_json::to_string(&status).unwrap();
        assert!(serialized.contains("Healthy"));
    }

    #[test]
    fn test_health_status_degraded() {
        let status = HealthStatus::Degraded;
        let serialized = serde_json::to_string(&status).unwrap();
        assert!(serialized.contains("Degraded"));
    }

    #[test]
    fn test_health_status_unhealthy() {
        let status = HealthStatus::Unhealthy;
        let serialized = serde_json::to_string(&status).unwrap();
        assert!(serialized.contains("Unhealthy"));
    }

    #[test]
    fn test_health_status_unknown() {
        let status = HealthStatus::Unknown;
        let serialized = serde_json::to_string(&status).unwrap();
        assert!(serialized.contains("Unknown"));
    }

    #[test]
    fn test_health_status_roundtrip() {
        for status in [
            HealthStatus::Healthy,
            HealthStatus::Degraded,
            HealthStatus::Unhealthy,
            HealthStatus::Unknown,
        ] {
            let serialized = serde_json::to_string(&status).unwrap();
            let deserialized: HealthStatus = serde_json::from_str(&serialized).unwrap();
            // Just verify it roundtrips without panicking
            let _ = format!("{:?}", deserialized);
        }
    }

    // ==================== UpdateType Tests ====================

    #[test]
    fn test_update_type_serialization() {
        let update_types = [
            UpdateType::StateChanged,
            UpdateType::ActionStarted,
            UpdateType::ActionCompleted,
            UpdateType::ProgressUpdate,
            UpdateType::ErrorOccurred,
            UpdateType::UserRequired,
            UpdateType::MetricsUpdate,
            UpdateType::LogMessage,
        ];

        for update_type in update_types {
            let serialized = serde_json::to_string(&update_type).unwrap();
            let deserialized: UpdateType = serde_json::from_str(&serialized).unwrap();
            let _ = format!("{:?}", deserialized);
        }
    }

    // ==================== WorkflowUpdate Tests ====================

    #[test]
    fn test_workflow_update_creation() {
        let update = WorkflowUpdate {
            session_id: "test-session-123".to_string(),
            timestamp: 1234567890,
            update_type: UpdateType::StateChanged,
            payload: serde_json::json!({"state": "executing"}),
        };
        assert_eq!(update.session_id, "test-session-123");
        assert_eq!(update.timestamp, 1234567890);
    }

    #[test]
    fn test_workflow_update_serialization() {
        let update = WorkflowUpdate {
            session_id: "session-abc".to_string(),
            timestamp: 9876543210,
            update_type: UpdateType::ProgressUpdate,
            payload: serde_json::json!({"progress": 0.75}),
        };
        let serialized = serde_json::to_string(&update).unwrap();
        let deserialized: WorkflowUpdate = serde_json::from_str(&serialized).unwrap();
        assert_eq!(deserialized.session_id, "session-abc");
        assert_eq!(deserialized.timestamp, 9876543210);
    }

    // ==================== APIRequest Tests ====================

    #[tokio::test]
    async fn test_api_request_start_workflow() {
        let request = APIRequest::StartWorkflow {
            session_id: "test-session".to_string(),
            params: PlannerExecParams {
                workflow_id: "test-workflow-123".to_string(),
                goal: "Test workflow".to_string(),
                workflow_type: WorkflowType::Simple,
                max_steps: 10,
                timeout_ms: Some(3600000),
                context: HashMap::new(),
                allowed_capabilities: vec![],
                resource_limits: crate::runners::planner_exec::schemas::ResourceLimits::default(),
                preferences: crate::runners::planner_exec::schemas::ExecutionPreferences::default(),
            },
            streaming: true,
        };

        let serialized = serde_json::to_string(&request).unwrap();
        let deserialized: APIRequest = serde_json::from_str(&serialized).unwrap();

        match deserialized {
            APIRequest::StartWorkflow {
                session_id,
                streaming,
                ..
            } => {
                assert_eq!(session_id, "test-session");
                assert!(streaming);
            }
            _ => panic!("Unexpected request type"),
        }
    }

    #[test]
    fn test_api_request_stop_workflow() {
        let request = APIRequest::StopWorkflow {
            session_id: "session-to-stop".to_string(),
            force: true,
        };
        let serialized = serde_json::to_string(&request).unwrap();
        let deserialized: APIRequest = serde_json::from_str(&serialized).unwrap();
        match deserialized {
            APIRequest::StopWorkflow { session_id, force } => {
                assert_eq!(session_id, "session-to-stop");
                assert!(force);
            }
            _ => panic!("Unexpected request type"),
        }
    }

    #[test]
    fn test_api_request_pause_workflow() {
        let request = APIRequest::PauseWorkflow {
            session_id: "session-to-pause".to_string(),
        };
        let serialized = serde_json::to_string(&request).unwrap();
        let deserialized: APIRequest = serde_json::from_str(&serialized).unwrap();
        match deserialized {
            APIRequest::PauseWorkflow { session_id } => {
                assert_eq!(session_id, "session-to-pause");
            }
            _ => panic!("Unexpected request type"),
        }
    }

    #[test]
    fn test_api_request_resume_workflow() {
        let request = APIRequest::ResumeWorkflow {
            session_id: "session-to-resume".to_string(),
        };
        let serialized = serde_json::to_string(&request).unwrap();
        let deserialized: APIRequest = serde_json::from_str(&serialized).unwrap();
        match deserialized {
            APIRequest::ResumeWorkflow { session_id } => {
                assert_eq!(session_id, "session-to-resume");
            }
            _ => panic!("Unexpected request type"),
        }
    }

    #[test]
    fn test_api_request_get_status() {
        let request = APIRequest::GetWorkflowStatus {
            session_id: "status-session".to_string(),
        };
        let serialized = serde_json::to_string(&request).unwrap();
        let deserialized: APIRequest = serde_json::from_str(&serialized).unwrap();
        match deserialized {
            APIRequest::GetWorkflowStatus { session_id } => {
                assert_eq!(session_id, "status-session");
            }
            _ => panic!("Unexpected request type"),
        }
    }

    #[test]
    fn test_api_request_list_active() {
        let request = APIRequest::ListActiveWorkflows;
        let serialized = serde_json::to_string(&request).unwrap();
        let deserialized: APIRequest = serde_json::from_str(&serialized).unwrap();
        assert!(matches!(deserialized, APIRequest::ListActiveWorkflows));
    }

    #[test]
    fn test_api_request_get_history() {
        let request = APIRequest::GetWorkflowHistory {
            session_id: "history-session".to_string(),
            include_telemetry: true,
        };
        let serialized = serde_json::to_string(&request).unwrap();
        let deserialized: APIRequest = serde_json::from_str(&serialized).unwrap();
        match deserialized {
            APIRequest::GetWorkflowHistory {
                session_id,
                include_telemetry,
            } => {
                assert_eq!(session_id, "history-session");
                assert!(include_telemetry);
            }
            _ => panic!("Unexpected request type"),
        }
    }

    #[test]
    fn test_api_request_health_check() {
        let request = APIRequest::HealthCheck {
            component: Some("executor".to_string()),
        };
        let serialized = serde_json::to_string(&request).unwrap();
        let deserialized: APIRequest = serde_json::from_str(&serialized).unwrap();
        match deserialized {
            APIRequest::HealthCheck { component } => {
                assert_eq!(component, Some("executor".to_string()));
            }
            _ => panic!("Unexpected request type"),
        }
    }

    #[test]
    fn test_api_request_get_metrics() {
        let request = APIRequest::GetMetrics {
            session_id: Some("metrics-session".to_string()),
            format: "json".to_string(),
        };
        let serialized = serde_json::to_string(&request).unwrap();
        let deserialized: APIRequest = serde_json::from_str(&serialized).unwrap();
        match deserialized {
            APIRequest::GetMetrics { session_id, format } => {
                assert_eq!(session_id, Some("metrics-session".to_string()));
                assert_eq!(format, "json");
            }
            _ => panic!("Unexpected request type"),
        }
    }

    #[test]
    fn test_api_request_user_intervention() {
        let mut params = HashMap::new();
        params.insert("key".to_string(), "value".to_string());
        let request = APIRequest::UserIntervention {
            session_id: "intervention-session".to_string(),
            action: "approve".to_string(),
            parameters: params.clone(),
        };
        let serialized = serde_json::to_string(&request).unwrap();
        let deserialized: APIRequest = serde_json::from_str(&serialized).unwrap();
        match deserialized {
            APIRequest::UserIntervention {
                session_id,
                action,
                parameters,
            } => {
                assert_eq!(session_id, "intervention-session");
                assert_eq!(action, "approve");
                assert_eq!(parameters.get("key"), Some(&"value".to_string()));
            }
            _ => panic!("Unexpected request type"),
        }
    }

    // ==================== APIResponse Tests ====================

    #[test]
    fn test_api_response_workflow_started() {
        let response = APIResponse::WorkflowStarted {
            session_id: "started-session".to_string(),
            stream_subject: Some("smith.planner.streams.test".to_string()),
        };
        let serialized = serde_json::to_string(&response).unwrap();
        let deserialized: APIResponse = serde_json::from_str(&serialized).unwrap();
        match deserialized {
            APIResponse::WorkflowStarted {
                session_id,
                stream_subject,
            } => {
                assert_eq!(session_id, "started-session");
                assert!(stream_subject.is_some());
            }
            _ => panic!("Unexpected response type"),
        }
    }

    #[test]
    fn test_api_response_workflow_stopped() {
        let response = APIResponse::WorkflowStopped {
            session_id: "stopped-session".to_string(),
            summary: None,
        };
        let serialized = serde_json::to_string(&response).unwrap();
        let deserialized: APIResponse = serde_json::from_str(&serialized).unwrap();
        match deserialized {
            APIResponse::WorkflowStopped {
                session_id,
                summary,
            } => {
                assert_eq!(session_id, "stopped-session");
                assert!(summary.is_none());
            }
            _ => panic!("Unexpected response type"),
        }
    }

    #[test]
    fn test_api_response_workflow_status() {
        let mut metadata = HashMap::new();
        metadata.insert("key".to_string(), "value".to_string());
        let response = APIResponse::WorkflowStatus {
            session_id: "status-session".to_string(),
            state: WorkflowState::Executing,
            progress: 0.75,
            current_action: Some("action-123".to_string()),
            metadata,
        };
        let serialized = serde_json::to_string(&response).unwrap();
        let deserialized: APIResponse = serde_json::from_str(&serialized).unwrap();
        match deserialized {
            APIResponse::WorkflowStatus {
                session_id,
                progress,
                ..
            } => {
                assert_eq!(session_id, "status-session");
                assert_eq!(progress, 0.75);
            }
            _ => panic!("Unexpected response type"),
        }
    }

    #[test]
    fn test_api_response_active_workflows() {
        let workflows = vec![WorkflowInfo {
            session_id: "workflow-1".to_string(),
            workflow_type: WorkflowType::Simple,
            state: WorkflowState::Executing,
            progress: 0.5,
            created_at: 1000,
            last_activity: 2000,
            duration_ms: 1000,
        }];
        let response = APIResponse::ActiveWorkflows { workflows };
        let serialized = serde_json::to_string(&response).unwrap();
        let deserialized: APIResponse = serde_json::from_str(&serialized).unwrap();
        match deserialized {
            APIResponse::ActiveWorkflows { workflows } => {
                assert_eq!(workflows.len(), 1);
                assert_eq!(workflows[0].session_id, "workflow-1");
            }
            _ => panic!("Unexpected response type"),
        }
    }

    #[test]
    fn test_api_response_error() {
        let mut details = HashMap::new();
        details.insert("field".to_string(), "invalid".to_string());
        let response = APIResponse::Error {
            code: "VALIDATION_ERROR".to_string(),
            message: "Invalid parameters".to_string(),
            details: Some(details),
        };
        let serialized = serde_json::to_string(&response).unwrap();
        let deserialized: APIResponse = serde_json::from_str(&serialized).unwrap();
        match deserialized {
            APIResponse::Error {
                code,
                message,
                details,
            } => {
                assert_eq!(code, "VALIDATION_ERROR");
                assert_eq!(message, "Invalid parameters");
                assert!(details.is_some());
            }
            _ => panic!("Unexpected response type"),
        }
    }

    #[test]
    fn test_api_response_health_status() {
        let mut details = HashMap::new();
        details.insert("uptime".to_string(), "1234".to_string());
        let response = APIResponse::HealthStatus {
            component: "executor".to_string(),
            status: HealthStatus::Healthy,
            details,
        };
        let serialized = serde_json::to_string(&response).unwrap();
        let deserialized: APIResponse = serde_json::from_str(&serialized).unwrap();
        match deserialized {
            APIResponse::HealthStatus { component, .. } => {
                assert_eq!(component, "executor");
            }
            _ => panic!("Unexpected response type"),
        }
    }

    #[test]
    fn test_api_response_metrics() {
        let response = APIResponse::Metrics {
            data: "{\"cpu\": 50}".to_string(),
            format: "json".to_string(),
        };
        let serialized = serde_json::to_string(&response).unwrap();
        let deserialized: APIResponse = serde_json::from_str(&serialized).unwrap();
        match deserialized {
            APIResponse::Metrics { data, format } => {
                assert!(data.contains("cpu"));
                assert_eq!(format, "json");
            }
            _ => panic!("Unexpected response type"),
        }
    }

    #[test]
    fn test_api_response_intervention_result() {
        let response = APIResponse::InterventionResult {
            session_id: "intervention-session".to_string(),
            success: true,
            message: "Action completed".to_string(),
        };
        let serialized = serde_json::to_string(&response).unwrap();
        let deserialized: APIResponse = serde_json::from_str(&serialized).unwrap();
        match deserialized {
            APIResponse::InterventionResult {
                session_id,
                success,
                message,
            } => {
                assert_eq!(session_id, "intervention-session");
                assert!(success);
                assert_eq!(message, "Action completed");
            }
            _ => panic!("Unexpected response type"),
        }
    }

    // ==================== WorkflowInfo Tests ====================

    #[tokio::test]
    async fn test_workflow_info_serialization() {
        let info = WorkflowInfo {
            session_id: "test-session".to_string(),
            workflow_type: WorkflowType::ResearchAndPlanning,
            state: WorkflowState::Executing,
            progress: 0.5,
            created_at: 1234567890,
            last_activity: 1234567900,
            duration_ms: 10000,
        };

        let serialized = serde_json::to_string(&info).unwrap();
        let deserialized: WorkflowInfo = serde_json::from_str(&serialized).unwrap();

        assert_eq!(deserialized.session_id, "test-session");
        assert_eq!(deserialized.progress, 0.5);
        assert_eq!(deserialized.created_at, 1234567890);
        assert_eq!(deserialized.last_activity, 1234567900);
        assert_eq!(deserialized.duration_ms, 10000);
    }

    #[test]
    fn test_workflow_info_all_states() {
        let states = [
            WorkflowState::Initializing,
            WorkflowState::Planning,
            WorkflowState::Executing,
            WorkflowState::Paused,
            WorkflowState::Completed,
        ];

        for state in states {
            let info = WorkflowInfo {
                session_id: "state-test".to_string(),
                workflow_type: WorkflowType::Simple,
                state: state.clone(),
                progress: 0.0,
                created_at: 0,
                last_activity: 0,
                duration_ms: 0,
            };
            let serialized = serde_json::to_string(&info).unwrap();
            let deserialized: WorkflowInfo = serde_json::from_str(&serialized).unwrap();
            assert_eq!(deserialized.session_id, "state-test");
        }
    }

    // ==================== APIEvent Tests ====================

    #[test]
    fn test_api_event_workflow_started() {
        let event = APIEvent::WorkflowStarted {
            session_id: "event-session".to_string(),
            workflow_type: WorkflowType::ResearchAndPlanning,
        };
        let serialized = serde_json::to_string(&event).unwrap();
        assert!(serialized.contains("WorkflowStarted"));
        assert!(serialized.contains("event-session"));
    }

    #[test]
    fn test_api_event_workflow_failed() {
        let event = APIEvent::WorkflowFailed {
            session_id: "failed-session".to_string(),
            error: "Test error".to_string(),
        };
        let serialized = serde_json::to_string(&event).unwrap();
        assert!(serialized.contains("WorkflowFailed"));
        assert!(serialized.contains("Test error"));
    }

    #[test]
    fn test_api_event_state_transition() {
        let event = APIEvent::StateTransition {
            session_id: "transition-session".to_string(),
            from_state: WorkflowState::Planning,
            to_state: WorkflowState::Executing,
        };
        let serialized = serde_json::to_string(&event).unwrap();
        assert!(serialized.contains("StateTransition"));
    }

    #[test]
    fn test_api_event_user_intervention() {
        let event = APIEvent::UserIntervention {
            session_id: "user-session".to_string(),
            intervention_type: "approval".to_string(),
        };
        let serialized = serde_json::to_string(&event).unwrap();
        assert!(serialized.contains("UserIntervention"));
        assert!(serialized.contains("approval"));
    }

    #[test]
    fn test_api_event_system_error() {
        let event = APIEvent::SystemError {
            session_id: "error-session".to_string(),
            error: "System failure".to_string(),
        };
        let serialized = serde_json::to_string(&event).unwrap();
        assert!(serialized.contains("SystemError"));
    }

    #[test]
    fn test_api_event_health_check() {
        let event = APIEvent::HealthCheck {
            component: "nats".to_string(),
            status: HealthStatus::Healthy,
        };
        let serialized = serde_json::to_string(&event).unwrap();
        assert!(serialized.contains("HealthCheck"));
        assert!(serialized.contains("nats"));
    }

    #[test]
    fn test_api_event_clone() {
        let event = APIEvent::WorkflowStarted {
            session_id: "clone-test".to_string(),
            workflow_type: WorkflowType::Simple,
        };
        let cloned = event.clone();
        let serialized = serde_json::to_string(&cloned).unwrap();
        assert!(serialized.contains("clone-test"));
    }

    // ==================== convert_resource_utilization Tests ====================

    #[test]
    fn test_convert_resource_utilization() {
        let util = ResourceUtilization {
            avg_memory_mb: 128.0,
            peak_memory_mb: 256.0,
            avg_cpu_percent: 50.0,
            peak_cpu_percent: 80.0,
            network_io_mb: 10.0,
            disk_io_mb: 5.0,
            execution_efficiency: 0.95,
        };
        let usage = convert_resource_utilization(&util);
        assert_eq!(usage.cpu_ms, 50000); // 50.0 * 1000
        assert_eq!(usage.memory_bytes, 268435456); // 256 * 1024 * 1024
        assert_eq!(usage.network_requests, 100); // 10.0 * 10
        assert_eq!(usage.fs_operations, 0);
    }

    #[test]
    fn test_convert_resource_utilization_zero() {
        let util = ResourceUtilization {
            avg_memory_mb: 0.0,
            peak_memory_mb: 0.0,
            avg_cpu_percent: 0.0,
            peak_cpu_percent: 0.0,
            network_io_mb: 0.0,
            disk_io_mb: 0.0,
            execution_efficiency: 0.0,
        };
        let usage = convert_resource_utilization(&util);
        assert_eq!(usage.cpu_ms, 0);
        assert_eq!(usage.memory_bytes, 0);
        assert_eq!(usage.network_requests, 0);
    }

    #[test]
    fn test_convert_resource_utilization_high_values() {
        let util = ResourceUtilization {
            avg_memory_mb: 512.0,
            peak_memory_mb: 1024.0,
            avg_cpu_percent: 100.0,
            peak_cpu_percent: 100.0,
            network_io_mb: 100.0,
            disk_io_mb: 50.0,
            execution_efficiency: 1.0,
        };
        let usage = convert_resource_utilization(&util);
        assert_eq!(usage.cpu_ms, 100000);
        assert_eq!(usage.memory_bytes, 1073741824); // 1GB
        assert_eq!(usage.network_requests, 1000);
    }
}