caxton 0.1.4

A secure WebAssembly runtime for multi-agent systems
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
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
---
title: Testing Strategies and Best Practices
layout: documentation
description: Comprehensive guide to testing multi-agent systems in Caxton, including unit tests, integration tests, and load testing strategies.
---

# Testing Strategies and Best Practices

Testing multi-agent systems presents unique challenges due to their distributed, asynchronous, and interactive nature. This guide provides comprehensive strategies for testing Caxton agents and the platform itself, ensuring reliability, performance, and correctness.

## Testing Philosophy

### Multi-Layer Testing Strategy

```
┌─────────────────────────────────────────────────────────┐
│ End-to-End Tests                                       │
│ • Full system scenarios                                │
│ • Multi-agent workflows                                │
│ • Performance under load                               │
└─────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────┐
│ Integration Tests                                      │
│ • Agent-to-agent communication                         │
│ • API endpoint testing                                 │
│ • Protocol compliance                                  │
└─────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────┐
│ Component Tests                                        │
│ • WASM agent testing                                   │
│ • Message routing                                      │
│ • Resource management                                  │
└─────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────┐
│ Unit Tests                                             │
│ • Individual functions                                 │
│ • Data structures                                      │
│ • Algorithm correctness                                │
└─────────────────────────────────────────────────────────┘
```

### Testing Principles

1. **Isolation**: Each test should be independent and not affect others
2. **Repeatability**: Tests must produce consistent results across environments
3. **Observability**: Tests should provide clear failure diagnosis
4. **Performance**: Tests should execute quickly to enable frequent runs
5. **Realism**: Test scenarios should reflect real-world usage patterns

## Unit Testing

### Testing WASM Agents

#### Test Framework Setup

```rust
// tests/test_framework.rs
use serde_json::json;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

pub struct MockHost {
    sent_messages: Arc<Mutex<Vec<FipaMessage>>>,
    stored_data: Arc<Mutex<HashMap<String, Vec<u8>>>>,
    current_timestamp: u64,
}

impl MockHost {
    pub fn new() -> Self {
        Self {
            sent_messages: Arc::new(Mutex::new(Vec::new())),
            stored_data: Arc::new(Mutex::new(HashMap::new())),
            current_timestamp: 1642684800000000, // Fixed timestamp for tests
        }
    }

    pub fn get_sent_messages(&self) -> Vec<FipaMessage> {
        self.sent_messages.lock().unwrap().clone()
    }

    pub fn clear_sent_messages(&self) {
        self.sent_messages.lock().unwrap().clear();
    }

    pub fn set_stored_data(&self, key: &str, data: &[u8]) {
        self.stored_data.lock().unwrap().insert(key.to_string(), data.to_vec());
    }

    pub fn get_stored_data(&self, key: &str) -> Option<Vec<u8>> {
        self.stored_data.lock().unwrap().get(key).cloned()
    }
}

// Mock host functions
static mut MOCK_HOST: Option<MockHost> = None;

#[no_mangle]
pub extern "C" fn send_message(msg_ptr: *const u8, msg_len: usize) -> i32 {
    let msg_bytes = unsafe { std::slice::from_raw_parts(msg_ptr, msg_len) };

    if let Ok(message) = serde_json::from_slice::<FipaMessage>(msg_bytes) {
        unsafe {
            if let Some(ref host) = MOCK_HOST {
                host.sent_messages.lock().unwrap().push(message);
                return 0;
            }
        }
    }

    1
}

#[no_mangle]
pub extern "C" fn current_timestamp() -> u64 {
    unsafe {
        MOCK_HOST.as_ref().map_or(0, |host| host.current_timestamp)
    }
}

#[no_mangle]
pub extern "C" fn store_data(key_ptr: *const u8, key_len: usize,
                             data_ptr: *const u8, data_len: usize) -> i32 {
    let key_bytes = unsafe { std::slice::from_raw_parts(key_ptr, key_len) };
    let data_bytes = unsafe { std::slice::from_raw_parts(data_ptr, data_len) };

    if let Ok(key) = std::str::from_utf8(key_bytes) {
        unsafe {
            if let Some(ref host) = MOCK_HOST {
                host.set_stored_data(key, data_bytes);
                return 0;
            }
        }
    }

    1
}

pub fn setup_test_environment() -> MockHost {
    let host = MockHost::new();
    unsafe {
        MOCK_HOST = Some(MockHost::new());
    }
    host
}

pub fn teardown_test_environment() {
    unsafe {
        MOCK_HOST = None;
    }
}
```

#### Agent Unit Tests

