wasm-rquickjs-cli 0.5.3

Tool for wrapping JavaScript modules as WebAssembly components using the QuickJS engine
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
//! Agentic TypeScript compatibility and performance suite.
//!
//! Use `tests/agentic_ts/run.sh` for manual measurements. CI runs only the report-contract path.

#![allow(dead_code)]

#[path = "common/mod.rs"]
mod common;

use anyhow::Context as _;
use camino::Utf8Path;
use common::{CompiledTest, FeatureCombination, TestInstance, copy_dir_recursive};
use serde_json::{Value, json};
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::io::Read as _;
use std::process::Command;
use std::time::{Duration, Instant};
use wasmtime::component::Val;

const SUITE_DIR: &str = "tests/agentic_ts";
const EXAMPLE_DIR: &str = "examples/runtime/agentic-ts";
const INPUT_HASH_ALGORITHM: &str = "blake3-composite-v1";
const ALLOWED_QUICKJS_HEAP_VARIATION_BYTES: u64 = 1_048_576;
const INVOCATION_DEADLINE_SECONDS: u64 = 900;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    if std::env::var_os("AGENTIC_TS_VALIDATE_REPORTS").is_some() {
        return validate_checked_reports(Utf8Path::new(SUITE_DIR).join("results"));
    }
    verify_toolchain()?;
    let iterations = std::env::var("AGENTIC_TS_ITERATIONS")
        .ok()
        .and_then(|value| value.parse::<usize>().ok())
        .unwrap_or(5);
    anyhow::ensure!(
        iterations >= 5,
        "AGENTIC_TS_ITERATIONS must be at least 5 to assess a warmed plateau"
    );

    let release_baseline = std::env::var_os("AGENTIC_TS_RELEASE_BASELINE").is_some();
    let build_started = Instant::now();
    let feature_combination = if release_baseline {
        FeatureCombination::TypeScriptTransformRuntime
    } else {
        FeatureCombination::TypeScriptCompilerProfiling
    };
    let compiled =
        CompiledTest::new_with_features(Utf8Path::new(EXAMPLE_DIR), true, feature_combination)
            .await?;
    let build_elapsed = build_started.elapsed();
    let component_size = fs::metadata(compiled.wasm_path())?.len();

    let instantiate_started = Instant::now();
    let mut instance = TestInstance::new_with_memory_tracking(compiled.wasm_path()).await?;
    let instantiate_elapsed = instantiate_started.elapsed();
    prepare_workspace(&instance)?;

    if release_baseline {
        return run_release_baseline(
            &compiled,
            &mut instance,
            iterations,
            build_elapsed,
            instantiate_elapsed,
            component_size,
            feature_combination,
        )
        .await;
    }

    if std::env::var_os("AGENTIC_TS_PROFILE_SMOKE").is_some() {
        let mut node = Vec::with_capacity(iterations);
        let mut wasm = Vec::with_capacity(iterations);
        for _ in 0..iterations {
            let sample = node_phase_profile()?;
            validate_phase_profile(&sample, "Node", false)?;
            node.push(sample);
            let sample = timed_invoke(&mut instance, "profile-tsc", &[Val::U64(300_000)]).await?;
            validate_phase_profile(&sample, "Wasm", true)?;
            wasm.push(sample);
        }
        let concurrent = timed_invoke(&mut instance, "run-concurrent", &[]).await?;
        for sibling in ["compiler", "cpu", "io"] {
            validate_execution_profile_timing(
                &concurrent["result"][sibling]["result"]["profile"],
                &format!("concurrent {sibling}"),
            )?;
        }
        let formatted = serde_json::to_string_pretty(&json!({
            "target": "p3",
            "node": summarize(&node),
            "wasm": summarize(&wasm),
            "concurrent": concurrent,
        }))?;
        if let Ok(path) = std::env::var("AGENTIC_TS_PROFILE_SMOKE_REPORT") {
            fs::write(path, format!("{formatted}\n"))?;
        }
        println!("{formatted}");
        return Ok(());
    }

    if std::env::var_os("AGENTIC_TS_MODULE_RESOLUTION_SMOKE").is_some() {
        let emit = timed_invoke(
            &mut instance,
            "run-tsc",
            &[
                string_list(&[
                    "--module",
                    "NodeNext",
                    "--moduleResolution",
                    "NodeNext",
                    "--target",
                    "ES2022",
                    "--outDir",
                    "dist/direct",
                    "projects/direct.ts",
                ]),
                Val::U64(300_000),
            ],
        )
        .await?;
        anyhow::ensure!(
            successful_result(&emit["result"]),
            "failed to emit controlled JavaScript"
        );

        let mut generated = Vec::with_capacity(iterations);
        for _ in 0..iterations {
            let sample = timed_invoke(
                &mut instance,
                "run-generated",
                &[Val::String("./dist/direct/direct.js".to_string())],
            )
            .await?;
            anyhow::ensure!(
                successful_result(&sample["result"])
                    && sample.pointer("/result/value/default/answer") == Some(&json!(42))
                    && sample.pointer("/result/value/default/state") == Some(&json!("ready")),
                "controlled generated-JavaScript workload failed: {sample:#}"
            );
            validate_module_resolution_counters(&sample, false)?;
            generated.push(sample);
        }

        let input_hashes = input_hashes()?;
        let formatted = serde_json::to_string_pretty(&json!({
            "schema": "module-resolution-smoke-v1",
            "target": "p3",
            "iterations": iterations,
            "inputs": {
                "algorithm": INPUT_HASH_ALGORITHM,
                "buildHash": input_hashes.build,
                "benchmarkHash": input_hashes.benchmark,
            },
            "component": {
                "bytes": component_size,
                "blake3": hash_file(compiled.wasm_path())?,
                "buildMs": millis(build_elapsed),
                "prepareAndInstantiateMs": millis(instantiate_elapsed),
            },
            "emit": emit,
            "generatedJavaScript": summarize(&generated),
        }))?;
        if let Ok(path) = std::env::var("AGENTIC_TS_MODULE_RESOLUTION_SMOKE_REPORT") {
            fs::write(path, format!("{formatted}\n"))?;
        }
        println!("{formatted}");
        return Ok(());
    }

    if std::env::var_os("AGENTIC_TS_CJS_GRAPH_SMOKE").is_some() {
        prepare_cjs_graph(&instance).context("prepare CommonJS graph")?;
        let mut without_probe_session = Vec::with_capacity(iterations);
        let mut with_probe_session = Vec::with_capacity(iterations);
        for iteration in 0..iterations {
            let cases = if iteration % 2 == 0 {
                [(false, "disabled"), (true, "enabled")]
            } else {
                [(true, "enabled"), (false, "disabled")]
            };
            for (enabled, suffix) in cases {
                let sample = timed_invoke(
                    &mut instance,
                    "run-generated",
                    &[Val::String(format!("./cjs-graph/measure-{suffix}.cjs"))],
                )
                .await
                .with_context(|| {
                    format!("CommonJS graph invocation with probe session {suffix}")
                })?;
                anyhow::ensure!(
                    successful_result(&sample["result"])
                        && sample.pointer("/result/value")
                            == Some(&json!(
                                "PASS: ajv compiles and runs schemas from installed CommonJS package graph"
                            )),
                    "controlled CommonJS graph failed with probe session {suffix}: {sample:#}"
                );
                validate_module_resolution_counters(&sample, enabled)?;
                if enabled {
                    with_probe_session.push(sample);
                } else {
                    anyhow::ensure!(
                        profile_counter(
                            &sample["result"]["profile"]["counters"],
                            "modules.pathProbe.sessionHits"
                        ) == 0,
                        "disabled CommonJS probe session still recorded cache hits: {sample:#}"
                    );
                    without_probe_session.push(sample);
                }
            }
        }

        let fixture = Utf8Path::new("tests/node_modules_apps/apps/popular-pure-js");
        let input_hashes = input_hashes().context("hash CommonJS graph inputs")?;
        let environment = environment(iterations, feature_combination.label())
            .context("capture CommonJS graph environment")?;
        let package_json_hash =
            hash_file(&fixture.join("package.json")).context("hash CommonJS graph package.json")?;
        let package_lock_hash = hash_file(&fixture.join("package-lock.json"))
            .context("hash CommonJS graph package-lock.json")?;
        let entry_hash =
            hash_file(&fixture.join("test-05-ajv.cjs")).context("hash CommonJS graph entry")?;
        let component_hash =
            hash_file(compiled.wasm_path()).context("hash CommonJS graph component")?;
        let formatted = serde_json::to_string_pretty(&json!({
            "schema": "cjs-graph-smoke-v2",
            "target": "p3",
            "iterations": iterations,
            "environment": environment,
            "inputs": {
                "algorithm": INPUT_HASH_ALGORITHM,
                "buildHash": input_hashes.build,
                "benchmarkHash": input_hashes.benchmark,
            },
            "fixture": {
                "packageJsonBlake3": package_json_hash,
                "packageLockBlake3": package_lock_hash,
                "entryBlake3": entry_hash,
            },
            "component": {
                "bytes": component_size,
                "blake3": component_hash,
                "buildMs": millis(build_elapsed),
                "prepareAndInstantiateMs": millis(instantiate_elapsed),
            },
            "commonJsGraph": {
                "withoutProbeSession": summarize(&without_probe_session),
                "withProbeSession": summarize(&with_probe_session),
            },
        }))
        .context("serialize CommonJS graph report")?;
        if let Ok(path) = std::env::var("AGENTIC_TS_CJS_GRAPH_SMOKE_REPORT") {
            fs::write(&path, format!("{formatted}\n"))
                .with_context(|| format!("write CommonJS graph report {path}"))?;
        }
        println!("{formatted}");
        return Ok(());
    }

    let node_baseline = node_baseline()?;
    let node_phase_profile = node_phase_profile()?;
    let cold = timed_invoke(
        &mut instance,
        "run-tsc",
        &[
            string_list(&["--noEmit", "-p", "projects/core/tsconfig.json"]),
            Val::U64(300_000),
        ],
    )
    .await?;
    let wasm_phase_profile =
        timed_invoke(&mut instance, "profile-tsc", &[Val::U64(300_000)]).await?;

    let mut unchanged = Vec::with_capacity(iterations);
    for _ in 0..iterations {
        unchanged.push(
            timed_invoke(
                &mut instance,
                "run-tsc",
                &[
                    string_list(&["-p", "projects/core/tsconfig.check.json"]),
                    Val::U64(300_000),
                ],
            )
            .await?,
        );
    }

    let incremental_cold = timed_invoke(
        &mut instance,
        "run-tsc",
        &[
            string_list(&[
                "--noEmit",
                "--incremental",
                "--tsBuildInfoFile",
                ".cache/manual.tsbuildinfo",
                "-p",
                "projects/core/tsconfig.json",
            ]),
            Val::U64(300_000),
        ],
    )
    .await?;
    let mut incremental = Vec::with_capacity(iterations);
    for _ in 0..iterations {
        incremental.push(
            timed_invoke(
                &mut instance,
                "run-tsc",
                &[
                    string_list(&[
                        "--noEmit",
                        "--incremental",
                        "--tsBuildInfoFile",
                        ".cache/manual.tsbuildinfo",
                        "-p",
                        "projects/core/tsconfig.json",
                    ]),
                    Val::U64(300_000),
                ],
            )
            .await?,
        );
    }

    let broken_path = instance
        .temp_dir_path()
        .join("workspace/projects/core/src/broken.ts");
    let mut failed_type_checks = Vec::with_capacity(iterations);
    for attempt in 0..iterations {
        fs::write(
            &broken_path,
            format!("export const broken: number = 'wrong-{attempt}';\n"),
        )?;
        failed_type_checks.push(
            timed_invoke(
                &mut instance,
                "run-tsc",
                &[
                    string_list(&["--noEmit", "-p", "projects/core/tsconfig.json"]),
                    Val::U64(300_000),
                ],
            )
            .await?,
        );
    }
    fs::write(&broken_path, "export const fixed: number = 42;\n")?;
    let failed_recovery = timed_invoke(
        &mut instance,
        "run-tsc",
        &[
            string_list(&["--noEmit", "-p", "projects/core/tsconfig.json"]),
            Val::U64(300_000),
        ],
    )
    .await?;

    let project_build = timed_invoke(
        &mut instance,
        "run-tsc",
        &[
            string_list(&["--build", "tsconfig.json"]),
            Val::U64(300_000),
        ],
    )
    .await?;
    let direct_ts = timed_invoke(
        &mut instance,
        "run-entry",
        &[Val::String("./projects/direct.ts".to_string())],
    )
    .await?;
    let emit_direct = timed_invoke(
        &mut instance,
        "run-tsc",
        &[
            string_list(&[
                "--module",
                "NodeNext",
                "--moduleResolution",
                "NodeNext",
                "--target",
                "ES2022",
                "--outDir",
                "dist/direct",
                "projects/direct.ts",
            ]),
            Val::U64(300_000),
        ],
    )
    .await?;
    let generated_js = timed_invoke(
        &mut instance,
        "run-generated",
        &[Val::String("./dist/direct/direct.js".to_string())],
    )
    .await?;
    let cpu_baseline = timed_invoke(&mut instance, "run-cpu", &[]).await?;
    let io_baseline = timed_invoke(&mut instance, "run-io", &[]).await?;
    let concurrent = json!({
        "cpuBaseline": cpu_baseline,
        "ioBaseline": io_baseline,
        "contended": timed_invoke(&mut instance, "run-concurrent", &[]).await?,
        "interpretation": "all jobs were submitted together; compare sibling completion with isolated baselines to identify overlap or serialization",
    });
    let mut timeouts = Vec::with_capacity(iterations);
    for _ in 0..iterations {
        timeouts.push(timed_invoke(&mut instance, "probe-timeout", &[]).await?);
    }
    let timeout_recovery = timed_invoke(
        &mut instance,
        "run-entry",
        &[Val::String("./projects/direct.ts".to_string())],
    )
    .await?;
    let mut cancellations = Vec::with_capacity(iterations);
    for _ in 0..iterations {
        cancellations.push(timed_invoke(&mut instance, "probe-cancellation", &[]).await?);
    }
    let cancellation_recovery = timed_invoke(
        &mut instance,
        "run-entry",
        &[Val::String("./projects/direct.ts".to_string())],
    )
    .await?;
    let memory_plateau = memory_plateau(
        &unchanged,
        &incremental,
        &failed_type_checks,
        &timeouts,
        &cancellations,
        &[
            ("coldNoEmit", &cold),
            ("phaseProfile", &wasm_phase_profile),
            ("incrementalCold", &incremental_cold),
            ("invalidRecovery", &failed_recovery),
            ("projectReferences", &project_build),
            ("directTypeScript", &direct_ts),
            ("emitDirect", &emit_direct),
            ("generatedJavaScript", &generated_js),
            ("cpuBaseline", &cpu_baseline),
            ("ioBaseline", &io_baseline),
            ("concurrent", &concurrent["contended"]),
            ("timeoutRecovery", &timeout_recovery),
            ("cancellationRecovery", &cancellation_recovery),
        ],
    )?;

    let environment = environment(iterations, feature_combination.label())?;
    let input_hashes = input_hashes()?;
    let report = json!({
        "schemaVersion": 5,
        "environment": environment,
        "inputs": {
            "algorithm": INPUT_HASH_ALGORITHM,
            "buildHash": input_hashes.build,
            "benchmarkHash": input_hashes.benchmark,
        },
        "target": "p3",
        "component": {
            "path": compiled.wasm_path().as_str(),
            "bytes": component_size,
            "blake3": hash_file(compiled.wasm_path())?,
            "buildMs": millis(build_elapsed),
            "prepareAndInstantiateMs": millis(instantiate_elapsed),
        },
        "nodeBaseline": node_baseline,
        "phaseProfiles": {
            "node": node_phase_profile,
            "wasm": wasm_phase_profile,
            "interpretation": "the shared TypeScript API profiler runs a no-emit core-project check; compare phase proportions within a target because instrumentation overhead differs between Node and QuickJS",
        },
        "workloads": {
            "coldNoEmit": cold,
            "unchangedFreshJobs": summarize(&unchanged),
            "incrementalCold": incremental_cold,
            "incrementalFreshJobs": summarize(&incremental),
            "invalidThenValid": {
                "failedChecks": summarize(&failed_type_checks),
                "recovery": failed_recovery,
            },
            "projectReferences": project_build,
            "directTypeScript": direct_ts,
            "emitDirect": emit_direct,
            "generatedJavaScript": generated_js,
            "concurrent": concurrent,
            "timeouts": {
                "attempts": summarize(&timeouts),
                "recovery": timeout_recovery,
            },
            "cancellations": {
                "attempts": summarize(&cancellations),
                "recovery": cancellation_recovery,
            },
            "memoryPlateau": memory_plateau,
        },
        "wasmLinearMemoryHighWaterBytes": instance.linear_memory_high_water_bytes(),
        "notes": [
            "manual local measurement; no CI threshold",
            "fresh QuickJS execution job per compiler/run operation",
            "workspace and .tsbuildinfo persist within the component instance",
        ],
    });

    validate_report(&report)?;
    validate_regression_guards(&report)?;
    let formatted = serde_json::to_string_pretty(&report)?;
    if let Ok(path) = std::env::var("AGENTIC_TS_REPORT") {
        fs::write(path, format!("{formatted}\n"))?;
    }
    println!("{formatted}");
    Ok(())
}

