aptu-coder 0.22.3

MCP server for multi-language code structure analysis
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
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
// SPDX-FileCopyrightText: 2026 aptu-coder contributors
// SPDX-License-Identifier: Apache-2.0

mod common;

use common::call_tool_raw;

async fn call_exec_command_raw(params: serde_json::Value) -> serde_json::Value {
    call_tool_raw("exec_command", params).await
}

fn truncate_output(output: &str, max_lines: usize, max_bytes: usize) -> (String, bool) {
    let lines: Vec<&str> = output.lines().collect();

    let output_to_use = if lines.len() > max_lines {
        lines[..max_lines].join("\n")
    } else {
        output.to_string()
    };

    if output_to_use.len() > max_bytes {
        (output_to_use[..max_bytes].to_string(), true)
    } else {
        (output_to_use, lines.len() > max_lines)
    }
}

#[tokio::test]
async fn exec_command_happy_path() {
    // Arrange: prepare a simple echo command
    let command = "echo hello";

    // Act: execute the command via a mock handler
    // Since we can't directly call the tool handler without a full server setup,
    // we'll test the core logic by spawning the command directly
    let mut child = std::process::Command::new(
        std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string()),
    )
    .arg("-c")
    .arg(command)
    .stdout(std::process::Stdio::piped())
    .stderr(std::process::Stdio::piped())
    .spawn()
    .expect("should spawn command");

    let stdout = child
        .stdout
        .take()
        .map(|mut s| {
            let mut buf = Vec::new();
            std::io::Read::read_to_end(&mut s, &mut buf).ok();
            String::from_utf8_lossy(&buf).to_string()
        })
        .unwrap_or_default();

    let _stderr = child
        .stderr
        .take()
        .map(|mut s| {
            let mut buf = Vec::new();
            std::io::Read::read_to_end(&mut s, &mut buf).ok();
            String::from_utf8_lossy(&buf).to_string()
        })
        .unwrap_or_default();

    let status = child.wait().expect("should wait for child");
    let exit_code = status.code();

    // Assert
    assert_eq!(exit_code, Some(0), "exit code should be 0");
    assert!(
        stdout.contains("hello"),
        "stdout should contain 'hello', got: {}",
        stdout
    );
}

#[tokio::test]
async fn exec_command_nonzero_exit() {
    // Arrange: command that exits with code 42
    let command = "exit 42";

    // Act
    let mut child = std::process::Command::new(
        std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string()),
    )
    .arg("-c")
    .arg(command)
    .stdout(std::process::Stdio::piped())
    .stderr(std::process::Stdio::piped())
    .spawn()
    .expect("should spawn command");

    let _stdout = child
        .stdout
        .take()
        .map(|mut s| {
            let mut buf = Vec::new();
            std::io::Read::read_to_end(&mut s, &mut buf).ok();
            String::from_utf8_lossy(&buf).to_string()
        })
        .unwrap_or_default();

    let _stderr = child
        .stderr
        .take()
        .map(|mut s| {
            let mut buf = Vec::new();
            std::io::Read::read_to_end(&mut s, &mut buf).ok();
            String::from_utf8_lossy(&buf).to_string()
        })
        .unwrap_or_default();

    let status = child.wait().expect("should wait for child");
    let exit_code = status.code();

    // Assert
    assert_eq!(exit_code, Some(42), "exit code should be 42");
}

#[tokio::test]
async fn exec_command_working_dir_rejection() {
    // exec_command has no CWD confinement; working_dir=/tmp (outside server CWD) must succeed.
    // Only edit_overwrite/edit_replace enforce CWD confinement.
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "echo hi",
        "working_dir": "/tmp"
    }))
    .await;

    // Assert: handler must succeed (no confinement for exec_command)
    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(true),
        "exec_command with working_dir outside CWD must succeed: {resp}"
    );
    let sc = &resp["result"]["structuredContent"];
    assert_eq!(sc["exit_code"], 0, "exit_code mismatch: {sc}");
}

#[tokio::test]
async fn exec_command_output_truncation() {
    // Arrange: command that produces >2000 lines
    let command = "seq 1 3000";

    // Act
    let mut child = std::process::Command::new(
        std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string()),
    )
    .arg("-c")
    .arg(command)
    .stdout(std::process::Stdio::piped())
    .stderr(std::process::Stdio::piped())
    .spawn()
    .expect("should spawn command");

    let stdout = child
        .stdout
        .take()
        .map(|mut s| {
            let mut buf = Vec::new();
            std::io::Read::read_to_end(&mut s, &mut buf).ok();
            String::from_utf8_lossy(&buf).to_string()
        })
        .unwrap_or_default();

    let _stderr = child
        .stderr
        .take()
        .map(|mut s| {
            let mut buf = Vec::new();
            std::io::Read::read_to_end(&mut s, &mut buf).ok();
            String::from_utf8_lossy(&buf).to_string()
        })
        .unwrap_or_default();

    let _status = child.wait().expect("should wait for child");

    // Assert: output should have >2000 lines
    let line_count = stdout.lines().count();
    assert!(
        line_count > 2000,
        "output should have >2000 lines, got: {}",
        line_count
    );
}

#[test]
fn test_truncate_output_by_lines() {
    // Arrange: create output with 2500 lines
    let output = (1..=2500)
        .map(|i| i.to_string())
        .collect::<Vec<_>>()
        .join("\n");

    // Act
    let (truncated, was_truncated) = truncate_output(&output, 2000, 50 * 1024);

    // Assert
    assert!(was_truncated, "should be truncated");
    let line_count = truncated.lines().count();
    assert_eq!(line_count, 2000, "should have exactly 2000 lines");
}

