alef 0.66.0

Opinionated polyglot binding generator for Rust libraries
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
use super::*;

#[test]
fn test_scaffold_ffi_with_core_import() {
    let config = test_config();
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Ffi]).unwrap();
    let files = language_files(&all_files);
    assert_eq!(files.len(), 2);
    let cargo_toml = &files[0].content;
    assert!(cargo_toml.contains("serde = \"1\""));
    assert!(cargo_toml.contains("serde_json"));
    assert!(cargo_toml.contains("my-lib ="));
    let cmake = &files[1].content;
    assert!(cmake.contains("find_package"));
    assert!(cmake.contains("my-lib-ffi::my-lib-ffi"));
}

#[test]
fn test_scaffold_ffi_deps_are_pinned() {
    let config = test_config();
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Ffi]).unwrap();
    let files = language_files(&all_files);
    let cargo_toml = &files[0].content;
    assert!(
        cargo_toml.contains("cbindgen = \"0.29\""),
        "cbindgen should be pinned to a specific minor for reproducible headers"
    );
    assert!(cargo_toml.contains("serde = \"1\""));
    assert!(cargo_toml.contains("ignored = [\"ahash\", \"serde\", \"serde_json\", \"tokio\"]"));
    assert!(cargo_toml.contains("serde_json = \"1\""));
    assert!(cargo_toml.contains("tokio = "));
    assert!(cargo_toml.contains("[dev-dependencies]"));
    assert!(cargo_toml.contains("tempfile = \"3\""));
}

#[test]
fn test_scaffold_ffi_merges_extra_dependencies() {
    let mut config = test_config();
    let mut deps: std::collections::HashMap<String, toml::Value> = Default::default();
    deps.insert(
        "my-lib-http".to_string(),
        toml::Value::try_from(toml::Table::from_iter([(
            "path".to_string(),
            toml::Value::String("../my-lib-http".to_string()),
        )]))
        .unwrap(),
    );
    deps.insert(
        "my-lib-graphql".to_string(),
        toml::Value::try_from(toml::Table::from_iter([(
            "path".to_string(),
            toml::Value::String("../my-lib-graphql".to_string()),
        )]))
        .unwrap(),
    );
    deps.insert("anyhow".to_string(), toml::Value::String("1.0".to_string()));
    config.extra_dependencies = deps;

    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Ffi]).unwrap();
    let files = language_files(&all_files);
    let cargo_toml = &files[0].content;
    assert!(
        cargo_toml.contains("my-lib-http = { path = \"../my-lib-http\" }"),
        "scaffold should emit my-lib-http path dep, got:\n{cargo_toml}"
    );
    assert!(
        cargo_toml.contains("my-lib-graphql = { path = \"../my-lib-graphql\" }"),
        "scaffold should emit my-lib-graphql path dep, got:\n{cargo_toml}"
    );
    assert!(
        cargo_toml.contains("anyhow = \"1.0\""),
        "scaffold should emit anyhow string dep, got:\n{cargo_toml}"
    );
}

#[test]
fn test_scaffold_ffi_injects_version_for_workspace_member_deps() {
    use std::fs;
    use tempfile::TempDir;

    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    fs::write(
        root.join("Cargo.toml"),
        r#"
[workspace]
resolver = "2"
members = ["crates/my-lib-core", "crates/my-lib-http"]

[workspace.package]
version = "4.2.0"
"#,
    )
    .unwrap();
    for member in ["my-lib-core", "my-lib-http"] {
        fs::create_dir_all(root.join(format!("crates/{member}/src"))).unwrap();
        fs::write(root.join(format!("crates/{member}/src/lib.rs")), "pub fn f() {}").unwrap();
        fs::write(
            root.join(format!("crates/{member}/Cargo.toml")),
            format!("[package]\nname = \"{member}\"\nversion.workspace = true\n"),
        )
        .unwrap();
    }

    let mut config = test_config();
    config.workspace_root = Some(root.to_path_buf());
    let mut deps: std::collections::HashMap<String, toml::Value> = Default::default();
    for member in ["my-lib-core", "my-lib-http"] {
        deps.insert(
            member.to_string(),
            toml::Value::Table(toml::map::Map::from_iter([(
                "path".to_string(),
                toml::Value::String(format!("../{member}")),
            )])),
        );
    }
    deps.insert("anyhow".to_string(), toml::Value::String("1.0".to_string()));
    config.extra_dependencies = deps;

    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Ffi]).unwrap();
    let files = language_files(&all_files);
    let cargo_toml = &files[0].content;

    for member in ["my-lib-core", "my-lib-http"] {
        assert!(
            cargo_toml.contains(&format!("{member} = {{ path = \"../{member}\", version = \"4.2.0\" }}")),
            "FFI manifest must version-inject internal workspace dep {member}; got:\n{cargo_toml}"
        );
    }
    assert!(
        cargo_toml.contains("anyhow = \"1.0\""),
        "external dep must be emitted unchanged, got:\n{cargo_toml}"
    );
}

