agent-file-tools 0.51.0

Agent File Tools — tree-sitter powered code analysis for AI agents
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
//! Integration tests for the auto-format pipeline through the binary protocol.
//!
//! Verifies that mutation commands run the formatter when available and
//! gracefully degrade when the formatter is missing or the language is unsupported.

use std::fs;
use std::process::Command;
use std::sync::{Mutex, MutexGuard, OnceLock};

use serde_json::json;

#[cfg(unix)]
use super::helpers::warm_executable;
use super::helpers::{user_config, AftProcess};

// ============================================================================
// Helpers
// ============================================================================

/// Check if a binary is available on PATH by attempting to run `--version`.
fn is_on_path(binary: &str) -> bool {
    Command::new(binary)
        .arg("--version")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok()
}

/// Install a stub `tsc` checker that prints a fixed TS2322 error and exits 2.
/// On Unix the stub is a `tsc` shell script with the executable bit set.
/// On Windows it's a `tsc.cmd` batch file (Windows resolves both `tsc` and
/// `tsc.cmd` against PATH via PATHEXT). Either way the resolver finds it
/// when `<dir>/node_modules/.bin` is prepended to PATH.
fn install_tsc_stub(dir: &std::path::Path, file_name: &str) {
    let bin_dir = dir.join("node_modules").join(".bin");
    fs::create_dir_all(&bin_dir).unwrap();

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let stub = bin_dir.join("tsc");
        fs::write(
            &stub,
            format!(
                "#!/bin/sh\nprintf '%s(1,7): error TS2322: Type \\\"string\\\" is not assignable to type \\\"number\\\".\\n' '{}/{file_name}'\nexit 2\n",
                dir.display()
            ),
        )
        .unwrap();
        let mut perms = fs::metadata(&stub).unwrap().permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&stub, perms).unwrap();
        warm_executable(&stub, &["--version"]);
    }

    #[cfg(windows)]
    {
        // Batch file: @echo off + a single echo with the canonical error
        // format. Path uses backslashes per Windows convention so the
        // resolver-printed location matches the file we wrote.
        let stub = bin_dir.join("tsc.cmd");
        fs::write(
            &stub,
            format!(
                "@echo off\r\necho {}\\{file_name}(1,7): error TS2322: Type \"string\" is not assignable to type \"number\".\r\nexit /b 2\r\n",
                dir.display()
            ),
        )
        .unwrap();
    }
}

/// Prepend `<dir>/node_modules/.bin` to a PATH-style env var so a stub
/// installed via `install_tsc_stub` resolves before any real `tsc` on the
/// runner. Cross-platform: `std::env::split_paths` and `join_paths` use
/// `:` on Unix and `;` on Windows automatically.
fn prepend_path(existing_path: &std::ffi::OsStr, dir: &std::path::Path) -> std::ffi::OsString {
    let mut paths = std::env::split_paths(existing_path).collect::<Vec<_>>();
    paths.insert(0, dir.join("node_modules").join(".bin"));
    std::env::join_paths(paths).unwrap()
}

/// Serialize tests that install and invoke the rustfmt wrapper so concurrent
/// runs do not interfere with their response-timeout windows.
fn rustfmt_edition_test_lock() -> MutexGuard<'static, ()> {
    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
    LOCK.get_or_init(|| Mutex::new(()))
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

/// Install a rustfmt wrapper that rejects a missing or unexpected edition flag.
fn install_rustfmt_edition_guard(dir: &std::path::Path, expected_edition: Option<&str>) {
    let bin_dir = dir.join("node_modules").join(".bin");
    fs::create_dir_all(&bin_dir).unwrap();

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;

        let guard = match expected_edition {
            Some(edition) => format!(
                "if [ \"$1\" != \"--edition\" ] || [ \"$2\" != \"{edition}\" ]; then\n  printf '%s\\n' 'rustfmt expected --edition {edition}' >&2\n  exit 1\nfi\n"
            ),
            None => "if [ \"$1\" = \"--edition\" ]; then\n  printf '%s\\n' 'rustfmt expected no edition flag' >&2\n  exit 1\nfi\n".to_string(),
        };
        let stub = bin_dir.join("rustfmt");
        fs::write(
            &stub,
            format!(
                "#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then\n  exec \"$AFT_TEST_REAL_RUSTFMT\" \"$@\"\nfi\n{guard}exec \"$AFT_TEST_REAL_RUSTFMT\" \"$@\"\n"
            ),
        )
        .unwrap();
        fs::set_permissions(&stub, fs::Permissions::from_mode(0o755)).unwrap();
        warm_executable(&stub, &["--version"]);
    }

    #[cfg(windows)]
    {
        let script = match expected_edition {
            Some(edition) => format!(
                "@echo off\r\nif \"%~1\"==\"--version\" goto version\r\nif not \"%~1\"==\"--edition\" goto missing\r\nif not \"%~2\"==\"{edition}\" goto missing\r\n\"%AFT_TEST_REAL_RUSTFMT%\" %*\r\nexit /b %errorlevel%\r\n:version\r\n\"%AFT_TEST_REAL_RUSTFMT%\" --version\r\nexit /b %errorlevel%\r\n:missing\r\necho rustfmt expected --edition {edition} 1>&2\r\nexit /b 1\r\n"
            ),
            None => "@echo off\r\nif \"%~1\"==\"--version\" goto version\r\nif \"%~1\"==\"--edition\" goto unexpected_edition\r\n\"%AFT_TEST_REAL_RUSTFMT%\" %*\r\nexit /b %errorlevel%\r\n:version\r\n\"%AFT_TEST_REAL_RUSTFMT%\" --version\r\nexit /b %errorlevel%\r\n:unexpected_edition\r\necho rustfmt expected no edition flag 1>&2\r\nexit /b 1\r\n".to_string(),
        };
        fs::write(bin_dir.join("rustfmt.cmd"), script).unwrap();
    }
}