async fn run_release_baseline(
    compiled: &CompiledTest,
    instance: &mut TestInstance,
    iterations: usize,
    build_elapsed: Duration,
    instantiate_elapsed: Duration,
    component_size: u64,
    feature_combination: FeatureCombination,
) -> anyhow::Result<()> {
    const CHECK_ARGS: &[&str] = &["--noEmit", "-p", "projects/core/tsconfig.check.json"];
    const INCREMENTAL_ARGS: &[&str] = &[
        "--noEmit",
        "--incremental",
        "--tsBuildInfoFile",
        ".cache/release-baseline.tsbuildinfo",
        "-p",
        "projects/core/tsconfig.check.json",
    ];

    anyhow::ensure!(
        feature_combination.label() == "typescript-transform-runtime",
        "release baseline must use the production TypeScript feature"
    );
    let node_executable = command_text(Command::new("which").arg("node"))?;

    let mut host_cold = Vec::with_capacity(iterations);
    let mut wasm_cold = Vec::with_capacity(iterations);
    for iteration in 0..iterations {
        if iteration % 2 == 0 {
            host_cold.push(fresh_host_tsc(&node_executable, CHECK_ARGS)?);
            wasm_cold.push(fresh_wasm_tsc(compiled.wasm_path(), CHECK_ARGS).await?);
        } else {
            wasm_cold.push(fresh_wasm_tsc(compiled.wasm_path(), CHECK_ARGS).await?);
            host_cold.push(fresh_host_tsc(&node_executable, CHECK_ARGS)?);
        }
    }

    let host_workspace = camino_tempfile::Utf8TempDir::new()?;
    prepare_host_workspace(host_workspace.path())?;
    let mut host_repeated = Vec::with_capacity(iterations);
    let mut wasm_repeated = Vec::with_capacity(iterations);
    for iteration in 0..iterations {
        if iteration % 2 == 0 {
            host_repeated.push(host_tsc(
                &node_executable,
                host_workspace.path(),
                CHECK_ARGS,
            )?);
            wasm_repeated.push(wasm_tsc(instance, CHECK_ARGS).await?);
        } else {
            wasm_repeated.push(wasm_tsc(instance, CHECK_ARGS).await?);
            host_repeated.push(host_tsc(
                &node_executable,
                host_workspace.path(),
                CHECK_ARGS,
            )?);
        }
    }

    let host_incremental_seed =
        host_tsc(&node_executable, host_workspace.path(), INCREMENTAL_ARGS)?;
    let wasm_incremental_seed = wasm_tsc(instance, INCREMENTAL_ARGS).await?;
    let mut host_incremental = Vec::with_capacity(iterations);
    let mut wasm_incremental = Vec::with_capacity(iterations);
    for iteration in 0..iterations {
        if iteration % 2 == 0 {
            host_incremental.push(host_tsc(
                &node_executable,
                host_workspace.path(),
                INCREMENTAL_ARGS,
            )?);
            wasm_incremental.push(wasm_tsc(instance, INCREMENTAL_ARGS).await?);
        } else {
            wasm_incremental.push(wasm_tsc(instance, INCREMENTAL_ARGS).await?);
            host_incremental.push(host_tsc(
                &node_executable,
                host_workspace.path(),
                INCREMENTAL_ARGS,
            )?);
        }
    }

    let environment = environment(iterations, feature_combination.label())?;
    let input_hashes = input_hashes()?;
    let report = json!({
        "schema": "agentic-ts-release-baseline-v1",
        "environment": environment,
        "inputs": {
            "algorithm": INPUT_HASH_ALGORITHM,
            "buildHash": input_hashes.build,
            "benchmarkHash": input_hashes.benchmark,
        },
        "target": "p3",
        "fixture": {
            "name": "small",
            "project": "projects/core/tsconfig.check.json",
            "description": "the checked-in single-source core TypeScript project",
            "seriesArguments": {
                "coldAndRepeated": CHECK_ARGS,
                "incremental": INCREMENTAL_ARGS,
            },
        },
        "component": {
            "path": compiled.wasm_path().as_str(),
            "bytes": component_size,
            "blake3": hash_file(compiled.wasm_path())?,
            "buildMs": millis(build_elapsed),
            "initialPrepareAndInstantiateMs": millis(instantiate_elapsed),
        },
        "host": {
            "environmentPolicy": {
                "mode": "clear",
                "provided": ["HOME", "PATH"],
            },
            "coldFreshProcessState": summarize(&host_cold),
            "repeatedUnchangedFreshProcesses": summarize(&host_repeated),
            "incrementalSeed": host_incremental_seed,
            "incrementalFreshProcesses": summarize(&host_incremental),
        },
        "wasm": {
            "coldFreshJobState": summarize(&wasm_cold),
            "repeatedUnchangedFreshJobs": summarize(&wasm_repeated),
            "incrementalSeed": wasm_incremental_seed,
            "incrementalFreshJobs": summarize(&wasm_incremental),
        },
        "timingBoundary": {
            "host": "Node process spawn through exit; fresh-workspace preparation is excluded",
            "wasm": "run-tsc export invocation through result; component instantiation and fresh-workspace preparation are excluded",
        },
        "memory": {
            "allowedQuickJsHeapVariationBytes": ALLOWED_QUICKJS_HEAP_VARIATION_BYTES,
            "repeatedUnchangedQuickJsHeap": quickjs_heap_series(&wasm_repeated)?,
            "incrementalQuickJsHeap": quickjs_heap_series(&wasm_incremental)?,
            "reusedInstanceLinearMemoryHighWaterBytes": instance.linear_memory_high_water_bytes(),
            "interpretation": "fresh-job QuickJS terminal heaps are a reclamation guard; Wasm linear memory is a monotone instance-wide high-water observation",
        },
        "notes": [
            "manual local release measurement; no CI timing threshold",
            "production TypeScript transform feature; profiling-only filesystem counters disabled",
            "host commands use fresh Node processes; Wasm commands use fresh QuickJS jobs",
            "cold logical state uses fresh workspaces and Wasm instances outside the timed boundary",
            "only the incremental series preserves its explicit .tsbuildinfo",
        ],
    });

    validate_release_baseline_report(&report)?;
    let formatted = serde_json::to_string_pretty(&report)?;
    if let Ok(path) = std::env::var("AGENTIC_TS_REPORT") {
        fs::write(path, format!("{formatted}\n"))?;
    }
    println!("{formatted}");
    Ok(())
}

async fn fresh_wasm_tsc(wasm_path: &Utf8Path, args: &[&str]) -> anyhow::Result<Value> {
    let mut instance = TestInstance::new_with_memory_tracking(wasm_path).await?;
    prepare_workspace(&instance)?;
    wasm_tsc(&mut instance, args).await
}

async fn wasm_tsc(instance: &mut TestInstance, args: &[&str]) -> anyhow::Result<Value> {
    timed_invoke(instance, "run-tsc", &[string_list(args), Val::U64(300_000)]).await
}

fn fresh_host_tsc(node_executable: &str, args: &[&str]) -> anyhow::Result<Value> {
    let workspace = camino_tempfile::Utf8TempDir::new()?;
    prepare_host_workspace(workspace.path())?;
    host_tsc(node_executable, workspace.path(), args)
}

