selfware 0.2.2

Your personal AI workshop — software you own, software that lasts
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
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
//! Security Sandbox
//!
//! Defense in depth:
//! - Filesystem sandboxing
//! - Network firewall rules
//! - Resource limits
//! - Audit logging
//! - Autonomy levels

use anyhow::{anyhow, Result};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::time::Duration;

/// Autonomy level for agent operations
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default,
)]
pub enum AutonomyLevel {
    /// Agent can only suggest, human must approve and execute
    SuggestOnly,
    /// Agent can execute safe operations, must confirm destructive ones
    #[default]
    ConfirmDestructive,
    /// Agent can execute all operations except explicitly forbidden ones
    SemiAutonomous,
    /// Agent has full control (use with caution)
    FullAutonomous,
}

impl AutonomyLevel {
    /// Icon for display
    pub fn icon(&self) -> &'static str {
        match self {
            AutonomyLevel::SuggestOnly => "🔒",
            AutonomyLevel::ConfirmDestructive => "⚠️",
            AutonomyLevel::SemiAutonomous => "🔓",
            AutonomyLevel::FullAutonomous => "🔥",
        }
    }

    /// Description
    pub fn description(&self) -> &'static str {
        match self {
            AutonomyLevel::SuggestOnly => "Agent can only suggest actions, human executes",
            AutonomyLevel::ConfirmDestructive => {
                "Agent executes safe ops, confirms destructive ones"
            }
            AutonomyLevel::SemiAutonomous => "Agent executes most ops, respects explicit denials",
            AutonomyLevel::FullAutonomous => "Agent has full control (dangerous)",
        }
    }

    /// Is this a restricted level?
    pub fn is_restricted(&self) -> bool {
        matches!(
            self,
            AutonomyLevel::SuggestOnly | AutonomyLevel::ConfirmDestructive
        )
    }

    /// Can auto-execute safe operations?
    pub fn can_auto_execute_safe(&self) -> bool {
        !matches!(self, AutonomyLevel::SuggestOnly)
    }

    /// Can auto-execute destructive operations?
    pub fn can_auto_execute_destructive(&self) -> bool {
        matches!(
            self,
            AutonomyLevel::SemiAutonomous | AutonomyLevel::FullAutonomous
        )
    }

    /// Parse from string
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "suggest" | "suggest_only" | "suggestonly" => Some(AutonomyLevel::SuggestOnly),
            "confirm" | "confirm_destructive" | "confirmdestructive" => {
                Some(AutonomyLevel::ConfirmDestructive)
            }
            "semi" | "semi_autonomous" | "semiautonomous" => Some(AutonomyLevel::SemiAutonomous),
            "full" | "full_autonomous" | "fullautonomous" => Some(AutonomyLevel::FullAutonomous),
            _ => None,
        }
    }
}

impl std::fmt::Display for AutonomyLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            AutonomyLevel::SuggestOnly => "SuggestOnly",
            AutonomyLevel::ConfirmDestructive => "ConfirmDestructive",
            AutonomyLevel::SemiAutonomous => "SemiAutonomous",
            AutonomyLevel::FullAutonomous => "FullAutonomous",
        };
        write!(f, "{}", name)
    }
}

/// Operation risk level
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
)]
pub enum RiskLevel {
    /// Safe operation (read, list)
    #[default]
    Safe,
    /// Low risk (write to allowed paths)
    Low,
    /// Medium risk (modify existing files)
    Medium,
    /// High risk (delete files, system changes)
    High,
    /// Critical risk (system destruction potential)
    Critical,
}

impl RiskLevel {
    /// Icon
    pub fn icon(&self) -> &'static str {
        match self {
            RiskLevel::Safe => "",
            RiskLevel::Low => "",
            RiskLevel::Medium => "⚠️",
            RiskLevel::High => "🔥",
            RiskLevel::Critical => "💀",
        }
    }

    /// Is destructive?
    pub fn is_destructive(&self) -> bool {
        matches!(self, RiskLevel::High | RiskLevel::Critical)
    }

    /// Color code
    pub fn color(&self) -> &'static str {
        match self {
            RiskLevel::Safe => "\x1b[32m",
            RiskLevel::Low => "\x1b[33m",
            RiskLevel::Medium => "\x1b[33m",
            RiskLevel::High => "\x1b[31m",
            RiskLevel::Critical => "\x1b[91m",
        }
    }
}

impl std::fmt::Display for RiskLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            RiskLevel::Safe => "Safe",
            RiskLevel::Low => "Low",
            RiskLevel::Medium => "Medium",
            RiskLevel::High => "High",
            RiskLevel::Critical => "Critical",
        };
        write!(f, "{}", name)
    }
}

/// File access type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum FileAccess {
    Read,
    Write,
    Create,
    Delete,
    Execute,
    List,
}

impl FileAccess {
    /// Risk level for this access type
    pub fn risk_level(&self) -> RiskLevel {
        match self {
            FileAccess::Read | FileAccess::List => RiskLevel::Safe,
            FileAccess::Create => RiskLevel::Low,
            FileAccess::Write => RiskLevel::Medium,
            FileAccess::Delete => RiskLevel::High,
            FileAccess::Execute => RiskLevel::High,
        }
    }
}

impl std::fmt::Display for FileAccess {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            FileAccess::Read => "read",
            FileAccess::Write => "write",
            FileAccess::Create => "create",
            FileAccess::Delete => "delete",
            FileAccess::Execute => "execute",
            FileAccess::List => "list",
        };
        write!(f, "{}", name)
    }
}

/// Filesystem sandbox policy
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct FilesystemPolicy {
    /// Allowed paths (whitelist)
    pub allowed_paths: Vec<PathBuf>,
    /// Denied paths (blacklist, takes precedence)
    pub denied_paths: Vec<PathBuf>,
    /// Allowed extensions
    pub allowed_extensions: Option<HashSet<String>>,
    /// Denied extensions
    pub denied_extensions: HashSet<String>,
    /// Max file size for write (bytes)
    pub max_write_size: Option<u64>,
    /// Allow symlinks
    pub allow_symlinks: bool,
    /// Allow hidden files (starting with .)
    pub allow_hidden: bool,
}

impl FilesystemPolicy {
    /// Create new policy
    pub fn new() -> Self {
        Self {
            allow_symlinks: false,
            allow_hidden: true,
            ..Default::default()
        }
    }

