lean-ctx-engine 3.12.3

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
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
// SPDX-License-Identifier: Apache-2.0
use super::*;

#[cfg(not(feature = "no-jail"))]
#[test]
fn rejects_path_outside_root() {
    // Hermetic config (empty data dir => jail on) so a parallel test that
    // flips `path_jail` cannot leak into this enforcement check. The guard
    // holds the global test_env_lock, which also serializes against every
    // `LEAN_CTX_ALLOW_PATH` mutation (all of them go through that lock).
    let _iso = crate::core::data_dir::isolated_data_dir();
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("root");
    let other = tmp.path().join("other");
    std::fs::create_dir_all(&root).unwrap();
    std::fs::create_dir_all(&other).unwrap();
    std::fs::write(root.join("a.txt"), "ok").unwrap();
    std::fs::write(other.join("b.txt"), "no").unwrap();

    let ok = jail_path(&root.join("a.txt"), &root);
    assert!(ok.is_ok());

    let bad = jail_path(&other.join("b.txt"), &root);
    assert!(bad.is_err());
}

/// #475: a configured read-only root is readable but never writable. Reads
/// resolve (the root joins the allow-list like an extra_root), while the
/// single write choke point `enforce_writable` default-denies every write
/// inside it — including a not-yet-existing file, which inherits the
/// directory's read-only status. `isolated_data_dir` holds `test_env_lock`,
/// serialising the `LEAN_CTX_READ_ONLY_ROOTS` mutation against other tests.
#[cfg(not(feature = "no-jail"))]
#[test]
fn read_only_roots_deny_writes_but_allow_reads() {
    // `isolated_data_dir` already holds `test_env_lock` for its lifetime —
    // taking it again here would self-deadlock on a non-reentrant Mutex.
    let _iso = crate::core::data_dir::isolated_data_dir();

    let tmp = tempfile::tempdir().unwrap();
    let project = tmp.path().join("project");
    let refrepo = tmp.path().join("refrepo");
    std::fs::create_dir_all(&project).unwrap();
    std::fs::create_dir_all(refrepo.join("sub")).unwrap();
    std::fs::write(refrepo.join("lib.rs"), "pub fn x() {}\n").unwrap();

    // Canonicalize the configured root the same (symlink-resolving) way the
    // guard does, so macOS /var → /private/var can't defeat the prefix match.
    let ro_canon = canonicalize_secure(&refrepo);
    crate::test_env::set_var(
        "LEAN_CTX_READ_ONLY_ROOTS",
        ro_canon.to_string_lossy().as_ref(),
    );

    let existing = refrepo.join("lib.rs");
    let new_file = refrepo.join("sub").join("new.rs");
    let proj_file = project.join("main.rs");

    // Capture every decision while the env is live (it is cleared below).
    let read_existing = jail_path(&existing, &project);
    let deny_existing = enforce_writable(&existing);
    let deny_new = enforce_writable(&new_file);
    let allow_project = enforce_writable(&proj_file);
    let ro_existing = is_read_only_path(&existing);
    let ro_project = is_read_only_path(&proj_file);

    crate::test_env::remove_var("LEAN_CTX_READ_ONLY_ROOTS");

    assert!(
        deny_existing.is_err(),
        "write to an existing file in a read-only root must be denied"
    );
    assert!(
        deny_new.is_err(),
        "creating a new file in a read-only root must be denied"
    );
    assert!(
        allow_project.is_ok(),
        "writes into the project root must stay allowed: {allow_project:?}"
    );
    assert!(
        read_existing.is_ok(),
        "reads inside a read-only root must resolve (read allow-list): {read_existing:?}"
    );
    assert!(ro_existing, "the file is inside the read-only root");
    assert!(!ro_project, "the project file is not read-only");
}

/// #406 regression: a long-lived process (the MCP server) must honor
/// `path_jail = false` written to config after startup. The config cache is
/// now keyed on content, so even an edit that preserves the file mtime takes
/// effect — a path outside the jail root is accepted once the flag flips.
/// (With the former mtime-only cache the stale `None` kept the jail on.)
#[cfg(not(feature = "no-jail"))]
#[test]
fn honors_path_jail_false_after_mtime_preserving_edit() {
    let _iso = crate::core::data_dir::isolated_data_dir();
    let cfg_path = crate::core::config::Config::path().unwrap();
    if let Some(parent) = cfg_path.parent() {
        std::fs::create_dir_all(parent).unwrap();
    }

    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("project");
    let outside = tmp.path().join("outside");
    std::fs::create_dir_all(&root).unwrap();
    std::fs::create_dir_all(&outside).unwrap();
    let secret = outside.join("secret.txt");
    std::fs::write(&secret, "x").unwrap();

    // Warm the config cache with the jail on (no path_jail key).
    std::fs::write(&cfg_path, "# jail on\n").unwrap();
    let mtime0 = std::fs::metadata(&cfg_path).unwrap().modified().unwrap();
    assert_eq!(crate::core::config::Config::load().path_jail, None);

    // Flip path_jail=false but restore the original mtime, so any mtime-only
    // cache would keep serving the stale jail-on value.
    std::fs::write(&cfg_path, "path_jail = false\n").unwrap();
    filetime::set_file_mtime(&cfg_path, filetime::FileTime::from_system_time(mtime0)).unwrap();

    assert!(
        jail_path(&secret, &root).is_ok(),
        "path_jail=false must take effect without a fresh process (#406)"
    );
}

