splicer 2.4.1

Plan and generate middleware splice operations for WebAssembly component composition graphs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
//! Extracts tier interface constants from the canonical WIT files in
//! `wit/tierN/world.wit` so the Rust code has a single source of truth
//! for the interface names it detects at composition time.
//!
//! For each `wit/tierN/world.wit` file, we parse:
//!   - the `package` declaration → e.g. `splicer:tier1@0.1.0`
//!   - every `interface <name>` declaration → e.g. `before`, `after`, `blocking`
//!   - every `<fn-name>: [async] func(...)` line inside each interface
//!
//! and generate a Rust source file at `$OUT_DIR/tier_interfaces.rs` with:
//!   - `TIER{N}_PACKAGE: &str` — the unversioned package key
//!   - `TIER{N}_VERSION: &str` — the semver version
//!   - `TIER{N}_INTERFACES: &[&str]` — fully-qualified interface names
//!   - `TIER{N}_{IFACE}_FNS: &[&str]` — function names inside each interface
//!
//! Additionally, asserts that every typedef / record-field /
//! function-param name that the Rust adapter codegen string-matches
//! against actually exists in the corresponding WIT file. A WIT
//! rename without a matching Rust update fails the build here,
//! instead of producing a runtime panic at adapter generation.

use std::fs;
use std::path::Path;

fn main() {
    let out_dir = std::env::var("OUT_DIR").unwrap();
    let dest = Path::new(&out_dir).join("tier_interfaces.rs");

    let mut generated = String::new();

    // Discover all wit/tierN/ directories in sorted order.
    let wit_dir = Path::new("wit");
    if !wit_dir.is_dir() {
        // No wit/ directory — write an empty file so the include! doesn't fail.
        fs::write(&dest, "// No wit/ directory found during build.\n").unwrap();
        return;
    }

    // Watch every world.wit under wit/ (tier dirs + common + any
    // future siblings) so cargo rebuilds when any WIT changes.
    for entry in fs::read_dir(wit_dir).unwrap().filter_map(|e| e.ok()) {
        if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
            continue;
        }
        let world_path = entry.path().join("world.wit");
        if world_path.exists() {
            println!("cargo::rerun-if-changed={}", world_path.display());
        }
    }

    let mut tier_dirs: Vec<_> = fs::read_dir(wit_dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false))
        .filter(|e| {
            e.file_name()
                .to_str()
                .map(|n| n.starts_with("tier"))
                .unwrap_or(false)
        })
        .collect();
    tier_dirs.sort_by_key(|e| e.file_name());

    for dir_entry in &tier_dirs {
        let dir_name = dir_entry.file_name();
        let dir_name = dir_name.to_str().unwrap();

        // Extract the tier number from the directory name (e.g. "tier1" → "1").
        let tier_num = dir_name
            .strip_prefix("tier")
            .expect("directory name must start with 'tier'");

        let world_path = dir_entry.path().join("world.wit");
        if !world_path.exists() {
            panic!(
                "Expected {}/world.wit to exist for tier {}",
                dir_entry.path().display(),
                tier_num
            );
        }

        // Tell cargo to re-run build.rs if the WIT file changes.
        println!("cargo::rerun-if-changed={}", world_path.display());

        let wit_src = fs::read_to_string(&world_path).unwrap_or_else(|e| {
            panic!("Failed to read {}: {e}", world_path.display());
        });

        // Parse `package splicer:tier1@0.1.0;`
        let (pkg_unversioned, pkg_version) = parse_package_decl(&wit_src, &world_path);

        // Parse every `interface <name> { ... }` block, capturing the
        // function names declared inside each.
        let ifaces = parse_interfaces(&wit_src);
        let iface_names: Vec<String> = ifaces.iter().map(|(n, _)| n.clone()).collect();

        // Build the fully-qualified interface names: "splicer:tier1/before" etc.
        let fq_names: Vec<String> = iface_names
            .iter()
            .map(|name| format!("{pkg_unversioned}/{name}"))
            .collect();

        let upper = tier_num.to_uppercase();
        generated.push_str(&format!(
            "/// Package key for tier-{tier_num} interfaces (no version suffix).\n\
             #[allow(dead_code)]\n\
             pub const TIER{upper}_PACKAGE: &str = \"{pkg_unversioned}\";\n\n\
             /// Semver version of the tier-{tier_num} WIT package.\n\
             #[allow(dead_code)]\n\
             pub const TIER{upper}_VERSION: &str = \"{pkg_version}\";\n\n"
        ));

        // Per-interface named constants (e.g. TIER1_BEFORE, TIER1_AFTER).
        for ((name, _fns), fq) in ifaces.iter().zip(fq_names.iter()) {
            let iface_upper = name.to_uppercase().replace('-', "_");
            let const_name = format!("TIER{upper}_{iface_upper}");
            generated.push_str(&format!(
                "/// Fully-qualified name of the `{name}` interface in the tier-{tier_num} WIT package.\n\
                 /// Derived from `wit/{dir_name}/world.wit` at build time.\n\
                 pub const {const_name}: &str = \"{fq}\";\n\n"
            ));
        }

        // The aggregate array referencing the per-interface constants.
        generated.push_str(&format!(
            "/// All tier-{tier_num} interface names, for middleware detection.\n\
             /// Derived from `wit/{dir_name}/world.wit` at build time.\n\
             pub const TIER{upper}_INTERFACES: &[&str] = &[\n"
        ));
        for name in &iface_names {
            let iface_upper = name.to_uppercase().replace('-', "_");
            let const_name = format!("TIER{upper}_{iface_upper}");
            generated.push_str(&format!("    {const_name},\n"));
        }
        generated.push_str("];\n\n");
    }

    // Emit COMMON_PACKAGE / COMMON_VERSION from wit/common/world.wit so
    // test scaffolds + any caller threading through versioned interface
    // names don't have to hardcode them. Keeps the wit-bump fix to a
    // single file.
    let common_path = wit_dir.join("common").join("world.wit");
    if common_path.exists() {
        println!("cargo::rerun-if-changed={}", common_path.display());
        let wit_src = fs::read_to_string(&common_path).unwrap_or_else(|e| {
            panic!("Failed to read {}: {e}", common_path.display());
        });
        let (pkg_unversioned, pkg_version) = parse_package_decl(&wit_src, &common_path);
        generated.push_str(&format!(
            "/// Package key for the shared `splicer:common` types (no version suffix).\n\
             #[allow(dead_code)]\n\
             pub const COMMON_PACKAGE: &str = \"{pkg_unversioned}\";\n\n\
             /// Semver version of the `splicer:common` WIT package.\n\
             #[allow(dead_code)]\n\
             pub const COMMON_VERSION: &str = \"{pkg_version}\";\n\n"
        ));
    }

    validate_schema_names(wit_dir);

    fs::write(&dest, &generated).unwrap();

    generate_builtin_protocol(&out_dir);
    generate_builtin_config_constants(&out_dir);
    stage_embedded_strategies(&out_dir);
    emit_sdk_test_version(&out_dir);
}