#[test]
fn test_truncate_output_by_bytes() {
    // Arrange: create output that exceeds byte limit
    let output = "x".repeat(100 * 1024); // 100KB

    // Act
    let (truncated, was_truncated) = truncate_output(&output, 2000, 50 * 1024);

    // Assert
    assert!(was_truncated, "should be truncated");
    assert!(
        truncated.len() <= 50 * 1024,
        "truncated output should not exceed 50KB"
    );
}

// Handler-level integration tests via MCP JSON-RPC
// These tests verify the five key behaviors of exec_command at the integration level

#[tokio::test]
async fn test_handler_structured_output() {
    let resp = call_exec_command_raw(serde_json::json!({"command": "echo hello"})).await;
    let sc = &resp["result"]["structuredContent"];
    assert_eq!(sc["exit_code"], 0, "exit_code mismatch: {sc}");
    assert!(
        sc["stdout"].as_str().unwrap_or("").contains("hello"),
        "stdout missing 'hello': {sc}"
    );
}

#[tokio::test]
async fn test_handler_invalid_working_dir() {
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "echo hi",
        "working_dir": "/nonexistent-absolute-path-for-test"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true: {resp}"
    );
}

#[tokio::test]
async fn test_handler_nonzero_exit() {
    let resp = call_exec_command_raw(serde_json::json!({"command": "exit 42"})).await;
    let sc = &resp["result"]["structuredContent"];
    assert_eq!(sc["exit_code"], 42, "exit_code mismatch: {sc}");
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for non-zero exit: {resp}"
    );
}

#[tokio::test]
async fn test_handler_shell_preference() {
    // Serialize all tests that mutate APTU_SHELL to prevent races when the
    // test suite runs in parallel (tokio::test spawns concurrent tasks).
    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
    let _guard = ENV_LOCK.lock().unwrap();

    // SAFETY: the static mutex above ensures no other test reads or writes
    // APTU_SHELL while we hold the guard.
    unsafe { std::env::set_var("APTU_SHELL", "sh") };
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "echo $0"
    }))
    .await;
    unsafe { std::env::remove_var("APTU_SHELL") };

    let sc = &resp["result"]["structuredContent"];
    let stdout = sc["stdout"].as_str().unwrap_or("");
    assert!(
        stdout.contains("sh"),
        "expected sh in $0 output, got: {stdout}"
    );
}

#[tokio::test]
async fn test_handler_stderr_populated() {
    let resp = call_exec_command_raw(serde_json::json!({"command": "sh -c 'echo err >&2'"})).await;
    let sc = &resp["result"]["structuredContent"];
    assert!(
        sc["stderr"].as_str().unwrap_or("").contains("err"),
        "stderr missing 'err': {sc}"
    );
}

#[tokio::test]
async fn test_exec_command_large_stdout_no_deadlock() {
    // Test that large stdout (>64KB) completes without deadlock
    // Use a simpler command that writes just under 50KB to avoid truncation by MAX_BYTES
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "seq 1 500"
    }))
    .await;

    let sc = &resp["result"]["structuredContent"];
    assert_eq!(sc["exit_code"], 0, "exit code should be 0: {sc}");
    assert!(
        sc["stdout"].as_str().unwrap_or("").contains("1"),
        "stdout should contain output: {sc}"
    );
}

#[tokio::test]
async fn test_exec_command_backgrounded_process() {
    // Test that backgrounded process returns with output_truncated=false (normal case)
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "echo 'parent done'"
    }))
    .await;

    let sc = &resp["result"]["structuredContent"];
    assert_eq!(
        sc["output_truncated"], false,
        "normal command should not truncate: {sc}"
    );
    assert!(
        sc["stdout"].as_str().unwrap_or("").contains("parent done"),
        "stdout should contain output: {sc}"
    );
}

#[tokio::test]
async fn test_exec_command_overflow_to_temp_file() {
    // Test that output >2000 lines sets output_truncated and populates slot file paths.
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "seq 1 3000"
    }))
    .await;

    // Structured content must indicate truncation and expose slot file paths.
    let sc = &resp["result"]["structuredContent"];
    assert_eq!(sc["output_truncated"], true, "should be truncated: {sc}");

    let stdout_path = sc["stdout_path"].as_str();
    assert!(
        stdout_path.is_some(),
        "stdout_path should be set on overflow: {sc}"
    );
    assert!(
        stdout_path.unwrap().contains("aptu-coder-overflow"),
        "stdout_path should reference the overflow directory: {sc}"
    );
    assert!(
        stdout_path.unwrap().contains("slot-"),
        "stdout_path should contain slot identifier: {sc}"
    );
}

#[tokio::test]
async fn test_exec_command_slot_isolation() {
    // Test that overflow calls use slot identifiers (0-7) visible in structuredContent.stdout_path.
    let mut slot_ids = std::collections::HashSet::new();

    for _ in 0..8 {
        let resp = call_exec_command_raw(serde_json::json!({
            "command": "seq 1 3000"
        }))
        .await;

        let sc = &resp["result"]["structuredContent"];
        if let Some(path_str) = sc["stdout_path"].as_str() {
            if let Some(slot_start) = path_str.find("slot-") {
                let rest = &path_str[slot_start..];
                let slot_end = rest.find('/').unwrap_or(rest.len());
                let slot_id = &rest[..slot_end];
                slot_ids.insert(slot_id.to_string());
            }
        }
    }

    // Sequential overflow calls must produce at least one slot identifier.
    assert!(
        !slot_ids.is_empty(),
        "should have extracted at least one slot identifier"
    );
}