    /// Allow a path
    pub fn allow_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.allowed_paths.push(path.into());
        self
    }

    /// Deny a path
    pub fn deny_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.denied_paths.push(path.into());
        self
    }

    /// Deny an extension
    pub fn deny_extension(mut self, ext: &str) -> Self {
        self.denied_extensions.insert(ext.to_string());
        self
    }

    /// Set max write size
    pub fn max_size(mut self, size: u64) -> Self {
        self.max_write_size = Some(size);
        self
    }

    /// Check if path is allowed
    pub fn is_allowed(&self, path: &Path, access: FileAccess) -> Result<()> {
        let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());

        // Check denied paths first (blacklist takes precedence)
        for denied in &self.denied_paths {
            let denied_canonical = denied.canonicalize().unwrap_or_else(|_| denied.clone());
            if path.starts_with(&denied_canonical) {
                return Err(anyhow!("Path is in denied list: {}", path.display()));
            }
        }

        // Check extension
        if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
            if self.denied_extensions.contains(ext) {
                return Err(anyhow!("Extension .{} is denied", ext));
            }
            if let Some(allowed) = &self.allowed_extensions {
                if !allowed.contains(ext) {
                    return Err(anyhow!("Extension .{} is not in allowed list", ext));
                }
            }
        }

        // Check hidden files
        if !self.allow_hidden {
            if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                if name.starts_with('.') {
                    return Err(anyhow!("Hidden files are not allowed"));
                }
            }
        }

        // Check allowed paths (whitelist)
        if !self.allowed_paths.is_empty() {
            let in_allowed = self
                .allowed_paths
                .iter()
                .any(|allowed| path.starts_with(allowed));
            if !in_allowed {
                return Err(anyhow!("Path is not in allowed list: {}", path.display()));
            }
        }

        // For write/create, check if safe based on access type
        if matches!(
            access,
            FileAccess::Write | FileAccess::Create | FileAccess::Delete
        ) {
            // Additional checks could go here
        }

        Ok(())
    }

    /// Check if symlinks are allowed
    pub fn check_symlink(&self, path: &Path) -> Result<()> {
        if !self.allow_symlinks && path.is_symlink() {
            return Err(anyhow!("Symlinks are not allowed"));
        }
        Ok(())
    }

    /// Check write size
    pub fn check_size(&self, size: u64) -> Result<()> {
        if let Some(max) = self.max_write_size {
            if size > max {
                return Err(anyhow!("Write size {} exceeds limit {}", size, max));
            }
        }
        Ok(())
    }
}

/// Network access type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum NetworkAccess {
    Connect,
    Listen,
    Dns,
}

impl std::fmt::Display for NetworkAccess {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            NetworkAccess::Connect => "connect",
            NetworkAccess::Listen => "listen",
            NetworkAccess::Dns => "dns",
        };
        write!(f, "{}", name)
    }
}

/// Network rule action
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum RuleAction {
    Allow,
    #[default]
    Deny,
    Log,
}

/// Network firewall rule
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkRule {
    /// Rule name
    pub name: String,
    /// Action
    pub action: RuleAction,
    /// Target (host pattern)
    pub host: Option<String>,
    /// Port or port range
    pub port: Option<PortSpec>,
    /// Protocol
    pub protocol: Option<String>,
    /// Access type
    pub access: Option<NetworkAccess>,
}

/// Port specification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PortSpec {
    Single(u16),
    Range(u16, u16),
    List(Vec<u16>),
}

impl PortSpec {
    /// Check if port matches
    pub fn matches(&self, port: u16) -> bool {
        match self {
            PortSpec::Single(p) => *p == port,
            PortSpec::Range(start, end) => port >= *start && port <= *end,
            PortSpec::List(ports) => ports.contains(&port),
        }
    }
}

impl NetworkRule {
    /// Create new rule
    pub fn new(name: &str, action: RuleAction) -> Self {
        Self {
            name: name.to_string(),
            action,
            host: None,
            port: None,
            protocol: None,
            access: None,
        }
    }

    /// Set host pattern
    pub fn host(mut self, host: &str) -> Self {
        self.host = Some(host.to_string());
        self
    }

    /// Set port
    pub fn port(mut self, port: u16) -> Self {
        self.port = Some(PortSpec::Single(port));
        self
    }

    /// Set port range
    pub fn port_range(mut self, start: u16, end: u16) -> Self {
        self.port = Some(PortSpec::Range(start, end));
        self
    }

    /// Set access type
    pub fn access(mut self, access: NetworkAccess) -> Self {
        self.access = Some(access);
        self
    }

    /// Check if rule matches
    pub fn matches(&self, host: &str, port: u16, access: NetworkAccess) -> bool {
        // Check host pattern
        if let Some(pattern) = &self.host {
            if !Self::host_matches(pattern, host) {
                return false;
            }
        }

        // Check port
        if let Some(port_spec) = &self.port {
            if !port_spec.matches(port) {
                return false;
            }
        }

        // Check access type
        if let Some(acc) = &self.access {
            if *acc != access {
                return false;
            }
        }

        true
    }

    /// Check if host matches pattern
    fn host_matches(pattern: &str, host: &str) -> bool {
        if pattern == "*" {
            return true;
        }
        if pattern.starts_with("*.") {
            // Wildcard subdomain
            let suffix = &pattern[1..];
            return host.ends_with(suffix);
        }
        pattern == host
    }
}

/// Network policy
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NetworkPolicy {
    /// Rules (evaluated in order)
    pub rules: Vec<NetworkRule>,
    /// Default action
    pub default_action: RuleAction,
    /// Allow localhost
    pub allow_localhost: bool,
}

impl NetworkPolicy {
    /// Create new policy
    pub fn new() -> Self {
        Self {
            default_action: RuleAction::Deny,
            allow_localhost: true,
            ..Default::default()
        }
    }

    /// Add rule
    pub fn add_rule(mut self, rule: NetworkRule) -> Self {
        self.rules.push(rule);
        self
    }

    /// Check access
    pub fn check(&self, host: &str, port: u16, access: NetworkAccess) -> RuleAction {
        // Localhost exception
        if self.allow_localhost && (host == "localhost" || host == "127.0.0.1" || host == "::1") {
            return RuleAction::Allow;
        }

        // Check rules in order
        for rule in &self.rules {
            if rule.matches(host, port, access) {
                return rule.action;
            }
        }

        self.default_action
    }

    /// Is allowed
    pub fn is_allowed(&self, host: &str, port: u16, access: NetworkAccess) -> bool {
        matches!(self.check(host, port, access), RuleAction::Allow)
    }
}

/// Resource limits
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ResourceLimits {
    /// Max CPU time (seconds)
    pub max_cpu_time: Option<u64>,
    /// Max memory (bytes)
    pub max_memory: Option<u64>,
    /// Max file descriptors
    pub max_fds: Option<u32>,
    /// Max processes
    pub max_processes: Option<u32>,
    /// Max output size (bytes)
    pub max_output_size: Option<u64>,
    /// Execution timeout
    pub timeout: Option<Duration>,
}

impl ResourceLimits {
    /// Create new limits
    pub fn new() -> Self {
        Self::default()
    }

    /// Set CPU time limit
    pub fn cpu_time(mut self, seconds: u64) -> Self {
        self.max_cpu_time = Some(seconds);
        self
    }

    /// Set memory limit
    pub fn memory(mut self, bytes: u64) -> Self {
        self.max_memory = Some(bytes);
        self
    }

    /// Set memory limit in MB
    pub fn memory_mb(self, mb: u64) -> Self {
        self.memory(mb * 1024 * 1024)
    }

    /// Set timeout
    pub fn timeout(mut self, duration: Duration) -> Self {
        self.timeout = Some(duration);
        self
    }

    /// Set timeout in seconds
    pub fn timeout_secs(self, seconds: u64) -> Self {
        self.timeout(Duration::from_secs(seconds))
    }

    /// Set max processes
    pub fn max_procs(mut self, count: u32) -> Self {
        self.max_processes = Some(count);
        self
    }