```rust
// tests/agent_tests.rs
use super::test_framework::*;
use serde_json::json;

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

    #[test]
    fn test_agent_initialization() {
        let _host = setup_test_environment();

        // Test agent initialization
        let result = agent_init();
        assert_eq!(result, 0, "Agent initialization should succeed");

        teardown_test_environment();
    }

    #[test]
    fn test_simple_request_response() {
        let host = setup_test_environment();

        // Initialize agent
        agent_init();

        // Create test request message
        let request = json!({
            "performative": "request",
            "sender": "test_client",
            "receiver": "test_agent",
            "content": {
                "action": "echo",
                "data": "hello world"
            },
            "reply_with": "test_001"
        });

        let request_bytes = serde_json::to_vec(&request).unwrap();

        // Send message to agent
        let result = handle_message(request_bytes.as_ptr(), request_bytes.len());
        assert_eq!(result, 0, "Message handling should succeed");

        // Check that agent sent a response
        let sent_messages = host.get_sent_messages();
        assert_eq!(sent_messages.len(), 1, "Agent should send one response");

        let response = &sent_messages[0];
        assert_eq!(response.performative, "inform");
        assert_eq!(response.receiver, "test_client");
        assert_eq!(response.in_reply_to.as_ref().unwrap(), "test_001");
        assert_eq!(response.content["result"], "hello world");

        teardown_test_environment();
    }

    #[test]
    fn test_invalid_message_handling() {
        let host = setup_test_environment();
        agent_init();

        // Send invalid JSON
        let invalid_json = b"invalid json data";
        let result = handle_message(invalid_json.as_ptr(), invalid_json.len());
        assert_ne!(result, 0, "Invalid JSON should be rejected");

        // Send message with invalid performative
        let invalid_performative = json!({
            "performative": "invalid_performative",
            "sender": "test_client",
            "receiver": "test_agent",
            "content": {}
        });

        let msg_bytes = serde_json::to_vec(&invalid_performative).unwrap();
        let result = handle_message(msg_bytes.as_ptr(), msg_bytes.len());

        // Should send NOT_UNDERSTOOD
        let sent_messages = host.get_sent_messages();
        assert!(!sent_messages.is_empty(), "Agent should respond to invalid performative");
        assert_eq!(sent_messages[0].performative, "not_understood");

        teardown_test_environment();
    }

    #[test]
    fn test_data_processing_operations() {
        let host = setup_test_environment();
        agent_init();

        let test_cases = vec![
            ("uppercase", "hello", "HELLO"),
            ("lowercase", "WORLD", "world"),
            ("reverse", "abc", "cba"),
            ("length", "test", "4"),
        ];

        for (operation, input, expected) in test_cases {
            host.clear_sent_messages();

            let request = json!({
                "performative": "request",
                "sender": "test_client",
                "receiver": "test_agent",
                "content": {
                    "action": "process_text",
                    "operation": operation,
                    "text": input
                },
                "reply_with": format!("test_{}", operation)
            });

            let request_bytes = serde_json::to_vec(&request).unwrap();
            let result = handle_message(request_bytes.as_ptr(), request_bytes.len());

            assert_eq!(result, 0, "Operation {} should succeed", operation);

            let sent_messages = host.get_sent_messages();
            assert_eq!(sent_messages.len(), 1, "Should send one response for {}", operation);

            let response = &sent_messages[0];
            assert_eq!(response.performative, "inform");
            assert_eq!(
                response.content["result"].as_str().unwrap(),
                expected,
                "Operation {} should produce correct result",
                operation
            );
        }

        teardown_test_environment();
    }

    #[test]
    fn test_state_persistence() {
        let host = setup_test_environment();
        agent_init();

        // Set some state
        let set_request = json!({
            "performative": "request",
            "sender": "test_client",
            "receiver": "test_agent",
            "content": {
                "action": "set_counter",
                "counter_name": "test_counter",
                "value": 42
            },
            "reply_with": "set_001"
        });

        let request_bytes = serde_json::to_vec(&set_request).unwrap();
        let result = handle_message(request_bytes.as_ptr(), request_bytes.len());
        assert_eq!(result, 0);

        // Verify state was stored
        let stored_data = host.get_stored_data("counters");
        assert!(stored_data.is_some(), "Counter data should be stored");

        // Get the state
        host.clear_sent_messages();
        let get_request = json!({
            "performative": "request",
            "sender": "test_client",
            "receiver": "test_agent",
            "content": {
                "action": "get_counter",
                "counter_name": "test_counter"
            },
            "reply_with": "get_001"
        });

        let request_bytes = serde_json::to_vec(&get_request).unwrap();
        let result = handle_message(request_bytes.as_ptr(), request_bytes.len());
        assert_eq!(result, 0);

        let sent_messages = host.get_sent_messages();
        assert_eq!(sent_messages.len(), 1);
        assert_eq!(sent_messages[0].content["value"], 42);

        teardown_test_environment();
    }

    #[test]
    fn test_resource_limits() {
        let host = setup_test_environment();
        agent_init();

        // Test memory allocation limits
        let large_request = json!({
            "performative": "request",
            "sender": "test_client",
            "receiver": "test_agent",
            "content": {
                "action": "allocate_memory",
                "size": 100 * 1024 * 1024 // 100MB - should exceed limits
            },
            "reply_with": "memory_test"
        });

        let request_bytes = serde_json::to_vec(&large_request).unwrap();
        let result = handle_message(request_bytes.as_ptr(), request_bytes.len());

        // Should either fail during processing or send failure response
        if result == 0 {
            let sent_messages = host.get_sent_messages();
            assert_eq!(sent_messages.len(), 1);
            assert_eq!(sent_messages[0].performative, "failure");
        } else {
            assert_ne!(result, 0, "Large allocation should fail");
        }

        teardown_test_environment();
    }

    #[test]
    fn test_concurrent_message_handling() {
        let host = setup_test_environment();
        agent_init();

        // Send multiple messages in sequence
        let message_count = 10;
        for i in 0..message_count {
            let request = json!({
                "performative": "request",
                "sender": "test_client",
                "receiver": "test_agent",
                "content": {
                    "action": "increment_counter",
                    "counter_name": "concurrent_test"
                },
                "reply_with": format!("concurrent_{}", i)
            });

            let request_bytes = serde_json::to_vec(&request).unwrap();
            let result = handle_message(request_bytes.as_ptr(), request_bytes.len());
            assert_eq!(result, 0, "Message {} should succeed", i);
        }

        // Verify all messages were processed
        let sent_messages = host.get_sent_messages();
        assert_eq!(sent_messages.len(), message_count);

        // Check final counter value
        host.clear_sent_messages();
        let get_request = json!({
            "performative": "request",
            "sender": "test_client",
            "receiver": "test_agent",
            "content": {
                "action": "get_counter",
                "counter_name": "concurrent_test"
            },
            "reply_with": "get_final"
        });

        let request_bytes = serde_json::to_vec(&get_request).unwrap();
        handle_message(request_bytes.as_ptr(), request_bytes.len());

        let sent_messages = host.get_sent_messages();
        assert_eq!(sent_messages[0].content["value"], message_count);

        teardown_test_environment();
    }
}
```

### Property-Based Testing

Test agents with randomly generated inputs to discover edge cases:

```rust
// tests/property_tests.rs
use proptest::prelude::*;
use serde_json::json;

proptest! {
    #[test]
    fn test_message_content_robustness(
        content in prop::collection::hash_map(
            "[a-zA-Z0-9_]{1,20}",
            any::<serde_json::Value>(),
            0..10
        )
    ) {
        let host = setup_test_environment();
        agent_init();

        let request = json!({
            "performative": "request",
            "sender": "property_test",
            "receiver": "test_agent",
            "content": content,
            "reply_with": "property_001"
        });

        let request_bytes = serde_json::to_vec(&request).unwrap();
        let result = handle_message(request_bytes.as_ptr(), request_bytes.len());

        // Agent should either succeed or fail gracefully (no panics)
        assert!(result == 0 || result != 0, "Agent should handle arbitrary content");

        // If it succeeded, should have sent a response
        if result == 0 {
            let sent_messages = host.get_sent_messages();
            assert!(!sent_messages.is_empty(), "Successful handling should send response");
        }

        teardown_test_environment();
    }

    #[test]
    fn test_text_processing_operations(
        text in "[\\PC]{0,1000}",
        operation in "uppercase|lowercase|reverse|length"
    ) {
        let host = setup_test_environment();
        agent_init();

        let request = json!({
            "performative": "request",
            "sender": "property_test",
            "receiver": "test_agent",
            "content": {
                "action": "process_text",
                "operation": operation,
                "text": text
            },
            "reply_with": "prop_test"
        });

        let request_bytes = serde_json::to_vec(&request).unwrap();
        let result = handle_message(request_bytes.as_ptr(), request_bytes.len());

        // Text processing should always succeed
        prop_assert_eq!(result, 0);

        let sent_messages = host.get_sent_messages();
        prop_assert_eq!(sent_messages.len(), 1);

        let response = &sent_messages[0];
        prop_assert_eq!(response.performative, "inform");

        // Verify operation correctness
        let result_str = response.content["result"].as_str().unwrap();
        match operation {
            "uppercase" => prop_assert_eq!(result_str, text.to_uppercase()),
            "lowercase" => prop_assert_eq!(result_str, text.to_lowercase()),
            "reverse" => prop_assert_eq!(result_str, text.chars().rev().collect::<String>()),
            "length" => prop_assert_eq!(result_str, text.len().to_string()),
            _ => unreachable!()
        }

        teardown_test_environment();
    }
}
```

## Integration Testing

### Multi-Agent Communication Testing

```rust
// tests/integration_tests.rs
use caxton_client::*;
use tokio::time::{timeout, Duration, sleep};
use std::fs;

#[tokio::test]
async fn test_agent_to_agent_communication() {
    let client = CaxtonClient::new("http://localhost:8080").await.unwrap();

    // Deploy sender agent
    let sender_wasm = fs::read("target/wasm32-wasi/release/sender_agent.wasm").unwrap();
    let sender = client.deploy_agent(DeployAgentRequest {
        wasm_module: sender_wasm,
        config: AgentConfig {
            name: "sender_agent".to_string(),
            capabilities: vec!["message_sending".to_string()],
            ..Default::default()
        },
    }).await.unwrap();

    // Deploy receiver agent
    let receiver_wasm = fs::read("target/wasm32-wasi/release/receiver_agent.wasm").unwrap();
    let receiver = client.deploy_agent(DeployAgentRequest {
        wasm_module: receiver_wasm,
        config: AgentConfig {
            name: "receiver_agent".to_string(),
            capabilities: vec!["message_receiving".to_string()],
            ..Default::default()
        },
    }).await.unwrap();

    // Wait for agents to be ready
    sleep(Duration::from_millis(500)).await;

    // Subscribe to messages from receiver
    let mut message_stream = client.subscribe_to_messages(MessageFilter {
        sender_ids: Some(vec![receiver.agent_id.clone()]),
        performatives: Some(vec!["inform".to_string()]),
        ..Default::default()
    }).await.unwrap();

    // Send command to sender agent
    client.send_message(FipaMessage {
        performative: "request".to_string(),
        sender: "integration_test".to_string(),
        receiver: sender.agent_id.clone(),
        content: json!({
            "action": "send_greeting",
            "target_agent": receiver.agent_id,
            "message": "Hello from integration test!"
        }),
        ..Default::default()
    }).await.unwrap();

    // Wait for inter-agent communication to complete
    let response = timeout(
        Duration::from_secs(10),
        message_stream.next()
    ).await.unwrap().unwrap();

    // Verify the communication chain worked
    assert_eq!(response.sender, receiver.agent_id);
    assert_eq!(response.performative, "inform");
    assert!(response.content["processed_greeting"].as_str().unwrap()
        .contains("Hello from integration test!"));

    // Cleanup
    client.remove_agent(&sender.agent_id).await.unwrap();
    client.remove_agent(&receiver.agent_id).await.unwrap();
}

#[tokio::test]
async fn test_contract_net_protocol() {
    let client = CaxtonClient::new("http://localhost:8080").await.unwrap();

    // Deploy task coordinator
    let coordinator_wasm = fs::read("target/wasm32-wasi/release/coordinator_agent.wasm").unwrap();
    let coordinator = client.deploy_agent(DeployAgentRequest {
        wasm_module: coordinator_wasm,
        config: AgentConfig {
            name: "task_coordinator".to_string(),
            capabilities: vec!["task_coordination".to_string()],
            ..Default::default()
        },
    }).await.unwrap();

    // Deploy multiple worker agents
    let worker_wasm = fs::read("target/wasm32-wasi/release/worker_agent.wasm").unwrap();
    let mut workers = Vec::new();

    for i in 0..3 {
        let worker = client.deploy_agent(DeployAgentRequest {
            wasm_module: worker_wasm.clone(),
            config: AgentConfig {
                name: format!("worker_agent_{}", i),
                capabilities: vec!["data_processing".to_string()],
                ..Default::default()
            },
        }).await.unwrap();
        workers.push(worker);
    }

    // Wait for all agents to be ready
    sleep(Duration::from_millis(1000)).await;

    // Subscribe to task completion messages
    let mut completion_stream = client.subscribe_to_messages(MessageFilter {
        performatives: Some(vec!["inform".to_string()]),
        content_filters: Some(vec![
            ("task_completed".to_string(), serde_json::Value::Bool(true))
        ]),
        ..Default::default()
    }).await.unwrap();

    // Start contract net protocol
    let task_request = FipaMessage {
        performative: "request".to_string(),
        sender: "integration_test".to_string(),
        receiver: coordinator.agent_id.clone(),
        content: json!({
            "action": "distribute_task",
            "task": {
                "id": "test_task_001",
                "description": "Process dataset",
                "requirements": {
                    "capability": "data_processing",
                    "deadline": "2024-01-15T18:00:00Z"
                },
                "data": {"size": 1000, "type": "json"}
            },
            "protocol": "contract_net"
        }),
        conversation_id: Some("contract_net_test_001".to_string()),
        ..Default::default()
    };

    client.send_message(task_request).await.unwrap();

    // Wait for task completion (contract net + execution)
    let completion_msg = timeout(
        Duration::from_secs(30),
        completion_stream.next()
    ).await.unwrap().unwrap();

    // Verify task was completed successfully
    assert_eq!(completion_msg.performative, "inform");
    assert_eq!(completion_msg.content["task_id"], "test_task_001");
    assert_eq!(completion_msg.content["status"], "completed");
    assert!(completion_msg.content["result"].is_object());

    // Cleanup all agents
    client.remove_agent(&coordinator.agent_id).await.unwrap();
    for worker in workers {
        client.remove_agent(&worker.agent_id).await.unwrap();
    }
}

#[tokio::test]
async fn test_message_ordering_and_delivery() {
    let client = CaxtonClient::new("http://localhost:8080").await.unwrap();

    // Deploy sequence processor agent
    let processor_wasm = fs::read("target/wasm32-wasi/release/sequence_processor.wasm").unwrap();
    let processor = client.deploy_agent(DeployAgentRequest {
        wasm_module: processor_wasm,
        config: AgentConfig {
            name: "sequence_processor".to_string(),
            ..Default::default()
        },
    }).await.unwrap();

    sleep(Duration::from_millis(200)).await;

    // Send sequence of numbered messages
    let message_count = 50;
    for i in 0..message_count {
        let message = FipaMessage {
            performative: "inform".to_string(),
            sender: "integration_test".to_string(),
            receiver: processor.agent_id.clone(),
            content: json!({
                "sequence_number": i,
                "data": format!("Message {}", i)
            }),
            ..Default::default()
        };

        client.send_message(message).await.unwrap();

        // Small delay to test ordering
        if i % 5 == 0 {
            sleep(Duration::from_millis(10)).await;
        }
    }

    // Request sequence verification
    sleep(Duration::from_millis(500)).await;
    let verification_response = client.send_message_and_wait(
        FipaMessage {
            performative: "request".to_string(),
            sender: "integration_test".to_string(),
            receiver: processor.agent_id.clone(),
            content: json!({
                "action": "verify_sequence",
                "expected_count": message_count
            }),
            reply_with: Some("sequence_check".to_string()),
            ..Default::default()
        },
        Duration::from_secs(10)
    ).await.unwrap();

    // Verify all messages were received in order
    assert_eq!(verification_response.performative, "inform");
    assert_eq!(verification_response.content["messages_received"], message_count);
    assert_eq!(verification_response.content["sequence_valid"], true);

    client.remove_agent(&processor.agent_id).await.unwrap();
}
```