fn host_tsc(node_executable: &str, workspace: &Utf8Path, args: &[&str]) -> anyhow::Result<Value> {
    let started = Instant::now();
    let output = Command::new(node_executable)
        .current_dir(workspace)
        .arg("node_modules/typescript/lib/tsc.js")
        .args(args)
        .env_clear()
        .env("HOME", workspace.join(".home"))
        .env("PATH", workspace.join("node_modules/.bin"))
        .output()?;
    Ok(json!({
        "wallMs": millis(started.elapsed()),
        "result": {
            "value": { "exitCode": output.status.code() },
            "stdout": String::from_utf8_lossy(&output.stdout),
            "stderr": String::from_utf8_lossy(&output.stderr),
            "overflowed": false,
        },
    }))
}

fn prepare_host_workspace(workspace: &Utf8Path) -> anyhow::Result<()> {
    let source = Utf8Path::new(SUITE_DIR);
    fs::create_dir_all(workspace)?;
    for file in ["package.json", "package-lock.json", "tsconfig.json"] {
        fs::copy(source.join(file), workspace.join(file))?;
    }
    for directory in ["node_modules", "projects"] {
        copy_dir_recursive(
            source.join(directory).as_std_path(),
            workspace.join(directory).as_std_path(),
        )?;
    }
    fs::create_dir_all(workspace.join(".home"))?;
    fs::create_dir_all(workspace.join(".cache"))?;
    Ok(())
}

fn validate_release_baseline_report(report: &Value) -> anyhow::Result<()> {
    anyhow::ensure!(
        report["schema"] == "agentic-ts-release-baseline-v1",
        "unsupported release baseline schema"
    );
    let iterations = report["environment"]["iterations"]
        .as_u64()
        .filter(|iterations| *iterations >= 5)
        .ok_or_else(|| anyhow::anyhow!("release baseline needs at least five iterations"))?;
    anyhow::ensure!(
        report["fixture"]["name"] == "small"
            && report["fixture"]["project"] == "projects/core/tsconfig.check.json"
            && report["fixture"]["seriesArguments"]["coldAndRepeated"]
                == json!(["--noEmit", "-p", "projects/core/tsconfig.check.json"])
            && report["fixture"]["seriesArguments"]["incremental"]
                == json!([
                    "--noEmit",
                    "--incremental",
                    "--tsBuildInfoFile",
                    ".cache/release-baseline.tsbuildinfo",
                    "-p",
                    "projects/core/tsconfig.check.json"
                ])
            && report["environment"]["componentFeatures"] == "typescript-transform-runtime"
            && report["environment"]["componentCargoProfile"] == "release"
            && report["environment"]["harnessCargoProfile"] == "release"
            && report["host"]["environmentPolicy"]["mode"] == "clear"
            && report["host"]["environmentPolicy"]["provided"] == json!(["HOME", "PATH"])
            && report["timingBoundary"]["host"]
                .as_str()
                .is_some_and(|value| value.contains("excluded"))
            && report["timingBoundary"]["wasm"]
                .as_str()
                .is_some_and(|value| value.contains("excluded")),
        "release baseline does not identify the small production-profile fixture"
    );

    fn validate_series(
        series: &Value,
        label: &str,
        iterations: u64,
        require_linear_memory: bool,
    ) -> anyhow::Result<()> {
        let samples = series["samples"]
            .as_array()
            .ok_or_else(|| anyhow::anyhow!("{label} has no samples"))?;
        anyhow::ensure!(
            series["iterations"] == iterations && samples.len() as u64 == iterations,
            "{label} does not contain the declared sample count"
        );
        for sample in samples {
            anyhow::ensure!(
                successful_result(&sample["result"])
                    && sample.pointer("/result/value/exitCode") == Some(&json!(0))
                    && sample["wallMs"]
                        .as_f64()
                        .is_some_and(|duration| duration.is_finite() && duration >= 0.0),
                "{label} contains a failed or invalid sample: {sample:#}"
            );
            if require_linear_memory {
                anyhow::ensure!(
                    sample["linearMemoryHighWaterBytes"]
                        .as_u64()
                        .is_some_and(|bytes| bytes > 0),
                    "{label} sample has no Wasm memory observation"
                );
            }
        }
        let expected = summarize(samples);
        for field in ["medianMs", "p95Ms", "throughputPerSecond"] {
            let stored = series[field]
                .as_f64()
                .ok_or_else(|| anyhow::anyhow!("{label} {field} is not numeric"))?;
            let recomputed = expected[field]
                .as_f64()
                .expect("recomputed release summary field is numeric");
            let tolerance = f64::EPSILON * recomputed.abs().max(1.0) * 8.0;
            anyhow::ensure!(
                stored.is_finite() && (stored - recomputed).abs() <= tolerance,
                "{label} {field} does not reconcile with its samples"
            );
        }
        Ok(())
    }

    for (path, label, require_linear_memory) in [
        (
            "/host/coldFreshProcessState",
            "host cold release series",
            false,
        ),
        (
            "/host/repeatedUnchangedFreshProcesses",
            "host repeated release series",
            false,
        ),
        (
            "/host/incrementalFreshProcesses",
            "host incremental release series",
            false,
        ),
        ("/wasm/coldFreshJobState", "Wasm cold release series", true),
        (
            "/wasm/repeatedUnchangedFreshJobs",
            "Wasm repeated release series",
            true,
        ),
        (
            "/wasm/incrementalFreshJobs",
            "Wasm incremental release series",
            true,
        ),
    ] {
        validate_series(
            report
                .pointer(path)
                .ok_or_else(|| anyhow::anyhow!("missing {label}"))?,
            label,
            iterations,
            require_linear_memory,
        )?;
    }

    for (path, label, require_linear_memory) in [
        ("/host/incrementalSeed", "host incremental seed", false),
        ("/wasm/incrementalSeed", "Wasm incremental seed", true),
    ] {
        let sample = report
            .pointer(path)
            .ok_or_else(|| anyhow::anyhow!("missing {label}"))?;
        anyhow::ensure!(
            successful_result(&sample["result"])
                && sample.pointer("/result/value/exitCode") == Some(&json!(0))
                && sample["wallMs"]
                    .as_f64()
                    .is_some_and(|duration| duration.is_finite() && duration >= 0.0),
            "{label} failed: {sample:#}"
        );
        if require_linear_memory {
            anyhow::ensure!(
                sample["linearMemoryHighWaterBytes"]
                    .as_u64()
                    .is_some_and(|bytes| bytes > 0),
                "{label} has no Wasm memory observation"
            );
        }
    }

    anyhow::ensure!(
        report["memory"]["allowedQuickJsHeapVariationBytes"]
            == ALLOWED_QUICKJS_HEAP_VARIATION_BYTES,
        "release baseline changed the QuickJS heap-variation limit"
    );
    for (group, series_path) in [
        (
            "repeatedUnchangedQuickJsHeap",
            "/wasm/repeatedUnchangedFreshJobs/samples",
        ),
        (
            "incrementalQuickJsHeap",
            "/wasm/incrementalFreshJobs/samples",
        ),
    ] {
        let samples = report
            .pointer(series_path)
            .and_then(Value::as_array)
            .ok_or_else(|| anyhow::anyhow!("missing release samples for {group}"))?;
        anyhow::ensure!(
            report["memory"][group] == quickjs_heap_series(samples)?,
            "release baseline QuickJS heap summary does not reconcile for {group}"
        );
        for point in ["beforeToolLoad", "afterCompiler"] {
            anyhow::ensure!(
                report["memory"][group][point]["samples"]
                    .as_array()
                    .is_some_and(|samples| samples.len() as u64 == iterations)
                    && report["memory"][group][point]["variationBytes"]
                        .as_u64()
                        .is_some_and(|variation| variation <= ALLOWED_QUICKJS_HEAP_VARIATION_BYTES),
                "release baseline QuickJS heap varied unexpectedly for {group}/{point}"
            );
        }
    }
    let reused_instance_high_water = [
        "/wasm/repeatedUnchangedFreshJobs/samples",
        "/wasm/incrementalFreshJobs/samples",
    ]
    .into_iter()
    .flat_map(|path| {
        report
            .pointer(path)
            .and_then(Value::as_array)
            .into_iter()
            .flatten()
    })
    .chain(std::iter::once(&report["wasm"]["incrementalSeed"]))
    .filter_map(|sample| sample["linearMemoryHighWaterBytes"].as_u64())
    .max()
    .ok_or_else(|| anyhow::anyhow!("release baseline has no reused-instance memory observation"))?;
    anyhow::ensure!(
        report["memory"]["reusedInstanceLinearMemoryHighWaterBytes"].as_u64()
            == Some(reused_instance_high_water),
        "release baseline reused-instance memory high water does not reconcile"
    );
    Ok(())
}

fn validate_release_baseline_regression_guards(report: &Value) -> anyhow::Result<()> {
    let mut failed_host = report.clone();
    failed_host["host"]["coldFreshProcessState"]["samples"][0]["result"]["value"]["exitCode"] =
        json!(1);
    anyhow::ensure!(
        validate_release_baseline_report(&failed_host).is_err(),
        "release validator accepted a failed host sample"
    );

    let mut failed_wasm = report.clone();
    failed_wasm["wasm"]["coldFreshJobState"]["samples"][0]["result"]["value"]["exitCode"] =
        json!(1);
    anyhow::ensure!(
        validate_release_baseline_report(&failed_wasm).is_err(),
        "release validator accepted a failed Wasm sample"
    );

    let mut missing_sample = report.clone();
    missing_sample["host"]["repeatedUnchangedFreshProcesses"]["samples"]
        .as_array_mut()
        .expect("validated report has repeated host samples")
        .pop();
    anyhow::ensure!(
        validate_release_baseline_report(&missing_sample).is_err(),
        "release validator accepted a missing sample"
    );

    for field in ["medianMs", "p95Ms", "throughputPerSecond"] {
        let mut false_summary = report.clone();
        false_summary["host"]["repeatedUnchangedFreshProcesses"][field] = json!(1);
        anyhow::ensure!(
            validate_release_baseline_report(&false_summary).is_err(),
            "release validator accepted an unreconciled {field}"
        );
    }

    let mut adjacent_throughput = report.clone();
    let throughput =
        adjacent_throughput["host"]["repeatedUnchangedFreshProcesses"]["throughputPerSecond"]
            .as_f64()
            .expect("validated report has numeric throughput");
    adjacent_throughput["host"]["repeatedUnchangedFreshProcesses"]["throughputPerSecond"] =
        json!(f64::from_bits(throughput.to_bits() + 1));
    anyhow::ensure!(
        validate_release_baseline_report(&adjacent_throughput).is_ok(),
        "release validator rejected a one-ULP throughput round-trip difference"
    );

    let mut failed_seed = report.clone();
    failed_seed["wasm"]["incrementalSeed"]["result"]["value"]["exitCode"] = json!(1);
    anyhow::ensure!(
        validate_release_baseline_report(&failed_seed).is_err(),
        "release validator accepted a failed incremental seed"
    );

    let mut false_heap = report.clone();
    false_heap["memory"]["incrementalQuickJsHeap"]["afterCompiler"]["variationBytes"] =
        json!(u64::MAX);
    anyhow::ensure!(
        validate_release_baseline_report(&false_heap).is_err(),
        "release validator accepted an unreconciled heap summary"
    );

    let mut missing_memory = report.clone();
    missing_memory["wasm"]["coldFreshJobState"]["samples"][0]["linearMemoryHighWaterBytes"] =
        Value::Null;
    anyhow::ensure!(
        validate_release_baseline_report(&missing_memory).is_err(),
        "release validator accepted a sample without memory evidence"
    );

    let mut false_memory_high_water = report.clone();
    false_memory_high_water["memory"]["reusedInstanceLinearMemoryHighWaterBytes"] = json!(1);
    anyhow::ensure!(
        validate_release_baseline_report(&false_memory_high_water).is_err(),
        "release validator accepted an unreconciled memory high water"
    );
    Ok(())
}

struct CurrentReportIdentity {
    source_hint: String,
    build_hash: String,
    benchmark_hash: String,
}

