eidetic-engine 0.15.1

Durable, local-first, explainable memory for coding agents.
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
//! Security profiles and file-permission diagnostics (EE-279).
//!
//! Provides security profiles that control trust thresholds, redaction policies,
//! and file permission requirements. Profiles are validated at startup and can
//! be selected via `EE_SECURITY_PROFILE` or `--security-profile`.
//!
//! Available profiles:
//! - `default`: Balanced security for normal operation
//! - `strict`: High-security mode with aggressive redaction and low trust ceilings
//! - `permissive`: Relaxed security for development/debugging
//!
//! File permission diagnostics check that the workspace database and config files
//! have appropriate permissions (not world-readable, owned by current user, etc.).

use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;

use crate::config::env_registry::{EnvVar, read};

/// Security profile controlling trust and access policies.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum SecurityProfile {
    /// Balanced security for normal operation.
    #[default]
    Default,
    /// High-security mode with aggressive policies.
    Strict,
    /// Relaxed security for development/debugging.
    Permissive,
}

impl SecurityProfile {
    /// Stable lowercase wire form for JSON output.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Default => "default",
            Self::Strict => "strict",
            Self::Permissive => "permissive",
        }
    }

    /// All profiles in stable order.
    #[must_use]
    pub const fn all() -> [Self; 3] {
        [Self::Default, Self::Strict, Self::Permissive]
    }

    /// Trust ceiling for import sources under this profile.
    #[must_use]
    pub const fn trust_ceiling(self) -> f32 {
        match self {
            Self::Default => 1.0,
            Self::Strict => 0.8,
            Self::Permissive => 1.0,
        }
    }

    /// Trust floor for import sources under this profile.
    #[must_use]
    pub const fn trust_floor(self) -> f32 {
        match self {
            Self::Default => 0.05,
            Self::Strict => 0.01,
            Self::Permissive => 0.10,
        }
    }

    /// Whether secret redaction is enforced in output.
    ///
    /// Even the permissive profile keeps redaction enabled. The profile relaxes
    /// file-permission and import-source posture for local debugging, but it
    /// must not turn context packs into secret-bearing output.
    #[must_use]
    pub const fn enforce_redaction(self) -> bool {
        match self {
            Self::Default => true,
            Self::Strict => true,
            Self::Permissive => true,
        }
    }

    /// Whether file permission checks are enforced.
    #[must_use]
    pub const fn enforce_file_permissions(self) -> bool {
        match self {
            Self::Default => true,
            Self::Strict => true,
            Self::Permissive => false,
        }
    }

    /// Maximum allowed permission bits for database files (octal).
    /// 0o600 = owner read/write only.
    #[must_use]
    pub const fn max_db_permissions(self) -> u32 {
        match self {
            Self::Default => 0o600,
            Self::Strict => 0o600,
            Self::Permissive => 0o666,
        }
    }

    /// Maximum allowed permission bits for config files (octal).
    /// 0o644 = owner read/write, group/other read.
    #[must_use]
    pub const fn max_config_permissions(self) -> u32 {
        match self {
            Self::Default => 0o644,
            Self::Strict => 0o600,
            Self::Permissive => 0o666,
        }
    }

    /// Whether to allow importing from untrusted sources.
    #[must_use]
    pub const fn allow_untrusted_imports(self) -> bool {
        match self {
            Self::Default => true,
            Self::Strict => false,
            Self::Permissive => true,
        }
    }
}

impl fmt::Display for SecurityProfile {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for SecurityProfile {
    type Err = ParseSecurityProfileError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let normalized = s.trim().to_ascii_lowercase();
        match normalized.as_str() {
            "default" => Ok(Self::Default),
            "strict" => Ok(Self::Strict),
            "permissive" => Ok(Self::Permissive),
            _ => Err(ParseSecurityProfileError {
                input: s.to_owned(),
            }),
        }
    }
}

/// Error when parsing a security profile string.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseSecurityProfileError {
    /// The invalid input string.
    pub input: String,
}

impl fmt::Display for ParseSecurityProfileError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "unknown security profile `{}`; expected one of: default, strict, permissive",
            self.input
        )
    }
}

impl std::error::Error for ParseSecurityProfileError {}

/// Result of a file permission check.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FilePermissionCheck {
    /// Path that was checked.
    pub path: String,
    /// Whether the file exists.
    pub exists: bool,
    /// Current permission mode (octal), if readable.
    pub current_mode: Option<u32>,
    /// Maximum allowed mode for this file type.
    pub max_allowed_mode: u32,
    /// Whether the check passed.
    pub passed: bool,
    /// Issue description if check failed.
    pub issue: Option<String>,
    /// Suggested fix if check failed.
    pub repair: Option<String>,
}