#[test]
fn test_scaffold_ffi_target_dep_overrides_emit_cfg_blocks() {
    // [target.'cfg(...)'.dependencies] tables. This is the only shape that
    use crate::core::config::FfiTargetDepOverride;
    use crate::core::config::languages::FfiConfig;

    let mut config = test_config();
    config.features = vec!["full".to_string(), "ocr".to_string()];
    config.ffi = Some(FfiConfig {
        prefix: None,
        error_style: "last_error".to_string(),
        header_name: None,
        lib_name: None,
        visitor_callbacks: false,
        features: None,
        extra_features: vec![],
        serde_rename_all: None,
        exclude_functions: vec![],
        exclude_types: vec![],
        capsule_types: Default::default(),
        rename_fields: Default::default(),
        plugin_error_constructor: None,
        target_dep_overrides: vec![FfiTargetDepOverride {
            cfg: "all(target_os = \"android\", target_arch = \"x86_64\")".to_string(),
            features: vec!["android-target".to_string()],
            default_features: true,
        }],
    });

    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Ffi]).unwrap();
    let files = language_files(&all_files);
    let cargo_toml = &files[0].content;

    // The default branch is wrapped in cfg(not(<override-cfg>)).
    assert!(
        cargo_toml.contains("[target.'cfg(not(all(target_os = \"android\", target_arch = \"x86_64\")))'.dependencies]"),
        "expected default-branch target table with cfg(not(...)), got:\n{cargo_toml}"
    );
    assert!(
        cargo_toml.contains("my-lib = { path = \"../..\", version = \"0.1.0\", features = [\"full\", \"ocr\"] }"),
        "default branch should keep the full feature set, got:\n{cargo_toml}"
    );

    assert!(
        cargo_toml.contains("[target.'cfg(all(target_os = \"android\", target_arch = \"x86_64\"))'.dependencies]"),
        "expected override target table, got:\n{cargo_toml}"
    );
    assert!(
        cargo_toml.contains("my-lib = { path = \"../..\", version = \"0.1.0\", features = [\"android-target\"] }"),
        "override branch should emit android-target feature, got:\n{cargo_toml}"
    );

    assert!(cargo_toml.contains("[dependencies]\nahash = \"0.8\""));
    assert!(
        !cargo_toml.contains("\n[dependencies]\nmy-lib ="),
        "core-crate dep should have moved out of [dependencies], got:\n{cargo_toml}"
    );
}

/// Regression test for the dropped `[crates.ffi.target_dep_overrides].default_features`
/// key: xberg's `windows-target` / `macos-intel-target` overrides set
/// `default_features = false` to drop the core crate's own `default = ["tokio-runtime",
/// "simd-utf8"]` set on those targets, alongside swapping in the reduced feature list.
/// Before `FfiTargetDepOverride` gained this field the key was silently discarded, so the
/// override target block always inherited the core dep's default features regardless of
/// what the config said.
#[test]
fn test_scaffold_ffi_target_dep_overrides_default_features_false_drops_defaults() {
    use crate::core::config::FfiTargetDepOverride;
    use crate::core::config::languages::FfiConfig;

    let mut config = test_config();
    config.features = vec!["full".to_string(), "ocr".to_string()];
    config.ffi = Some(FfiConfig {
        prefix: None,
        error_style: "last_error".to_string(),
        header_name: None,
        lib_name: None,
        visitor_callbacks: false,
        features: None,
        extra_features: vec![],
        serde_rename_all: None,
        exclude_functions: vec![],
        exclude_types: vec![],
        capsule_types: Default::default(),
        rename_fields: Default::default(),
        plugin_error_constructor: None,
        target_dep_overrides: vec![FfiTargetDepOverride {
            cfg: "target_os = \"windows\"".to_string(),
            features: vec!["windows-target".to_string()],
            default_features: false,
        }],
    });

    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Ffi]).unwrap();
    let files = language_files(&all_files);
    let cargo_toml = &files[0].content;

    assert!(
        cargo_toml.contains("[target.'cfg(target_os = \"windows\")'.dependencies]"),
        "expected the windows override target table, got:\n{cargo_toml}"
    );
    assert!(
        cargo_toml.contains(
            "my-lib = { path = \"../..\", version = \"0.1.0\", default-features = false, features = [\"windows-target\"] }"
        ),
        "default_features: false must drop the core dep's default features on the override branch, got:\n{cargo_toml}"
    );
    assert!(
        cargo_toml.contains(
            "[target.'cfg(not(target_os = \"windows\"))'.dependencies]\nmy-lib = { path = \"../..\", version = \"0.1.0\", features = [\"full\", \"ocr\"] }"
        ),
        "the default (non-overridden) branch must keep the full default feature set with no default-features key, got:\n{cargo_toml}"
    );
}

/// Regression test: `cargo-sort` (and hence `poly lint`) orders
/// `[target.'cfg(...)'.dependencies]` tables alphabetically by the raw cfg
/// predicate string (plain byte-wise comparison), NOT with the default
/// `cfg(not(any(...)))` branch always first. With multiple overrides whose
/// combined cfg is wrapped in `any(...)`, an `all(...)`-prefixed override (as
/// xberg configures for its macOS-Intel target) must sort *before* the
/// `not(any(...))` default branch — `'a'` < `'n'` — while a `target_os = ...`
/// override sorts after it (`'n'` < `'t'`).
#[test]
fn test_scaffold_ffi_target_dep_overrides_sort_all_before_not() {
    use crate::core::config::FfiTargetDepOverride;
    use crate::core::config::languages::FfiConfig;

    let mut config = test_config();
    config.features = vec!["full".to_string(), "ocr".to_string()];
    config.ffi = Some(FfiConfig {
        prefix: None,
        error_style: "last_error".to_string(),
        header_name: None,
        lib_name: None,
        visitor_callbacks: false,
        features: None,
        extra_features: vec![],
        serde_rename_all: None,
        exclude_functions: vec![],
        exclude_types: vec![],
        capsule_types: Default::default(),
        rename_fields: Default::default(),
        plugin_error_constructor: None,
        target_dep_overrides: vec![
            FfiTargetDepOverride {
                cfg: "target_os = \"android\"".to_string(),
                features: vec!["android-target".to_string()],
                default_features: true,
            },
            FfiTargetDepOverride {
                cfg: "target_os = \"windows\"".to_string(),
                features: vec!["windows-target".to_string()],
                default_features: true,
            },
            FfiTargetDepOverride {
                cfg: "all(target_os = \"macos\", target_arch = \"x86_64\")".to_string(),
                features: vec!["macos-intel-target".to_string()],
                default_features: true,
            },
        ],
    });

    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Ffi]).unwrap();
    let files = language_files(&all_files);
    let cargo_toml = &files[0].content;

    let all_pos = cargo_toml
        .find("[target.'cfg(all(target_os = \"macos\", target_arch = \"x86_64\"))'.dependencies]")
        .expect("expected the macOS-Intel `all(...)` override block");
    let not_pos = cargo_toml
        .find("[target.'cfg(not(any(")
        .expect("expected the default `not(any(...))` block");
    let android_pos = cargo_toml
        .find("[target.'cfg(target_os = \"android\")'.dependencies]")
        .expect("expected the android override block");

    assert!(
        all_pos < not_pos,
        "the `all(...)` override must sort BEFORE the `not(...)` default branch; got:\n{cargo_toml}"
    );
    assert!(
        not_pos < android_pos,
        "the `not(...)` default branch must sort before `target_os = \"android\"`; got:\n{cargo_toml}"
    );
    toml::from_str::<toml::Value>(cargo_toml).expect("generated FFI Cargo.toml must be valid TOML");
}