#[test]
fn allows_nonexistent_child_under_root() {
    // jail_path reads the protected-session env, which the macOS
    // protected_store tests set process-wide under this lock.
    let _env = crate::core::data_dir::test_env_lock();
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("root");
    std::fs::create_dir_all(&root).unwrap();
    std::fs::write(root.join("a.txt"), "ok").unwrap();

    let p = root.join("new").join("file.txt");
    let ok = jail_path(&p, &root).unwrap();
    assert!(ok.to_string_lossy().contains("file.txt"));
}

#[cfg(not(feature = "no-jail"))]
#[test]
fn relative_candidate_resolves_against_root_not_cwd() {
    // Regression: in the daemon (CWD != project) a relative graph path like
    // `sub/file.rs` must resolve under the jail root, not the process CWD.
    let _iso = crate::core::data_dir::isolated_data_dir();
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("project");
    std::fs::create_dir_all(root.join("sub")).unwrap();
    std::fs::write(root.join("sub").join("file.rs"), "ok").unwrap();

    let jailed = jail_path(Path::new("sub/file.rs"), &root)
        .expect("relative candidate should resolve under the jail root");
    assert!(jailed.ends_with("sub/file.rs"));
    assert!(
        is_under_prefix(&canonicalize_or_self(&jailed), &canonicalize_or_self(&root)),
        "resolved path must live under the jail root: {jailed:?}"
    );
}

/// The same with the jail off: `path_jail = false` (or the `no-jail` build)
/// returned the relative path as given, so callers opened it against the
/// process CWD.
#[test]
fn relative_candidate_resolves_against_root_with_the_jail_off() {
    let _iso = crate::core::data_dir::isolated_data_dir();
    let cfg_path = crate::core::config::Config::path().unwrap();
    std::fs::create_dir_all(cfg_path.parent().unwrap()).unwrap();
    std::fs::write(&cfg_path, "path_jail = false\n").unwrap();
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("project");
    std::fs::create_dir_all(root.join("sub")).unwrap();
    std::fs::write(root.join("sub").join("file.rs"), "ok").unwrap();

    let resolved = jail_path(Path::new("sub/file.rs"), &root).unwrap();

    assert_eq!(
        resolved,
        canonicalize_or_self(&root.join("sub").join("file.rs"))
    );
}

#[test]
fn ide_allow_dirs_are_registry_derived_and_skip_home() {
    use crate::core::editor_registry::{ConfigType, EditorTarget};

    let home = tempfile::tempdir().unwrap();
    let h = home.path();
    // VS Code keeps its config outside a dotfile dir — the old hard-coded
    // list missed this entirely.
    std::fs::create_dir_all(h.join("Library/Application Support/Code/User")).unwrap();
    std::fs::create_dir_all(h.join(".cursor")).unwrap();

    let targets = vec![
        EditorTarget {
            name: "VS Code",
            agent_key: "vscode".into(),
            config_path: h.join("Library/Application Support/Code/User/mcp.json"),
            detect_path: h.join("Library/Application Support/Code"),
            config_type: ConfigType::VsCodeMcp,
        },
        EditorTarget {
            name: "Cursor",
            agent_key: "cursor".into(),
            config_path: h.join(".cursor/mcp.json"),
            detect_path: h.join(".cursor"),
            config_type: ConfigType::McpJson,
        },
        // A $HOME-level config file: its parent is $HOME and must be skipped.
        EditorTarget {
            name: "Claude Code",
            agent_key: "claude".into(),
            config_path: h.join(".claude.json"),
            detect_path: h.join(".no-such-dir"),
            config_type: ConfigType::McpJson,
        },
    ];

    let mut out = Vec::new();
    collect_ide_allow_dirs(h, &targets, &mut out);

    assert!(
        out.iter().any(|p| p.ends_with("Code/User")),
        "non-dotfile VS Code dir must be covered: {out:?}"
    );
    assert!(out.iter().any(|p| p.ends_with(".cursor")), "{out:?}");
    let home_canon = canonicalize_secure(h);
    assert!(
        !out.contains(&home_canon),
        "must never widen the jail to $HOME: {out:?}"
    );
}

// P0-10 (#422): foreign editor config dirs are opt-in. lean-ctx's own state
// dir is added by the caller via the data_dir root, NOT by `home_allow_dirs`,
// so the default home allow-list is empty and `~/.lean-ctx` (not an editor)
// never appears here.
#[test]
fn ide_config_dirs_are_excluded_by_default() {
    let home = tempfile::tempdir().unwrap();
    for d in [".lean-ctx", ".cursor", ".codex"] {
        std::fs::create_dir_all(home.path().join(d)).unwrap();
    }

    let denied = home_allow_dirs(home.path(), false);
    assert!(
        denied.is_empty(),
        "foreign editor dirs must stay jailed by default: {denied:?}"
    );

    // Opt-in exposes the editor dirs that actually exist under this home.
    // Entries are registry-derived (foreign real-$HOME paths are filtered out
    // by the in-home guard), so the result stays hermetic — and `~/.lean-ctx`
    // is never added here because it is not an editor.
    let allowed = home_allow_dirs(home.path(), true);
    assert!(
        allowed.iter().any(|p| p.ends_with(".cursor")),
        "opt-in must expose editor dirs: {allowed:?}"
    );
    assert!(
        !allowed.iter().any(|p| p.ends_with(".lean-ctx")),
        "lean-ctx's own dir is covered by the data_dir root, not home_allow_dirs: {allowed:?}"
    );
}

