curie-build 0.7.0

The Curie build tool
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
use crate::compile::{
    flat_package_src_dirs, flat_package_test_dirs, javac_release_arg, KOTLIN_COMPILER_COORD,
    KOTLIN_STDLIB_COORD,
};
use crate::incremental::{
    self, javac_version, needs_recompile, walk_files, write_javac_version_stamp, CompileStatus,
    Inputs, Stamp,
};
use crate::jar::classpath_string;
use crate::{build, descriptor};
use crate::build::central_repos;
use anyhow::{bail, Context, Result};
use curie_deps::resolver::{resolve, DepEntry, ResolveOptions};
use std::path::{Path, PathBuf};
use std::process::Command;
const JUNIT_STANDALONE_COORD: &str =
    "org.junit.platform:junit-platform-console-standalone";

/// Stamp file (under `target/`) recording the canonical test source set from
/// the last successful test compile, used to detect added/removed test sources
/// that mtime comparison can't see.
const TEST_SOURCE_SET_STAMP: &str = ".test-sources";

/// Compile test sources and run all tests via the JUnit Platform Console
/// Standalone launcher.
///
/// `classes_dir`        — directory containing already-compiled production classes.
/// `dep_jars`           — resolved production dependency JARs.
/// `kotlin_stdlib_jars` — Kotlin stdlib JARs (empty for Java-only projects).
/// `resources_dir`      — production resources dir if it exists (`src/main/resources`
///                        or top-level `resources/`), otherwise `None`.
/// `test_resources_dir` — test resources dir if it exists (`src/test/resources` or
///                        top-level `test-resources/`), otherwise `None`.
/// `filter`             — optional class-name pattern passed to `--include-classname`.
///
/// Returns `Ok(())` when all tests pass (or when no test sources exist).
/// Returns `Err` when compilation fails or any test fails.
///
/// The argument count exceeds clippy's default cap (7) because the test
/// pipeline genuinely needs each piece independently — all of them flow
/// in from a `CompileOutput` plus the user's CLI flags, and bundling them
/// into an intermediate struct adds plumbing without making the API
/// clearer.  Revisit if the list grows further.
#[allow(clippy::too_many_arguments)]
pub fn run_tests(
    project_root: &Path,
    desc: &descriptor::Descriptor,
    classes_dir: &Path,
    dep_jars: &[PathBuf],
    kotlin_stdlib_jars: &[PathBuf],
    groovy_jars: &[PathBuf],
    resources_dir: Option<&Path>,
    test_resources_dir: Option<&Path>,
    filter: Option<&str>,
    offline: bool,
    coverage: bool,
    extra_cp: &[PathBuf],
) -> Result<()> {
    // --- discover test sources -----------------------------------------------
    let (java_test_sources, kotlin_test_sources) = discover_test_sources(project_root);
    let groovy_test_sources = discover_groovy_test_sources(project_root);

    let all_test_sources: Vec<PathBuf> = {
        let mut v = java_test_sources.clone();
        v.extend(kotlin_test_sources.iter().cloned());
        v.extend(groovy_test_sources.iter().cloned());
        v.sort();
        v.dedup();
        v
    };

    if all_test_sources.is_empty() {
        crate::parallel::emit(&crate::style::neutral("Tests", "no test sources found"));
        return Ok(());
    }

    let has_kotlin_tests = !kotlin_test_sources.is_empty();
    let has_java_tests   = !java_test_sources.is_empty();
    let has_groovy_tests = !groovy_test_sources.is_empty();

    // --- resolve JUnit standalone launcher -----------------------------------
    let extra_repos = build::extra_repos(desc);

    // spock-core 2.x is built against JUnit Platform 1.x.  The default
    // standalone runner is JUnit 6 (Platform 2.x) which has an incompatible
    // `--scan-class-path` discovery protocol.  When Spock is enabled and the
    // user hasn't overridden the version, use the latest 1.x standalone.
    let junit_version = if desc.spock.enabled() && !desc.test.junit_platform_version_is_user_set() {
        "1.14.4"
    } else {
        desc.test.junit_platform_version()
    };
    let standalone_jar = resolve_standalone(&extra_repos, offline, junit_version)
        .context("failed to resolve JUnit Platform Console Standalone")?;

    // --- resolve test-scoped dependencies ------------------------------------
    // Build effective BOM list for test resolution:
    //   [bom-imports] (lower priority) + [test-bom-imports] (higher priority).
    // Later entries in the list win, so prod BOMs come first.
    let test_bom_gavs = desc.test_bom_gavs()?;

    let test_dep_jars = if desc.test_dependencies.is_empty() {
        vec![]
    } else {
        let pairs: Vec<DepEntry> = desc
            .test_dependencies
            .iter()
            .map(|(k, v)| DepEntry { key: k, version: v.version(), repo_id: v.repository(), exclusions: v.exclusions(), classifier: None, allow_version_conflict: v.allow_version_conflict() })
            .collect();

        resolve(
            &pairs,
            &ResolveOptions {
                default_repos: central_repos(),
                named_repos: extra_repos.clone(),
                progress: crate::parallel::try_get_sink().is_none(),
                bom_imports: test_bom_gavs.clone(),
                offline,
                skip_version_ranges: false,
                // User-declared [test-dependencies]: fail on a major-version
                // conflict unless the coordinate sets allowVersionConflict.
                error_on_version_conflict: true,
            },
        )
        .context("test dependency resolution failed")?
    };

    // --- resolve spock-core (when [spock] is configured) ---------------------
    // spock-core's transitive deps (junit-platform-engine, opentest4j, …)
    // carry no explicit version — they are managed by the embedded junit-bom
    // which spock-bom imports.  We pass spock-bom as an extra bom_import so
    // those managed versions land in global_managed and the resolver can
    // resolve the full transitive closure.
    let spock_jars: Vec<PathBuf> = if desc.spock.enabled() {
        let spock_version = desc.spock.version();
        let spock_bom = curie_deps::Gav::from_key_version(
            "org.spockframework:spock-bom",
            spock_version,
        )?;
        let mut spock_bom_imports = test_bom_gavs.clone();
        spock_bom_imports.push(spock_bom);

        let jars = resolve(
            &[DepEntry {
                key: "org.spockframework:spock-core",
                version: spock_version,
                repo_id: None,
                exclusions: vec![],
                classifier: None,
                allow_version_conflict: false,
            }],
            &ResolveOptions {
                default_repos: central_repos(),
                named_repos: extra_repos.clone(),
                progress: crate::parallel::try_get_sink().is_none(),
                bom_imports: spock_bom_imports,
                offline,
                skip_version_ranges: false, error_on_version_conflict: false,
            },
        )
        .context("Spock resolution failed")?;
        crate::parallel::emit(&crate::style::resolve("Resolve Spock", &format!("{} JAR(s)", jars.len())));
        jars
    } else {
        vec![]
    };

    // --- resolve Kotlin compiler for test compilation (when needed) ----------
    let test_kotlin_stdlib_jars: Vec<PathBuf>;
    let test_kotlin_compiler_jars: Vec<PathBuf>; // all resolved JARs for -cp invocation

    if has_kotlin_tests && kotlin_stdlib_jars.is_empty() {
        // Production had no Kotlin sources but tests do — resolve now.
        let kver = desc.kotlin.version();
        let kotlin_jars = resolve(
            &[
                DepEntry { key: KOTLIN_COMPILER_COORD, version: kver, repo_id: None, exclusions: vec![], classifier: None, allow_version_conflict: false },
                DepEntry { key: KOTLIN_STDLIB_COORD, version: kver, repo_id: None, exclusions: vec![], classifier: None, allow_version_conflict: false },
            ],
            &ResolveOptions {
                default_repos: central_repos(),
                named_repos: extra_repos.clone(),
                progress: crate::parallel::try_get_sink().is_none(),
                bom_imports: test_bom_gavs.clone(),
                offline,
                skip_version_ranges: false, error_on_version_conflict: false,
            },
        )
        .context("Kotlin compiler/stdlib resolution failed (test phase)")?;

        let stdlib: Vec<PathBuf> = kotlin_jars
            .iter()
            .filter(|p| {
                p.file_name()
                    .map(|f| !f.to_string_lossy().starts_with("kotlin-compiler-embeddable"))
                    .unwrap_or(true)
            })
            .cloned()
            .collect();

        test_kotlin_compiler_jars = kotlin_jars;
        test_kotlin_stdlib_jars = stdlib;
    } else if has_kotlin_tests {
        // Re-resolve compiler (all transitive deps) — stdlib already in kotlin_stdlib_jars.
        let kver = desc.kotlin.version();
        let kotlin_jars = resolve(
            &[
                DepEntry { key: KOTLIN_COMPILER_COORD, version: kver, repo_id: None, exclusions: vec![], classifier: None, allow_version_conflict: false },
                DepEntry { key: KOTLIN_STDLIB_COORD, version: kver, repo_id: None, exclusions: vec![], classifier: None, allow_version_conflict: false },
            ],
            &ResolveOptions {
                default_repos: central_repos(),
                named_repos: extra_repos.clone(),
                progress: false,
                bom_imports: test_bom_gavs.clone(),
                offline,
                skip_version_ranges: false, error_on_version_conflict: false,
            },
        )
        .context("Kotlin compiler resolution failed (test phase)")?;

        test_kotlin_compiler_jars = kotlin_jars;
        // Stdlib was already resolved in the prod compile phase.
        test_kotlin_stdlib_jars = kotlin_stdlib_jars.to_vec();
    } else {
        test_kotlin_compiler_jars = Vec::new();
        test_kotlin_stdlib_jars = kotlin_stdlib_jars.to_vec();
    }

    // --- resolve test-annotation-processor jars ----------------------------
    // Test compile sees BOTH production processors (so Lombok applied to
    // production code is also applied to test code referencing the same
    // annotations) AND test-only processors.
    let mut test_ap_coords: Vec<(&str, &str)> = desc.ap_pairs();
    test_ap_coords.extend(desc.test_ap_pairs());
    let (test_ap_jars, test_ap_on_cp_jars) = if test_ap_coords.is_empty() {
        (Vec::new(), Vec::new())
    } else {
        let ap_entries: Vec<DepEntry> = test_ap_coords
            .iter()
            .map(|(k, v)| DepEntry { key: k, version: v, repo_id: None, exclusions: vec![], classifier: None, allow_version_conflict: false })
            .collect();
        let jars = resolve(
            &ap_entries,
            &ResolveOptions {
                default_repos: central_repos(),
                named_repos: extra_repos.clone(),
                progress: crate::parallel::try_get_sink().is_none(),
                bom_imports: test_bom_gavs.clone(),
                offline,
                skip_version_ranges: false, error_on_version_conflict: false,
            },
        )
        .context("test annotation-processor resolution failed")?;

        // Resolve each on-compile-classpath coord individually for its
        // transitive closure (second resolve hits ~/.m2; cheap).
        let on_cp_coords = desc.test_ap_on_compile_classpath_coords();
        let mut on_cp_jars: Vec<PathBuf> = Vec::new();
        for coord in on_cp_coords {
            let version = test_ap_coords
                .iter()
                .find(|(k, _)| *k == coord)
                .map(|(_, v)| *v)
                .expect("on-cp coord must be in test_ap_coords");
            let single = resolve(
                &[DepEntry { key: coord, version, repo_id: None, exclusions: vec![], classifier: None, allow_version_conflict: false }],
                &ResolveOptions {
                    default_repos: central_repos(),
                    named_repos: extra_repos.clone(),
                    progress: false,
                    bom_imports: test_bom_gavs.clone(),
                    offline,
                    skip_version_ranges: false, error_on_version_conflict: false,
                },
            )
            .with_context(|| {
                format!("test annotation-processor classpath resolution failed for {}", coord)
            })?;
            on_cp_jars.extend(single);
        }
        (jars, on_cp_jars)
    };

    // --- compile test sources (incremental) ----------------------------------
    let test_classes_dir = project_root.join("target").join("test-classes");
    std::fs::create_dir_all(&test_classes_dir)
        .context("failed to create target/test-classes")?;

    let toml_path = project_root.join("Curie.toml");
    let test_manifest_path = project_root.join("target").join(".test-classes.toml");

    // Pre-compile prune (same scheme as production compile).
    let old_test_manifest = crate::class_manifest::load(&test_manifest_path)?;
    let current_test_sources_set: std::collections::HashSet<String> = all_test_sources
        .iter()
        .filter_map(|p| p.canonicalize().ok())
        .map(|p| p.to_string_lossy().into_owned())
        .collect();
    let canonical_test_target = project_root
        .join("target")
        .canonicalize()
        .ok()
        .and_then(|p| p.to_str().map(String::from));
    let pre_pruned_tests: usize = match &old_test_manifest {
        Some(old) => {
            let stale = crate::class_manifest::stale_classes(
                old,
                None,
                &current_test_sources_set,
                canonical_test_target.as_deref(),
            );
            crate::class_manifest::delete_classes(&test_classes_dir, &stale)?
        }
        None => 0,
    };

    // Source-set tracking (all languages): catches a test source added with a
    // preserved-old mtime, or a deletion, which mtime comparison alone misses.
    let test_source_set = incremental::canonical_source_set(&all_test_sources);
    let test_source_set_prev = incremental::load_source_set(
        &incremental::source_set_stamp_path(&project_root.join("target"), TEST_SOURCE_SET_STAMP),
    );
    let test_source_set_changed =
        incremental::source_set_changed(test_source_set_prev.as_ref(), &test_source_set);

    let test_compile_status = if pre_pruned_tests > 0 {
        CompileStatus::StaleClasses
    } else if test_source_set_changed {
        CompileStatus::SourceSetChanged
    } else if old_test_manifest
        .as_ref()
        .is_some_and(|m| crate::class_manifest::has_missing_classes(m, &test_classes_dir))
    {
        // A recorded test class vanished from target/test-classes — recompile to
        // regenerate it rather than reporting the incomplete output up to date.
        CompileStatus::MissingClasses
    } else {
        needs_recompile(
            &all_test_sources,
            &test_classes_dir,
            &toml_path,
            &project_root.join("target"),
            &[classes_dir],
        )
    };
    let needs_recompile_tests = test_compile_status.needs_recompile();

    if needs_recompile_tests {
        let reason = if pre_pruned_tests > 0 {
            "  [stale classes removed]".to_string()
        } else if test_source_set_changed {
            "  [source set changed]".to_string()
        } else {
            format!("  [{}]", test_compile_status.reason())
        };
        crate::parallel::emit(&crate::style::active(
            "Compile tests",
            &format!("{} source file(s){}", all_test_sources.len(), reason),
        ));

        // Shared classpath for both phases:
        //   production classes + src/main/resources + prod deps + test deps
        //   + standalone launcher + kotlin stdlib + extras
        let mut shared_cp: Vec<PathBuf> = Vec::new();
        shared_cp.push(classes_dir.to_path_buf());
        if let Some(rd) = resources_dir {
            shared_cp.push(rd.to_path_buf());
        }
        shared_cp.extend_from_slice(dep_jars);
        shared_cp.extend_from_slice(&test_dep_jars);
        shared_cp.extend_from_slice(extra_cp);
        shared_cp.extend_from_slice(&test_ap_on_cp_jars);
        shared_cp.extend_from_slice(&test_kotlin_stdlib_jars);
        shared_cp.extend_from_slice(groovy_jars);
        shared_cp.extend_from_slice(&spock_jars);
        shared_cp.push(standalone_jar.clone());

        if has_kotlin_tests {
            // Phase 1: kotlinc — compile all .kt + .java test sources together.
            let mut kotlinc = Command::new("java");
            kotlinc.arg("--enable-native-access=ALL-UNNAMED");
            kotlinc.arg("-cp").arg(classpath_string(&test_kotlin_compiler_jars));
            kotlinc.arg("org.jetbrains.kotlin.cli.jvm.K2JVMCompiler");
            kotlinc.arg("-no-stdlib").arg("-no-reflect");
            kotlinc.arg("-module-name").arg(kotlin_test_module_name(desc));
            kotlinc.arg("-d").arg(&test_classes_dir);

            if !shared_cp.is_empty() {
                kotlinc.arg("-cp").arg(classpath_string(&shared_cp));
            }

            for src in &kotlin_test_sources {
                kotlinc.arg(src);
            }
            for src in &java_test_sources {
                kotlinc.arg(src);
            }

            let status = crate::proc::spawn_cmd(&mut kotlinc)
                .context("failed to invoke kotlinc for test compilation")?;

            if !status.success() {
                bail!("Kotlin test compilation failed");
            }
        }

        if has_java_tests {
            // Phase 2: javac — re-compile Java test sources.
            let wrapper_jar = crate::wrapper::ensure()?;
            let mut javac = Command::new("java");
            javac.arg("-jar").arg(&wrapper_jar);
            javac.arg("--curie-manifest-out").arg(&test_manifest_path);
            if let Some(release) = javac_release_arg(desc)? {
                javac.arg("--release").arg(release);
            }
            if desc.java.preview_enabled() {
                javac.arg("--enable-preview");
            }
            javac
                .arg("-g")
                .arg("-d")
                .arg(&test_classes_dir);

            // Classpath for compiling Java tests: test-classes (kotlin bytecode
            // from phase 1) + shared_cp.
            let mut compile_cp: Vec<PathBuf> = Vec::new();
            if has_kotlin_tests {
                compile_cp.push(test_classes_dir.clone());
            }
            compile_cp.extend_from_slice(&shared_cp);
            javac.arg("-cp").arg(classpath_string(&compile_cp));

            // Annotation-processor path + generated-test-sources directory.
            if !test_ap_jars.is_empty() {
                let gen_dir = project_root
                    .join("target")
                    .join("generated-test-sources")
                    .join("annotations");
                std::fs::create_dir_all(&gen_dir).with_context(|| {
                    format!("failed to create {}", gen_dir.display())
                })?;
                javac.arg("-processorpath").arg(classpath_string(&test_ap_jars));
                javac.arg("-s").arg(&gen_dir);
            }
            for (key, value) in desc.flat_test_ap_options() {
                javac.arg(format!("-A{}={}", key, value));
            }

            for src in &java_test_sources {
                javac.arg(src);
            }

            let status = crate::proc::spawn_cmd(&mut javac)
                .context("failed to invoke java — is a JRE installed?")?;

            if !status.success() {
                bail!("test compilation failed");
            }

            // Post-compile prune for Java test classes.
            if let Some(old) = &old_test_manifest {
                if let Some(new) = crate::class_manifest::load(&test_manifest_path)? {
                    let stale = crate::class_manifest::stale_classes(
                        old, Some(&new), &current_test_sources_set, None,
                    );
                    let n = crate::class_manifest::delete_classes(&test_classes_dir, &stale)?;
                    if n > 0 {
                        crate::parallel::emit(&crate::style::stale(
                            "Stale tests",
                            &format!("removed {} orphaned class file{}", n, if n == 1 { "" } else { "s" }),
                        ));
                    }
                }
            }
        }

        if has_groovy_tests {
            // Groovy test phase: compile all .groovy test sources.
            // Java test sources (if any) are compiled by the Java phase above so
            // they produce a .classes.toml manifest and get full AP support.
            // test_classes_dir is added to the compiler classpath so Groovy test
            // code can reference Java test types from the same module.
            let groovy_cp_jars: Vec<PathBuf> = {
                if groovy_jars.is_empty() {
                    // Groovy tests exist but production had no groovy sources
                    // → resolve the Groovy runtime now.
                    use crate::compile::GROOVY_COORD;
                    resolve(
                        &[DepEntry { key: GROOVY_COORD, version: desc.groovy.version(), repo_id: None, exclusions: vec![], classifier: None, allow_version_conflict: false }],
                        &ResolveOptions {
                            default_repos: central_repos(),
                            named_repos: extra_repos.clone(),
                            progress: crate::parallel::try_get_sink().is_none(),
                            bom_imports: test_bom_gavs.clone(),
                            offline,
                            skip_version_ranges: false, error_on_version_conflict: false,
                        },
                    )
                    .context("Groovy test compiler resolution failed")?
                } else {
                    groovy_jars.to_vec()
                }
            };
            // Spock AST transforms are loaded by the groovyc JVM process
            // itself, so spock-core and ALL its transitive deps (incl. opentest4j,
            // junit-platform-*) must be on the process -cp alongside groovy.jar.
            // shared_cp already contains all of these — use it as the process cp
            // (excluding the standalone launcher jar which is not a compile dep).
            let groovyc_process_cp: Vec<PathBuf> = {
                let mut cp = groovy_cp_jars.clone();
                cp.extend(shared_cp.iter().filter(|p| {
                    !p.file_name()
                        .map(|f| f.to_string_lossy().starts_with("junit-platform-console-standalone"))
                        .unwrap_or(false)
                }).cloned());
                cp
            };

            let mut groovyc = Command::new("java");
            if let Some(arg) = crate::compile::groovy_target_bytecode_arg(desc) {
                groovyc.arg(arg);
            }
            groovyc.arg("-cp").arg(classpath_string(&groovyc_process_cp));
            groovyc.arg("org.codehaus.groovy.tools.FileSystemCompiler");
            groovyc.arg("-d").arg(&test_classes_dir);
            let gcp = crate::compile::groovyc_compiler_classpath(
                &shared_cp,
                &groovy_cp_jars,
                if has_java_tests { Some(&test_classes_dir) } else { None },
            );
            if !gcp.is_empty() {
                groovyc.arg("--classpath").arg(classpath_string(&gcp));
            }
            for src in &groovy_test_sources { groovyc.arg(src); }
            let status = crate::proc::spawn_cmd(&mut groovyc)
                .context("failed to invoke groovyc for test compilation")?;
            if !status.success() {
                bail!("Groovy test compilation failed");
            }
        }

        // Record the JDK version used so that a future upgrade triggers a rebuild.
        if let Ok(version) = javac_version() {
            write_javac_version_stamp(&project_root.join("target"), &version)?;
        }

        // Stamp the canonical test source set so the next build detects
        // additions/deletions that leave no surviving mtime to compare against.
        incremental::write_source_set(
            &incremental::source_set_stamp_path(&project_root.join("target"), TEST_SOURCE_SET_STAMP),
            &test_source_set,
        )?;
    } else {
        crate::parallel::emit(&crate::style::up_to_date("Compile tests"));
    }

    // --- skip if stamp is newer than all inputs ------------------------------
    let stamp_path = project_root.join("target").join(".test-stamp");

    if filter.is_none() && !needs_test_run(&all_test_sources, classes_dir, &toml_path, &stamp_path, resources_dir, test_resources_dir) {
        crate::parallel::emit(&crate::style::up_to_date("Tests"));
        return Ok(());
    }

    // --- run tests -----------------------------------------------------------
    // Classpath for running tests:
    //   test classes + production classes + src/main/resources + src/test/resources
    //   + prod deps + test deps + kotlin stdlib
    // (standalone is provided as -jar, not on -cp)
    let mut run_cp: Vec<PathBuf> = Vec::new();
    run_cp.push(test_classes_dir.clone());
    run_cp.push(classes_dir.to_path_buf());
    if let Some(rd) = resources_dir {
        run_cp.push(rd.to_path_buf());
    }
    if let Some(trd) = test_resources_dir {
        run_cp.push(trd.to_path_buf());
    }
    run_cp.extend_from_slice(dep_jars);
    run_cp.extend_from_slice(&test_dep_jars);
    run_cp.extend_from_slice(extra_cp);
    run_cp.extend_from_slice(&test_kotlin_stdlib_jars);
    run_cp.extend_from_slice(groovy_jars);
    run_cp.extend_from_slice(&spock_jars);

    crate::parallel::emit("");

    // --- prepare per-test result directories ---------------------------------
    let sidecar_path = project_root.join("target").join("build.tests.json");
    let output_dir   = project_root.join("target").join("test-output");

    if output_dir.exists() {
        std::fs::remove_dir_all(&output_dir)
            .context("failed to clear target/test-output")?;
    }
    std::fs::create_dir_all(&output_dir)
        .context("failed to create target/test-output")?;

    // JUnit Platform's default class-name filter matches *Test/*Tests and
    // similar Java/Kotlin conventions but skips Groovy *Spec classes.  When
    // Spock is enabled, broaden the filter to include `.*Spec` names.
    let effective_filter = if filter.is_some() {
        filter
    } else if !spock_jars.is_empty() {
        Some(".*Tests?$|^Test.*|.*TestCase$|.*Spec$")
    } else {
        None
    };

    let runner_jar = crate::test_runner::ensure_runner_jar(&standalone_jar)
        .context("failed to prepare Curie test runner")?;

    let agent_coords = desc.test_dep_java_agent_coords();
    let agent_jars   = crate::java_agent::find_agent_jars(&agent_coords, &run_cp);

    // --- coverage: resolve JaCoCo agent and prepare exec output path ---------
    let coverage_dir  = project_root.join("target").join("coverage");
    let coverage_exec = coverage_dir.join("jacoco.exec");
    let jacoco_agent_jar: Option<PathBuf> = if coverage {
        std::fs::create_dir_all(&coverage_dir)
            .context("failed to create target/coverage")?;
        let default_repos = build::central_repos();
        let extra_repos   = build::extra_repos(desc);
        let jar = crate::coverage::resolve_agent_jar(&default_repos, &extra_repos, offline)
            .context("failed to resolve JaCoCo agent for coverage")?;
        crate::parallel::emit(&crate::style::resolve("Coverage", "JaCoCo agent"));
        Some(jar)
    } else {
        None
    };

    // Build extra JVM args (e.g. JaCoCo agent for coverage).
    let mut extra_jvm_args: Vec<String> = Vec::new();
    if let Some(ref agent_jar) = jacoco_agent_jar {
        extra_jvm_args.push(crate::coverage::agent_jvm_arg(agent_jar, &coverage_exec));
    }

    let mut java = crate::test_runner::build_runner_command(
        &runner_jar,
        &standalone_jar,
        &classpath_string(&run_cp),
        &sidecar_path,
        &output_dir,
        effective_filter,
        desc.java.preview_enabled(),
        &agent_jars,
        &extra_jvm_args,
    );

    let status = crate::proc::spawn_cmd(&mut java)
        .context("failed to invoke java — is a JRE installed?")?;

    crate::parallel::emit("");

    if !status.success() {
        bail!("tests failed");
    }

    // --- coverage report generation ------------------------------------------
    if coverage && coverage_exec.exists() {
        let default_repos = build::central_repos();
        let extra_repos   = build::extra_repos(desc);
        let cli_jar = crate::coverage::resolve_cli_jar(&default_repos, &extra_repos, offline)
            .context("failed to resolve JaCoCo CLI for report generation")?;

        // Collect source roots for the HTML report (production sources only).
        let source_dirs = discover_source_roots(project_root);

        let summary = crate::coverage::generate_report(
            &cli_jar,
            &coverage_exec,
            classes_dir,
            &source_dirs,
            &coverage_dir,
        )?;

        let html_index = coverage_dir.join("html").join("index.html");
        let rel_html = html_index
            .strip_prefix(project_root)
            .unwrap_or(&html_index);

        crate::parallel::emit(&crate::style::active("Coverage", &summary.summary_line()));
        crate::parallel::emit(&crate::style::info(
            "Report",
            &rel_html.display().to_string(),
        ));
    }

    // --- write stamp on success ----------------------------------------------
    std::fs::write(&stamp_path, b"")
        .with_context(|| format!("failed to write test stamp {}", stamp_path.display()))?;

    Ok(())
}