#[tokio::test]
async fn test_handler_interleaved_ordering() {
    // Arrange: command writes to both stdout and stderr
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "echo stdout_line && echo stderr_line >&2"
    }))
    .await;

    // Act: inspect structuredContent.interleaved
    let sc = &resp["result"]["structuredContent"];
    let interleaved = sc["interleaved"].as_str().unwrap_or("");

    // Assert: both lines are captured in the single interleaved field.
    // Exact ordering is non-deterministic (merge polls both streams); we verify
    // that both streams contribute to the interleaved output.
    assert!(
        interleaved.contains("stdout_line"),
        "interleaved missing stdout_line: {interleaved}"
    );
    assert!(
        interleaved.contains("stderr_line"),
        "interleaved missing stderr_line: {interleaved}"
    );
    // Verify structuredContent.stdout and .stderr are populated separately too
    assert!(
        sc["stdout"].as_str().unwrap_or("").contains("stdout_line"),
        "stdout field missing stdout_line: {sc}"
    );
    assert!(
        sc["stderr"].as_str().unwrap_or("").contains("stderr_line"),
        "stderr field missing stderr_line: {sc}"
    );
}

#[test]
fn test_handler_output_collection_error() {
    // Verify ShellOutput can be constructed with output_collection_error set.
    // The field is populated when a post-exit drain timeout fires; that path
    // is difficult to trigger deterministically in an integration test, so we
    // verify the struct-level contract here.
    use aptu_coder::ShellOutput;
    let mut output = ShellOutput::new(
        "out".into(),
        "err".into(),
        "out\nerr\n".into(),
        Some(0),
        false,
    );
    assert!(
        output.output_collection_error.is_none(),
        "output_collection_error must be None by default"
    );
    output.output_collection_error =
        Some("post-exit drain timeout: background process held pipes".into());
    assert!(
        output.output_collection_error.is_some(),
        "output_collection_error should be settable"
    );
}

#[tokio::test]
async fn test_handler_content_priority() {
    // Arrange: run a simple command
    let resp = call_exec_command_raw(serde_json::json!({"command": "echo hello"})).await;

    // Act: check the first content block for an annotations.priority field
    let content = &resp["result"]["content"];
    let first = &content[0];
    let priority = &first["annotations"]["priority"];

    // Assert: priority annotation present and equals 0.0
    assert!(
        !priority.is_null(),
        "first content block should have annotations.priority: {first}"
    );
    let pval = priority.as_f64().unwrap_or(f64::NAN);
    assert!(
        (pval - 0.0).abs() < f64::EPSILON,
        "priority should be 0.0, got: {pval}"
    );
}

#[tokio::test]
async fn test_exec_cache_hit_on_sequential_repeat() {
    // Arrange: run the same command twice sequentially
    let cmd = "echo cache_test_123";
    let params1 = serde_json::json!({"command": cmd});
    let params2 = serde_json::json!({"command": cmd});

    // Act: first call executes the command
    let resp1 = call_exec_command_raw(params1).await;
    let sc1 = &resp1["result"]["structuredContent"];
    let stdout1 = sc1["stdout"].as_str().unwrap_or("").to_string();

    // Second call executes independently (exec_command is non-cacheable)
    let resp2 = call_exec_command_raw(params2).await;
    let sc2 = &resp2["result"]["structuredContent"];
    let stdout2 = sc2["stdout"].as_str().unwrap_or("").to_string();

    // Assert: both calls succeeded with identical output (both ran the command)
    assert_eq!(sc1["exit_code"], 0, "first call should succeed: {sc1}");
    assert_eq!(sc2["exit_code"], 0, "second call should succeed: {sc2}");
    assert_eq!(
        stdout1, stdout2,
        "both calls should produce the same output"
    );
    assert!(
        stdout1.contains("cache_test_123"),
        "output should contain the echo string"
    );
    // Assert: cache_hit is absent (exec_command is non-cacheable)
    assert!(
        sc1["cache_hit"].is_null(),
        "cache_hit must be absent for exec_command: {sc1}"
    );
    assert!(
        sc2["cache_hit"].is_null(),
        "cache_hit must be absent for exec_command: {sc2}"
    );
}

#[tokio::test]
async fn test_exec_cache_skipped_with_stdin() {
    // Arrange: run a command with stdin
    let cmd = "cat";
    let stdin_content = "test_stdin_data";
    let params = serde_json::json!({
        "command": cmd,
        "stdin": stdin_content
    });

    // Act: call with stdin
    let resp = call_exec_command_raw(params).await;
    let sc = &resp["result"]["structuredContent"];

    // Assert: command executed and stdin was passed through
    assert_eq!(sc["exit_code"], 0, "cat with stdin should succeed: {sc}");
    assert!(
        sc["stdout"]
            .as_str()
            .unwrap_or("")
            .contains("test_stdin_data"),
        "stdout should contain the stdin content: {sc}"
    );
    // Assert: cache_hit is absent (exec_command is non-cacheable regardless of stdin)
    assert!(
        sc["cache_hit"].is_null(),
        "cache_hit must be absent for exec_command with stdin: {sc}"
    );
}