/// Read `splicer-tool-sdk/Cargo.toml` and emit its `[package].version`
/// as a Rust constant for test fixtures to consume. The SDK Cargo.toml
/// is stripped from the published tarball, but install-time builds
/// don't compile test code, so the fallback path is never read.
fn emit_sdk_test_version(out_dir: &str) {
    let dest = Path::new(out_dir).join("sdk_test_version.rs");
    let sdk_cargo = Path::new("splicer-tool-sdk").join("Cargo.toml");
    let version = if sdk_cargo.is_file() {
        println!("cargo::rerun-if-changed={}", sdk_cargo.display());
        let src = fs::read_to_string(&sdk_cargo)
            .unwrap_or_else(|e| panic!("Failed to read {}: {e}", sdk_cargo.display()));
        parse_cargo_package_version(&src, &sdk_cargo)
    } else {
        // Install-time path: SDK Cargo.toml stripped, but tests never
        // compile here. Fallback keeps the file syntactically valid.
        "0.0.0".to_string()
    };
    fs::write(
        &dest,
        format!("pub const SDK_TEST_VERSION: &str = \"{version}\";\n"),
    )
    .unwrap();
}

/// Stage every tier-3/4 builtin crate (discovered by scanning
/// `builtins/*/manifest.toml` for `tier = 3` or `4`) under
/// `$OUT_DIR/embedded-strategies/<name>/`, and emit
/// `$OUT_DIR/embedded_strategies.rs` so `src/strategies.rs` can
/// `include!` the matching `include_dir!` statics + `EMBEDDED` slice.
/// Accepts either `Cargo.toml` or `Cargo.toml.embed` at the source
/// and rewrites the strategy's `splicer-tool-sdk` dep to drop the
/// dev-only `path` hint on the way into OUT_DIR.
fn stage_embedded_strategies(out_dir: &str) {
    let manifest_dir =
        std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR set by cargo");
    let builtins_root = Path::new(&manifest_dir).join("builtins");
    let staged_root = Path::new(out_dir).join("embedded-strategies");

    let mut names: Vec<String> = discover_source_dist_strategies(&builtins_root);
    names.sort();

    for name in &names {
        let src_root = builtins_root.join(name);
        let dest_root = staged_root.join(name);
        rerun_for_strategy_sources(&src_root);

        if dest_root.exists() {
            fs::remove_dir_all(&dest_root).unwrap_or_else(|e| {
                panic!("Failed to clean {}: {e}", dest_root.display());
            });
        }
        fs::create_dir_all(&dest_root).unwrap_or_else(|e| {
            panic!("Failed to create {}: {e}", dest_root.display());
        });

        stage_strategy_dir(&src_root, &dest_root);
    }

    emit_embedded_strategies_rs(out_dir, &names);
}