fn validate_current_manifest_identity(
    path: &Utf8Path,
    report: &Value,
    identity: &CurrentReportIdentity,
) -> anyhow::Result<()> {
    anyhow::ensure!(
        report["environment"]["commitHint"].as_str() == Some(identity.source_hint.as_str()),
        "{path} source hint does not match its current-report manifest"
    );
    anyhow::ensure!(
        report["inputs"]["buildHash"].as_str() == Some(identity.build_hash.as_str()),
        "{path} build hash does not match its current-report manifest"
    );
    anyhow::ensure!(
        report["inputs"]["benchmarkHash"].as_str() == Some(identity.benchmark_hash.as_str()),
        "{path} benchmark hash does not match its current-report manifest"
    );
    Ok(())
}

fn validate_current_manifest_identity_regression_guards(
    path: &Utf8Path,
    report: &Value,
    identity: &CurrentReportIdentity,
) -> anyhow::Result<()> {
    for pointer in [
        "/environment/commitHint",
        "/inputs/buildHash",
        "/inputs/benchmarkHash",
    ] {
        let mut mismatched = report.clone();
        *mismatched
            .pointer_mut(pointer)
            .expect("validated report has currentness identity field") =
            json!("0000000000000000000000000000000000000000000000000000000000000000");
        anyhow::ensure!(
            validate_current_manifest_identity(path, &mismatched, identity).is_err(),
            "current-report manifest identity accepted a mismatched field: {pointer}"
        );
    }
    Ok(())
}

fn validate_checked_reports(directory: camino::Utf8PathBuf) -> anyhow::Result<()> {
    validate_composite_hash_contract()?;
    validate_report_path_contract()?;
    let tracker = fs::read_to_string(Utf8Path::new(SUITE_DIR).join("TRACKER.md"))?;
    let allow_untracked_reports = std::env::var_os("AGENTIC_TS_ALLOW_UNTRACKED_REPORTS").is_some();
    let mut reports_to_check = reports_to_check()?;
    let mut current_manifest_reports = report_paths_from_env("AGENTIC_TS_CURRENT_REPORTS")?;
    anyhow::ensure!(
        allow_untracked_reports || !current_manifest_reports.is_empty(),
        "checked-report validation requires manifest identity; use tests/agentic_ts/run.sh --check"
    );
    let current_manifest_identity = if current_manifest_reports.is_empty() {
        None
    } else {
        Some(CurrentReportIdentity {
            source_hint: std::env::var("AGENTIC_TS_EXPECTED_SOURCE_REF").context(
                "AGENTIC_TS_EXPECTED_SOURCE_REF is required with AGENTIC_TS_CURRENT_REPORTS",
            )?,
            build_hash: std::env::var("AGENTIC_TS_EXPECTED_BUILD_HASH").context(
                "AGENTIC_TS_EXPECTED_BUILD_HASH is required with AGENTIC_TS_CURRENT_REPORTS",
            )?,
            benchmark_hash: std::env::var("AGENTIC_TS_EXPECTED_BENCHMARK_HASH").context(
                "AGENTIC_TS_EXPECTED_BENCHMARK_HASH is required with AGENTIC_TS_CURRENT_REPORTS",
            )?,
        })
    };
    let current_input_hashes = if reports_to_check.is_empty() {
        None
    } else {
        Some(input_hashes()?)
    };
    let mut reports = BTreeMap::new();
    let mut cjs_graph_reports = BTreeMap::new();
    let mut release_baseline_reports = BTreeMap::new();
    for entry in fs::read_dir(&directory)? {
        let path = camino::Utf8PathBuf::from_path_buf(entry?.path())
            .map_err(|path| anyhow::anyhow!("non-UTF-8 report path: {}", path.display()))?;
        if path.extension() != Some("json") {
            continue;
        }
        let filename = path
            .file_name()
            .ok_or_else(|| anyhow::anyhow!("report has no filename: {path}"))?
            .to_string();
        let report: Value = serde_json::from_slice(&fs::read(&path)?)?;
        let is_cjs_graph = report["schema"] == "cjs-graph-smoke-v2";
        let is_release_baseline = report["schema"] == "agentic-ts-release-baseline-v1";
        if is_cjs_graph {
            validate_cjs_graph_report_metadata(&path, &report)?;
            validate_cjs_graph_report(&report)?;
            validate_cjs_graph_regression_guards(&report)?;
        } else if is_release_baseline {
            validate_release_baseline_metadata(&path, &report)?;
            validate_release_baseline_report(&report)?;
            validate_release_baseline_regression_guards(&report)?;
        } else {
            validate_report_metadata(&path, &report)?;
            validate_report(&report)?;
            validate_regression_guards(&report)?;
        }
        if current_manifest_reports.remove(&path) {
            let identity = current_manifest_identity
                .as_ref()
                .expect("manifest identity exists");
            validate_current_manifest_identity(&path, &report, identity)?;
            validate_current_manifest_identity_regression_guards(&path, &report, identity)?;
        }
        let check_current = reports_to_check.remove(&path);
        if check_current {
            validate_current_inputs(&path, &report, current_input_hashes.as_ref().unwrap())?;
        }
        anyhow::ensure!(
            tracker.contains(&filename) || (allow_untracked_reports && check_current),
            "TRACKER.md does not reference {filename}"
        );
        if is_cjs_graph {
            cjs_graph_reports.insert(filename, report);
        } else if is_release_baseline {
            release_baseline_reports.insert(filename, report);
        } else {
            reports.insert(filename, report);
        }
    }
    anyhow::ensure!(!reports.is_empty(), "no checked-in reports found");
    anyhow::ensure!(
        reports_to_check.is_empty(),
        "reports requested for currentness checking were not found: {reports_to_check:?}"
    );
    anyhow::ensure!(
        current_manifest_reports.is_empty(),
        "current-report manifest entries were not found: {current_manifest_reports:?}"
    );

    // P2 generation was removed; retained P2 reports are historical and must keep their
    // P3 companion. Current measurements are P3-only.
    for (filename, p2) in reports
        .iter()
        .filter(|(filename, _)| filename.contains("-p2-"))
    {
        let p3_filename = filename.replacen("-p2-", "-p3-", 1);
        let p3 = reports.get(&p3_filename).ok_or_else(|| {
            anyhow::anyhow!("missing P3 companion for historical P2 report {filename}")
        })?;
        validate_report_pair(filename, &p3_filename, p2, p3)?;
        let mut duplicate_component = p3.clone();
        duplicate_component["component"]["blake3"] = p2["component"]["blake3"].clone();
        anyhow::ensure!(
            validate_report_pair(filename, &p3_filename, p2, &duplicate_component).is_err(),
            "paired-report guard accepted an identical P2/P3 component digest"
        );
    }

    anyhow::ensure!(
        !cjs_graph_reports.is_empty(),
        "checked reports must include the GOL-350 CommonJS graph P2/P3 evidence"
    );
    for (filename, p2) in cjs_graph_reports
        .iter()
        .filter(|(filename, _)| filename.contains("-p2-"))
    {
        let p3_filename = filename.replacen("-p2-", "-p3-", 1);
        let p3 = cjs_graph_reports.get(&p3_filename).ok_or_else(|| {
            anyhow::anyhow!("missing P3 companion for historical P2 report {filename}")
        })?;
        validate_cjs_graph_report_pair(filename, &p3_filename, p2, p3)?;
    }

    for (filename, p2) in release_baseline_reports
        .iter()
        .filter(|(filename, _)| filename.contains("-p2-"))
    {
        let p3_filename = filename.replacen("-p2-", "-p3-", 1);
        let p3 = release_baseline_reports.get(&p3_filename).ok_or_else(|| {
            anyhow::anyhow!("missing P3 companion for historical P2 report {filename}")
        })?;
        validate_release_baseline_pair(filename, &p3_filename, p2, p3)?;
        let mut duplicate_component = p3.clone();
        duplicate_component["component"]["blake3"] = p2["component"]["blake3"].clone();
        anyhow::ensure!(
            validate_release_baseline_pair(filename, &p3_filename, p2, &duplicate_component)
                .is_err(),
            "paired release-baseline guard accepted an identical P2/P3 component digest"
        );
    }
    Ok(())
}

fn validate_report_pair(
    p2_filename: &str,
    p3_filename: &str,
    p2: &Value,
    p3: &Value,
) -> anyhow::Result<()> {
    for field in [
        "/inputs/algorithm",
        "/inputs/buildHash",
        "/inputs/benchmarkHash",
        "/environment/commitHint",
        "/environment/dirty",
        "/environment/iterations",
        "/environment/node",
        "/environment/npm",
        "/environment/typescript",
        "/environment/componentFeatures",
        "/environment/componentCargoProfile",
        "/environment/harnessCargoProfile",
        "/environment/lockedBuilds",
        "/environment/rustc",
        "/environment/cargo",
    ] {
        anyhow::ensure!(
            p2.pointer(field) == p3.pointer(field),
            "paired reports {p2_filename} and {p3_filename} disagree at {field}"
        );
    }
    anyhow::ensure!(
        p2.pointer("/component/blake3") != p3.pointer("/component/blake3"),
        "paired reports {p2_filename} and {p3_filename} use the same component digest"
    );
    Ok(())
}

fn validate_cjs_graph_report_pair(
    p2_filename: &str,
    p3_filename: &str,
    p2: &Value,
    p3: &Value,
) -> anyhow::Result<()> {
    validate_report_pair(p2_filename, p3_filename, p2, p3)?;
    for field in [
        "/schema",
        "/iterations",
        "/fixture/packageJsonBlake3",
        "/fixture/packageLockBlake3",
        "/fixture/entryBlake3",
    ] {
        anyhow::ensure!(
            p2.pointer(field) == p3.pointer(field),
            "paired CommonJS graph reports {p2_filename} and {p3_filename} disagree at {field}"
        );
    }
    Ok(())
}

fn validate_release_baseline_pair(
    p2_filename: &str,
    p3_filename: &str,
    p2: &Value,
    p3: &Value,
) -> anyhow::Result<()> {
    validate_report_pair(p2_filename, p3_filename, p2, p3)?;
    for field in ["/schema", "/fixture/name", "/fixture/project"] {
        anyhow::ensure!(
            p2.pointer(field) == p3.pointer(field),
            "paired release baselines {p2_filename} and {p3_filename} disagree at {field}"
        );
    }
    Ok(())
}

fn validate_release_baseline_metadata(path: &Utf8Path, report: &Value) -> anyhow::Result<()> {
    let target = report["target"]
        .as_str()
        .filter(|target| matches!(*target, "p2" | "p3"))
        .ok_or_else(|| anyhow::anyhow!("{path} has no supported target"))?;
    let os = report["environment"]["os"]
        .as_str()
        .ok_or_else(|| anyhow::anyhow!("{path} has no OS"))?;
    let arch = report["environment"]["arch"]
        .as_str()
        .ok_or_else(|| anyhow::anyhow!("{path} has no architecture"))?;
    let filename = path
        .file_name()
        .ok_or_else(|| anyhow::anyhow!("{path} has no filename"))?;
    anyhow::ensure!(
        filename.contains("-release-")
            && filename.ends_with(&format!("-{target}-{os}-{arch}.json")),
        "{path} filename does not identify a release target and host"
    );
    anyhow::ensure!(
        report["environment"]["node"] == "22.14.0"
            && report["environment"]["npm"] == "10.9.2"
            && report["environment"]["typescript"] == "5.8.2"
            && report["environment"]["dirty"] == false
            && report["environment"]["lockedBuilds"] == "1"
            && report["environment"]["artifactCache"].is_null()
            && report["environment"]["wasmtimeCache"].is_null()
            && report["environment"]["preparedComponentCache"].is_null()
            && report["environment"]["unoptimized"].is_null(),
        "{path} does not use the pinned clean-state release settings"
    );
    // Historical P2 reports used the shadow lock; P3 reports use the workspace lock, or the
    // fork shadow lock when measured with `tools/dev-test.sh fork`.
    let expected_lock_kinds: &[&str] = if target == "p2" {
        &["p2-shadow"]
    } else {
        &["workspace", "fork-shadow"]
    };
    anyhow::ensure!(
        report["inputs"]["algorithm"] == INPUT_HASH_ALGORITHM
            && is_blake3_hash(&report["inputs"]["buildHash"])
            && is_blake3_hash(&report["inputs"]["benchmarkHash"])
            && is_blake3_hash(&report["component"]["blake3"])
            && report["component"]["bytes"]
                .as_u64()
                .is_some_and(|bytes| bytes > 0)
            && report["environment"]["hostDependencyGraph"]["kind"]
                .as_str()
                .is_some_and(|kind| expected_lock_kinds.contains(&kind))
            && is_blake3_hash(&report["environment"]["hostDependencyGraph"]["lockBlake3"])
            && report["environment"]["commitHint"]
                .as_str()
                .is_some_and(|commit| !commit.is_empty())
            && report["environment"]["rustc"]
                .as_str()
                .is_some_and(|version| !version.is_empty())
            && report["environment"]["cargo"]
                .as_str()
                .is_some_and(|version| !version.is_empty()),
        "{path} has incomplete release provenance"
    );
    Ok(())
}