impl FilePermissionCheck {
    /// Create a passing check result.
    #[must_use]
    pub fn pass(path: impl Into<String>, mode: u32, max_allowed: u32) -> Self {
        Self {
            path: path.into(),
            exists: true,
            current_mode: Some(mode),
            max_allowed_mode: max_allowed,
            passed: true,
            issue: None,
            repair: None,
        }
    }

    /// Create a failing check result.
    #[must_use]
    pub fn fail(
        path: impl Into<String>,
        mode: u32,
        max_allowed: u32,
        issue: impl Into<String>,
        repair: impl Into<String>,
    ) -> Self {
        Self {
            path: path.into(),
            exists: true,
            current_mode: Some(mode),
            max_allowed_mode: max_allowed,
            passed: false,
            issue: Some(issue.into()),
            repair: Some(repair.into()),
        }
    }

    /// Create a failing check result when a trustworthy mode could not be read.
    #[must_use]
    pub fn fail_without_mode(
        path: impl Into<String>,
        max_allowed: u32,
        issue: impl Into<String>,
        repair: impl Into<String>,
    ) -> Self {
        Self {
            path: path.into(),
            exists: true,
            current_mode: None,
            max_allowed_mode: max_allowed,
            passed: false,
            issue: Some(issue.into()),
            repair: Some(repair.into()),
        }
    }

    /// Create a result for a file that doesn't exist.
    #[must_use]
    pub fn not_found(path: impl Into<String>, max_allowed: u32) -> Self {
        Self {
            path: path.into(),
            exists: false,
            current_mode: None,
            max_allowed_mode: max_allowed,
            passed: true,
            issue: None,
            repair: None,
        }
    }
}

/// Summary of all file permission checks for a workspace.
#[derive(Clone, Debug)]
pub struct FilePermissionReport {
    /// Security profile used for checks.
    pub profile: SecurityProfile,
    /// Individual file check results.
    pub checks: Vec<FilePermissionCheck>,
    /// Overall pass/fail verdict.
    pub passed: bool,
    /// Total number of issues found.
    pub issue_count: u32,
}

impl FilePermissionReport {
    /// Create a new report from check results.
    #[must_use]
    pub fn from_checks(profile: SecurityProfile, checks: Vec<FilePermissionCheck>) -> Self {
        let issue_count = checks.iter().filter(|c| !c.passed).count() as u32;
        let passed = issue_count == 0;
        Self {
            profile,
            checks,
            passed,
            issue_count,
        }
    }
}

/// Check file permissions for a workspace against a security profile.
#[must_use]
pub fn check_workspace_permissions(
    workspace: &Path,
    profile: SecurityProfile,
) -> FilePermissionReport {
    let mut checks = Vec::new();
    let max_file_mode = if profile.enforce_file_permissions() {
        profile.max_db_permissions()
    } else {
        0o777
    };
    let max_config_mode = if profile.enforce_file_permissions() {
        profile.max_config_permissions()
    } else {
        0o777
    };

    let db_path = workspace.join(".ee").join("ee.db");
    checks.push(check_file_permissions(&db_path, max_file_mode, "database"));

    let config_path = workspace.join(".ee").join("config.toml");
    checks.push(check_file_permissions(
        &config_path,
        max_config_mode,
        "config",
    ));

    let index_dir = workspace.join(".ee").join("index");
    if optional_directory_should_be_checked(&index_dir) {
        checks.push(check_directory_permissions(
            &index_dir,
            max_file_mode,
            "index directory",
        ));
    }

    FilePermissionReport::from_checks(profile, checks)
}