#[tokio::test]
async fn test_exec_cache_not_populated_on_failure() {
    // Arrange: run a command that fails (non-zero exit)
    let cmd = "false";
    let params1 = serde_json::json!({"command": cmd});
    let params2 = serde_json::json!({"command": cmd});

    // Act: first call executes and fails
    let resp1 = call_exec_command_raw(params1).await;
    let sc1 = &resp1["result"]["structuredContent"];

    // Second call re-executes independently
    let resp2 = call_exec_command_raw(params2).await;
    let sc2 = &resp2["result"]["structuredContent"];

    // Assert: both calls failed (non-zero exit) and cache_hit is absent
    assert_ne!(sc1["exit_code"], 0, "false command should fail: {sc1}");
    assert_ne!(
        sc2["exit_code"], 0,
        "false command should fail on second call too: {sc2}"
    );
    assert!(
        sc1["cache_hit"].is_null(),
        "cache_hit must be absent for failing exec_command: {sc1}"
    );
    assert!(
        sc2["cache_hit"].is_null(),
        "cache_hit must be absent for failing exec_command: {sc2}"
    );
}

#[tokio::test]
async fn test_exec_slot_files_not_written_for_small_output() {
    // Slot files must NOT be written when output is under the 2000-line limit.
    let cmd = "echo slot_file_test";
    let params = serde_json::json!({"command": cmd});

    let resp = call_exec_command_raw(params).await;
    let sc = &resp["result"]["structuredContent"];

    assert_eq!(
        sc["output_truncated"], false,
        "small output must not be truncated: {sc}"
    );
    assert!(
        sc["stdout_path"].is_null(),
        "stdout_path must be absent for small output: {sc}"
    );
    assert!(
        sc["stderr_path"].is_null(),
        "stderr_path must be absent for small output: {sc}"
    );
}

#[tokio::test]
async fn test_cd_prefix_chain_passthrough_with_working_dir() {
    // When working_dir is set and the leading cd path differs, the sanitizer must
    // pass the full command through unmodified so the shell executes every cd in order.
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "cd /tmp && pwd && cd /var && pwd",
        "working_dir": std::env::current_dir().unwrap().to_str().unwrap()
    }))
    .await;

    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(true),
        "expected success: {resp}"
    );
    let stdout = resp["result"]["structuredContent"]["stdout"]
        .as_str()
        .unwrap_or("");
    let tmp_pos = stdout.find("/tmp").expect("expected /tmp in stdout");
    let var_pos = stdout.find("/var").expect("expected /var in stdout");
    assert!(
        tmp_pos < var_pos,
        "/tmp must precede /var in stdout: {stdout}"
    );
}

#[tokio::test]
async fn test_cd_prefix_plain_absolute_promoted_when_no_working_dir() {
    // When no working_dir is supplied and the command starts with a plain absolute
    // cd path, the sanitizer promotes the path as working_dir and strips the prefix.
    // The server CWD is crates/aptu-coder; use its src/ subdir as the target.
    let cwd = std::env::current_dir().unwrap();
    let target = cwd.join("src");
    let target_str = target.to_str().unwrap().to_owned();

    let resp = call_exec_command_raw(serde_json::json!({
        "command": format!("cd {} && pwd", target_str)
    }))
    .await;

    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(true),
        "expected success: {resp}"
    );
    let stdout = resp["result"]["structuredContent"]["stdout"]
        .as_str()
        .unwrap_or("");
    assert!(
        stdout.trim().ends_with("/src"),
        "pwd should resolve to the src subdir: {stdout}"
    );
}

#[tokio::test]
async fn test_cd_prefix_shell_special_passes_through() {
    // Shell-special cd forms (cd ~, cd $HOME, cd -, relative paths without working_dir)
    // must not be intercepted by the sanitizer; they pass through to the shell unmodified.
    // cd ~ is universally supported and expands to the home directory.
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "cd ~ && pwd"
    }))
    .await;

    // The shell handles cd ~ naturally; the command must succeed.
    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(true),
        "cd ~ must reach the shell unmodified and succeed: {resp}"
    );
    let stdout = resp["result"]["structuredContent"]["stdout"]
        .as_str()
        .unwrap_or("");
    assert!(
        !stdout.trim().is_empty(),
        "pwd after cd ~ must produce output: {stdout}"
    );
}

#[tokio::test]
async fn test_exec_command_working_dir_outside_cwd() {
    // working_dir pointing outside server CWD must succeed (no CWD confinement for exec_command)
    let tmp = tempfile::TempDir::new().expect("tempdir");
    let tmp_path = tmp.path().to_str().expect("utf8").to_owned();
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "echo hello",
        "working_dir": tmp_path
    }))
    .await;
    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(true),
        "working_dir outside server CWD must succeed for exec_command: {resp}"
    );
    let sc = &resp["result"]["structuredContent"];
    assert_eq!(sc["exit_code"], 0, "exit_code mismatch: {sc}");
    assert!(
        sc["stdout"].as_str().unwrap_or("").contains("hello"),
        "stdout missing 'hello': {sc}"
    );
}

/// exec_command invalid working_dir must not expose raw path in error message.
#[tokio::test]
async fn test_exec_command_invalid_working_dir_no_path_leak() {
    let bad_wd = "/nonexistent-exec-working-dir-test";
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "echo hi",
        "working_dir": bad_wd
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true: {resp}"
    );
    let msg = resp["result"]["content"][0]["text"]
        .as_str()
        .expect("should have error text");
    assert!(
        !msg.contains(bad_wd),
        "error message must not contain working_dir path: {msg}"
    );
}