### API Testing

```rust
// tests/api_tests.rs
use reqwest::Client;
use serde_json::json;
use std::collections::HashMap;

#[tokio::test]
async fn test_agent_lifecycle_api() {
    let client = Client::new();
    let base_url = "http://localhost:8080/api/v1";

    // Load test agent WASM
    let wasm_bytes = std::fs::read("target/wasm32-wasi/release/test_agent.wasm").unwrap();
    let wasm_b64 = base64::encode(&wasm_bytes);

    // Test agent deployment
    // Note: capabilities are registered in code, not config
    // In test code, capabilities should be mocked/stubbed rather than configured via JSON
    let deploy_request = json!({
        "wasm_module": wasm_b64,
        "config": {
            "name": "api_test_agent",
            "resources": {
                "memory": "50MB",
                "cpu": "100m"
            }
            // capabilities field removed - handle via mocks in test code
        }
    });

    let deploy_response = client
        .post(&format!("{}/agents", base_url))
        .json(&deploy_request)
        .send()
        .await
        .unwrap();

    assert_eq!(deploy_response.status(), 200);
    let agent_info: serde_json::Value = deploy_response.json().await.unwrap();
    let agent_id = agent_info["agent_id"].as_str().unwrap();

    // Test agent listing
    let list_response = client
        .get(&format!("{}/agents", base_url))
        .send()
        .await
        .unwrap();

    assert_eq!(list_response.status(), 200);
    let agents_list: serde_json::Value = list_response.json().await.unwrap();
    assert!(agents_list["agents"].as_array().unwrap().len() > 0);

    // Test get agent details
    let agent_response = client
        .get(&format!("{}/agents/{}", base_url, agent_id))
        .send()
        .await
        .unwrap();

    assert_eq!(agent_response.status(), 200);
    let agent_details: serde_json::Value = agent_response.json().await.unwrap();
    assert_eq!(agent_details["agent_id"], agent_id);
    assert_eq!(agent_details["name"], "api_test_agent");
    assert_eq!(agent_details["status"], "running");

    // Test message sending
    let message_request = json!({
        "performative": "request",
        "sender": "api_test",
        "receiver": agent_id,
        "content": {
            "action": "ping"
        },
        "reply_with": "api_ping_001"
    });

    let message_response = client
        .post(&format!("{}/messages", base_url))
        .json(&message_request)
        .send()
        .await
        .unwrap();

    assert_eq!(message_response.status(), 200);
    let send_result: serde_json::Value = message_response.json().await.unwrap();
    assert_eq!(send_result["status"], "delivered");

    // Test agent stopping
    let stop_response = client
        .post(&format!("{}/agents/{}/stop", base_url, agent_id))
        .json(&json!({"grace_period_seconds": 5}))
        .send()
        .await
        .unwrap();

    assert_eq!(stop_response.status(), 200);

    // Wait for graceful shutdown
    tokio::time::sleep(tokio::time::Duration::from_secs(6)).await;

    // Test agent removal
    let remove_response = client
        .delete(&format!("{}/agents/{}", base_url, agent_id))
        .send()
        .await
        .unwrap();

    assert_eq!(remove_response.status(), 200);

    // Verify agent is gone
    let check_response = client
        .get(&format!("{}/agents/{}", base_url, agent_id))
        .send()
        .await
        .unwrap();

    assert_eq!(check_response.status(), 404);
}

#[tokio::test]
async fn test_metrics_api() {
    let client = Client::new();
    let base_url = "http://localhost:8080/api/v1";

    // Test system metrics
    let system_metrics_response = client
        .get(&format!("{}/metrics/system", base_url))
        .send()
        .await
        .unwrap();

    assert_eq!(system_metrics_response.status(), 200);
    let metrics: serde_json::Value = system_metrics_response.json().await.unwrap();

    // Verify expected metric fields
    assert!(metrics["agents"].is_object());
    assert!(metrics["messages"].is_object());
    assert!(metrics["resources"].is_object());
    assert!(metrics["performance"].is_object());

    assert!(metrics["agents"]["total"].is_number());
    assert!(metrics["messages"]["rate_per_second"].is_number());
    assert!(metrics["resources"]["memory_used_mb"].is_number());

    // Test metrics filtering
    let filtered_response = client
        .get(&format!("{}/metrics/system?fields=agents,messages", base_url))
        .send()
        .await
        .unwrap();

    assert_eq!(filtered_response.status(), 200);
    let filtered_metrics: serde_json::Value = filtered_response.json().await.unwrap();

    assert!(filtered_metrics["agents"].is_object());
    assert!(filtered_metrics["messages"].is_object());
    assert!(filtered_metrics["resources"].is_null());
}

#[tokio::test]
async fn test_websocket_api() {
    use tokio_tungstenite::{connect_async, tungstenite::Message};
    use futures_util::{SinkExt, StreamExt};

    // Connect to WebSocket
    let (ws_stream, _) = connect_async("ws://localhost:8080/ws")
        .await
        .unwrap();

    let (mut write, mut read) = ws_stream.split();

    // Subscribe to agent events
    let subscribe_message = json!({
        "type": "subscribe",
        "events": ["agent.*", "message.*"],
        "filters": {
            "agent_ids": []
        }
    });

    write.send(Message::Text(subscribe_message.to_string()))
        .await
        .unwrap();

    // Create an agent to generate events
    let client = reqwest::Client::new();
    let wasm_bytes = std::fs::read("target/wasm32-wasi/release/test_agent.wasm").unwrap();
    let deploy_request = json!({
        "wasm_module": base64::encode(&wasm_bytes),
        "config": {
            "name": "ws_test_agent"
        }
    });

    tokio::spawn(async move {
        tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
        let _ = client
            .post("http://localhost:8080/api/v1/agents")
            .json(&deploy_request)
            .send()
            .await;
    });

    // Wait for deployment event
    let event_timeout = tokio::time::timeout(
        tokio::time::Duration::from_secs(10),
        read.next()
    );

    let event = event_timeout.await.unwrap().unwrap().unwrap();

    if let Message::Text(event_text) = event {
        let event_data: serde_json::Value = serde_json::from_str(&event_text).unwrap();
        assert_eq!(event_data["type"], "agent.deployed");
        assert!(event_data["agent_id"].is_string());
    } else {
        panic!("Expected text message");
    }
}
```