fn check_file_permissions(path: &Path, max_mode: u32, file_type: &str) -> FilePermissionCheck {
    if let Some(check) = check_path_symlink_components(path, max_mode, file_type) {
        return check;
    }

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        match std::fs::symlink_metadata(path) {
            Ok(metadata) => {
                let mode = metadata.permissions().mode() & 0o777;
                if !metadata.file_type().is_file() {
                    return FilePermissionCheck::fail(
                        path.display().to_string(),
                        mode,
                        max_mode,
                        format!("{file_type} is not a regular file"),
                        format!(
                            "Replace {} with a regular file before re-running diagnostics.",
                            path.display()
                        ),
                    );
                }
                let excess_bits = mode & !max_mode;
                if excess_bits == 0 {
                    FilePermissionCheck::pass(path.display().to_string(), mode, max_mode)
                } else {
                    FilePermissionCheck::fail(
                        path.display().to_string(),
                        mode,
                        max_mode,
                        format!(
                            "{} has mode {:04o}, has disallowed bits {:04o} (max {:04o})",
                            file_type, mode, excess_bits, max_mode
                        ),
                        format!("chmod {:04o} {}", max_mode, shell_quote_path(path)),
                    )
                }
            }
            Err(error)
                if matches!(
                    error.kind(),
                    std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
                ) =>
            {
                FilePermissionCheck::not_found(path.display().to_string(), max_mode)
            }
            Err(e) => FilePermissionCheck {
                path: path.display().to_string(),
                exists: true,
                current_mode: None,
                max_allowed_mode: max_mode,
                passed: false,
                issue: Some(format!("failed to read {} metadata: {}", file_type, e)),
                repair: None,
            },
        }
    }

    #[cfg(not(unix))]
    {
        match std::fs::symlink_metadata(path) {
            Ok(metadata) if metadata.file_type().is_file() => {
                FilePermissionCheck::pass(path.display().to_string(), 0, max_mode)
            }
            Ok(_) => FilePermissionCheck::fail_without_mode(
                path.display().to_string(),
                max_mode,
                format!("{file_type} is not a regular file"),
                format!(
                    "Replace {} with a regular file before re-running diagnostics.",
                    path.display()
                ),
            ),
            Err(error)
                if matches!(
                    error.kind(),
                    std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
                ) =>
            {
                FilePermissionCheck::not_found(path.display().to_string(), max_mode)
            }
            Err(e) => FilePermissionCheck {
                path: path.display().to_string(),
                exists: true,
                current_mode: None,
                max_allowed_mode: max_mode,
                passed: false,
                issue: Some(format!("failed to read {} metadata: {}", file_type, e)),
                repair: None,
            },
        }
    }
}

fn check_directory_permissions(path: &Path, max_mode: u32, dir_type: &str) -> FilePermissionCheck {
    let max_dir_mode = max_directory_permissions(max_mode);

    if let Some(check) = check_path_symlink_components(path, max_dir_mode, dir_type) {
        return check;
    }

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        match std::fs::symlink_metadata(path) {
            Ok(metadata) => {
                let mode = metadata.permissions().mode() & 0o777;
                if !metadata.file_type().is_dir() {
                    return FilePermissionCheck::fail(
                        path.display().to_string(),
                        mode,
                        max_dir_mode,
                        format!("{dir_type} is not a directory"),
                        format!(
                            "Replace {} with a directory before re-running diagnostics.",
                            path.display()
                        ),
                    );
                }
                let excess_bits = mode & !max_dir_mode;
                if excess_bits == 0 {
                    FilePermissionCheck::pass(path.display().to_string(), mode, max_dir_mode)
                } else {
                    FilePermissionCheck::fail(
                        path.display().to_string(),
                        mode,
                        max_dir_mode,
                        format!(
                            "{} has mode {:04o}, has disallowed bits {:04o} (max {:04o})",
                            dir_type, mode, excess_bits, max_dir_mode
                        ),
                        format!("chmod {:04o} {}", max_dir_mode, shell_quote_path(path)),
                    )
                }
            }
            Err(error)
                if matches!(
                    error.kind(),
                    std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
                ) =>
            {
                FilePermissionCheck::not_found(path.display().to_string(), max_dir_mode)
            }
            Err(e) => FilePermissionCheck {
                path: path.display().to_string(),
                exists: true,
                current_mode: None,
                max_allowed_mode: max_dir_mode,
                passed: false,
                issue: Some(format!("failed to read {} metadata: {}", dir_type, e)),
                repair: None,
            },
        }
    }

    #[cfg(not(unix))]
    {
        match std::fs::symlink_metadata(path) {
            Ok(metadata) if metadata.file_type().is_dir() => {
                FilePermissionCheck::pass(path.display().to_string(), 0, max_dir_mode)
            }
            Ok(_) => FilePermissionCheck::fail_without_mode(
                path.display().to_string(),
                max_dir_mode,
                format!("{dir_type} is not a directory"),
                format!(
                    "Replace {} with a directory before re-running diagnostics.",
                    path.display()
                ),
            ),
            Err(error)
                if matches!(
                    error.kind(),
                    std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
                ) =>
            {
                FilePermissionCheck::not_found(path.display().to_string(), max_dir_mode)
            }
            Err(e) => FilePermissionCheck {
                path: path.display().to_string(),
                exists: true,
                current_mode: None,
                max_allowed_mode: max_dir_mode,
                passed: false,
                issue: Some(format!("failed to read {} metadata: {}", dir_type, e)),
                repair: None,
            },
        }
    }
}