/// Tiers whose builtins are source-distributed (staged into OUT_DIR
/// and compiled at splice time). Tiers not listed here ship as
/// pre-built wasm pulled from OCI. Extend when a new source-dist
/// tier comes online.
const STRATEGY_TIERS: &[i64] = &[3, 4];

/// Scan `builtins_root/*/manifest.toml` and return the names of
/// crates whose `[builtin].tier` is in [`STRATEGY_TIERS`]. Builtins
/// without a manifest (host-side helpers like `builtin-protocol`)
/// are skipped.
fn discover_source_dist_strategies(builtins_root: &Path) -> Vec<String> {
    let mut out = Vec::new();
    let Ok(entries) = fs::read_dir(builtins_root) else {
        return out;
    };
    for entry in entries.filter_map(|e| e.ok()) {
        if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
            continue;
        }
        let manifest_path = entry.path().join("manifest.toml");
        if !manifest_path.is_file() {
            continue;
        }
        println!("cargo::rerun-if-changed={}", manifest_path.display());
        let text = fs::read_to_string(&manifest_path)
            .unwrap_or_else(|e| panic!("Failed to read {}: {e}", manifest_path.display()));
        let parsed: toml::Value = toml::from_str(&text)
            .unwrap_or_else(|e| panic!("Failed to parse {}: {e}", manifest_path.display()));
        let tier = parsed
            .get("builtin")
            .and_then(|b| b.get("tier"))
            .and_then(|t| t.as_integer());
        if let Some(t) = tier {
            if STRATEGY_TIERS.contains(&t) {
                out.push(entry.file_name().to_string_lossy().into_owned());
            }
        }
    }
    out
}

/// Emit a Rust source file that declares one `static <UPPER>: Dir<'_>`
/// per staged strategy plus the `EMBEDDED` slice tying names to
/// directories. `src/strategies.rs` `include!`s this so adding a new
/// tier-3/4 builtin is a pure source-tree edit -- the registry
/// updates automatically on next build.
fn emit_embedded_strategies_rs(out_dir: &str, names: &[String]) {
    let dest = Path::new(out_dir).join("embedded_strategies.rs");
    let mut content =
        String::from("// Auto-generated by build.rs from builtins/*/manifest.toml.\n\n");
    for name in names {
        let upper = name.to_uppercase().replace('-', "_");
        content.push_str(&format!(
            "static {upper}: ::include_dir::Dir<'_> = \
             ::include_dir::include_dir!(\"$OUT_DIR/embedded-strategies/{name}\");\n",
        ));
    }
    content.push_str("\nstatic EMBEDDED: &[(&str, &::include_dir::Dir<'_>)] = &[\n");
    for name in names {
        let upper = name.to_uppercase().replace('-', "_");
        content.push_str(&format!("    (\"{name}\", &{upper}),\n"));
    }
    content.push_str("];\n");
    fs::write(&dest, content).unwrap_or_else(|e| panic!("Failed to write {}: {e}", dest.display()));
}

fn rerun_for_strategy_sources(src_root: &Path) {
    println!("cargo::rerun-if-changed={}", src_root.display());
    for name in ["Cargo.toml", "Cargo.toml.embed", "manifest.toml"] {
        let p = src_root.join(name);
        if p.exists() {
            println!("cargo::rerun-if-changed={}", p.display());
        }
    }
    let src_dir = src_root.join("src");
    if src_dir.is_dir() {
        walk_for_rerun(&src_dir);
    }
}

fn walk_for_rerun(dir: &Path) {
    let Ok(entries) = fs::read_dir(dir) else {
        return;
    };
    for entry in entries.filter_map(|e| e.ok()) {
        let ft = match entry.file_type() {
            Ok(ft) => ft,
            Err(_) => continue,
        };
        let path = entry.path();
        if ft.is_dir() {
            walk_for_rerun(&path);
        } else if ft.is_file() {
            println!("cargo::rerun-if-changed={}", path.display());
        }
    }
}