#[test]
fn canonicalize_or_self_strips_verbatim() {
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path().join("project");
    std::fs::create_dir_all(&dir).unwrap();

    let result = canonicalize_or_self(&dir);
    let s = result.to_string_lossy();
    assert!(
        !s.starts_with(r"\\?\"),
        "canonicalize_or_self should strip verbatim prefix, got: {s}"
    );
}

#[test]
fn jail_path_accepts_same_dir_different_format() {
    let _env = crate::core::data_dir::test_env_lock();
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("project");
    std::fs::create_dir_all(&root).unwrap();
    std::fs::write(root.join("file.rs"), "ok").unwrap();

    let result = jail_path(&root.join("file.rs"), &root);
    assert!(result.is_ok(), "same dir should be accepted: {result:?}");
}

#[cfg(not(feature = "no-jail"))]
#[test]
fn error_message_contains_escape_info() {
    // isolated_data_dir holds the global test_env_lock, serializing this
    // against any parallel `LEAN_CTX_ALLOW_PATH="/"` mutation.
    let _iso = crate::core::data_dir::isolated_data_dir();
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("root");
    let other = tmp.path().join("other");
    std::fs::create_dir_all(&root).unwrap();
    std::fs::create_dir_all(&other).unwrap();
    std::fs::write(other.join("b.txt"), "no").unwrap();

    let err = jail_path(&other.join("b.txt"), &root).unwrap_err();
    assert!(
        err.to_string().contains("path escapes project root"),
        "error should mention escape: {err}"
    );
}

// GH #887: over MCP (meta hints gated off) the rejection was bare, so
// agents shelled out to work around the jail instead of widening it via
// config. The agent-visible error must name the sanctioned config keys.
#[cfg(not(feature = "no-jail"))]
#[test]
fn escape_error_names_config_keys_without_meta() {
    let _iso = crate::core::data_dir::isolated_data_dir();
    crate::test_env::remove_var("LEAN_CTX_META");
    crate::test_env::remove_var("LEAN_CTX_DIAGNOSTICS");
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("root");
    let other = tmp.path().join("other");
    std::fs::create_dir_all(&root).unwrap();
    std::fs::create_dir_all(&other).unwrap();
    std::fs::write(other.join("b.txt"), "no").unwrap();

    let err = jail_path(&other.join("b.txt"), &root).unwrap_err();
    let msg = err.to_string();
    // One command that resolves it without a restart — never "open a new
    // IDE window" or an env var the running server cannot see.
    assert!(
        msg.contains("lean-ctx allow-path") && msg.contains("no restart"),
        "agent-visible escape error should hint at resolution: {msg}"
    );
    assert!(msg.contains("do not retry"), "{msg}");
    assert!(!msg.contains("LEAN_CTX_EXTRA_ROOTS="), "{msg}");
}

// GH #392: config entries like "$HOME/code" or "~/code" were taken
// literally and never matched.
#[test]
fn expand_user_path_expands_tilde_and_vars() {
    let _env_lock = crate::core::data_dir::test_env_lock();
    let home = dirs::home_dir().expect("home dir");
    // `$HOME` is the variable when it is set — on Windows `dirs::home_dir`
    // ignores it (the profile folder), so the two can differ there; the
    // profile folder only stands in for an unset `$HOME`.
    let env_home = std::env::var_os("HOME").map_or_else(|| home.clone(), PathBuf::from);
    let env_home_s = env_home.to_string_lossy().to_string();

    assert_eq!(expand_user_path("~"), home);
    assert_eq!(expand_user_path("~/code"), home.join("code"));
    assert_eq!(expand_user_path("$HOME/code"), env_home.join("code"));
    assert_eq!(expand_user_path("${HOME}/code"), env_home.join("code"));
    // Multiple variables in one entry.
    crate::test_env::set_var("LEAN_CTX_TEST_SUB", "sub");
    assert_eq!(
        expand_user_path("$HOME/$LEAN_CTX_TEST_SUB/x"),
        PathBuf::from(format!("{env_home_s}/sub/x"))
    );
    crate::test_env::remove_var("LEAN_CTX_TEST_SUB");
    // Absolute paths pass through untouched.
    assert_eq!(expand_user_path("/etc"), PathBuf::from("/etc"));
}

#[cfg(windows)]
#[test]
fn expand_user_path_home_falls_back_when_env_is_unset() {
    let _env_lock = crate::core::data_dir::test_env_lock();
    let expected_home = dirs::home_dir().expect("home dir");
    let previous_home = std::env::var_os("HOME");

    struct RestoreHome(Option<std::ffi::OsString>);

    impl Drop for RestoreHome {
        fn drop(&mut self) {
            match self.0.take() {
                Some(value) => crate::test_env::set_var("HOME", value),
                None => crate::test_env::remove_var("HOME"),
            }
        }
    }

    let _restore_home = RestoreHome(previous_home);
    crate::test_env::remove_var("HOME");

    assert_eq!(std::env::var_os("HOME"), None);
    assert_eq!(expand_user_path("$HOME/code"), expected_home.join("code"));
    assert_eq!(expand_user_path("${HOME}/code"), expected_home.join("code"));
}

#[test]
fn expand_user_path_leaves_unset_vars_verbatim() {
    let _env_lock = crate::core::data_dir::test_env_lock();
    crate::test_env::remove_var("LEAN_CTX_TEST_UNSET_VAR");
    let p = expand_user_path("$LEAN_CTX_TEST_UNSET_VAR/code");
    assert_eq!(p, PathBuf::from("$LEAN_CTX_TEST_UNSET_VAR/code"));
}

// GH #392: `allow_paths = ["/"]` (via the same env-var channel) must grant
// access to any absolute path — "/" is a prefix of everything.
//
// Env-mutating tests here hold the process-global
// `data_dir::test_env_lock()` (directly, or via `isolated_data_dir()`
// which wraps it) — NOT a module-local mutex. test_env's SAFETY contract
// says *all* test env mutation serializes through that one lock; a local
// lock only serializes this module against itself, so e.g.
// `artifacts::external_corpus_requires_allow_list` (which holds the
// global lock) could observe this test's `LEAN_CTX_ALLOW_PATH="/"` and
// fail its jail-rejection assert (the pre-existing parallel-run flake
// reported in #695).
#[cfg(unix)]
#[test]
fn allow_path_root_slash_permits_everything() {
    let _guard = crate::core::data_dir::test_env_lock();
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("root");
    let other = tmp.path().join("other");
    std::fs::create_dir_all(&root).unwrap();
    std::fs::create_dir_all(&other).unwrap();
    std::fs::write(other.join("b.txt"), "allowed").unwrap();

    crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", "/");
    let result = jail_path(&other.join("b.txt"), &root);
    crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");

    assert!(result.is_ok(), "allow path '/' must permit all: {result:?}");
}

// Finding 3 (GH security audit): env-channel jail relaxations must be
// detectable so startup + doctor can surface them loudly.
#[test]
fn active_relaxations_detects_allow_path_env() {
    let _iso = crate::core::data_dir::isolated_data_dir();
    crate::test_env::remove_var("LEAN_CTX_EXTRA_ROOTS");
    crate::test_env::remove_var("LEAN_CTX_ALLOW_IDE_DIRS");
    crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", "/tmp");

    let relaxed = active_relaxations();

    crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");

    assert!(
        relaxed.iter().any(|r| r.source == "LEAN_CTX_ALLOW_PATH"),
        "LEAN_CTX_ALLOW_PATH must be reported as a jail relaxation: {relaxed:?}"
    );
}

#[cfg(not(feature = "no-jail"))]
#[test]
fn active_relaxations_empty_when_jail_intact() {
    let _iso = crate::core::data_dir::isolated_data_dir();
    for var in [
        "LEAN_CTX_ALLOW_PATH",
        "LCTX_ALLOW_PATH",
        "LEAN_CTX_EXTRA_ROOTS",
        "LEAN_CTX_ALLOW_IDE_DIRS",
        "LEAN_CTX_PATH_JAIL_SCOPE",
    ] {
        crate::test_env::remove_var(var);
    }

    assert!(
        active_relaxations().is_empty(),
        "an intact jail (clean config, no relaxation env) must report no relaxations: {:?}",
        active_relaxations()
    );
}

#[test]
fn allow_path_env_permits_outside_root() {
    let _guard = crate::core::data_dir::test_env_lock();
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("root");
    let other = tmp.path().join("other");
    std::fs::create_dir_all(&root).unwrap();
    std::fs::create_dir_all(&other).unwrap();
    std::fs::write(other.join("b.txt"), "allowed").unwrap();

    let canon = canonicalize_or_self(&other);
    crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", canon.to_string_lossy().as_ref());
    let result = jail_path(&other.join("b.txt"), &root);
    crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");

    assert!(
        result.is_ok(),
        "LEAN_CTX_ALLOW_PATH should permit access: {result:?}"
    );
}

#[cfg(all(unix, not(feature = "no-jail")))]
#[test]
fn rejects_symlink_escape_on_unix() {
    use std::os::unix::fs::symlink;

    // isolated_data_dir holds the global test_env_lock — no parallel test
    // can set `LEAN_CTX_ALLOW_PATH="/"` and let this escape resolve.
    let _iso = crate::core::data_dir::isolated_data_dir();
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("root");
    let other = tmp.path().join("other");
    std::fs::create_dir_all(&root).unwrap();
    std::fs::create_dir_all(&other).unwrap();
    std::fs::write(other.join("secret.txt"), "no").unwrap();

    let link = root.join("link.txt");
    symlink(other.join("secret.txt"), &link).unwrap();

    let bad = jail_path(&link, &root);
    assert!(bad.is_err(), "symlink escape must be rejected: {bad:?}");
}

#[test]
fn rejects_null_byte_in_path() {
    let _env = crate::core::data_dir::test_env_lock();
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("root");
    std::fs::create_dir_all(&root).unwrap();

    let bad_path = PathBuf::from("file\0.txt");
    let result = jail_path(&bad_path, &root);
    assert!(result.is_err(), "null byte in path must be rejected");
    assert!(
        result.unwrap_err().to_string().contains("null byte"),
        "error must mention null byte"
    );
}

/// #403 Bug 1: an explicit path under a session-scoped `extra_root` (e.g. a
/// sibling git worktree from MCP `roots/list`) must resolve, while the same
/// path is rejected without it — and a path under *no* root is rejected even
/// when extra roots are present. Holds both env locks so neither a parallel
/// `path_jail` flip nor a `LEAN_CTX_ALLOW_PATH` mutation can leak in.
#[cfg(not(feature = "no-jail"))]
#[test]
fn extra_roots_permit_paths_outside_jail() {
    let _iso = crate::core::data_dir::isolated_data_dir();

    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("project");
    let worktree = tmp.path().join("worktree");
    let elsewhere = tmp.path().join("elsewhere");
    for d in [&root, &worktree, &elsewhere] {
        std::fs::create_dir_all(d).unwrap();
    }
    let in_worktree = worktree.join("a.txt");
    std::fs::write(&in_worktree, "x").unwrap();
    let outside = elsewhere.join("b.txt");
    std::fs::write(&outside, "y").unwrap();

    // Parity: with no extra roots, the worktree path escapes the jail.
    assert!(jail_path(&in_worktree, &root).is_err());
    assert!(jail_path_with_roots(&in_worktree, &root, &[]).is_err());

    // The session-scoped extra root permits it — via the slice alone, with
    // nothing in env/config.
    let extra = vec![worktree.to_string_lossy().to_string()];
    assert!(
        jail_path_with_roots(&in_worktree, &root, &extra).is_ok(),
        "path under a session extra_root must resolve (#403)"
    );

    // A path under neither the jail nor any extra root is still rejected.
    assert!(
        jail_path_with_roots(&outside, &root, &extra).is_err(),
        "paths outside ALL roots must still be rejected"
    );

    // Empty entries are ignored (no accidental allow-all).
    assert!(jail_path_with_roots(&outside, &root, &[String::new()]).is_err());
}

/// GH #1228: Claude Code auto-memory under `…/.claude/projects/<slug>/memory/`
/// must be readable/writable via ctx_* without a manual extra_roots edit.
#[cfg(not(feature = "no-jail"))]
#[test]
fn harness_auto_memory_path_is_allowed_without_extra_roots() {
    let _iso = crate::core::data_dir::isolated_data_dir();
    let tmp = tempfile::tempdir().unwrap();
    let old_home = std::env::var_os("HOME");
    crate::test_env::set_var("HOME", tmp.path());
    crate::test_env::remove_var("CLAUDE_CONFIG_DIR");
    let root = tmp.path().join("project");
    let memory = tmp
        .path()
        .join(".claude")
        .join("projects")
        .join("-tmp-project")
        .join("memory");
    std::fs::create_dir_all(&root).unwrap();
    std::fs::create_dir_all(&memory).unwrap();
    let mem_file = memory.join("MEMORY.md");
    std::fs::write(&mem_file, "# index\n").unwrap();

    assert!(is_harness_auto_memory_path(&mem_file));
    assert!(is_harness_auto_memory_path(&memory));
    assert!(!is_harness_auto_memory_path(
        &tmp.path()
            .join(".claude")
            .join("projects")
            .join("-tmp-project")
            .join("session.jsonl")
    ));

    assert!(
        jail_path_with_roots(&mem_file, &root, &[]).is_ok(),
        "auto-memory file must pass PathJail without extra_roots"
    );

    // A look-alike `.claude/projects/<slug>/memory` outside the harness home
    // (a cloned repo, /tmp) is an ordinary path, not auto memory.
    let elsewhere = tempfile::tempdir().unwrap();
    let fake = elsewhere
        .path()
        .join(".claude/projects/-x/memory/MEMORY.md");
    std::fs::create_dir_all(fake.parent().unwrap()).unwrap();
    std::fs::write(&fake, "x").unwrap();
    assert!(!is_harness_auto_memory_path(&fake));
    assert!(
        jail_path_with_roots(&fake, &root, &[]).is_err(),
        "look-alike memory dir outside ~ must stay jailed"
    );
    assert!(!is_harness_auto_memory_path(
        &memory.join("../../../../.ssh/id_ed25519")
    ));

    match old_home {
        Some(h) => crate::test_env::set_var("HOME", h),
        None => crate::test_env::remove_var("HOME"),
    }
}

/// #820: lean-ctx state dir (tee files) is implicitly allowed by the jail.
#[test]
fn state_dir_tee_files_pass_jail() {
    let _lock = crate::core::data_dir::test_env_lock();
    let state = crate::core::paths::state_dir().expect("state_dir must be available");
    let tee_path = state.join("tee").join("some_command_deadbeef.log");
    // Use a root that is clearly NOT the state dir's parent
    let fake_root = std::env::temp_dir().join("pathjail_test_820_root");
    std::fs::create_dir_all(&fake_root).ok();
    // The tee path is outside the fake root, but the state dir allowance
    // should make it pass (the state dir itself exists on disk).
    let result = jail_path_with_roots(&tee_path, &fake_root, &[]);
    // If state_dir exists on disk (it does in dev), the path should be allowed.
    // If the tee file itself doesn't exist, canonicalize_existing_ancestor
    // resolves to the state_dir (which does exist) + remainder.
    if state.exists() {
        assert!(
            result.is_ok(),
            "tee-file path under lean-ctx state dir must be auto-allowed: {result:?}"
        );
    }
    std::fs::remove_dir_all(&fake_root).ok();
}

#[test]
fn detected_cache_hint_recognizes_go_cargo_python() {
    use std::path::Path;
    let go = detected_cache_hint(Path::new("/Users/x/go/pkg/mod/github.com/foo/bar/main.go"));
    assert!(go.is_some(), "Go module cache should be detected");
    assert!(go.unwrap().contains("Go module cache"));

    let cargo = detected_cache_hint(Path::new(
        "/home/x/.cargo/registry/src/crates.io/serde-1.0/lib.rs",
    ));
    assert!(cargo.is_some(), "Rust cargo registry should be detected");
    assert!(cargo.unwrap().contains("Rust crate registry"));

    let py = detected_cache_hint(Path::new(
        "/usr/lib/python3.12/site-packages/requests/api.py",
    ));
    assert!(py.is_some(), "Python site-packages should be detected");

    let normal = detected_cache_hint(Path::new("/home/x/projects/myapp/src/main.rs"));
    assert!(normal.is_none(), "Normal project path should not match");
}

#[test]
fn detect_cache_root_extracts_marker_dir() {
    let cases = [
        (
            "/Users/x/go/pkg/mod/github.com/foo/bar@v1.2.3/baz.go",
            "Go module cache",
            "/Users/x/go/pkg/mod",
        ),
        (
            "/home/u/.cargo/registry/src/index-abc/serde-1.0/src/lib.rs",
            "Rust crate registry",
            "/home/u/.cargo/registry",
        ),
        (
            "/opt/venv/lib/python3.12/site-packages/requests/api.py",
            "Python site-packages",
            "/opt/venv/lib/python3.12/site-packages",
        ),
        (
            "/w/app/node_modules/react/index.js",
            "Node modules",
            "/w/app/node_modules",
        ),
        (
            "/home/u/.pyenv/versions/3.12.4/lib/python3.12/json/__init__.py",
            "pyenv Python installations",
            "/home/u/.pyenv/versions",
        ),
    ];
    for (path, want_label, want_root) in cases {
        let (label, root) = detect_language_cache_root(Path::new(path))
            .unwrap_or_else(|| panic!("expected cache match for {path}"));
        assert_eq!(label, want_label, "label for {path}");
        assert_eq!(root, PathBuf::from(want_root), "root for {path}");
    }
    assert!(
        detect_language_cache_root(Path::new("/home/u/proj/src/main.rs")).is_none(),
        "a normal project path is not a cache"
    );
}

/// The core #899 guarantee: once a detected cache root is registered, a path
/// under it *reads* (jail resolves) but never *writes* (enforce_writable
/// denies), and registration is idempotent.
#[cfg(not(feature = "no-jail"))]
#[test]
fn registered_cache_root_reads_allow_writes_deny() {
    let _iso = crate::core::data_dir::isolated_data_dir();

    let tmp = tempfile::tempdir().unwrap();
    // A fake Go module cache so detect_language_cache_root matches the path.
    let dep = tmp.path().join("go/pkg/mod/example.com/lib@v1");
    std::fs::create_dir_all(&dep).unwrap();
    let file = dep.join("lib.go");
    std::fs::write(&file, "package lib").unwrap();

    // A project jail that does NOT contain the cache.
    let project = tmp.path().join("project");
    std::fs::create_dir_all(&project).unwrap();

    // Before registration: the read escapes the jail.
    assert!(jail_path_with_roots(&file, &project, &[]).is_err());

    // Register the detected root; the second call is a no-op.
    let (_, root) = detect_language_cache_root(&file).expect("cache match");
    assert!(
        register_session_read_only_root(&root),
        "first register is new"
    );
    assert!(
        !register_session_read_only_root(&root),
        "re-register is a no-op"
    );

    // After: the read resolves, but writes are denied (read-only tier).
    assert!(
        jail_path_with_roots(&file, &project, &[]).is_ok(),
        "registered cache root must be readable"
    );
    assert!(is_read_only_path(&file), "cache file is read-only");
    assert!(
        enforce_writable(&file).is_err(),
        "writes into the cache root must be denied"
    );
}

/// Agent instruction files (skills, commands, rules, global instruction
/// files) and the agents' own settings/MCP configs below `~` are auto-admitted
/// read-only; the credentials beside them, `..` tricks and same-named folders
/// elsewhere are not.
#[test]
fn agent_instruction_roots_are_admitted_but_credentials_stay_jailed() {
    let _home = crate::core::data_dir::test_env_lock();
    let home = dirs::home_dir().expect("home dir in test env");
    for (inside, root) in [
        (".claude/skills/review/SKILL.md", ".claude/skills"),
        (".codex/skills/x/SKILL.md", ".codex/skills"),
        (".claude/CLAUDE.md", ".claude/CLAUDE.md"),
        (".agents/skills/a/SKILL.md", ".agents/skills"),
        (".cursor/rules/style.mdc", ".cursor/rules"),
        // Host output of the agent's own session (focus 2026-10-15).
        (
            ".claude/projects/-w-p/0a1b/tool-results/out.txt",
            ".claude/projects/-w-p/0a1b/tool-results",
        ),
        (
            ".claude/projects/-w-p/0a1b/subagents/agent-1.jsonl",
            ".claude/projects/-w-p/0a1b/subagents",
        ),
        (
            ".cursor/projects/17761/agent-tools/x.txt",
            ".cursor/projects/17761/agent-tools",
        ),
        (
            ".cursor/projects/17761/terminals/1.txt",
            ".cursor/projects/17761/terminals",
        ),
        (".claude/settings.json", ".claude/settings.json"),
        (".codex/config.toml", ".codex/config.toml"),
        (".cursor/mcp.json", ".cursor/mcp.json"),
    ] {
        let (_, detected) = detect_language_cache_root(&home.join(inside))
            .unwrap_or_else(|| panic!("{inside} must be admitted"));
        assert!(
            detected.ends_with(root),
            "{inside} → {}",
            detected.display()
        );
    }
    for private in [
        ".claude/.credentials.json",
        ".claude.json",
        ".claude/settings.json.bak",
        ".codex/auth.json",
        ".codex/sessions/2026/x.jsonl",
        ".codex/config.toml/../auth.json",
        ".claude/skills/../.credentials.json",
        ".claude/projects/p/transcript.jsonl",
        ".claude/projects/p/s/tool-results/../../../../.credentials.json",
        ".cursor/projects/17761/mcp-auth.json",
        ".cursor/projects/17761/agent-transcripts/t.jsonl",
        ".codex/sessions/2026/10/15/rollout.jsonl",
    ] {
        assert!(
            detect_language_cache_root(&home.join(private)).is_none(),
            "{private} must stay jailed"
        );
    }
    assert!(
        detect_language_cache_root(Path::new("/opt/x/.claude/skills/a/SKILL.md")).is_none(),
        "only the home directory's agent folders are admitted"
    );
}

/// The host's per-user scratch dir (`<tmp>/claude-<uid>`) is admitted only
/// when it is this user's and not writable by others; another account's or a
/// group/world-writable one stays jailed.
#[cfg(unix)]
#[test]
fn host_scratch_dir_is_admitted_only_when_private_to_this_user() {
    use std::os::unix::fs::PermissionsExt;
    // SAFETY: geteuid has no arguments or failure state.
    let uid = unsafe { libc::geteuid() };
    let dir = std::env::temp_dir().join(format!("claude-{uid}"));
    let created = !dir.exists();
    if created {
        std::fs::create_dir(&dir).unwrap();
        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).unwrap();
    }
    let file = dir.join("-w-p/session/scratchpad/q.sql");
    let (label, root) = detect_language_cache_root(&file).expect("own scratch dir admitted");
    assert_eq!(label, "Claude Code scratchpad");
    assert_eq!(root, canonicalize_secure(&dir));
    let foreign = std::env::temp_dir().join(format!("claude-{}/x", uid.wrapping_add(1)));
    assert!(detect_language_cache_root(&foreign).is_none());
    if created {
        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o777)).unwrap();
        assert!(
            detect_language_cache_root(&file).is_none(),
            "a scratch dir others can write into is not admitted"
        );
        std::fs::remove_dir(&dir).unwrap();
    }
}