fn validate_cjs_graph_report_metadata(path: &Utf8Path, report: &Value) -> anyhow::Result<()> {
    anyhow::ensure!(
        report["schema"] == "cjs-graph-smoke-v2",
        "{path} uses an unsupported CommonJS graph schema"
    );
    anyhow::ensure!(
        report["environment"]["node"] == "22.14.0"
            && report["environment"]["npm"] == "10.9.2"
            && report["environment"]["typescript"] == "5.8.2"
            && report["environment"]["componentFeatures"] == "typescript-compiler-profiling"
            && report["environment"]["iterations"] == report["iterations"]
            && report["iterations"].as_u64().unwrap_or(0) >= 5,
        "{path} does not use the pinned CommonJS graph settings"
    );
    let target = report["target"]
        .as_str()
        .filter(|target| matches!(*target, "p2" | "p3"))
        .ok_or_else(|| anyhow::anyhow!("{path} has no supported target"))?;
    let os = report["environment"]["os"]
        .as_str()
        .ok_or_else(|| anyhow::anyhow!("{path} has no OS"))?;
    let arch = report["environment"]["arch"]
        .as_str()
        .ok_or_else(|| anyhow::anyhow!("{path} has no architecture"))?;
    let filename = path
        .file_name()
        .ok_or_else(|| anyhow::anyhow!("{path} has no filename"))?;
    anyhow::ensure!(
        filename.ends_with(&format!("-gol-350-cjs-{target}-{os}-{arch}.json")),
        "{path} filename does not match its workload, target, and host metadata"
    );
    anyhow::ensure!(
        report["inputs"]["algorithm"] == INPUT_HASH_ALGORITHM
            && is_blake3_hash(&report["inputs"]["buildHash"])
            && is_blake3_hash(&report["inputs"]["benchmarkHash"])
            && is_blake3_hash(&report["fixture"]["packageJsonBlake3"])
            && is_blake3_hash(&report["fixture"]["packageLockBlake3"])
            && is_blake3_hash(&report["fixture"]["entryBlake3"])
            && is_blake3_hash(&report["component"]["blake3"])
            && report["environment"]["commitHint"]
                .as_str()
                .is_some_and(|commit| !commit.is_empty())
            && report["environment"]["dirty"] == false,
        "{path} has incomplete or dirty CommonJS graph provenance"
    );
    Ok(())
}

fn validate_cjs_graph_report(report: &Value) -> anyhow::Result<()> {
    let iterations = report["iterations"]
        .as_u64()
        .ok_or_else(|| anyhow::anyhow!("CommonJS graph report has no iteration count"))?;
    for (series_name, require_session_hits) in
        [("withoutProbeSession", false), ("withProbeSession", true)]
    {
        let series = &report["commonJsGraph"][series_name];
        let samples = series["samples"]
            .as_array()
            .ok_or_else(|| anyhow::anyhow!("CommonJS graph report has no {series_name} samples"))?;
        anyhow::ensure!(
            series["iterations"] == iterations && samples.len() as u64 == iterations,
            "CommonJS graph {series_name} summary does not contain every requested sample"
        );
        for sample in samples {
            anyhow::ensure!(
                successful_result(&sample["result"])
                    && sample.pointer("/result/value")
                        == Some(&json!(
                            "PASS: ajv compiles and runs schemas from installed CommonJS package graph"
                        )),
                "checked CommonJS graph {series_name} sample failed: {sample:#}"
            );
            validate_module_resolution_counters(sample, require_session_hits)?;
            if !require_session_hits {
                anyhow::ensure!(
                    profile_counter(
                        &sample["result"]["profile"]["counters"],
                        "modules.pathProbe.sessionHits"
                    ) == 0,
                    "checked CommonJS graph disabled series recorded session hits"
                );
            }
        }
    }
    Ok(())
}

fn validate_cjs_graph_regression_guards(report: &Value) -> anyhow::Result<()> {
    let mut missing_session_hits = report.clone();
    missing_session_hits["commonJsGraph"]["withProbeSession"]["samples"][0]["result"]["profile"]
        ["counters"]["modules.pathProbe.sessionHits"] = json!(0);
    anyhow::ensure!(
        validate_cjs_graph_report(&missing_session_hits).is_err(),
        "CommonJS graph validation accepted a sample without reconciled session hits"
    );

    let mut failed_sample = report.clone();
    failed_sample["commonJsGraph"]["withoutProbeSession"]["samples"][0]["result"]["value"] =
        json!("FAIL");
    anyhow::ensure!(
        validate_cjs_graph_report(&failed_sample).is_err(),
        "CommonJS graph validation accepted a failed workload"
    );
    Ok(())
}

fn validate_report_metadata(path: &Utf8Path, report: &Value) -> anyhow::Result<()> {
    anyhow::ensure!(
        report["schemaVersion"] == 4 || report["schemaVersion"] == 5,
        "{path} uses an unsupported schema"
    );
    anyhow::ensure!(
        report["environment"]["node"] == "22.14.0"
            && report["environment"]["npm"] == "10.9.2"
            && report["environment"]["typescript"] == "5.8.2"
            && report["environment"]["iterations"].as_u64().unwrap_or(0) >= 5,
        "{path} does not use the pinned baseline settings"
    );
    if report["schemaVersion"] == 5 {
        anyhow::ensure!(
            report["environment"]["componentFeatures"] == "typescript-compiler-profiling",
            "{path} does not identify the profiling component feature"
        );
    }
    let target = report["target"]
        .as_str()
        .ok_or_else(|| anyhow::anyhow!("{path} has no target"))?;
    let os = report["environment"]["os"]
        .as_str()
        .ok_or_else(|| anyhow::anyhow!("{path} has no OS"))?;
    let arch = report["environment"]["arch"]
        .as_str()
        .ok_or_else(|| anyhow::anyhow!("{path} has no architecture"))?;
    let filename = path
        .file_name()
        .ok_or_else(|| anyhow::anyhow!("{path} has no filename"))?;
    anyhow::ensure!(
        filename.ends_with(&format!("-{target}-{os}-{arch}.json")),
        "{path} filename does not match its target and host metadata"
    );
    if filename.contains("-release-") {
        anyhow::ensure!(
            report["environment"]["componentCargoProfile"] == "release"
                && report["environment"]["harnessCargoProfile"] == "release"
                && is_blake3_hash(&report["environment"]["hostDependencyGraph"]["lockBlake3"]),
            "{path} is labeled as a release measurement without release profiles and a pinned host graph"
        );
    }
    anyhow::ensure!(
        report["inputs"]["algorithm"] == INPUT_HASH_ALGORITHM
            && is_blake3_hash(&report["inputs"]["buildHash"])
            && is_blake3_hash(&report["inputs"]["benchmarkHash"])
            && is_blake3_hash(&report["component"]["blake3"])
            && report["environment"]["commitHint"]
                .as_str()
                .is_some_and(|commit| !commit.is_empty())
            && report["environment"]["rustc"]
                .as_str()
                .is_some_and(|version| !version.is_empty())
            && report["environment"]["cargo"]
                .as_str()
                .is_some_and(|version| !version.is_empty()),
        "{path} has incomplete source fingerprints"
    );
    Ok(())
}

fn reports_to_check() -> anyhow::Result<BTreeSet<camino::Utf8PathBuf>> {
    report_paths_from_env("AGENTIC_TS_REPORTS_TO_CHECK")
}

fn report_paths_from_env(variable: &str) -> anyhow::Result<BTreeSet<camino::Utf8PathBuf>> {
    let results_directory = Utf8Path::new(SUITE_DIR).join("results");
    let current_directory = camino::Utf8PathBuf::from_path_buf(std::env::current_dir()?)
        .map_err(|path| anyhow::anyhow!("non-UTF-8 current directory: {}", path.display()))?;
    let configured_source_root = camino::Utf8PathBuf::from(
        std::env::var("AGENTIC_TS_SOURCE_ROOT").unwrap_or_else(|_| ".".to_string()),
    );
    let source_root = if configured_source_root == Utf8Path::new(".") {
        current_directory
    } else if configured_source_root.is_absolute() {
        configured_source_root
    } else {
        current_directory.join(configured_source_root)
    };
    std::env::var(variable)
        .unwrap_or_default()
        .lines()
        .filter(|line| !line.trim().is_empty())
        .map(|line| normalize_report_path(line.trim(), &source_root, &results_directory))
        .collect()
}

fn normalize_report_path(
    value: &str,
    source_root: &Utf8Path,
    results_directory: &Utf8Path,
) -> anyhow::Result<camino::Utf8PathBuf> {
    let path = Utf8Path::new(value);
    let path = if path.is_absolute() {
        path.strip_prefix(source_root).map_err(|_| {
            anyhow::anyhow!("report path to check is outside {source_root}: {value}")
        })?
    } else {
        path
    };
    anyhow::ensure!(
        path.parent() == Some(results_directory)
            && path.extension() == Some("json")
            && !path
                .components()
                .any(|component| component.as_str() == ".."),
        "report path to check is outside {results_directory}: {value}"
    );
    Ok(path.to_path_buf())
}

fn validate_report_path_contract() -> anyhow::Result<()> {
    let root = camino_tempfile::Utf8TempDir::new()?;
    let results_directory = Utf8Path::new(SUITE_DIR).join("results");
    let relative = results_directory.join("report.json");
    anyhow::ensure!(
        normalize_report_path(relative.as_str(), root.path(), &results_directory)? == relative,
        "relative report paths are not preserved"
    );
    anyhow::ensure!(
        normalize_report_path(
            root.path().join(&relative).as_str(),
            root.path(),
            &results_directory,
        )? == relative,
        "absolute report paths are not normalized"
    );
    anyhow::ensure!(
        normalize_report_path(
            "tests/agentic_ts/other/report.json",
            root.path(),
            &results_directory
        )
        .is_err(),
        "out-of-directory report path was accepted"
    );
    Ok(())
}

fn validate_current_inputs(
    path: &Utf8Path,
    report: &Value,
    current: &InputHashes,
) -> anyhow::Result<()> {
    anyhow::ensure!(
        report["inputs"]["buildHash"] == current.build,
        "{path} build inputs are stale: report={}, current={}",
        report["inputs"]["buildHash"],
        current.build,
    );
    anyhow::ensure!(
        report["inputs"]["benchmarkHash"] == current.benchmark,
        "{path} benchmark inputs are stale: report={}, current={}",
        report["inputs"]["benchmarkHash"],
        current.benchmark,
    );
    Ok(())
}

fn is_blake3_hash(value: &Value) -> bool {
    value.as_str().is_some_and(|hash| {
        hash.len() == 64
            && hash
                .bytes()
                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
    })
}

async fn timed_invoke(
    instance: &mut TestInstance,
    function: &str,
    args: &[Val],
) -> anyhow::Result<Value> {
    instance.set_epoch_deadline(INVOCATION_DEADLINE_SECONDS);
    let started = Instant::now();
    let value = instance.invoke(None, function, args).await?;
    let elapsed = started.elapsed();
    let Some(Val::String(encoded)) = value else {
        anyhow::bail!("{function} did not return a JSON string")
    };
    let wall_ms = millis(elapsed);
    let result = serde_json::from_str::<Value>(&encoded)?;
    let outer_overhead_ms = result
        .pointer("/value/toolAndCompilerMs")
        .or_else(|| result.pointer("/value/phasesMs/measuredTotal"))
        .and_then(Value::as_f64)
        .map(|inner_ms| wall_ms - inner_ms);
    Ok(json!({
        "wallMs": wall_ms,
        "outerOverheadMs": outer_overhead_ms,
        "linearMemoryHighWaterBytes": instance.linear_memory_high_water_bytes(),
        "result": result,
    }))
}