/// Create a temp directory scoped to format tests.
/// Create a unique temp directory for each test invocation.
fn format_test_dir(test_name: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir()
        .join("aft_format_tests")
        .join(test_name);
    fs::create_dir_all(&dir).unwrap();
    dir
}

// ============================================================================
// format_integration tests
// ============================================================================

#[test]

fn format_integration_applied_rustfmt() {
    if !is_on_path("rustfmt") {
        eprintln!("SKIP: rustfmt not on PATH");
        return;
    }

    let dir = format_test_dir("applied_rustfmt");
    // Cargo.toml needed so config-file detection triggers for Rust
    fs::write(dir.join("Cargo.toml"), "[package]\nname = \"test\"").unwrap();
    let target = dir.join("format_applied.rs");
    let _ = fs::remove_file(&target);

    let ugly_code = "fn  main( ){  let   x=1;  }";

    let path = prepend_path(&std::env::var_os("PATH").unwrap_or_default(), &dir);
    let mut aft = AftProcess::spawn_with_env(&[("PATH", path.as_os_str())]);
    aft.configure_format_on_edit(&dir);
    let resp = aft.send(&format!(
        r#"{{"id":"fmt-1","command":"write","file":{},"content":"{}"}}"#,
        crate::helpers::json_string(&target.display()),
        ugly_code
    ));

    assert_eq!(resp["success"], true, "write should succeed: {:?}", resp);
    assert_eq!(
        resp["formatted"], true,
        "rustfmt should have formatted the file"
    );
    assert!(
        resp.get("format_skipped_reason").is_none() || resp["format_skipped_reason"].is_null(),
        "no skip reason when formatted"
    );

    // Verify on-disk content is actually formatted
    let on_disk = fs::read_to_string(&target).unwrap();
    assert!(
        !on_disk.contains("fn  main"),
        "file should be reformatted, got: {}",
        on_disk
    );
    assert!(
        on_disk.contains("fn main()"),
        "file should contain properly formatted fn main(), got: {}",
        on_disk
    );

    let reflow_text = resp["reformatted"]["text"]
        .as_str()
        .expect("rustfmt reflow should surface reformatted.text");
    assert!(
        reflow_text.contains("fn main()"),
        "excerpt should show post-format text, got: {reflow_text}"
    );

    let _ = fs::remove_file(&target);
    let status = aft.shutdown();
    assert!(status.success());
}

#[test]
fn format_integration_rustfmt_uses_package_edition() {
    // Each test starts an AFT process and invokes the real rustfmt through its
    // guard; serializing them avoids starving their response-timeout windows.
    let _lock = rustfmt_edition_test_lock();
    let Some(real_rustfmt) = which::which("rustfmt").ok() else {
        eprintln!("SKIP: rustfmt not on PATH");
        return;
    };

    let dir = format_test_dir("rustfmt_package_edition");
    fs::write(
        dir.join("Cargo.toml"),
        "[package]\nname = \"test\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
    )
    .unwrap();
    install_rustfmt_edition_guard(&dir, Some("2021"));
    let target = dir.join("src").join("format_edition.rs");
    fs::create_dir_all(target.parent().unwrap()).unwrap();

    let path = prepend_path(&std::ffi::OsString::new(), &dir);
    let mut aft = AftProcess::spawn_with_env(&[
        ("PATH", path.as_os_str()),
        ("AFT_TEST_REAL_RUSTFMT", real_rustfmt.as_os_str()),
    ]);
    aft.configure_format_on_edit(&dir);
    let resp = aft.send(&format!(
        r#"{{"id":"fmt-rust-edition","command":"write","file":{},"content":"async   fn   format_me( ) {{ }}\n"}}"#,
        crate::helpers::json_string(&target.display()),
    ));

    assert_eq!(resp["success"], true, "write should succeed: {resp:?}");
    assert_eq!(
        resp["formatted"], true,
        "edition-aware rustfmt should format async Rust: {resp:?}"
    );
    assert!(
        fs::read_to_string(&target)
            .unwrap()
            .contains("async fn format_me() {}"),
        "rustfmt should format the async function"
    );

    let status = aft.shutdown();
    assert!(status.success());
}

#[test]
fn format_integration_rustfmt_uses_workspace_package_edition() {
    let _lock = rustfmt_edition_test_lock();
    let Some(real_rustfmt) = which::which("rustfmt").ok() else {
        eprintln!("SKIP: rustfmt not on PATH");
        return;
    };

    let workspace = format_test_dir("rustfmt_workspace_edition");
    fs::write(
        workspace.join("Cargo.toml"),
        "[workspace]\nmembers = [\"member\"]\n\n[workspace.package]\nedition = \"2021\"\n",
    )
    .unwrap();
    let member = workspace.join("member");
    fs::create_dir_all(member.join("src")).unwrap();
    fs::write(
        member.join("Cargo.toml"),
        "[package]\nname = \"member\"\nversion = \"0.1.0\"\nedition.workspace = true\n",
    )
    .unwrap();
    install_rustfmt_edition_guard(&member, Some("2021"));
    let target = member.join("src").join("lib.rs");

    let path = prepend_path(&std::ffi::OsString::new(), &member);
    let mut aft = AftProcess::spawn_with_env(&[
        ("PATH", path.as_os_str()),
        ("AFT_TEST_REAL_RUSTFMT", real_rustfmt.as_os_str()),
    ]);
    aft.configure_format_on_edit(&member);
    let resp = aft.send(&format!(
        r#"{{"id":"fmt-workspace-edition","command":"write","file":{},"content":"async   fn   format_member( ) {{ }}\n"}}"#,
        crate::helpers::json_string(&target.display()),
    ));

    assert_eq!(resp["success"], true, "write should succeed: {resp:?}");
    assert_eq!(
        resp["formatted"], true,
        "workspace edition should be passed to rustfmt: {resp:?}"
    );
    assert!(
        fs::read_to_string(&target)
            .unwrap()
            .contains("async fn format_member() {}"),
        "rustfmt should format the async workspace member"
    );

    let status = aft.shutdown();
    assert!(status.success());
}