/// Copy a strategy crate's source tree into `dest_root`, writing a
/// normalized `Cargo.toml` (sourced from either `Cargo.toml` or
/// `Cargo.toml.embed`). Skips `Cargo.lock`/`target/`/hidden so the
/// staged dir is a clean source tree.
fn stage_strategy_dir(src_root: &Path, dest_root: &Path) {
    let cargo_src = if src_root.join("Cargo.toml").is_file() {
        src_root.join("Cargo.toml")
    } else if src_root.join("Cargo.toml.embed").is_file() {
        src_root.join("Cargo.toml.embed")
    } else {
        panic!(
            "Strategy crate at {} has neither Cargo.toml nor Cargo.toml.embed",
            src_root.display()
        );
    };
    let cargo_text = fs::read_to_string(&cargo_src)
        .unwrap_or_else(|e| panic!("Failed to read {}: {e}", cargo_src.display()));
    let normalized = normalize_strategy_cargo_toml(&cargo_text, &cargo_src);
    fs::write(dest_root.join("Cargo.toml"), normalized).unwrap_or_else(|e| {
        panic!(
            "Failed to write staged Cargo.toml for {}: {e}",
            src_root.display()
        );
    });

    for entry in fs::read_dir(src_root)
        .unwrap_or_else(|e| panic!("Failed to read {}: {e}", src_root.display()))
        .filter_map(|e| e.ok())
    {
        let name = entry.file_name();
        let name_str = name.to_string_lossy();
        // Cargo.toml is written above. Skip lock + target + hidden +
        // the .embed copy so the staged dir is a clean source tree.
        if matches!(
            name_str.as_ref(),
            "Cargo.toml" | "Cargo.toml.embed" | "Cargo.lock" | "target"
        ) || name_str.starts_with('.')
        {
            continue;
        }
        let src_path = entry.path();
        let dest_path = dest_root.join(&name);
        let ft = entry.file_type().unwrap_or_else(|e| {
            panic!("Failed to stat {}: {e}", src_path.display());
        });
        if ft.is_dir() {
            copy_dir_recursive(&src_path, &dest_path);
        } else if ft.is_file() {
            fs::copy(&src_path, &dest_path).unwrap_or_else(|e| {
                panic!(
                    "Failed to copy {} -> {}: {e}",
                    src_path.display(),
                    dest_path.display()
                );
            });
        }
    }
}

fn copy_dir_recursive(src: &Path, dest: &Path) {
    fs::create_dir_all(dest).unwrap_or_else(|e| {
        panic!("Failed to create {}: {e}", dest.display());
    });
    let Ok(entries) = fs::read_dir(src) else {
        return;
    };
    for entry in entries.filter_map(|e| e.ok()) {
        let ft = match entry.file_type() {
            Ok(ft) => ft,
            Err(_) => continue,
        };
        let name = entry.file_name();
        let src_path = entry.path();
        let dest_path = dest.join(&name);
        if ft.is_dir() {
            copy_dir_recursive(&src_path, &dest_path);
        } else if ft.is_file() {
            fs::copy(&src_path, &dest_path).unwrap_or_else(|e| {
                panic!(
                    "Failed to copy {} -> {}: {e}",
                    src_path.display(),
                    dest_path.display()
                );
            });
        }
    }
}

/// Rewrite the strategy's `splicer-tool-sdk` dep to a plain version
/// string, stripping the dev-only `path` hint that only resolves at
/// the repo location (not after OUT_DIR staging).
fn normalize_strategy_cargo_toml(src: &str, src_path: &Path) -> String {
    let mut parsed: toml::Value = toml::from_str(src).unwrap_or_else(|e| {
        panic!("Failed to parse {} as TOML: {e}", src_path.display());
    });
    let version = parsed
        .get("dependencies")
        .and_then(|d| d.get("splicer-tool-sdk"))
        .and_then(|d| match d {
            toml::Value::String(s) => Some(s.clone()),
            toml::Value::Table(t) => t
                .get("version")
                .and_then(|v| v.as_str())
                .map(str::to_string),
            _ => None,
        })
        .unwrap_or_else(|| {
            panic!(
                "Strategy {} must declare splicer-tool-sdk = \"<version>\" \
                 (or `{{ version = \"<version>\", path = \"...\" }}`) in [dependencies]",
                src_path.display(),
            );
        });

    if let Some(deps) = parsed
        .get_mut("dependencies")
        .and_then(|d| d.as_table_mut())
    {
        deps.insert("splicer-tool-sdk".to_string(), toml::Value::String(version));
    }
    toml::to_string(&parsed).unwrap_or_else(|e| {
        panic!(
            "Failed to re-serialize normalized Cargo.toml for {}: {e}",
            src_path.display()
        );
    })
}

