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
//! Node.js compatibility inventory report generator.
//!
//! This report is generated from tests/node_compat/config.jsonc plus the pinned vendored Node.js
//! sources used to detect tests that rely on Node internals. It does not compile or run the node
//! compatibility runner itself. Entries classified as `runnable` are treated as passing because
//! the node compatibility PR test runs them and fails CI if any of them fail.
//!
//! Run the read-only report contracts with:
//!   cargo test --test node_compat_report -- ':tag:report_contract'
//!
//! Regenerate the report with:
//!   ./tests/node_compat/generate-report.sh
//!
//! The report is written to tests/node_compat/report.md

test_r::enable!();

#[allow(dead_code)]
mod common;

use camino_tempfile::Utf8TempDir;
use common::js_subtest_parser::{BlockKind, SubtestDiscovery, discover_subtests_with_options};
use common::{
    NodeCompatCategory, NodeCompatTestEntry, classify_test, load_node_compat_config,
    load_node_compat_config_with_suite_root, strip_jsonc_comments,
};
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::Path;
use test_r::test;

const CONFIG_PATH: &str = "tests/node_compat/config.jsonc";
const REPORT_PATH: &str = "tests/node_compat/report.md";
const SUITE_ROOT: &str = "tests/node_compat/suite";

#[derive(Debug, Clone)]
struct InventoryItem {
    key: String,
    file_path: String,
    category: NodeCompatCategory,
    reason: Option<String>,
}

#[derive(Debug, Clone, Copy, Default)]
struct CategoryCounts {
    runnable: usize,
    known_gap: usize,
    wasi_impossible: usize,
    engine_difference: usize,
    node_internals: usize,
    unevaluated: usize,
}

impl CategoryCounts {
    fn add(&mut self, category: NodeCompatCategory) {
        match category {
            NodeCompatCategory::Runnable => self.runnable += 1,
            NodeCompatCategory::KnownGap => self.known_gap += 1,
            NodeCompatCategory::WasmImpossible => self.wasi_impossible += 1,
            NodeCompatCategory::EngineDifference => self.engine_difference += 1,
            NodeCompatCategory::NodeInternals => self.node_internals += 1,
            NodeCompatCategory::Unevaluated => self.unevaluated += 1,
        }
    }

    fn total(self) -> usize {
        self.runnable
            + self.known_gap
            + self.wasi_impossible
            + self.engine_difference
            + self.node_internals
            + self.unevaluated
    }

    fn primary_total(self) -> usize {
        self.runnable + self.known_gap
    }

    fn public_total(self) -> usize {
        self.runnable
            + self.known_gap
            + self.wasi_impossible
            + self.engine_difference
            + self.unevaluated
    }
}

#[test]
#[ignore = "explicit report-generation command; default harness execution is read-only"]
fn generate_node_compat_config_report() -> anyhow::Result<()> {
    let (report, counts) = render_node_compat_config_report()?;
    fs::write(REPORT_PATH, &report)?;

    println!("Report written to {REPORT_PATH}");
    println!("Expanded inventory entries: {}", counts.total());
    println!(
        "Primary compatibility (CI-enforced): {}/{} ({:.1}%)",
        counts.runnable,
        counts.primary_total(),
        pct(counts.runnable, counts.primary_total())
    );
    println!(
        "Excluded from primary: WASI-impossible={}, engine-difference={}, unevaluated={}, node-internals={}",
        counts.wasi_impossible, counts.engine_difference, counts.unevaluated, counts.node_internals
    );

    Ok(())
}

#[test]
#[test_r::tag(report_contract)]
fn node_compat_config_report_is_current() -> anyhow::Result<()> {
    let (expected, _) = render_node_compat_config_report()?;
    let actual = fs::read_to_string(REPORT_PATH)?;
    assert_eq!(
        actual, expected,
        "{REPORT_PATH} is stale; run `./tests/node_compat/generate-report.sh`"
    );
    Ok(())
}