/// exec_command invalid cd prefix path must not expose raw path in error message.
#[tokio::test]
async fn test_exec_command_invalid_cd_path_no_path_leak() {
    let bad_cd_path = "/nonexistent-cd-prefix-path-test";
    let resp = call_exec_command_raw(serde_json::json!({
        "command": format!("cd {bad_cd_path} && pwd")
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true: {resp}"
    );
    let msg = resp["result"]["content"][0]["text"]
        .as_str()
        .expect("should have error text");
    assert!(
        !msg.contains(bad_cd_path),
        "error message must not contain cd prefix path: {msg}"
    );
}

#[tokio::test]
async fn test_handler_unclosed_heredoc() {
    // Arrange: a heredoc with no closing delimiter
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "cat << EOF\nhello\nworld\n"
    }))
    .await;

    // Assert: unclosed heredoc is rejected before spawning
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true: {resp}"
    );
    let msg = resp["result"]["content"][0]["text"]
        .as_str()
        .expect("should have error text");
    assert!(
        msg.contains("heredoc"),
        "error message should mention heredoc: {msg}"
    );
}

#[tokio::test]
async fn test_handler_unclosed_dash_heredoc() {
    // Arrange: <<- heredoc with no closing delimiter
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "cat <<- EOF\n\thello\n\tworld\n"
    }))
    .await;

    // Assert: unclosed <<- heredoc is rejected
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for unclosed <<- heredoc: {resp}"
    );
    let msg = resp["result"]["content"][0]["text"]
        .as_str()
        .expect("should have error text");
    assert!(
        msg.contains("heredoc"),
        "error message should mention heredoc: {msg}"
    );
}

#[tokio::test]
async fn test_handler_heredoc_delimiter_on_last_line_no_trailing_newline() {
    // Arrange: closing delimiter appears on the final line with no trailing
    // newline -- verifies the scanner handles the no-newline edge case without
    // off-by-one errors.
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "cat << EOF\nhello\nEOF"
    }))
    .await;

    // Assert: valid heredoc (delimiter present) is accepted
    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=false for valid heredoc with no trailing newline: {resp}"
    );
}

#[tokio::test]
async fn test_handler_unclosed_heredoc_no_trailing_newline() {
    // Arrange: unclosed heredoc whose body has no trailing newline -- ensures
    // the scanner reports the missing delimiter correctly in this edge case.
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "cat << EOF\nhello"
    }))
    .await;

    // Assert: unclosed heredoc is rejected
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for unclosed heredoc with no trailing newline: {resp}"
    );
    let msg = resp["result"]["content"][0]["text"]
        .as_str()
        .expect("should have error text");
    assert!(
        msg.contains("heredoc"),
        "error message should mention heredoc: {msg}"
    );
}

#[tokio::test]
async fn test_handler_heredoc_trailing_space_on_delimiter_not_accepted() {
    // Arrange: closing line is "EOF " (trailing space) -- shell does NOT treat
    // this as the closing delimiter, so the scanner must not either.
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "cat << EOF\nhello\nEOF \n"
    }))
    .await;

    // Assert: scanner sees no valid closer and rejects the command
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true: trailing space on delimiter must not be accepted: {resp}"
    );
    let msg = resp["result"]["content"][0]["text"]
        .as_str()
        .expect("should have error text");
    assert!(
        msg.contains("heredoc"),
        "error message should mention heredoc: {msg}"
    );
}

#[tokio::test]
async fn test_handler_heredoc_leading_space_on_non_dash_delimiter_not_accepted() {
    // Arrange: closing line is "  EOF" (leading spaces, non-<<- heredoc) --
    // shell does NOT treat this as the closing delimiter.
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "cat << EOF\nhello\n  EOF\n"
    }))
    .await;

    // Assert: scanner sees no valid closer and rejects the command
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true: leading spaces on non-<<- delimiter must not be accepted: {resp}"
    );
    let msg = resp["result"]["content"][0]["text"]
        .as_str()
        .expect("should have error text");
    assert!(
        msg.contains("heredoc"),
        "error message should mention heredoc: {msg}"
    );
}

#[tokio::test]
async fn test_timeout_fires_on_slow_command() {
    // Arrange: a command that sleeps longer than the timeout
    // Act: wrap in harness-level timeout to guard against regression
    let test_fut = async {
        let resp = call_exec_command_raw(serde_json::json!({
            "command": "sleep 60",
            "timeout_secs": 1
        }))
        .await;

        // Assert: error with isError=true, timed_out=true in structured content
        assert!(
            resp["result"]["isError"].as_bool().unwrap_or(false),
            "expected isError=true for timed-out command: {resp}"
        );
        let sc = &resp["result"]["structuredContent"];
        assert_eq!(
            sc["timed_out"].as_bool(),
            Some(true),
            "expected structuredContent.timed_out=true: {resp}"
        );
        assert_eq!(
            sc["timeout_secs"], 1,
            "expected structuredContent.timeout_secs=1: {resp}"
        );
    };

    tokio::time::timeout(std::time::Duration::from_secs(10), test_fut)
        .await
        .expect("test timed out (harness guard)");
}