/// Cursor writes long tool output and terminal logs per workspace and its
/// agent reads them back; only those two folders open, not the workspace's
/// MCP credentials or transcripts.
#[test]
fn cursor_agent_output_is_admitted_but_workspace_secrets_stay_jailed() {
    // Reads $HOME, which the symlink test below swaps.
    let _guard = crate::core::data_dir::test_env_lock();
    let home = dirs::home_dir().expect("home dir in test env");
    for (inside, root) in [
        (
            ".cursor/projects/1776093250124/agent-tools/9f2c.txt",
            ".cursor/projects/1776093250124/agent-tools",
        ),
        (
            ".cursor/projects/Users-me-app/terminals/3.txt",
            ".cursor/projects/Users-me-app/terminals",
        ),
        (
            ".cursor/projects/w/terminals",
            ".cursor/projects/w/terminals",
        ),
    ] {
        let (label, detected) = detect_language_cache_root(&home.join(inside))
            .unwrap_or_else(|| panic!("{inside} must be admitted"));
        assert_eq!(label, "Cursor agent output");
        assert!(
            detected.ends_with(root),
            "{inside} → {}",
            detected.display()
        );
    }
    for private in [
        ".cursor/projects/w/mcp-auth.json",
        ".cursor/projects/w/agent-transcripts/a.jsonl",
        ".cursor/projects/w",
        ".cursor/projects/agent-tools",
        ".cursor/projects/w/terminals/../mcp-auth.json",
        ".cursor/agent-tools/x.txt",
    ] {
        assert!(
            detect_language_cache_root(&home.join(private)).is_none(),
            "{private} must stay jailed"
        );
    }
    assert!(
        detect_language_cache_root(Path::new("/opt/x/.cursor/projects/w/terminals/1.txt"))
            .is_none(),
        "only the home directory's Cursor folder is admitted"
    );
}