#[test]
fn test_scaffold_ffi_emits_android_target_aggregate_feature() {
    use std::fs;
    use tempfile::TempDir;

    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nresolver = \"2\"\nmembers = [\"crates/kreuzberg\"]\n",
    )
    .unwrap();
    fs::create_dir_all(root.join("crates/kreuzberg/src")).unwrap();
    fs::write(root.join("crates/kreuzberg/src/lib.rs"), "pub fn f() {}").unwrap();
    fs::write(
        root.join("crates/kreuzberg/Cargo.toml"),
        r#"[package]
name = "kreuzberg"
version = "0.1.0"

[features]
android-target = ["no-ort-target", "ocr"]
no-ort-target = ["pdf", "html"]
pdf = []
html = []
ocr = []
embeddings = []
"#,
    )
    .unwrap();

    let mut config = test_config();
    config.name = "kreuzberg".to_string();
    config.workspace_root = Some(root.to_path_buf());
    config.sources = vec![PathBuf::from("crates/kreuzberg/src/lib.rs")];
    config.features = vec![
        "full".to_string(),
        "pdf".to_string(),
        "ocr".to_string(),
        "html".to_string(),
        "embeddings".to_string(),
    ];

    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Ffi]).unwrap();
    let files = language_files(&all_files);
    let cargo_toml = &files[0].content;

    assert!(
        cargo_toml.contains(r#"android-target = ["kreuzberg/android-target", "html", "ocr", "pdf"]"#),
        "FFI manifest must emit the android-target aggregate feature; got:\n{cargo_toml}"
    );
    toml::from_str::<toml::Value>(cargo_toml).expect("generated Cargo.toml must be valid TOML");
}

#[test]
fn test_scaffold_ffi_omits_android_target_when_core_lacks_it() {
    use std::fs;
    use tempfile::TempDir;

    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nresolver = \"2\"\nmembers = [\"crates/kreuzberg\"]\n",
    )
    .unwrap();
    fs::create_dir_all(root.join("crates/kreuzberg/src")).unwrap();
    fs::write(root.join("crates/kreuzberg/src/lib.rs"), "pub fn f() {}").unwrap();
    fs::write(
        root.join("crates/kreuzberg/Cargo.toml"),
        "[package]\nname = \"kreuzberg\"\nversion = \"0.1.0\"\n\n[features]\npdf = []\nocr = []\n",
    )
    .unwrap();

    let mut config = test_config();
    config.name = "kreuzberg".to_string();
    config.workspace_root = Some(root.to_path_buf());
    config.sources = vec![PathBuf::from("crates/kreuzberg/src/lib.rs")];
    config.features = vec!["pdf".to_string(), "ocr".to_string()];

    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Ffi]).unwrap();
    let files = language_files(&all_files);
    let cargo_toml = &files[0].content;

    assert!(
        !cargo_toml.contains("android-target"),
        "FFI manifest must not emit android-target when core crate lacks it; got:\n{cargo_toml}"
    );
}

#[test]
fn test_scaffold_go_production_format() {
    let config = test_config();
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Go]).unwrap();
    let files = language_files(&all_files);
    assert_eq!(files.len(), 3);
    let content = &files[0].content;
    assert!(content.contains("go 1.26"));
    assert!(!content.contains("require ("));
}

#[test]
fn test_scaffold_go_injects_capsule_require() {
    let config = minimal_config_from_toml(
        r#"
[crates.go]
module = "github.com/test/my-lib"

[crates.go.capsule_types.Language]
host_type = "*tree_sitter.Language"
package = "github.com/tree-sitter/go-tree-sitter"
package_version = "v0.25.0"
"#,
    );
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Go]).unwrap();
    let files = language_files(&all_files);
    let go_mod = files
        .iter()
        .find(|f| f.path.to_string_lossy().ends_with("go.mod"))
        .expect("go.mod must be emitted");
    assert!(
        go_mod.content.contains("github.com/tree-sitter/go-tree-sitter v0.25.0"),
        "go.mod must require the go-tree-sitter capsule package, got:\n{}",
        go_mod.content
    );
    assert!(go_mod.content.contains("require ("), "go.mod must have a require block");
}

#[test]
fn test_scaffold_go_uses_inert_module_when_unconfigured() {
    let config = minimal_config_from_toml(
        r#"
[crates.go]
module_major = 5
"#,
    );
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Go]).unwrap();
    let files = language_files(&all_files);
    let go_mod = files
        .iter()
        .find(|f| f.path == Path::new("packages/go/v5/go.mod"))
        .expect("go.mod must be emitted");

    assert!(
        go_mod.content.starts_with("module example.invalid/my-lib\n"),
        "unconfigured Go scaffold must use inert example.invalid fallback, got:\n{}",
        go_mod.content
    );
}

#[test]
fn test_scaffold_java_production_features() {
    let config = test_config();
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Java]).unwrap();
    let files = language_files(&all_files);
    assert_eq!(files.len(), 5);
    let content = &files[0].content;
    assert!(content.contains("<properties>"));
    assert!(content.contains("<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>"));
    assert!(content.contains("<dependencies>"));
    assert!(content.contains("<build>"));
    assert!(content.contains("maven-compiler-plugin"));
    assert!(content.contains("maven-surefire-plugin"));
    assert!(content.contains("--enable-native-access=ALL-UNNAMED"));
    assert!(content.contains("-Djava.library.path=${project.basedir}/../../target/release"));
}