## Load Testing

### Performance Testing Framework

```rust
// tests/load_tests.rs
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use tokio::time::{Instant, Duration};
use futures::future::join_all;

#[derive(Clone)]
pub struct LoadTestMetrics {
    pub requests_sent: Arc<AtomicU64>,
    pub responses_received: Arc<AtomicU64>,
    pub errors: Arc<AtomicU64>,
    pub total_latency_micros: Arc<AtomicU64>,
    pub start_time: Instant,
}

impl LoadTestMetrics {
    pub fn new() -> Self {
        Self {
            requests_sent: Arc::new(AtomicU64::new(0)),
            responses_received: Arc::new(AtomicU64::new(0)),
            errors: Arc::new(AtomicU64::new(0)),
            total_latency_micros: Arc::new(AtomicU64::new(0)),
            start_time: Instant::now(),
        }
    }

    pub fn record_request(&self) {
        self.requests_sent.fetch_add(1, Ordering::Relaxed);
    }

    pub fn record_response(&self, latency_micros: u64) {
        self.responses_received.fetch_add(1, Ordering::Relaxed);
        self.total_latency_micros.fetch_add(latency_micros, Ordering::Relaxed);
    }

    pub fn record_error(&self) {
        self.errors.fetch_add(1, Ordering::Relaxed);
    }

    pub fn print_summary(&self) {
        let duration = self.start_time.elapsed();
        let requests = self.requests_sent.load(Ordering::Relaxed);
        let responses = self.responses_received.load(Ordering::Relaxed);
        let errors = self.errors.load(Ordering::Relaxed);
        let total_latency = self.total_latency_micros.load(Ordering::Relaxed);

        println!("Load Test Summary:");
        println!("  Duration: {:?}", duration);
        println!("  Requests sent: {}", requests);
        println!("  Responses received: {}", responses);
        println!("  Errors: {}", errors);
        println!("  Success rate: {:.2}%",
            (responses as f64 / requests as f64) * 100.0);
        println!("  Average latency: {:.2} ms",
            (total_latency as f64 / responses as f64) / 1000.0);
        println!("  Throughput: {:.2} req/sec",
            requests as f64 / duration.as_secs_f64());
    }
}

#[tokio::test]
async fn test_message_throughput() {
    let client = CaxtonClient::new("http://localhost:8080").await.unwrap();

    // Deploy high-performance echo agent
    let echo_wasm = std::fs::read("target/wasm32-wasi/release/echo_agent.wasm").unwrap();
    let echo_agent = client.deploy_agent(DeployAgentRequest {
        wasm_module: echo_wasm,
        config: AgentConfig {
            name: "load_test_echo".to_string(),
            resources: ResourceLimits {
                max_memory_bytes: 100 * 1024 * 1024, // 100MB
                max_cpu_micros: 1_000_000, // 1 second per message
                ..Default::default()
            },
            ..Default::default()
        },
    }).await.unwrap();

    tokio::time::sleep(Duration::from_millis(500)).await;

    let metrics = LoadTestMetrics::new();
    let concurrent_clients = 50;
    let messages_per_client = 100;

    // Spawn concurrent message senders
    let mut tasks = Vec::new();
    for client_id in 0..concurrent_clients {
        let client = client.clone();
        let agent_id = echo_agent.agent_id.clone();
        let metrics = metrics.clone();

        let task = tokio::spawn(async move {
            for msg_id in 0..messages_per_client {
                let start_time = Instant::now();

                let message = FipaMessage {
                    performative: "request".to_string(),
                    sender: format!("load_client_{}", client_id),
                    receiver: agent_id.clone(),
                    content: json!({
                        "action": "echo",
                        "data": format!("Message {} from client {}", msg_id, client_id)
                    }),
                    reply_with: Some(format!("load_{}_{}", client_id, msg_id)),
                    ..Default::default()
                };

                metrics.record_request();

                match client.send_message_and_wait(message, Duration::from_secs(5)).await {
                    Ok(response) => {
                        let latency = start_time.elapsed().as_micros() as u64;
                        metrics.record_response(latency);

                        // Verify response
                        if response.performative != "inform" {
                            metrics.record_error();
                        }
                    }
                    Err(_) => {
                        metrics.record_error();
                    }
                }

                // Small delay to prevent overwhelming
                if msg_id % 10 == 0 {
                    tokio::time::sleep(Duration::from_millis(1)).await;
                }
            }
        });

        tasks.push(task);
    }

    // Wait for all tasks to complete
    join_all(tasks).await;

    metrics.print_summary();

    // Verify performance targets
    let responses = metrics.responses_received.load(Ordering::Relaxed);
    let errors = metrics.errors.load(Ordering::Relaxed);
    let total_expected = (concurrent_clients * messages_per_client) as u64;

    assert!(responses > total_expected * 95 / 100,
        "Should have >95% success rate, got {}/{}", responses, total_expected);
    assert!(errors < total_expected * 5 / 100,
        "Should have <5% error rate, got {}/{}", errors, total_expected);

    let avg_latency = metrics.total_latency_micros.load(Ordering::Relaxed) / responses;
    assert!(avg_latency < 100_000, // 100ms
        "Average latency should be <100ms, got {}ms", avg_latency / 1000);

    client.remove_agent(&echo_agent.agent_id).await.unwrap();
}

#[tokio::test]
async fn test_agent_scaling() {
    let client = CaxtonClient::new("http://localhost:8080").await.unwrap();
    let wasm_bytes = std::fs::read("target/wasm32-wasi/release/simple_agent.wasm").unwrap();

    let agent_count = 100;
    let mut agents = Vec::new();

    let deployment_start = Instant::now();

    // Deploy many agents concurrently
    let mut deploy_tasks = Vec::new();
    for i in 0..agent_count {
        let client = client.clone();
        let wasm_bytes = wasm_bytes.clone();

        let task = tokio::spawn(async move {
            client.deploy_agent(DeployAgentRequest {
                wasm_module: wasm_bytes,
                config: AgentConfig {
                    name: format!("scale_test_agent_{}", i),
                    resources: ResourceLimits {
                        max_memory_bytes: 10 * 1024 * 1024, // 10MB each
                        ..Default::default()
                    },
                    ..Default::default()
                },
            }).await
        });

        deploy_tasks.push(task);
    }

    // Wait for all deployments
    let deployment_results = join_all(deploy_tasks).await;
    let deployment_time = deployment_start.elapsed();

    println!("Deployed {} agents in {:?}", agent_count, deployment_time);

    for result in deployment_results {
        let agent = result.unwrap().unwrap();
        agents.push(agent);
    }

    // Verify all agents are running
    tokio::time::sleep(Duration::from_millis(1000)).await;

    let agent_list = client.list_agents(ListAgentsRequest {
        status_filter: Some(AgentStatus::Running),
        ..Default::default()
    }).await.unwrap();

    assert!(agent_list.agents.len() >= agent_count,
        "Should have at least {} running agents", agent_count);

    // Test concurrent message handling
    let metrics = LoadTestMetrics::new();
    let mut message_tasks = Vec::new();

    for (i, agent) in agents.iter().take(50).enumerate() {
        let client = client.clone();
        let agent_id = agent.agent_id.clone();
        let metrics = metrics.clone();

        let task = tokio::spawn(async move {
            for j in 0..10 {
                let start = Instant::now();
                metrics.record_request();

                match client.send_message_and_wait(
                    FipaMessage {
                        performative: "request".to_string(),
                        sender: "scale_test".to_string(),
                        receiver: agent_id.clone(),
                        content: json!({"action": "ping", "id": j}),
                        reply_with: Some(format!("scale_{}_{}", i, j)),
                        ..Default::default()
                    },
                    Duration::from_secs(10)
                ).await {
                    Ok(_) => {
                        metrics.record_response(start.elapsed().as_micros() as u64);
                    }
                    Err(_) => {
                        metrics.record_error();
                    }
                }
            }
        });

        message_tasks.push(task);
    }

    join_all(message_tasks).await;
    metrics.print_summary();

    // Cleanup all agents
    let mut cleanup_tasks = Vec::new();
    for agent in agents {
        let client = client.clone();
        let agent_id = agent.agent_id.clone();

        let task = tokio::spawn(async move {
            client.remove_agent(&agent_id).await
        });

        cleanup_tasks.push(task);
    }

    join_all(cleanup_tasks).await;

    // Verify performance characteristics
    let responses = metrics.responses_received.load(Ordering::Relaxed);
    let total_sent = metrics.requests_sent.load(Ordering::Relaxed);
    assert!(responses > total_sent * 95 / 100, "High success rate required under load");
}

#[tokio::test]
async fn test_memory_pressure() {
    let client = CaxtonClient::new("http://localhost:8080").await.unwrap();

    // Deploy agent with limited memory
    let memory_agent_wasm = std::fs::read("target/wasm32-wasi/release/memory_test_agent.wasm").unwrap();
    let memory_agent = client.deploy_agent(DeployAgentRequest {
        wasm_module: memory_agent_wasm,
        config: AgentConfig {
            name: "memory_pressure_test".to_string(),
            resources: ResourceLimits {
                max_memory_bytes: 20 * 1024 * 1024, // 20MB limit
                ..Default::default()
            },
            ..Default::default()
        },
    }).await.unwrap();

    tokio::time::sleep(Duration::from_millis(200)).await;

    // Send increasingly large data
    for size in [1024, 10240, 102400, 1048576] { // 1KB to 1MB
        let large_data = "x".repeat(size);

        let response = client.send_message_and_wait(
            FipaMessage {
                performative: "request".to_string(),
                sender: "memory_test".to_string(),
                receiver: memory_agent.agent_id.clone(),
                content: json!({
                    "action": "process_large_data",
                    "data": large_data
                }),
                reply_with: Some(format!("memory_test_{}", size)),
                ..Default::default()
            },
            Duration::from_secs(30)
        ).await;

        match response {
            Ok(resp) => {
                println!("Successfully processed {} bytes", size);
                assert_eq!(resp.performative, "inform");
            }
            Err(e) => {
                if size > 512 * 1024 { // Expect failures for very large data
                    println!("Expected failure for {} bytes: {}", size, e);
                } else {
                    panic!("Unexpected failure for {} bytes: {}", size, e);
                }
            }
        }

        // Allow memory to be released
        tokio::time::sleep(Duration::from_millis(100)).await;
    }

    client.remove_agent(&memory_agent.agent_id).await.unwrap();
}
```