#[test]
fn format_integration_rustfmt_uses_member_edition_from_virtual_workspace() {
    let _lock = rustfmt_edition_test_lock();
    let Some(real_rustfmt) = which::which("rustfmt").ok() else {
        eprintln!("SKIP: rustfmt not on PATH");
        return;
    };

    let workspace = format_test_dir("rustfmt_virtual_workspace_edition");
    fs::write(
        workspace.join("Cargo.toml"),
        "[workspace]\nmembers = [\"member\"]\n",
    )
    .unwrap();
    let member = workspace.join("member");
    fs::create_dir_all(member.join("src")).unwrap();
    fs::write(
        member.join("Cargo.toml"),
        "[package]\nname = \"member\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
    )
    .unwrap();
    install_rustfmt_edition_guard(&workspace, Some("2021"));
    let target = member.join("src").join("lib.rs");

    let path = prepend_path(&std::ffi::OsString::new(), &workspace);
    let mut aft = AftProcess::spawn_with_env(&[
        ("PATH", path.as_os_str()),
        ("AFT_TEST_REAL_RUSTFMT", real_rustfmt.as_os_str()),
    ]);
    aft.configure_format_on_edit(&workspace);
    let resp = aft.send(&format!(
        r#"{{"id":"fmt-virtual-workspace-edition","command":"write","file":{},"content":"async   fn   format_member( ) {{ }}\n"}}"#,
        crate::helpers::json_string(&target.display()),
    ));

    assert_eq!(resp["success"], true, "write should succeed: {resp:?}");
    assert_eq!(
        resp["formatted"], true,
        "member edition should be passed through a virtual workspace: {resp:?}"
    );
    assert!(
        fs::read_to_string(&target)
            .unwrap()
            .contains("async fn format_member() {}"),
        "rustfmt should format the async virtual-workspace member"
    );

    let status = aft.shutdown();
    assert!(status.success());
}

#[test]
fn format_integration_rustfmt_prefers_member_edition_over_workspace_default() {
    let _lock = rustfmt_edition_test_lock();
    let Some(real_rustfmt) = which::which("rustfmt").ok() else {
        eprintln!("SKIP: rustfmt not on PATH");
        return;
    };

    let workspace = format_test_dir("rustfmt_member_edition_precedence");
    fs::write(
        workspace.join("Cargo.toml"),
        "[workspace]\nmembers = [\"member\"]\n\n[workspace.package]\nedition = \"2018\"\n",
    )
    .unwrap();
    let member = workspace.join("member");
    fs::create_dir_all(member.join("src")).unwrap();
    fs::write(
        member.join("Cargo.toml"),
        "[package]\nname = \"member\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
    )
    .unwrap();
    install_rustfmt_edition_guard(&workspace, Some("2021"));
    let target = member.join("src").join("lib.rs");

    let path = prepend_path(&std::ffi::OsString::new(), &workspace);
    let mut aft = AftProcess::spawn_with_env(&[
        ("PATH", path.as_os_str()),
        ("AFT_TEST_REAL_RUSTFMT", real_rustfmt.as_os_str()),
    ]);
    aft.configure_format_on_edit(&workspace);
    let resp = aft.send(&format!(
        r#"{{"id":"fmt-member-edition-precedence","command":"write","file":{},"content":"async   fn   format_member( ) {{ }}\n"}}"#,
        crate::helpers::json_string(&target.display()),
    ));

    assert_eq!(resp["success"], true, "write should succeed: {resp:?}");
    assert_eq!(
        resp["formatted"], true,
        "member edition should override workspace.package.edition: {resp:?}"
    );

    let status = aft.shutdown();
    assert!(status.success());
}

#[test]
fn format_integration_rustfmt_preserves_bare_2015_invocation() {
    let _lock = rustfmt_edition_test_lock();
    let Some(real_rustfmt) = which::which("rustfmt").ok() else {
        eprintln!("SKIP: rustfmt not on PATH");
        return;
    };

    let dir = format_test_dir("rustfmt_no_edition");
    fs::write(
        dir.join("Cargo.toml"),
        "[package]\nname = \"test\"\nversion = \"0.1.0\"\n",
    )
    .unwrap();
    install_rustfmt_edition_guard(&dir, None);
    let target = dir.join("src").join("format_2015.rs");
    fs::create_dir_all(target.parent().unwrap()).unwrap();

    let path = prepend_path(&std::ffi::OsString::new(), &dir);
    let mut aft = AftProcess::spawn_with_env(&[
        ("PATH", path.as_os_str()),
        ("AFT_TEST_REAL_RUSTFMT", real_rustfmt.as_os_str()),
    ]);
    aft.configure_format_on_edit(&dir);
    let resp = aft.send(&format!(
        r#"{{"id":"fmt-no-edition","command":"write","file":{},"content":"fn  main( ) {{ }}\n"}}"#,
        crate::helpers::json_string(&target.display()),
    ));

    assert_eq!(resp["success"], true, "write should succeed: {resp:?}");
    assert_eq!(
        resp["formatted"], true,
        "a manifest without edition must run bare rustfmt: {resp:?}"
    );
    assert!(
        fs::read_to_string(&target)
            .unwrap()
            .contains("fn main() {}"),
        "rustfmt should format the Rust 2015-compatible function"
    );

    let status = aft.shutdown();
    assert!(status.success());
}