#[test]
fn test_scaffold_java_scm_uses_configured_non_github_host() {
    let config = minimal_config_from_toml(
        r#"
[crates.scaffold]
description = "Test library"
license = "MIT"
repository = "https://gitlab.example.com/acme/my-lib"
authors = ["Alice"]
keywords = ["test"]
"#,
    );
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Java]).unwrap();
    let files = language_files(&all_files);
    let pom = files
        .iter()
        .find(|f| f.path == Path::new("packages/java/pom.xml"))
        .expect("pom.xml must be emitted");

    assert!(pom.content.contains("scm:git:git://gitlab.example.com/acme/my-lib.git"));
    assert!(
        pom.content
            .contains("scm:git:ssh://git@gitlab.example.com/acme/my-lib.git")
    );
    assert!(!pom.content.contains("github.com/acme/my-lib"));
}

#[test]
fn test_scaffold_ruby_production_features() {
    let config = test_config();
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Ruby]).unwrap();
    let files = language_files(&all_files);
    // The `spec/<gem>_spec.rb` seed is appended last inside `scaffold_ruby`, so it takes index
    // 6 and pushes `scaffold_ruby_cargo`'s manifest — extended onto the tail by the `Language::
    // Ruby` scaffold arm, and therefore always last overall — from 6 to 7. Every index before
    // it is unchanged. ~keep
    assert_eq!(files.len(), 8);
    let content = &files[0].content;
    assert!(content.contains(r#"spec.required_ruby_version = ">= 3.2.0""#));
    assert!(!content.contains("< 4.0"));
    assert!(content.contains("spec.extensions"));
    assert!(content.contains("README*"));
    assert!(content.contains("LICENSE*"));
    assert!(content.contains("lib/**/*"));
    assert!(content.contains("ext/**/*"));
    assert!(content.contains("sig/**/*"));
    assert!(content.contains("spec.metadata[\"keywords\"]"));
    assert!(content.contains("frozen_string_literal: true"));
    assert!(content.contains("spec.metadata[\"rubygems_mfa_required\"] = \"true\""));
    assert_eq!(files[1].path, PathBuf::from("packages/ruby/.rubocop.yml"));
    assert_eq!(files[2].path, PathBuf::from("packages/ruby/Rakefile"));
    assert!(files[2].content.contains("RbSys::ExtensionTask"));
    assert!(files[2].content.contains("my_lib_rb"));
    assert!(files[2].content.contains("require \"rb_sys/extensiontask\""));
    assert!(files[2].content.contains("MANIFEST_PATH"));
    assert!(files[2].content.contains("--manifest-path"));
    assert!(files[2].content.contains("task compile: \"compile:ruby\""));
    assert_eq!(
        files[3].path,
        PathBuf::from("packages/ruby/ext/my_lib_rb/native/extconf.rb")
    );
    assert!(files[3].content.contains("create_rust_makefile"));
    assert!(files[3].content.contains("rb_sys/mkmf"));
    assert!(
        files[3].content.contains("config.ext_dir = \".\""),
        "extconf.rb must set ext_dir = \".\" so rb_sys finds the sibling Cargo.toml"
    );
    assert_eq!(files[4].path, PathBuf::from("packages/ruby/Gemfile"));
    assert_eq!(files[5].path, PathBuf::from("packages/ruby/Steepfile"));
    assert_eq!(files[6].path, PathBuf::from("packages/ruby/spec/my_lib_spec.rb"));
    assert!(
        !files[6].generated_header,
        "the spec seed must stay create-only so a real suite is never overwritten"
    );
    assert_eq!(
        files[7].path,
        PathBuf::from("packages/ruby/ext/my_lib_rb/native/Cargo.toml")
    );
    assert!(files[7].content.contains("magnus"));
    assert!(
        files[7].content.contains("path = \"../src/lib.rs\""),
        "Ruby Cargo.toml [lib] must set path to the binding source crate"
    );
}

/// Regression: the generated gemspec must declare `sorbet-runtime` as a runtime
/// dependency so projects running `bundle install --without development` can load
/// the `native.rb` wrapper, which unconditionally `require 'sorbet-runtime'`.
/// Missing the dep caused `LoadError: cannot load such file -- sorbet-runtime`
/// in CI E2E runs.
#[test]
fn test_scaffold_ruby_gemspec_includes_sorbet_runtime_dependency() {
    let config = test_config();
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Ruby]).unwrap();
    let files = language_files(&all_files);
    let gemspec = &files[0].content;
    assert!(
        gemspec.contains("sorbet-runtime"),
        "gemspec must add sorbet-runtime as a runtime dependency; got:\n{gemspec}"
    );
    assert!(
        gemspec.contains("spec.add_dependency \"sorbet-runtime\""),
        "gemspec must use spec.add_dependency (not add_development_dependency) for sorbet-runtime; got:\n{gemspec}"
    );
    assert!(
        gemspec.contains("~> 0.5"),
        "sorbet-runtime dependency must carry a ~> 0.5 version constraint; got:\n{gemspec}"
    );
}

#[test]
fn test_scaffold_ruby_gemspec_excludes_native_build_artifacts() {
    let all_files = scaffold(&test_api(), &test_config(), &[Language::Ruby]).unwrap();
    let files = language_files(&all_files);
    let gemspec = &files[0].content;

    assert!(gemspec.contains("/(?:target|tmp)/"));
    assert!(gemspec.contains("\\.(?:bundle|so|dylib|dll|o|a|log)\\z"));
    assert!(gemspec.contains("\\.dSYM/"));
}

#[test]
fn test_java_checkstyle_no_cosmetic_checks() {
    let mut config = test_config();
    config.languages = vec![Language::Java];
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Java]).unwrap();
    let files = language_files(&all_files);
    let checkstyle = files.iter().find(|f| f.path.ends_with("checkstyle.xml")).unwrap();
    assert!(!checkstyle.content.contains("WhitespaceAfter"));
    assert!(!checkstyle.content.contains("WhitespaceAround"));
    assert!(!checkstyle.content.contains("GenericWhitespace"));
    assert!(!checkstyle.content.contains("EmptyBlock"));
    assert!(!checkstyle.content.contains("NeedBraces"));
    assert!(!checkstyle.content.contains("MagicNumber"));
    assert!(!checkstyle.content.contains("JavadocPackage"));
    assert!(checkstyle.content.contains("EqualsHashCode"));
    assert!(checkstyle.content.contains("UnusedImports"));
    assert!(checkstyle.content.contains("MethodLength"));
    assert!(checkstyle.content.contains("LineLength"));
    assert!(checkstyle.content.contains("\"200\""));
}