const fn max_directory_permissions(max_file_mode: u32) -> u32 {
    max_file_mode | ((max_file_mode & 0o444) >> 2)
}

fn optional_directory_should_be_checked(path: &Path) -> bool {
    match first_existing_symlink_component(path) {
        Ok(Some(_)) | Err(_) => true,
        Ok(None) => std::fs::symlink_metadata(path).is_ok(),
    }
}

#[cfg(unix)]
fn shell_quote_path(path: &Path) -> String {
    shell_quote(&path.to_string_lossy())
}

#[cfg(unix)]
fn shell_quote(value: &str) -> String {
    let mut quoted = String::with_capacity(value.len() + 2);
    quoted.push('\'');
    for ch in value.chars() {
        if ch == '\'' {
            quoted.push_str("'\\''");
        } else {
            quoted.push(ch);
        }
    }
    quoted.push('\'');
    quoted
}

fn check_path_symlink_components(
    path: &Path,
    max_mode: u32,
    path_type: &str,
) -> Option<FilePermissionCheck> {
    match first_existing_symlink_component(path) {
        Ok(Some(symlink_path)) => Some(FilePermissionCheck::fail_without_mode(
            path.display().to_string(),
            max_mode,
            format!(
                "{} path traverses symbolic link '{}' while checking '{}'",
                path_type,
                symlink_path.display(),
                path.display()
            ),
            "Replace the symlink with a real workspace path before re-running diagnostics.",
        )),
        Ok(None) => None,
        Err(error) => Some(FilePermissionCheck::fail_without_mode(
            path.display().to_string(),
            max_mode,
            format!(
                "failed to inspect {} path component '{}': {}",
                path_type,
                error.path.display(),
                error.source
            ),
            "Choose a readable workspace path or re-run with corrected permissions.",
        )),
    }
}

#[derive(Debug)]
struct SymlinkComponentInspectionError {
    path: PathBuf,
    source: std::io::Error,
}

fn first_existing_symlink_component(
    path: &Path,
) -> Result<Option<PathBuf>, SymlinkComponentInspectionError> {
    let mut current = PathBuf::new();
    for component in path.components() {
        current.push(component.as_os_str());
        if matches!(
            component,
            std::path::Component::Prefix(_) | std::path::Component::RootDir
        ) {
            continue;
        }
        match std::fs::symlink_metadata(&current) {
            Ok(metadata) if metadata.file_type().is_symlink() => return Ok(Some(current)),
            Ok(_) => {}
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                return Ok(None);
            }
            Err(source) if source.kind() == std::io::ErrorKind::NotADirectory => {
                return Err(SymlinkComponentInspectionError {
                    path: current,
                    source,
                });
            }
            Err(source) => {
                return Err(SymlinkComponentInspectionError {
                    path: current,
                    source,
                });
            }
        }
    }
    Ok(None)
}

