pi_agent_rust 0.1.7

High-performance AI coding agent CLI - Rust port of Pi Agent
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
//! Persistent storage for extension capability decisions.
//!
//! When a user chooses "Allow Always" or "Deny Always" for an extension
//! capability prompt, the decision is recorded here so it survives across
//! sessions.  Decisions are keyed by `(extension_id, capability)` and
//! optionally scoped to a version range.

use crate::config::Config;
use crate::error::{Error, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use tempfile::NamedTempFile;

/// On-disk schema version.
const CURRENT_VERSION: u32 = 1;

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

/// A persisted capability decision.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PersistedDecision {
    /// The capability that was prompted (e.g. `exec`, `http`).
    pub capability: String,

    /// `true` = allowed, `false` = denied.
    pub allow: bool,

    /// ISO-8601 timestamp when the decision was made.
    pub decided_at: String,

    /// Optional ISO-8601 expiry.  `None` means the decision never expires.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<String>,

    /// Optional semver range string (e.g. `>=1.0.0`).
    /// If the extension's version no longer satisfies this range the decision
    /// is treated as absent (user gets re-prompted).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version_range: Option<String>,
}

/// Root structure serialized to disk.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct PermissionsFile {
    version: u32,
    /// `extension_id` → list of decisions.
    decisions: HashMap<String, Vec<PersistedDecision>>,
}

impl Default for PermissionsFile {
    fn default() -> Self {
        Self {
            version: CURRENT_VERSION,
            decisions: HashMap::new(),
        }
    }
}

// ---------------------------------------------------------------------------
// Store
// ---------------------------------------------------------------------------

/// In-memory mirror of the on-disk permissions file with load/save helpers.
#[derive(Debug, Clone)]
pub struct PermissionStore {
    path: PathBuf,
    /// `extension_id` → `capability` → decision.
    decisions: HashMap<String, HashMap<String, PersistedDecision>>,
}

impl PermissionStore {
    /// Open (or create) the permissions store at the default global path.
    pub fn open_default() -> Result<Self> {
        Self::open(&Config::permissions_path())
    }

    /// Open (or create) the permissions store at a specific path.
    pub fn open(path: &Path) -> Result<Self> {
        let decisions = if path.exists() {
            let raw = std::fs::read_to_string(path).map_err(|e| {
                Error::config(format!(
                    "Failed to read permissions file {}: {e}",
                    path.display()
                ))
            })?;
            let file: PermissionsFile = serde_json::from_str(&raw).map_err(|e| {
                Error::config(format!(
                    "Failed to parse permissions file {}: {e}",
                    path.display()
                ))
            })?;
            // Convert Vec<PersistedDecision> → HashMap keyed by capability.
            file.decisions
                .into_iter()
                .map(|(ext_id, decs)| {
                    let by_cap: HashMap<String, PersistedDecision> = decs
                        .into_iter()
                        .map(|d| (d.capability.clone(), d))
                        .collect();
                    (ext_id, by_cap)
                })
                .collect()
        } else {
            HashMap::new()
        };

        Ok(Self {
            path: path.to_path_buf(),
            decisions,
        })
    }

    /// Look up a persisted decision for `(extension_id, capability)`.
    ///
    /// Returns `Some(true)` for allow, `Some(false)` for deny, `None` if no
    /// decision is stored (or the stored decision has expired).
    pub fn lookup(&self, extension_id: &str, capability: &str) -> Option<bool> {
        let by_cap = self.decisions.get(extension_id)?;
        let dec = by_cap.get(capability)?;

        // Check expiry.
        if let Some(ref exp) = dec.expires_at {
            let now = now_iso8601();
            if now > *exp {
                return None;
            }
        }

        Some(dec.allow)
    }

    /// Record a decision and persist to disk.
    pub fn record(&mut self, extension_id: &str, capability: &str, allow: bool) -> Result<()> {
        let decision = PersistedDecision {
            capability: capability.to_string(),
            allow,
            decided_at: now_iso8601(),
            expires_at: None,
            version_range: None,
        };

        self.decisions
            .entry(extension_id.to_string())
            .or_default()
            .insert(capability.to_string(), decision);

        self.save()
    }

    /// Record a decision with a version range constraint.
    pub fn record_with_version(
        &mut self,
        extension_id: &str,
        capability: &str,
        allow: bool,
        version_range: &str,
    ) -> Result<()> {
        let decision = PersistedDecision {
            capability: capability.to_string(),
            allow,
            decided_at: now_iso8601(),
            expires_at: None,
            version_range: Some(version_range.to_string()),
        };

        self.decisions
            .entry(extension_id.to_string())
            .or_default()
            .insert(capability.to_string(), decision);

        self.save()
    }