/// edit_match with a mis-wrapped replacement → reformatted.text in response.
#[test]
fn format_integration_edit_match_reformatted_excerpt_on_reflow() {
    if !is_on_path("rustfmt") {
        eprintln!("SKIP: rustfmt not on PATH");
        return;
    }

    let dir = format_test_dir("edit_match_reflow");
    fs::write(dir.join("Cargo.toml"), "[package]\nname = \"test\"").unwrap();
    let target = dir.join("format_edit_match_reflow.rs");
    fs::write(
        &target,
        "fn main() {\n    helper();\n}\n\nfn helper() {\n    println!(\"ok\");\n}\n",
    )
    .unwrap();

    let path = prepend_path(&std::env::var_os("PATH").unwrap_or_default(), &dir);
    let mut aft = AftProcess::spawn_with_env(&[("PATH", path.as_os_str())]);
    aft.send(
        &serde_json::json!({
            "id": "cfg-fmt-reflow",
            "command": "configure",
            "harness": "opencode",
            "project_root": dir.display().to_string(),
            "config": user_config(serde_json::json!({ "format_on_edit": true })),
        })
        .to_string(),
    );

    let req = serde_json::json!({
        "id": "fmt-edit-match",
        "command": "edit_match",
        "file": target.display().to_string(),
        "match": "fn helper() {\n    println!(\"ok\");\n}",
        "replacement": "fn helper() {  println!(  \"ok\"  );  }",
    });
    let resp = aft.send(&serde_json::to_string(&req).unwrap());

    assert_eq!(
        resp["success"], true,
        "edit_match should succeed: {:?}",
        resp
    );
    assert_eq!(resp["formatted"], true);
    let reflow_text = resp["reformatted"]["text"]
        .as_str()
        .expect("replacement reflow should surface reformatted.text");
    assert!(
        reflow_text.contains("println!"),
        "excerpt should contain formatted helper body, got: {reflow_text}"
    );

    let _ = fs::remove_file(&target);
    let status = aft.shutdown();
    assert!(status.success());
}

/// Well-formatted write → reformatted field absent (self-suppress).
#[test]
fn format_integration_write_self_suppresses_reformatted_when_no_reflow() {
    if !is_on_path("rustfmt") {
        eprintln!("SKIP: rustfmt not on PATH");
        return;
    }

    let dir = format_test_dir("write_self_suppress");
    fs::write(dir.join("Cargo.toml"), "[package]\nname = \"test\"").unwrap();
    let target = dir.join("format_self_suppress.rs");
    let _ = fs::remove_file(&target);

    let neat = "fn main() {\n    let x = 1;\n}\n";

    let path = prepend_path(&std::env::var_os("PATH").unwrap_or_default(), &dir);
    let mut aft = AftProcess::spawn_with_env(&[("PATH", path.as_os_str())]);
    aft.configure(&dir);
    let resp = aft.send(&format!(
        r#"{{"id":"fmt-self","command":"write","file":{},"content":{}}}"#,
        crate::helpers::json_string(&target.display()),
        crate::helpers::json_string(&neat)
    ));

    assert_eq!(resp["success"], true, "write should succeed: {:?}", resp);
    assert!(
        resp.get("reformatted").is_none() || resp["reformatted"].is_null(),
        "already-formatted content should not emit reformatted: {:?}",
        resp
    );

    let _ = fs::remove_file(&target);
    let status = aft.shutdown();
    assert!(status.success());
}

/// Write a .txt file → formatter is unsupported for this language.
#[test]
fn format_integration_unsupported_language() {
    let dir = format_test_dir("unsupported_lang");
    let target = dir.join("format_unsupported.txt");
    let _ = fs::remove_file(&target);

    let path = prepend_path(&std::env::var_os("PATH").unwrap_or_default(), &dir);
    let mut aft = AftProcess::spawn_with_env(&[("PATH", path.as_os_str())]);
    aft.configure_format_on_edit(&dir);
    let resp = aft.send(&format!(
        r#"{{"id":"fmt-2","command":"write","file":{},"content":"hello world"}}"#,
        crate::helpers::json_string(&target.display())
    ));

    assert_eq!(resp["success"], true, "write should succeed: {:?}", resp);
    assert_eq!(
        resp["formatted"], false,
        "txt files should not be formatted"
    );
    assert_eq!(
        resp["format_skipped_reason"], "unsupported_language",
        "skip reason should be unsupported_language"
    );

    let _ = fs::remove_file(&target);
    let status = aft.shutdown();
    assert!(status.success());
}

/// Write a .py file without a formatter config → no_formatter_configured.
#[test]
fn format_integration_no_formatter_configured() {
    let dir = format_test_dir("no_formatter_configured");
    let target = dir.join("format_no_formatter_configured.py");
    let _ = fs::remove_file(&target);

    let mut aft = AftProcess::spawn();
    let resp = aft.send(&format!(
        r#"{{"id":"fmt-3","command":"write","file":{},"content":"x = 1"}}"#,
        crate::helpers::json_string(&target.display())
    ));

    assert_eq!(resp["success"], true, "write should succeed: {:?}", resp);
    assert_eq!(
        resp["formatted"], false,
        "should not be formatted without formatter"
    );
    assert_eq!(
        resp["format_skipped_reason"], "no_formatter_configured",
        "skip reason should be no_formatter_configured"
    );

    let _ = fs::remove_file(&target);
    let status = aft.shutdown();
    assert!(status.success());
}

