supercov-engine 0.0.55

Rust instrumentation, evidence, attribution, and query engine for Supercov
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
//! The whole JVM lifecycle, through a real build system.
//!
//! The frontend test proves instrumented Java and Kotlin compile and that the
//! JUnit Platform listener attributes what they reach. This proves the parts
//! around it: that a project is copied and rewritten without touching the
//! author's tree, that Supercov's runtime, listener and configuration land
//! where the build already looks, that the build runs the suite unchanged, and
//! that a run is published and can be read back.
//!
//! Needs Maven and a JDK, and Maven needs its dependencies resolvable. Skips
//! otherwise rather than failing a suite the machine cannot run.
//!
//! Every test here is `#[ignore]`, and `npm run test:jvm` passes
//! `--include-ignored`. Not because they are unimportant -- they are the only
//! proof the JVM frontend works at all -- but because running a real Gradle or
//! Maven build belongs to a job that provisioned one. The CI job that does
//! sets up a JDK, Gradle with its cache, the Kotlin compiler and the JUnit
//! console runner, and finishes in twelve minutes. `cargo test --workspace`
//! picks them up on any runner that merely happens to have a JDK on it, cold
//! caches and all: the filesystem-safety job went from eleven minutes to over
//! seventy on Windows that way, and would now hit its timeout and fail.
//!
//! A test that needs a toolchain provisioned for it should say so rather than
//! run wherever one is lying around.

use std::path::{Path, PathBuf};
use std::process::Command;

use supercov_engine::jvm_project::JvmBuild;
use supercov_engine::jvm_run::{DirectJvmRunRequest, run_direct_jvm};

mod common;