/// Load security profile from environment or use default.
#[must_use]
pub fn load_profile_from_env() -> SecurityProfile {
    read(EnvVar::SecurityProfile)
        .and_then(|s| s.parse().ok())
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    #[cfg(unix)]
    use super::shell_quote_path;
    use super::{
        FilePermissionCheck, FilePermissionReport, SecurityProfile, check_workspace_permissions,
    };

    type TestResult = Result<(), String>;

    fn ensure<T: std::fmt::Debug + PartialEq>(actual: T, expected: T, ctx: &str) -> TestResult {
        if actual == expected {
            Ok(())
        } else {
            Err(format!("{ctx}: expected {expected:?}, got {actual:?}"))
        }
    }

    #[test]
    fn security_profile_round_trips_through_str() -> TestResult {
        for profile in SecurityProfile::all() {
            let s = profile.as_str();
            let parsed = SecurityProfile::from_str(s).map_err(|e| e.to_string())?;
            ensure(parsed, profile, &format!("round-trip {s}"))?;
        }
        Ok(())
    }

    #[test]
    fn security_profile_accepts_case_insensitive() -> TestResult {
        for (input, expected) in [
            ("DEFAULT", SecurityProfile::Default),
            ("Strict", SecurityProfile::Strict),
            ("PERMISSIVE", SecurityProfile::Permissive),
            (" strict ", SecurityProfile::Strict),
        ] {
            let parsed = SecurityProfile::from_str(input).map_err(|e| e.to_string())?;
            ensure(parsed, expected, input)?;
        }
        Ok(())
    }

    #[test]
    fn security_profile_rejects_unknown() {
        assert!(SecurityProfile::from_str("unknown").is_err());
        assert!(SecurityProfile::from_str("").is_err());
    }

    #[test]
    fn security_profile_default_is_default() -> TestResult {
        ensure(
            SecurityProfile::default(),
            SecurityProfile::Default,
            "default",
        )
    }

    #[test]
    fn strict_profile_has_lower_ceilings() -> TestResult {
        let default = SecurityProfile::Default;
        let strict = SecurityProfile::Strict;

        ensure(
            default.trust_ceiling() > strict.trust_ceiling(),
            true,
            "ceiling",
        )?;
        ensure(default.trust_floor() > strict.trust_floor(), true, "floor")
    }

    #[test]
    fn permissive_profile_keeps_redaction_but_relaxes_file_permissions() -> TestResult {
        let permissive = SecurityProfile::Permissive;

        ensure(permissive.enforce_redaction(), true, "redaction")?;
        ensure(permissive.enforce_file_permissions(), false, "file perms")
    }

    #[test]
    fn strict_profile_blocks_untrusted_imports() -> TestResult {
        ensure(
            SecurityProfile::Strict.allow_untrusted_imports(),
            false,
            "strict",
        )
    }

    #[test]
    fn file_permission_check_pass_records_mode() {
        let check = FilePermissionCheck::pass("/test/db", 0o600, 0o600);
        assert!(check.passed);
        assert!(check.exists);
        assert_eq!(check.current_mode, Some(0o600));
        assert!(check.issue.is_none());
    }

    #[test]
    fn file_permission_check_fail_records_issue() {
        let check =
            FilePermissionCheck::fail("/test/db", 0o644, 0o600, "too permissive", "chmod 600");
        assert!(!check.passed);
        assert!(check.issue.is_some());
        assert!(check.repair.is_some());
    }

    #[test]
    fn file_permission_check_not_found_passes() {
        let check = FilePermissionCheck::not_found("/nonexistent", 0o600);
        assert!(check.passed);
        assert!(!check.exists);
    }

    #[test]
    fn file_permission_report_counts_issues() {
        let checks = vec![
            FilePermissionCheck::pass("/a", 0o600, 0o600),
            FilePermissionCheck::fail("/b", 0o644, 0o600, "bad", "fix"),
            FilePermissionCheck::pass("/c", 0o600, 0o600),
        ];
        let report = FilePermissionReport::from_checks(SecurityProfile::Default, checks);

        assert!(!report.passed);
        assert_eq!(report.issue_count, 1);
        assert_eq!(report.checks.len(), 3);
    }

    #[test]
    fn file_permission_report_passes_when_no_issues() {
        let checks = vec![
            FilePermissionCheck::pass("/a", 0o600, 0o600),
            FilePermissionCheck::not_found("/b", 0o600),
        ];
        let report = FilePermissionReport::from_checks(SecurityProfile::Strict, checks);

        assert!(report.passed);
        assert_eq!(report.issue_count, 0);
    }

    #[test]
    fn workspace_permission_symlink_scan_accepts_canonical_absolute_roots() -> TestResult {
        let tempdir = tempfile::tempdir().map_err(|error| error.to_string())?;
        let base =
            std::fs::canonicalize(tempdir.path()).unwrap_or_else(|_| tempdir.path().to_path_buf());
        let db_path = base.join(".ee").join("ee.db");

        let symlink = super::first_existing_symlink_component(&db_path)
            .map_err(|error| format!("{}: {}", error.path.display(), error.source))?;

        ensure(
            symlink,
            None,
            "security profile path scan should skip structural root/prefix anchors",
        )
    }

    #[cfg(unix)]
    #[test]
    fn workspace_permission_report_fails_on_symlinked_ee_directory() -> TestResult {
        use std::os::unix::fs::symlink;

        let tempdir = tempfile::tempdir().map_err(|error| error.to_string())?;
        let workspace = tempdir.path().join("workspace");
        let linked_ee = tempdir.path().join("linked-ee");
        std::fs::create_dir(&workspace).map_err(|error| error.to_string())?;
        std::fs::create_dir(&linked_ee).map_err(|error| error.to_string())?;
        std::fs::write(linked_ee.join("ee.db"), b"db").map_err(|error| error.to_string())?;
        symlink(&linked_ee, workspace.join(".ee")).map_err(|error| error.to_string())?;

        let report = check_workspace_permissions(&workspace, SecurityProfile::Default);

        assert!(!report.passed);
        let db_check = report
            .checks
            .iter()
            .find(|check| check.path.ends_with(".ee/ee.db"))
            .ok_or_else(|| "database check missing".to_owned())?;
        assert!(!db_check.passed);
        assert_eq!(db_check.current_mode, None);
        assert!(
            db_check
                .issue
                .as_deref()
                .is_some_and(|issue| issue.contains("symbolic link"))
        );
        Ok(())
    }

    #[cfg(unix)]
    #[test]
    fn workspace_permission_report_fails_when_ee_path_is_regular_file() -> TestResult {
        let raw_temp_root = std::env::temp_dir();
        let temp_root = raw_temp_root.canonicalize().unwrap_or(raw_temp_root);
        let tempdir = tempfile::Builder::new()
            .prefix("ee-security-profile-")
            .tempdir_in(temp_root)
            .map_err(|error| error.to_string())?;
        let workspace = tempdir.path().join("workspace");
        std::fs::create_dir(&workspace).map_err(|error| error.to_string())?;
        std::fs::write(workspace.join(".ee"), b"not a directory")
            .map_err(|error| error.to_string())?;

        let report = check_workspace_permissions(&workspace, SecurityProfile::Default);

        assert!(!report.passed);
        let db_check = report
            .checks
            .iter()
            .find(|check| check.path.ends_with(".ee/ee.db"))
            .ok_or_else(|| "database check missing".to_owned())?;
        assert!(!db_check.passed);
        assert_eq!(db_check.current_mode, None);
        assert!(
            db_check
                .issue
                .as_deref()
                .is_some_and(|issue| issue.contains("failed to inspect database path component")),
            "regular .ee file must fail closed instead of passing as not found: {:?}",
            db_check.issue
        );
        Ok(())
    }

    #[cfg(unix)]
    #[test]
    fn workspace_permission_report_checks_symlinked_optional_index_dir() -> TestResult {
        use std::os::unix::fs::symlink;

        let tempdir = tempfile::tempdir().map_err(|error| error.to_string())?;
        let workspace = tempdir.path().join("workspace");
        let ee_dir = workspace.join(".ee");
        let linked_index = tempdir.path().join("linked-index");
        std::fs::create_dir(&workspace).map_err(|error| error.to_string())?;
        std::fs::create_dir(&ee_dir).map_err(|error| error.to_string())?;
        std::fs::create_dir(&linked_index).map_err(|error| error.to_string())?;
        symlink(&linked_index, ee_dir.join("index")).map_err(|error| error.to_string())?;

        let report = check_workspace_permissions(&workspace, SecurityProfile::Default);

        assert!(!report.passed);
        let index_check = report
            .checks
            .iter()
            .find(|check| check.path.ends_with(".ee/index"))
            .ok_or_else(|| "index directory check missing".to_owned())?;
        assert!(!index_check.passed);
        assert_eq!(index_check.current_mode, None);
        assert!(
            index_check
                .issue
                .as_deref()
                .is_some_and(|issue| issue.contains("symbolic link"))
        );
        Ok(())
    }

    #[cfg(unix)]
    #[test]
    fn workspace_permission_report_fails_on_config_directory() -> TestResult {
        use std::os::unix::fs::PermissionsExt;

        let tempdir = tempfile::tempdir().map_err(|error| error.to_string())?;
        let workspace = tempdir.path().join("workspace");
        let ee_dir = workspace.join(".ee");
        let config_dir = ee_dir.join("config.toml");
        std::fs::create_dir(&workspace).map_err(|error| error.to_string())?;
        std::fs::create_dir(&ee_dir).map_err(|error| error.to_string())?;
        std::fs::create_dir(&config_dir).map_err(|error| error.to_string())?;
        std::fs::set_permissions(&config_dir, std::fs::Permissions::from_mode(0o644))
            .map_err(|error| error.to_string())?;

        let report = check_workspace_permissions(&workspace, SecurityProfile::Default);

        std::fs::set_permissions(&config_dir, std::fs::Permissions::from_mode(0o755))
            .map_err(|error| error.to_string())?;
        assert!(!report.passed);
        let config_check = report
            .checks
            .iter()
            .find(|check| check.path.ends_with(".ee/config.toml"))
            .ok_or_else(|| "config check missing".to_owned())?;
        assert!(!config_check.passed);
        assert!(
            config_check
                .issue
                .as_deref()
                .is_some_and(|issue| issue.contains("not a regular file"))
        );
        Ok(())
    }

    #[cfg(unix)]
    #[test]
    fn workspace_permission_report_fails_on_index_regular_file() -> TestResult {
        use std::os::unix::fs::PermissionsExt;

        let tempdir = tempfile::tempdir().map_err(|error| error.to_string())?;
        let workspace = tempdir.path().join("workspace");
        let ee_dir = workspace.join(".ee");
        let index_file = ee_dir.join("index");
        std::fs::create_dir(&workspace).map_err(|error| error.to_string())?;
        std::fs::create_dir(&ee_dir).map_err(|error| error.to_string())?;
        std::fs::write(&index_file, b"not a directory").map_err(|error| error.to_string())?;
        std::fs::set_permissions(&index_file, std::fs::Permissions::from_mode(0o600))
            .map_err(|error| error.to_string())?;

        let report = check_workspace_permissions(&workspace, SecurityProfile::Default);

        assert!(!report.passed);
        let index_check = report
            .checks
            .iter()
            .find(|check| check.path.ends_with(".ee/index"))
            .ok_or_else(|| "index directory check missing".to_owned())?;
        assert!(!index_check.passed);
        assert!(
            index_check
                .issue
                .as_deref()
                .is_some_and(|issue| issue.contains("not a directory"))
        );
        Ok(())
    }

    #[cfg(unix)]
    #[test]
    fn workspace_permission_report_rejects_world_traversable_index_directory() -> TestResult {
        use std::os::unix::fs::PermissionsExt;

        let tempdir = tempfile::tempdir().map_err(|error| error.to_string())?;
        let workspace = tempdir.path().join("workspace");
        let ee_dir = workspace.join(".ee");
        let index_dir = ee_dir.join("index");
        std::fs::create_dir(&workspace).map_err(|error| error.to_string())?;
        std::fs::create_dir(&ee_dir).map_err(|error| error.to_string())?;
        std::fs::create_dir(&index_dir).map_err(|error| error.to_string())?;
        std::fs::set_permissions(&index_dir, std::fs::Permissions::from_mode(0o711))
            .map_err(|error| error.to_string())?;

        let report = check_workspace_permissions(&workspace, SecurityProfile::Default);

        assert!(!report.passed);
        let index_check = report
            .checks
            .iter()
            .find(|check| check.path.ends_with(".ee/index"))
            .ok_or_else(|| "index directory check missing".to_owned())?;
        assert!(!index_check.passed);
        assert_eq!(index_check.current_mode, Some(0o711));
        assert_eq!(index_check.max_allowed_mode, 0o700);
        assert!(
            index_check
                .issue
                .as_deref()
                .is_some_and(|issue| issue.contains("disallowed bits 0011"))
        );

        std::fs::set_permissions(&index_dir, std::fs::Permissions::from_mode(0o700))
            .map_err(|error| error.to_string())?;
        let repaired_report = check_workspace_permissions(&workspace, SecurityProfile::Default);

        assert!(repaired_report.passed);
        Ok(())
    }

    #[cfg(unix)]
    #[test]
    fn workspace_permission_repair_quotes_shell_sensitive_paths() -> TestResult {
        use std::os::unix::fs::PermissionsExt;

        let tempdir = tempfile::tempdir().map_err(|error| error.to_string())?;
        let workspace = tempdir.path().join("workspace with ' quote");
        let ee_dir = workspace.join(".ee");
        let db_path = ee_dir.join("ee.db");
        std::fs::create_dir(&workspace).map_err(|error| error.to_string())?;
        std::fs::create_dir(&ee_dir).map_err(|error| error.to_string())?;
        std::fs::write(&db_path, b"db").map_err(|error| error.to_string())?;
        std::fs::set_permissions(&db_path, std::fs::Permissions::from_mode(0o644))
            .map_err(|error| error.to_string())?;

        let report = check_workspace_permissions(&workspace, SecurityProfile::Default);
        let db_check = report
            .checks
            .iter()
            .find(|check| check.path.ends_with(".ee/ee.db"))
            .ok_or_else(|| "database check missing".to_owned())?;

        assert!(!db_check.passed);
        let expected_repair = format!("chmod 0600 {}", shell_quote_path(&db_path));
        assert_eq!(db_check.repair.as_deref(), Some(expected_repair.as_str()));
        assert!(
            db_check
                .repair
                .as_deref()
                .is_some_and(|repair| repair.contains("'\\''")),
            "repair command must escape embedded single quotes: {:?}",
            db_check.repair
        );
        Ok(())
    }

    #[cfg(unix)]
    #[test]
    fn strict_workspace_permission_report_rejects_default_readable_config() -> TestResult {
        use std::os::unix::fs::PermissionsExt;

        let tempdir = tempfile::tempdir().map_err(|error| error.to_string())?;
        let workspace = tempdir.path().join("workspace");
        let ee_dir = workspace.join(".ee");
        let db_path = ee_dir.join("ee.db");
        let config_path = ee_dir.join("config.toml");
        std::fs::create_dir(&workspace).map_err(|error| error.to_string())?;
        std::fs::create_dir(&ee_dir).map_err(|error| error.to_string())?;
        std::fs::write(&db_path, b"db").map_err(|error| error.to_string())?;
        std::fs::write(&config_path, b"config").map_err(|error| error.to_string())?;
        std::fs::set_permissions(&db_path, std::fs::Permissions::from_mode(0o600))
            .map_err(|error| error.to_string())?;
        std::fs::set_permissions(&config_path, std::fs::Permissions::from_mode(0o644))
            .map_err(|error| error.to_string())?;

        let default_report = check_workspace_permissions(&workspace, SecurityProfile::Default);
        let strict_report = check_workspace_permissions(&workspace, SecurityProfile::Strict);

        assert!(default_report.passed);
        assert!(!strict_report.passed);
        assert_eq!(strict_report.issue_count, 1);
        let config_check = strict_report
            .checks
            .iter()
            .find(|check| check.path.ends_with(".ee/config.toml"))
            .ok_or_else(|| "config check missing".to_owned())?;
        assert!(!config_check.passed);
        assert_eq!(config_check.current_mode, Some(0o644));
        assert_eq!(config_check.max_allowed_mode, 0o600);
        assert!(
            config_check
                .issue
                .as_deref()
                .is_some_and(|issue| issue.contains("disallowed bits 0044")),
            "strict config diagnostic should name the group/other read bits: {:?}",
            config_check.issue
        );
        let expected_repair = format!("chmod 0600 {}", shell_quote_path(&config_path));
        assert_eq!(
            config_check.repair.as_deref(),
            Some(expected_repair.as_str())
        );

        std::fs::set_permissions(&config_path, std::fs::Permissions::from_mode(0o600))
            .map_err(|error| error.to_string())?;
        let repaired_report = check_workspace_permissions(&workspace, SecurityProfile::Strict);
        assert!(repaired_report.passed);
        Ok(())
    }

    #[cfg(unix)]
    #[test]
    fn permissive_workspace_permission_report_relaxes_mode_bits() -> TestResult {
        use std::os::unix::fs::PermissionsExt;

        let tempdir = tempfile::tempdir().map_err(|error| error.to_string())?;
        let workspace = tempdir.path().join("workspace");
        let ee_dir = workspace.join(".ee");
        let db_path = ee_dir.join("ee.db");
        let config_path = ee_dir.join("config.toml");
        let index_dir = ee_dir.join("index");
        std::fs::create_dir(&workspace).map_err(|error| error.to_string())?;
        std::fs::create_dir(&ee_dir).map_err(|error| error.to_string())?;
        std::fs::create_dir(&index_dir).map_err(|error| error.to_string())?;
        std::fs::write(&db_path, b"db").map_err(|error| error.to_string())?;
        std::fs::write(&config_path, b"config").map_err(|error| error.to_string())?;
        std::fs::set_permissions(&db_path, std::fs::Permissions::from_mode(0o777))
            .map_err(|error| error.to_string())?;
        std::fs::set_permissions(&config_path, std::fs::Permissions::from_mode(0o666))
            .map_err(|error| error.to_string())?;
        std::fs::set_permissions(&index_dir, std::fs::Permissions::from_mode(0o777))
            .map_err(|error| error.to_string())?;

        let default_report = check_workspace_permissions(&workspace, SecurityProfile::Default);
        let permissive_report =
            check_workspace_permissions(&workspace, SecurityProfile::Permissive);

        assert!(!default_report.passed);
        assert!(permissive_report.passed);
        assert_eq!(permissive_report.issue_count, 0);
        Ok(())
    }
}