#[tokio::test]
async fn test_fast_command_completes_with_timed_out_false() {
    // Arrange: a fast command with generous timeout
    let test_fut = async {
        let resp = call_exec_command_raw(serde_json::json!({
            "command": "echo ok",
            "timeout_secs": 10
        }))
        .await;

        // Assert: success with timed_out=false
        assert!(
            !resp["result"]["isError"].as_bool().unwrap_or(false),
            "expected isError=false for fast command: {resp}"
        );
        let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
        assert!(
            text.contains("Exit code: 0"),
            "expected exit code 0: {resp}"
        );
        let sc = &resp["result"]["structuredContent"];
        // timed_out is skip_serialized when false; if present, it must be false
        if let Some(val) = sc.as_object().and_then(|o| o.get("timed_out")) {
            assert_eq!(
                val.as_bool(),
                Some(false),
                "expected timed_out=false: {resp}"
            );
        }
    };

    tokio::time::timeout(std::time::Duration::from_secs(10), test_fut)
        .await
        .expect("test timed out (harness guard)");
}

#[tokio::test]
async fn test_timeout_secs_zero_is_treated_as_none() {
    // Arrange: timeout_secs=0 should be treated as no timeout (unlimited)
    let test_fut = async {
        let resp = call_exec_command_raw(serde_json::json!({
            "command": "echo ok",
            "timeout_secs": 0
        }))
        .await;

        // Assert: command completes normally
        assert!(
            !resp["result"]["isError"].as_bool().unwrap_or(false),
            "expected isError=false for timeout_secs=0: {resp}"
        );
        let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
        assert!(
            text.contains("Exit code: 0"),
            "expected exit code 0: {resp}"
        );
    };

    tokio::time::timeout(std::time::Duration::from_secs(10), test_fut)
        .await
        .expect("test timed out (harness guard)");
}

#[tokio::test]
async fn test_timeout_not_fires_for_immediate_command_without_timeout_secs() {
    // Arrange: no timeout_secs (None) should not produce a timeout
    let test_fut = async {
        let resp = call_exec_command_raw(serde_json::json!({
            "command": "echo hello"
        }))
        .await;

        // Assert: command completes normally
        assert!(
            !resp["result"]["isError"].as_bool().unwrap_or(false),
            "expected isError=false when timeout is None: {resp}"
        );
        let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
        assert!(
            text.contains("Exit code: 0"),
            "expected exit code 0: {resp}"
        );
        // timed_out should not be present (no timeout_secs provided)
        let sc = resp.get("result").and_then(|r| r.get("structuredContent"));
        if let Some(sc) = sc {
            // If present, must be false
            if let Some(val) = sc.as_object().and_then(|o| o.get("timed_out")) {
                assert_eq!(
                    val.as_bool(),
                    Some(false),
                    "timed_out should be false when absent: {resp}"
                );
            }
        }
    };

    tokio::time::timeout(std::time::Duration::from_secs(10), test_fut)
        .await
        .expect("test timed out (harness guard)");
}

#[tokio::test]
async fn test_drain_timeout_negative_rejected() {
    let test_fut = async {
        let resp = call_exec_command_raw(serde_json::json!({
            "command": "echo hello",
            "drain_timeout_secs": -1
        }))
        .await;
        assert!(
            resp["result"]["isError"].as_bool().unwrap_or(false),
            "expected isError: {resp}"
        );
    };
    tokio::time::timeout(std::time::Duration::from_secs(10), test_fut)
        .await
        .expect("test timed out");
}

#[tokio::test]
async fn test_drain_timeout_zero_uses_default() {
    let test_fut = async {
        let resp = call_exec_command_raw(serde_json::json!({
            "command": "echo hello",
            "drain_timeout_secs": 0
        }))
        .await;
        let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
        assert!(
            text.contains("Exit code: 0"),
            "expected exit code 0: {resp}"
        );
        assert!(
            resp["result"]["structuredContent"]["stdout"]
                .as_str()
                .unwrap_or("")
                .contains("hello"),
            "stdout should contain hello: {resp}"
        );
    };
    tokio::time::timeout(std::time::Duration::from_secs(10), test_fut)
        .await
        .expect("test timed out");
}

#[tokio::test]
async fn test_drain_timeout_positive_happy_path() {
    let test_fut = async {
        let resp = call_exec_command_raw(serde_json::json!({
            "command": "echo hello",
            "drain_timeout_secs": 100
        }))
        .await;
        let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
        assert!(text.contains("Exit code: 0"), "exit code: {resp}");
        let sc = &resp["result"]["structuredContent"];
        assert!(
            sc["stdout"].as_str().unwrap_or("").contains("hello"),
            "stdout: {resp}"
        );
        assert_eq!(sc["output_truncated"], false, "truncated: {resp}");
    };
    tokio::time::timeout(std::time::Duration::from_secs(10), test_fut)
        .await
        .expect("test timed out");
}

#[tokio::test]
async fn test_drain_timeout_background_pipe_holder() {
    let test_fut = async {
        let resp = call_exec_command_raw(serde_json::json!({
            "command": "echo main done; sleep 30 &",
            "drain_timeout_secs": 1000
        }))
        .await;
        let sc = &resp["result"]["structuredContent"];
        assert!(
            sc["output_truncated"].as_bool().unwrap_or(false),
            "expected truncation: {resp}"
        );
        assert!(
            sc["stdout"].as_str().unwrap_or("").contains("main done"),
            "stdout: {resp}"
        );
    };
    tokio::time::timeout(std::time::Duration::from_secs(3), test_fut)
        .await
        .expect("test timed out");
}