#[test]
fn test_go_golangci_v2_format() {
    let mut config = test_config();
    config.languages = vec![Language::Go];
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Go]).unwrap();
    let files = language_files(&all_files);
    let golangci = files.iter().find(|f| f.path.ends_with(".golangci.yml")).unwrap();
    assert!(golangci.content.contains("version: \"2\""));
    assert!(golangci.content.contains("default: none"));
    assert!(golangci.content.contains("settings:"));
    assert!(!golangci.content.contains("linters-settings:"));
    assert!(golangci.content.contains("errcheck"));
    assert!(golangci.content.contains("govet"));
    assert!(golangci.content.contains("misspell"));
    assert!(golangci.content.contains("locale: US"));
    assert!(golangci.content.contains("exclusions:"));
}

#[test]
fn test_scaffold_csharp_csproj_at_package_root() {
    let config = test_config();
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Csharp]).unwrap();
    let files = language_files(&all_files);
    let csproj = files
        .iter()
        .find(|f| f.path.to_string_lossy().ends_with(".csproj"))
        .expect("C# scaffold must produce a .csproj file");
    assert_eq!(
        csproj.path,
        PathBuf::from("packages/csharp/MyLib/MyLib.csproj"),
        "csproj must be in the namespace subdirectory so runtimes/** glob aligns with FFI staging"
    );
    assert!(
        csproj.content.contains("Microsoft.NET.Sdk"),
        "csproj must use Microsoft.NET.Sdk"
    );
    assert!(
        csproj.content.contains("net10.0"),
        "csproj must target net10.0 by default"
    );
    assert!(
        csproj.content.contains("<RootNamespace>MyLib</RootNamespace>"),
        "csproj must set RootNamespace to the PascalCase project name"
    );
    assert!(
        csproj.content.contains("<Nullable>enable</Nullable>"),
        "csproj must enable nullable reference types"
    );
    assert!(
        !csproj
            .content
            .contains("<GenerateAssemblyInfo>false</GenerateAssemblyInfo>"),
        "csproj must NOT suppress SDK AssemblyInfo so version stays in sync with <Version> tag"
    );
    assert!(
        csproj.content.contains("<Company>Alice</Company>"),
        "csproj must derive Company from the configured authors (first author), \
         not a hardcoded alef literal, to provide SDK-generated AssemblyCompanyAttribute; got:\n{}",
        csproj.content
    );
    assert!(
        csproj.content.contains("<Product>"),
        "csproj must set Product to provide SDK-generated AssemblyProductAttribute"
    );
    assert!(
        !csproj.generated_header,
        "csproj must be scaffold-once (generated_header = false)"
    );
}

#[test]
fn test_render_csharp_csproj_omits_project_url_and_tags_when_unconfigured() {
    // `test_config()` sets `[crates.scaffold] keywords = ["test"]`, which is a
    // genuinely-configured keyword list, not an unconfigured one — using it here
    // would assert PackageTags is absent while the fixture guarantees it's present.
    // `minimal_config_from_toml` carries no `[crates.scaffold]`/`[crates.package_metadata]`
    // at all, so `ScaffoldMeta.homepage`/`.keywords` are genuinely empty. ~keep
    let config = minimal_config_from_toml("");
    let content = render_csharp_csproj(&config, "1.2.3");

    assert!(
        !content.contains("<PackageProjectUrl>"),
        "unconfigured homepage must not invent a PackageProjectUrl: {content}"
    );
    assert!(
        !content.contains("<PackageTags>"),
        "unconfigured keywords must not invent PackageTags: {content}"
    );
}

#[test]
fn test_render_csharp_csproj_includes_project_url_and_tags_when_configured() {
    let config = test_config_from_toml(
        r#"
[crates.package_metadata]
homepage = "https://example.com/my-lib"
keywords = ["llm", "bindings"]
"#,
    );
    let meta_csproj = render_csharp_csproj(&config, "1.2.3");
    let meta_runtime_csproj = render_csharp_runtime_csproj(&config, "1.2.3");

    for content in [&meta_csproj, &meta_runtime_csproj] {
        assert!(
            content.contains("<PackageProjectUrl>https://example.com/my-lib</PackageProjectUrl>"),
            "csproj must carry the configured homepage as PackageProjectUrl: {content}"
        );
        assert!(
            content.contains("<PackageTags>bindings;llm</PackageTags>"),
            "csproj must carry the configured keywords (alphabetised by scaffold_meta) as \
             semicolon-separated PackageTags: {content}"
        );
    }
}

#[test]
fn test_render_csharp_runtime_csproj_derives_company_from_authors() {
    let config = test_config();
    let content = render_csharp_runtime_csproj(&config, "1.2.3");

    assert!(
        content.contains("<Company>Alice</Company>"),
        "runtime csproj must derive Company from the configured authors, not a hardcoded alef literal: {content}"
    );
}

#[test]
fn test_render_csharp_csproj_rid_comment_matches_thin_meta_package_reality() {
    let config = test_config();
    let content = render_csharp_csproj(&config, "1.2.3");

    assert!(
        !content.contains("Native asset resolution at consumer build time is driven by the\n         `runtimes/<rid>/native/` payload baked into the NuGet package"),
        "the RID comment must not claim this package embeds runtimes/<rid>/native/ payload — \
         the surrounding csproj is explicitly a thin meta-package that carries none: {content}"
    );
    assert!(
        content.contains("RID-fallback graph"),
        "the RID comment must describe NuGet's RID-fallback graph as the real resolution mechanism: {content}"
    );
}