/// Collect production source root directories for the coverage report.
///
/// Checks Maven-style (`src/main/java`, `src/main/kotlin`, `src/main/groovy`)
/// and flat-package source directories under `src/`.
fn discover_source_roots(project_root: &Path) -> Vec<PathBuf> {
    use crate::compile::flat_package_src_dirs;

    let mut roots: Vec<PathBuf> = Vec::new();

    let maven_java = project_root.join("src").join("main").join("java");
    if maven_java.exists() {
        roots.push(maven_java);
    }
    let maven_kotlin = project_root.join("src").join("main").join("kotlin");
    if maven_kotlin.exists() {
        roots.push(maven_kotlin);
    }
    let maven_groovy = project_root.join("src").join("main").join("groovy");
    if maven_groovy.exists() {
        roots.push(maven_groovy);
    }
    roots.extend(flat_package_src_dirs(project_root));

    roots
}

// ---------------------------------------------------------------------------
// Source discovery
// ---------------------------------------------------------------------------

/// Collect test source files from all supported layout roots.
///
/// Returns `(java_sources, kotlin_sources)` — each sorted and deduplicated.
///
/// **Maven-style layouts:**
/// - Separate tree: `src/test/java` — all `*.java` files.
/// - Separate tree: `src/test/kotlin` — all `*.kt` files.
/// - `src/main/java` and `src/main/kotlin` are production roots; files there
///   named `*Test.java` / `*Spec.java` are production classes (Maven-compatible).
///
/// **Curie flat-package layouts:**
/// - Co-located unit tests: each dot-named directory under `src/` — files
///   ending in `Test.java/kt`, `Tests.java/kt`, or `Spec.java/kt`.
/// - Integration tests: each dot-named directory under `tests/` — all
///   `*.java` and `*.kt` files.
fn discover_test_sources(project_root: &Path) -> (Vec<PathBuf>, Vec<PathBuf>) {
    let mut java_sources: Vec<PathBuf> = Vec::new();
    let mut kotlin_sources: Vec<PathBuf> = Vec::new();

    // --- Maven-style Java: separate test tree src/test/java -----------------
    let test_java_src = project_root.join("src").join("test").join("java");
    if test_java_src.exists() {
        let separate: Vec<PathBuf> = walk_files(&test_java_src)
            .filter(|e| e.file_name().to_string_lossy().ends_with(".java"))
            .map(|e| e.into_path())
            .collect();
        java_sources.extend(separate);
    }

    // --- Maven-style Kotlin: separate test tree src/test/kotlin -------------
    let test_kotlin_src = project_root.join("src").join("test").join("kotlin");
    if test_kotlin_src.exists() {
        let separate: Vec<PathBuf> = walk_files(&test_kotlin_src)
            .filter(|e| e.file_name().to_string_lossy().ends_with(".kt"))
            .map(|e| e.into_path())
            .collect();
        kotlin_sources.extend(separate);
    }

    // --- Flat-package: co-located unit tests in src/<dot.pkg>/ --------------
    for pkg_dir in flat_package_src_dirs(project_root) {
        let colocated_java: Vec<PathBuf> = walk_files(&pkg_dir)
            .filter(|e| {
                let name = e.file_name().to_string_lossy();
                name.ends_with("Test.java")
                    || name.ends_with("Tests.java")
                    || name.ends_with("Spec.java")
            })
            .map(|e| e.into_path())
            .collect();
        java_sources.extend(colocated_java);

        let colocated_kotlin: Vec<PathBuf> = walk_files(&pkg_dir)
            .filter(|e| {
                let name = e.file_name().to_string_lossy();
                name.ends_with("Test.kt")
                    || name.ends_with("Tests.kt")
                    || name.ends_with("Spec.kt")
            })
            .map(|e| e.into_path())
            .collect();
        kotlin_sources.extend(colocated_kotlin);
    }

    // --- Flat-package: integration tests in tests/<dot.pkg>/ ----------------
    for pkg_dir in flat_package_test_dirs(project_root) {
        let java_int: Vec<PathBuf> = walk_files(&pkg_dir)
            .filter(|e| e.file_name().to_string_lossy().ends_with(".java"))
            .map(|e| e.into_path())
            .collect();
        java_sources.extend(java_int);

        let kotlin_int: Vec<PathBuf> = walk_files(&pkg_dir)
            .filter(|e| e.file_name().to_string_lossy().ends_with(".kt"))
            .map(|e| e.into_path())
            .collect();
        kotlin_sources.extend(kotlin_int);
    }

    // Deduplicate by canonical path and sort for determinism.
    java_sources.sort();
    java_sources.dedup();
    kotlin_sources.sort();
    kotlin_sources.dedup();

    (java_sources, kotlin_sources)
}