    /// Check if memory is within limits
    pub fn check_memory(&self, bytes: u64) -> Result<()> {
        if let Some(max) = self.max_memory {
            if bytes > max {
                return Err(anyhow!("Memory usage {} exceeds limit {}", bytes, max));
            }
        }
        Ok(())
    }

    /// Check if output size is within limits
    pub fn check_output(&self, bytes: u64) -> Result<()> {
        if let Some(max) = self.max_output_size {
            if bytes > max {
                return Err(anyhow!("Output size {} exceeds limit {}", bytes, max));
            }
        }
        Ok(())
    }
}

/// Audit log entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditEntry {
    /// Timestamp
    pub timestamp: DateTime<Utc>,
    /// Action type
    pub action: String,
    /// Subject (who)
    pub subject: String,
    /// Object (what)
    pub object: String,
    /// Result
    pub result: AuditResult,
    /// Details
    pub details: Option<String>,
    /// Risk level
    pub risk: RiskLevel,
}

/// Audit result
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AuditResult {
    Allowed,
    Denied,
    Prompted,
    Failed,
}

impl AuditResult {
    /// Icon
    pub fn icon(&self) -> &'static str {
        match self {
            AuditResult::Allowed => "",
            AuditResult::Denied => "",
            AuditResult::Prompted => "?",
            AuditResult::Failed => "!",
        }
    }
}

impl std::fmt::Display for AuditResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            AuditResult::Allowed => "Allowed",
            AuditResult::Denied => "Denied",
            AuditResult::Prompted => "Prompted",
            AuditResult::Failed => "Failed",
        };
        write!(f, "{}", name)
    }
}

impl AuditEntry {
    /// Create new entry
    pub fn new(action: &str, subject: &str, object: &str, result: AuditResult) -> Self {
        Self {
            timestamp: Utc::now(),
            action: action.to_string(),
            subject: subject.to_string(),
            object: object.to_string(),
            result,
            details: None,
            risk: RiskLevel::Safe,
        }
    }

    /// With details
    pub fn with_details(mut self, details: &str) -> Self {
        self.details = Some(details.to_string());
        self
    }

    /// With risk level
    pub fn with_risk(mut self, risk: RiskLevel) -> Self {
        self.risk = risk;
        self
    }

    /// Format for display
    pub fn display(&self) -> String {
        format!(
            "[{}] {} {} {} on {} - {}",
            self.timestamp.format("%Y-%m-%d %H:%M:%S"),
            self.risk.icon(),
            self.subject,
            self.action,
            self.object,
            self.result
        )
    }
}

/// Audit logger
#[derive(Debug, Default)]
pub struct AuditLogger {
    /// Log entries
    entries: Vec<AuditEntry>,
    /// Max entries to keep
    max_entries: usize,
    /// Log to file
    log_file: Option<PathBuf>,
    /// Log level (minimum risk to log)
    min_risk: RiskLevel,
}

impl AuditLogger {
    /// Create new logger
    pub fn new() -> Self {
        Self {
            max_entries: 10000,
            min_risk: RiskLevel::Safe,
            ..Default::default()
        }
    }

    /// Set log file
    pub fn with_file(mut self, path: PathBuf) -> Self {
        self.log_file = Some(path);
        self
    }

    /// Set minimum risk level to log
    pub fn with_min_risk(mut self, risk: RiskLevel) -> Self {
        self.min_risk = risk;
        self
    }

    /// Log an entry
    pub fn log(&mut self, entry: AuditEntry) {
        if entry.risk >= self.min_risk {
            self.entries.push(entry);

            // Limit size
            if self.entries.len() > self.max_entries {
                self.entries.remove(0);
            }
        }
    }

    /// Log a simple action
    pub fn log_action(
        &mut self,
        action: &str,
        subject: &str,
        object: &str,
        result: AuditResult,
        risk: RiskLevel,
    ) {
        self.log(AuditEntry::new(action, subject, object, result).with_risk(risk));
    }

    /// Get recent entries
    pub fn recent(&self, limit: usize) -> Vec<&AuditEntry> {
        self.entries.iter().rev().take(limit).collect()
    }

    /// Get entries by result
    pub fn by_result(&self, result: AuditResult) -> Vec<&AuditEntry> {
        self.entries.iter().filter(|e| e.result == result).collect()
    }

    /// Get denied entries
    pub fn denied(&self) -> Vec<&AuditEntry> {
        self.by_result(AuditResult::Denied)
    }

    /// Get entries by risk level
    pub fn by_risk(&self, risk: RiskLevel) -> Vec<&AuditEntry> {
        self.entries.iter().filter(|e| e.risk == risk).collect()
    }

    /// Count entries
    pub fn count(&self) -> usize {
        self.entries.len()
    }

    /// Clear entries
    pub fn clear(&mut self) {
        self.entries.clear();
    }

    /// Get summary
    pub fn summary(&self) -> AuditSummary {
        AuditSummary {
            total: self.entries.len(),
            allowed: self.by_result(AuditResult::Allowed).len(),
            denied: self.by_result(AuditResult::Denied).len(),
            prompted: self.by_result(AuditResult::Prompted).len(),
            high_risk: self
                .entries
                .iter()
                .filter(|e| e.risk >= RiskLevel::High)
                .count(),
        }
    }
}

/// Audit summary
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditSummary {
    pub total: usize,
    pub allowed: usize,
    pub denied: usize,
    pub prompted: usize,
    pub high_risk: usize,
}

impl AuditSummary {
    /// Display
    pub fn display(&self) -> String {
        format!(
            "{} actions: {} allowed, {} denied, {} prompted ({} high-risk)",
            self.total, self.allowed, self.denied, self.prompted, self.high_risk
        )
    }
}

/// Confirmation token required when disabling the sandbox via `set_enabled`.
pub const SANDBOX_DISABLE_TOKEN: &str = "CONFIRM_SANDBOX_DISABLE";

/// Security sandbox combining all policies
#[derive(Debug)]
pub struct SecuritySandbox {
    /// Autonomy level
    pub autonomy: AutonomyLevel,
    /// Filesystem policy
    pub filesystem: FilesystemPolicy,
    /// Network policy
    pub network: NetworkPolicy,
    /// Resource limits
    pub resources: ResourceLimits,
    /// Audit logger
    pub audit: AuditLogger,
    /// Enabled
    pub enabled: bool,
}

impl Default for SecuritySandbox {
    fn default() -> Self {
        Self::new()
    }
}

impl SecuritySandbox {
    /// Create new sandbox with default policies
    pub fn new() -> Self {
        Self {
            autonomy: AutonomyLevel::ConfirmDestructive,
            filesystem: FilesystemPolicy::new(),
            network: NetworkPolicy::new(),
            resources: ResourceLimits::new(),
            audit: AuditLogger::new(),
            enabled: true,
        }
    }