/// A configured formatter whose binary is missing → formatter_not_installed.
#[test]
fn format_integration_formatter_not_installed() {
    let dir = format_test_dir("formatter_not_installed");
    fs::write(dir.join("biome.json"), "{}\n").unwrap();
    let target = dir.join("format_formatter_not_installed.ts");
    let _ = fs::remove_file(&target);

    let path = prepend_path(&std::ffi::OsString::new(), &dir);
    let mut aft = AftProcess::spawn_with_env(&[
        ("PATH", path.as_os_str()),
        ("AFT_DISABLE_WELL_KNOWN_LOOKUP", std::ffi::OsStr::new("1")),
    ]);
    let cfg = aft.configure_format_on_edit(&dir);
    assert_eq!(cfg["success"], true, "configure should succeed: {:?}", cfg);
    let resp = aft.send(&format!(
        r#"{{"id":"fmt-3b","command":"write","file":{},"content":"const x = 1;\n"}}"#,
        crate::helpers::json_string(&target.display())
    ));

    assert_eq!(resp["success"], true, "write should succeed: {:?}", resp);
    assert_eq!(resp["formatted"], false);
    assert_eq!(
        resp["format_skipped_reason"], "formatter_not_installed",
        "skip reason should be formatter_not_installed: {:?}",
        resp
    );

    let _ = fs::remove_file(&target);
    let status = aft.shutdown();
    assert!(status.success());
}

#[cfg(unix)]
#[test]
fn format_integration_ruff_old_version_is_gated_at_format_time() {
    use std::os::unix::fs::PermissionsExt;

    let dir = format_test_dir("ruff_old_version");
    fs::write(dir.join("ruff.toml"), "line-length = 88\n").unwrap();
    let bin_dir = dir.join("node_modules").join(".bin");
    fs::create_dir_all(&bin_dir).unwrap();
    let canary = dir.join("ruff-version-canary");
    let _ = fs::remove_file(&canary);
    let ruff = bin_dir.join("ruff");
    fs::write(
        &ruff,
        "#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then printf executed > \"$RUFF_CANARY\"; printf 'ruff 0.1.1\\n'; exit 0; fi\nexit 0\n",
    )
    .unwrap();
    fs::set_permissions(&ruff, fs::Permissions::from_mode(0o755)).unwrap();
    // The `--version` branch writes the canary checked below, so warm through
    // the fixture's inert branch before AFT performs the real version probe.
    warm_executable(&ruff, &["--warmup"]);

    let target = dir.join("format_ruff_old.py");
    let path = prepend_path(&std::ffi::OsString::new(), &dir);
    let mut aft = AftProcess::spawn_with_env(&[
        ("PATH", path.as_os_str()),
        ("RUFF_CANARY", canary.as_os_str()),
    ]);
    let cfg = aft.configure_format_on_edit(&dir);
    assert_eq!(cfg["success"], true, "configure should succeed: {cfg:?}");

    let resp = aft.send(&format!(
        r#"{{"id":"fmt-ruff-old","command":"write","file":{},"content":"x = 1\\n"}}"#,
        crate::helpers::json_string(&target.display())
    ));
    assert_eq!(resp["success"], true, "write should succeed: {resp:?}");
    assert_eq!(resp["formatted"], false);
    assert_eq!(resp["format_skipped_reason"], "formatter_not_installed");
    assert!(
        canary.exists(),
        "the version probe should run on a format operation"
    );

    let (status, stderr) = aft.stderr_output();
    assert!(status.success());
    assert!(
        stderr.contains("ruff formatter version 0.1.1 is too old"),
        "version-gated format warning should name the detected version; stderr: {stderr}"
    );
}

#[cfg(unix)]
#[test]
fn format_integration_oxfmt_config_runs_oxfmt() {
    let dir = format_test_dir("oxfmt_config_runs");
    fs::write(dir.join(".oxfmtrc.json"), "{}\n").unwrap();
    let bin_dir = dir.join("node_modules").join(".bin");
    fs::create_dir_all(&bin_dir).unwrap();
    let stub = bin_dir.join("oxfmt");
    fs::write(
        &stub,
        "#!/bin/sh\nif [ \"$1\" = \"--write\" ]; then printf 'const x = 1;\n' > \"$2\"; fi\n",
    )
    .unwrap();
    use std::os::unix::fs::PermissionsExt;
    fs::set_permissions(&stub, fs::Permissions::from_mode(0o755)).unwrap();
    warm_executable(&stub, &["--version"]);

    let target = dir.join("format_oxfmt.ts");
    let _ = fs::remove_file(&target);
    let path = prepend_path(&std::ffi::OsString::new(), &dir);
    let mut aft = AftProcess::spawn_with_env(&[("PATH", path.as_os_str())]);
    let cfg = aft.configure_format_on_edit(&dir);
    assert_eq!(cfg["success"], true, "configure should succeed: {:?}", cfg);

    let resp = aft.send(&format!(
        r#"{{"id":"fmt-3c","command":"write","file":{},"content":"const   x=1;\n"}}"#,
        crate::helpers::json_string(&target.display())
    ));

    assert_eq!(resp["success"], true, "write should succeed: {:?}", resp);
    assert_eq!(
        resp["formatted"], true,
        "oxfmt should have formatted the file"
    );
    assert_eq!(fs::read_to_string(&target).unwrap(), "const x = 1;\n");

    let _ = fs::remove_file(&target);
    let status = aft.shutdown();
    assert!(status.success());
}