// ---------------------------------------------------------------------------
// Heredoc file-write rejection tests
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_heredoc_cat_redirect_write_rejected() {
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "cat > /tmp/file << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true: {resp}"
    );
}

#[tokio::test]
async fn test_heredoc_cat_append_write_rejected() {
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "cat >> /tmp/file << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true: {resp}"
    );
}

#[tokio::test]
async fn test_heredoc_tee_write_rejected() {
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "tee /tmp/file << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true: {resp}"
    );
}

#[tokio::test]
async fn test_heredoc_tee_append_flag_rejected() {
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "tee -a /tmp/file << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true: {resp}"
    );
}

#[tokio::test]
async fn test_heredoc_bare_redirect_rejected() {
    let resp = call_exec_command_raw(serde_json::json!({
        "command": ">> /tmp/file << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true: {resp}"
    );
}

#[tokio::test]
async fn test_heredoc_bare_single_redirect_rejected() {
    // Bare > file << EOF with no command before the redirect operator.
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "> /tmp/file << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for bare > redirect: {resp}"
    );
}

#[tokio::test]
async fn test_heredoc_tee_append_redirect_rejected() {
    // tee >> file << EOF -- tee with an explicit append redirect operator.
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "tee >> /tmp/file << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for tee >> redirect: {resp}"
    );
}

#[tokio::test]
async fn test_heredoc_tee_single_redirect_rejected() {
    // tee > file << EOF -- tee with an explicit write redirect operator.
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "tee > /tmp/file << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for tee > redirect: {resp}"
    );
}

#[tokio::test]
async fn test_heredoc_cat_redirect_in_quotes_accepted() {
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "echo 'cat > file <<EOF'"
    }))
    .await;
    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(true),
        "expected isError=false: {resp}"
    );
}

#[tokio::test]
async fn test_heredoc_cat_stdout_accepted() {
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "cat << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(true),
        "expected isError=false: {resp}"
    );
}

#[tokio::test]
async fn test_heredoc_awk_bitshift_accepted() {
    // The awk command should execute (exit code 2 from awk syntax),
    // NOT be rejected by pre-spawn validation.
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "awk '{print 1 << 2}'"
    }))
    .await;
    // awk syntax error on macOS produces exit code 2, so isError=true,
    // but the important thing is that the command *ran* at all (not
    // rejected by pre-spawn heredoc validation).  Verify by checking
    // the output contains the awk error message.
    let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
    assert!(
        text.contains("awk:"),
        "expected awk to run (not be rejected by pre-scan): {resp}"
    );
}

// ---------------------------------------------------------------------------
// Extended heredoc file-write rejection tests (subshells, process/command
// substitution, variable commands, additional file-write tools)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_heredoc_subshell_rejected() {
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "(cat > /tmp/file << EOF\ncontent\nEOF)"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for subshell heredoc: {resp}"
    );
}

#[tokio::test]
async fn test_heredoc_process_substitution_rejected() {
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "cat > >(tee /tmp/file) << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for process substitution heredoc: {resp}"
    );
}

#[tokio::test]
async fn test_heredoc_command_substitution_rejected() {
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "cat > $(echo /tmp/file) << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for command substitution heredoc: {resp}"
    );
}

#[tokio::test]
async fn test_heredoc_variable_command_rejected() {
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "$cmd > /tmp/file << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for variable command heredoc: {resp}"
    );
}

#[tokio::test]
async fn test_heredoc_printf_write_rejected() {
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "printf '%s\\n' hello > /tmp/file << EOF\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for printf heredoc: {resp}"
    );
}

#[tokio::test]
async fn test_heredoc_pipeline_accepted() {
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "cat << EOF | grep pattern\nhello pattern world\nEOF"
    }))
    .await;
    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(true),
        "expected isError=false for pipeline heredoc: {resp}"
    );
}

#[tokio::test]
async fn test_heredoc_quoted_subshell_delimiter_accepted() {
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "cat << '$(EOF)'\ncontent\n$(EOF)"
    }))
    .await;
    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(true),
        "expected isError=false for quoted subshell-like delimiter: {resp}"
    );
}

#[tokio::test]
async fn test_heredoc_escaped_paren_accepted() {
    // Escaped parentheses (\)) in a non-file-write command must not be
    // misinterpreted by paren_aware_token as an unmatched closing paren
    // that opens a spurious depth-tracking context.  The FSM operates on
    // raw bytes; '\' is not a paren-depth marker, so the depth counter
    // stays at 0 and the command is correctly accepted.
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "echo \"hello \\)\" << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(true),
        "expected isError=false for escaped paren in non-write command: {resp}"
    );
}

// ---------------------------------------------------------------------------
// Heredoc + stdin-consuming flag rejection tests
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_heredoc_stdin_bodyfile_flag_rejected() {
    // Arrange: --body-file - with heredoc (both consume stdin)
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "curl --body-file - << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for --body-file - with heredoc: {resp}"
    );
    let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
    assert!(
        text.contains("stdin-consuming flag"),
        "error should mention stdin-consuming flag: {text}"
    );
}

#[tokio::test]
async fn test_heredoc_stdin_data_flag_rejected() {
    // Arrange: --data - with heredoc
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "curl --data - << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for --data - with heredoc: {resp}"
    );
    let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
    assert!(
        text.contains("stdin-consuming flag"),
        "error should mention stdin-consuming flag: {text}"
    );
}