/// Puts `$HOME` back when a test that swapped it ends (also on panic).
#[cfg(not(feature = "no-jail"))]
#[cfg(unix)]
struct RestoreHome(Option<std::ffi::OsString>);

#[cfg(not(feature = "no-jail"))]
#[cfg(unix)]
impl Drop for RestoreHome {
    fn drop(&mut self) {
        match self.0.take() {
            Some(value) => crate::test_env::set_var("HOME", value),
            None => crate::test_env::remove_var("HOME"),
        }
    }
}

/// The agent writes Cursor's output folders itself: a folder (or workspace)
/// that is a symlink must not open its target, and a link inside one is
/// never followed.
#[cfg(not(feature = "no-jail"))]
#[cfg(unix)]
#[test]
fn symlinked_cursor_agent_output_is_never_admitted() {
    let _guard = crate::core::data_dir::test_env_lock();
    let _restore_home = RestoreHome(std::env::var_os("HOME"));
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path().canonicalize().unwrap();
    crate::test_env::set_var("HOME", &home);

    let ssh = home.join(".ssh");
    let notes = home.join("notes");
    let projects = home.join(".cursor/projects");
    let real = projects.join("real/agent-tools");
    std::fs::create_dir_all(&ssh).unwrap();
    std::fs::create_dir_all(&notes).unwrap();
    std::fs::write(notes.join("a.txt"), "x").unwrap();
    std::fs::create_dir_all(&real).unwrap();
    std::fs::create_dir_all(projects.join("linked")).unwrap();
    std::os::unix::fs::symlink(&ssh, projects.join("linked/agent-tools")).unwrap();
    std::os::unix::fs::symlink(&ssh, projects.join("linked-ws")).unwrap();
    std::fs::create_dir_all(ssh.join("terminals")).unwrap();
    std::os::unix::fs::symlink(&notes, real.join("planted")).unwrap();

    assert!(detect_language_cache_root(&real.join("1.txt")).is_some());
    for linked in [
        projects.join("linked/agent-tools/id_ed25519"),
        projects.join("linked-ws/terminals/1.txt"),
    ] {
        assert!(
            detect_language_cache_root(&linked).is_none(),
            "{} must stay jailed",
            linked.display()
        );
    }
    assert!(
        !register_symlink_target_read_only(&real.join("planted/a.txt"), &real),
        "a link inside the agent's own output folder is never followed"
    );
}