#[cfg(unix)]
#[test]
fn format_integration_oxfmt_ignored_path_reports_formatter_excluded_path() {
    let dir = format_test_dir("oxfmt_ignored_path");
    fs::write(dir.join(".oxfmtrc.json"), "{}\n").unwrap();
    let bin_dir = dir.join("node_modules").join(".bin");
    fs::create_dir_all(&bin_dir).unwrap();
    let stub = bin_dir.join("oxfmt");
    fs::write(
        &stub,
        "#!/bin/sh\nprintf 'Expected at least one target file after applying ignore rules.\n' >&2\nexit 1\n",
    )
    .unwrap();
    use std::os::unix::fs::PermissionsExt;
    fs::set_permissions(&stub, fs::Permissions::from_mode(0o755)).unwrap();
    warm_executable(&stub, &["--version"]);

    let target = dir.join("format_oxfmt_ignored.ts");
    let _ = fs::remove_file(&target);
    let path = prepend_path(&std::ffi::OsString::new(), &dir);
    let mut aft = AftProcess::spawn_with_env(&[("PATH", path.as_os_str())]);
    let cfg = aft.configure_format_on_edit(&dir);
    assert_eq!(cfg["success"], true, "configure should succeed: {:?}", cfg);

    let resp = aft.send(&format!(
        r#"{{"id":"fmt-3d","command":"write","file":{},"content":"const   x=1;\n"}}"#,
        crate::helpers::json_string(&target.display())
    ));

    assert_eq!(resp["success"], true, "write should succeed: {:?}", resp);
    assert_eq!(resp["formatted"], false);
    assert_eq!(
        resp["format_skipped_reason"], "formatter_excluded_path",
        "oxfmt ignored paths should report formatter_excluded_path: {:?}",
        resp
    );

    let _ = fs::remove_file(&target);
    let status = aft.shutdown();
    assert!(status.success());
}

/// add_import on a .rs file → verify response has formatted field.

#[test]
fn format_integration_add_import_with_format() {
    let dir = format_test_dir("add_import");
    fs::write(dir.join("Cargo.toml"), "[package]\nname = \"test\"").unwrap();
    let target = dir.join("format_add_import.rs");
    // Write a valid Rust file with a function
    fs::write(&target, "fn main() {\n    println!(\"hello\");\n}\n").unwrap();

    let mut aft = AftProcess::spawn();
    aft.configure(&dir);
    let resp = aft.send(&format!(
        r#"{{"id":"fmt-4","command":"add_import","file":{},"module":"std::collections::HashMap"}}"#,
        crate::helpers::json_string(&target.display())
    ));

    assert_eq!(
        resp["success"], true,
        "add_import should succeed: {:?}",
        resp
    );
    assert_eq!(resp["added"], true);
    // The formatted field must always be present
    assert!(
        resp.get("formatted").is_some() && !resp["formatted"].is_null(),
        "formatted field must be present in add_import response: {:?}",
        resp
    );

    // Verify the import was actually added to the file
    let on_disk = fs::read_to_string(&target).unwrap();
    assert!(
        on_disk.contains("use std::collections::HashMap"),
        "import should be in file, got: {}",
        on_disk
    );

    let _ = fs::remove_file(&target);
    let status = aft.shutdown();
    assert!(status.success());
}

/// edit_symbol on a .rs file → verify formatted field in response.

#[test]
fn format_integration_edit_symbol_with_format() {
    let dir = format_test_dir("edit_symbol");
    fs::write(dir.join("Cargo.toml"), "[package]\nname = \"test\"").unwrap();
    let target = dir.join("format_edit_symbol.rs");
    // Write a Rust file with a function to edit
    fs::write(&target, "fn greet() {\n    println!(\"hi\");\n}\n").unwrap();

    let mut aft = AftProcess::spawn();
    aft.configure(&dir);

    // Use edit_symbol to replace the function
    let new_body = r#"fn greet() {\n    println!(\"hello world\");\n}"#;
    let resp = aft.send(&format!(
        r#"{{"id":"fmt-5","command":"edit_symbol","file":{},"symbol":"greet","operation":"replace","content":"{}"}}"#,
        crate::helpers::json_string(&target.display()),
        new_body
    ));

    assert_eq!(
        resp["success"], true,
        "edit_symbol should succeed: {:?}",
        resp
    );
    // The formatted field must always be present
    assert!(
        resp.get("formatted").is_some() && !resp["formatted"].is_null(),
        "formatted field must be present in edit_symbol response: {:?}",
        resp
    );

    let _ = fs::remove_file(&target);
    let status = aft.shutdown();
    assert!(status.success());
}

/// Verify that the `formatted` field is always present in mutation responses,
/// even for unsupported languages.
#[test]
fn format_integration_fields_always_present() {
    let dir = format_test_dir("fields_present");
    // Cargo.toml needed for .rs test
    fs::write(dir.join("Cargo.toml"), "[package]\nname = \"test\"").unwrap();

    // Test 1: write to a .md file (unsupported language for formatting)
    let md_target = dir.join("format_fields_check.md");
    let _ = fs::remove_file(&md_target);

    let mut aft = AftProcess::spawn();
    aft.configure_format_on_edit(&dir);
    let resp = aft.send(&format!(
        r#"{{"id":"fmt-6a","command":"write","file":{},"content":"Hello markdown"}}"#,
        crate::helpers::json_string(&md_target.display())
    ));

    assert_eq!(
        resp["success"], true,
        "write to .md should succeed: {:?}",
        resp
    );
    // `formatted` must be present (not missing from JSON)
    assert!(
        resp.get("formatted").is_some(),
        "formatted field must be present even for unsupported languages: {:?}",
        resp
    );
    assert_eq!(resp["formatted"], false);
    assert_eq!(resp["format_skipped_reason"], "unsupported_language");

    // Test 2: write to a .rs file — formatted field present with value true (if rustfmt available)
    let rs_target = dir.join("format_fields_check.rs");
    let _ = fs::remove_file(&rs_target);

    let resp2 = aft.send(&format!(
        r#"{{"id":"fmt-6b","command":"write","file":{},"content":"fn main() {{}}"}}"#,
        crate::helpers::json_string(&rs_target.display())
    ));

    assert_eq!(
        resp2["success"], true,
        "write to .rs should succeed: {:?}",
        resp2
    );
    assert!(
        resp2.get("formatted").is_some(),
        "formatted field must be present for .rs files: {:?}",
        resp2
    );

    let _ = fs::remove_file(&md_target);
    let _ = fs::remove_file(&rs_target);
    let status = aft.shutdown();
    assert!(status.success());
}