#[tokio::test]
async fn test_heredoc_stdin_data_raw_flag_rejected() {
    // Arrange: --data-raw - with heredoc
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "curl --data-raw - << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for --data-raw - with heredoc: {resp}"
    );
    let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
    assert!(
        text.contains("stdin-consuming flag"),
        "error should mention stdin-consuming flag: {text}"
    );
}

#[tokio::test]
async fn test_heredoc_stdin_data_binary_flag_rejected() {
    // Arrange: --data-binary - with heredoc
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "curl --data-binary - << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for --data-binary - with heredoc: {resp}"
    );
    let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
    assert!(
        text.contains("stdin-consuming flag"),
        "error should mention stdin-consuming flag: {text}"
    );
}

#[tokio::test]
async fn test_heredoc_stdin_data_urlencode_flag_rejected() {
    // Arrange: --data-urlencode - with heredoc
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "curl --data-urlencode - << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for --data-urlencode - with heredoc: {resp}"
    );
    let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
    assert!(
        text.contains("stdin-consuming flag"),
        "error should mention stdin-consuming flag: {text}"
    );
}

#[tokio::test]
async fn test_heredoc_stdin_dash_d_flag_rejected() {
    // Arrange: -d - with heredoc
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "curl -d - << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for -d - with heredoc: {resp}"
    );
    let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
    assert!(
        text.contains("stdin-consuming flag"),
        "error should mention stdin-consuming flag: {text}"
    );
}

#[tokio::test]
async fn test_heredoc_stdin_cap_f_flag_rejected() {
    // Arrange: -F - with heredoc
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "curl -F - << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for -F - with heredoc: {resp}"
    );
    let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
    assert!(
        text.contains("stdin-consuming flag"),
        "error should mention stdin-consuming flag: {text}"
    );
}

#[tokio::test]
async fn test_heredoc_stdin_stdin_flag_rejected() {
    // Arrange: --stdin with heredoc
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "some-tool --stdin << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for --stdin with heredoc: {resp}"
    );
    let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
    assert!(
        text.contains("stdin-consuming flag"),
        "error should mention stdin-consuming flag: {text}"
    );
}

#[tokio::test]
async fn test_heredoc_stdin_cat_dash_rejected() {
    // Arrange: cat - with heredoc (reads from stdin with - argument).
    // Note: cat - is already caught by the file-write heredoc check
    // (cat is a known file-write command), so the error message will
    // reference file-write rather than stdin-consuming flag.
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "cat - << EOF\ncontent\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for cat - with heredoc: {resp}"
    );
}

#[tokio::test]
async fn test_heredoc_stdin_param_conflict_rejected() {
    // Arrange: params.stdin set + heredoc in command
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "cat << EOF\ncontent\nEOF",
        "stdin": "some_content"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for stdin param + heredoc: {resp}"
    );
    let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
    assert!(
        text.contains("stdin parameter and heredoc cannot be used together"),
        "error should mention conflict: {text}"
    );
}

#[tokio::test]
async fn test_heredoc_stdin_param_no_conflict_succeeds() {
    // Arrange: params.stdin set, no heredoc (regression guard)
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "cat",
        "stdin": "hello"
    }))
    .await;
    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(true),
        "expected isError=false for stdin param without heredoc: {resp}"
    );
    let sc = &resp["result"]["structuredContent"];
    assert_eq!(sc["exit_code"], 0, "cat with stdin should succeed: {sc}");
}

#[tokio::test]
async fn test_scan_backward_flag_in_single_quotes_not_rejected() {
    // Arrange: --body-file - inside single quotes with heredoc
    // Should NOT be rejected (flag inside quotes is literal, not a flag)
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "echo '--body-file -' << EOF\ndata\nEOF"
    }))
    .await;
    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(true),
        "expected isError=false for quoted --body-file - with heredoc: {resp}"
    );
}

#[tokio::test]
async fn test_scan_backward_flag_in_double_quotes_not_rejected() {
    // Arrange: --data - inside double quotes with heredoc
    // Should NOT be rejected (flag inside quotes is literal, not a flag)
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "echo \"--data -\" << EOF\ndata\nEOF"
    }))
    .await;
    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(true),
        "expected isError=false for quoted --data - with heredoc: {resp}"
    );
}

#[tokio::test]
async fn test_body_file_flag_with_heredoc_rejected() {
    // Arrange: --body-file - outside quotes with heredoc
    // MUST be rejected (stdin-consuming flag + heredoc conflict)
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "curl --body-file - << EOF\ndata\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for --body-file - with heredoc: {resp}"
    );
    let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
    assert!(
        text.contains("stdin-consuming flag") || text.contains("stdin"),
        "error should mention stdin conflict: {text}"
    );
}

#[tokio::test]
async fn test_data_flag_d_with_heredoc_rejected() {
    // Arrange: -d - outside quotes with heredoc
    // MUST be rejected (stdin-consuming flag + heredoc conflict)
    let resp = call_exec_command_raw(serde_json::json!({
        "command": "curl -d - << EOF\ndata\nEOF"
    }))
    .await;
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for -d - with heredoc: {resp}"
    );
    let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
    assert!(
        text.contains("stdin-consuming flag") || text.contains("stdin"),
        "error should mention stdin conflict: {text}"
    );
}