#[test]
fn test_render_csharp_csproj_is_thin_meta_package() {
    let config = test_config();
    let content = render_csharp_csproj(&config, "1.2.3");
    assert!(
        !content.contains(r#"Include="runtimes/**""#),
        "meta csproj must NOT pack the fat runtimes/** payload (413 regression): {content}"
    );
    assert!(
        content.contains(r#"Include="runtime.json" Pack="true" PackagePath="/" Condition="Exists('runtime.json')""#),
        "meta csproj must pack the thin runtime.json RID-fallback graph: {content}"
    );
    assert!(
        content.contains(r#"<Target Name="RequireRuntimeJson" BeforeTargets="Pack">"#),
        "meta csproj must hard-error if runtime.json is missing before pack: {content}"
    );
    // so ../../../LICENSE correctly reaches the workspace root.
    assert!(
        content.contains(r#"Include="../../../LICENSE""#),
        "LICENSE path must be ../../../LICENSE to reach workspace root: {content}"
    );
    assert!(
        content.contains("<Version>1.2.3</Version>"),
        "version must be substituted: {content}"
    );
}

#[test]
fn test_render_csharp_csproj_stamps_assembly_version_properties() {
    let config = test_config();
    let content = render_csharp_csproj(&config, "1.9.0-rc.48");

    assert!(
        content.contains("<Version>1.9.0-rc.48</Version>"),
        "Version must carry the full SemVer including prerelease: {content}"
    );
    assert!(
        content.contains("<InformationalVersion>1.9.0-rc.48</InformationalVersion>"),
        "InformationalVersion must carry the full SemVer for diagnostics: {content}"
    );

    assert!(
        content.contains("<AssemblyVersion>1.9.0.0</AssemblyVersion>"),
        "AssemblyVersion must be a 4-component numeric (prerelease stripped): {content}"
    );
    assert!(
        content.contains("<FileVersion>1.9.0.0</FileVersion>"),
        "FileVersion must be a 4-component numeric (prerelease stripped): {content}"
    );

    assert!(
        !content.contains("0.0.0.0"),
        "no version property may be 0.0.0.0: {content}"
    );
}

#[test]
fn test_render_csharp_csproj_advertises_all_published_runtime_identifiers() {
    let config = test_config();
    let content = render_csharp_csproj(&config, "1.9.0-rc.48");

    for rid in [
        "win-x64",
        "win-arm64",
        "linux-x64",
        "linux-arm64",
        "osx-x64",
        "osx-arm64",
    ] {
        assert!(
            content.contains(rid),
            "RuntimeIdentifiers must include {rid}: {content}"
        );
    }
    assert!(
        content.contains("<RuntimeIdentifiers>"),
        "csproj must declare <RuntimeIdentifiers> (plural) for multi-RID packaging: {content}"
    );
    assert!(
        content.contains("<PlatformTarget>AnyCPU</PlatformTarget>"),
        "managed assembly must be AnyCPU so PE Machine header stays processor-neutral: {content}"
    );
    assert!(
        !content.contains("<RuntimeIdentifier Condition="),
        "package csproj must NOT use conditional singular <RuntimeIdentifier> (forces runtime-specific build): {content}"
    );
}

#[test]
fn test_scaffold_csharp_emits_runtime_json_template() {
    let config = test_config();
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Csharp]).unwrap();
    let files = language_files(&all_files);
    let template = files
        .iter()
        .find(|f| f.path.to_string_lossy().ends_with("runtime.json.template"))
        .expect("C# scaffold must emit runtime.json.template so CI can render runtime.json before pack");

    assert_eq!(
        template.path,
        PathBuf::from("packages/csharp/MyLib/runtime.json.template"),
        "runtime.json.template must sit beside the csproj so the RequireRuntimeJson target finds it"
    );
    assert!(
        !template.generated_header,
        "runtime.json.template must be scaffold-once (no DO NOT EDIT header — it is JSON)"
    );
    assert!(
        template.content.contains("{{VERSION}}"),
        "template must keep the literal version placeholder for CI substitution: {}",
        template.content
    );

    let parsed: serde_json::Value =
        serde_json::from_str(&template.content).expect("runtime.json.template must be valid JSON");
    let runtimes = parsed["runtimes"]
        .as_object()
        .expect("runtime.json must have a runtimes object");

    // Each enabled glibc/windows/macos RID pulls in its per-RID native package pinned
    // to the placeholder. Assert against the actual package id so the test tracks config.
    for rid in [
        "win-x64",
        "win-arm64",
        "linux-x64",
        "linux-arm64",
        "osx-x64",
        "osx-arm64",
    ] {
        let rid_entry = runtimes[rid]
            .as_object()
            .unwrap_or_else(|| panic!("RID {rid} entry must be an object"));
        assert_eq!(
            rid_entry.len(),
            1,
            "RID {rid} must map exactly one package id: {}",
            template.content
        );
        let (package_id, dependencies) = rid_entry.iter().next().unwrap();
        let expected_dependency = format!("{package_id}.runtime.{rid}");
        assert_eq!(
            dependencies.get(&expected_dependency).and_then(|value| value.as_str()),
            Some("{{VERSION}}"),
            "RID {rid} must depend on {expected_dependency} pinned to the version placeholder: {}",
            template.content
        );
    }

    // musl RIDs ship no native package of their own; they fall back to the glibc asset.
    assert_eq!(
        runtimes["linux-musl-x64"]["#import"][0].as_str(),
        Some("linux-x64"),
        "linux-musl-x64 must #import linux-x64: {}",
        template.content
    );
    assert_eq!(
        runtimes["linux-musl-arm64"]["#import"][0].as_str(),
        Some("linux-arm64"),
        "linux-musl-arm64 must #import linux-arm64: {}",
        template.content
    );
}

#[test]
fn test_scaffold_csharp_emits_runtime_project_for_meta_split() {
    let config = test_config();
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Csharp]).unwrap();
    let files = language_files(&all_files);
    let runtime = files
        .iter()
        .find(|f| f.path.to_string_lossy().ends_with(".Runtime.csproj"))
        .expect("C# scaffold must emit the native-only .Runtime project (native half of the meta+runtime split)");

    assert_eq!(
        runtime.path,
        PathBuf::from("packages/csharp/MyLib.Runtime/MyLib.Runtime.csproj"),
        "runtime project must be the sibling ../<Namespace>.Runtime the meta csproj references"
    );
    assert!(
        !runtime.generated_header,
        "runtime csproj must be scaffold-once (generated_header = false)"
    );
}