// ============================================================================
// validate_full integration tests
// ============================================================================

/// Send mutation without validate param → no validation_errors in response.
#[test]
fn validate_full_default_no_errors() {
    let dir = format_test_dir("validate_default");
    let target = dir.join("validate_default.rs");
    let _ = fs::remove_file(&target);

    let mut aft = AftProcess::spawn();
    let resp = aft.send(&format!(
        r#"{{"id":"val-1","command":"write","file":{},"content":"fn main() {{}}"}}"#,
        crate::helpers::json_string(&target.display())
    ));

    assert_eq!(resp["success"], true, "write should succeed: {:?}", resp);
    // Without validate:"full", validation_errors should not be present (or empty)
    let has_errors = resp.get("validation_errors").is_some()
        && !resp["validation_errors"].is_null()
        && resp["validation_errors"]
            .as_array()
            .is_some_and(|a| !a.is_empty());
    assert!(
        !has_errors,
        "validation_errors should be absent or empty without validate:full, got: {:?}",
        resp
    );
    // validate_skipped_reason should not be present
    assert!(
        resp.get("validate_skipped_reason").is_none() || resp["validate_skipped_reason"].is_null(),
        "validate_skipped_reason should not be present without validate:full: {:?}",
        resp
    );

    let _ = fs::remove_file(&target);
    let status = aft.shutdown();
    assert!(status.success());
}

#[test]
fn validate_on_edit_full_from_config_runs_checker() {
    if !cfg!(unix) {
        eprintln!("SKIP: tsc stub test requires unix executable permissions");
        return;
    }

    let dir = format_test_dir("validate_config_full");
    let target = dir.join("validate_config_full.ts");
    let _ = fs::remove_file(&target);
    fs::write(dir.join("tsconfig.json"), "{}\n").unwrap();
    install_tsc_stub(&dir, "validate_config_full.ts");

    let mut aft = AftProcess::spawn();
    let cfg = aft.send(
        &json!({
            "id": "cfg-val-full",
            "command": "configure",
            "harness": "opencode",
            "project_root": dir,
            "config": user_config(serde_json::json!({
                "validate_on_edit": "full",
                "checker": { "typescript": "tsc" }
            }))
        })
        .to_string(),
    );
    assert_eq!(cfg["success"], true, "configure should succeed: {:?}", cfg);

    let resp = aft.send(&format!(
        r#"{{"id":"val-config-full","command":"write","file":{},"content":"const x: number = \"oops\";\n"}}"#,
        crate::helpers::json_string(&target.display())
    ));

    assert_eq!(resp["success"], true, "write should succeed: {:?}", resp);
    let errors = resp["validation_errors"]
        .as_array()
        .expect("validate_on_edit:full should include validation_errors");
    assert!(
        !errors.is_empty(),
        "broken TypeScript types should produce validation_errors: {:?}",
        resp
    );

    let _ = fs::remove_file(&target);
    let status = aft.shutdown();
    assert!(status.success());
}

#[test]
fn validate_on_edit_off_from_config_skips_checker() {
    let dir = format_test_dir("validate_config_off");
    let target = dir.join("validate_config_off.ts");
    let _ = fs::remove_file(&target);
    fs::write(dir.join("tsconfig.json"), "{}\n").unwrap();
    #[cfg(unix)]
    install_tsc_stub(&dir, "validate_config_off.ts");

    let mut aft = AftProcess::spawn();
    let cfg = aft.send(
        &json!({
            "id": "cfg-val-off",
            "command": "configure",
            "harness": "opencode",
            "project_root": dir,
        })
        .to_string(),
    );
    assert_eq!(cfg["success"], true, "configure should succeed: {:?}", cfg);

    let resp = aft.send(&format!(
        r#"{{"id":"val-config-off","command":"write","file":{},"content":"const x: number = \"oops\";\n"}}"#,
        crate::helpers::json_string(&target.display())
    ));

    assert_eq!(resp["success"], true, "write should succeed: {:?}", resp);
    let has_errors = resp.get("validation_errors").is_some()
        && !resp["validation_errors"].is_null()
        && resp["validation_errors"]
            .as_array()
            .is_some_and(|errors| !errors.is_empty());
    assert!(
        !has_errors,
        "validate_on_edit:off should not produce validation_errors: {:?}",
        resp
    );

    let _ = fs::remove_file(&target);
    let status = aft.shutdown();
    assert!(status.success());
}

/// Send write with validate:"full" on a .rs file with valid code → if cargo available,
/// response includes validation_errors: [] (empty).
#[test]
fn validate_full_with_checker() {
    if !is_on_path("cargo") {
        eprintln!("SKIP: cargo not on PATH");
        return;
    }

    let dir = format_test_dir("validate_valid");
    let target = dir.join("validate_valid.rs");
    // Write valid Rust code
    let _ = fs::remove_file(&target);

    let mut aft = AftProcess::spawn();
    let resp = aft.send(&format!(
        r#"{{"id":"val-2","command":"write","file":{},"content":"fn main() {{}}","validate":"full"}}"#,
        crate::helpers::json_string(&target.display())
    ));

    assert_eq!(resp["success"], true, "write should succeed: {:?}", resp);
    // With validate:"full" and cargo available, we should get validation fields
    // Note: cargo check on an isolated .rs file may skip or error (no Cargo.toml),
    // so we check that the validate path was invoked (either errors or skip reason present)
    let has_validation =
        resp.get("validation_errors").is_some() || resp.get("validate_skipped_reason").is_some();
    assert!(
        has_validation,
        "validate:full should produce validation_errors or validate_skipped_reason: {:?}",
        resp
    );

    let _ = fs::remove_file(&target);
    let status = aft.shutdown();
    assert!(status.success());
}