    /// Remove all decisions for a specific extension.
    pub fn revoke_extension(&mut self, extension_id: &str) -> Result<()> {
        self.decisions.remove(extension_id);
        self.save()
    }

    /// Remove all persisted decisions.
    pub fn reset(&mut self) -> Result<()> {
        self.decisions.clear();
        self.save()
    }

    /// List all persisted decisions grouped by extension.
    pub const fn list(&self) -> &HashMap<String, HashMap<String, PersistedDecision>> {
        &self.decisions
    }

    /// Seed the in-memory cache of an `ExtensionManager`-style
    /// `HashMap<String, HashMap<String, bool>>` from persisted decisions.
    ///
    /// Only non-expired entries are included.
    pub fn to_cache_map(&self) -> HashMap<String, HashMap<String, bool>> {
        let now = now_iso8601();
        self.decisions
            .iter()
            .map(|(ext_id, by_cap)| {
                let filtered: HashMap<String, bool> = by_cap
                    .iter()
                    .filter(|(_, dec)| dec.expires_at.as_ref().is_none_or(|exp| now <= *exp))
                    .map(|(cap, dec)| (cap.clone(), dec.allow))
                    .collect();
                (ext_id.clone(), filtered)
            })
            .filter(|(_, m)| !m.is_empty())
            .collect()
    }

    /// Retrieve the full decision cache (including version ranges) for
    /// runtime enforcement.
    pub fn to_decision_cache(&self) -> HashMap<String, HashMap<String, PersistedDecision>> {
        let now = now_iso8601();
        self.decisions
            .iter()
            .map(|(ext_id, by_cap)| {
                let filtered: HashMap<String, PersistedDecision> = by_cap
                    .iter()
                    .filter(|(_, dec)| dec.expires_at.as_ref().is_none_or(|exp| now <= *exp))
                    .map(|(cap, dec)| (cap.clone(), dec.clone()))
                    .collect();
                (ext_id.clone(), filtered)
            })
            .filter(|(_, m)| !m.is_empty())
            .collect()
    }

    // -----------------------------------------------------------------------
    // Internal
    // -----------------------------------------------------------------------

    /// Atomic write to disk following the same pattern as `config.rs`.
    fn save(&self) -> Result<()> {
        let parent = self.path.parent().unwrap_or_else(|| Path::new("."));
        if !parent.as_os_str().is_empty() {
            std::fs::create_dir_all(parent)?;
        }

        // Convert internal HashMap → Vec for stable serialization.
        let file = PermissionsFile {
            version: CURRENT_VERSION,
            decisions: self
                .decisions
                .iter()
                .map(|(ext_id, by_cap)| {
                    let decs: Vec<PersistedDecision> = by_cap.values().cloned().collect();
                    (ext_id.clone(), decs)
                })
                .collect(),
        };

        let mut contents = serde_json::to_string_pretty(&file)?;
        contents.push('\n');

        let mut tmp = NamedTempFile::new_in(parent)?;

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            let perms = std::fs::Permissions::from_mode(0o600);
            tmp.as_file().set_permissions(perms)?;
        }

        tmp.write_all(contents.as_bytes())?;
        tmp.as_file().sync_all()?;

        tmp.persist(&self.path).map_err(|err| {
            Error::config(format!(
                "Failed to persist permissions file to {}: {}",
                self.path.display(),
                err.error
            ))
        })?;

        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn now_iso8601() -> String {
    // Use wall-clock time.  We don't need sub-second precision for expiry
    // comparisons, but include it for diagnostics.
    let now = std::time::SystemTime::now();
    let duration = now
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default();
    let secs = duration.as_secs();
    // Simple ISO-8601 without pulling in chrono: YYYY-MM-DDThh:mm:ssZ
    // (good enough for lexicographic comparison).
    let days = secs / 86400;
    let time_of_day = secs % 86400;
    let hours = time_of_day / 3600;
    let minutes = (time_of_day % 3600) / 60;
    let seconds = time_of_day % 60;

    // Convert days since epoch to date using a basic algorithm.
    let (year, month, day) = days_to_ymd(days);
    format!("{year:04}-{month:02}-{day:02}T{hours:02}:{minutes:02}:{seconds:02}Z")
}

/// Convert days since Unix epoch to (year, month, day).
const fn days_to_ymd(days: u64) -> (u64, u64, u64) {
    // Algorithm from Howard Hinnant's `chrono`-compatible date library.
    let z = days + 719_468;
    let era = z / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    (y, m, d)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn roundtrip_empty() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");

        let store = PermissionStore::open(&path).unwrap();
        assert!(store.list().is_empty());

        // File should not exist until a record is made.
        assert!(!path.exists());
    }