/// Scan `builtins/<name>/` for shipped wasm-builtins and emit the
/// `(name, version)` slice that `src/builtins/tier1_2.rs` `include!`s
/// as the OCI version registry. Reads each builtin's `Cargo.toml` or
/// `Cargo.toml.embed`, whichever survives the publish-time rename.
fn generate_builtin_protocol(out_dir: &str) {
    let dest = Path::new(out_dir).join("builtin_protocol.rs");
    let builtins_dir = Path::new("builtins");

    // Watch the directory itself so cargo reruns when crates are
    // added/removed; per-Cargo.toml lines below catch content changes.
    println!("cargo::rerun-if-changed=builtins");

    let mut rows = String::new();
    if builtins_dir.is_dir() {
        let mut crate_dirs: Vec<_> = fs::read_dir(builtins_dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .filter(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false))
            .collect();
        crate_dirs.sort_by_key(|e| e.file_name());

        for entry in crate_dirs {
            let entry_path = entry.path();
            let cargo_toml = entry_path.join("Cargo.toml");
            let cargo_embed = entry_path.join("Cargo.toml.embed");
            let manifest_path = if cargo_toml.is_file() {
                cargo_toml
            } else if cargo_embed.is_file() {
                cargo_embed
            } else {
                continue;
            };
            // builtin-protocol is a host-side helper (no `wit/`),
            // pulled as a regular crates.io dep; skip it.
            if !entry_path.join("wit").is_dir() {
                continue;
            }
            println!("cargo::rerun-if-changed={}", manifest_path.display());
            for sub in ["src", "wit"] {
                let dir = entry_path.join(sub);
                if dir.is_dir() {
                    walk_for_rerun(&dir);
                }
            }
            let mtoml = entry_path.join("manifest.toml");
            if mtoml.is_file() {
                println!("cargo::rerun-if-changed={}", mtoml.display());
            }
            let src = fs::read_to_string(&manifest_path).unwrap_or_else(|e| {
                panic!("Failed to read {}: {e}", manifest_path.display());
            });
            let version = parse_cargo_package_version(&src, &manifest_path);
            // The directory name is what users put in yaml and what the
            // publish workflow uses as the OCI path component, so it's
            // the canonical "builtin name" -- not Cargo.toml's `name`,
            // even though they match by convention today.
            let name = entry.file_name().to_string_lossy().into_owned();
            rows.push_str(&format!("    (\"{name}\", \"{version}\"),\n"));
        }
    }

    let content = format!(
        "// Auto-generated by build.rs from builtins/*/Cargo.toml(.embed). Do not edit.\n&[\n{rows}]\n"
    );
    fs::write(&dest, content).unwrap();
}

/// Extract `version = "..."` from `[package]`. Line-based (avoids
/// adding `toml` to this reader's path).
fn parse_cargo_package_version(src: &str, path: &Path) -> String {
    let mut in_package = false;
    for line in src.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with('[') {
            in_package = trimmed == "[package]";
            continue;
        }
        if !in_package {
            continue;
        }
        let Some(rest) = trimmed.strip_prefix("version") else {
            continue;
        };
        let Some(rest) = rest.trim_start().strip_prefix('=') else {
            continue;
        };
        let rest = rest.trim_start();
        let Some(rest) = rest.strip_prefix('"') else {
            panic!(
                "[package] version in {} is not a quoted string: {trimmed:?}",
                path.display()
            );
        };
        let Some(end) = rest.find('"') else {
            panic!(
                "[package] version in {} has unterminated quote: {trimmed:?}",
                path.display()
            );
        };
        let v = &rest[..end];
        if v.is_empty() {
            panic!("Empty version in [package] of {}", path.display());
        }
        return v.to_string();
    }
    panic!(
        "No `version = \"...\"` found in [package] of {}",
        path.display()
    );
}