/// Discover Groovy test sources — mirrors [`discover_test_sources`] for `.groovy` files.
///
/// `src/main/groovy` is a production root; files there named `*Test.groovy` / `*Spec.groovy`
/// are production classes (Maven-compatible).  The co-located convention applies only to
/// flat-package roots under `src/<dot.pkg>/`.
fn discover_groovy_test_sources(project_root: &Path) -> Vec<PathBuf> {
    let mut sources: Vec<PathBuf> = Vec::new();

    // Separate test tree src/test/groovy/
    let test_groovy = project_root.join("src").join("test").join("groovy");
    if test_groovy.exists() {
        let all: Vec<PathBuf> = walk_files(&test_groovy)
            .filter(|e| e.file_name().to_string_lossy().ends_with(".groovy"))
            .map(|e| e.into_path())
            .collect();
        sources.extend(all);
    }

    // Flat-package: co-located tests in src/<dot.pkg>/
    for pkg_dir in flat_package_src_dirs(project_root) {
        let colocated: Vec<PathBuf> = walk_files(&pkg_dir)
            .filter(|e| {
                let name = e.file_name().to_string_lossy();
                name.ends_with("Test.groovy")
                    || name.ends_with("Tests.groovy")
                    || name.ends_with("Spec.groovy")
            })
            .map(|e| e.into_path())
            .collect();
        sources.extend(colocated);
    }

    // Flat-package: integration tests in tests/<dot.pkg>/
    for pkg_dir in flat_package_test_dirs(project_root) {
        let all: Vec<PathBuf> = walk_files(&pkg_dir)
            .filter(|e| e.file_name().to_string_lossy().ends_with(".groovy"))
            .map(|e| e.into_path())
            .collect();
        sources.extend(all);
    }

    sources.sort();
    sources.dedup();
    sources
}