    #[test]
    fn record_and_lookup() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");

        let mut store = PermissionStore::open(&path).unwrap();
        store.record("my-ext", "exec", true).unwrap();
        store.record("my-ext", "env", false).unwrap();
        store.record("other-ext", "http", true).unwrap();

        assert_eq!(store.lookup("my-ext", "exec"), Some(true));
        assert_eq!(store.lookup("my-ext", "env"), Some(false));
        assert_eq!(store.lookup("other-ext", "http"), Some(true));
        assert_eq!(store.lookup("unknown", "exec"), None);
        assert_eq!(store.lookup("my-ext", "unknown"), None);

        // Reload from disk.
        let store2 = PermissionStore::open(&path).unwrap();
        assert_eq!(store2.lookup("my-ext", "exec"), Some(true));
        assert_eq!(store2.lookup("my-ext", "env"), Some(false));
        assert_eq!(store2.lookup("other-ext", "http"), Some(true));
    }

    #[test]
    fn revoke_extension() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");

        let mut store = PermissionStore::open(&path).unwrap();
        store.record("my-ext", "exec", true).unwrap();
        store.record("my-ext", "env", false).unwrap();
        store.record("other-ext", "http", true).unwrap();

        store.revoke_extension("my-ext").unwrap();

        assert_eq!(store.lookup("my-ext", "exec"), None);
        assert_eq!(store.lookup("my-ext", "env"), None);
        assert_eq!(store.lookup("other-ext", "http"), Some(true));

        // Persists to disk.
        let store2 = PermissionStore::open(&path).unwrap();
        assert_eq!(store2.lookup("my-ext", "exec"), None);
    }

    #[test]
    fn reset_all() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");

        let mut store = PermissionStore::open(&path).unwrap();
        store.record("a", "exec", true).unwrap();
        store.record("b", "http", false).unwrap();
        store.reset().unwrap();

        assert!(store.list().is_empty());

        let store2 = PermissionStore::open(&path).unwrap();
        assert!(store2.list().is_empty());
    }

    #[test]
    fn to_cache_map_filters_expired() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");

        let mut store = PermissionStore::open(&path).unwrap();

        // Insert a non-expired decision directly.
        store
            .decisions
            .entry("ext1".to_string())
            .or_default()
            .insert(
                "exec".to_string(),
                PersistedDecision {
                    capability: "exec".to_string(),
                    allow: true,
                    decided_at: "2026-01-01T00:00:00Z".to_string(),
                    expires_at: Some("2099-12-31T23:59:59Z".to_string()),
                    version_range: None,
                },
            );

        // Insert an expired decision.
        store
            .decisions
            .entry("ext1".to_string())
            .or_default()
            .insert(
                "env".to_string(),
                PersistedDecision {
                    capability: "env".to_string(),
                    allow: false,
                    decided_at: "2020-01-01T00:00:00Z".to_string(),
                    expires_at: Some("2020-06-01T00:00:00Z".to_string()),
                    version_range: None,
                },
            );

        let cache = store.to_cache_map();
        assert_eq!(cache.get("ext1").and_then(|m| m.get("exec")), Some(&true));
        // Expired entry should be absent.
        assert_eq!(cache.get("ext1").and_then(|m| m.get("env")), None);
    }

    #[test]
    fn overwrite_decision() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");

        let mut store = PermissionStore::open(&path).unwrap();
        store.record("ext", "exec", true).unwrap();
        assert_eq!(store.lookup("ext", "exec"), Some(true));

        // Overwrite with deny.
        store.record("ext", "exec", false).unwrap();
        assert_eq!(store.lookup("ext", "exec"), Some(false));

        // Persists.
        let store2 = PermissionStore::open(&path).unwrap();
        assert_eq!(store2.lookup("ext", "exec"), Some(false));
    }

    #[test]
    fn version_range_stored() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");

        let mut store = PermissionStore::open(&path).unwrap();
        store
            .record_with_version("ext", "exec", true, ">=1.0.0")
            .unwrap();

        let store2 = PermissionStore::open(&path).unwrap();
        let dec = store2
            .decisions
            .get("ext")
            .and_then(|m| m.get("exec"))
            .unwrap();
        assert_eq!(dec.version_range.as_deref(), Some(">=1.0.0"));
        assert!(dec.allow);
    }

    #[test]
    fn now_iso8601_format() {
        let ts = now_iso8601();
        // Basic format check: YYYY-MM-DDThh:mm:ssZ
        assert_eq!(ts.len(), 20);
        assert!(ts.ends_with('Z'));
        assert_eq!(ts.as_bytes()[4], b'-');
        assert_eq!(ts.as_bytes()[7], b'-');
        assert_eq!(ts.as_bytes()[10], b'T');
        assert_eq!(ts.as_bytes()[13], b':');
        assert_eq!(ts.as_bytes()[16], b':');
    }

    // -----------------------------------------------------------------------
    // days_to_ymd tests
    // -----------------------------------------------------------------------

    #[test]
    fn days_to_ymd_epoch() {
        // Day 0 = 1970-01-01
        assert_eq!(days_to_ymd(0), (1970, 1, 1));
    }

    #[test]
    fn days_to_ymd_known_dates() {
        // 2000-01-01 = day 10957
        assert_eq!(days_to_ymd(10957), (2000, 1, 1));
        // 2000-02-29 (leap year) = day 10957 + 31 (Jan) + 28 (Feb 1..28) = 11016
        assert_eq!(days_to_ymd(11016), (2000, 2, 29));
        // 2000-03-01 = day 11017
        assert_eq!(days_to_ymd(11017), (2000, 3, 1));
        // 2024-01-01 = day 19723
        assert_eq!(days_to_ymd(19723), (2024, 1, 1));
    }

    #[test]
    fn days_to_ymd_dec_31() {
        // 1970-12-31 = day 364
        assert_eq!(days_to_ymd(364), (1970, 12, 31));
        // 1971-01-01 = day 365
        assert_eq!(days_to_ymd(365), (1971, 1, 1));
    }

    #[test]
    fn days_to_ymd_leap_year_boundary() {
        // 1972 is a leap year: Feb 29 = day 789 (730 days for 1970-1971 + 31 + 28)
        // 1970: 365, 1971: 365 = 730
        // Jan 1972: 31 → 761, Feb 1-28: 28 → 789 = Feb 29
        assert_eq!(days_to_ymd(789), (1972, 2, 29));
        assert_eq!(days_to_ymd(790), (1972, 3, 1));
    }

    #[test]
    fn days_to_ymd_far_future() {
        // 2099-12-31 = day 47481, 2100-01-01 = day 47482
        assert_eq!(days_to_ymd(47_481), (2099, 12, 31));
        assert_eq!(days_to_ymd(47_482), (2100, 1, 1));
    }

    // -----------------------------------------------------------------------
    // now_iso8601 additional tests
    // -----------------------------------------------------------------------

    #[test]
    fn now_iso8601_lexicographic_order() {
        let ts1 = now_iso8601();
        let ts2 = now_iso8601();
        // Second call should be >= first (same second or later)
        assert!(ts2 >= ts1);
    }

    #[test]
    fn now_iso8601_year_plausible() {
        let ts = now_iso8601();
        let year: u32 = ts[0..4].parse().unwrap();
        assert!(year >= 2024);
        assert!(year <= 2100);
    }

    // -----------------------------------------------------------------------
    // PersistedDecision serde tests
    // -----------------------------------------------------------------------

    #[test]
    fn persisted_decision_serde_minimal() {
        // Optional fields should be omitted when None
        let dec = PersistedDecision {
            capability: "exec".to_string(),
            allow: true,
            decided_at: "2026-01-15T10:30:00Z".to_string(),
            expires_at: None,
            version_range: None,
        };
        let json = serde_json::to_string(&dec).unwrap();
        assert!(!json.contains("expires_at"));
        assert!(!json.contains("version_range"));

        let roundtrip: PersistedDecision = serde_json::from_str(&json).unwrap();
        assert_eq!(roundtrip, dec);
    }

    #[test]
    fn persisted_decision_serde_full() {
        let dec = PersistedDecision {
            capability: "http".to_string(),
            allow: false,
            decided_at: "2026-01-15T10:30:00Z".to_string(),
            expires_at: Some("2026-06-15T10:30:00Z".to_string()),
            version_range: Some(">=2.0.0".to_string()),
        };
        let json = serde_json::to_string(&dec).unwrap();
        assert!(json.contains("expires_at"));
        assert!(json.contains("version_range"));

        let roundtrip: PersistedDecision = serde_json::from_str(&json).unwrap();
        assert_eq!(roundtrip, dec);
    }

    #[test]
    fn persisted_decision_deserialize_missing_optionals() {
        // JSON without optional fields should deserialize fine
        let json = r#"{"capability":"exec","allow":true,"decided_at":"2026-01-01T00:00:00Z"}"#;
        let dec: PersistedDecision = serde_json::from_str(json).unwrap();
        assert_eq!(dec.capability, "exec");
        assert!(dec.allow);
        assert!(dec.expires_at.is_none());
        assert!(dec.version_range.is_none());
    }

    // -----------------------------------------------------------------------
    // PermissionsFile serde tests
    // -----------------------------------------------------------------------

    #[test]
    fn permissions_file_default_version() {
        let file = PermissionsFile::default();
        assert_eq!(file.version, CURRENT_VERSION);
        assert!(file.decisions.is_empty());
    }

    #[test]
    fn permissions_file_serde_roundtrip() {
        let mut decisions = HashMap::new();
        decisions.insert(
            "ext-a".to_string(),
            vec![PersistedDecision {
                capability: "exec".to_string(),
                allow: true,
                decided_at: "2026-01-01T00:00:00Z".to_string(),
                expires_at: None,
                version_range: None,
            }],
        );
        let file = PermissionsFile {
            version: CURRENT_VERSION,
            decisions,
        };
        let json = serde_json::to_string_pretty(&file).unwrap();
        let roundtrip: PermissionsFile = serde_json::from_str(&json).unwrap();
        assert_eq!(roundtrip.version, CURRENT_VERSION);
        assert_eq!(roundtrip.decisions.len(), 1);
        assert_eq!(roundtrip.decisions["ext-a"].len(), 1);
        assert_eq!(roundtrip.decisions["ext-a"][0].capability, "exec");
    }

    // -----------------------------------------------------------------------
    // PermissionStore edge cases
    // -----------------------------------------------------------------------

    #[test]
    fn open_corrupt_file_returns_error() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");
        std::fs::write(&path, "not valid json!!!").unwrap();

        let result = PermissionStore::open(&path);
        assert!(result.is_err());
        let err_msg = format!("{}", result.unwrap_err());
        assert!(err_msg.contains("parse"));
    }

    #[test]
    fn open_empty_json_object_returns_error() {
        // An empty object {} is missing required fields
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");
        std::fs::write(&path, "{}").unwrap();

        let result = PermissionStore::open(&path);
        assert!(result.is_err());
    }

    #[test]
    fn open_valid_empty_decisions() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");
        std::fs::write(&path, r#"{"version":1,"decisions":{}}"#).unwrap();

        let store = PermissionStore::open(&path).unwrap();
        assert!(store.list().is_empty());
    }

    #[test]
    fn lookup_expired_decision_returns_none() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");
        let mut store = PermissionStore::open(&path).unwrap();

        // Insert a decision that expired in the past
        store
            .decisions
            .entry("ext".to_string())
            .or_default()
            .insert(
                "exec".to_string(),
                PersistedDecision {
                    capability: "exec".to_string(),
                    allow: true,
                    decided_at: "2020-01-01T00:00:00Z".to_string(),
                    expires_at: Some("2020-06-01T00:00:00Z".to_string()),
                    version_range: None,
                },
            );

        assert_eq!(store.lookup("ext", "exec"), None);
    }

    #[test]
    fn lookup_future_expiry_returns_decision() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");
        let mut store = PermissionStore::open(&path).unwrap();

        store
            .decisions
            .entry("ext".to_string())
            .or_default()
            .insert(
                "exec".to_string(),
                PersistedDecision {
                    capability: "exec".to_string(),
                    allow: false,
                    decided_at: "2026-01-01T00:00:00Z".to_string(),
                    expires_at: Some("2099-12-31T23:59:59Z".to_string()),
                    version_range: None,
                },
            );

        assert_eq!(store.lookup("ext", "exec"), Some(false));
    }

    #[test]
    fn lookup_no_expiry_returns_decision() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");
        let mut store = PermissionStore::open(&path).unwrap();

        store
            .decisions
            .entry("ext".to_string())
            .or_default()
            .insert(
                "exec".to_string(),
                PersistedDecision {
                    capability: "exec".to_string(),
                    allow: true,
                    decided_at: "2026-01-01T00:00:00Z".to_string(),
                    expires_at: None,
                    version_range: None,
                },
            );

        assert_eq!(store.lookup("ext", "exec"), Some(true));
    }

    #[test]
    fn record_creates_parent_directories() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir
            .path()
            .join("deep")
            .join("nested")
            .join("permissions.json");

        let mut store = PermissionStore::open(&path).unwrap();
        store.record("ext", "exec", true).unwrap();

        assert!(path.exists());
        let store2 = PermissionStore::open(&path).unwrap();
        assert_eq!(store2.lookup("ext", "exec"), Some(true));
    }

    #[test]
    fn multiple_capabilities_per_extension() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");
        let mut store = PermissionStore::open(&path).unwrap();

        store.record("ext", "exec", true).unwrap();
        store.record("ext", "http", false).unwrap();
        store.record("ext", "env", true).unwrap();
        store.record("ext", "fs", false).unwrap();

        assert_eq!(store.lookup("ext", "exec"), Some(true));
        assert_eq!(store.lookup("ext", "http"), Some(false));
        assert_eq!(store.lookup("ext", "env"), Some(true));
        assert_eq!(store.lookup("ext", "fs"), Some(false));

        // All persist
        let store2 = PermissionStore::open(&path).unwrap();
        assert_eq!(store2.lookup("ext", "exec"), Some(true));
        assert_eq!(store2.lookup("ext", "http"), Some(false));
        assert_eq!(store2.lookup("ext", "env"), Some(true));
        assert_eq!(store2.lookup("ext", "fs"), Some(false));
    }

    #[test]
    fn record_with_version_stores_range() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");
        let mut store = PermissionStore::open(&path).unwrap();

        store
            .record_with_version("ext", "exec", true, "^1.0.0")
            .unwrap();
        store
            .record_with_version("ext", "http", false, ">=2.0.0 <3.0.0")
            .unwrap();

        let dec_exec = store.decisions["ext"].get("exec").unwrap();
        assert_eq!(dec_exec.version_range.as_deref(), Some("^1.0.0"));
        assert!(dec_exec.allow);

        let dec_http = store.decisions["ext"].get("http").unwrap();
        assert_eq!(dec_http.version_range.as_deref(), Some(">=2.0.0 <3.0.0"));
        assert!(!dec_http.allow);
    }

    #[test]
    fn record_with_version_overwrites_previous() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");
        let mut store = PermissionStore::open(&path).unwrap();

        store
            .record_with_version("ext", "exec", true, "^1.0.0")
            .unwrap();
        store
            .record_with_version("ext", "exec", false, "^2.0.0")
            .unwrap();

        let dec = store.decisions["ext"].get("exec").unwrap();
        assert_eq!(dec.version_range.as_deref(), Some("^2.0.0"));
        assert!(!dec.allow);
    }

    #[test]
    fn list_returns_all_decisions() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");
        let mut store = PermissionStore::open(&path).unwrap();

        store.record("ext-a", "exec", true).unwrap();
        store.record("ext-a", "http", false).unwrap();
        store.record("ext-b", "env", true).unwrap();

        let all = store.list();
        assert_eq!(all.len(), 2);
        assert_eq!(all["ext-a"].len(), 2);
        assert_eq!(all["ext-b"].len(), 1);
    }

    #[test]
    fn revoke_nonexistent_extension_is_noop() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");
        let mut store = PermissionStore::open(&path).unwrap();

        store.record("ext", "exec", true).unwrap();
        // Revoking a non-existent extension should not fail
        store.revoke_extension("nonexistent").unwrap();

        assert_eq!(store.lookup("ext", "exec"), Some(true));
    }

    // -----------------------------------------------------------------------
    // to_cache_map additional scenarios
    // -----------------------------------------------------------------------

    #[test]
    fn to_cache_map_all_expired_removes_extension() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");
        let mut store = PermissionStore::open(&path).unwrap();

        // All decisions for this extension are expired
        store
            .decisions
            .entry("ext".to_string())
            .or_default()
            .insert(
                "exec".to_string(),
                PersistedDecision {
                    capability: "exec".to_string(),
                    allow: true,
                    decided_at: "2020-01-01T00:00:00Z".to_string(),
                    expires_at: Some("2020-06-01T00:00:00Z".to_string()),
                    version_range: None,
                },
            );
        store
            .decisions
            .entry("ext".to_string())
            .or_default()
            .insert(
                "http".to_string(),
                PersistedDecision {
                    capability: "http".to_string(),
                    allow: false,
                    decided_at: "2020-01-01T00:00:00Z".to_string(),
                    expires_at: Some("2020-06-01T00:00:00Z".to_string()),
                    version_range: None,
                },
            );

        let cache = store.to_cache_map();
        // Extension should not appear at all since all entries are expired
        assert!(!cache.contains_key("ext"));
    }

    #[test]
    fn to_cache_map_no_expiry_always_included() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");
        let mut store = PermissionStore::open(&path).unwrap();

        store
            .decisions
            .entry("ext".to_string())
            .or_default()
            .insert(
                "exec".to_string(),
                PersistedDecision {
                    capability: "exec".to_string(),
                    allow: true,
                    decided_at: "2026-01-01T00:00:00Z".to_string(),
                    expires_at: None,
                    version_range: None,
                },
            );

        let cache = store.to_cache_map();
        assert_eq!(cache.get("ext").and_then(|m| m.get("exec")), Some(&true));
    }

    #[test]
    fn to_cache_map_multiple_extensions() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");
        let mut store = PermissionStore::open(&path).unwrap();

        store.record("ext-a", "exec", true).unwrap();
        store.record("ext-a", "http", false).unwrap();
        store.record("ext-b", "env", true).unwrap();

        let cache = store.to_cache_map();
        assert_eq!(cache.len(), 2);
        assert_eq!(cache.get("ext-a").and_then(|m| m.get("exec")), Some(&true));
        assert_eq!(cache.get("ext-a").and_then(|m| m.get("http")), Some(&false));
        assert_eq!(cache.get("ext-b").and_then(|m| m.get("env")), Some(&true));
    }

    // -----------------------------------------------------------------------
    // File permissions test (Unix)
    // -----------------------------------------------------------------------

    #[cfg(unix)]
    #[test]
    fn save_sets_file_permissions_0o600() {
        use std::os::unix::fs::PermissionsExt as _;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");

        let mut store = PermissionStore::open(&path).unwrap();
        store.record("ext", "exec", true).unwrap();

        let metadata = std::fs::metadata(&path).unwrap();
        let mode = metadata.permissions().mode() & 0o777;
        assert_eq!(mode, 0o600);
    }

    // -----------------------------------------------------------------------
    // Disk persistence roundtrip tests
    // -----------------------------------------------------------------------

    #[test]
    fn multiple_saves_and_reloads() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");

        // First session
        {
            let mut store = PermissionStore::open(&path).unwrap();
            store.record("ext-a", "exec", true).unwrap();
            store.record("ext-b", "http", false).unwrap();
        }

        // Second session: modify and add
        {
            let mut store = PermissionStore::open(&path).unwrap();
            store.record("ext-a", "exec", false).unwrap(); // overwrite
            store.record("ext-c", "env", true).unwrap(); // new
        }

        // Third session: verify all state
        {
            let store = PermissionStore::open(&path).unwrap();
            assert_eq!(store.lookup("ext-a", "exec"), Some(false)); // overwritten
            assert_eq!(store.lookup("ext-b", "http"), Some(false)); // unchanged
            assert_eq!(store.lookup("ext-c", "env"), Some(true)); // new
        }
    }

    #[test]
    fn reset_then_record_works() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");

        let mut store = PermissionStore::open(&path).unwrap();
        store.record("ext", "exec", true).unwrap();
        store.reset().unwrap();
        store.record("ext", "http", false).unwrap();

        assert_eq!(store.lookup("ext", "exec"), None);
        assert_eq!(store.lookup("ext", "http"), Some(false));

        let store2 = PermissionStore::open(&path).unwrap();
        assert_eq!(store2.lookup("ext", "exec"), None);
        assert_eq!(store2.lookup("ext", "http"), Some(false));
    }

    #[test]
    fn decided_at_is_recent() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("permissions.json");

        let mut store = PermissionStore::open(&path).unwrap();
        store.record("ext", "exec", true).unwrap();

        let dec = &store.decisions["ext"]["exec"];
        // decided_at should be a recent timestamp (year >= 2024)
        let year: u32 = dec.decided_at[0..4].parse().unwrap();
        assert!(year >= 2024);
    }

    mod proptest_permissions {
        use super::*;
        use proptest::prelude::*;

        proptest! {
            /// `days_to_ymd` produces valid month/day ranges.
            #[test]
            fn days_to_ymd_valid_ranges(days in 0..100_000u64) {
                let (y, m, d) = days_to_ymd(days);
                assert!(y >= 1970, "year {y} too small for days={days}");
                assert!((1..=12).contains(&m), "month {m} out of range");
                assert!((1..=31).contains(&d), "day {d} out of range");
            }

            /// `days_to_ymd(0)` is 1970-01-01.
            #[test]
            fn days_to_ymd_epoch(_dummy in 0..1u8) {
                let (y, m, d) = days_to_ymd(0);
                assert_eq!((y, m, d), (1970, 1, 1));
            }

            /// Consecutive days increment the day or roll the month/year.
            #[test]
            fn days_to_ymd_consecutive(days in 0..99_999u64) {
                let (y1, m1, d1) = days_to_ymd(days);
                let (y2, m2, d2) = days_to_ymd(days + 1);
                // Either same date with day+1, or month/year rollover
                if d2 == d1 + 1 && m2 == m1 && y2 == y1 {
                    // Normal day increment
                } else if d2 == 1 {
                    // Day rolled over to 1 — month or year changed
                    assert!(m2 != m1 || y2 != y1);
                } else {
                    panic!("unexpected day sequence: {y1}-{m1}-{d1} -> {y2}-{m2}-{d2}");
                }
            }

            /// `now_iso8601` produces valid ISO-8601 format.
            #[test]
            fn now_iso8601_format(_dummy in 0..1u8) {
                let ts = now_iso8601();
                assert_eq!(ts.len(), 20, "expected YYYY-MM-DDThh:mm:ssZ, got {ts}");
                assert!(ts.ends_with('Z'));
                assert_eq!(&ts[4..5], "-");
                assert_eq!(&ts[7..8], "-");
                assert_eq!(&ts[10..11], "T");
                assert_eq!(&ts[13..14], ":");
                assert_eq!(&ts[16..17], ":");
            }

            /// `PersistedDecision` serde roundtrip preserves all fields.
            #[test]
            fn decision_serde_roundtrip(
                cap in "[a-z]{1,10}",
                allow in proptest::bool::ANY,
                has_expiry in proptest::bool::ANY,
                has_range in proptest::bool::ANY
            ) {
                let dec = PersistedDecision {
                    capability: cap,
                    allow,
                    decided_at: "2025-01-01T00:00:00Z".to_string(),
                    expires_at: if has_expiry { Some("2030-01-01T00:00:00Z".to_string()) } else { None },
                    version_range: if has_range { Some(">=1.0.0".to_string()) } else { None },
                };
                let json = serde_json::to_string(&dec).unwrap();
                let back: PersistedDecision = serde_json::from_str(&json).unwrap();
                assert_eq!(dec, back);
            }

            /// Record then lookup returns the correct allow/deny value.
            #[test]
            fn record_lookup_roundtrip(
                ext_id in "[a-z]{1,8}",
                cap in "[a-z]{1,8}",
                allow in proptest::bool::ANY
            ) {
                let dir = tempfile::tempdir().unwrap();
                let path = dir.path().join("perm.json");
                let mut store = PermissionStore::open(&path).unwrap();
                store.record(&ext_id, &cap, allow).unwrap();
                assert_eq!(store.lookup(&ext_id, &cap), Some(allow));
            }

            /// Lookup for unknown extension returns None.
            #[test]
            fn lookup_unknown_extension(ext in "[a-z]{1,10}", cap in "[a-z]{1,5}") {
                let dir = tempfile::tempdir().unwrap();
                let path = dir.path().join("perm.json");
                let store = PermissionStore::open(&path).unwrap();
                assert_eq!(store.lookup(&ext, &cap), None);
            }

            /// Record overwrites previous decision for same (ext, cap).
            #[test]
            fn record_overwrites(ext in "[a-z]{1,8}", cap in "[a-z]{1,8}") {
                let dir = tempfile::tempdir().unwrap();
                let path = dir.path().join("perm.json");
                let mut store = PermissionStore::open(&path).unwrap();
                store.record(&ext, &cap, true).unwrap();
                assert_eq!(store.lookup(&ext, &cap), Some(true));
                store.record(&ext, &cap, false).unwrap();
                assert_eq!(store.lookup(&ext, &cap), Some(false));
            }

            /// Revoke removes all decisions for an extension.
            #[test]
            fn revoke_removes_all(ext in "[a-z]{1,8}", cap1 in "[a-z]{1,5}", cap2 in "[a-z]{1,5}") {
                let dir = tempfile::tempdir().unwrap();
                let path = dir.path().join("perm.json");
                let mut store = PermissionStore::open(&path).unwrap();
                store.record(&ext, &cap1, true).unwrap();
                store.record(&ext, &cap2, false).unwrap();
                store.revoke_extension(&ext).unwrap();
                assert_eq!(store.lookup(&ext, &cap1), None);
                assert_eq!(store.lookup(&ext, &cap2), None);
            }

            /// Days 365 is in 1971 (non-leap year 1970).
            #[test]
            fn days_to_ymd_year_boundary(_dummy in 0..1u8) {
                let (y, m, d) = days_to_ymd(365);
                assert_eq!(y, 1971);
                assert_eq!(m, 1);
                assert_eq!(d, 1);
            }

            /// Leap day 2000 (day 10957 from epoch) is Feb 29.
            #[test]
            fn days_to_ymd_leap_day_2000(_dummy in 0..1u8) {
                // 2000-02-29 is day 11016 from epoch
                // 1970-01-01 + 11016 days
                let (y, m, d) = days_to_ymd(11016);
                assert_eq!((y, m, d), (2000, 2, 29));
            }
        }
    }
}