fn render_node_compat_config_report() -> anyhow::Result<(String, CategoryCounts)> {
    let entries = load_node_compat_config(CONFIG_PATH)?;
    let node_version = load_node_version(CONFIG_PATH)?;
    let items = expand_entries(&entries);

    let mut counts = CategoryCounts::default();
    let mut by_module: BTreeMap<String, CategoryCounts> = BTreeMap::new();
    let mut by_category: BTreeMap<NodeCompatCategory, Vec<&InventoryItem>> = BTreeMap::new();
    let mut missing_reasons: Vec<&InventoryItem> = Vec::new();

    for item in &items {
        counts.add(item.category);
        by_category.entry(item.category).or_default().push(item);
        by_module
            .entry(module_for_item(item).to_string())
            .or_default()
            .add(item.category);

        if item.category != NodeCompatCategory::Runnable
            && item.reason.as_deref().is_none_or(str::is_empty)
        {
            missing_reasons.push(item);
        }
    }

    let mut report = String::new();
    report.push_str(&format!(
        "# Node.js v{node_version} Compatibility Inventory\n\n"
    ));
    report.push_str(&format!(
        "Source: `{CONFIG_PATH}` | Engine: wasm-rquickjs (QuickJS)\n\n"
    ));
    report.push_str(
        "This report is generated from `config.jsonc` and the pinned vendored Node.js sources \
         used to detect tests that rely on Node internals. It does **not** run the vendored tests \
         itself. Entries classified as `runnable` are reported as passing because the \
         `node_compat` PR test executes runnable entries and fails CI if any of them fail.\n\n",
    );

    push_summary(&mut report, counts);
    push_module_table(&mut report, &by_module);
    push_split_summary(&mut report, &entries);
    push_reason_sections(&mut report, &by_category);
    push_missing_reasons(&mut report, &missing_reasons);

    Ok((report, counts))
}

#[test]
#[test_r::tag(report_contract)]
fn node_compat_config_requires_vendored_suite() -> anyhow::Result<()> {
    let fixture = NodeCompatConfigFixture::new()?;
    let error = fixture.load().unwrap_err();
    assert!(
        error
            .to_string()
            .contains("vendored Node.js test suite is unavailable"),
        "{error:#}"
    );
    Ok(())
}

#[test]
#[test_r::tag(report_contract)]
fn node_compat_config_requires_matching_vendored_version() -> anyhow::Result<()> {
    let fixture = NodeCompatConfigFixture::new()?;
    fixture.write_suite_version("22.13.0")?;
    let error = fixture.load().unwrap_err();
    assert!(error.to_string().contains("version mismatch"), "{error:#}");
    assert!(error.to_string().contains("22.14.0"), "{error:#}");
    Ok(())
}

#[test]
#[test_r::tag(report_contract)]
fn node_compat_config_requires_source_for_implicit_classification() -> anyhow::Result<()> {
    let fixture = NodeCompatConfigFixture::with_implicit_entry()?;
    fixture.write_suite_version("22.14.0")?;
    let error = fixture.load().unwrap_err();
    assert!(
        error
            .to_string()
            .contains("cannot classify node-compat entry"),
        "{error:#}"
    );
    Ok(())
}

#[test]
#[test_r::tag(report_contract)]
fn node_compat_config_classifies_from_vendored_source() -> anyhow::Result<()> {
    let fixture = NodeCompatConfigFixture::with_implicit_entry()?;
    fixture.write_suite_version("22.14.0")?;
    fixture.write_source("// Flags: --expose-internals\n'use strict';\n")?;
    let entries = fixture.load()?;
    assert_eq!(entries.len(), 1);
    assert_eq!(entries[0].category, NodeCompatCategory::NodeInternals);
    Ok(())
}

struct NodeCompatConfigFixture {
    _temp: Utf8TempDir,
    config_path: camino::Utf8PathBuf,
    suite_root: camino::Utf8PathBuf,
}

impl NodeCompatConfigFixture {
    fn new() -> anyhow::Result<Self> {
        Self::create(false)
    }

    fn with_implicit_entry() -> anyhow::Result<Self> {
        Self::create(true)
    }