    /// Create a strict sandbox
    pub fn strict() -> Self {
        Self {
            autonomy: AutonomyLevel::SuggestOnly,
            filesystem: FilesystemPolicy::new()
                .deny_path("/etc")
                .deny_path("/usr")
                .deny_path("/bin")
                .deny_path("/sbin")
                .deny_extension("exe")
                .deny_extension("sh"),
            network: NetworkPolicy {
                default_action: RuleAction::Deny,
                allow_localhost: true,
                rules: vec![],
            },
            resources: ResourceLimits::new()
                .memory_mb(512)
                .timeout_secs(300)
                .max_procs(10),
            audit: AuditLogger::new().with_min_risk(RiskLevel::Low),
            enabled: true,
        }
    }

    /// Create a permissive sandbox
    pub fn permissive() -> Self {
        Self {
            autonomy: AutonomyLevel::SemiAutonomous,
            filesystem: FilesystemPolicy::new()
                .deny_path("/etc/shadow")
                .deny_path("/etc/passwd"),
            network: NetworkPolicy {
                default_action: RuleAction::Allow,
                allow_localhost: true,
                rules: vec![],
            },
            resources: ResourceLimits::new(),
            audit: AuditLogger::new().with_min_risk(RiskLevel::High),
            enabled: true,
        }
    }

    /// Set autonomy level
    pub fn with_autonomy(mut self, level: AutonomyLevel) -> Self {
        self.autonomy = level;
        self
    }

    /// Enable/disable the sandbox.
    ///
    /// WARNING: Disabling the sandbox bypasses all safety checks.
    ///
    /// Callers must supply `confirmation: Some(SANDBOX_DISABLE_TOKEN)` when
    /// disabling. Re-enabling does not require a token.
    pub fn set_enabled(&mut self, enabled: bool, confirmation: Option<&str>) -> Result<()> {
        if self.enabled && !enabled {
            match confirmation {
                Some(token) if token == SANDBOX_DISABLE_TOKEN => {}
                Some(_) => {
                    self.audit.log_action(
                        "sandbox_disable_rejected",
                        "system",
                        "invalid confirmation token",
                        AuditResult::Denied,
                        RiskLevel::Critical,
                    );
                    return Err(anyhow!(
                        "Sandbox disable rejected: invalid confirmation token"
                    ));
                }
                None => {
                    self.audit.log_action(
                        "sandbox_disable_rejected",
                        "system",
                        "no confirmation token provided",
                        AuditResult::Denied,
                        RiskLevel::Critical,
                    );
                    return Err(anyhow!(
                        "Sandbox disable rejected: confirmation token required. \
                         Pass confirmation: Some(SANDBOX_DISABLE_TOKEN) to confirm."
                    ));
                }
            }
            tracing::warn!("Sandbox DISABLED — all safety checks will be bypassed");
            self.audit.log_action(
                "sandbox_disable",
                "system",
                "sandbox disabled by caller (confirmed)",
                AuditResult::Allowed,
                RiskLevel::Critical,
            );
        } else if !self.enabled && enabled {
            tracing::info!("Sandbox re-enabled");
            self.audit.log_action(
                "sandbox_enable",
                "system",
                "sandbox re-enabled by caller",
                AuditResult::Allowed,
                RiskLevel::Low,
            );
        }
        self.enabled = enabled;
        Ok(())
    }

    /// Check file access
    pub fn check_file_access(&mut self, path: &Path, access: FileAccess) -> Result<bool> {
        if !self.enabled {
            self.audit.log_action(
                &format!("file_{}", access),
                "agent",
                &path.display().to_string(),
                AuditResult::Allowed,
                RiskLevel::Medium,
            );
            return Ok(true);
        }

        let risk = access.risk_level();
        let result = self.filesystem.is_allowed(path, access);

        let audit_result = match &result {
            Ok(()) => {
                if risk.is_destructive() && !self.autonomy.can_auto_execute_destructive() {
                    AuditResult::Prompted
                } else {
                    AuditResult::Allowed
                }
            }
            Err(_) => AuditResult::Denied,
        };

        self.audit.log_action(
            &format!("file_{}", access),
            "agent",
            &path.display().to_string(),
            audit_result,
            risk,
        );

        match result {
            Ok(()) => {
                if risk.is_destructive() && !self.autonomy.can_auto_execute_destructive() {
                    Ok(false) // Needs confirmation
                } else {
                    Ok(true)
                }
            }
            Err(e) => Err(e),
        }
    }

    /// Check network access
    pub fn check_network_access(
        &mut self,
        host: &str,
        port: u16,
        access: NetworkAccess,
    ) -> Result<bool> {
        if !self.enabled {
            self.audit.log_action(
                &format!("net_{}", access),
                "agent",
                &format!("{}:{}", host, port),
                AuditResult::Allowed,
                RiskLevel::Medium,
            );
            return Ok(true);
        }

        let action = self.network.check(host, port, access);
        let result = match action {
            RuleAction::Allow => AuditResult::Allowed,
            RuleAction::Deny => AuditResult::Denied,
            RuleAction::Log => AuditResult::Allowed,
        };

        self.audit.log_action(
            &format!("net_{}", access),
            "agent",
            &format!("{}:{}", host, port),
            result,
            if matches!(access, NetworkAccess::Listen) {
                RiskLevel::Medium
            } else {
                RiskLevel::Low
            },
        );

        match action {
            RuleAction::Allow | RuleAction::Log => Ok(true),
            RuleAction::Deny => Err(anyhow!("Network access denied: {}:{}", host, port)),
        }
    }

    /// Check if operation needs confirmation
    pub fn needs_confirmation(&self, risk: RiskLevel) -> bool {
        if !self.enabled {
            tracing::debug!(
                "Sandbox disabled — skipping confirmation for {:?} risk operation",
                risk
            );
            return false;
        }

        match self.autonomy {
            AutonomyLevel::SuggestOnly => true,
            AutonomyLevel::ConfirmDestructive => risk.is_destructive(),
            AutonomyLevel::SemiAutonomous => risk == RiskLevel::Critical,
            AutonomyLevel::FullAutonomous => false,
        }
    }

    /// Get security status
    pub fn status(&self) -> SandboxStatus {
        SandboxStatus {
            enabled: self.enabled,
            autonomy: self.autonomy,
            audit_count: self.audit.count(),
            denied_count: self.audit.denied().len(),
        }
    }
}

/// Sandbox status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SandboxStatus {
    pub enabled: bool,
    pub autonomy: AutonomyLevel,
    pub audit_count: usize,
    pub denied_count: usize,
}