/// A link inside a language cache lives in a writable project, where an agent
/// could plant it: it must never open its target, even below a temp dir.
#[cfg(not(feature = "no-jail"))]
#[cfg(unix)]
#[test]
fn symlink_in_language_cache_is_never_followed() {
    let _iso = crate::core::data_dir::isolated_data_dir();
    let tmp = tempfile::tempdir().unwrap();
    let tmp_path = tmp.path().canonicalize().unwrap();
    let root = tmp_path.join("go/pkg/mod");
    let outside = tmp_path.join("outside");
    std::fs::create_dir_all(&root).unwrap();
    std::fs::create_dir_all(&outside).unwrap();
    std::fs::write(outside.join("secret.txt"), "x").unwrap();
    std::os::unix::fs::symlink(&outside, root.join("planted")).unwrap();
    let project = tmp_path.join("project");
    std::fs::create_dir_all(&project).unwrap();

    let linked = root.join("planted/secret.txt");
    register_session_read_only_root(&root);
    assert!(!register_symlink_target_read_only(&linked, &root));
    assert!(
        jail_path_with_roots(&linked, &project, &[]).is_err(),
        "the planted link's target stays jailed"
    );
}

/// Cursor's workspace folder names, as found in `~/.cursor/projects`.
#[test]
fn cursor_workspace_slug_matches_cursor_naming() {
    for (root, slug) in [
        (
            "/Users/me/Documents/Projects/lean-ctx",
            "Users-me-Documents-Projects-lean-ctx",
        ),
        (
            "/private/var/folders/bb/cyj_m1m1/T/tmpO2JVyY",
            "private-var-folders-bb-cyj-m1m1-T-tmpO2JVyY",
        ),
        ("/home/u/my app.v2", "home-u-my-app-v2"),
    ] {
        assert_eq!(cursor_workspace_slug(Path::new(root)), slug);
    }
}