/// Emit `BUILTIN_CONFIG_*` constants for `src/config_provider.rs`
/// from `wit/builtin-config/world.wit`. Bumping the package version
/// in the WIT propagates everywhere.
fn generate_builtin_config_constants(out_dir: &str) {
    let dest = Path::new(out_dir).join("builtin_config_constants.rs");
    let wit_path = Path::new("wit").join("builtin-config").join("world.wit");

    if !wit_path.exists() {
        fs::write(&dest, "// No wit/builtin-config/world.wit found.\n").unwrap();
        return;
    }
    println!("cargo::rerun-if-changed={}", wit_path.display());

    let wit_src = fs::read_to_string(&wit_path)
        .unwrap_or_else(|e| panic!("Failed to read {}: {e}", wit_path.display()));
    let (pkg, version) = parse_package_decl(&wit_src, &wit_path);
    let ifaces = parse_interfaces(&wit_src);

    let mut content = String::from(
        "// Auto-generated by build.rs from wit/builtin-config/world.wit. Do not edit.\n\n",
    );
    content.push_str(&format!(
        "#[allow(dead_code)]\npub const BUILTIN_CONFIG_PACKAGE: &str = \"{pkg}\";\n\n",
    ));
    content.push_str(&format!(
        "#[allow(dead_code)]\npub const BUILTIN_CONFIG_VERSION: &str = \"{version}\";\n\n",
    ));
    let mut iface_consts: Vec<String> = Vec::new();
    for (name, _) in &ifaces {
        let upper = name.to_uppercase().replace('-', "_");
        let unversioned = format!("{pkg}/{name}");
        let versioned = format!("{unversioned}@{version}");
        let unver_const = format!("BUILTIN_CONFIG_{upper}");
        let ver_const = format!("BUILTIN_CONFIG_{upper}_VERSIONED");
        content.push_str(&format!(
            "#[allow(dead_code)]\npub const {unver_const}: &str = \"{unversioned}\";\n\n",
        ));
        content.push_str(&format!(
            "#[allow(dead_code)]\npub const {ver_const}: &str = \"{versioned}\";\n\n",
        ));
        iface_consts.push(unver_const);
    }
    content.push_str("#[allow(dead_code)]\npub const BUILTIN_CONFIG_INTERFACES: &[&str] = &[\n");
    for c in &iface_consts {
        content.push_str(&format!("    {c},\n"));
    }
    content.push_str("];\n");

    fs::write(&dest, content).unwrap();
}

/// Asserts that every WIT typedef / record-field / function-param
/// that `src/adapter/tier2/emit.rs` looks up by string actually
/// exists in the WIT files. A WIT rename without a matching Rust
/// update fails here at build time.
///
/// The expected names below MUST stay in sync with the `TYPEDEF_*` /
/// `FIELD_*` / `TREE_*` / `CALLID_*` / `ON_*` constants declared in
/// `src/adapter/tier2/emit.rs`. The mirroring isn't ideal — but it
/// turns a runtime panic ("no field named …") into a compile-time
/// failure at the file that owns the schema.
fn validate_schema_names(wit_dir: &Path) {
    let common_path = wit_dir.join("common").join("world.wit");
    if !common_path.exists() {
        // Nothing to validate. The runtime `include_str!` will fail
        // anyway if this file is genuinely missing.
        return;
    }
    let common_src = fs::read_to_string(&common_path)
        .unwrap_or_else(|e| panic!("Failed to read {}: {e}", common_path.display()));

    // (typedef-name, expected-fields). Mirrors `TYPEDEF_*` and the
    // `FIELD_*` / `TREE_*` / `CALLID_*` field constants in
    // `src/adapter/tier2/emit.rs`. Empty `fields` means typedef-only.
    let common_records: &[(&str, &[&str])] = &[
        ("field", &["name", "tree"]),
        (
            "field-tree",
            &[
                "cells",
                "record-infos",
                "flags-infos",
                "enum-infos",
                "variant-infos",
                "handle-infos",
                "root",
            ],
        ),
        ("call-id", &["interface-name", "function-name"]),
        ("enum-info", &["type-name", "case-name"]),
        ("record-info", &["type-name", "fields"]),
    ];
    for (name, fields) in common_records {
        require_record_with_fields(&common_src, &common_path, name, fields);
    }
    // `cell` is a variant; this item only requires its existence.
    // The 18 case discriminants are pinned by an ordering test in
    // `tier2/cells.rs` and are tracked as a separate audit item.
    require_typedef(&common_src, &common_path, "variant", "cell");

    let tier2_path = wit_dir.join("tier2").join("world.wit");
    if !tier2_path.exists() {
        return;
    }
    let tier2_src = fs::read_to_string(&tier2_path)
        .unwrap_or_else(|e| panic!("Failed to read {}: {e}", tier2_path.display()));
    // Mirrors `ON_CALL_*` / `ON_RET_*` in `src/adapter/tier2/emit.rs`.
    // `result` is a WIT keyword and shows up as `%result` in the WIT
    // source; the validator strips the `%` before comparison.
    require_func_params(&tier2_src, &tier2_path, "on-call", &["call", "args"]);
    require_func_params(&tier2_src, &tier2_path, "on-return", &["call", "result"]);
}

fn require_typedef(src: &str, path: &Path, kind: &str, name: &str) {
    if extract_typedef_body(src, kind, name).is_none() {
        panic!(
            "Schema mismatch: `{kind} {name}` not found in {}.\n\
             The Rust adapter codegen (src/adapter/tier2/emit.rs) references this typedef.\n\
             Either restore the WIT typedef, or update the constants in emit.rs and build.rs.",
            path.display()
        );
    }
}