// ---------------------------------------------------------------------------
// JUnit standalone resolution
// ---------------------------------------------------------------------------

fn resolve_standalone(
    extra_repos: &[curie_deps::repo::Repository],
    offline: bool,
    junit_version: &str,
) -> Result<PathBuf> {
    let coord = format!("{}:{}", JUNIT_STANDALONE_COORD, junit_version);
    // coord is "group:artifact:version" — split off the version for the resolver.
    // The resolver takes (key, version) pairs where key = "group:artifact".
    let jars = resolve(
        &[DepEntry { key: JUNIT_STANDALONE_COORD, version: junit_version, repo_id: None, exclusions: vec![], classifier: None, allow_version_conflict: false }],
        &ResolveOptions {
            default_repos: central_repos(),
            named_repos: extra_repos.to_vec(),
            progress: false,
            bom_imports: vec![],
            offline,
            skip_version_ranges: false, error_on_version_conflict: false,
        },
    )
    .with_context(|| format!("failed to resolve {}", coord))?;

    // The standalone JAR is self-contained (fat JAR) — only one JAR is expected.
    // Filter to the standalone JAR itself (not transitive deps, which it
    // already bundles internally).
    jars.into_iter()
        .find(|p| {
            p.file_name()
                .map(|f| {
                    let s = f.to_string_lossy();
                    s.starts_with("junit-platform-console-standalone")
                })
                .unwrap_or(false)
        })
        .with_context(|| {
            format!(
                "junit-platform-console-standalone-{}.jar not found after resolution",
                junit_version
            )
        })
}