#[test]
fn test_render_csharp_runtime_csproj_is_native_only_per_rid_package() {
    let config = test_config();
    let content = render_csharp_runtime_csproj(&config, "1.9.0-rc.48");

    // PackageId is parameterized per RID so one project packs every enabled RID.
    assert!(
        content.contains("<PackageId>MyLib.runtime.$(PublishedRID)</PackageId>"),
        "runtime package id must be <PackageId>.runtime.$(PublishedRID): {content}"
    );
    assert!(
        content.contains("<PublishedRID Condition=\"'$(PublishedRID)' == ''\">"),
        "runtime csproj must default PublishedRID so a bare pack still evaluates: {content}"
    );
    // Native payload comes from the meta package's staged runtimes/ dir.
    assert!(
        content.contains(
            r#"Include="../MyLib/runtimes/$(PublishedRID)/native/**" Pack="true" PackagePath="runtimes/$(PublishedRID)/native/""#
        ),
        "runtime csproj must pack the meta package's staged native payload under runtimes/<rid>/native/: {content}"
    );
    // Native-only: no managed assembly, deps suppressed, NU5128 tolerated.
    assert!(
        content.contains("<IncludeBuildOutput>false</IncludeBuildOutput>"),
        "runtime package must not ship a managed assembly: {content}"
    );
    assert!(
        content.contains("NU5128"),
        "runtime csproj must suppress the native-only NU5128 warning: {content}"
    );
    // Hard-error guard so an empty native payload fails the pack loudly.
    assert!(
        content.contains(r#"<Target Name="RequireRuntimeAssets" BeforeTargets="Pack">"#),
        "runtime csproj must guard against packing without staged natives: {content}"
    );
    assert!(
        content.contains("<Version>1.9.0-rc.48</Version>"),
        "runtime version must be substituted: {content}"
    );
    assert!(
        content.contains(r#"Include="../../../LICENSE""#),
        "runtime project sits at the same depth as the meta package, so LICENSE is ../../../LICENSE: {content}"
    );
}

#[test]
fn test_scaffold_java_checkstyle_suppressions_use_config_location() {
    let config = test_config();
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Java]).unwrap();
    let files = language_files(&all_files);
    let xml = files.iter().find(|f| f.path.ends_with("checkstyle.xml")).unwrap();
    assert!(
        xml.content.contains(r#"value="checkstyle-suppressions.xml""#),
        "checkstyle suppressions path must be relative to project basedir; content:\n{}",
        xml.content
    );
    let properties = files
        .iter()
        .find(|f| f.path.ends_with("checkstyle.properties"))
        .unwrap();
    assert!(
        properties.content.is_empty(),
        "checkstyle properties must be empty (0 bytes) so end-of-file-fixer leaves it untouched on every regen; a lone trailing newline gets stripped back to empty; content:\n{}",
        properties.content
    );
}

/// alef writes snippet-validation scratch sources under `.alef/snippets/sessions/<hash>/` inside
/// the scaffolded Java project (see `ValidationSession::workspace_directory`). Because
/// `sourceDirectory` is the project basedir, the maven-checkstyle-plugin walks that scratch
/// directory too unless the plugin config excludes it explicitly.
#[test]
fn test_scaffold_java_checkstyle_plugin_excludes_alef_scratch_directory() {
    let config = test_config();
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Java]).unwrap();
    let files = language_files(&all_files);
    let pom = files.iter().find(|f| f.path.ends_with("pom.xml")).unwrap();
    let checkstyle_section = pom
        .content
        .split("<artifactId>maven-checkstyle-plugin</artifactId>")
        .nth(1)
        .and_then(|section| section.split("</plugin>").next())
        .expect("pom.xml must configure maven-checkstyle-plugin");
    assert!(
        checkstyle_section.contains("<excludes>") && checkstyle_section.contains(".alef"),
        "checkstyle plugin must exclude the .alef/ snippet-validation scratch directory so \
         generated snippet scratch sources never fail `mvn compile`; block:\n{checkstyle_section}"
    );
}

/// Regression: `<sourcepath>${project.basedir}</sourcepath>` makes javadoc walk the WHOLE
/// project, including `src/test/java/`. Test sources import JUnit/AssertJ, which are
/// test-scoped and therefore absent from the javadoc classpath, so with the `failOnWarning`
/// this pom also sets, `attach-javadocs` fails outright for any consumer that has Java tests
/// (observed as a `maven-javadoc-plugin:jar (attach-javadocs)` failure over
/// `packages/java/src/test/java/**`). maven-source-plugin already restricts itself the same
/// way for the same reason; javadoc was the one plugin left unrestricted. ~keep
#[test]
fn test_scaffold_java_javadoc_plugin_documents_only_publishable_sources() {
    let config = test_config();
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Java]).unwrap();
    let files = language_files(&all_files);
    let pom = files.iter().find(|f| f.path.ends_with("pom.xml")).unwrap();
    let javadoc_section = pom
        .content
        .split("<artifactId>maven-javadoc-plugin</artifactId>")
        .nth(1)
        .and_then(|section| section.split("</plugin>").next())
        .expect("pom.xml must configure maven-javadoc-plugin");
    assert!(
        javadoc_section.contains("<sourceFileIncludes>"),
        "javadoc plugin must restrict which sources it documents, or a basedir sourcepath \
         sweeps in src/test/java and fails the build; block:\n{javadoc_section}"
    );
    let includes = javadoc_section
        .split("<sourceFileIncludes>")
        .nth(1)
        .and_then(|block| block.split("</sourceFileIncludes>").next())
        .expect("the <sourceFileIncludes> block must be well-formed");
    assert!(
        !includes.contains("src/test/java"),
        "javadoc must never be pointed at test sources; includes:\n{includes}"
    );
    assert!(
        includes.contains("<sourceFileInclude>src/main/java/**/*.java</sourceFileInclude>"),
        "the conventional src/main/java overlay must stay documented; includes:\n{includes}"
    );
}