## Chaos Testing

Test system resilience under failure conditions:

```rust
// tests/chaos_tests.rs
use rand::Rng;
use std::sync::Arc;
use tokio::time::{Duration, sleep, Instant};

#[tokio::test]
async fn test_agent_failure_recovery() {
    let client = CaxtonClient::new("http://localhost:8080").await.unwrap();

    // Deploy multiple agents
    let agent_count = 10;
    let mut agents = Vec::new();
    let wasm_bytes = std::fs::read("target/wasm32-wasi/release/resilient_agent.wasm").unwrap();

    for i in 0..agent_count {
        let agent = client.deploy_agent(DeployAgentRequest {
            wasm_module: wasm_bytes.clone(),
            config: AgentConfig {
                name: format!("chaos_agent_{}", i),
                ..Default::default()
            },
        }).await.unwrap();
        agents.push(agent);
    }

    sleep(Duration::from_millis(500)).await;

    // Start continuous message sending
    let running = Arc::new(std::sync::atomic::AtomicBool::new(true));
    let message_task = {
        let client = client.clone();
        let agents = agents.clone();
        let running = running.clone();

        tokio::spawn(async move {
            let mut message_count = 0;
            while running.load(std::sync::atomic::Ordering::Relaxed) {
                let agent = &agents[message_count % agents.len()];

                let _ = client.send_message(FipaMessage {
                    performative: "inform".to_string(),
                    sender: "chaos_test".to_string(),
                    receiver: agent.agent_id.clone(),
                    content: json!({"heartbeat": message_count}),
                    ..Default::default()
                }).await;

                message_count += 1;
                sleep(Duration::from_millis(10)).await;
            }
        })
    };

    // Randomly kill and restart agents
    let chaos_task = {
        let client = client.clone();
        let mut agents = agents.clone();
        let wasm_bytes = wasm_bytes.clone();

        tokio::spawn(async move {
            let mut rng = rand::thread_rng();

            for iteration in 0..20 {
                sleep(Duration::from_millis(rng.gen_range(100..1000))).await;

                if !agents.is_empty() {
                    // Pick random agent to kill
                    let victim_idx = rng.gen_range(0..agents.len());
                    let victim = agents.remove(victim_idx);

                    println!("Chaos iteration {}: Killing agent {}", iteration, victim.agent_id);
                    let _ = client.remove_agent(&victim.agent_id).await;

                    // Wait a bit, then restart
                    sleep(Duration::from_millis(rng.gen_range(100..500))).await;

                    match client.deploy_agent(DeployAgentRequest {
                        wasm_module: wasm_bytes.clone(),
                        config: AgentConfig {
                            name: format!("chaos_agent_restart_{}", iteration),
                            ..Default::default()
                        },
                    }).await {
                        Ok(new_agent) => {
                            println!("Restarted as agent {}", new_agent.agent_id);
                            agents.push(new_agent);
                        }
                        Err(e) => {
                            eprintln!("Failed to restart agent: {}", e);
                        }
                    }
                }
            }
        })
    };

    // Run chaos for 30 seconds
    sleep(Duration::from_secs(30)).await;
    running.store(false, std::sync::atomic::Ordering::Relaxed);

    // Wait for tasks to complete
    let _ = tokio::join!(message_task, chaos_task);

    // Verify system is still functional
    let final_agent_list = client.list_agents(ListAgentsRequest::default()).await.unwrap();
    assert!(!final_agent_list.agents.is_empty(), "System should still have agents running");

    // Test that remaining agents are responsive
    if let Some(agent) = final_agent_list.agents.first() {
        let response = client.send_message_and_wait(
            FipaMessage {
                performative: "request".to_string(),
                sender: "chaos_test".to_string(),
                receiver: agent.agent_id.clone(),
                content: json!({"action": "ping"}),
                reply_with: Some("post_chaos_ping".to_string()),
                ..Default::default()
            },
            Duration::from_secs(5)
        ).await;

        assert!(response.is_ok(), "Remaining agents should be responsive");
    }

    // Cleanup remaining agents
    for agent in final_agent_list.agents {
        let _ = client.remove_agent(&agent.agent_id).await;
    }
}

#[tokio::test]
async fn test_network_partition_simulation() {
    // This test simulates network partitions by temporarily blocking
    // communication between groups of agents

    let client = CaxtonClient::new("http://localhost:8080").await.unwrap();

    // Deploy agents in two "partitions"
    let partition_a_agents = deploy_agent_group(&client, "partition_a", 5).await;
    let partition_b_agents = deploy_agent_group(&client, "partition_b", 5).await;

    sleep(Duration::from_millis(500)).await;

    // Start inter-partition communication
    let communication_task = start_inter_partition_communication(
        &client,
        &partition_a_agents,
        &partition_b_agents
    ).await;

    // Simulate network partition for 10 seconds
    // (In a real test, you'd configure network rules or use proxy)
    println!("Simulating network partition...");
    sleep(Duration::from_secs(10)).await;

    // Resume communication
    println!("Restoring network connectivity...");
    sleep(Duration::from_secs(5)).await;

    // Stop communication test
    communication_task.abort();

    // Verify agents are still responsive within their partitions
    for agent in &partition_a_agents {
        let response = client.send_message_and_wait(
            FipaMessage {
                performative: "request".to_string(),
                sender: "partition_test".to_string(),
                receiver: agent.agent_id.clone(),
                content: json!({"action": "status_check"}),
                reply_with: Some("status_check".to_string()),
                ..Default::default()
            },
            Duration::from_secs(5)
        ).await;

        assert!(response.is_ok(), "Agent should be responsive after partition");
    }

    // Cleanup
    cleanup_agents(&client, &partition_a_agents).await;
    cleanup_agents(&client, &partition_b_agents).await;
}

async fn deploy_agent_group(
    client: &CaxtonClient,
    group_name: &str,
    count: usize
) -> Vec<DeployAgentResponse> {
    let mut agents = Vec::new();
    let wasm_bytes = std::fs::read("target/wasm32-wasi/release/partition_test_agent.wasm").unwrap();

    for i in 0..count {
        let agent = client.deploy_agent(DeployAgentRequest {
            wasm_module: wasm_bytes.clone(),
            config: AgentConfig {
                name: format!("{}_{}", group_name, i),
                ..Default::default()
            },
        }).await.unwrap();
        agents.push(agent);
    }

    agents
}

async fn start_inter_partition_communication(
    client: &CaxtonClient,
    partition_a: &[DeployAgentResponse],
    partition_b: &[DeployAgentResponse],
) -> tokio::task::JoinHandle<()> {
    let client = client.clone();
    let a_agents = partition_a.to_vec();
    let b_agents = partition_b.to_vec();

    tokio::spawn(async move {
        let mut message_id = 0;

        loop {
            // Send message from A to B
            if !a_agents.is_empty() && !b_agents.is_empty() {
                let sender = &a_agents[message_id % a_agents.len()];
                let receiver = &b_agents[message_id % b_agents.len()];

                let _ = client.send_message(FipaMessage {
                    performative: "inform".to_string(),
                    sender: sender.agent_id.clone(),
                    receiver: receiver.agent_id.clone(),
                    content: json!({
                        "partition_message": message_id,
                        "from_partition": "A"
                    }),
                    ..Default::default()
                }).await;

                message_id += 1;
            }

            sleep(Duration::from_millis(100)).await;
        }
    })
}

async fn cleanup_agents(client: &CaxtonClient, agents: &[DeployAgentResponse]) {
    for agent in agents {
        let _ = client.remove_agent(&agent.agent_id).await;
    }
}
```