fn require_record_with_fields(src: &str, path: &Path, name: &str, fields: &[&str]) {
    let body = extract_typedef_body(src, "record", name).unwrap_or_else(|| {
        panic!(
            "Schema mismatch: `record {name}` not found in {}.\n\
             The Rust adapter codegen (src/adapter/tier2/emit.rs) references this typedef.\n\
             Either restore the WIT typedef, or update the constants in emit.rs and build.rs.",
            path.display()
        )
    });
    for field in fields {
        if !record_body_has_field(&body, field) {
            panic!(
                "Schema mismatch: `record {name}` in {} is missing field `{field}`.\n\
                 The Rust adapter codegen (src/adapter/tier2/emit.rs) references this field.\n\
                 Either restore the WIT field, or update the constants in emit.rs and build.rs.",
                path.display()
            );
        }
    }
}

fn require_func_params(src: &str, path: &Path, fn_name: &str, params: &[&str]) {
    let decl = extract_func_decl(src, fn_name).unwrap_or_else(|| {
        panic!(
            "Schema mismatch: function `{fn_name}` not found in {}.\n\
             The Rust adapter codegen (src/adapter/tier2/emit.rs) references it.",
            path.display()
        )
    });
    let param_names = parse_func_param_names(&decl);
    for expected in params {
        let canonical = expected.strip_prefix('%').unwrap_or(expected);
        if !param_names.iter().any(|n| n == canonical) {
            panic!(
                "Schema mismatch: function `{fn_name}` in {} is missing param `{canonical}`. \
                 Found params: {:?}\n\
                 The Rust adapter codegen (src/adapter/tier2/emit.rs) references this param.\n\
                 Either restore the WIT param, or update the constants in emit.rs and build.rs.",
                path.display(),
                param_names,
            );
        }
    }
}

/// Return the body text of a typedef block (everything between the
/// matching `{` and `}`), or `None` if no `<kind> <name> { … }`
/// declaration exists. Brace-depth tracking handles nested types.
fn extract_typedef_body(src: &str, kind: &str, name: &str) -> Option<String> {
    let header_prefix = format!("{kind} {name}");
    let mut depth: i32 = 0;
    let mut body = String::new();
    let mut found = false;
    for line in src.lines() {
        let trimmed = line.trim();
        if !found {
            if let Some(rest) = trimmed.strip_prefix(&header_prefix) {
                // The next non-whitespace character must be `{` for
                // this to be a typedef declaration (vs. e.g. a use of
                // `record-info` as a type reference).
                let rest = rest.trim_start();
                if let Some(after_brace) = rest.strip_prefix('{') {
                    found = true;
                    depth = 1;
                    if !after_brace.trim().is_empty() {
                        body.push_str(after_brace);
                        body.push('\n');
                    }
                }
            }
            continue;
        }
        for ch in trimmed.chars() {
            match ch {
                '{' => depth += 1,
                '}' => depth -= 1,
                _ => {}
            }
        }
        if depth <= 0 {
            // Strip the closing brace and stop. WIT typedef bodies
            // don't put trailing content after `}` on the same line,
            // but be defensive in case future WIT does.
            let close = trimmed.rfind('}').unwrap_or(trimmed.len());
            body.push_str(&trimmed[..close]);
            return Some(body);
        }
        body.push_str(trimmed);
        body.push('\n');
    }
    if found {
        Some(body)
    } else {
        None
    }
}

/// True iff the typedef body has a line whose first ident-token is
/// `field` (with the leading `%` keyword-escape stripped) followed by
/// a `:`.
fn record_body_has_field(body: &str, field: &str) -> bool {
    for line in body.lines() {
        let trimmed = line.trim();
        let trimmed = trimmed.strip_prefix('%').unwrap_or(trimmed);
        if let Some(rest) = trimmed.strip_prefix(field) {
            // `record_body_has_field("cells", body)` must not match
            // `cells-of:` etc. The next char must be whitespace or `:`.
            let next = rest.chars().next();
            if next == Some(':') || next.map(|c| c.is_whitespace()).unwrap_or(false) {
                let after = rest.trim_start();
                if after.starts_with(':') {
                    return true;
                }
            }
        }
    }
    false
}

/// Find a function declaration line of the form
/// `<fn_name>: [async] func( ... );` and return the trimmed line.
/// Tier-2 hooks fit on one line; multi-line decls aren't supported
/// (extend if a future hook ever spans lines).
fn extract_func_decl(src: &str, fn_name: &str) -> Option<String> {
    for line in src.lines() {
        let trimmed = line.trim();
        let Some(rest) = trimmed.strip_prefix(fn_name) else {
            continue;
        };
        let Some(rest) = rest.trim_start().strip_prefix(':') else {
            continue;
        };
        let rest = rest.trim_start();
        let rest = rest.strip_prefix("async ").unwrap_or(rest);
        if rest.starts_with("func(") || rest.starts_with("func (") {
            return Some(trimmed.to_string());
        }
    }
    None
}