/// Bite test: builds the scaffolded pom/checkstyle config in a real temp Maven project and
/// runs `mvn -o validate` (the phase checkstyle is bound to). A genuine violation in a "real"
/// binding source must still fail the build; the same violation shape planted under
/// `.alef/snippets/sessions/<hash>/` must not. Skips when `mvn` is unavailable.
#[test]
fn test_scaffold_java_checkstyle_ignores_alef_scratch_but_still_catches_real_violations() {
    if crate::test_support::spawn_from_stable_dir("mvn")
        .arg("--version")
        .output()
        .is_err()
    {
        return;
    }

    let config = test_config();
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Java]).unwrap();
    let files = language_files(&all_files);

    let project_dir = tempfile::tempdir().expect("temp project directory");
    for name in [
        "pom.xml",
        "checkstyle.xml",
        "checkstyle.properties",
        "checkstyle-suppressions.xml",
    ] {
        let file = files
            .iter()
            .find(|f| f.path.ends_with(name))
            .unwrap_or_else(|| panic!("scaffold must emit {name}"));
        std::fs::write(project_dir.path().join(name), &file.content).expect("write scaffolded file");
    }

    let group_id = config.java_group_id();
    let source_root = group_id.split('.').next().unwrap_or("dev");
    let package_dir = project_dir.path().join(source_root).join("scratchcheck");
    std::fs::create_dir_all(&package_dir).expect("package directory");

    let long_line = "x".repeat(220);

    // A genuine style violation in a real binding source must still fail `mvn validate`.
    let real_source = package_dir.join("RealSource.java");
    std::fs::write(
        &real_source,
        format!("package scratchcheck;\n\npublic final class RealSource {{\n    // {long_line}\n}}\n"),
    )
    .expect("write real source");

    let real_violation_output = std::process::Command::new("mvn")
        // Not `-o`: a freshly provisioned CI runner has no cached copy of the checkstyle/
        // source plugins this scaffolded `pom.xml` declares, so `-o` fails on plugin
        // resolution before checkstyle ever runs -- passing the `!success()` assertion
        // below for the wrong reason and never even reaching the one it exists to prove.
        // Runners have real network access; only Maven's own offline flag was blocking it.
        // ~keep
        .args(["-q", "validate"])
        .current_dir(project_dir.path())
        .output()
        .expect("mvn runs");
    assert!(
        !real_violation_output.status.success(),
        "checkstyle must still fail on a genuine violation in a real binding source; stdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&real_violation_output.stdout),
        String::from_utf8_lossy(&real_violation_output.stderr),
    );

    std::fs::remove_file(&real_source).expect("remove real violation source");

    // The same violation shape, planted as snippet-validation scratch, must be ignored.
    let scratch_dir = project_dir.path().join(".alef/snippets/sessions/deadbeefcafefeed");
    std::fs::create_dir_all(&scratch_dir).expect("scratch session directory");
    std::fs::write(
        scratch_dir.join("Example.java"),
        format!("public final class _TestVisitor {{\n    // {long_line}\n}}\n"),
    )
    .expect("write scratch source");

    let scratch_output = std::process::Command::new("mvn")
        // Not `-o`: see the comment on the first `mvn` invocation above -- same reason,
        // and here an unresolved plugin would fail this `success()` assertion for a
        // network problem instead of a real checkstyle regression. ~keep
        .args(["-q", "validate"])
        .current_dir(project_dir.path())
        .output()
        .expect("mvn runs");
    assert!(
        scratch_output.status.success(),
        "checkstyle must ignore .alef snippet-validation scratch sources; stdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&scratch_output.stdout),
        String::from_utf8_lossy(&scratch_output.stderr),
    );
}

#[test]
fn test_ruby_cargo_machete_rb_sys_only() {
    use crate::core::ir::*;

    let config = test_config_from_toml(
        r#"
[crates.ruby]
gem_name = "test_lib"
"#,
    );

    let api = ApiSurface {
        crate_name: "test-lib".to_string(),
        version: "1.0.0".to_string(),
        types: vec![],
        functions: vec![],
        enums: vec![],
        errors: vec![],
        excluded_type_paths: std::collections::HashMap::new(),
        excluded_trait_names: std::collections::HashSet::new(),
        services: vec![],
        handler_contracts: vec![],
        unsupported_public_items: Vec::new(),
    };

    let result = crate::scaffold::languages::scaffold_ruby_cargo(&api, &config);
    assert!(result.is_ok(), "scaffold_ruby_cargo should succeed");

    let files = result.unwrap();
    let cargo_toml_file = files
        .iter()
        .find(|f| f.path.to_string_lossy().ends_with("Cargo.toml"))
        .expect("Should generate Cargo.toml");

    let content = &cargo_toml_file.content;

    assert!(
        content.contains("[package.metadata.cargo-machete]"),
        "Should contain [package.metadata.cargo-machete] section; got:\n{}",
        content
    );

    assert!(
        content.contains("ignored = [\"rb-sys\"]"),
        "Should ignore only rb-sys (pinned for mingw sysroot bug but used transitively through Magnus); got:\n{}",
        content
    );

    let ignored_section = content
        .split("[package.metadata.cargo-machete]")
        .nth(1)
        .and_then(|s| s.split("[lib]").next())
        .unwrap_or("");

    assert!(
        !ignored_section.contains("\"tokio\""),
        "tokio should not be in ignored list (now directly used by NIF code); got:\n{}",
        ignored_section
    );
    assert!(
        !ignored_section.contains("\"async-trait\""),
        "async-trait should not be in ignored list (now directly used by NIF code); got:\n{}",
        ignored_section
    );
    assert!(
        !ignored_section.contains("\"futures\""),
        "futures should not be in ignored list (now directly used by NIF code); got:\n{}",
        ignored_section
    );
    assert!(
        !ignored_section.contains("\"ahash\""),
        "ahash should not be in ignored list (now directly used by NIF code); got:\n{}",
        ignored_section
    );
}