## Test Automation and CI/CD

### GitHub Actions Workflow

```yaml
# .github/workflows/test.yml
name: Comprehensive Testing

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]

env:
  CARGO_TERM_COLOR: always
  RUST_BACKTRACE: 1

jobs:
  unit-tests:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3

    - name: Install Rust
      uses: actions-rs/toolchain@v1
      with:
        toolchain: stable
        target: wasm32-wasi
        components: rustfmt, clippy
        override: true

    - name: Cache cargo registry
      uses: actions/cache@v3
      with:
        path: ~/.cargo/registry
        key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}

    - name: Install WASM tools
      run: |
        curl -L https://github.com/WebAssembly/binaryen/releases/download/version_116/binaryen-version_116-x86_64-linux.tar.gz | tar xz
        echo "$PWD/binaryen-version_116/bin" >> $GITHUB_PATH

    - name: Build WASM test agents
      run: |
        cd tests/test_agents
        cargo build --target wasm32-wasi --release
        wasm-opt -Os target/wasm32-wasi/release/*.wasm -o optimized/

    - name: Run unit tests
      run: cargo test --lib --bins --tests unit_tests

    - name: Run property-based tests
      run: cargo test property_tests
      env:
        PROPTEST_CASES: 1000

  integration-tests:
    runs-on: ubuntu-latest
    needs: unit-tests
    services:
      caxton:
        image: caxton:test
        ports:
          - 8080:8080
          - 50051:50051
        options: >-
          --health-cmd "curl -f http://localhost:8080/health"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    steps:
    - uses: actions/checkout@v3

    - name: Wait for Caxton to be ready
      run: |
        timeout 60 bash -c 'until curl -f http://localhost:8080/health; do sleep 2; done'

    - name: Run integration tests
      run: cargo test integration_tests
      env:
        CAXTON_ENDPOINT: http://localhost:8080
        RUST_LOG: info

  load-tests:
    runs-on: ubuntu-latest
    needs: integration-tests
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'

    steps:
    - uses: actions/checkout@v3

    - name: Set up load test environment
      run: |
        docker-compose -f docker-compose.loadtest.yml up -d
        sleep 30  # Wait for services to be ready

    - name: Run load tests
      run: |
        cargo test load_tests --release
      env:
        CAXTON_ENDPOINT: http://localhost:8080
        LOAD_TEST_DURATION: 300  # 5 minutes
        MAX_CONCURRENT_CLIENTS: 100

    - name: Collect performance metrics
      run: |
        docker-compose -f docker-compose.loadtest.yml exec caxton curl -s http://localhost:8080/api/v1/metrics/system > metrics.json

    - name: Upload performance results
      uses: actions/upload-artifact@v3
      with:
        name: load-test-results
        path: |
          metrics.json
          load_test_*.log

  chaos-tests:
    runs-on: ubuntu-latest
    needs: integration-tests
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'

    steps:
    - uses: actions/checkout@v3

    - name: Set up chaos test environment
      run: |
        # Install chaos engineering tools
        kubectl apply -f k8s/chaos-test-environment.yml
        sleep 60

    - name: Run chaos tests
      run: |
        cargo test chaos_tests --release -- --test-threads=1
      env:
        CAXTON_ENDPOINT: http://localhost:8080
        CHAOS_DURATION: 600  # 10 minutes

    - name: Generate test report
      if: always()
      run: |
        cargo test --no-run --message-format=json | jq -r 'select(.reason == "test") | .name' > test_results.txt

    - name: Upload chaos test results
      uses: actions/upload-artifact@v3
      if: always()
      with:
        name: chaos-test-results
        path: |
          test_results.txt
          chaos_test_*.log
```

### Test Configuration

```toml
# tests/Cargo.toml
[package]
name = "caxton-tests"
version = "0.1.0"
edition = "2021"

[[bin]]
name = "test-runner"
path = "src/test_runner.rs"

[dependencies]
caxton-client = { path = "../client" }
caxton-sdk = { path = "../sdk" }
tokio = { version = "1.0", features = ["full"] }
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
reqwest = { version = "0.11", features = ["json"] }
futures = "0.3"
proptest = "1.0"
criterion = { version = "0.5", features = ["html_reports"] }
base64 = "0.21"
uuid = { version = "1.0", features = ["v4"] }
rand = "0.8"

[dev-dependencies]
tokio-test = "0.4"
tempfile = "3.0"
```

This comprehensive testing guide provides strategies for validating all aspects of Caxton's multi-agent system, from individual agent behavior to system-wide performance and resilience. The layered approach ensures thorough coverage while maintaining test efficiency and reliability.