/// A Cursor session reads its own workspace's output, never another
/// project's — not even after that project's session registered its folder
/// in the process-global read-only roots. Writes stay denied.
#[cfg(not(feature = "no-jail"))]
#[cfg(unix)]
#[test]
fn cursor_agent_output_opens_only_for_the_own_workspace() {
    let _iso = crate::core::data_dir::isolated_data_dir();
    let _restore_home = RestoreHome(std::env::var_os("HOME"));
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path().canonicalize().unwrap();
    crate::test_env::set_var("HOME", &home);

    let app = home.join("code/app");
    let other = home.join("code/app-other");
    let log_of = |project: &Path| {
        let dir = home
            .join(".cursor/projects")
            .join(cursor_workspace_slug(project))
            .join("terminals");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("1.txt"), "$ cargo test").unwrap();
        dir.join("1.txt")
    };
    for project in [&app, &other] {
        std::fs::create_dir_all(project.join(".git")).unwrap();
    }
    let app_log = log_of(&app);
    let other_log = log_of(&other);

    assert!(jail_path_auto_admitting(&app_log, &app, &[]).is_ok());
    assert!(
        jail_path_auto_admitting(&other_log, &app, &[]).is_err(),
        "another project's terminal log stays jailed"
    );
    assert!(
        jail_path_with_roots(&app_log, &other, &[]).is_err(),
        "a folder registered for app does not open for app-other"
    );
    assert!(jail_path_with_roots(&app_log, &app, &[]).is_ok());
    assert!(is_read_only_path(&app_log), "writes stay denied");
}