fn summarize(samples: &[Value]) -> Value {
    let mut durations = samples
        .iter()
        .filter_map(|sample| sample["wallMs"].as_f64())
        .collect::<Vec<_>>();
    durations.sort_by(f64::total_cmp);
    let total = durations.iter().sum::<f64>();
    let p95_index = ((durations.len() as f64 * 0.95).ceil() as usize)
        .saturating_sub(1)
        .min(durations.len() - 1);
    json!({
        "iterations": durations.len(),
        "medianMs": durations[durations.len() / 2],
        "p95Ms": durations[p95_index],
        "throughputPerSecond": durations.len() as f64 / (total / 1000.0),
        "samples": samples,
    })
}

fn quickjs_heap_series(samples: &[Value]) -> anyhow::Result<Value> {
    fn values_at(samples: &[Value], point: &str) -> anyhow::Result<Vec<u64>> {
        samples
            .iter()
            .map(|sample| {
                sample
                    .pointer(&format!("/result/value/quickJsMemory/{point}/heapUsed"))
                    .and_then(Value::as_u64)
                    .ok_or_else(|| anyhow::anyhow!("missing QuickJS heap sample at {point}"))
            })
            .collect()
    }

    fn summarize_values(values: Vec<u64>) -> Value {
        let minimum = values.iter().copied().min().unwrap_or(0);
        let maximum = values.iter().copied().max().unwrap_or(0);
        json!({
            "samples": values,
            "minimumBytes": minimum,
            "maximumBytes": maximum,
            "variationBytes": maximum - minimum,
        })
    }

    Ok(json!({
        "beforeToolLoad": summarize_values(values_at(samples, "beforeToolLoad")?),
        "afterCompiler": summarize_values(values_at(samples, "afterCompiler")?),
    }))
}

fn memory_plateau(
    unchanged: &[Value],
    incremental: &[Value],
    failed: &[Value],
    timeouts: &[Value],
    cancellations: &[Value],
    checkpoints: &[(&str, &Value)],
) -> anyhow::Result<Value> {
    fn linear_memory_series(samples: &[Value]) -> anyhow::Result<Value> {
        let values = samples
            .iter()
            .map(|sample| {
                sample["linearMemoryHighWaterBytes"]
                    .as_u64()
                    .ok_or_else(|| anyhow::anyhow!("missing linear-memory high-water sample"))
            })
            .collect::<anyhow::Result<Vec<_>>>()?;
        let minimum = values.iter().copied().min().unwrap_or(0);
        let maximum = values.iter().copied().max().unwrap_or(0);
        Ok(json!({
            "samples": values,
            "minimumBytes": minimum,
            "maximumBytes": maximum,
            "growthBytes": maximum - minimum,
        }))
    }

    let checkpoints = checkpoints
        .iter()
        .map(|(label, sample)| {
            Ok(json!({
                "label": label,
                "bytes": sample["linearMemoryHighWaterBytes"]
                    .as_u64()
                    .ok_or_else(|| anyhow::anyhow!("missing linear-memory checkpoint"))?,
            }))
        })
        .collect::<anyhow::Result<Vec<_>>>()?;

    Ok(json!({
        "wasmLinearMemory": {
            "unchangedCompilerJobs": linear_memory_series(unchanged)?,
            "warmedIncrementalCompilerJobs": linear_memory_series(incremental)?,
            "failedCompilerJobs": linear_memory_series(failed)?,
            "timedOutJobs": linear_memory_series(timeouts)?,
            "cancelledJobs": linear_memory_series(cancellations)?,
            "otherWorkloadCheckpoints": checkpoints,
            "interpretation": "descriptive instance-wide monotone high-water observations; they show where the reserved peak grows but cannot identify allocations that remain within an earlier peak",
        },
        "quickJsHeap": {
            "allowedVariationBytes": ALLOWED_QUICKJS_HEAP_VARIATION_BYTES,
            "unchangedCompilerJobs": quickjs_heap_series(unchanged)?,
            "warmedIncrementalCompilerJobs": quickjs_heap_series(incremental)?,
            "failedCompilerJobs": quickjs_heap_series(failed)?,
            "interpretation": "before-tool-load samples compare fresh runtimes; after-compiler samples describe heap usage immediately before each runtime is dropped",
        },
    }))
}

struct InputHashes {
    build: String,
    benchmark: String,
}

fn input_hashes() -> anyhow::Result<InputHashes> {
    let source_root = std::env::var("AGENTIC_TS_SOURCE_ROOT").unwrap_or_else(|_| ".".to_string());
    let source_root = Utf8Path::new(&source_root);

    let mut build_files = input_files(&[
        "Cargo.toml",
        "Cargo.lock",
        ".github/scripts/enable-wasmtime-fork.sh",
        "crates/golem-context/Cargo.toml",
        "crates/golem-websocket/Cargo.toml",
        "crates/wasi-logging/Cargo.toml",
        "crates/wasm-rquickjs/Cargo.toml",
        "crates/wasm-rquickjs/skeleton/Cargo.toml_",
        "crates/wasm-rquickjs/skeleton/Cargo.lock",
    ]);
    for directory in [
        "crates/wasi-logging/src",
        "crates/wasm-rquickjs/src",
        "crates/wasm-rquickjs/skeleton/src",
        EXAMPLE_DIR,
    ] {
        collect_input_files(source_root, Utf8Path::new(directory), &mut build_files)
            .with_context(|| format!("collect build inputs from {directory}"))?;
    }

    let mut benchmark_files = input_files(&[
        "tests/agentic_ts.rs",
        "tests/agentic_ts/package.json",
        "tests/agentic_ts/package-lock.json",
        "tests/agentic_ts/profile-typescript.mjs",
        "tests/agentic_ts/tsconfig.json",
        "tests/agentic_ts/run.sh",
        "tools/dev-test.sh",
    ]);
    collect_input_files(
        source_root,
        Utf8Path::new("tests/agentic_ts/projects"),
        &mut benchmark_files,
    )
    .context("collect TypeScript project benchmark inputs")?;
    for directory in [
        "tests/common",
        "crates/golem-websocket/wit",
        "crates/golem-websocket/wit-p3",
    ] {
        collect_input_files(source_root, Utf8Path::new(directory), &mut benchmark_files)
            .with_context(|| format!("collect benchmark inputs from {directory}"))?;
    }
    for required in [
        "tests/common/js_subtest_parser.rs",
        "tests/common/test_server.rs",
        "crates/golem-websocket/wit/golem-websocket.wit",
        "crates/golem-websocket/wit-p3/golem-websocket.wit",
    ] {
        anyhow::ensure!(
            benchmark_files.contains(Utf8Path::new(required)),
            "required benchmark input is not covered: {required}"
        );
    }

    Ok(InputHashes {
        build: composite_hash(source_root, "build", &build_files)
            .context("hash collected build inputs")?,
        benchmark: composite_hash(source_root, "benchmark", &benchmark_files)
            .context("hash collected benchmark inputs")?,
    })
}

fn input_files(paths: &[&str]) -> BTreeSet<camino::Utf8PathBuf> {
    paths
        .iter()
        .map(|path| Utf8Path::new(path).to_path_buf())
        .collect()
}

fn collect_input_files(
    source_root: &Utf8Path,
    directory: &Utf8Path,
    files: &mut BTreeSet<camino::Utf8PathBuf>,
) -> anyhow::Result<()> {
    for entry in fs::read_dir(source_root.join(directory))? {
        let entry = entry?;
        let name = entry
            .file_name()
            .into_string()
            .map_err(|name| anyhow::anyhow!("non-UTF-8 input name: {}", name.to_string_lossy()))?;
        let path = directory.join(name);
        let metadata = fs::symlink_metadata(source_root.join(&path))?;
        anyhow::ensure!(
            !metadata.file_type().is_symlink(),
            "input symlinks are unsupported: {path}"
        );
        if metadata.is_dir() {
            collect_input_files(source_root, &path, files)?;
        } else {
            anyhow::ensure!(metadata.is_file(), "unsupported input type: {path}");
            files.insert(path);
        }
    }
    Ok(())
}

fn composite_hash(
    source_root: &Utf8Path,
    domain: &str,
    files: &BTreeSet<camino::Utf8PathBuf>,
) -> anyhow::Result<String> {
    anyhow::ensure!(!files.is_empty(), "{domain} input set is empty");
    let mut hasher = blake3::Hasher::new();
    hash_part(&mut hasher, INPUT_HASH_ALGORITHM.as_bytes());
    hash_part(&mut hasher, domain.as_bytes());
    for path in files {
        anyhow::ensure!(
            path.is_relative()
                && !path
                    .components()
                    .any(|component| component.as_str() == ".."),
            "input path escapes the source root: {path}"
        );
        let metadata = fs::symlink_metadata(source_root.join(path))
            .with_context(|| format!("read {domain} input metadata for {path}"))?;
        anyhow::ensure!(
            metadata.is_file() && !metadata.file_type().is_symlink(),
            "input is not a regular file: {path}"
        );
        let components = path.components().collect::<Vec<_>>();
        hasher.update(&(components.len() as u64).to_le_bytes());
        for component in components {
            hash_part(&mut hasher, component.as_str().as_bytes());
        }
        hash_part(
            &mut hasher,
            &fs::read(source_root.join(path))
                .with_context(|| format!("read {domain} input {path}"))?,
        );
    }
    Ok(hasher.finalize().to_hex().to_string())
}

fn hash_part(hasher: &mut blake3::Hasher, bytes: &[u8]) {
    hasher.update(&(bytes.len() as u64).to_le_bytes());
    hasher.update(bytes);
}

fn hash_file(path: &Utf8Path) -> anyhow::Result<String> {
    let mut file = fs::File::open(path)?;
    let mut hasher = blake3::Hasher::new();
    let mut buffer = [0_u8; 64 * 1024];
    loop {
        let read = file.read(&mut buffer)?;
        if read == 0 {
            break;
        }
        hasher.update(&buffer[..read]);
    }
    Ok(hasher.finalize().to_hex().to_string())
}

fn validate_composite_hash_contract() -> anyhow::Result<()> {
    let root = camino_tempfile::Utf8TempDir::new()?;
    fs::create_dir(root.path().join("inputs"))?;
    fs::write(root.path().join("inputs/a.txt"), b"alpha")?;

    let mut files = BTreeSet::new();
    collect_input_files(root.path(), Utf8Path::new("inputs"), &mut files)?;
    let original = composite_hash(root.path(), "test", &files)?;
    anyhow::ensure!(
        original == composite_hash(root.path(), "test", &files)?,
        "composite input hashes are not deterministic"
    );

    fs::write(root.path().join("unrelated.txt"), b"ignored")?;
    anyhow::ensure!(
        original == composite_hash(root.path(), "test", &files)?,
        "an out-of-scope file changed the composite hash"
    );

    fs::write(root.path().join("inputs/a.txt"), b"changed")?;
    anyhow::ensure!(
        original != composite_hash(root.path(), "test", &files)?,
        "an input content change did not change the composite hash"
    );

    fs::write(root.path().join("inputs/b.txt"), b"beta")?;
    let mut added_files = BTreeSet::new();
    collect_input_files(root.path(), Utf8Path::new("inputs"), &mut added_files)?;
    anyhow::ensure!(
        files.len() + 1 == added_files.len()
            && composite_hash(root.path(), "test", &files)?
                != composite_hash(root.path(), "test", &added_files)?,
        "an added input file did not change the composite hash"
    );
    anyhow::ensure!(
        composite_hash(root.path(), "test", &added_files)?
            != composite_hash(root.path(), "different-domain", &added_files)?,
        "the composite hash does not separate input domains"
    );
    Ok(())
}

fn node_baseline() -> anyhow::Result<Value> {
    let build_info = camino_tempfile::NamedUtf8TempFile::new()?;
    let started = Instant::now();
    let output = Command::new("node")
        .current_dir(SUITE_DIR)
        .args([
            "node_modules/typescript/lib/tsc.js",
            "--noEmit",
            "--tsBuildInfoFile",
            build_info.path().as_str(),
            "-p",
            "projects/core/tsconfig.json",
        ])
        .output()?;
    Ok(json!({
        "wallMs": millis(started.elapsed()),
        "exitCode": output.status.code(),
        "stdout": String::from_utf8_lossy(&output.stdout),
        "stderr": String::from_utf8_lossy(&output.stderr),
    }))
}