    fn create(with_implicit_entry: bool) -> anyhow::Result<Self> {
        let temp = Utf8TempDir::new()?;
        let config_path = temp.path().join("config.jsonc");
        let suite_root = temp.path().join("suite");
        let tests = if with_implicit_entry {
            r#"{"parallel/test-internal.js": {}}"#
        } else {
            "{}"
        };
        fs::write(
            &config_path,
            format!(r#"{{"nodeVersion": "22.14.0", "tests": {tests}}}"#),
        )?;
        Ok(Self {
            _temp: temp,
            config_path,
            suite_root,
        })
    }

    fn write_suite_version(&self, version: &str) -> anyhow::Result<()> {
        fs::create_dir_all(&self.suite_root)?;
        fs::write(self.suite_root.join("NODE_VERSION"), format!("{version}\n"))?;
        Ok(())
    }

    fn write_source(&self, source: &str) -> anyhow::Result<()> {
        let source_path = self.suite_root.join("parallel/test-internal.js");
        fs::create_dir_all(source_path.parent().unwrap())?;
        fs::write(source_path, source)?;
        Ok(())
    }

    fn load(&self) -> anyhow::Result<Vec<NodeCompatTestEntry>> {
        load_node_compat_config_with_suite_root(
            self.config_path.as_str(),
            self.suite_root.as_std_path(),
        )
    }
}

#[test]
#[test_r::tag(report_contract)]
fn module_related_node_compat_entries_are_configured() -> anyhow::Result<()> {
    let entries = load_node_compat_config(CONFIG_PATH)?;
    let configured: BTreeSet<_> = entries.into_iter().map(|entry| entry.path).collect();
    let expected = collect_module_related_entrypoints()?;

    let missing: Vec<_> = expected
        .into_iter()
        .filter(|entry| !configured.contains(entry))
        .collect();

    assert!(
        missing.is_empty(),
        "module-related node_compat tests are vendored but missing from {CONFIG_PATH}:\n{}",
        missing.join("\n")
    );

    Ok(())
}

#[test]
#[test_r::tag(report_contract)]
fn module_related_known_gaps_are_deferred_or_covered() -> anyhow::Result<()> {
    let entries = load_node_compat_config(CONFIG_PATH)?;
    let module_entrypoints = collect_module_related_entrypoints()?;
    let items = expand_entries(&entries);

    let unexpected: Vec<_> = items
        .iter()
        .filter(|item| {
            (module_entrypoints.contains(&item.file_path) || is_module_adjacent_known_gap(item))
                && item.category == NodeCompatCategory::KnownGap
                && !is_accepted_module_known_gap_reason(item.reason.as_deref())
        })
        .map(|item| {
            format!(
                "{}: {}",
                item.key,
                item.reason.as_deref().unwrap_or("<missing reason>")
            )
        })
        .collect();

    assert!(
        unexpected.is_empty(),
        "module-related known-gap entries need an accepted deferral reason:\n{}",
        unexpected.join("\n")
    );

    Ok(())
}

#[test]
#[test_r::tag(report_contract)]
fn module_known_gap_deferrals_require_an_exact_reason() {
    for accepted in [
        "WebAssembly module loading for .wasm files is not implemented; binary input is currently treated as JS source",
        "module.register does not transfer MessagePort ownership from transferList into an isolated loader context",
    ] {
        assert!(is_accepted_module_known_gap_reason(Some(accepted)));
        assert!(!is_accepted_module_known_gap_reason(Some(&format!(
            "unrelated module failure; {accepted}"
        ))));
    }
}

#[test]
#[test_r::tag(report_contract)]
fn vm_split_fixtures_include_top_level_executable_statements() -> anyhow::Result<()> {
    for (path, expected_count) in [
        ("parallel/test-vm-basic.js", 10),
        ("parallel/test-vm-module-basic.js", 13),
    ] {
        let source = fs::read_to_string(Path::new(SUITE_ROOT).join(path))?;
        let blocks = match discover_subtests_with_options(path, &source, false, true) {
            SubtestDiscovery::Block(blocks) => blocks,
            other => panic!("Expected block discovery for {path}, got {other:?}"),
        };
        assert_eq!(blocks.len(), expected_count, "{path}");
        assert!(
            blocks
                .iter()
                .any(|block| block.kind == BlockKind::Statement),
            "{path} must expose executable statements as subtests"
        );
    }

    Ok(())
}

fn is_accepted_module_known_gap_reason(reason: Option<&str>) -> bool {
    const ACCEPTED_REASONS: &[&str] = &[
        "--input-type=module eval emulation is incomplete for cwd-relative static/dynamic imports",
        "WASM child emulation does not support --experimental-test-module-mocks CLI flag",
        "WASM child emulation does not support --experimental-test-module-mocks/--experimental-default-type flags",
        "WASM child emulation does not support --permission/--allow-worker/--experimental-test-module-mocks flags",
        "WASM child emulation does not support --permission/--experimental-test-module-mocks flags",
        "WebAssembly global is missing in current runtime",
        "WebAssembly module loading for .wasm files is not implemented; binary input is currently treated as JS source",
        "rooted symlink targets cannot be resolved inside a WASI preopen; the adapter rejects them at creation, while persistent relative symlinks are covered by runtime tests",
        "child_process execPath emulation does not fully match spawnSync({ encoding }) behavior for --check stdin runs",
        "child_process execPath emulation does not implement --experimental-print-required-tla diagnostics output",
        "child_process execPath emulation does not implement --trace-require-module warning output",
        "child_process execPath emulation does not yet support this ESM/CJS fixture runner path; direct CJS named export interop is covered by test-require-module.js",
        "child_process execPath emulation does not yet support this ESM/CJS fixture runner path; same-process CJS import/require interop is covered by module-interop runtime tests",
        "child_process execPath emulation does not yet support this ESM/CJS fixture runner path; same-process builtin and CJS interop are covered by runtime and node_compat tests",
        "child_process execPath emulation lacks full --import/--require preload semantics",
        "common-shim spawnPromisified child emulation does not support --no-experimental-require-module",
        "emulated child_process inline eval does not keep the child alive for dynamic import() resolution",
        "loader hooks in this vendored file are exercised through spawned process.execPath CLI loader flags/eval, deferred to simulated Node CLI mode support",
        "QuickJS property redefinition errors use engine-specific wording; Node-compatible normalization without replacing public intrinsics is tracked by GOL-361",
        "programmatic loader registration in this vendored file is exercised through spawned process.execPath --eval/--import/--loader CLI mode",
        "module.register does not transfer MessagePort ownership from transferList into an isolated loader context",
        "remaining failures run through spawnSync(process.execPath, ...) and assert exact child-process status/stderr cycle diagnostics; direct node modules app same-process module graph coverage lives in tests/node_modules_apps",
        "remaining failures run through spawnSync(process.execPath, ...) and assert exact child-process status/stdout/stderr diagnostics; one TLA/dynamic-import sequencing case can still hit a QuickJS linker assert through process.execPath emulation, but direct same-process node modules app coverage passes",
        "requires isolated process.execPath --eval execution, TypeScript input-type flags, and child warning/output/exit capture",
        "requires isolated process.execPath --experimental-transform-types execution and CLI source-map configuration",
        "requires isolated process.execPath TypeScript entry execution and Node CLI default-module / require-module flag handling",
        "requires isolated process.execPath TypeScript entry execution and Node CLI flags; the direct process.features check requires a separate feature-disabled component",
        "requires child_process execFileSync with copied process.execPath and Node global module path layout",
        "requires simulated Node CLI flag handling for --no-experimental-require-module/--experimental-detect-module",
        "requires simulated process.execPath / Node CLI mode support deferred to follow-up PR",
        "requires simulated process.execPath / Node CLI mode support for child-process JSON module warning assertions",
        "requires simulated process.execPath / Node CLI module_timer and trace-event support",
        "requires spawned process.execPath --check execution with --experimental-default-type=module",
        "requires spawned process.execPath entry-point execution for extensionless ESM files",
        "requires spawned process.execPath entry-point execution plus WebAssembly module loading support",
        "requires spawned process.execPath entry-point execution to verify extensionless .wasm classification outside module scope",
        "requires spawned process.execPath entry-point execution with --experimental-default-type=module",
        "same-process ESM invalid package config diagnostics are covered by module-resolution runtime tests; vendored fixture asserts stderr/status through spawned process.execPath ESM entry-point emulation",
        "same-process dynamic import cache behavior is covered by runner_dynamic_import_cache_survives_removed_file; full Node test also requires spawned process.execPath --input-type=module support",
        "same-process import.meta.resolve behavior is covered by runtime tests; remaining vendored failure requires child_process execPath emulation for --input-type/--import ESM CLI modes",
    ];

    reason.is_some_and(|reason| ACCEPTED_REASONS.contains(&reason))
}

fn collect_module_related_entrypoints() -> anyhow::Result<BTreeSet<String>> {
    let mut entries = BTreeSet::new();
    collect_matching_files("es-module", is_es_module_entrypoint, &mut entries)?;
    collect_matching_files("parallel", is_parallel_module_entrypoint, &mut entries)?;
    collect_matching_files("sequential", is_sequential_module_entrypoint, &mut entries)?;
    Ok(entries)
}

fn collect_matching_files(
    suite_dir: &str,
    predicate: fn(&str) -> bool,
    entries: &mut BTreeSet<String>,
) -> anyhow::Result<()> {
    let dir = Path::new(SUITE_ROOT).join(suite_dir);
    for entry in fs::read_dir(&dir)? {
        let entry = entry?;
        if !entry.file_type()?.is_file() {
            continue;
        }

        let file_name = entry.file_name();
        let file_name = file_name.to_string_lossy();
        if predicate(&file_name) {
            entries.insert(format!("{suite_dir}/{file_name}"));
        }
    }
    Ok(())
}

fn is_js_entrypoint(name: &str) -> bool {
    name.starts_with("test-") && (name.ends_with(".js") || name.ends_with(".mjs"))
}

fn is_es_module_entrypoint(name: &str) -> bool {
    is_js_entrypoint(name)
}

fn is_parallel_module_entrypoint(name: &str) -> bool {
    is_js_entrypoint(name)
        && [
            "test-module-",
            "test-module.",
            "test-require-",
            "test-require.",
            "test-cjs-",
            "test-cjs.",
            "test-esm-",
            "test-esm.",
            "test-commonjs-",
            "test-commonjs.",
        ]
        .iter()
        .any(|prefix| name.starts_with(prefix))
}

fn is_sequential_module_entrypoint(name: &str) -> bool {
    is_js_entrypoint(name) && name.starts_with("test-module")
}

fn is_module_adjacent_known_gap(item: &InventoryItem) -> bool {
    match item.file_path.as_str() {
        "parallel/test-cli-eval.js" => item
            .reason
            .as_deref()
            .is_some_and(|reason| reason.contains("--input-type=module")),
        "parallel/test-cli-syntax-piped-good.js" => true,
        "parallel/test-no-addons-resolution-condition.js" => true,
        "parallel/test-runner-import-no-scheme.js" => true,
        "parallel/test-runner-module-mocking.js" => true,
        _ => false,
    }
}

fn expand_entries(entries: &[NodeCompatTestEntry]) -> Vec<InventoryItem> {
    let mut items = Vec::new();
    for entry in entries {
        if entry.split && !entry.subtests.is_empty() {
            for subtest in &entry.subtests {
                items.push(InventoryItem {
                    key: format!("{}#{}", entry.path, subtest.name),
                    file_path: entry.path.clone(),
                    category: subtest.category,
                    reason: subtest.reason.clone(),
                });
            }
        } else {
            items.push(InventoryItem {
                key: entry.path.clone(),
                file_path: entry.path.clone(),
                category: entry.category,
                reason: entry.reason.clone(),
            });
        }
    }
    items.sort_by(|a, b| a.key.cmp(&b.key));
    items
}

fn load_node_version(config_path: &str) -> anyhow::Result<String> {
    let content = fs::read_to_string(config_path)?;
    let json_str = strip_jsonc_comments(&content);
    let value: serde_json::Value = serde_json::from_str(&json_str)?;
    Ok(value
        .get("nodeVersion")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown")
        .to_string())
}

fn push_summary(report: &mut String, counts: CategoryCounts) {
    let primary_total = counts.primary_total();
    let public_total = counts.public_total();
    let total = counts.total();

    report.push_str("## Summary\n\n");
    report.push_str(
        "Primary compatibility is measured over the public API surface we can provide: \
         CI-enforced passing (`runnable`) plus `known-gap`. WASI-impossible tests, engine \
         differences, unevaluated tests, and Node.js-internals tests are acknowledged separately \
         and excluded from the primary percentage.\n\n",
    );
    report.push_str(&format!(
        "**Primary compatibility (CI-enforced):** {}/{} ({:.1}%)\n\n",
        counts.runnable,
        primary_total,
        pct(counts.runnable, primary_total)
    ));
    report.push_str(
        "When comparing revisions, read the runnable count and secondary full-public percentage \
         alongside the primary percentage. Reclassifying a test into an excluded category can \
         increase the primary percentage without increasing runnable coverage.\n\n",
    );

    report.push_str("| Classification | Count | Primary % | Public inventory % | All listed % |\n");
    report.push_str("|----------------|-------|-----------|--------------------|--------------|\n");
    push_summary_row(
        report,
        "✅ passing (runnable)",
        counts.runnable,
        primary_total,
        public_total,
        total,
    );
    push_summary_row(
        report,
        "🧩 known gap",
        counts.known_gap,
        primary_total,
        public_total,
        total,
    );
    push_summary_row(
        report,
        "🚫 WASI-impossible (excluded)",
        counts.wasi_impossible,
        primary_total,
        public_total,
        total,
    );
    push_summary_row(
        report,
        "⚙️ engine difference (excluded)",
        counts.engine_difference,
        primary_total,
        public_total,
        total,
    );
    push_summary_row(
        report,
        "❔ unevaluated (excluded)",
        counts.unevaluated,
        primary_total,
        public_total,
        total,
    );
    push_summary_row(
        report,
        "🔒 Node.js internals (excluded)",
        counts.node_internals,
        primary_total,
        public_total,
        total,
    );
    report.push_str(&format!(
        "| **Total** | **{total}** |  |  | **100.0%** |\n\n"
    ));

    report.push_str(&format!(
        "Secondary full-public compatibility, including public tests that are currently \
         excluded from primary: **{}/{} ({:.1}%)**.\n\n",
        counts.runnable,
        public_total,
        pct(counts.runnable, public_total)
    ));
}

fn push_summary_row(
    report: &mut String,
    label: &str,
    count: usize,
    primary_total: usize,
    public_total: usize,
    total: usize,
) {
    let primary_pct = if label.contains("excluded") || label.contains("internals") {
        "—".to_string()
    } else {
        format!("{:.1}%", pct(count, primary_total))
    };
    let public_pct = if label.contains("internals") {
        "—".to_string()
    } else {
        format!("{:.1}%", pct(count, public_total))
    };
    report.push_str(&format!(
        "| {label} | {count} | {primary_pct} | {public_pct} | {:.1}% |\n",
        pct(count, total)
    ));
}

fn push_module_table(report: &mut String, by_module: &BTreeMap<String, CategoryCounts>) {
    report.push_str("## Inventory by Module\n\n");
    report.push_str("| Module | Total | Passing | Gap | WASI-impossible | Engine diff | Unevaluated | Internals | Primary % | Public compatibility % |\n");
    report.push_str("|--------|-------|----------|-----|-----------------|-------------|-------------|-----------|-----------|--------------------|\n");

    for (module, counts) in by_module {
        report.push_str(&format!(
            "| {module} | {} | {} | {} | {} | {} | {} | {} | {:.1}% | {:.1}% |\n",
            counts.total(),
            counts.runnable,
            counts.known_gap,
            counts.wasi_impossible,
            counts.engine_difference,
            counts.unevaluated,
            counts.node_internals,
            pct(counts.runnable, counts.primary_total()),
            pct(counts.runnable, counts.public_total()),
        ));
    }
    report.push('\n');
}

fn push_split_summary(report: &mut String, entries: &[NodeCompatTestEntry]) {
    report.push_str("## Split Test Summary\n\n");
    let split_entries: Vec<_> = entries.iter().filter(|entry| entry.split).collect();
    if split_entries.is_empty() {
        report.push_str("_No split test entries in config.jsonc._\n\n");
        return;
    }

    report.push_str("| File | Subtests | Passing | Gap | WASI-impossible | Engine diff | Unevaluated | Internals |\n");
    report.push_str("|------|----------|----------|-----|-----------------|-------------|-------------|-----------|\n");

    for entry in split_entries {
        let mut counts = CategoryCounts::default();
        for subtest in &entry.subtests {
            counts.add(subtest.category);
        }
        let filename = entry.path.rsplit('/').next().unwrap_or(&entry.path);
        report.push_str(&format!(
            "| `{}` | {} | {} | {} | {} | {} | {} | {} |\n",
            filename,
            entry.subtests.len(),
            counts.runnable,
            counts.known_gap,
            counts.wasi_impossible,
            counts.engine_difference,
            counts.unevaluated,
            counts.node_internals,
        ));
    }
    report.push('\n');
}

fn push_reason_sections(
    report: &mut String,
    by_category: &BTreeMap<NodeCompatCategory, Vec<&InventoryItem>>,
) {
    report.push_str("## Classified Non-Runnable Tests\n\n");
    for category in [
        NodeCompatCategory::KnownGap,
        NodeCompatCategory::WasmImpossible,
        NodeCompatCategory::EngineDifference,
        NodeCompatCategory::Unevaluated,
        NodeCompatCategory::NodeInternals,
    ] {
        let items = by_category.get(&category).cloned().unwrap_or_default();
        report.push_str(&format!("### {} ({})\n\n", category.label(), items.len()));
        if items.is_empty() {
            report.push_str("_No entries._\n\n");
            continue;
        }

        let mut by_reason: BTreeMap<String, Vec<&InventoryItem>> = BTreeMap::new();
        for item in items {
            by_reason
                .entry(
                    item.reason
                        .as_deref()
                        .filter(|reason| !reason.trim().is_empty())
                        .unwrap_or("missing reason")
                        .to_string(),
                )
                .or_default()
                .push(item);
        }

        let mut groups: Vec<_> = by_reason.into_iter().collect();
        groups.sort_by_key(|(_, items)| std::cmp::Reverse(items.len()));

        report.push_str("| Reason | Count | Example entries |\n");
        report.push_str("|--------|-------|-----------------|\n");
        for (reason, items) in &groups {
            let examples: Vec<_> = items
                .iter()
                .take(3)
                .map(|item| format!("`{}`", item.key))
                .collect();
            let suffix = if items.len() > 3 {
                format!(", ... (+{})", items.len() - 3)
            } else {
                String::new()
            };
            report.push_str(&format!(
                "| {} | {} | {}{} |\n",
                escape_table_cell(reason),
                items.len(),
                examples.join(", "),
                suffix
            ));
        }
        report.push('\n');
    }
}

fn push_missing_reasons(report: &mut String, missing_reasons: &[&InventoryItem]) {
    report.push_str("## Config Hygiene\n\n");
    if missing_reasons.is_empty() {
        report.push_str("All non-runnable entries have reasons.\n");
    } else {
        report.push_str(&format!(
            "{} non-runnable entr{} missing a reason.\n\n",
            missing_reasons.len(),
            if missing_reasons.len() == 1 {
                "y is"
            } else {
                "ies are"
            }
        ));
        report.push_str("<details>\n<summary>Entries missing reasons</summary>\n\n");
        for item in missing_reasons {
            report.push_str(&format!("- `{}` ({})\n", item.key, item.category.label()));
        }
        report.push_str("\n</details>\n");
    }
}

fn module_for_item(item: &InventoryItem) -> &str {
    let filename = item.file_path.rsplit('/').next().unwrap_or(&item.file_path);
    classify_test(filename)
}

fn pct(numerator: usize, denominator: usize) -> f64 {
    if denominator == 0 {
        0.0
    } else {
        numerator as f64 / denominator as f64 * 100.0
    }
}

fn escape_table_cell(value: &str) -> String {
    value.replace('\n', " ").replace('|', "\\|")
}