impl SandboxStatus {
    /// Display
    pub fn display(&self) -> String {
        format!(
            "Sandbox: {} | Autonomy: {} | Actions: {} ({} denied)",
            if self.enabled { "ON" } else { "OFF" },
            self.autonomy,
            self.audit_count,
            self.denied_count
        )
    }
}

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

    #[test]
    fn test_autonomy_level_default() {
        assert_eq!(AutonomyLevel::default(), AutonomyLevel::ConfirmDestructive);
    }

    #[test]
    fn test_autonomy_level_parse() {
        assert_eq!(
            AutonomyLevel::parse("suggest"),
            Some(AutonomyLevel::SuggestOnly)
        );
        assert_eq!(
            AutonomyLevel::parse("confirm"),
            Some(AutonomyLevel::ConfirmDestructive)
        );
        assert_eq!(
            AutonomyLevel::parse("semi"),
            Some(AutonomyLevel::SemiAutonomous)
        );
        assert_eq!(
            AutonomyLevel::parse("full"),
            Some(AutonomyLevel::FullAutonomous)
        );
        assert_eq!(AutonomyLevel::parse("invalid"), None);
    }

    #[test]
    fn test_autonomy_level_icon() {
        assert_eq!(AutonomyLevel::SuggestOnly.icon(), "🔒");
        assert_eq!(AutonomyLevel::FullAutonomous.icon(), "🔥");
    }

    #[test]
    fn test_autonomy_level_permissions() {
        assert!(!AutonomyLevel::SuggestOnly.can_auto_execute_safe());
        assert!(AutonomyLevel::ConfirmDestructive.can_auto_execute_safe());
        assert!(!AutonomyLevel::ConfirmDestructive.can_auto_execute_destructive());
        assert!(AutonomyLevel::FullAutonomous.can_auto_execute_destructive());
    }

    #[test]
    fn test_autonomy_level_display() {
        assert_eq!(format!("{}", AutonomyLevel::SuggestOnly), "SuggestOnly");
    }

    #[test]
    fn test_risk_level_is_destructive() {
        assert!(!RiskLevel::Safe.is_destructive());
        assert!(!RiskLevel::Low.is_destructive());
        assert!(!RiskLevel::Medium.is_destructive());
        assert!(RiskLevel::High.is_destructive());
        assert!(RiskLevel::Critical.is_destructive());
    }

    #[test]
    fn test_risk_level_icon() {
        assert_eq!(RiskLevel::Safe.icon(), "");
        assert_eq!(RiskLevel::Critical.icon(), "💀");
    }

    #[test]
    fn test_file_access_risk() {
        assert_eq!(FileAccess::Read.risk_level(), RiskLevel::Safe);
        assert_eq!(FileAccess::Create.risk_level(), RiskLevel::Low);
        assert_eq!(FileAccess::Write.risk_level(), RiskLevel::Medium);
        assert_eq!(FileAccess::Delete.risk_level(), RiskLevel::High);
    }

    #[test]
    fn test_filesystem_policy_new() {
        let policy = FilesystemPolicy::new();
        assert!(!policy.allow_symlinks);
        assert!(policy.allow_hidden);
    }

    #[test]
    fn test_filesystem_policy_builder() {
        let policy = FilesystemPolicy::new()
            .allow_path("/home/user")
            .deny_path("/etc")
            .deny_extension("exe")
            .max_size(1024);

        assert_eq!(policy.allowed_paths.len(), 1);
        assert_eq!(policy.denied_paths.len(), 1);
        assert!(policy.denied_extensions.contains("exe"));
        assert_eq!(policy.max_write_size, Some(1024));
    }

    #[test]
    fn test_filesystem_policy_denied() {
        let policy = FilesystemPolicy::new().deny_path("/etc");

        let result = policy.is_allowed(Path::new("/etc/passwd"), FileAccess::Read);
        assert!(result.is_err());
    }

    #[test]
    fn test_filesystem_policy_extension_denied() {
        let policy = FilesystemPolicy::new().deny_extension("exe");

        let result = policy.is_allowed(Path::new("/tmp/virus.exe"), FileAccess::Read);
        assert!(result.is_err());
    }

    #[test]
    fn test_filesystem_policy_check_size() {
        let policy = FilesystemPolicy::new().max_size(100);
        assert!(policy.check_size(50).is_ok());
        assert!(policy.check_size(150).is_err());
    }

    #[test]
    fn test_port_spec_matches() {
        assert!(PortSpec::Single(80).matches(80));
        assert!(!PortSpec::Single(80).matches(443));

        assert!(PortSpec::Range(80, 90).matches(85));
        assert!(!PortSpec::Range(80, 90).matches(100));

        assert!(PortSpec::List(vec![80, 443]).matches(443));
        assert!(!PortSpec::List(vec![80, 443]).matches(8080));
    }

    #[test]
    fn test_network_rule_new() {
        let rule = NetworkRule::new("allow_http", RuleAction::Allow)
            .host("*.example.com")
            .port(80);

        assert_eq!(rule.name, "allow_http");
        assert!(rule.matches("api.example.com", 80, NetworkAccess::Connect));
        assert!(!rule.matches("api.example.com", 443, NetworkAccess::Connect));
    }

    #[test]
    fn test_network_rule_host_pattern() {
        let rule = NetworkRule::new("wildcard", RuleAction::Allow).host("*.google.com");

        assert!(rule.matches("www.google.com", 443, NetworkAccess::Connect));
        assert!(!rule.matches("google.com", 443, NetworkAccess::Connect));
    }

    #[test]
    fn test_network_policy_localhost() {
        let policy = NetworkPolicy::new();
        assert!(policy.is_allowed("localhost", 8080, NetworkAccess::Connect));
        assert!(policy.is_allowed("127.0.0.1", 8080, NetworkAccess::Connect));
    }

    #[test]
    fn test_network_policy_default_deny() {
        let policy = NetworkPolicy::new();
        assert!(!policy.is_allowed("example.com", 80, NetworkAccess::Connect));
    }

    #[test]
    fn test_network_policy_rules() {
        let policy = NetworkPolicy::new()
            .add_rule(NetworkRule::new("allow_http", RuleAction::Allow).port(80));

        assert!(policy.is_allowed("example.com", 80, NetworkAccess::Connect));
        assert!(!policy.is_allowed("example.com", 443, NetworkAccess::Connect));
    }

    #[test]
    fn test_resource_limits_new() {
        let limits = ResourceLimits::new();
        assert!(limits.max_memory.is_none());
        assert!(limits.timeout.is_none());
    }

    #[test]
    fn test_resource_limits_builder() {
        let limits = ResourceLimits::new()
            .memory_mb(512)
            .timeout_secs(60)
            .max_procs(10);

        assert_eq!(limits.max_memory, Some(512 * 1024 * 1024));
        assert_eq!(limits.timeout, Some(Duration::from_secs(60)));
        assert_eq!(limits.max_processes, Some(10));
    }

    #[test]
    fn test_resource_limits_check_memory() {
        let limits = ResourceLimits::new().memory_mb(1);
        assert!(limits.check_memory(500_000).is_ok());
        assert!(limits.check_memory(2_000_000).is_err());
    }

    #[test]
    fn test_audit_result_icon() {
        assert_eq!(AuditResult::Allowed.icon(), "");
        assert_eq!(AuditResult::Denied.icon(), "");
    }

    #[test]
    fn test_audit_entry_new() {
        let entry = AuditEntry::new("file_read", "agent", "/tmp/file", AuditResult::Allowed);
        assert_eq!(entry.action, "file_read");
        assert_eq!(entry.result, AuditResult::Allowed);
    }

    #[test]
    fn test_audit_entry_builder() {
        let entry = AuditEntry::new("delete", "agent", "/tmp/file", AuditResult::Denied)
            .with_details("Permission denied")
            .with_risk(RiskLevel::High);

        assert!(entry.details.is_some());
        assert_eq!(entry.risk, RiskLevel::High);
    }

    #[test]
    fn test_audit_logger_new() {
        let logger = AuditLogger::new();
        assert_eq!(logger.count(), 0);
    }

    #[test]
    fn test_audit_logger_log() {
        let mut logger = AuditLogger::new();
        logger.log(AuditEntry::new(
            "test",
            "agent",
            "object",
            AuditResult::Allowed,
        ));

        assert_eq!(logger.count(), 1);
    }

    #[test]
    fn test_audit_logger_log_action() {
        let mut logger = AuditLogger::new();
        logger.log_action(
            "file_read",
            "agent",
            "/tmp/file",
            AuditResult::Allowed,
            RiskLevel::Safe,
        );

        assert_eq!(logger.count(), 1);
    }

    #[test]
    fn test_audit_logger_denied() {
        let mut logger = AuditLogger::new();
        logger.log_action(
            "delete",
            "agent",
            "/etc/passwd",
            AuditResult::Denied,
            RiskLevel::High,
        );

        assert_eq!(logger.denied().len(), 1);
    }

    #[test]
    fn test_audit_logger_min_risk() {
        let mut logger = AuditLogger::new().with_min_risk(RiskLevel::High);
        logger.log_action(
            "read",
            "agent",
            "/tmp/file",
            AuditResult::Allowed,
            RiskLevel::Safe,
        );

        assert_eq!(logger.count(), 0); // Not logged because risk is below minimum
    }

    #[test]
    fn test_audit_logger_summary() {
        let mut logger = AuditLogger::new();
        logger.log_action("a", "agent", "x", AuditResult::Allowed, RiskLevel::Safe);
        logger.log_action("b", "agent", "y", AuditResult::Denied, RiskLevel::High);

        let summary = logger.summary();
        assert_eq!(summary.total, 2);
        assert_eq!(summary.allowed, 1);
        assert_eq!(summary.denied, 1);
    }

    #[test]
    fn test_security_sandbox_new() {
        let sandbox = SecuritySandbox::new();
        assert!(sandbox.enabled);
        assert_eq!(sandbox.autonomy, AutonomyLevel::ConfirmDestructive);
    }

    #[test]
    fn test_security_sandbox_strict() {
        let sandbox = SecuritySandbox::strict();
        assert_eq!(sandbox.autonomy, AutonomyLevel::SuggestOnly);
    }

    #[test]
    fn test_security_sandbox_permissive() {
        let sandbox = SecuritySandbox::permissive();
        assert_eq!(sandbox.autonomy, AutonomyLevel::SemiAutonomous);
    }

    #[test]
    fn test_security_sandbox_needs_confirmation() {
        let sandbox = SecuritySandbox::new();
        assert!(!sandbox.needs_confirmation(RiskLevel::Safe));
        assert!(sandbox.needs_confirmation(RiskLevel::High));
    }

    #[test]
    fn test_security_sandbox_disabled() {
        let mut sandbox = SecuritySandbox::new();
        sandbox
            .set_enabled(false, Some(SANDBOX_DISABLE_TOKEN))
            .expect("disabling with correct token should succeed");

        assert!(!sandbox.needs_confirmation(RiskLevel::Critical));
    }

    #[test]
    fn test_security_sandbox_disable_requires_token() {
        let mut sandbox = SecuritySandbox::new();
        assert!(sandbox.set_enabled(false, None).is_err());
        assert!(sandbox.enabled);
        assert!(sandbox.set_enabled(false, Some("wrong")).is_err());
        assert!(sandbox.enabled);
        assert!(sandbox
            .set_enabled(false, Some(SANDBOX_DISABLE_TOKEN))
            .is_ok());
        assert!(!sandbox.enabled);
        assert!(sandbox.set_enabled(true, None).is_ok());
        assert!(sandbox.enabled);
    }

    #[test]
    fn test_security_sandbox_status() {
        let sandbox = SecuritySandbox::new();
        let status = sandbox.status();

        assert!(status.enabled);
        assert_eq!(status.autonomy, AutonomyLevel::ConfirmDestructive);
    }

    #[test]
    fn test_sandbox_status_display() {
        let status = SandboxStatus {
            enabled: true,
            autonomy: AutonomyLevel::ConfirmDestructive,
            audit_count: 100,
            denied_count: 5,
        };

        let display = status.display();
        assert!(display.contains("ON"));
        assert!(display.contains("ConfirmDestructive"));
        assert!(display.contains("100"));
    }

    #[test]
    fn test_security_sandbox_check_network() {
        let mut sandbox = SecuritySandbox::new();

        // Localhost should be allowed
        let result = sandbox.check_network_access("localhost", 8080, NetworkAccess::Connect);
        assert!(result.is_ok());
        assert!(result.unwrap());

        // External should be denied by default
        let result = sandbox.check_network_access("example.com", 80, NetworkAccess::Connect);
        assert!(result.is_err());
    }

    // ================== Additional Coverage Tests ==================

    #[test]
    fn test_autonomy_level_description() {
        assert!(AutonomyLevel::SuggestOnly.description().contains("suggest"));
        assert!(AutonomyLevel::ConfirmDestructive
            .description()
            .contains("confirms"));
        assert!(AutonomyLevel::SemiAutonomous
            .description()
            .contains("executes"));
        assert!(AutonomyLevel::FullAutonomous.description().contains("full"));
    }

    #[test]
    fn test_autonomy_level_is_restricted() {
        assert!(AutonomyLevel::SuggestOnly.is_restricted());
        assert!(AutonomyLevel::ConfirmDestructive.is_restricted());
        assert!(!AutonomyLevel::SemiAutonomous.is_restricted());
        assert!(!AutonomyLevel::FullAutonomous.is_restricted());
    }

    #[test]
    fn test_autonomy_level_parse_all_variants() {
        // SuggestOnly variants
        assert_eq!(
            AutonomyLevel::parse("suggest_only"),
            Some(AutonomyLevel::SuggestOnly)
        );
        assert_eq!(
            AutonomyLevel::parse("SUGGESTONLY"),
            Some(AutonomyLevel::SuggestOnly)
        );

        // ConfirmDestructive variants
        assert_eq!(
            AutonomyLevel::parse("confirm_destructive"),
            Some(AutonomyLevel::ConfirmDestructive)
        );
        assert_eq!(
            AutonomyLevel::parse("confirmdestructive"),
            Some(AutonomyLevel::ConfirmDestructive)
        );

        // SemiAutonomous variants
        assert_eq!(
            AutonomyLevel::parse("semi_autonomous"),
            Some(AutonomyLevel::SemiAutonomous)
        );
        assert_eq!(
            AutonomyLevel::parse("semiautonomous"),
            Some(AutonomyLevel::SemiAutonomous)
        );

        // FullAutonomous variants
        assert_eq!(
            AutonomyLevel::parse("full_autonomous"),
            Some(AutonomyLevel::FullAutonomous)
        );
        assert_eq!(
            AutonomyLevel::parse("fullautonomous"),
            Some(AutonomyLevel::FullAutonomous)
        );
    }

    #[test]
    fn test_risk_level_color() {
        assert!(RiskLevel::Safe.color().contains("32")); // green
        assert!(RiskLevel::Low.color().contains("33")); // yellow
        assert!(RiskLevel::Medium.color().contains("33")); // yellow
        assert!(RiskLevel::High.color().contains("31")); // red
        assert!(RiskLevel::Critical.color().contains("91")); // bright red
    }

    #[test]
    fn test_risk_level_display() {
        assert_eq!(format!("{}", RiskLevel::Safe), "Safe");
        assert_eq!(format!("{}", RiskLevel::Low), "Low");
        assert_eq!(format!("{}", RiskLevel::Medium), "Medium");
        assert_eq!(format!("{}", RiskLevel::High), "High");
        assert_eq!(format!("{}", RiskLevel::Critical), "Critical");
    }

    #[test]
    fn test_file_access_all_variants() {
        let accesses = vec![
            (FileAccess::Read, RiskLevel::Safe),
            (FileAccess::List, RiskLevel::Safe),
            (FileAccess::Create, RiskLevel::Low),
            (FileAccess::Write, RiskLevel::Medium),
            (FileAccess::Delete, RiskLevel::High),
            (FileAccess::Execute, RiskLevel::High),
        ];
        for (access, expected_risk) in accesses {
            assert_eq!(access.risk_level(), expected_risk);
        }
    }

    #[test]
    fn test_file_access_display() {
        assert_eq!(format!("{}", FileAccess::Read), "read");
        assert_eq!(format!("{}", FileAccess::Write), "write");
        assert_eq!(format!("{}", FileAccess::Create), "create");
        assert_eq!(format!("{}", FileAccess::Delete), "delete");
        assert_eq!(format!("{}", FileAccess::Execute), "execute");
        assert_eq!(format!("{}", FileAccess::List), "list");
    }

    #[test]
    fn test_network_access_display() {
        assert_eq!(format!("{}", NetworkAccess::Connect), "connect");
        assert_eq!(format!("{}", NetworkAccess::Listen), "listen");
        assert_eq!(format!("{}", NetworkAccess::Dns), "dns");
    }

    #[test]
    fn test_rule_action_serde() {
        let actions = vec![RuleAction::Allow, RuleAction::Deny, RuleAction::Log];
        for action in actions {
            let json = serde_json::to_string(&action).unwrap();
            let parsed: RuleAction = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, action);
        }
    }

    #[test]
    fn test_rule_action_default() {
        assert_eq!(RuleAction::default(), RuleAction::Deny);
    }

    #[test]
    fn test_network_rule_port_range() {
        let rule = NetworkRule::new("range_rule", RuleAction::Allow).port_range(8000, 9000);

        assert!(rule.matches("example.com", 8500, NetworkAccess::Connect));
        assert!(!rule.matches("example.com", 7999, NetworkAccess::Connect));
        assert!(!rule.matches("example.com", 9001, NetworkAccess::Connect));
    }

    #[test]
    fn test_network_rule_access_filter() {
        let rule = NetworkRule::new("listen_only", RuleAction::Allow).access(NetworkAccess::Listen);

        assert!(rule.matches("example.com", 80, NetworkAccess::Listen));
        assert!(!rule.matches("example.com", 80, NetworkAccess::Connect));
    }

    #[test]
    fn test_network_rule_wildcard_all() {
        let rule = NetworkRule::new("all", RuleAction::Allow).host("*");

        assert!(rule.matches("anything.com", 80, NetworkAccess::Connect));
        assert!(rule.matches("localhost", 8080, NetworkAccess::Connect));
    }

    #[test]
    fn test_network_policy_check_log_action() {
        let policy =
            NetworkPolicy::new().add_rule(NetworkRule::new("log_rule", RuleAction::Log).port(8080));

        // Log action should return Log
        let result = policy.check("example.com", 8080, NetworkAccess::Connect);
        assert_eq!(result, RuleAction::Log);
    }

    #[test]
    fn test_network_policy_ipv6_localhost() {
        let policy = NetworkPolicy::new();
        assert!(policy.is_allowed("::1", 8080, NetworkAccess::Connect));
    }

    #[test]
    fn test_resource_limits_cpu_time() {
        let limits = ResourceLimits::new().cpu_time(120);
        assert_eq!(limits.max_cpu_time, Some(120));
    }

    #[test]
    fn test_resource_limits_memory() {
        let limits = ResourceLimits::new().memory(1_000_000);
        assert_eq!(limits.max_memory, Some(1_000_000));
    }

    #[test]
    fn test_resource_limits_timeout() {
        let limits = ResourceLimits::new().timeout(Duration::from_secs(30));
        assert_eq!(limits.timeout, Some(Duration::from_secs(30)));
    }

    #[test]
    fn test_resource_limits_check_output() {
        let limits = ResourceLimits::new();
        // No limit set - should pass
        assert!(limits.check_output(1_000_000).is_ok());

        // With limit
        let mut limits2 = ResourceLimits::new();
        limits2.max_output_size = Some(1000);
        assert!(limits2.check_output(500).is_ok());
        assert!(limits2.check_output(2000).is_err());
    }

    #[test]
    fn test_audit_result_all_variants() {
        let results = vec![
            (AuditResult::Allowed, ""),
            (AuditResult::Denied, ""),
            (AuditResult::Prompted, "?"),
            (AuditResult::Failed, "!"),
        ];
        for (result, icon) in results {
            assert_eq!(result.icon(), icon);
        }
    }

    #[test]
    fn test_audit_result_display() {
        assert_eq!(format!("{}", AuditResult::Allowed), "Allowed");
        assert_eq!(format!("{}", AuditResult::Denied), "Denied");
        assert_eq!(format!("{}", AuditResult::Prompted), "Prompted");
        assert_eq!(format!("{}", AuditResult::Failed), "Failed");
    }

    #[test]
    fn test_audit_entry_display() {
        let entry = AuditEntry::new("file_read", "agent", "/tmp/test", AuditResult::Allowed)
            .with_risk(RiskLevel::Safe);
        let display = entry.display();
        assert!(display.contains("agent"));
        assert!(display.contains("file_read"));
        assert!(display.contains("/tmp/test"));
        assert!(display.contains("Allowed"));
    }

    #[test]
    fn test_audit_logger_with_file() {
        let logger = AuditLogger::new().with_file(PathBuf::from("/tmp/audit.log"));
        assert!(logger.log_file.is_some());
    }

    #[test]
    fn test_audit_logger_recent() {
        let mut logger = AuditLogger::new();
        logger.log_action("a1", "agent", "x", AuditResult::Allowed, RiskLevel::Safe);
        logger.log_action("a2", "agent", "y", AuditResult::Denied, RiskLevel::High);
        logger.log_action("a3", "agent", "z", AuditResult::Allowed, RiskLevel::Low);

        let recent = logger.recent(2);
        assert_eq!(recent.len(), 2);
        // Should be in reverse order
        assert_eq!(recent[0].action, "a3");
        assert_eq!(recent[1].action, "a2");
    }

    #[test]
    fn test_audit_logger_by_result() {
        let mut logger = AuditLogger::new();
        logger.log_action("a1", "agent", "x", AuditResult::Allowed, RiskLevel::Safe);
        logger.log_action("a2", "agent", "y", AuditResult::Prompted, RiskLevel::Medium);
        logger.log_action("a3", "agent", "z", AuditResult::Allowed, RiskLevel::Low);

        let prompted = logger.by_result(AuditResult::Prompted);
        assert_eq!(prompted.len(), 1);
        assert_eq!(prompted[0].action, "a2");
    }

    #[test]
    fn test_audit_logger_by_risk() {
        let mut logger = AuditLogger::new();
        logger.log_action("a1", "agent", "x", AuditResult::Allowed, RiskLevel::High);
        logger.log_action("a2", "agent", "y", AuditResult::Allowed, RiskLevel::Low);
        logger.log_action("a3", "agent", "z", AuditResult::Allowed, RiskLevel::High);

        let high_risk = logger.by_risk(RiskLevel::High);
        assert_eq!(high_risk.len(), 2);
    }

    #[test]
    fn test_audit_logger_clear() {
        let mut logger = AuditLogger::new();
        logger.log_action("a1", "agent", "x", AuditResult::Allowed, RiskLevel::Safe);
        logger.log_action("a2", "agent", "y", AuditResult::Denied, RiskLevel::High);
        assert_eq!(logger.count(), 2);

        logger.clear();
        assert_eq!(logger.count(), 0);
    }

    #[test]
    fn test_audit_summary_display() {
        let summary = AuditSummary {
            total: 100,
            allowed: 80,
            denied: 15,
            prompted: 5,
            high_risk: 10,
        };
        let display = summary.display();
        assert!(display.contains("100"));
        assert!(display.contains("80"));
        assert!(display.contains("15"));
        assert!(display.contains("5"));
        assert!(display.contains("10"));
    }

    #[test]
    fn test_security_sandbox_default() {
        let sandbox = SecuritySandbox::default();
        assert!(sandbox.enabled);
        assert_eq!(sandbox.autonomy, AutonomyLevel::ConfirmDestructive);
    }

    #[test]
    fn test_security_sandbox_with_autonomy() {
        let sandbox = SecuritySandbox::new().with_autonomy(AutonomyLevel::FullAutonomous);
        assert_eq!(sandbox.autonomy, AutonomyLevel::FullAutonomous);
    }

    #[test]
    fn test_security_sandbox_needs_confirmation_all_levels() {
        // SuggestOnly - always needs confirmation
        let sandbox = SecuritySandbox::new().with_autonomy(AutonomyLevel::SuggestOnly);
        assert!(sandbox.needs_confirmation(RiskLevel::Safe));
        assert!(sandbox.needs_confirmation(RiskLevel::Critical));

        // ConfirmDestructive - only destructive needs confirmation
        let sandbox = SecuritySandbox::new().with_autonomy(AutonomyLevel::ConfirmDestructive);
        assert!(!sandbox.needs_confirmation(RiskLevel::Safe));
        assert!(!sandbox.needs_confirmation(RiskLevel::Medium));
        assert!(sandbox.needs_confirmation(RiskLevel::High));

        // SemiAutonomous - only critical needs confirmation
        let sandbox = SecuritySandbox::new().with_autonomy(AutonomyLevel::SemiAutonomous);
        assert!(!sandbox.needs_confirmation(RiskLevel::High));
        assert!(sandbox.needs_confirmation(RiskLevel::Critical));

        // FullAutonomous - never needs confirmation
        let sandbox = SecuritySandbox::new().with_autonomy(AutonomyLevel::FullAutonomous);
        assert!(!sandbox.needs_confirmation(RiskLevel::Critical));
    }

    #[test]
    fn test_sandbox_status_serde() {
        let status = SandboxStatus {
            enabled: true,
            autonomy: AutonomyLevel::SemiAutonomous,
            audit_count: 50,
            denied_count: 3,
        };
        let json = serde_json::to_string(&status).unwrap();
        let parsed: SandboxStatus = serde_json::from_str(&json).unwrap();
        assert!(parsed.enabled);
        assert_eq!(parsed.autonomy, AutonomyLevel::SemiAutonomous);
        assert_eq!(parsed.audit_count, 50);
    }

    #[test]
    fn test_port_spec_serde() {
        let specs = vec![
            PortSpec::Single(80),
            PortSpec::Range(8000, 9000),
            PortSpec::List(vec![80, 443, 8080]),
        ];
        for spec in specs {
            let json = serde_json::to_string(&spec).unwrap();
            let _: PortSpec = serde_json::from_str(&json).unwrap();
        }
    }

    #[test]
    fn test_filesystem_policy_allowed_extensions() {
        let mut policy = FilesystemPolicy::new();
        policy.allowed_extensions = Some(["rs", "txt"].iter().map(|s| s.to_string()).collect());

        // Test uses /tmp which should exist
        let allowed_path = std::env::temp_dir().join("test.rs");
        assert!(policy.is_allowed(&allowed_path, FileAccess::Read).is_ok());

        let denied_path = std::env::temp_dir().join("test.exe");
        assert!(policy.is_allowed(&denied_path, FileAccess::Read).is_err());
    }

    #[test]
    fn test_filesystem_policy_hidden_files() {
        let mut policy = FilesystemPolicy::new();
        policy.allow_hidden = false;

        let hidden_path = std::env::temp_dir().join(".hidden");
        assert!(policy.is_allowed(&hidden_path, FileAccess::Read).is_err());
    }

    #[test]
    fn test_network_rule_serde() {
        let rule = NetworkRule::new("test_rule", RuleAction::Allow)
            .host("*.example.com")
            .port(443)
            .access(NetworkAccess::Connect);

        let json = serde_json::to_string(&rule).unwrap();
        let parsed: NetworkRule = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.name, "test_rule");
        assert_eq!(parsed.action, RuleAction::Allow);
    }

    #[test]
    fn test_resource_limits_serde() {
        let limits = ResourceLimits::new().memory_mb(512).timeout_secs(60);

        let json = serde_json::to_string(&limits).unwrap();
        let parsed: ResourceLimits = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.max_memory, Some(512 * 1024 * 1024));
    }

    #[test]
    fn test_audit_entry_serde() {
        let entry = AuditEntry::new("test", "agent", "/path", AuditResult::Allowed)
            .with_details("details")
            .with_risk(RiskLevel::Medium);

        let json = serde_json::to_string(&entry).unwrap();
        let parsed: AuditEntry = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.action, "test");
        assert_eq!(parsed.risk, RiskLevel::Medium);
    }

    #[test]
    fn test_security_sandbox_check_network_log_action() {
        let mut sandbox = SecuritySandbox::new();
        sandbox.network =
            NetworkPolicy::new().add_rule(NetworkRule::new("log_http", RuleAction::Log).port(80));

        let result = sandbox.check_network_access("example.com", 80, NetworkAccess::Connect);
        assert!(result.is_ok());
        assert!(result.unwrap()); // Log action allows
    }

    #[test]
    fn test_security_sandbox_disabled_network() {
        let mut sandbox = SecuritySandbox::new();
        sandbox
            .set_enabled(false, Some(SANDBOX_DISABLE_TOKEN))
            .expect("disabling with correct token should succeed");

        // When disabled, even external hosts should be allowed
        let result = sandbox.check_network_access("malicious.com", 80, NetworkAccess::Connect);
        assert!(result.is_ok());
        assert!(result.unwrap());
    }
}