/// Send write with validate:"full" on a .txt file → validate_skipped_reason: "unsupported_language"
#[test]
fn validate_full_unsupported_language() {
    let dir = format_test_dir("validate_unsupported");
    let target = dir.join("validate_unsupported.txt");
    let _ = fs::remove_file(&target);

    let mut aft = AftProcess::spawn();
    let resp = aft.send(&format!(
        r#"{{"id":"val-3","command":"write","file":{},"content":"hello","validate":"full"}}"#,
        crate::helpers::json_string(&target.display())
    ));

    assert_eq!(resp["success"], true, "write should succeed: {:?}", resp);
    assert_eq!(
        resp["validate_skipped_reason"], "unsupported_language",
        "should skip validation for unsupported language: {:?}",
        resp
    );

    let _ = fs::remove_file(&target);
    let status = aft.shutdown();
    assert!(status.success());
}

#[test]
fn validate_full_no_checker_configured() {
    let dir = format_test_dir("validate_no_checker_configured");
    let target = dir.join("validate_no_checker_configured.ts");
    let _ = fs::remove_file(&target);

    let mut aft = AftProcess::spawn();
    let resp = aft.send(&format!(
        r#"{{"id":"val-3b","command":"write","file":{},"content":"const x = 1;\n","validate":"full"}}"#,
        crate::helpers::json_string(&target.display())
    ));

    assert_eq!(resp["success"], true, "write should succeed: {:?}", resp);
    assert_eq!(
        resp["validate_skipped_reason"], "no_checker_configured",
        "should skip validation without checker config: {:?}",
        resp
    );

    let _ = fs::remove_file(&target);
    let status = aft.shutdown();
    assert!(status.success());
}

#[cfg(unix)]
#[test]
fn validate_full_nonzero_without_diagnostics_reports_error() {
    let dir = format_test_dir("validate_checker_error_no_diagnostics");
    fs::write(dir.join("tsconfig.json"), "{}\n").unwrap();
    let target = dir.join("validate_checker_error_no_diagnostics.ts");
    let _ = fs::remove_file(&target);

    let bin_dir = dir.join("node_modules").join(".bin");
    fs::create_dir_all(&bin_dir).unwrap();
    let stub = bin_dir.join("tsc");
    fs::write(
        &stub,
        "#!/bin/sh\necho 'failed before diagnostics' >&2\nexit 2\n",
    )
    .unwrap();
    use std::os::unix::fs::PermissionsExt;
    fs::set_permissions(&stub, fs::Permissions::from_mode(0o755)).unwrap();
    warm_executable(&stub, &["--version"]);

    let path = prepend_path(&std::ffi::OsString::new(), &dir);
    let mut aft = AftProcess::spawn_with_env(&[("PATH", path.as_os_str())]);
    let cfg = aft.configure(&dir);
    assert_eq!(cfg["success"], true, "configure should succeed: {:?}", cfg);
    let resp = aft.send(&format!(
        r#"{{"id":"val-error-no-diag","command":"write","file":{},"content":"const x = 1;\n","validate":"full"}}"#,
        crate::helpers::json_string(&target.display())
    ));

    assert_eq!(resp["success"], true, "write should succeed: {:?}", resp);
    assert_eq!(
        resp["validate_skipped_reason"], "error",
        "non-zero checker without parseable diagnostics must not look clean: {:?}",
        resp
    );

    let _ = fs::remove_file(&target);
    let status = aft.shutdown();
    assert!(status.success());
}

#[test]
fn validate_full_checker_not_installed() {
    let dir = format_test_dir("validate_checker_not_installed");
    fs::write(dir.join("tsconfig.json"), "{}\n").unwrap();
    let target = dir.join("validate_checker_not_installed.ts");
    let _ = fs::remove_file(&target);

    let path = prepend_path(&std::ffi::OsString::new(), &dir);
    let mut aft = AftProcess::spawn_with_env(&[
        ("PATH", path.as_os_str()),
        ("AFT_DISABLE_WELL_KNOWN_LOOKUP", std::ffi::OsStr::new("1")),
    ]);
    let cfg = aft.configure(&dir);
    assert_eq!(cfg["success"], true, "configure should succeed: {:?}", cfg);
    let resp = aft.send(&format!(
        r#"{{"id":"val-3c","command":"write","file":{},"content":"const x = 1;\n","validate":"full"}}"#,
        crate::helpers::json_string(&target.display())
    ));

    assert_eq!(resp["success"], true, "write should succeed: {:?}", resp);
    assert_eq!(
        resp["validate_skipped_reason"], "checker_not_installed",
        "should report missing checker binary: {:?}",
        resp
    );

    let _ = fs::remove_file(&target);
    let status = aft.shutdown();
    assert!(status.success());
}

/// Send write with validate:"full" via add_import to verify validate param flows through
/// all mutation commands (not just write).
#[test]
fn validate_full_flows_through_add_import() {
    let dir = format_test_dir("validate_import");
    let target = dir.join("validate_import.rs");
    // Create a valid Rust file first
    fs::write(&target, "fn main() {\n    println!(\"hello\");\n}\n").unwrap();

    let mut aft = AftProcess::spawn();
    let resp = aft.send(&format!(
        r#"{{"id":"val-4","command":"add_import","file":{},"module":"std::collections::HashMap","validate":"full"}}"#,
        crate::helpers::json_string(&target.display())
    ));

    assert_eq!(
        resp["success"], true,
        "add_import should succeed: {:?}",
        resp
    );
    // Validate param should flow through — either errors or skip reason
    let has_validation =
        resp.get("validation_errors").is_some() || resp.get("validate_skipped_reason").is_some();
    assert!(
        has_validation,
        "validate:full should produce validation_errors or validate_skipped_reason via add_import: {:?}",
        resp
    );

    let _ = fs::remove_file(&target);
    let status = aft.shutdown();
    assert!(status.success());
}