1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
use std::path::{Path, PathBuf};
/// Canonicalize a path and strip the Windows verbatim/extended-length prefix (`\\?\`)
/// that `std::fs::canonicalize` adds on Windows. This prefix breaks many tools and
/// string-based path comparisons.
///
/// On non-Windows platforms this is equivalent to `std::fs::canonicalize`.
pub fn safe_canonicalize(path: &Path) -> std::io::Result<PathBuf> {
// TCC choke-point (#356): a launchd-standalone process (daemon/proxy/auto-
// updater, ppid 1) must never realpath a path under ~/Documents, ~/Desktop
// or ~/Downloads — the `stat` trips the macOS privacy prompt in lean-ctx's
// own name, and every release re-invalidates the grant (new cdhash), so it
// re-prompts forever. Heuristic call sites (project-root detection, session
// matching, path normalization, scan-root checks) all funnel through here,
// so guarding the sink protects them centrally instead of one opt-in check
// per call site. Return the path unchanged (lexical) rather than touching
// the filesystem. Security boundaries (PathJail) deliberately bypass this
// guard via `canonicalize_secure` — they only resolve paths the client
// explicitly asked to access, where a prompt is legitimate, and must keep
// resolving symlinks to detect jail escapes.
if !may_probe_path(path) {
return Ok(path.to_path_buf());
}
canonicalize_raw(path)
}
/// Raw realpath + Windows-verbatim strip, with **no** TCC guard. Internal sink
/// shared by [`safe_canonicalize`] (which gates it behind `may_probe_path`) and
/// [`canonicalize_secure`] (which never gates it).
pub(crate) fn canonicalize_raw(path: &Path) -> std::io::Result<PathBuf> {
let canon = std::fs::canonicalize(path)?;
Ok(strip_verbatim(canon))
}
/// Like `safe_canonicalize` but returns the original path on failure.
pub fn safe_canonicalize_or_self(path: &Path) -> PathBuf {
safe_canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}
/// SECURITY canonicalize: always resolves symlinks, even under ~/Documents in a
/// launchd-standalone process. PathJail relies on this to detect symlink jail
/// escapes (#356 must never weaken the security boundary). A standalone process
/// only reaches here for a path the client *explicitly* asked to access, where a
/// one-time TCC prompt is legitimate — unlike the self-initiated heuristic
/// probes that [`safe_canonicalize`] suppresses.
pub fn canonicalize_secure(path: &Path) -> std::io::Result<PathBuf> {
canonicalize_raw(path)
}
/// Like `canonicalize_secure` but returns the original path on failure.
pub fn canonicalize_secure_or_self(path: &Path) -> PathBuf {
canonicalize_secure(path).unwrap_or_else(|_| path.to_path_buf())
}
/// Canonicalize with a timeout guard. Protects against hangs on WSL2 DrvFS,
/// Windows reparse points, NFS, FUSE, sshfs, and other slow filesystems.
/// Falls back to the original path if canonicalize doesn't complete within the timeout.
/// Self-healing: after a timeout, subsequent calls to slow mounts skip the thread entirely.
///
/// Heuristic variant — honours the #356 TCC guard (see [`safe_canonicalize`]).
pub fn safe_canonicalize_bounded(path: &Path, timeout_ms: u64) -> PathBuf {
canonicalize_bounded_with(path, timeout_ms, safe_canonicalize_or_self)
}
/// SECURITY variant of [`safe_canonicalize_bounded`] — bypasses the #356 TCC
/// guard so PathJail keeps resolving symlinks to detect jail escapes. See
/// [`canonicalize_secure`] for why a prompt here (explicit request) is legitimate.
pub fn canonicalize_secure_bounded(path: &Path, timeout_ms: u64) -> PathBuf {
canonicalize_bounded_with(path, timeout_ms, canonicalize_secure_or_self)
}
/// Shared timeout machinery for the bounded canonicalizers. `resolve` selects
/// the guarded (`safe_canonicalize_or_self`) or security (`canonicalize_secure_or_self`)
/// sink so both variants get identical slow-mount/self-healing behaviour.
fn canonicalize_bounded_with(
path: &Path,
timeout_ms: u64,
resolve: fn(&Path) -> PathBuf,
) -> PathBuf {
use super::io_health;
let path_str = path.to_string_lossy();
if io_health::is_slow_mount(&path_str) && io_health::recent_freeze_count() > 0 {
return resolve(path);
}
let effective_timeout =
io_health::adaptive_timeout(std::time::Duration::from_millis(timeout_ms));
let path_owned = path.to_path_buf();
let (tx, rx) = std::sync::mpsc::channel();
let _ = std::thread::Builder::new()
.name("canonicalize-bounded".into())
.spawn(move || {
let _ = tx.send(resolve(&path_owned));
});
if let Ok(canonical) = rx.recv_timeout(effective_timeout) {
canonical
} else {
io_health::record_freeze();
tracing::warn!(
"[SECURITY] canonicalize timed out ({}ms) for {}; PathJail checks on \
uncanonicalized paths may be less reliable",
effective_timeout.as_millis(),
path.display()
);
path.to_path_buf()
}
}
/// Remove the `\\?\` / `//?/` verbatim prefix from a `PathBuf`.
/// Handles both regular verbatim (`\\?\C:\...`) and UNC verbatim (`\\?\UNC\...`).
pub fn strip_verbatim(path: PathBuf) -> PathBuf {
let s = path.to_string_lossy();
if let Some(stripped) = strip_verbatim_str(&s) {
PathBuf::from(stripped)
} else {
path
}
}
/// Remove the `\\?\` / `//?/` verbatim prefix from a path string.
/// Returns `Some(cleaned)` if a prefix was found, `None` otherwise.
pub fn strip_verbatim_str(path: &str) -> Option<String> {
let normalized = path.replace('\\', "/");
if let Some(rest) = normalized.strip_prefix("//?/UNC/") {
Some(format!("//{rest}"))
} else {
normalized
.strip_prefix("//?/")
.map(std::string::ToString::to_string)
}
}
/// MSYS2/Git Bash drive mapping: `/c/Users/...` -> `C:/Users/...`.
///
/// Returns `None` when the path does not carry a single-letter drive prefix.
/// Callers must apply this **only on Windows hosts**: clients running under
/// MSYS2/Git Bash hand POSIX-style drive paths to a native Windows lean-ctx.
/// On Linux/macOS `/c/...` is a literal directory and must pass through
/// untouched (GH #397 — the unconditional rewrite broke every `ctx_*` tool
/// for Linux projects rooted under `/c/...` and similar paths).
fn translate_msys_drive_prefix(p: &str) -> Option<String> {
if p.len() >= 3
&& p.starts_with('/')
&& p.as_bytes()[1].is_ascii_alphabetic()
&& p.as_bytes()[2] == b'/'
{
let drive = p.as_bytes()[1].to_ascii_uppercase() as char;
Some(format!("{drive}:{}", &p[2..]))
} else {
None
}
}
/// A Windows absolute path (`C:\…`, `C:/…`) or UNC path (`\\server`, `//server`),
/// recognised lexically on every platform.
pub fn is_windows_absolute_path(path: &str) -> bool {
let bytes = path.as_bytes();
if bytes.len() >= 3
&& bytes[0].is_ascii_alphabetic()
&& bytes[1] == b':'
&& matches!(bytes[2], b'\\' | b'/')
{
return true;
}
path.starts_with("\\\\") || path.starts_with("//")
}
/// Lexical (string-only) part of [`normalize_tool_path`]: MSYS2 drive prefix
/// (Windows hosts only), separators, double slashes, trailing slash. Performs
/// **no** filesystem access, so it is safe on persisted paths in
/// TCC-standalone processes (launchd daemon, #356) and as a dedupe key where
/// symlink resolution is not worth a `realpath` per entry.
pub fn normalize_tool_path_lexical(path: &str) -> String {
let mut p = match strip_verbatim_str(path) {
Some(stripped) => stripped,
None => path.to_string(),
};
if cfg!(windows)
&& let Some(translated) = translate_msys_drive_prefix(&p)
{
p = translated;
} else if !cfg!(windows) {
p = unescape_shell_path(&p);
}
p = p.replace('\\', "/");
// Collapse double slashes (preserve UNC paths starting with //)
while p.contains("//") && !p.starts_with("//") {
p = p.replace("//", "/");
}
// Remove trailing slash (unless root like "/" or "C:/")
if p.len() > 1 && p.ends_with('/') && !p.ends_with(":/") {
p.pop();
}
p
}
/// Undo shell quoting that agents copy into tool paths on Unix: one pair of
/// surrounding quotes (`'/a b/c'`) and backslash escapes (`My\ Project`,
/// `src/\(app\)`). Without this the separator rewrite below turned
/// `My\ Project` into `My/ Project` — a directory that does not exist, so
/// every path below a folder with a space failed. A backslash is never a
/// separator on Unix and practically never part of a file name; a backslash
/// before an ordinary character is kept for the rewrite as before.
fn unescape_shell_path(path: &str) -> String {
let trimmed = path.trim();
let unquoted = [('\'', '\''), ('"', '"')]
.iter()
.find_map(|&(open, close)| {
trimmed
.strip_prefix(open)
.and_then(|rest| rest.strip_suffix(close))
.filter(|inner| !inner.is_empty())
})
.unwrap_or(path);
if !unquoted.contains('\\') {
return unquoted.to_string();
}
let mut out = String::with_capacity(unquoted.len());
let mut chars = unquoted.chars().peekable();
while let Some(c) = chars.next() {
if c == '\\'
&& let Some(&next) = chars.peek()
&& matches!(
next,
' ' | '('
| ')'
| '['
| ']'
| '{'
| '}'
| '&'
| '\''
| '"'
| '$'
| '!'
| '#'
| ';'
| '*'
| '?'
| '<'
| '>'
| '|'
| '~'
| '`'
| '='
)
{
out.push(next);
chars.next();
continue;
}
out.push(c);
}
out
}
/// Normalize paths from any client format to a consistent OS-native form.
/// Handles MSYS2/Git Bash drive prefixes on Windows hosts
/// (`/c/Users/...` -> `C:/Users/...`), mixed separators, double slashes, and
/// trailing slashes. Uses forward slashes for consistency. On non-Windows
/// hosts `/c/...` is a literal directory and passes through unchanged (#397).
/// Whether two recorded project roots name the same project: equal after
/// separator and trailing-slash normalization, or after resolving symlinks.
/// The one comparison for project-scoped records (agents, messages, shares):
/// a raw string comparison split one project into several by spelling.
pub fn same_project(a: &str, b: &str) -> bool {
let lexical = |path: &str| {
let path = path.trim().replace('\\', "/");
let trimmed = path.trim_end_matches('/');
if trimmed.is_empty() {
path
} else {
trimmed.to_string()
}
};
a == b || lexical(a) == lexical(b) || normalize_tool_path(a) == normalize_tool_path(b)
}
pub fn normalize_tool_path(path: &str) -> String {
let mut p = normalize_tool_path_lexical(path);
// Resolve symlinks for absolute paths to ensure cache key consistency.
// Skip relative paths (preserve "." / "../" as-is), root-only paths (/ or C:/),
// slow mounts (WSL DrvFS /mnt/) where canonicalize can hang, and paths a
// TCC-standalone process must not stat (launchd daemon + ~/Documents, #356).
// Uses safe_canonicalize to strip Windows \\?\ prefix.
let is_absolute = p.starts_with('/') || (p.len() >= 3 && p.as_bytes()[1] == b':');
let is_root_only = p == "/" || (p.len() <= 3 && p.ends_with('/') && is_absolute);
if is_absolute
&& !is_root_only
&& !crate::core::io_health::is_slow_mount(&p)
&& may_probe_path(Path::new(&*p))
&& let Ok(canonical) = safe_canonicalize(Path::new(&*p))
{
let canonical_str = canonical.to_string_lossy().replace('\\', "/");
if !canonical_str.is_empty() {
p = canonical_str;
}
}
p
}
/// Agent/IDE CLI config or sandbox directories some clients launch their MCP
/// server from, but which are never a user's project root. Adopting one as the
/// project root jails every real repository path out — the root cause of #580
/// (GitHub Copilot CLI launches from `~/.copilot`; Cursor, Windsurf, Gemini CLI
/// and LM Studio behave similarly). This is the canonical set: every "is this an
/// agent dir?" check across the codebase delegates here so the list never drifts.
pub const AGENT_CONFIG_DIRS: &[&str] = &[
".claude",
".codex",
".codebuddy",
".codewhale",
".copilot",
".cursor",
".windsurf",
".gemini",
".lmstudio",
];
/// Returns `true` if `dir` is — or lies inside — a known agent/IDE config dir
/// ([`AGENT_CONFIG_DIRS`]). Separator-agnostic so Windows backslash paths
/// (`C:\Users\me\.copilot`) match too; #580 is a Windows Copilot report.
///
/// A checkout inside `<dir>/worktrees/<name>` (where Claude Code places its
/// git worktrees, e.g. `<repo>/.claude/worktrees/fix-x`) is a real project,
/// not agent config, and is exempt; `<dir>/worktrees` itself is not.
pub fn is_agent_config_dir(dir: &Path) -> bool {
let s = dir.to_string_lossy().replace('\\', "/");
AGENT_CONFIG_DIRS.iter().any(|name| {
let segment = format!("/{name}");
s.match_indices(&segment).any(|(at, _)| {
let tail = &s[at + segment.len()..];
(tail.is_empty() || tail.starts_with('/')) && !is_worktree_checkout_tail(tail)
})
})
}
/// `tail` (the path after an agent dir) names `/worktrees/<name>[/...]`.
fn is_worktree_checkout_tail(tail: &str) -> bool {
tail.strip_prefix("/worktrees/")
.and_then(|rest| rest.split('/').next())
.is_some_and(|name| !name.is_empty())
}
fn is_wsl_windows_user_profile(dir: &Path) -> bool {
let normalized = dir.to_string_lossy();
if !normalized.starts_with("/mnt/") {
return false;
}
let mut components = normalized
.split('/')
.filter(|component| !component.is_empty());
let (Some(mount), Some(drive), Some(users), Some(username)) = (
components.next(),
components.next(),
components.next(),
components.next(),
) else {
return false;
};
mount.eq_ignore_ascii_case("mnt")
&& drive.len() == 1
&& drive.as_bytes()[0].is_ascii_alphabetic()
&& users.eq_ignore_ascii_case("users")
&& !username.is_empty()
&& components.next().is_none()
}
/// Every spelling of the user's home directory a root guard must refuse: the
/// profile folder (`dirs::home_dir`, which on Windows ignores the
/// environment) and the override-friendly home (`HOME`/`USERPROFILE`,
/// [`crate::core::home::resolve_home_dir`]). On Unix both are `$HOME` and
/// one entry remains.
pub fn home_dirs() -> Vec<PathBuf> {
let mut homes: Vec<PathBuf> = Vec::with_capacity(2);
for home in [dirs::home_dir(), crate::core::home::resolve_home_dir()]
.into_iter()
.flatten()
{
if !homes.contains(&home) {
homes.push(home);
}
}
homes
}
/// A startup root the server must not adopt as a jail root: too broad
/// ([`is_broad_or_unsafe_root`]) or an agent/IDE config directory.
pub fn is_suspicious_root(dir: &Path) -> bool {
is_broad_or_unsafe_root(dir) || is_agent_config_dir(dir)
}
/// Returns `true` if the directory is too broad to be a valid project root.
/// Rejects home directories (including WSL-mounted Windows profiles), filesystem
/// root, `.` (bare CWD), agent/IDE config directories ([`AGENT_CONFIG_DIRS`])
/// and LeanCTX's own stores ([`is_lean_ctx_store_dir`]). Used to prevent
/// adopting a bogus project root and writing project-scoped data into the
/// global `~/.lean-ctx/` data directory.
pub fn is_broad_or_unsafe_root(dir: &Path) -> bool {
// Compared without the Windows verbatim `\\?\` prefix, which
// `std::fs::canonicalize` adds there: `\\?\C:\Users\me` is the home
// directory as much as `C:\Users\me`.
let plain = strip_verbatim(dir.to_path_buf());
if home_dirs()
.into_iter()
.any(|home| plain == strip_verbatim(home))
{
return true;
}
if is_wsl_windows_user_profile(dir) {
return true;
}
let s = dir.to_string_lossy();
if s == "/" || s == "\\" || s == "." {
return true;
}
is_agent_config_dir(dir) || is_lean_ctx_store_dir(dir)
}
/// `dir` is LeanCTX's data, state, config or cache directory itself. A CLI
/// started there without a project (the Cockpit's fallback working directory)
/// must never adopt it as a project. Folders inside a store stay allowed:
/// setups and fixtures with `LEAN_CTX_DATA_DIR` in a temp dir keep their
/// projects there. Resolved read-only: nothing is created. Both sides are
/// compared as given and canonical, so another spelling of the same folder
/// (a symlink, macOS `/var` → `/private/var`) matches too.
pub fn is_lean_ctx_store_dir(dir: &Path) -> bool {
let real_dir = dir.canonicalize().ok();
[
crate::core::data_dir::resolve_data_dir(),
crate::core::paths::state_dir_read_only(),
crate::core::paths::config_dir_read_only(),
crate::core::paths::cache_dir_read_only(),
]
.into_iter()
.flatten()
.filter(|store| store.is_absolute())
.any(|store| {
let real_store = store.canonicalize().ok();
dir == store
|| real_store.as_deref() == Some(dir)
|| (real_dir.is_some() && real_dir == real_store)
})
}
/// Well-known project markers used to identify project roots.
pub const PROJECT_MARKERS: &[&str] = &[
".git",
"Cargo.toml",
"package.json",
"go.mod",
"pyproject.toml",
"setup.py",
"pom.xml",
"build.gradle",
"Makefile",
"project.godot",
".lean-ctx.toml",
".planning",
];
/// Returns `true` if `dir` contains at least one known project marker.
///
/// TCC guard (#356): a launchd-owned process (daemon/proxy/auto-updater) must
/// not stat marker files under `~/Documents` & co. — the probe itself pops the
/// macOS privacy prompt. For those processes this conservatively reports
/// "no marker" without touching the filesystem.
pub fn has_project_marker(dir: &Path) -> bool {
if !may_probe_path(dir) {
return false;
}
PROJECT_MARKERS.iter().any(|m| dir.join(m).exists())
}
/// Returns `true` if the (lstat) metadata describes a symlink — or, on
/// Windows, *any* reparse point (junctions, mount points, app-exec links).
///
/// Security boundaries must use this instead of `FileType::is_symlink`:
/// Rust's `is_symlink()` reports `false` for NTFS junctions, which redirect
/// exactly like directory symlinks and would otherwise bypass jail/TOCTOU
/// checks on Windows (GL#442).
pub fn is_symlink_or_reparse(meta: &std::fs::Metadata) -> bool {
if meta.file_type().is_symlink() {
return true;
}
#[cfg(windows)]
{
use std::os::windows::fs::MetadataExt;
const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0400;
meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
}
#[cfg(not(windows))]
false
}
/// Returns `true` if `dir` is the home directory or one of the macOS "magic"
/// home subdirectories (`Documents`, `Desktop`, `Downloads`).
///
/// macOS guards these with TCC: the first time a process *enumerates or stats
/// inside* one, the OS pops a privacy prompt ("lean-ctx would like to access
/// files in your Documents folder", #356). They are also never valid project
/// roots or multi-repo workspace parents, so scan heuristics should treat them
/// as off-limits *without* calling `read_dir` (which is what trips the prompt).
pub fn is_tcc_sensitive_home_dir(dir: &Path) -> bool {
let Some(home) = dirs::home_dir() else {
return false;
};
if dir == home {
return true;
}
if dir.parent() != Some(home.as_path()) {
return false;
}
matches!(
dir.file_name().and_then(|n| n.to_str()),
Some("Documents" | "Desktop" | "Downloads")
)
}
/// Returns `true` if `path` lies inside (or is) one of the macOS TCC-protected
/// home folders (`~/Documents`, `~/Desktop`, `~/Downloads`). Pure string/path
/// comparison — performs **no** filesystem access itself.
///
/// Unlike [`is_tcc_sensitive_home_dir`] (which only matches the magic dirs
/// themselves), this also matches nested paths like `~/Documents/proj/src`,
/// because *any* `stat` below the magic dir trips the TCC prompt (#356).
pub fn is_under_tcc_protected_dir(path: &Path) -> bool {
if !cfg!(target_os = "macos") {
return false;
}
let Some(home) = dirs::home_dir() else {
return false;
};
["Documents", "Desktop", "Downloads"]
.iter()
.any(|magic| path.starts_with(home.join(magic)))
}
/// Returns `true` when this process is its own TCC identity on macOS — i.e.
/// it was started (or re-parented) by `launchd` rather than by a
/// TCC-granted host like a terminal or an editor.
///
/// Context (#356): TCC permissions attach to the *responsible process*. The
/// lean-ctx daemon/proxy LaunchAgents and the scheduled auto-updater run
/// directly under `launchd` (ppid 1), so any `stat`/`read_dir` they perform
/// under `~/Documents` pops the privacy prompt **in lean-ctx's own name** —
/// and because every release replaces the ad-hoc-signed binary (new cdhash),
/// a previously granted permission is invalidated on each update, re-prompting
/// forever. Such processes must never probe TCC-protected paths on their own
/// initiative. Child processes of a terminal or editor (MCP server, CLI)
/// inherit their host's TCC grant and keep full functionality.
pub fn process_is_tcc_standalone() -> bool {
#[cfg(target_os = "macos")]
{
// Deliberately uncached: getppid is a cheap syscall, the env override
// must stay testable within one process, and a daemonizing fork could
// change the answer after startup.
if let Ok(v) = std::env::var("LEAN_CTX_TCC_STANDALONE") {
match v.trim() {
"1" | "true" => return true,
"0" | "false" => return false,
_ => {}
}
}
// A process carrying the deny-~/Documents seatbelt sentinel is, by
// construction, a launchd-standalone descendant: the sentinel is set
// only by the LaunchAgent plist env and the self re-exec, and child
// processes inherit it. This catches a daemon the long-lived standalone
// proxy spawned via `start_daemon` (ppid = proxy, not 1), whose code-side
// path guards would otherwise stay off because `getppid()` is no longer
// 1. (#356)
if std::env::var_os(crate::core::tcc_guard_sandbox::SEATBELT_SENTINEL).is_some() {
return true;
}
// SAFETY: `getppid` takes no arguments and cannot fail.
(unsafe { libc::getppid() }) == 1
}
#[cfg(not(target_os = "macos"))]
{
false
}
}
/// Returns `true` when this process may `stat`/`read_dir`/`canonicalize`
/// `path` without risking a macOS TCC privacy prompt in lean-ctx's name.
///
/// Heuristic call sites (project-marker probes, session/root matching) must
/// consult this before touching paths from persisted state; security
/// boundaries (PathJail) are exempt — they only ever canonicalize paths the
/// client explicitly asked to access, in which case a prompt is legitimate.
pub fn may_probe_path(path: &Path) -> bool {
!(process_is_tcc_standalone() && is_under_tcc_protected_dir(path))
}
/// Returns `true` if `dir` is a multi-repo workspace parent — i.e. it has at
/// least 2 immediate child directories that each contain a project marker.
pub fn has_multi_repo_children(dir: &Path) -> bool {
// Never enumerate the home dir or macOS TCC-protected dirs: read_dir there
// pops a macOS privacy prompt (#356) and they are never workspace parents.
// `is_tcc_sensitive_home_dir` only matches the magic dirs themselves;
// `!may_probe_path` additionally refuses *nested* paths like
// `~/Documents/proj` when this process is launchd-standalone.
if is_tcc_sensitive_home_dir(dir) || !may_probe_path(dir) {
return false;
}
let Ok(entries) = std::fs::read_dir(dir) else {
return false;
};
let count = entries
.filter_map(Result::ok)
.filter(|e| e.file_type().is_ok_and(|ft| ft.is_dir()))
.filter(|e| has_project_marker(&e.path()))
.take(2)
.count();
count >= 2
}
/// Returns `true` if `project_root` collides with the lean-ctx data directory.
/// This prevents project-scoped files (overlays.json, policies.json) from being
/// written into `~/.lean-ctx/` or `~/.config/lean-ctx/`.
pub fn is_data_dir_collision(project_root: &Path) -> bool {
if is_broad_or_unsafe_root(project_root) {
return true;
}
if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
let project_lean_ctx = project_root.join(".lean-ctx");
if project_lean_ctx == data_dir || data_dir.starts_with(&project_lean_ctx) {
return true;
}
}
false
}
/// Returns the project-scoped `.lean-ctx/` directory if the project root is safe.
/// Returns `Err` if the project root collides with the global data directory.
pub fn safe_project_data_dir(project_root: &Path) -> Result<PathBuf, String> {
if is_data_dir_collision(project_root) {
return Err(format!(
"project root {} collides with global data directory; \
skipping project-scoped write",
project_root.display()
));
}
Ok(project_root.join(".lean-ctx"))
}
/// First executable named `name` on `PATH`, resolved in-process.
///
/// Replaces spawning `where`/`which`: on Windows every spawn from the
/// console-less daemon allocates a `conhost.exe`, and detection runs often.
/// Windows tries each `PATHEXT` extension before the bare name, as `cmd`
/// does when it runs a command, so an npm install yields `lean-ctx.cmd` rather
/// than the extensionless shell shim beside it. Unix requires an execute bit,
/// like `which`.
pub fn find_on_path(name: &str) -> Option<PathBuf> {
find_all_on_path(name).into_iter().next()
}
/// Every executable named `name` on `PATH`, in lookup order: the one
/// [`find_on_path`] returns first, then the ones it shadows.
pub fn find_all_on_path(name: &str) -> Vec<PathBuf> {
if name.is_empty() {
return Vec::new();
}
let Some(path_var) = std::env::var_os("PATH") else {
return Vec::new();
};
let candidates = path_candidates(name);
std::env::split_paths(&path_var)
.filter(|dir| !dir.as_os_str().is_empty())
.flat_map(|dir| candidates.iter().map(move |c| dir.join(c)))
.filter(|p| is_executable_file(p))
.collect()
}
#[cfg(windows)]
fn path_candidates(name: &str) -> Vec<String> {
let mut out = Vec::new();
if Path::new(name).extension().is_none() {
let exts = std::env::var("PATHEXT").unwrap_or_default();
let exts = if exts.trim().is_empty() {
".COM;.EXE;.BAT;.CMD".to_string()
} else {
exts
};
out.extend(
exts.split(';')
.map(str::trim)
.filter(|e| !e.is_empty())
.map(|e| format!("{name}{e}")),
);
}
out.push(name.to_string());
out
}
#[cfg(not(windows))]
fn path_candidates(name: &str) -> Vec<String> {
vec![name.to_string()]
}
#[cfg(unix)]
fn is_executable_file(p: &Path) -> bool {
use std::os::unix::fs::PermissionsExt;
std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
}
#[cfg(not(unix))]
fn is_executable_file(p: &Path) -> bool {
p.is_file()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn find_on_path_resolves_extensionless_name_and_misses_unknown() {
let _env_lock = crate::core::data_dir::test_env_lock();
let tmp = tempfile::tempdir().unwrap();
#[cfg(windows)]
let file_name = "leanctx-fop-probe.cmd";
#[cfg(not(windows))]
let file_name = "leanctx-fop-probe";
let file = tmp.path().join(file_name);
std::fs::write(&file, "x").unwrap();
// An npm install puts an extensionless shell shim beside the `.cmd`;
// Windows must resolve to the runnable `.cmd`, not the shim.
#[cfg(windows)]
std::fs::write(tmp.path().join("leanctx-fop-probe"), "#!/bin/sh").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let old = std::env::var_os("PATH");
let mut dirs = vec![tmp.path().to_path_buf()];
dirs.extend(old.iter().flat_map(std::env::split_paths));
// SAFETY: serialized by test_env_lock; restored below.
unsafe { std::env::set_var("PATH", std::env::join_paths(dirs).unwrap()) };
let found = find_on_path("leanctx-fop-probe");
let missing = find_on_path("leanctx-fop-definitely-missing");
match old {
// SAFETY: still serialized by test_env_lock; restores the saved PATH.
Some(v) => unsafe { std::env::set_var("PATH", v) },
// SAFETY: still serialized by test_env_lock; PATH was unset before.
None => unsafe { std::env::remove_var("PATH") },
}
let found = found.expect("probe on PATH");
assert!(
found
.to_string_lossy()
.eq_ignore_ascii_case(&file.to_string_lossy()),
"{found:?} vs {file:?}"
);
assert!(missing.is_none());
}
/// AP04 review I1: project-scoped records compare roots by project, not
/// by spelling — a symlinked root, a trailing slash and Windows
/// separators name the same project; another directory does not.
#[cfg(unix)]
#[test]
fn same_project_ignores_spelling_but_not_identity() {
let tmp = tempfile::tempdir().unwrap();
let real = tmp.path().join("repo");
let other = tmp.path().join("other");
std::fs::create_dir_all(&real).unwrap();
std::fs::create_dir_all(&other).unwrap();
let link = tmp.path().join("link");
std::os::unix::fs::symlink(&real, &link).unwrap();
let (real, link, other) = (
real.to_string_lossy().to_string(),
link.to_string_lossy().to_string(),
other.to_string_lossy().to_string(),
);
assert!(same_project(&real, &link));
assert!(same_project(&real, &format!("{real}/")));
assert!(same_project(r"C:\work\repo", "C:/work/repo/"));
assert!(!same_project(&real, &other));
}
#[test]
fn lean_ctx_stores_are_never_a_project_root() {
let iso = crate::core::data_dir::isolated_data_dir();
let project = tempfile::tempdir().unwrap();
// The Cockpit's fallback working directory itself.
assert!(is_broad_or_unsafe_root(iso.path()));
// A fixture project inside a temp data dir stays a project.
assert!(!is_broad_or_unsafe_root(&iso.path().join("proj")));
assert!(!is_broad_or_unsafe_root(project.path()));
}
#[cfg(unix)]
#[test]
fn a_store_under_another_spelling_is_still_refused() {
let iso = crate::core::data_dir::isolated_data_dir();
let links = tempfile::tempdir().unwrap();
let alias = links.path().join("data-alias");
std::os::unix::fs::symlink(iso.path(), &alias).unwrap();
assert!(is_broad_or_unsafe_root(&alias));
// A folder that only links into the store is not the store.
let inner = iso.path().join("proj");
std::fs::create_dir_all(&inner).unwrap();
let inner_alias = links.path().join("proj-alias");
std::os::unix::fs::symlink(&inner, &inner_alias).unwrap();
assert!(!is_broad_or_unsafe_root(&inner_alias));
}
#[test]
fn strip_regular_verbatim() {
let p = PathBuf::from(r"\\?\C:\Users\dev\project");
let result = strip_verbatim(p);
assert_eq!(result, PathBuf::from("C:/Users/dev/project"));
}
#[test]
fn tcc_sensitive_home_dir_matches_home_and_magic_dirs() {
// HOME is read here and again inside the check; tests that set HOME
// hold the env lock, so holding it keeps both reads the same.
let _env_lock = crate::core::data_dir::test_env_lock();
let Some(home) = dirs::home_dir() else {
return;
};
// Home itself and the macOS magic dirs are off-limits (#356).
assert!(is_tcc_sensitive_home_dir(&home));
assert!(is_tcc_sensitive_home_dir(&home.join("Documents")));
assert!(is_tcc_sensitive_home_dir(&home.join("Desktop")));
assert!(is_tcc_sensitive_home_dir(&home.join("Downloads")));
}
#[test]
fn tcc_sensitive_home_dir_allows_real_projects() {
let _env_lock = crate::core::data_dir::test_env_lock();
let Some(home) = dirs::home_dir() else {
return;
};
// A real project (even nested under Documents) and non-magic home children
// are scannable — only the bare magic dirs / home are blocked.
assert!(!is_tcc_sensitive_home_dir(
&home.join("Documents").join("my-project")
));
assert!(!is_tcc_sensitive_home_dir(&home.join("code")));
assert!(!is_tcc_sensitive_home_dir(&home.join("Projects")));
}
#[test]
#[cfg(target_os = "macos")]
fn under_tcc_protected_dir_matches_nested_paths() {
let _env_lock = crate::core::data_dir::test_env_lock();
let Some(home) = dirs::home_dir() else {
return;
};
// The magic dirs themselves and anything nested below them (#356).
assert!(is_under_tcc_protected_dir(&home.join("Documents")));
assert!(is_under_tcc_protected_dir(
&home.join("Documents/deep/nested/project")
));
assert!(is_under_tcc_protected_dir(&home.join("Desktop/scratch")));
assert!(is_under_tcc_protected_dir(&home.join("Downloads/x.zip")));
// Home itself, siblings, and non-home paths are fine.
assert!(!is_under_tcc_protected_dir(&home));
assert!(!is_under_tcc_protected_dir(&home.join("code/project")));
assert!(!is_under_tcc_protected_dir(Path::new("/tmp/Documents")));
}
#[test]
#[cfg(target_os = "macos")]
#[serial_test::serial]
fn tcc_standalone_blocks_probes_under_protected_dirs() {
// `#[serial]` and `test_env_lock` are two different mutexes; the tests
// in this module need both. `LEAN_CTX_TCC_STANDALONE` is read by
// `is_tcc_standalone` (line ~376) on every path normalization, so
// setting it here reaches any test that resolves a path — most of which
// serialize on `test_env_lock`, not on `#[serial]`.
let _env_lock = crate::core::data_dir::test_env_lock();
let Some(home) = dirs::home_dir() else {
return;
};
let doc_proj = home.join("Documents/some-project");
crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "1");
assert!(process_is_tcc_standalone());
assert!(!may_probe_path(&doc_proj));
// Non-protected paths stay probeable even for standalone processes.
assert!(may_probe_path(Path::new("/tmp/some-project")));
// has_project_marker must refuse without touching the filesystem.
assert!(!has_project_marker(&doc_proj));
crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "0");
assert!(!process_is_tcc_standalone());
assert!(may_probe_path(&doc_proj));
crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
}
#[test]
#[cfg(target_os = "macos")]
#[serial_test::serial]
fn tcc_standalone_detected_via_seatbelt_sentinel() {
let _env_lock = crate::core::data_dir::test_env_lock();
let Some(home) = dirs::home_dir() else {
return;
};
let doc_proj = home.join("Documents/some-project");
// No explicit override: a process carrying the deny-~/Documents seatbelt
// sentinel (inherited from its sandboxed launchd parent) counts as
// standalone even when ppid != 1, so its heuristic probes stay
// suppressed — this is the proxy→daemon chain the ppid check missed. (#356)
crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
crate::test_env::set_var(crate::core::tcc_guard_sandbox::SEATBELT_SENTINEL, "1");
assert!(process_is_tcc_standalone());
assert!(!may_probe_path(&doc_proj));
crate::test_env::remove_var(crate::core::tcc_guard_sandbox::SEATBELT_SENTINEL);
// With neither override nor sentinel a normal test process (ppid != 1)
// is not standalone, so the sentinel is what flipped the result above.
assert!(!process_is_tcc_standalone());
}
#[test]
#[cfg(target_os = "macos")]
#[serial_test::serial]
fn tcc_standalone_skips_canonicalize_under_protected_dirs() {
let _env_lock = crate::core::data_dir::test_env_lock();
let Some(home) = dirs::home_dir() else {
return;
};
// A path that does NOT exist under ~/Documents. With the TCC choke-point
// guard active, `safe_canonicalize` returns Ok(input) *without* calling
// `std::fs::canonicalize` (which would Err on a missing path) — proving
// the filesystem is never touched (#356). This is the structural fix:
// every heuristic canonicalize funnels through here.
let missing = home.join("Documents/lean-ctx-tcc-test-does-not-exist-xyzzy");
crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "1");
let guarded = safe_canonicalize(&missing);
assert!(
guarded.is_ok(),
"standalone safe_canonicalize must short-circuit (no stat) under ~/Documents"
);
assert_eq!(guarded.unwrap(), missing);
assert_eq!(safe_canonicalize_or_self(&missing), missing);
// Outside the protected dirs the guard never engages, even when standalone.
let tmp_missing = Path::new("/tmp/lean-ctx-tcc-test-does-not-exist-xyzzy");
assert!(safe_canonicalize(tmp_missing).is_err());
// Without standalone the guard is inactive: a missing ~/Documents path
// Errs from the real `std::fs::canonicalize` as before.
crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "0");
assert!(safe_canonicalize(&missing).is_err());
crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
}
#[test]
#[cfg(target_os = "macos")]
#[serial_test::serial]
fn canonicalize_secure_bypasses_tcc_guard_for_pathjail() {
let _env_lock = crate::core::data_dir::test_env_lock();
// SECURITY counterpart to the test above (#356): PathJail must keep
// resolving symlinks even when standalone under ~/Documents, so the jail
// can detect escapes. `canonicalize_secure` therefore must NOT honour the
// guard — it always touches the filesystem. We prove that by feeding a
// missing ~/Documents path while standalone: the guarded path returns
// Ok(lexical) (no stat), while the secure path Errs (it did stat).
let Some(home) = dirs::home_dir() else {
return;
};
let missing = home.join("Documents/lean-ctx-secure-canon-does-not-exist-xyzzy");
crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "1");
// Guarded sink short-circuits (no fs access).
assert_eq!(safe_canonicalize(&missing).unwrap(), missing);
// Security sink ignores the guard and actually stats -> Err on a missing
// path. If this ever returns Ok(lexical), the jail's symlink-escape
// detection has silently regressed under ~/Documents.
assert!(
canonicalize_secure(&missing).is_err(),
"canonicalize_secure must bypass the TCC guard and touch the filesystem"
);
assert_eq!(canonicalize_secure_or_self(&missing), missing);
crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
}
#[test]
fn strip_unc_verbatim() {
let p = PathBuf::from(r"\\?\UNC\server\share\dir");
let result = strip_verbatim(p);
assert_eq!(result, PathBuf::from("//server/share/dir"));
}
#[test]
fn no_prefix_unchanged() {
let p = PathBuf::from("/home/user/project");
let result = strip_verbatim(p.clone());
assert_eq!(result, p);
}
#[test]
fn windows_drive_unchanged() {
let p = PathBuf::from("C:/Users/dev");
let result = strip_verbatim(p.clone());
assert_eq!(result, p);
}
#[test]
fn strip_str_regular() {
assert_eq!(
strip_verbatim_str(r"\\?\E:\code\lean-ctx"),
Some("E:/code/lean-ctx".to_string())
);
}
#[test]
fn strip_str_unc() {
assert_eq!(
strip_verbatim_str(r"\\?\UNC\myserver\data"),
Some("//myserver/data".to_string())
);
}
#[test]
fn strip_str_forward_slash_variant() {
assert_eq!(
strip_verbatim_str("//?/C:/Users/dev"),
Some("C:/Users/dev".to_string())
);
}
#[test]
fn strip_str_no_prefix() {
assert_eq!(strip_verbatim_str("/home/user"), None);
}
#[test]
fn safe_canonicalize_or_self_nonexistent() {
let p = Path::new("/this/path/should/not/exist/xyzzy");
let result = safe_canonicalize_or_self(p);
assert_eq!(result, p.to_path_buf());
}
// The drive translation itself is platform-independent and testable
// everywhere; only its *application* is gated on Windows hosts (#397).
#[test]
fn msys_drive_prefix_translation() {
assert_eq!(
translate_msys_drive_prefix("/c/Users/ABC").as_deref(),
Some("C:/Users/ABC")
);
assert_eq!(
translate_msys_drive_prefix("/D/Program Files").as_deref(),
Some("D:/Program Files")
);
assert_eq!(translate_msys_drive_prefix("/usr/local/bin"), None);
assert_eq!(translate_msys_drive_prefix("/c"), None);
assert_eq!(translate_msys_drive_prefix("c/Users"), None);
}
#[cfg(windows)]
#[test]
fn normalize_msys_path_to_native() {
assert_eq!(
normalize_tool_path("/c/Users/ABC/AppData/lean-ctx"),
"C:/Users/ABC/AppData/lean-ctx"
);
assert_eq!(
normalize_tool_path("/D/Program Files/lean-ctx.exe"),
"D:/Program Files/lean-ctx.exe"
);
}
// GH #397: on Linux/macOS, /c/… is a literal directory — a Linux project
// rooted there must not be rewritten to a Windows drive path.
#[cfg(not(windows))]
#[test]
fn normalize_single_letter_unix_path_untouched() {
assert_eq!(
normalize_tool_path_lexical("/c/Users/me/proj"),
"/c/Users/me/proj"
);
assert_eq!(
normalize_tool_path_lexical("/x/projects/app/src"),
"/x/projects/app/src"
);
}
#[test]
fn normalize_native_windows_path_unchanged() {
assert_eq!(
normalize_tool_path("C:/Users/ABC/lean-ctx.exe"),
"C:/Users/ABC/lean-ctx.exe"
);
}
#[test]
fn normalize_backslash_windows_path() {
assert_eq!(
normalize_tool_path(r"C:\Users\ABC\lean-ctx.exe"),
"C:/Users/ABC/lean-ctx.exe"
);
}
#[test]
fn normalize_unix_path_unchanged() {
assert_eq!(
normalize_tool_path("/usr/local/bin/lean-ctx"),
"/usr/local/bin/lean-ctx"
);
}
#[cfg(not(windows))]
#[test]
fn normalize_unescapes_shell_quoting_on_unix() {
assert_eq!(
normalize_tool_path_lexical(r"/Users/me/Pfadi\ Scouting/app/main.ts"),
"/Users/me/Pfadi Scouting/app/main.ts",
"an escaped space must not become a separator"
);
assert_eq!(
normalize_tool_path_lexical(r"/srv/\(group\)/a\&b.txt"),
"/srv/(group)/a&b.txt"
);
assert_eq!(
normalize_tool_path_lexical("'/Users/me/My Project/src'"),
"/Users/me/My Project/src"
);
assert_eq!(normalize_tool_path_lexical("\"/tmp/a b\""), "/tmp/a b");
assert_eq!(
normalize_tool_path_lexical("'"),
"'",
"a lone quote is a name"
);
}
#[test]
fn normalize_windows_path_with_spaces_and_backslashes() {
// The exact "paths with spaces" scenario reported on Windows (#324):
// backslashes are converted to forward slashes (so client render layers
// never escape-mangle them) while spaces in directory names survive.
assert_eq!(
normalize_tool_path(r"C:\Users\My Name\My Project\src\main.rs"),
"C:/Users/My Name/My Project/src/main.rs"
);
assert_eq!(
normalize_tool_path(r"C:\Program Files\app\config.toml"),
"C:/Program Files/app/config.toml"
);
}
#[test]
fn normalize_double_slashes() {
assert_eq!(
normalize_tool_path("C:/Users//ABC//lean-ctx"),
"C:/Users/ABC/lean-ctx"
);
}
#[test]
fn normalize_trailing_slash_removed() {
assert_eq!(normalize_tool_path("C:/Users/ABC/"), "C:/Users/ABC");
assert_eq!(
normalize_tool_path_lexical("/tmp/nonexistent-dir-xyzzy/"),
"/tmp/nonexistent-dir-xyzzy"
);
}
#[test]
fn normalize_root_slash_preserved() {
assert_eq!(normalize_tool_path("/"), "/");
}
#[test]
fn normalize_drive_root_preserved() {
assert_eq!(normalize_tool_path("C:/"), "C:/");
}
#[test]
fn normalize_verbatim_with_msys() {
assert_eq!(normalize_tool_path(r"\\?\C:\Users\dev"), "C:/Users/dev");
}
#[test]
fn broad_root_rejects_home() {
let _home = crate::core::data_dir::test_env_lock();
if let Some(home) = dirs::home_dir() {
assert!(is_broad_or_unsafe_root(&home));
}
}
#[test]
fn broad_root_rejects_wsl_windows_user_profile() {
assert!(is_broad_or_unsafe_root(Path::new("/mnt/c/Users/dev")));
assert!(!is_broad_or_unsafe_root(Path::new(
"/mnt/c/Users/dev/projects/my-app"
)));
}
#[test]
fn broad_root_rejects_filesystem_root() {
assert!(is_broad_or_unsafe_root(Path::new("/")));
}
#[test]
fn broad_root_rejects_dot() {
assert!(is_broad_or_unsafe_root(Path::new(".")));
}
#[test]
fn broad_root_rejects_agent_dirs() {
assert!(is_broad_or_unsafe_root(Path::new("/home/user/.claude")));
assert!(is_broad_or_unsafe_root(Path::new("/home/user/.codex")));
}
#[test]
fn broad_root_rejects_copilot_and_friends() {
// #580: the previously-missing agent/IDE dirs must now be rejected so
// they are never adopted as the project root (the Copilot CLI case).
assert!(is_broad_or_unsafe_root(Path::new("/home/user/.copilot")));
assert!(is_broad_or_unsafe_root(Path::new("/home/user/.cursor")));
assert!(is_broad_or_unsafe_root(Path::new("/home/user/.windsurf")));
assert!(is_broad_or_unsafe_root(Path::new("/home/user/.gemini")));
assert!(is_broad_or_unsafe_root(Path::new("/home/user/.lmstudio")));
}
#[test]
fn agent_config_dir_matches_every_known_client() {
for name in AGENT_CONFIG_DIRS {
let leaf = format!("/home/user/{name}");
assert!(is_agent_config_dir(Path::new(&leaf)), "{leaf}");
let nested = format!("/home/user/{name}/mcp");
assert!(is_agent_config_dir(Path::new(&nested)), "{nested}");
}
}
#[test]
fn claude_code_worktree_checkout_is_not_agent_config() {
// Claude Code puts git worktrees at `<repo>/.claude/worktrees/<name>`;
// those are the user's project, not agent config (#1903 regression).
for p in [
"/repo/.claude/worktrees/fix-x",
"/repo/.claude/worktrees/fix-x/rust/src",
r"C:\repo\.claude\worktrees\fix-x",
] {
assert!(!is_agent_config_dir(Path::new(p)), "{p}");
assert!(!is_broad_or_unsafe_root(Path::new(p)), "{p}");
}
for p in [
"/repo/.claude/worktrees",
"/repo/.claude/worktrees/",
"/repo/.claude/settings",
"/repo/.claude/worktrees/fix-x/.claude",
"/repo/.claude/worktrees/fix-x/.codex/mcp",
"/home/user/.claude/worktreesx/a",
] {
assert!(is_agent_config_dir(Path::new(p)), "{p}");
}
assert!(!is_agent_config_dir(Path::new("/repo/.claudex/a")));
}
#[test]
fn agent_config_dir_matches_windows_backslash() {
// #580 is a Windows Copilot report — backslash paths must match too.
assert!(is_agent_config_dir(Path::new(r"C:\Users\me\.copilot")));
assert!(is_agent_config_dir(Path::new(r"C:\Users\me\.copilot\mcp")));
}
#[test]
fn agent_config_dir_ignores_real_projects() {
assert!(!is_agent_config_dir(Path::new("/home/user/code/lean-ctx")));
assert!(!is_agent_config_dir(Path::new(r"C:\src\app")));
}
#[test]
fn broad_root_allows_project_subdir() {
let tmp = tempfile::tempdir().unwrap();
let subdir = tmp.path().join("my-project");
std::fs::create_dir_all(&subdir).unwrap();
assert!(!is_broad_or_unsafe_root(&subdir));
}
#[test]
fn broad_root_allows_home_subdirs() {
let _home = crate::core::data_dir::test_env_lock();
if let Some(home) = dirs::home_dir() {
let subdir = home.join("projects").join("my-app");
assert!(!is_broad_or_unsafe_root(&subdir));
}
}
#[test]
fn data_dir_collision_rejects_home() {
let _home = crate::core::data_dir::test_env_lock();
if let Some(home) = dirs::home_dir() {
assert!(is_data_dir_collision(&home));
}
}
#[test]
fn data_dir_collision_allows_normal_project() {
let tmp = tempfile::tempdir().unwrap();
let project = tmp.path().join("my-project");
std::fs::create_dir_all(&project).unwrap();
assert!(!is_data_dir_collision(&project));
}
#[test]
fn has_project_marker_detects_git() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("repo");
std::fs::create_dir_all(&root).unwrap();
assert!(!has_project_marker(&root));
std::fs::create_dir(root.join(".git")).unwrap();
assert!(has_project_marker(&root));
}
#[test]
fn has_project_marker_detects_cargo_toml() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("rust-project");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join("Cargo.toml"), "[package]").unwrap();
assert!(has_project_marker(&root));
}
#[test]
fn has_project_marker_detects_godot_project() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("godot-game");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join("project.godot"), "config_version=5\n").unwrap();
assert!(has_project_marker(&root));
}
#[test]
fn multi_repo_children_needs_two() {
let tmp = tempfile::tempdir().unwrap();
let parent = tmp.path().join("code");
std::fs::create_dir_all(&parent).unwrap();
// 0 repos → false
assert!(!has_multi_repo_children(&parent));
// 1 repo → false
let repo1 = parent.join("repo1");
std::fs::create_dir_all(repo1.join(".git")).unwrap();
assert!(!has_multi_repo_children(&parent));
// 2 repos → true
let repo2 = parent.join("repo2");
std::fs::create_dir_all(repo2.join(".git")).unwrap();
assert!(has_multi_repo_children(&parent));
}
#[test]
fn multi_repo_children_ignores_files() {
let tmp = tempfile::tempdir().unwrap();
let parent = tmp.path().join("mixed");
std::fs::create_dir_all(&parent).unwrap();
// One repo dir + one plain file with .git name (not a dir)
let repo1 = parent.join("repo1");
std::fs::create_dir_all(repo1.join(".git")).unwrap();
std::fs::write(parent.join("not-a-repo"), "file").unwrap();
assert!(!has_multi_repo_children(&parent));
// Add second actual repo
let repo2 = parent.join("repo2");
std::fs::create_dir_all(&repo2).unwrap();
std::fs::write(repo2.join("package.json"), "{}").unwrap();
assert!(has_multi_repo_children(&parent));
}
#[test]
fn multi_repo_children_nonexistent_dir() {
assert!(!has_multi_repo_children(Path::new("/nonexistent/path/xyz")));
}
#[test]
fn regular_file_is_not_symlink_or_reparse() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("plain.txt");
std::fs::write(&file, "x").unwrap();
let meta = std::fs::symlink_metadata(&file).unwrap();
assert!(!is_symlink_or_reparse(&meta));
}
#[cfg(unix)]
#[test]
fn unix_symlink_is_detected() {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("target.txt");
std::fs::write(&target, "x").unwrap();
let link = tmp.path().join("link.txt");
std::os::unix::fs::symlink(&target, &link).unwrap();
let meta = std::fs::symlink_metadata(&link).unwrap();
assert!(is_symlink_or_reparse(&meta));
}
/// Runs in the windows-latest CI lane (GL#442). Symlink creation needs
/// either admin or Developer Mode — skip gracefully when unavailable.
#[cfg(windows)]
#[test]
fn windows_symlink_is_detected() {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("target.txt");
std::fs::write(&target, "x").unwrap();
let link = tmp.path().join("link.txt");
if std::os::windows::fs::symlink_file(&target, &link).is_err() {
eprintln!("skipping: symlink creation not permitted on this runner");
return;
}
let meta = std::fs::symlink_metadata(&link).unwrap();
assert!(is_symlink_or_reparse(&meta));
}
}