fn parse_func_param_names(decl: &str) -> Vec<String> {
    let Some(open) = decl.find('(') else {
        return Vec::new();
    };
    let Some(close) = decl[open + 1..].rfind(')') else {
        return Vec::new();
    };
    let inside = &decl[open + 1..open + 1 + close];

    // Split on commas at depth 0 — types like `list<u32>` or
    // `tuple<string, u32>` carry their own commas inside angle
    // brackets that we must not split on.
    let mut depth: i32 = 0;
    let mut params: Vec<String> = Vec::new();
    let mut current = String::new();
    for ch in inside.chars() {
        match ch {
            '<' | '(' | '{' => {
                depth += 1;
                current.push(ch);
            }
            '>' | ')' | '}' => {
                depth -= 1;
                current.push(ch);
            }
            ',' if depth == 0 => {
                if let Some(n) = parse_one_param_name(&current) {
                    params.push(n);
                }
                current.clear();
            }
            _ => current.push(ch),
        }
    }
    if !current.trim().is_empty() {
        if let Some(n) = parse_one_param_name(&current) {
            params.push(n);
        }
    }
    params
}

fn parse_one_param_name(s: &str) -> Option<String> {
    let s = s.trim();
    let (name, _ty) = s.split_once(':')?;
    let name = name.trim();
    if name.is_empty() {
        return None;
    }
    Some(name.strip_prefix('%').unwrap_or(name).to_string())
}

/// Extract the package declaration from a WIT source string.
/// Returns `(unversioned_package, version)` — e.g. `("splicer:tier1", "0.1.0")`.
fn parse_package_decl(src: &str, path: &Path) -> (String, String) {
    for line in src.lines() {
        let line = line.trim();
        if let Some(rest) = line.strip_prefix("package ") {
            // "splicer:tier1@0.1.0;" → strip trailing ';' and split on '@'.
            let rest = rest.trim().trim_end_matches(';').trim();
            if let Some((pkg, ver)) = rest.split_once('@') {
                return (pkg.to_string(), ver.to_string());
            }
            panic!(
                "Package declaration in {} missing version: '{}'",
                path.display(),
                line
            );
        }
    }
    panic!("No `package` declaration found in {}", path.display());
}

/// Extract every `interface <name> { ... }` block from a WIT source
/// string, returning `(iface_name, fn_names)` pairs in declaration
/// order. Function names are parsed with a line-based matcher —
/// anything of the form `<name>: [async] func(...)` inside the
/// interface body. This is deliberately narrow: full WIT type
/// parsing (param/result types, compound signatures) is a separate
/// project that would want `wit-parser`; here we only extract names
/// the adapter needs to string-match against component exports at
/// runtime.
fn parse_interfaces(src: &str) -> Vec<(String, Vec<String>)> {
    let mut out: Vec<(String, Vec<String>)> = Vec::new();
    let mut current: Option<(String, Vec<String>)> = None;

    for line in src.lines() {
        let line = line.trim();

        if let Some(rest) = line.strip_prefix("interface ") {
            // Starting a new interface block. If one was open (shouldn't
            // happen in well-formed WIT), flush it first.
            if let Some(prev) = current.take() {
                out.push(prev);
            }
            let name = rest
                .split_whitespace()
                .next()
                .unwrap_or("")
                .trim_end_matches('{')
                .to_string();
            if !name.is_empty() {
                current = Some((name, Vec::new()));
            }
            continue;
        }

        if line == "}" {
            if let Some(iface) = current.take() {
                out.push(iface);
            }
            continue;
        }

        if let Some((_, ref mut fns)) = current.as_mut() {
            if let Some(fn_name) = parse_fn_decl_name(line) {
                fns.push(fn_name);
            }
        }
    }

    // A file missing a closing `}` still flushes a partial block, for
    // sanity — malformed WIT should fail elsewhere.
    if let Some(iface) = current {
        out.push(iface);
    }

    out
}

/// Extract the function name from a line like
/// `before-call: async func(name: string);` or
/// `get-info: func() -> string;`. Returns `None` for anything that
/// doesn't look like a function declaration.
fn parse_fn_decl_name(line: &str) -> Option<String> {
    // Must contain `func(` somewhere after a `:`.
    let (lhs, rhs) = line.split_once(':')?;
    let rhs = rhs.trim();
    let rhs = rhs.strip_prefix("async ").unwrap_or(rhs);
    if !rhs.starts_with("func(") && !rhs.starts_with("func ") {
        return None;
    }
    let name = lhs.trim();
    if name.is_empty() || name.contains(char::is_whitespace) {
        return None;
    }
    Some(name.to_string())
}