fn temporary(label: &str) -> PathBuf {
    let root = std::env::temp_dir().join(format!(
        "supercov-jvm-run-{label}-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(&root).unwrap();
    root
}

fn write(root: &Path, relative: &str, contents: &str) {
    let path = root.join(relative);
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(path, contents).unwrap();
}

const POM: &str = r#"<project xmlns="http://maven.apache.org/POM/4.0.0">
  <modelVersion>4.0.0</modelVersion>
  <groupId>example</groupId>
  <artifactId>demo</artifactId>
  <version>1.0</version>
  <properties>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>5.10.2</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.2.5</version>
      </plugin>
    </plugins>
  </build>
</project>
"#;

/// `a > 10 && loud` gives two conditions, so MC/DC has something to say. The
/// suite shows one condition's independence and not the other's, which is the
/// difference between a number that measures something and one that does not.
const SOURCE: &str = r#"package app;

public class Calculator {
    public static String size(int a, boolean loud) {
        if (a > 10 && loud) {
            return "BIG";
        }
        return "small";
    }
}
"#;

const SUITE: &str = r#"package app;

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

class CalculatorTest {
    @Test
    void bigWhenLoudAndLarge() {
        assertEquals("BIG", Calculator.size(20, true));
    }

    @Test
    void smallOtherwise() {
        assertEquals("small", Calculator.size(1, false));
    }

    @Test
    @Disabled("proves a skipped test is recorded as one")
    void neverRuns() {
        assertEquals("small", Calculator.size(0, true));
    }
}
"#;

fn fixture(root: &Path) {
    write(root, "pom.xml", POM);
    write(root, "src/main/java/app/Calculator.java", SOURCE);
    write(root, "src/test/java/app/CalculatorTest.java", SUITE);
}

/// Maven resolves from the network on a cold cache. A machine without it can
/// still run every other test in the suite.
fn maven_can_resolve(mvn: &Path, root: &Path) -> bool {
    fixture(root);
    Command::new(mvn)
        .args(["-q", "test"])
        .current_dir(root)
        .output()
        .is_ok_and(|out| out.status.success())
}

#[test]
#[ignore = "drives a real Maven or Gradle build; run it with `npm run test:jvm`"]
fn a_maven_project_runs_through_its_own_build_and_publishes_what_each_test_reached() {
    let _building = common::building();
    let Some(mvn) = common::tool("mvn") else {
        common::skip("jvm", "no Maven found");
        return;
    };
    let resolvable = common::resolvable("jvm", || {
        let warmup = temporary("maven-warmup");
        let built = maven_can_resolve(&mvn, &warmup);
        std::fs::remove_dir_all(&warmup).ok();
        built
    });
    if !resolvable {
        common::skip(
            "jvm",
            "Maven cannot resolve this project's dependencies here",
        );
        return;
    }

    let root = temporary("maven");
    fixture(&root);
    let before = std::fs::read_to_string(root.join("src/main/java/app/Calculator.java")).unwrap();

    let request = DirectJvmRunRequest {
        root: root.clone(),
        command: vec![mvn.display().to_string(), "test".into()],
        run_id: "run-jvm-maven".into(),
        started_at: "2026-01-01T00:00:00.000Z".into(),
    };
    let mut diagnostics = Vec::new();
    let result = match run_direct_jvm(&request, &mut diagnostics) {
        Ok(result) => result,
        Err(error) => panic!(
            "run failed: {error}\n--- diagnostics ---\n{}",
            String::from_utf8_lossy(&diagnostics)
        ),
    };

    // The author's tree is untouched: instrumentation happens on a copy, and
    // nothing Supercov generates lands beside the code they wrote.
    assert_eq!(
        std::fs::read_to_string(root.join("src/main/java/app/Calculator.java")).unwrap(),
        before,
        "the project's own sources must come back exactly as they went in"
    );
    assert!(
        !root
            .join("src/main/java/com/supercorp/supercov/Supercov.java")
            .exists(),
        "Supercov's runtime belongs in the workspace, not in the author's tree"
    );

    assert_eq!(result.exit_code, 0);
    assert_eq!(result.build, JvmBuild::Maven);
    assert_eq!(result.source_files, 1);
    // The disabled one included: a test the suite declared and did not run is
    // a fact worth reporting, not an absence worth hiding.
    assert_eq!(result.tests, 3);

    let archive = result.run_directory.join("evidence.raw.gz");
    let entries =
        supercov_engine::evidence_archive::read_archive(&archive).expect("published archive");
    let named = entries
        .iter()
        .map(|entry| entry.path.as_str())
        .collect::<Vec<_>>();
    for required in ["coverage-model.json", "frontend.json", "manifest.json"] {
        assert!(named.contains(&required), "{named:?}");
    }
    assert_eq!(
        named
            .iter()
            .filter(|path| path.ends_with("mcdc.json"))
            .count(),
        3,
        "one record per test: {named:?}"
    );

    let records = entries
        .iter()
        .filter(|entry| entry.path.ends_with("mcdc.json"))
        .map(|entry| String::from_utf8(entry.contents.clone()).expect("utf-8"))
        .collect::<Vec<_>>();
    let statuses = records
        .iter()
        .filter(|record| record.contains("\"status\":\"skipped\""))
        .count();
    assert_eq!(statuses, 1, "the disabled test is recorded as skipped");
    assert!(
        records
            .iter()
            .any(|record| record.contains("CalculatorTest#bigWhenLoudAndLarge()")),
        "tests carry the names the framework itself chose"
    );
    assert!(
        records
            .iter()
            .all(|record| record.contains("\"runner\":\"junit-platform\"")),
        "{records:?}"
    );
    std::fs::remove_dir_all(root).ok();
}

const BUILD_GRADLE: &str = r#"plugins {
    id 'java'
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.10.2'
    // Gradle 9 requires every project to declare this itself, in exactly the
    // configuration its documentation recommends: on the classpath the tests
    // run with, not the one they compile against.
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

test {
    useJUnitPlatform()
}
"#;

fn gradle_fixture(root: &Path) {
    write(root, "settings.gradle", "rootProject.name = 'demo'\n");
    write(root, "build.gradle", BUILD_GRADLE);
    write(root, "src/main/java/app/Calculator.java", SOURCE);
    write(root, "src/test/java/app/CalculatorTest.java", SUITE);
}

#[test]
#[ignore = "drives a real Maven or Gradle build; run it with `npm run test:jvm`"]
fn a_gradle_project_runs_through_its_own_build_and_publishes_what_each_test_reached() {
    let _building = common::building();
    let Some(gradle) = common::tool("gradle") else {
        common::skip("jvm", "no Gradle found");
        return;
    };
    let resolvable = common::resolvable("jvm", || {
        let warmup = temporary("gradle-warmup");
        gradle_fixture(&warmup);
        let built = Command::new(&gradle)
            .args(["--quiet", "--console=plain", "test"])
            .current_dir(&warmup)
            .output()
            .is_ok_and(|out| out.status.success());
        std::fs::remove_dir_all(&warmup).ok();
        built
    });
    if !resolvable {
        common::skip(
            "jvm",
            "Gradle cannot resolve this project's dependencies here",
        );
        return;
    }

    let root = temporary("gradle");
    gradle_fixture(&root);
    let before = std::fs::read_to_string(root.join("build.gradle")).unwrap();

    let request = DirectJvmRunRequest {
        root: root.clone(),
        command: vec![
            gradle.display().to_string(),
            "--console=plain".into(),
            "test".into(),
        ],
        run_id: "run-jvm-gradle".into(),
        started_at: "2026-01-01T00:00:00.000Z".into(),
    };
    let mut diagnostics = Vec::new();
    let result = match run_direct_jvm(&request, &mut diagnostics) {
        Ok(result) => result,
        Err(error) => panic!(
            "run failed: {error}\n--- diagnostics ---\n{}",
            String::from_utf8_lossy(&diagnostics)
        ),
    };

    // The launcher dependency goes into the copy, never into the author's own
    // build file.
    assert_eq!(
        std::fs::read_to_string(root.join("build.gradle")).unwrap(),
        before,
        "the project's own build file must come back exactly as it went in"
    );
    assert_eq!(result.exit_code, 0);
    assert_eq!(result.build, JvmBuild::Gradle);
    assert_eq!(result.tests, 3);
    std::fs::remove_dir_all(root).ok();
}

const TESTNG_POM: &str = r#"<project xmlns="http://maven.apache.org/POM/4.0.0">
  <modelVersion>4.0.0</modelVersion>
  <groupId>example</groupId>
  <artifactId>demo</artifactId>
  <version>1.0</version>
  <properties>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>7.10.2</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.2.5</version>
      </plugin>
    </plugins>
  </build>
</project>
"#;

/// TestNG's own idioms: a data provider that runs one method several times,
/// and a skip. Neither has a JUnit Platform equivalent to fall back on.
const TESTNG_SUITE: &str = r#"package app;

import org.testng.SkipException;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;

public class CalculatorTest {
    @DataProvider(name = "sizes")
    public Object[][] sizes() {
        return new Object[][] {{20, true, "BIG"}, {1, false, "small"}};
    }

    @Test(dataProvider = "sizes")
    public void sizesAreNamed(int a, boolean loud, String expected) {
        assertEquals(Calculator.size(a, loud), expected);
    }

    @Test
    public void notToday() {
        throw new SkipException("nothing to do here");
    }
}
"#;

fn testng_fixture(root: &Path) {
    write(root, "pom.xml", TESTNG_POM);
    write(root, "src/main/java/app/Calculator.java", SOURCE);
    write(root, "src/test/java/app/CalculatorTest.java", TESTNG_SUITE);
}

#[test]
#[ignore = "drives a real Maven or Gradle build; run it with `npm run test:jvm`"]
fn a_testng_suite_is_attributed_through_its_own_lifecycle() {
    let _building = common::building();
    // TestNG is the one framework the JUnit Platform does not report, so it
    // needs a listener of its own. Kotest and Spock are platform engines and
    // need nothing extra.
    let Some(mvn) = common::tool("mvn") else {
        common::skip("jvm", "no Maven found");
        return;
    };
    let resolvable = common::resolvable("jvm", || {
        let warmup = temporary("testng-warmup");
        testng_fixture(&warmup);
        let built = Command::new(&mvn)
            .args(["-q", "test"])
            .current_dir(&warmup)
            .output()
            .is_ok_and(|out| out.status.success());
        std::fs::remove_dir_all(&warmup).ok();
        built
    });
    if !resolvable {
        common::skip("jvm", "Maven cannot resolve TestNG here");
        return;
    }

    let root = temporary("testng");
    testng_fixture(&root);
    let request = DirectJvmRunRequest {
        root: root.clone(),
        command: vec![mvn.display().to_string(), "-q".into(), "test".into()],
        run_id: "run-jvm-testng".into(),
        started_at: "2026-01-01T00:00:00.000Z".into(),
    };
    let mut diagnostics = Vec::new();
    let result = match run_direct_jvm(&request, &mut diagnostics) {
        Ok(result) => result,
        Err(error) => panic!(
            "run failed: {error}\n--- diagnostics ---\n{}",
            String::from_utf8_lossy(&diagnostics)
        ),
    };

    // Two data-provider invocations and the skip. The invocations are separate
    // tests because they reach different code, which is the point of a data
    // provider: collapsing them would credit one with what the other proved.
    assert_eq!(
        result.tests,
        3,
        "{diagnostics:?}",
        diagnostics = String::from_utf8_lossy(&diagnostics)
    );

    let archive = result.run_directory.join("evidence.raw.gz");
    let records = supercov_engine::evidence_archive::read_archive(&archive)
        .expect("published archive")
        .into_iter()
        .filter(|entry| entry.path.ends_with("mcdc.json"))
        .map(|entry| String::from_utf8(entry.contents).expect("utf-8"))
        .collect::<Vec<_>>();
    assert!(
        records
            .iter()
            .any(|record| record.contains("CalculatorTest#sizesAreNamed()")),
        "{records:?}"
    );
    assert!(
        records
            .iter()
            .any(|record| record.contains("CalculatorTest#sizesAreNamed()[1]")),
        "a second invocation is its own test: {records:?}"
    );
    assert_eq!(
        records
            .iter()
            .filter(|record| record.contains("\"status\":\"skipped\""))
            .count(),
        1,
        "the skipped test is recorded as one: {records:?}"
    );
    // Attributed by the lifecycle that actually saw it. A project can run both
    // frameworks in one JVM, so a result naming the platform here would claim
    // it was announced by something that never saw it.
    assert!(
        records
            .iter()
            .all(|record| record.contains("\"runner\":\"testng\"")),
        "{records:?}"
    );
    std::fs::remove_dir_all(root).ok();
}

const KOTLIN_BUILD_GRADLE: &str = r#"plugins {
    id 'org.jetbrains.kotlin.jvm' version '2.2.20'
}

repositories {
    mavenCentral()
}

// Pinned so the Java and Kotlin compilers agree on a target; Gradle refuses
// the build otherwise, and what is under test here is Supercov, not a
// toolchain mismatch.
java {
    sourceCompatibility = JavaVersion.VERSION_17
    targetCompatibility = JavaVersion.VERSION_17
}

kotlin {
    compilerOptions {
        jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
    }
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.10.2'
    testImplementation 'org.jetbrains.kotlin:kotlin-test'
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

test {
    useJUnitPlatform()
}
"#;

const KOTLIN_SOURCE: &str = r#"package app

object Calculator {
    fun size(a: Int, loud: Boolean): String {
        if (a > 10 && loud) {
            return "BIG"
        }
        return "small"
    }
}
"#;

const KOTLIN_SUITE: &str = r#"package app

import kotlin.test.Test
import kotlin.test.assertEquals

class CalculatorTest {
    @Test
    fun bigWhenLoudAndLarge() {
        assertEquals("BIG", Calculator.size(20, true))
    }

    @Test
    fun smallOtherwise() {
        assertEquals("small", Calculator.size(1, false))
    }
}
"#;

fn kotlin_fixture(root: &Path) {
    write(root, "settings.gradle", "rootProject.name = 'demo'\n");
    write(root, "build.gradle", KOTLIN_BUILD_GRADLE);
    write(root, "src/main/kotlin/app/Calculator.kt", KOTLIN_SOURCE);
    write(root, "src/test/kotlin/app/CalculatorTest.kt", KOTLIN_SUITE);
}

#[test]
#[ignore = "drives a real Maven or Gradle build; run it with `npm run test:jvm`"]
fn a_kotlin_project_is_measured_like_any_other_jvm_one() {
    let _building = common::building();
    // Kotlin is instrumented by the same rewriter and attributed by the same
    // listener; what differs is only the grammar the obligations come from.
    let Some(gradle) = common::tool("gradle") else {
        common::skip("jvm", "no Gradle found");
        return;
    };
    let resolvable = common::resolvable("jvm", || {
        let warmup = temporary("kotlin-warmup");
        kotlin_fixture(&warmup);
        let built = Command::new(&gradle)
            .args(["--quiet", "--console=plain", "test"])
            .current_dir(&warmup)
            .output()
            .is_ok_and(|out| out.status.success());
        std::fs::remove_dir_all(&warmup).ok();
        built
    });
    if !resolvable {
        common::skip("jvm", "Gradle cannot build this Kotlin project here");
        return;
    }

    let root = temporary("kotlin");
    kotlin_fixture(&root);
    let request = DirectJvmRunRequest {
        root: root.clone(),
        command: vec![
            gradle.display().to_string(),
            "--console=plain".into(),
            "test".into(),
        ],
        run_id: "run-jvm-kotlin".into(),
        started_at: "2026-01-01T00:00:00.000Z".into(),
    };
    let mut diagnostics = Vec::new();
    let result = match run_direct_jvm(&request, &mut diagnostics) {
        Ok(result) => result,
        Err(error) => panic!(
            "run failed: {error}\n--- diagnostics ---\n{}",
            String::from_utf8_lossy(&diagnostics)
        ),
    };
    assert_eq!(result.exit_code, 0);
    assert_eq!(result.tests, 2);
    assert_eq!(result.source_files, 1);

    // The decision the Kotlin source declares is in the published manifest,
    // which is what the numbers are measured against.
    let entries = supercov_engine::evidence_archive::read_archive(
        &result.run_directory.join("evidence.raw.gz"),
    )
    .expect("published archive");
    let manifest = String::from_utf8(
        entries
            .into_iter()
            .find(|entry| entry.path == "manifest.json")
            .expect("manifest")
            .contents,
    )
    .expect("utf-8");
    assert!(manifest.contains("Calculator.kt"), "{manifest}");
    assert_eq!(manifest.matches("\"conditions\"").count(), 1, "{manifest}");
    std::fs::remove_dir_all(root).ok();
}

/// Two modules, each with its own source set and its own test JVM. This is
/// the shape most real Java projects have, and almost nothing about a
/// single-module build generalises to it on its own: each module compiles only
/// its own sources, so a runtime written once at the top is invisible to every
/// one of them, and each forks a JVM of its own, so one evidence path would be
/// overwritten by whichever module finished last.
fn multi_module_maven(root: &Path) {
    write(
        root,
        "pom.xml",
        r#"<project xmlns="http://maven.apache.org/POM/4.0.0">
  <modelVersion>4.0.0</modelVersion>
  <groupId>example</groupId>
  <artifactId>parent</artifactId>
  <version>1.0</version>
  <packaging>pom</packaging>
  <modules>
    <module>core</module>
    <module>app</module>
  </modules>
  <properties>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>5.10.2</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>
"#,
    );
    for module in ["core", "app"] {
        write(
            root,
            &format!("{module}/pom.xml"),
            &format!(
                r#"<project xmlns="http://maven.apache.org/POM/4.0.0">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>example</groupId>
    <artifactId>parent</artifactId>
    <version>1.0</version>
  </parent>
  <artifactId>{module}</artifactId>
</project>
"#
            ),
        );
    }
    write(
        root,
        "core/src/main/java/core/Calc.java",
        &SOURCE
            .replace("package app;", "package core;")
            .replace("class Calculator", "class Calc"),
    );
    write(
        root,
        "core/src/test/java/core/CalcTest.java",
        "package core;\n\nimport org.junit.jupiter.api.Test;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nclass CalcTest {\n    @Test void big() { assertEquals(\"BIG\", Calc.size(20, true)); }\n    @Test void small() { assertEquals(\"small\", Calc.size(1, false)); }\n}\n",
    );
    write(
        root,
        "app/src/main/java/app/Greet.java",
        "package app;\n\npublic class Greet {\n    public static String hi(boolean loud) {\n        if (loud) { return \"HI\"; }\n        return \"hi\";\n    }\n}\n",
    );
    write(
        root,
        "app/src/test/java/app/GreetTest.java",
        "package app;\n\nimport org.junit.jupiter.api.Test;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nclass GreetTest {\n    @Test void loud() { assertEquals(\"HI\", Greet.hi(true)); }\n}\n",
    );
}

#[test]
#[ignore = "drives a real Maven or Gradle build; run it with `npm run test:jvm`"]
fn every_module_of_a_multi_module_build_is_measured_and_merged() {
    let _building = common::building();
    let Some(mvn) = common::tool("mvn") else {
        common::skip("jvm", "no Maven found");
        return;
    };
    let resolvable = common::resolvable("jvm", || {
        let warmup = temporary("multi-warmup");
        multi_module_maven(&warmup);
        let built = Command::new(&mvn)
            .args(["-q", "test"])
            .current_dir(&warmup)
            .output()
            .is_ok_and(|out| out.status.success());
        std::fs::remove_dir_all(&warmup).ok();
        built
    });
    if !resolvable {
        common::skip(
            "jvm",
            "Maven cannot resolve this project's dependencies here",
        );
        return;
    }

    let root = temporary("multi");
    multi_module_maven(&root);
    let request = DirectJvmRunRequest {
        root: root.clone(),
        command: vec![mvn.display().to_string(), "-q".into(), "test".into()],
        run_id: "run-jvm-multi".into(),
        started_at: "2026-01-01T00:00:00.000Z".into(),
    };
    let mut diagnostics = Vec::new();
    let result = match run_direct_jvm(&request, &mut diagnostics) {
        Ok(result) => result,
        Err(error) => panic!(
            "run failed: {error}\n--- diagnostics ---\n{}",
            String::from_utf8_lossy(&diagnostics)
        ),
    };
    assert_eq!(result.exit_code, 0);
    assert_eq!(result.modules, 2);
    assert_eq!(result.source_files, 2);
    // Every module's tests, not just the last one to finish.
    assert_eq!(result.tests, 3);

    let entries = supercov_engine::evidence_archive::read_archive(
        &result.run_directory.join("evidence.raw.gz"),
    )
    .expect("published archive");
    let records = entries
        .iter()
        .filter(|entry| entry.path.ends_with("mcdc.json"))
        .map(|entry| String::from_utf8(entry.contents.clone()).expect("utf-8"))
        .collect::<Vec<_>>();
    // The module is the worker, because the module is what forked a JVM.
    assert!(
        records
            .iter()
            .any(|record| record.contains("\"workerId\":\"core\"")),
        "{records:?}"
    );
    assert!(
        records
            .iter()
            .any(|record| record.contains("\"workerId\":\"app\"")),
        "{records:?}"
    );
    // And both modules' obligations are in the one manifest the numbers are
    // measured against.
    let manifest = String::from_utf8(
        entries
            .into_iter()
            .find(|entry| entry.path == "manifest.json")
            .expect("manifest")
            .contents,
    )
    .expect("utf-8");
    assert!(
        manifest.contains("core/src/main/java/core/Calc.java"),
        "{manifest}"
    );
    assert!(
        manifest.contains("app/src/main/java/app/Greet.java"),
        "{manifest}"
    );
    std::fs::remove_dir_all(root).ok();
}

fn multi_project_gradle(root: &Path) {
    write(
        root,
        "settings.gradle",
        "rootProject.name = 'demo'\ninclude 'core', 'app'\n",
    );
    // The root only aggregates: it has no source set of its own, which is the
    // usual shape and the one a root-only dependency declaration would miss.
    write(
        root,
        "build.gradle",
        "subprojects {\n    apply plugin: 'java'\n    repositories { mavenCentral() }\n    dependencies {\n        testImplementation 'org.junit.jupiter:junit-jupiter:5.10.2'\n        testRuntimeOnly 'org.junit.platform:junit-platform-launcher'\n    }\n    test { useJUnitPlatform() }\n}\n",
    );
    write(root, "core/build.gradle", "");
    write(root, "app/build.gradle", "");
    write(
        root,
        "core/src/main/java/core/Calc.java",
        "package core;\n\npublic class Calc {\n    public static String size(int a, boolean loud) {\n        if (a > 10 && loud) { return \"BIG\"; }\n        return \"small\";\n    }\n}\n",
    );
    write(
        root,
        "core/src/test/java/core/CalcTest.java",
        "package core;\n\nimport org.junit.jupiter.api.Test;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nclass CalcTest {\n    @Test void big() { assertEquals(\"BIG\", Calc.size(20, true)); }\n}\n",
    );
    write(
        root,
        "app/src/main/java/app/Greet.java",
        "package app;\n\npublic class Greet {\n    public static String hi(boolean loud) {\n        if (loud) { return \"HI\"; }\n        return \"hi\";\n    }\n}\n",
    );
    write(
        root,
        "app/src/test/java/app/GreetTest.java",
        "package app;\n\nimport org.junit.jupiter.api.Test;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nclass GreetTest {\n    @Test void loud() { assertEquals(\"HI\", Greet.hi(true)); }\n}\n",
    );
}

/// A Gradle build whose root only aggregates. A dependency declared in the
/// root reaches none of the subprojects, and the subprojects are where the
/// test sources -- and so the listener Supercov compiles -- actually live.
#[test]
#[ignore = "drives a real Maven or Gradle build; run it with `npm run test:jvm`"]
fn a_multi_project_gradle_build_reaches_every_subproject() {
    let _building = common::building();
    let Some(gradle) = common::tool("gradle") else {
        common::skip("jvm", "no Gradle found");
        return;
    };
    let resolvable = common::resolvable("jvm", || {
        let warmup = temporary("multi-gradle-warmup");
        multi_project_gradle(&warmup);
        let built = Command::new(&gradle)
            .args(["--quiet", "--console=plain", "test"])
            .current_dir(&warmup)
            .output()
            .is_ok_and(|out| out.status.success());
        std::fs::remove_dir_all(&warmup).ok();
        built
    });
    if !resolvable {
        common::skip(
            "jvm",
            "Gradle cannot resolve this project's dependencies here",
        );
        return;
    }

    let root = temporary("multi-gradle");
    multi_project_gradle(&root);
    let request = DirectJvmRunRequest {
        root: root.clone(),
        command: vec![
            gradle.display().to_string(),
            "--console=plain".into(),
            "test".into(),
        ],
        run_id: "run-jvm-multi-gradle".into(),
        started_at: "2026-01-01T00:00:00.000Z".into(),
    };
    let mut diagnostics = Vec::new();
    let result = match run_direct_jvm(&request, &mut diagnostics) {
        Ok(result) => result,
        Err(error) => panic!(
            "run failed: {error}\n--- diagnostics ---\n{}",
            String::from_utf8_lossy(&diagnostics)
        ),
    };
    assert_eq!(result.exit_code, 0);
    assert_eq!(result.modules, 2);
    assert_eq!(result.tests, 2);
    std::fs::remove_dir_all(root).ok();
}

/// Kotest is the reason the platform listener exists rather than an annotation
/// rewriter: its tests are strings in a constructor block, not annotated
/// methods, so nothing that reads test source can find them. The platform
/// announces them like any other engine's.
#[test]
#[ignore = "drives a real Maven or Gradle build; run it with `npm run test:jvm`"]
fn a_kotest_spec_is_attributed_under_the_names_kotest_reports() {
    let _building = common::building();
    let Some(gradle) = common::tool("gradle") else {
        common::skip("jvm", "no Gradle found");
        return;
    };
    let fixture = |root: &Path| {
        write(root, "settings.gradle", "rootProject.name = 'demo'\n");
        write(
            root,
            "build.gradle",
            &KOTLIN_BUILD_GRADLE.replace(
                "testImplementation 'org.junit.jupiter:junit-jupiter:5.10.2'\n    testImplementation 'org.jetbrains.kotlin:kotlin-test'",
                "testImplementation 'io.kotest:kotest-runner-junit5:5.9.1'",
            ),
        );
        write(root, "src/main/kotlin/app/Calculator.kt", KOTLIN_SOURCE);
        write(
            root,
            "src/test/kotlin/app/CalculatorSpec.kt",
            "package app\n\nimport io.kotest.core.spec.style.StringSpec\nimport io.kotest.matchers.shouldBe\n\nclass CalculatorSpec : StringSpec({\n    \"loud and large is big\" {\n        Calculator.size(20, true) shouldBe \"BIG\"\n    }\n    \"anything else is small\" {\n        Calculator.size(1, false) shouldBe \"small\"\n    }\n})\n",
        );
    };
    let resolvable = common::resolvable("jvm", || {
        let warmup = temporary("kotest-warmup");
        fixture(&warmup);
        let built = Command::new(&gradle)
            .args(["--quiet", "--console=plain", "test"])
            .current_dir(&warmup)
            .output()
            .is_ok_and(|out| out.status.success());
        std::fs::remove_dir_all(&warmup).ok();
        built
    });
    if !resolvable {
        common::skip("jvm", "Gradle cannot build this Kotest project here");
        return;
    }

    let root = temporary("kotest");
    fixture(&root);
    let request = DirectJvmRunRequest {
        root: root.clone(),
        command: vec![
            gradle.display().to_string(),
            "--console=plain".into(),
            "test".into(),
        ],
        run_id: "run-jvm-kotest".into(),
        started_at: "2026-01-01T00:00:00.000Z".into(),
    };
    let mut diagnostics = Vec::new();
    let result = match run_direct_jvm(&request, &mut diagnostics) {
        Ok(result) => result,
        Err(error) => panic!(
            "run failed: {error}\n--- diagnostics ---\n{}",
            String::from_utf8_lossy(&diagnostics)
        ),
    };
    assert_eq!(result.exit_code, 0);
    assert_eq!(result.tests, 2);

    let entries = supercov_engine::evidence_archive::read_archive(
        &result.run_directory.join("evidence.raw.gz"),
    )
    .expect("published archive");
    let records = entries
        .iter()
        .filter(|entry| entry.path.ends_with("mcdc.json"))
        .map(|entry| String::from_utf8(entry.contents.clone()).expect("utf-8"))
        .collect::<Vec<_>>();
    // The sentence its author wrote, not a method name invented for it.
    assert!(
        records
            .iter()
            .any(|record| record.contains("loud and large is big")),
        "{records:?}"
    );

    // And the Kotlin function it reached is measured at all. A Kotlin function
    // declaration hides its block behind an unnamed node, so asking the
    // grammar for a `body` field answered nothing and every Kotlin function
    // went unrecorded -- silently, because a function with no block is a real
    // thing in Kotlin and the absence read as one of those.
    let manifest = String::from_utf8(
        entries
            .into_iter()
            .find(|entry| entry.path == "manifest.json")
            .expect("manifest")
            .contents,
    )
    .expect("utf-8");
    assert!(manifest.contains("\"kind\":\"function\""), "{manifest}");
    assert!(
        records
            .iter()
            .all(|record| record.contains("kotlin:function:")),
        "both tests enter the function they exercise: {records:?}"
    );
    std::fs::remove_dir_all(root).ok();
}

/// Spock writes its tests in Groovy, which Supercov does not parse: it
/// measures the Java those specifications exercise, not the specifications
/// themselves. That makes a module with a Groovy test set look, to a
/// discovery pass that only reads .java and .kt, like a module with no tests
/// at all -- so it got no listener, recorded nothing, and the unarmed runtime
/// then threw on the first instrumented line. Supercov turned a passing suite
/// into a failing one.
#[test]
#[ignore = "drives a real Maven or Gradle build; run it with `npm run test:jvm`"]
fn a_spock_specification_is_measured_though_its_tests_are_groovy() {
    let _building = common::building();
    let Some(gradle) = common::tool("gradle") else {
        common::skip("jvm", "no Gradle found");
        return;
    };
    let fixture = |root: &Path| {
        write(
            root,
            "settings.gradle",
            "plugins {\n    id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0'\n}\nrootProject.name = 'demo'\n",
        );
        write(
            root,
            "build.gradle",
            // Groovy cannot read the newest JDKs' class files, so the build
            // asks for one it can; what is under test is Supercov.
            "plugins {\n    id 'groovy'\n    id 'java'\n}\n\nrepositories { mavenCentral() }\n\njava {\n    toolchain { languageVersion = JavaLanguageVersion.of(21) }\n}\n\ndependencies {\n    testImplementation 'org.spockframework:spock-core:2.3-groovy-4.0'\n    testImplementation 'org.apache.groovy:groovy:4.0.22'\n    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'\n}\n\ntest { useJUnitPlatform() }\n",
        );
        write(root, "src/main/java/app/Calculator.java", SOURCE);
        write(
            root,
            "src/test/groovy/app/CalculatorSpec.groovy",
            "package app\n\nimport spock.lang.Specification\n\nclass CalculatorSpec extends Specification {\n    def \"loud and large is big\"() {\n        expect:\n        Calculator.size(20, true) == \"BIG\"\n    }\n\n    def \"anything else is small\"() {\n        expect:\n        Calculator.size(1, false) == \"small\"\n    }\n}\n",
        );
    };
    let resolvable = common::resolvable("jvm", || {
        let warmup = temporary("spock-warmup");
        fixture(&warmup);
        let built = Command::new(&gradle)
            .args(["--quiet", "--console=plain", "test"])
            .current_dir(&warmup)
            .output()
            .is_ok_and(|out| out.status.success());
        std::fs::remove_dir_all(&warmup).ok();
        built
    });
    if !resolvable {
        common::skip("jvm", "Gradle cannot build this Spock project here");
        return;
    }

    let root = temporary("spock");
    fixture(&root);
    let request = DirectJvmRunRequest {
        root: root.clone(),
        command: vec![
            gradle.display().to_string(),
            "--console=plain".into(),
            "test".into(),
        ],
        run_id: "run-jvm-spock".into(),
        started_at: "2026-01-01T00:00:00.000Z".into(),
    };
    let mut diagnostics = Vec::new();
    let result = match run_direct_jvm(&request, &mut diagnostics) {
        Ok(result) => result,
        Err(error) => panic!(
            "run failed: {error}\n--- diagnostics ---\n{}",
            String::from_utf8_lossy(&diagnostics)
        ),
    };
    // The suite passes, which is the part that matters most: an unmeasurable
    // test set must cost coverage, never correctness.
    assert_eq!(result.exit_code, 0);
    assert_eq!(result.tests, 2);

    let records = supercov_engine::evidence_archive::read_archive(
        &result.run_directory.join("evidence.raw.gz"),
    )
    .expect("published archive")
    .into_iter()
    .filter(|entry| entry.path.ends_with("mcdc.json"))
    .map(|entry| String::from_utf8(entry.contents).expect("utf-8"))
    .collect::<Vec<_>>();
    // Under the sentence its author wrote, as Spock reports it.
    assert!(
        records
            .iter()
            .any(|record| record.contains("CalculatorSpec#loud and large is big")),
        "{records:?}"
    );
    std::fs::remove_dir_all(root).ok();
}

/// A build may fork more than one JVM to run its tests in parallel: Gradle's
/// maxParallelForks and surefire's forkCount both do, and RxJava sets the
/// first to the number of processors. Every fork runs the listener, so a
/// single agreed path meant each overwrote the last and the run kept whichever
/// finished last — 49 of the 406 tests RxJava had actually run.
#[test]
#[ignore = "drives a real Maven or Gradle build; run it with `npm run test:jvm`"]
fn every_forked_jvm_is_merged_rather_than_overwriting_the_last() {
    let _building = common::building();
    let Some(gradle) = common::tool("gradle") else {
        common::skip("jvm", "no Gradle found");
        return;
    };
    let fixture = |root: &Path| {
        write(root, "settings.gradle", "rootProject.name = 'demo'\n");
        write(
            root,
            "build.gradle",
            "plugins {\n    id 'java'\n}\n\nrepositories { mavenCentral() }\n\ndependencies {\n    testImplementation 'org.junit.jupiter:junit-jupiter:5.10.2'\n    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'\n}\n\ntest {\n    useJUnitPlatform()\n    // The whole point: more than one JVM, each writing evidence.\n    maxParallelForks = 4\n    forkEvery = 1\n}\n",
        );
        write(root, "src/main/java/app/Calculator.java", SOURCE);
        // Four classes, forkEvery = 1, so four JVMs.
        for name in ["A", "B", "C", "D"] {
            write(
                root,
                &format!("src/test/java/app/{name}Test.java"),
                &format!(
                    "package app;\n\nimport org.junit.jupiter.api.Test;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nclass {name}Test {{\n    @Test\n    void first() {{ assertEquals(\"BIG\", Calculator.size(20, true)); }}\n    @Test\n    void second() {{ assertEquals(\"small\", Calculator.size(1, false)); }}\n}}\n"
                ),
            );
        }
    };
    let resolvable = common::resolvable("jvm", || {
        let warmup = temporary("forks-warmup");
        fixture(&warmup);
        let built = Command::new(&gradle)
            .args(["--quiet", "--console=plain", "test"])
            .current_dir(&warmup)
            .output()
            .is_ok_and(|out| out.status.success());
        std::fs::remove_dir_all(&warmup).ok();
        built
    });
    if !resolvable {
        common::skip(
            "jvm",
            "Gradle cannot resolve this project's dependencies here",
        );
        return;
    }

    let root = temporary("forks");
    fixture(&root);
    let request = DirectJvmRunRequest {
        root: root.clone(),
        command: vec![
            gradle.display().to_string(),
            "--console=plain".into(),
            "test".into(),
        ],
        run_id: "run-jvm-forks".into(),
        started_at: "2026-01-01T00:00:00.000Z".into(),
    };
    let mut diagnostics = Vec::new();
    let result = match run_direct_jvm(&request, &mut diagnostics) {
        Ok(result) => result,
        Err(error) => panic!(
            "run failed: {error}\n--- diagnostics ---\n{}",
            String::from_utf8_lossy(&diagnostics)
        ),
    };
    assert_eq!(result.exit_code, 0);
    // Every test from every fork, not just the fork that finished last.
    assert_eq!(result.tests, 8);

    let records = supercov_engine::evidence_archive::read_archive(
        &result.run_directory.join("evidence.raw.gz"),
    )
    .expect("published archive")
    .into_iter()
    .filter(|entry| entry.path.ends_with("mcdc.json"))
    .map(|entry| String::from_utf8(entry.contents).expect("utf-8"))
    .collect::<Vec<_>>();
    for class in ["ATest", "BTest", "CTest", "DTest"] {
        assert!(
            records.iter().any(|record| record.contains(class)),
            "{class} is missing, so a fork was lost: {records:?}"
        );
    }
    std::fs::remove_dir_all(root).ok();
}