// ---------------------------------------------------------------------------
// Incremental run check
// ---------------------------------------------------------------------------

/// Returns true when tests need to be executed.
///
/// Inputs that invalidate the stamp:
///   - test sources
///   - Curie.toml
///   - any file under `target/classes` (production recompile happened)
///   - any file under `src/main/resources` or `src/test/resources`
///
/// The stamp (`target/.test-stamp`) is written after every successful
/// full test run.  A filtered run (`curie test --filter`) never writes the
/// stamp and always bypasses this check so that a partial run cannot mask
/// failures in the untested portion.
fn needs_test_run(
    test_sources: &[PathBuf],
    classes_dir: &Path,
    toml_path: &Path,
    stamp_path: &Path,
    resources_dir: Option<&Path>,
    test_resources_dir: Option<&Path>,
) -> bool {
    let mut inputs = Inputs::new();
    inputs
        .add_paths(test_sources)
        .add_file(toml_path)
        .add_dir(classes_dir)
        .add_dir_opt(resources_dir)
        .add_dir_opt(test_resources_dir);
    !Stamp::of(stamp_path).covers(&inputs)
}

/// Module name passed to `kotlinc -module-name` for test compilation,
/// matching kotlin-maven-plugin's default `testModuleName`
/// (`${project.artifactId}-test`) so the emitted
/// `META-INF/<name>-test.kotlin_module` matches `mvn`'s output
/// (`maven.rs::build_project` sets `artifactId` to `desc.buildable_name()`).
fn kotlin_test_module_name(desc: &descriptor::Descriptor) -> String {
    format!("{}-test", desc.buildable_name())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    #[test]
    fn kotlin_test_module_name_appends_test_suffix() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(
            dir.path().join("Curie.toml"),
            "[application]\nname = \"hello-kotlin\"\nversion = \"0.1.0\"\nmainClass = \"Main\"\n\
             [java]\nreleaseVersion = \"21\"\n",
        )
        .unwrap();
        let desc = descriptor::load(dir.path()).unwrap();

        assert_eq!(kotlin_test_module_name(&desc), "hello-kotlin-test");
    }

    // --- discover_test_sources -----------------------------------------------

    #[test]
    fn maven_layout_test_named_files_are_not_test_sources() {
        // A file like LoadTest.java in src/main/java is a production class.
        // The co-located convention does NOT apply to Maven layout roots.
        let dir = tempfile::tempdir().unwrap();
        let main_java = dir.path().join("src").join("main").join("java").join("com").join("example");
        fs::create_dir_all(&main_java).unwrap();
        fs::write(main_java.join("LoadTest.java"), b"public class LoadTest {}").unwrap();
        fs::write(main_java.join("SmokeTests.java"), b"public class SmokeTests {}").unwrap();
        fs::write(main_java.join("OpenApiSpec.java"), b"public class OpenApiSpec {}").unwrap();

        let (java, _kotlin) = discover_test_sources(dir.path());
        assert!(
            java.is_empty(),
            "test-named files in src/main/java must not be discovered as test sources; got: {java:?}"
        );
    }

    #[test]
    fn separate_test_tree_java_is_discovered() {
        let dir = tempfile::tempdir().unwrap();
        let test_java = dir.path().join("src").join("test").join("java").join("com").join("example");
        fs::create_dir_all(&test_java).unwrap();
        fs::write(test_java.join("GreeterTest.java"), b"public class GreeterTest {}").unwrap();
        fs::write(test_java.join("HelperUtil.java"), b"public class HelperUtil {}").unwrap();

        let (java, _kotlin) = discover_test_sources(dir.path());
        assert_eq!(java.len(), 2, "all files in src/test/java are test sources; got: {java:?}");
    }

    #[test]
    fn flat_package_colocated_tests_are_discovered() {
        let dir = tempfile::tempdir().unwrap();
        let pkg = dir.path().join("src").join("com.example");
        fs::create_dir_all(&pkg).unwrap();
        fs::write(pkg.join("Greeter.java"), b"package com.example; class Greeter {}").unwrap();
        fs::write(pkg.join("GreeterTest.java"), b"package com.example; class GreeterTest {}").unwrap();
        fs::write(pkg.join("GreeterSpec.java"), b"package com.example; class GreeterSpec {}").unwrap();

        let (java, _kotlin) = discover_test_sources(dir.path());
        assert_eq!(java.len(), 2, "only *Test.java and *Spec.java from flat-package are test sources; got: {java:?}");
        assert!(java.iter().any(|p| p.ends_with("GreeterTest.java")));
        assert!(java.iter().any(|p| p.ends_with("GreeterSpec.java")));
    }

    #[test]
    fn groovy_colocated_tests_not_from_maven_layout() {
        let dir = tempfile::tempdir().unwrap();
        let main_groovy = dir.path().join("src").join("main").join("groovy").join("com").join("example");
        fs::create_dir_all(&main_groovy).unwrap();
        fs::write(main_groovy.join("GreeterSpec.groovy"), b"package com.example; class GreeterSpec {}").unwrap();

        let sources = discover_groovy_test_sources(dir.path());
        assert!(
            sources.is_empty(),
            "test-named files in src/main/groovy must not be test sources; got: {sources:?}"
        );
    }

    #[test]
    fn groovy_separate_test_tree_is_discovered() {
        let dir = tempfile::tempdir().unwrap();
        let test_groovy = dir.path().join("src").join("test").join("groovy").join("com").join("example");
        fs::create_dir_all(&test_groovy).unwrap();
        fs::write(test_groovy.join("GreeterSpec.groovy"), b"package com.example; class GreeterSpec {}").unwrap();

        let sources = discover_groovy_test_sources(dir.path());
        assert_eq!(sources.len(), 1, "src/test/groovy files must be test sources; got: {sources:?}");
    }
}