fn node_phase_profile() -> anyhow::Result<Value> {
    let script = r#"
        import { profileTypeScript } from './tests/agentic_ts/profile-typescript.mjs';
        const value = await profileTypeScript({
            typescriptPath: './node_modules/typescript/lib/typescript.js',
            projectPath: './tests/agentic_ts/projects/core/tsconfig.json',
        });
        console.log(JSON.stringify(value));
    "#;
    let started = Instant::now();
    let output = Command::new("node")
        .args(["--input-type=module", "--eval", script])
        .output()?;
    anyhow::ensure!(
        output.status.success(),
        "Node phase profile failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let value: Value = serde_json::from_slice(&output.stdout)?;
    let wall_ms = millis(started.elapsed());
    Ok(json!({
        "wallMs": wall_ms,
        "outerOverheadMs": value["phasesMs"]["measuredTotal"]
            .as_f64()
            .map(|inner_ms| wall_ms - inner_ms),
        "result": { "value": value, "stdout": "", "stderr": "", "overflowed": false },
    }))
}

fn prepare_workspace(instance: &TestInstance) -> anyhow::Result<()> {
    let source = Utf8Path::new(SUITE_DIR);
    let workspace = instance.temp_dir_path().join("workspace");
    fs::create_dir_all(&workspace)?;
    for file in [
        "package.json",
        "package-lock.json",
        "tsconfig.json",
        "profile-typescript.mjs",
    ] {
        fs::copy(source.join(file), workspace.join(file))?;
    }
    for directory in ["node_modules", "projects"] {
        copy_dir_recursive(
            source.join(directory).as_std_path(),
            workspace.join(directory).as_std_path(),
        )?;
    }
    fs::create_dir_all(workspace.join(".home"))?;
    fs::create_dir_all(workspace.join(".cache"))?;
    Ok(())
}

fn prepare_cjs_graph(instance: &TestInstance) -> anyhow::Result<()> {
    let source = Utf8Path::new("tests/node_modules_apps/apps/popular-pure-js");
    let destination = instance.temp_dir_path().join("workspace/cjs-graph");
    copy_dir_recursive(source.as_std_path(), destination.as_std_path())?;
    let status = Command::new("npm")
        .args([
            "ci",
            "--install-links",
            "--ignore-scripts",
            "--no-audit",
            "--no-fund",
        ])
        .current_dir(&destination)
        .status()?;
    anyhow::ensure!(
        status.success(),
        "npm ci failed for the CommonJS graph smoke"
    );
    for (suffix, enabled) in [("disabled", false), ("enabled", true)] {
        let path = destination.join(format!("measure-{suffix}.cjs"));
        fs::write(
            &path,
            format!(
                "globalThis.__wasm_rquickjs_set_cjs_module_probe_session_enabled({enabled});\nmodule.exports = require('./test-05-ajv.cjs').run();\n"
            ),
        )
        .with_context(|| format!("write CommonJS graph measurement entry {path}"))?;
    }
    Ok(())
}

fn environment(iterations: usize, component_features: &str) -> anyhow::Result<Value> {
    let source_root = std::env::var("AGENTIC_TS_SOURCE_ROOT").unwrap_or_else(|_| ".".to_string());
    let host_lock_blake3 = std::env::var("WASM_RQUICKJS_TEST_HOST_LOCKFILE")
        .ok()
        .map(|path| hash_file(Utf8Path::new(&path)))
        .transpose()?;
    let dirty = !command_text(Command::new("git").args([
        "-C",
        &source_root,
        "status",
        "--porcelain",
        "--",
        ".",
        ":(exclude)tests/agentic_ts/results/*.json",
    ]))?
    .is_empty();
    Ok(json!({
        "commitHint": command_text(Command::new("git").args(["rev-parse", "HEAD"]))?,
        "dirty": dirty,
        "os": std::env::consts::OS,
        "arch": std::env::consts::ARCH,
        "rustc": command_text(Command::new("rustc").arg("--version"))?,
        "cargo": command_text(Command::new("cargo").arg("--version"))?,
        "node": command_text(Command::new("node").args(["-p", "process.versions.node"]))?,
        "npm": command_text(Command::new("npm").arg("--version"))?,
        "typescript": command_text(Command::new("node").args(["-p", "require('./tests/agentic_ts/node_modules/typescript/package.json').version"]))?,
        "componentFeatures": component_features,
        "componentCargoProfile": std::env::var("WASM_RQUICKJS_TEST_COMPONENT_PROFILE")
            .unwrap_or_else(|_| "dev".to_string()),
        "harnessCargoProfile": if cfg!(debug_assertions) { "dev" } else { "release" },
        "lockedBuilds": std::env::var("WASM_RQUICKJS_TEST_LOCKED_BUILDS").ok(),
        "hostDependencyGraph": {
            "kind": if cfg!(feature = "use-golem-wasmtime") { "fork-shadow" } else { "workspace" },
            "lockBlake3": host_lock_blake3,
        },
        "iterations": iterations,
        "artifactCache": std::env::var("WASM_RQUICKJS_TEST_ARTIFACT_CACHE").ok(),
        "wasmtimeCache": std::env::var("WASM_RQUICKJS_TEST_WASMTIME_CACHE").ok(),
        "preparedComponentCache": std::env::var("WASM_RQUICKJS_TEST_PREPARED_COMPONENT_CACHE").ok(),
        "unoptimized": std::env::var("WASM_RQUICKJS_TEST_UNOPTIMIZED").ok(),
    }))
}

fn verify_toolchain() -> anyhow::Result<()> {
    let node = command_text(Command::new("node").args(["-p", "process.versions.node"]))?;
    let npm = command_text(Command::new("npm").arg("--version"))?;
    anyhow::ensure!(node == "22.14.0", "requires Node.js 22.14.0; found {node}");
    anyhow::ensure!(npm == "10.9.2", "requires npm 10.9.2; found {npm}");
    anyhow::ensure!(
        Utf8Path::new(SUITE_DIR)
            .join("node_modules/typescript/lib/tsc.js")
            .exists(),
        "run npm ci in {SUITE_DIR} first"
    );
    Ok(())
}

fn validate_report(report: &Value) -> anyhow::Result<()> {
    anyhow::ensure!(
        report["nodeBaseline"]["exitCode"] == 0,
        "Node baseline failed"
    );
    if report["schemaVersion"] == 5 {
        validate_phase_profile(&report["phaseProfiles"]["node"], "Node", false)?;
        validate_phase_profile(&report["phaseProfiles"]["wasm"], "Wasm", true)?;
        for sibling in ["compiler", "cpu", "io"] {
            validate_execution_profile_timing(
                &report["workloads"]["concurrent"]["contended"]["result"][sibling]["result"]["profile"],
                &format!("concurrent {sibling}"),
            )?;
        }
    }
    for path in [
        "/workloads/coldNoEmit/result/value/exitCode",
        "/workloads/incrementalCold/result/value/exitCode",
        "/workloads/invalidThenValid/recovery/result/value/exitCode",
        "/workloads/projectReferences/result/value/exitCode",
        "/workloads/emitDirect/result/value/exitCode",
    ] {
        anyhow::ensure!(
            report.pointer(path) == Some(&json!(0))
                && successful_result(
                    report
                        .pointer(path.trim_end_matches("/value/exitCode"))
                        .unwrap_or(&Value::Null),
                ),
            "failed workload at {path}: {report:#}"
        );
    }
    for group in ["unchangedFreshJobs", "incrementalFreshJobs"] {
        let samples = report["workloads"][group]["samples"]
            .as_array()
            .ok_or_else(|| anyhow::anyhow!("missing samples for {group}"))?;
        anyhow::ensure!(samples.len() >= 5, "{group} needs at least five samples");
        for sample in samples {
            anyhow::ensure!(
                sample.pointer("/result/value/exitCode") == Some(&json!(0))
                    && successful_result(&sample["result"]),
                "failed sample in {group}: {sample:#}"
            );
        }
    }
    let failed_checks = report["workloads"]["invalidThenValid"]["failedChecks"]["samples"]
        .as_array()
        .ok_or_else(|| anyhow::anyhow!("missing repeated failed type checks"))?;
    anyhow::ensure!(
        failed_checks.len() >= 5
            && failed_checks.iter().all(|sample| {
                sample.pointer("/result/value/exitCode") == Some(&json!(2))
                    && sample["result"]["stdout"]
                        .as_str()
                        .is_some_and(|stdout| stdout.contains("error TS2322"))
                    && sample["result"]["overflowed"] == false
                    && sample["result"].get("runnerError").is_none()
            }),
        "a repeated invalid TypeScript check unexpectedly passed or failed incorrectly"
    );
    anyhow::ensure!(
        successful_result(&report["workloads"]["directTypeScript"]["result"])
            && successful_result(&report["workloads"]["generatedJavaScript"]["result"])
            && report.pointer("/workloads/directTypeScript/result/value/answer")
                == Some(&json!(42))
            && report.pointer("/workloads/generatedJavaScript/result/value/default/answer")
                == Some(&json!(42)),
        "direct TypeScript or generated JavaScript result was incorrect"
    );
    let cpu_baseline_value = report
        .pointer("/workloads/concurrent/cpuBaseline/result/value")
        .and_then(Value::as_u64);
    let io_baseline_value = report.pointer("/workloads/concurrent/ioBaseline/result/value");
    anyhow::ensure!(
        successful_result(&report["workloads"]["concurrent"]["cpuBaseline"]["result"])
            && successful_result(&report["workloads"]["concurrent"]["ioBaseline"]["result"])
            && successful_result(
                &report["workloads"]["concurrent"]["contended"]["result"]["compiler"]["result"]
            )
            && successful_result(
                &report["workloads"]["concurrent"]["contended"]["result"]["cpu"]["result"]
            )
            && successful_result(
                &report["workloads"]["concurrent"]["contended"]["result"]["io"]["result"]
            )
            && cpu_baseline_value.is_some()
            && io_baseline_value
                .and_then(|value| value["bytes"].as_u64())
                .is_some_and(|bytes| bytes > 0)
            && report
                .pointer("/workloads/concurrent/contended/result/compiler/result/value/exitCode")
                == Some(&json!(0))
            && report
                .pointer("/workloads/concurrent/contended/result/cpu/result/value")
                .and_then(Value::as_u64)
                == cpu_baseline_value
            && report.pointer("/workloads/concurrent/contended/result/io/result/value")
                == io_baseline_value,
        "concurrency workload result was incorrect"
    );
    validate_termination_series(
        &report["workloads"]["timeouts"],
        "timedOut",
        "execution job timed out",
    )?;
    validate_termination_series(
        &report["workloads"]["cancellations"],
        "cancelled",
        "execution job cancelled",
    )?;

    let memory = &report["workloads"]["memoryPlateau"];
    anyhow::ensure!(
        memory["wasmLinearMemory"]["otherWorkloadCheckpoints"]
            .as_array()
            .is_some_and(
                |samples| samples.len() == if report["schemaVersion"] == 5 { 13 } else { 12 }
            ),
        "Wasm linear-memory observations do not cover every non-series workload"
    );
    anyhow::ensure!(
        memory["quickJsHeap"]["allowedVariationBytes"] == ALLOWED_QUICKJS_HEAP_VARIATION_BYTES,
        "report changed the QuickJS heap-variation limit"
    );
    for group in [
        "unchangedCompilerJobs",
        "warmedIncrementalCompilerJobs",
        "failedCompilerJobs",
    ] {
        for point in ["beforeToolLoad", "afterCompiler"] {
            anyhow::ensure!(
                memory["quickJsHeap"][group][point]["samples"]
                    .as_array()
                    .is_some_and(|samples| samples.len() >= 5)
                    && memory["quickJsHeap"][group][point]["variationBytes"]
                        .as_u64()
                        .unwrap_or(u64::MAX)
                        <= ALLOWED_QUICKJS_HEAP_VARIATION_BYTES,
                "fresh-job QuickJS heap samples varied unexpectedly for {group}/{point}"
            );
        }
    }
    Ok(())
}

fn validate_phase_profile(
    profile: &Value,
    label: &str,
    require_execution_profile: bool,
) -> anyhow::Result<()> {
    let value = &profile["result"]["value"];
    anyhow::ensure!(
        successful_result(&profile["result"])
            && value["exitCode"] == 0
            && value["graph"]["rootFiles"]
                .as_u64()
                .is_some_and(|count| count > 0)
            && value["graph"]["totalSourceFiles"]
                .as_u64()
                .is_some_and(|count| count > 0),
        "{label} TypeScript phase profile failed"
    );
    for phase in [
        "import",
        "configRead",
        "configParse",
        "programCreate",
        "diagnostics",
        "measuredTotal",
        "unclassified",
    ] {
        anyhow::ensure!(
            value["phasesMs"][phase]
                .as_f64()
                .is_some_and(|duration| duration >= 0.0),
            "{label} TypeScript phase profile has no valid {phase} duration"
        );
    }
    for phase in ["configRead", "configParse", "programCreate", "diagnostics"] {
        for operation in [
            "fileExists",
            "directoryExists",
            "readFile",
            "readDirectory",
            "realpath",
            "getSourceFile",
        ] {
            anyhow::ensure!(
                value["io"][phase][operation]["calls"].as_u64().is_some(),
                "{label} TypeScript phase profile has no {phase}/{operation} count"
            );
        }
    }
    if require_execution_profile {
        let execution = &profile["result"]["profile"];
        validate_execution_profile_timing(execution, label)?;
        anyhow::ensure!(
            execution["version"] == 1
                && execution["totalMs"]
                    .as_f64()
                    .is_some_and(|duration| duration >= 0.0),
            "{label} execution profile has no supported version or total"
        );
        let counters = &execution["counters"];
        let counter = |name: &str| counters[name].as_u64().unwrap_or_default();
        anyhow::ensure!(
            counter("modules.resolve.calls")
                == counter("modules.resolve.success")
                    + counter("modules.resolve.missing")
                    + counter("modules.resolve.errors")
                && counter("modules.resolve.calls") > 0,
            "{label} module-resolution counters are incomplete"
        );
        anyhow::ensure!(
            counter("modules.sourceRead.calls")
                == counter("modules.sourceRead.success")
                    + counter("modules.sourceRead.notFound")
                    + counter("modules.sourceRead.errors")
                && counter("modules.sourceRead.bytes") > 0,
            "{label} module-source counters are incomplete"
        );
        anyhow::ensure!(
            counter("modules.fileProbe.calls")
                == counter("modules.fileProbe.found") + counter("modules.fileProbe.missing")
                && counter("modules.fileProbe.cacheHits") <= counter("modules.fileProbe.calls"),
            "{label} module file-probe counters are inconsistent"
        );
        let read_calls = counter("filesystem.readFile.calls")
            + counter("filesystem.readFileWithEncoding.calls")
            + counter("filesystem.readFileNative.calls")
            + counter("filesystem.read.calls");
        let read_bytes = counter("filesystem.readFile.bytes")
            + counter("filesystem.readFileWithEncoding.bytes")
            + counter("filesystem.readFileNative.bytes")
            + counter("filesystem.read.bytes");
        anyhow::ensure!(
            read_calls > 0 && read_bytes > 0,
            "{label} native filesystem counters did not observe compiler reads"
        );
    }
    Ok(())
}

fn validate_execution_profile_timing(execution: &Value, label: &str) -> anyhow::Result<()> {
    anyhow::ensure!(
        execution["version"] == 1
            && execution["totalMs"]
                .as_f64()
                .is_some_and(|duration| duration.is_finite() && duration >= 0.0),
        "{label} execution profile has no supported version or total"
    );
    let mut classified_ms = 0.0;
    for phase in [
        "queueDelay",
        "runtimeCreation",
        "loaderInitialization",
        "processConfiguration",
        "builtinInitialization",
        "transportWiring",
        "wrapperPreparation",
        "initialEvaluation",
        "userAwait",
        "resultFormatting",
        "teardown",
    ] {
        let duration = execution["phasesMs"][phase]
            .as_f64()
            .filter(|duration| duration.is_finite() && *duration >= 0.0)
            .ok_or_else(|| anyhow::anyhow!("{label} execution profile has no {phase}"))?;
        classified_ms += duration;
    }
    anyhow::ensure!(
        classified_ms <= execution["totalMs"].as_f64().unwrap() + 1.0,
        "{label} execution profile phases exceed its lifecycle total"
    );
    Ok(())
}

fn successful_result(value: &Value) -> bool {
    value["overflowed"] == false
        && value.get("runnerError").is_none()
        && value.get("value").is_some()
}

fn profile_counter(counters: &Value, name: &str) -> u64 {
    counters.get(name).and_then(Value::as_u64).unwrap_or(0)
}

fn validate_module_resolution_counters(
    sample: &Value,
    require_session_hits: bool,
) -> anyhow::Result<()> {
    let counters = &sample["result"]["profile"]["counters"];
    anyhow::ensure!(
        counters.get("modules.pathProbe.systemCalls").is_some(),
        "module-resolution physical counters are missing: {counters:#}"
    );
    let mut logical_calls = 0;
    let mut local_hits = 0;
    let mut session_hits = 0;

    for prefix in [
        "modules.fileProbe",
        "modules.directoryProbe",
        "modules.classificationProbe",
    ] {
        let calls = profile_counter(counters, &format!("{prefix}.calls"));
        let found = profile_counter(counters, &format!("{prefix}.found"));
        let missing = profile_counter(counters, &format!("{prefix}.missing"));
        anyhow::ensure!(
            calls == found + missing,
            "{prefix} logical calls do not match outcomes: {counters:#}"
        );

        let cache_hits = profile_counter(counters, &format!("{prefix}.cacheHits"));
        let cache_hits_found = profile_counter(counters, &format!("{prefix}.cacheHitsFound"));
        let cache_hits_missing = profile_counter(counters, &format!("{prefix}.cacheHitsMissing"));
        let prefix_session_hits = profile_counter(counters, &format!("{prefix}.sessionCacheHits"));
        let session_hits_found =
            profile_counter(counters, &format!("{prefix}.sessionCacheHitsFound"));
        let session_hits_missing =
            profile_counter(counters, &format!("{prefix}.sessionCacheHitsMissing"));
        anyhow::ensure!(
            cache_hits == cache_hits_found + cache_hits_missing + prefix_session_hits,
            "{prefix} cache-hit categories do not reconcile: {counters:#}"
        );
        anyhow::ensure!(
            prefix_session_hits == session_hits_found + session_hits_missing,
            "{prefix} session-hit outcomes do not reconcile: {counters:#}"
        );

        logical_calls += calls;
        local_hits += cache_hits_found + cache_hits_missing;
        session_hits += prefix_session_hits;
    }

    let path_system_calls = profile_counter(counters, "modules.pathProbe.systemCalls");
    let path_session_hits = profile_counter(counters, "modules.pathProbe.sessionHits");
    anyhow::ensure!(
        logical_calls > 0,
        "no module-resolution probes were recorded"
    );
    anyhow::ensure!(
        session_hits == path_session_hits,
        "shared and per-kind session hits do not reconcile: {counters:#}"
    );
    anyhow::ensure!(
        logical_calls == path_system_calls + path_session_hits + local_hits,
        "logical and physical path probes do not reconcile: {counters:#}"
    );
    if require_session_hits {
        anyhow::ensure!(
            path_session_hits > 0 && logical_calls > path_system_calls,
            "CommonJS graph did not exercise session-cache savings: {counters:#}"
        );
    }
    Ok(())
}

fn validate_termination_series(
    series: &Value,
    outcome: &str,
    expected_message: &str,
) -> anyhow::Result<()> {
    let samples = series["attempts"]["samples"]
        .as_array()
        .ok_or_else(|| anyhow::anyhow!("missing repeated {outcome} samples"))?;
    anyhow::ensure!(
        samples.len() >= 5
            && samples.iter().all(|sample| {
                sample["result"][outcome] == true
                    && sample["result"]["message"] == expected_message
                    && sample["wallMs"]
                        .as_f64()
                        .is_some_and(|wall_ms| wall_ms < 1_000.0)
            }),
        "repeated {outcome} probe failed"
    );
    anyhow::ensure!(
        successful_result(&series["recovery"]["result"])
            && series["recovery"].pointer("/result/value/answer") == Some(&json!(42)),
        "execution capacity was not recovered after repeated {outcome} jobs"
    );
    Ok(())
}

fn validate_regression_guards(report: &Value) -> anyhow::Result<()> {
    let mut failed_sample = report.clone();
    failed_sample["workloads"]["unchangedFreshJobs"]["samples"][0]["result"]["value"]["exitCode"] =
        json!(1);
    anyhow::ensure!(
        validate_report(&failed_sample).is_err(),
        "validation guard accepted a failed repeated workload"
    );

    let mut false_timeout = report.clone();
    false_timeout["workloads"]["timeouts"]["attempts"]["samples"][0]["result"]["message"] =
        json!("unrelated error");
    anyhow::ensure!(
        validate_report(&false_timeout).is_err(),
        "validation guard accepted an unrelated timeout error"
    );
    let mut invalid_runner_error = report.clone();
    invalid_runner_error["workloads"]["invalidThenValid"]["failedChecks"]["samples"][0]["result"] =
        json!({ "runnerError": { "message": "broken" } });
    anyhow::ensure!(
        validate_report(&invalid_runner_error).is_err(),
        "validation guard accepted a failed invalid-TypeScript workload"
    );
    let mut overflowed = report.clone();
    overflowed["workloads"]["directTypeScript"]["result"]["overflowed"] = json!(true);
    anyhow::ensure!(
        validate_report(&overflowed).is_err(),
        "validation guard accepted an overflowed successful workload"
    );
    let mut leaked_heap = report.clone();
    leaked_heap["workloads"]["memoryPlateau"]["quickJsHeap"]["unchangedCompilerJobs"]["beforeToolLoad"]
        ["variationBytes"] = json!(u64::MAX);
    anyhow::ensure!(
        validate_report(&leaked_heap).is_err(),
        "validation guard accepted unbounded fresh-job heap variation"
    );
    let mut missing_linear_memory_checkpoint = report.clone();
    missing_linear_memory_checkpoint["workloads"]["memoryPlateau"]["wasmLinearMemory"]["otherWorkloadCheckpoints"] =
        json!([]);
    anyhow::ensure!(
        validate_report(&missing_linear_memory_checkpoint).is_err(),
        "validation guard accepted incomplete linear-memory observations"
    );
    let mut relaxed_quickjs_heap = report.clone();
    relaxed_quickjs_heap["workloads"]["memoryPlateau"]["quickJsHeap"]["allowedVariationBytes"] =
        json!(u64::MAX);
    anyhow::ensure!(
        validate_report(&relaxed_quickjs_heap).is_err(),
        "validation guard accepted a report-controlled QuickJS heap limit"
    );
    if report["schemaVersion"] == 5 {
        let mut missing_phase = report.clone();
        missing_phase["phaseProfiles"]["wasm"]["result"]["value"]["phasesMs"]["programCreate"] =
            Value::Null;
        anyhow::ensure!(
            validate_report(&missing_phase).is_err(),
            "validation guard accepted an incomplete TypeScript phase profile"
        );
        let mut inconsistent_counters = report.clone();
        inconsistent_counters["phaseProfiles"]["wasm"]["result"]["profile"]["counters"]["modules.resolve.calls"] =
            json!(u64::MAX);
        anyhow::ensure!(
            validate_report(&inconsistent_counters).is_err(),
            "validation guard accepted inconsistent execution counters"
        );
    }
    Ok(())
}

fn string_list(values: &[&str]) -> Val {
    Val::List(
        values
            .iter()
            .map(|value| Val::String((*value).to_string()))
            .collect(),
    )
}

fn command_text(command: &mut Command) -> anyhow::Result<String> {
    let output = command.output()?;
    anyhow::ensure!(
        output.status.success(),
        "command failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    Ok(String::from_utf8(output.stdout)?.trim().to_string())
}

fn millis(duration: Duration) -> f64 {
    duration.as_secs_f64() * 1000.0
}