alef 0.62.8

Opinionated polyglot binding generator for Rust libraries
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
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
use crate::core::backend::GeneratedFile;
use crate::core::config::{Language, ResolvedCrateConfig};
use crate::core::ir::{ApiSurface, FieldDef, FunctionDef, PrimitiveType, TypeDef, TypeRef};
use crate::core::template_versions as tv;
use crate::{
    scaffold::cargo_package_header, scaffold::core_dep_features, scaffold::detect_workspace_inheritance_for_crate,
    scaffold::render_extra_deps, scaffold::scaffold_meta,
};
use std::collections::HashSet;
use std::path::PathBuf;

/// The path (relative to the project root) of the Ruby native crate's Cargo.toml.
///
/// Single source of truth for where `scaffold_ruby_cargo` writes that manifest, so a caller
/// wanting to read it back (e.g. `MagnusBackend::generate_bindings`, cross-checking the manifest
/// against `codegen::cfg::collect_cfg_features`) does not have to re-derive the formula from an
/// unrelated path such as `alef build`'s own `lib.rs` output directory -- which a `[crates.output]
/// ruby = "..."` override can point somewhere this formula's `native/` segment does not appear
/// under at all. ~keep
pub(crate) fn ruby_native_manifest_path(config: &ResolvedCrateConfig) -> PathBuf {
    let core_crate_dir = config.core_crate_dir();
    let pkg_dir = config.package_dir(Language::Ruby);
    PathBuf::from(format!(
        "{pkg_dir}/ext/{}_rb/native/Cargo.toml",
        core_crate_dir.replace('-', "_")
    ))
}

pub(crate) fn scaffold_ruby_cargo(
    api: &ApiSurface,
    config: &ResolvedCrateConfig,
) -> anyhow::Result<Vec<GeneratedFile>> {
    let meta = scaffold_meta(config);
    let version = &api.version;
    let core_crate_dir = config.core_crate_dir();
    let pkg_dir = config.package_dir(Language::Ruby);
    let native_crate_dir = format!("{pkg_dir}/ext/{}_rb/native", core_crate_dir.replace('-', "_"));
    let ws = detect_workspace_inheritance_for_crate(config.workspace_root.as_deref(), &native_crate_dir);
    let pkg_header = cargo_package_header(&format!("{core_crate_dir}-rb"), version, "2024", &meta, &ws);

    let extra_deps = render_extra_deps(config, Language::Ruby);

    let has_trait_bridges = !config.trait_bridges.is_empty();
    let has_streaming_adapter = config
        .adapters
        .iter()
        .any(|a| matches!(a.pattern, crate::core::config::AdapterPattern::Streaming));
    let has_async =
        api.functions.iter().any(|f| f.is_async) || api.types.iter().any(|t| t.methods.iter().any(|m| m.is_async));
    let needs_ahash = api.functions.iter().any(|f| f.params.iter().any(|p| p.map_is_ahash));
    let lib_name = format!("{}_rb", core_crate_dir.replace('-', "_"));

    let features_str = core_dep_features(config, Language::Ruby);
    let core_overrides = config
        .ruby
        .as_ref()
        .map(|c| c.target_dep_overrides.as_slice())
        .unwrap_or(&[]);
    let (core_dep_line, core_target_blocks) = crate::scaffold::render_core_dep_with_overrides(
        &config.name,
        &format!("../../../../../crates/{core_crate_dir}"),
        &features_str,
        version,
        core_overrides,
    );
    let core_target_blocks_section = if core_target_blocks.is_empty() {
        String::new()
    } else {
        format!("\n{core_target_blocks}")
    };
    let mut dep_lines: Vec<String> = vec![
        format!("magnus = \"{}\"", tv::cargo::MAGNUS),
        "rb-sys = \">=0.9, <0.9.128\"".to_owned(),
        "serde = { version = \"1\", features = [\"derive\"] }".to_owned(),
        "serde_json = \"1\"".to_owned(),
    ];
    if has_async || has_trait_bridges {
        dep_lines.push("tokio = { version = \"1\", features = [\"rt-multi-thread\"] }".to_owned());
    }
    if needs_ahash && !dep_lines.iter().any(|l| l.starts_with("ahash")) {
        dep_lines.push("ahash = \"0.8\"".to_owned());
    }
    if has_trait_bridges && !dep_lines.iter().any(|l| l.starts_with("async-trait")) {
        dep_lines.push("async-trait = \"0.1\"".to_owned());
    }
    if has_trait_bridges && !dep_lines.iter().any(|l| l.starts_with("tracing")) {
        dep_lines.push(format!("tracing = \"{}\"", tv::cargo::TRACING));
    }
    if has_streaming_adapter && !dep_lines.iter().any(|l| l.starts_with("futures")) {
        dep_lines.push("futures = \"0.3\"".to_owned());
    }
    for line in extra_deps.lines() {
        let trimmed = line.trim();
        if !trimmed.is_empty()
            && !dep_lines
                .iter()
                .any(|l| l.starts_with(trimmed.split('=').next().unwrap_or("")))
        {
            dep_lines.push(trimmed.to_owned());
        }
    }
    if !core_dep_line.is_empty() {
        dep_lines.push(core_dep_line);
    }
    crate::scaffold::sort_dependency_lines(&mut dep_lines);
    let deps_section = dep_lines.join("\n");

    let mut machete_ignored: Vec<&str> = vec!["rb-sys"];
    if has_trait_bridges {
        machete_ignored.push("async-trait");
        machete_ignored.push("tracing");
        if !has_async {
            machete_ignored.push("tokio");
        }
    }
    machete_ignored.sort_unstable();
    let ignored_list = machete_ignored
        .iter()
        .map(|d| format!("\"{d}\""))
        .collect::<Vec<_>>()
        .join(", ");
    let machete_section = format!("[package.metadata.cargo-machete]\nignored = [{ignored_list}]\n\n");

    // core dep. Without this, `#[cfg(feature = "X")]` arms emitted by the
    let cfg_features = crate::codegen::cfg::collect_cfg_features(api);
    let features_table = if cfg_features.is_empty() {
        String::new()
    } else {
        let mut lines: Vec<String> = Vec::with_capacity(cfg_features.len() + 1);
        let default_list: Vec<String> = cfg_features.iter().map(|name| format!("\"{name}\"")).collect();
        lines.push(format!("default = [{}]", default_list.join(", ")));
        for name in &cfg_features {
            lines.push(format!(
                r#"{name} = ["{core_dep_key}/{name}"]"#,
                core_dep_key = config.name
            ));
        }
        format!("[features]\n{}\n\n", lines.join("\n"))
    };

    let lints_section = crate::scaffold::cargo_lints_section(config);
    let content = format!(
        r#"{pkg_header}

{machete_section}[lib]
name = "{lib_name}"
path = "../src/lib.rs"
crate-type = ["cdylib"]

{features_table}[dependencies]
{deps_section}
{core_target_blocks_section}{lints_section}"#,
        pkg_header = pkg_header,
        lints_section = lints_section,
        machete_section = machete_section,
        lib_name = lib_name,
        features_table = features_table,
        deps_section = deps_section,
        core_target_blocks_section = core_target_blocks_section,
    );

    Ok(vec![GeneratedFile {
        path: ruby_native_manifest_path(config),
        content,
        generated_header: true,
    }])
}

pub(crate) fn scaffold_ruby(api: &ApiSurface, config: &ResolvedCrateConfig) -> anyhow::Result<Vec<GeneratedFile>> {
    let meta = scaffold_meta(config);
    let gem_name = config.ruby_gem_name();
    let gem_name_snake = gem_name.replace('-', "_");
    let core_crate_dir = config.core_crate_dir();
    let pkg_dir = config.package_dir(Language::Ruby);
    let ext_name = format!("{}_rb", core_crate_dir.replace('-', "_"));
    let cargo_pkg_name = format!("{}-rb", core_crate_dir);
    let version = crate::core::version::to_rubygems_prerelease(&api.version);
    let required_ruby_version = config
        .ruby
        .as_ref()
        .and_then(|c| c.required_ruby_version.clone())
        .unwrap_or_else(|| ">= 3.2.0".to_string());

    let authors_ruby = if meta.authors.is_empty() {
        "[]".to_string()
    } else {
        let entries: Vec<String> = meta.authors.iter().map(|a| format!("\"{}\"", a)).collect();
        format!("[{}]", entries.join(", "))
    };

    let metadata_ruby = if meta.keywords.is_empty() {
        String::new()
    } else {
        let word_array_safe = meta
            .keywords
            .iter()
            .all(|k| !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'));
        let array_literal = if word_array_safe {
            format!("%w[{}]", meta.keywords.join(" "))
        } else {
            let entries: Vec<String> = meta.keywords.iter().map(|k| format!("\"{}\"", k)).collect();
            format!("[{}]", entries.join(", "))
        };
        format!("  spec.metadata[\"keywords\"] = {}.join(\",\")\n", array_literal)
    };
    let homepage_ruby = meta
        .configured_repository
        .as_deref()
        .map(|repository| format!("  spec.homepage      = \"{repository}\"\n"))
        .unwrap_or_default();
    let license_ruby = meta
        .license
        .as_deref()
        .map(|license| format!("  spec.license       = \"{license}\"\n"))
        .unwrap_or_default();

    let content = format!(
        r#"# frozen_string_literal: true

Gem::Specification.new do |spec|
  spec.name = "{gem_name}"
  spec.version = "{version}"
  spec.authors       = {authors}
  spec.summary       = "{description}"
  spec.description   = "{description}"
{homepage}
{license}
  spec.required_ruby_version = "{required_ruby_version}"
{metadata}  spec.metadata["rubygems_mfa_required"] = "true"

  candidate_files    = Dir.glob(%w[README* LICENSE* lib/**/* ext/**/* sig/**/* Steepfile]).select {{ |f| File.file?(f) }}
  spec.files         = candidate_files.reject {{ |f| f.match?(%r{{/(?:target|tmp)/|\.(?:bundle|so|dylib|dll|o|a|log)\z|\.dSYM/}}) }}
  spec.require_paths = ["lib"]
  spec.extensions    = ["ext/{ext_name}/native/extconf.rb"]

  spec.add_dependency "rb_sys", {rb_sys}
  spec.add_dependency "sorbet-runtime", "{sorbet_runtime}"
end
"#,
        gem_name = gem_name,
        ext_name = ext_name,
        version = version,
        required_ruby_version = required_ruby_version,
        authors = authors_ruby,
        description = meta.description,
        homepage = homepage_ruby,
        license = license_ruby,
        metadata = metadata_ruby,
        rb_sys = tv::gem::RB_SYS,
        sorbet_runtime = tv::gem::SORBET_RUNTIME,
    );

    let rubocop_content = r#"plugins:
  - rubocop-performance
  - rubocop-rspec

AllCops:
  TargetRubyVersion: 3.2
  NewCops: enable
  SuggestExtensions: false
  Exclude:
    - "vendor/**/*"
    - "tmp/**/*"
    - "lib/**/*.bundle"
    - "lib/**/*.rb"
    - "ext/**/*"

Style/FrozenStringLiteralComment:
  Enabled: true
  EnforcedStyle: always

Style/StringLiterals:
  Enabled: true
  EnforcedStyle: double_quotes

Style/StringLiteralsInInterpolation:
  Enabled: true
  EnforcedStyle: double_quotes

Style/Documentation:
  Enabled: false

# Formatting — layout, indentation, line breaks, line length — is owned by
# rubyfmt (via poly). Disable rubocop's Layout department so the two do not
# fight; rubocop runs for correctness/style lint only (CI, toolchain-gated).
Layout:
  Enabled: false

Metrics/MethodLength:
  Max: 20
  Exclude:
    - "spec/**/*"

Metrics/BlockLength:
  Enabled: true
  Max: 350
  CountComments: false

Metrics/AbcSize:
  Max: 20
  Exclude:
    - "spec/**/*"

RSpec/ExampleLength:
  Max: 50

RSpec/MultipleExpectations:
  Max: 25

RSpec/NestedGroups:
  Max: 6
"#
    .to_string();

    // Ruby cross-compile platforms, each paired with the Rust target triple that ~keep
    // backs it. A platform whose triple is disabled via the workspace `[targets]` ~keep
    // opt-out table is dropped from the generated `CROSS_PLATFORMS` list. ~keep
    const RUBY_CROSS_PLATFORMS: &[(&str, &str)] = &[
        ("x86_64-linux", "x86_64-unknown-linux-gnu"),
        ("aarch64-linux", "aarch64-unknown-linux-gnu"),
        ("arm64-darwin", "aarch64-apple-darwin"),
        ("x86_64-darwin", "x86_64-apple-darwin"),
        ("x64-mingw-ucrt", "x86_64-pc-windows-msvc"),
    ];
    let cross_platforms = RUBY_CROSS_PLATFORMS
        .iter()
        .filter(|(_, triple)| config.target_enabled(triple))
        .map(|(platform, _)| format!("  {platform}"))
        .collect::<Vec<_>>()
        .join("\n");

    let rakefile_content = format!(
        r#"# frozen_string_literal: true

require "bundler"
Bundler::GemHelper.install_tasks name: "{gem_name_snake}"
require "rb_sys/extensiontask"
require "rspec/core/rake_task"

# Absolute path to the gem package directory, used as the anchor for resolving
# the gemspec and the native extension's Cargo manifest.
GEM_ROOT = __dir__
# Loaded gemspec used by Rake::ExtensionTask to compile the native extension.
GEMSPEC = Gem::Specification.load(File.expand_path("{gem_name_snake}.gemspec", GEM_ROOT))

# Set of supported platform identifiers for native gem cross-compilation.
# Used by `rb_sys/extensiontask` to drive the `rake compile:<platform>` tasks
# that produce platform-specific prebuilt gems published alongside the source
# gem on RubyGems.
CROSS_PLATFORMS = %w[
{cross_platforms}
].freeze

# rb_sys 0.9.x's Cargo::Metadata runs `cargo metadata` without `--manifest-path`,
# so it resolves to whatever workspace contains cwd. In this monorepo the root
# workspace excludes our crate, so the lookup fails with PackageNotFoundError.
# Chdir-around-construction also doesn't work because Rake::ExtensionTask resolves
# its own paths (lib_dir, ext_dir, task wiring) at construction time relative to
# cwd, breaking the compile pipeline. Patch Cargo::Metadata#cargo_metadata to add
# the explicit `--manifest-path` pointing at the crate's Cargo.toml so the lookup
# is unambiguous regardless of cwd.
MANIFEST_PATH = File.expand_path("ext/{ext_name}/native/Cargo.toml", GEM_ROOT)

# @!visibility private
module RbSys
  # @!visibility private
  module Cargo
    # @!visibility private
    class Metadata
      manifest_path = MANIFEST_PATH
      define_method(:cargo_metadata) do
        return @cargo_metadata if @cargo_metadata

        cargo = ENV["CARGO"] || "cargo"
        args = ["metadata", "--format-version", "1", "--manifest-path", manifest_path]
        args << "--no-deps" unless @deps
        out, stderr, status = Open3.capture3(cargo, *args)
        out.force_encoding(Encoding::UTF_8)
        raise "exited with non-zero status (#{{status}})" unless status.success?

        data = JSON.parse(out)
        raise "metadata must be a Hash" unless data.is_a?(Hash)

        @cargo_metadata = data
      rescue StandardError => e
        raise CargoMetadataError.new(e, stderr)
      end
      private :cargo_metadata
    end
  end
end

RbSys::ExtensionTask.new("{cargo_pkg_name}", GEMSPEC) do |ext|
  ext.lib_dir = "lib"
  ext.ext_dir = "ext/{ext_name}/native"
  ext.source_pattern = "*.{{}}"
  ext.platform = "ruby"
  ext.cross_compile = true
  ext.cross_platform = CROSS_PLATFORMS
  # Pin cross_compile_versions to Ruby 3.2-3.5 stable releases.
  # This overrides the container's RUBY_CC_VERSION env var at rake task definition time.
  # The setter was added in a later rb_sys version; guard against older gem installations
  # where the method does not exist (e.g., rb_sys 0.9.127 locked to avoid mingw bug in 0.9.128).
  # rb-sys-dock 0.9.x ships images for Ruby 3.2, 3.3, 3.4, and 3.5; this list must
  # match those available images. Per-ABI platform gem windows are controlled by rake-compiler-dock.
  ext.cross_compile_versions = %w[3.5.0 3.4.9 3.3.11 3.2.11] if ext.respond_to?(:cross_compile_versions=)
end

RSpec::Core::RakeTask.new(:spec)

# rake-compiler's `compile` task is a no-op when cross_compile is true; the real
# work hangs off `compile:<ruby_platform>`. Wire `compile` → `compile:ruby` so
# both the dev shorthand and CI's `bundle exec rake compile` actually build.
task compile: "compile:ruby"

task spec: :compile
task default: :spec
"#,
        gem_name_snake = gem_name_snake,
        cargo_pkg_name = cargo_pkg_name,
        ext_name = ext_name,
        cross_platforms = cross_platforms,
    );

    let extconf_content = format!(
        r#"# frozen_string_literal: true

require "mkmf"
require "rb_sys/mkmf"

default_profile = ENV.fetch("CARGO_PROFILE", "release")

create_rust_makefile("{ext_name}") do |config|
  config.profile = default_profile.to_sym
  # extconf.rb and Cargo.toml are siblings under ext/{ext_name}/native/; rb_sys interprets
  # ext_dir relative to extconf.rb, so "." finds the sibling Cargo.toml. "native" would
  # resolve to native/native/Cargo.toml and break `gem install` on end-user machines.
  config.ext_dir = "."
end
"#,
        ext_name = ext_name,
    );

    Ok(vec![
        GeneratedFile {
            path: PathBuf::from(format!("{pkg_dir}/{}.gemspec", gem_name_snake)),
            content,
            generated_header: true,
        },
        GeneratedFile {
            path: PathBuf::from(format!("{pkg_dir}/.rubocop.yml")),
            content: rubocop_content,
            generated_header: true,
        },
        GeneratedFile {
            path: PathBuf::from(format!("{pkg_dir}/Rakefile")),
            content: rakefile_content,
            generated_header: true,
        },
        GeneratedFile {
            path: PathBuf::from(format!(
                "{pkg_dir}/ext/{ext_name}/native/extconf.rb",
                ext_name = ext_name
            )),
            content: extconf_content,
            generated_header: true,
        },
        GeneratedFile {
            path: PathBuf::from(format!("{pkg_dir}/Gemfile")),
            content: format!(
                r#"# frozen_string_literal: true

source "https://rubygems.org"

gemspec

group :development do
  gem "rake-compiler", "{rake_compiler}"
  gem "rb_sys", {rb_sys}
  gem "rspec", "{rspec}"
  gem "rubocop", "{rubocop}"
  gem "rubocop-performance", "{rubocop_performance}"
  gem "rubocop-rspec", "{rubocop_rspec}"
  gem "steep", "{steep}"
end
"#,
                rake_compiler = tv::gem::RAKE_COMPILER,
                rb_sys = tv::gem::RB_SYS,
                rspec = tv::gem::RSPEC_SCAFFOLD,
                rubocop = tv::gem::RUBOCOP_SCAFFOLD,
                rubocop_performance = tv::gem::RUBOCOP_PERFORMANCE,
                rubocop_rspec = tv::gem::RUBOCOP_RSPEC_SCAFFOLD,
                steep = tv::gem::STEEP,
            ),
            generated_header: false,
        },
        GeneratedFile {
            path: PathBuf::from(format!("{pkg_dir}/Steepfile")),
            content: format!(
                r#"# frozen_string_literal: true

target :lib do
  signature "sig"
  check "lib"
  # The generated `lib/{gem_name_snake}/native.rb` carries inline Sorbet
  # `sig {{ ... }}` blocks on tagged-enum variant Data classes. Sorbet's runtime
  # provides those via `extend T::Sig`, but Steep does not understand the
  # extension (it relies on RBS, not Sorbet sigs) and reports
  # `Type `self` does not have method `sig`` on every block. RBS coverage
  # for the same surface lives in `sig/types.rbs`, so we steer Steep to the
  # RBS file by ignoring the .rb.
  ignore "lib/{gem_name_snake}/native.rb"
end
"#,
                gem_name_snake = gem_name_snake,
            ),
            generated_header: false,
        },
        // Appended last, deliberately: `test_scaffold_ruby_production_features` in
        // `src/scaffold/tests/ffi_go_java_ruby.rs` asserts this vec's entries by index, so
        // inserting the seed next to the `Rakefile` it belongs with would renumber every
        // later assertion. Appending still shifts one: the `Language::Ruby` scaffold arm
        // extends `scaffold_ruby_cargo`'s manifest onto the tail, so that manifest moves from
        // index 6 to 7 while every entry before the seed keeps its position.
        //
        // The `Rakefile` above unconditionally wires `RSpec::Core::RakeTask.new(:spec)` and
        // `task default: :spec`, so `rake` has always *run* a spec suite — against a `spec/`
        // directory nothing ever created. `rake spec` over an empty suite exits 0, so the
        // lane reported green while proving nothing; this seeds one real example so the
        // wiring has something to execute from day one. ~keep
        GeneratedFile {
            path: PathBuf::from(format!("{pkg_dir}/spec/{gem_name_snake}_spec.rb")),
            content: scaffold_ruby_spec(api, config, &gem_name_snake),
            generated_header: false,
        },
    ])
}

/// Literal value the seed passes for a String field, and asserts back out of the accessor.
const RUBY_SEED_STRING_LITERAL: &str = "alef-scaffold";

/// Build the seed content for `{pkg_dir}/spec/{gem_name_snake}_spec.rb`.
///
/// `write_scaffold_files_report` skips any `generated_header: false` path that already
/// exists (`can_skip`), so this only ever seeds a fresh project and never overwrites a real
/// suite. Because the path is *new*, existing repos pick the seed up with no migration at all
/// — unlike the zig/dart/swift seeds, whose files already existed with the wrong content and
/// each needed an in-place repair pass to reach a repo that had already been generated once.
///
/// "Pick it up" means the next run of a command that actually writes scaffold output: `alef
/// scaffold`, `alef all`, or `alef init`. Plain `alef generate` does not — it calls
/// `pipeline::scaffold` only to feed `reconcile_managed_scaffold_manifests`, which filters the
/// set down to `generated_header: true` `.toml` manifests and drops every seed on the floor.
/// That is pre-existing behaviour for every scaffold seed, not something this path introduces,
/// but it is the difference between "next generate" and "next scaffold" and is worth knowing
/// before wondering why the file has not appeared. ~keep
///
/// The seed must not be vacuous: `expect(1).to eq(1)` passes no matter what alef generated,
/// which is strictly worse than an empty lane because it manufactures confidence. Every tier
/// below therefore asserts against the *real*, currently-generated API surface, and every
/// tier — including the weakest — goes through `require_relative "../lib/<gem>"`, which loads
/// `lib/<gem>/native.rb`; that file raises `LoadError` when the compiled extension is absent.
/// So no tier can pass without the native extension actually being built and dlopened. That
/// is the deliberate difference from `scaffold_zig_test`'s `@hasDecl` tier, which is
/// comptime-only and therefore never links or invokes anything (alef task #85).
///
/// Tiers, strongest first:
///
/// 1. A visible zero-parameter, non-async function with a primitive/`String` return whose
///    generated wrapper really delegates to the core crate is actually **called** through the
///    Magnus boundary and its result type-checked; an infallible one is preferred over a
///    fallible one. Proves: extension links, the module function is registered under that
///    name, and its return value converts to the mapped Ruby type. Does not prove: anything
///    about the value's semantics — the seed cannot know what the function should return.
/// 2. Otherwise a visible DTO whose every binding-visible field is a plain
///    primitive/`String` is **constructed** through the generated kwargs constructor and
///    every field read back through its generated accessor. Proves: the class is registered,
///    the constructor accepts those keyword symbols, and each accessor round-trips the value
///    it was given (a renamed or dropped field fails, because the constructor silently
///    ignores unknown keys and the accessor would return the default instead). Does not
///    prove: any behaviour beyond field storage.
/// 3. Otherwise a visible type name is resolved as a constant on the module. Proves: the
///    extension loaded and registered that class. Does not prove: its shape or that anything
///    can be called on it.
/// 4. Only when no visible function or type exists at all (scaffolding before any Rust code)
///    does this fall back to asserting `VERSION` — always emitted by `generate_public_api` —
///    has a version-like shape. Proves: the gem and the native extension both load. Does not
///    prove: any generated API exists, because at this point none does.
///
/// Enums are deliberately absent from the ladder: the Magnus backend does not register them
/// as Ruby constants (see the note above `public_types` in `MagnusBackend::generate_public_api`),
/// so a `{module_name}::SomeEnum` reference would name something that does not exist. ~keep
fn scaffold_ruby_spec(api: &ApiSurface, config: &ResolvedCrateConfig, gem_name_snake: &str) -> String {
    use heck::ToUpperCamelCase as _;

    // `get_module_name(&config.ruby_gem_name())` in `MagnusBackend::generate_public_api` — the
    // module the generated `lib/<gem>.rb` opens and the native extension registers into. ~keep
    let module_name = config.ruby_gem_name().to_upper_camel_case();
    let (exclude_functions, exclude_types) = ruby_binding_exclusions(api, config);

    let call_candidates: Vec<(&FunctionDef, &'static str)> = api
        .functions
        .iter()
        .filter(|f| ruby_function_is_callable_seed_target(f, config, &exclude_functions))
        .filter_map(|f| ruby_return_expectation(&f.return_type).map(|expectation| (f, expectation)))
        .collect();
    // Infallible first: a fallible function's generated wrapper propagates a core `Err` as a
    // raised Ruby exception, and a function that legitimately fails in a clean checkout (no
    // network, no model downloaded, no GPU) would make the seed permanently red on a healthy
    // build — a false alarm is only marginally better than the vacuous pass this replaces. A
    // fallible function is still used when it is the only candidate: an example that can fail
    // for a real reason beats degrading to a weaker tier. ~keep
    let call_candidate = call_candidates
        .iter()
        .find(|(f, _)| f.error_type.is_none())
        .or_else(|| call_candidates.first())
        .copied();
    if let Some((f, expectation)) = call_candidate {
        return ruby_spec(gem_name_snake, &module_name, &ruby_call_example(&f.name, expectation));
    }

    let construct_candidate = api
        .types
        .iter()
        .filter(|t| ruby_type_is_visible(t, &exclude_types))
        .find_map(|t| simple_ruby_fields(t).map(|fields| (t, fields)));
    if let Some((ty, fields)) = construct_candidate {
        return ruby_spec(gem_name_snake, &module_name, &ruby_construct_example(&ty.name, &fields));
    }

    if let Some(ty) = api.types.iter().find(|t| ruby_type_is_visible(t, &exclude_types)) {
        return ruby_spec(gem_name_snake, &module_name, &ruby_constant_example(&ty.name));
    }

    ruby_spec(gem_name_snake, &module_name, &ruby_version_example())
}

/// Names excluded from Ruby binding generation, mirroring the union `MagnusBackend` itself
/// computes (`src/backends/magnus/gen_bindings/mod.rs`): `[crates.ruby] exclude_functions` /
/// `exclude_types`, plus any type marked `binding_excluded`. Unlike the zig and dart seeds
/// this deliberately does **not** fold in `[crates.ffi]`'s lists — the Magnus backend reads
/// only `config.ruby`, and mirroring an exclusion it does not honour would make the seed skip
/// a name that really is emitted. `is_reserved_fn` is not mirrored either: its backing list
/// (`MAGNUS_RESERVED_FN_NAMES`) is currently empty, so mirroring it would be dead code.
fn ruby_binding_exclusions(api: &ApiSurface, config: &ResolvedCrateConfig) -> (HashSet<String>, HashSet<String>) {
    let exclude_functions: HashSet<String> = config
        .ruby
        .as_ref()
        .map(|c| c.exclude_functions.iter().cloned().collect())
        .unwrap_or_default();
    let mut exclude_types: HashSet<String> = config
        .ruby
        .as_ref()
        .map(|c| c.exclude_types.iter().cloned().collect())
        .unwrap_or_default();
    exclude_types.extend(api.types.iter().filter(|t| t.binding_excluded).map(|t| t.name.clone()));
    (exclude_functions, exclude_types)
}

/// A type the seed may safely name, mirroring the `public_types` filter in
/// `MagnusBackend::generate_public_api` — that curated list is what a gem whose module name
/// differs from its crate name re-exports, so anything outside it may be absent from the
/// module the spec describes. `cfg`-gated types are additionally skipped: the Magnus backend
/// prepends `#[cfg(...)]` to them, so whether they are registered depends on which features
/// the extension was compiled with, which this scaffold-time seed cannot know.
fn ruby_type_is_visible(ty: &TypeDef, exclude_types: &HashSet<String>) -> bool {
    !ty.is_trait
        && !ty.is_opaque
        && !ty.binding_excluded
        && ty.cfg.is_none()
        && !exclude_types.contains(&ty.name)
        && !ty.name.ends_with("Update")
        && !ty.name.ends_with("Builder")
}

/// Whether `f` is safe for the strongest tier: a zero-argument, non-async, non-`cfg`-gated
/// function the seed can call with no knowledge of any parameter's ownership or conversion
/// requirements. The return type is checked separately by the caller, via
/// [`ruby_return_expectation`].
///
/// Async functions are excluded even when they take no arguments: Magnus registers them under
/// a different Rust body (`ruby_native_function_name` appends `_async`) that drives a Tokio
/// runtime, which is not something a scaffold seed should be the first thing to exercise.
/// Trait-bridge-managed functions are excluded because `module_init` skips registering them
/// outright. Functions whose Ruby-visible name (`ruby_public_function_name`, the leaf of
/// `original_rust_path`) differs from `name` are excluded too: the native extension registers
/// the leaf while `generate_public_api`'s re-export list uses `name`, so only functions where
/// the two agree are reachable under one name in both layouts.
///
/// The delegability check is the load-bearing one, not a formality. When
/// [`crate::codegen::shared::can_auto_delegate_function`] is false, the Magnus wrapper
/// generator (`gen_magnus_unimplemented_body`) emits a body that *raises* `RuntimeError:
/// Not implemented: <name>` for a fallible function — the symbol is registered and callable,
/// so nothing here would notice, and the seed would be permanently red on a perfectly healthy
/// build. Passing an empty opaque-type set is exact rather than approximate: every remaining
/// term of that predicate ranges over `params`, which this function has already constrained to
/// be empty, leaving only `!sanitized` and the return type. ~keep
fn ruby_function_is_callable_seed_target(
    f: &FunctionDef,
    config: &ResolvedCrateConfig,
    exclude_functions: &HashSet<String>,
) -> bool {
    !f.binding_excluded
        && !exclude_functions.contains(&f.name)
        && f.cfg.is_none()
        && !f.is_async
        && f.params.is_empty()
        && !f.return_sanitized
        && crate::codegen::shared::can_auto_delegate_function(f, &ahash::AHashSet::default())
        && crate::backends::magnus::ruby_public_function_name(f) == f.name
        && !crate::codegen::generators::trait_bridge::is_trait_bridge_managed_fn(&f.name, &config.trait_bridges)
}

/// The RSpec matcher asserting that a returned value has the Ruby type the Magnus type map
/// produces for `ty`, or `None` when the return type is not one this seed can type-check.
fn ruby_return_expectation(ty: &TypeRef) -> Option<&'static str> {
    match ty {
        TypeRef::String => Some("be_a(String)"),
        TypeRef::Primitive(primitive) => Some(ruby_primitive_expectation(primitive)),
        _ => None,
    }
}

fn ruby_primitive_expectation(primitive: &PrimitiveType) -> &'static str {
    match primitive {
        PrimitiveType::Bool => "be(true).or(be(false))",
        PrimitiveType::F32 | PrimitiveType::F64 => "be_a(Float)",
        _ => "be_a(Integer)",
    }
}

/// A field simple enough for the seed to both pass as a constructor keyword and assert back
/// out of its accessor.
struct SimpleRubyField {
    name: String,
    literal: String,
}

/// Compute a literal-constructible field list for `ty`, or `None` when any binding-visible
/// field falls outside the safely synthesizable subset. Bails on the *whole type* rather than
/// constructing it partially: a `Named` field with no default makes the generated constructor
/// raise `ArgumentError`, so a partial construction would fail at runtime rather than assert
/// anything.
///
/// Rejected: optional fields (the accessor returns `nil` semantics this seed would have to
/// model), `cfg`-gated fields, `binding_excluded` fields (dropped from the generated struct),
/// and anything whose name is not plain snake_case — the Ruby accessor and the constructor's
/// keyword symbol are both the raw Rust field name, so a positional name like `_0` would
/// produce an example naming a method that reads nothing.
fn simple_ruby_fields(ty: &TypeDef) -> Option<Vec<SimpleRubyField>> {
    if ty.has_stripped_cfg_fields {
        return None;
    }
    let mut fields = Vec::new();
    for field in crate::codegen::shared::binding_fields(&ty.fields) {
        if field.optional || field.cfg.is_some() || !is_plain_ruby_field_name(field) {
            return None;
        }
        let literal = match &field.ty {
            TypeRef::Primitive(primitive) => ruby_primitive_literal(primitive).to_string(),
            TypeRef::String => format!("\"{RUBY_SEED_STRING_LITERAL}\""),
            _ => return None,
        };
        fields.push(SimpleRubyField {
            name: field.name.clone(),
            literal,
        });
    }
    if fields.is_empty() { None } else { Some(fields) }
}

fn is_plain_ruby_field_name(field: &FieldDef) -> bool {
    let mut chars = field.name.chars();
    chars.next().is_some_and(|c| c.is_ascii_lowercase())
        && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}

/// A literal Ruby value for a primitive field. `bool` gets a non-default `true` and floats a
/// non-integral `1.5` so a constructor that silently drops the keyword and falls back to the
/// field's default is still caught by the accessor assertion.
fn ruby_primitive_literal(primitive: &PrimitiveType) -> &'static str {
    match primitive {
        PrimitiveType::Bool => "true",
        PrimitiveType::F32 | PrimitiveType::F64 => "1.5",
        _ => "1",
    }
}

/// Wrap one generated example in the spec file's frame. `require_relative` (rather than
/// `require`) is deliberate: it resolves against the package directory, so `rake spec` works
/// straight out of a fresh scaffold without a `spec_helper.rb` or a `$LOAD_PATH` entry.
fn ruby_spec(gem_name_snake: &str, module_name: &str, example: &str) -> String {
    format!(
        r#"# frozen_string_literal: true

require_relative "../lib/{gem_name_snake}"

RSpec.describe {module_name} do
{example}end
"#
    )
}

fn ruby_call_example(function_name: &str, expectation: &str) -> String {
    format!(
        r#"  # Calls the generated `{function_name}` module function end-to-end. The
  # `require_relative` above loads the gem, whose `native.rb` dlopens the compiled
  # extension and raises LoadError when it is missing, so this example crosses the real
  # Magnus boundary: it fails on an unbuilt extension, a link error, or a removed or
  # renamed export. It does not assert *what* the value should be -- only that the
  # binding returns a value of the mapped Ruby type. Create-only scaffold seed: alef never
  # regenerates over this file, so replace it with a real suite. ~keep
  it "calls the generated `{function_name}` module function" do
    expect(described_class.{function_name}).to({expectation})
  end
"#
    )
}

fn ruby_construct_example(type_name: &str, fields: &[SimpleRubyField]) -> String {
    let kwargs = fields
        .iter()
        .map(|f| format!("{}: {}", f.name, f.literal))
        .collect::<Vec<_>>()
        .join(", ");
    let assertion = if let [only] = fields {
        format!(
            "    expect(instance.{name}).to(eq({literal}))",
            name = only.name,
            literal = only.literal
        )
    } else {
        // One expectation over every field rather than one per field: the generated
        // `.rubocop.yml` caps `RSpec/MultipleExpectations` at 25, and a DTO can carry more
        // fields than that. ~keep
        let readers = fields
            .iter()
            .map(|f| format!("instance.{}", f.name))
            .collect::<Vec<_>>()
            .join(", ");
        let literals = fields.iter().map(|f| f.literal.clone()).collect::<Vec<_>>().join(", ");
        format!("    expect([{readers}]).to(eq([{literals}]))")
    };
    format!(
        r#"  # No generated function is safe to call with no arguments, so this exercises the
  # binding through the generated `{type_name}` class instead: the `require_relative`
  # above dlopens the compiled extension (LoadError when missing), the keyword
  # constructor registered by Magnus is invoked, and every field is read back through its
  # generated accessor. A dropped or renamed field fails here, because the constructor
  # ignores unknown keys and the accessor would return the field's default instead of the
  # value passed in. It proves nothing beyond field storage. Create-only scaffold seed:
  # alef never regenerates over this file, so replace it with a real suite. ~keep
  it "constructs the generated `{type_name}` class from keyword arguments" do
    instance = described_class::{type_name}.new({kwargs})
{assertion}
  end
"#
    )
}

fn ruby_constant_example(type_name: &str) -> String {
    format!(
        r#"  # `{type_name}` is not literal-constructible by a seed that cannot synthesize values
  # for its fields, so this only resolves it as a constant on the module. The
  # `require_relative` above still dlopens the compiled extension (LoadError when
  # missing) and the constant only exists because the extension registered the class, so
  # this fails on an unbuilt extension or a removed type -- but it proves nothing about
  # the class's shape and calls nothing on it. Create-only scaffold seed: alef never
  # regenerates over this file, so replace it with a real suite. ~keep
  it "registers the generated `{type_name}` class on the module" do
    expect(described_class.const_get(:{type_name})).to(be_a(Module))
  end
"#
    )
}

fn ruby_version_example() -> String {
    r#"  # No generated API surface exists yet for this crate, so there is nothing to assert
  # against beyond the gem loading. `VERSION` is emitted unconditionally by alef, and the
  # `require_relative` above pulls in `native.rb`, which raises LoadError when the compiled
  # extension is missing -- so this still fails on an unbuilt or unlinkable extension. It
  # proves no generated API exists, because at this point none does. The version is matched
  # by shape, not value, because this file is a create-only scaffold seed alef never
  # regenerates over -- pinning the exact version would break on the next release. ~keep
  it "loads the native extension and exposes a version" do
    expect(described_class::VERSION).to match(/\A\d+\.\d+\.\d+/)
  end
"#
    .to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::config::NewAlefConfig;

    fn resolve_config(toml_text: &str) -> ResolvedCrateConfig {
        let cfg: NewAlefConfig = toml::from_str(toml_text).expect("valid config");
        cfg.resolve().expect("resolve").remove(0)
    }

    fn minimal_config() -> ResolvedCrateConfig {
        resolve_config(
            r#"
[workspace]
languages = ["ruby"]
[[crates]]
name = "my-lib"
sources = []
"#,
        )
    }

    fn zero_arg_function(name: &str, return_type: TypeRef) -> FunctionDef {
        FunctionDef {
            name: name.to_string(),
            return_type,
            ..Default::default()
        }
    }

    fn simple_field(name: &str, ty: TypeRef) -> FieldDef {
        FieldDef {
            name: name.to_string(),
            ty,
            ..Default::default()
        }
    }

    fn dto(name: &str, fields: Vec<FieldDef>) -> TypeDef {
        TypeDef {
            name: name.to_string(),
            fields,
            ..Default::default()
        }
    }

    /// The strongest tier: a visible zero-arg, primitive-returning function is actually
    /// invoked across the Magnus boundary, not merely named.
    #[test]
    fn calls_a_visible_zero_argument_function() {
        let api = ApiSurface {
            functions: vec![zero_arg_function("ping", TypeRef::Primitive(PrimitiveType::Bool))],
            ..Default::default()
        };
        let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

        assert!(out.starts_with("# frozen_string_literal: true\n"), "got:\n{out}");
        assert!(out.contains("require_relative \"../lib/my_lib\"\n"), "got:\n{out}");
        assert!(out.contains("RSpec.describe MyLib do\n"), "got:\n{out}");
        assert!(
            out.contains("    expect(described_class.ping).to(be(true).or(be(false)))\n"),
            "got:\n{out}"
        );
    }

    /// The matcher must follow the Magnus type map, not a generic truthiness check.
    #[test]
    fn matches_the_returned_ruby_type_for_each_return_kind() {
        let cases = [
            (TypeRef::String, "expect(described_class.probe).to(be_a(String))"),
            (
                TypeRef::Primitive(PrimitiveType::U64),
                "expect(described_class.probe).to(be_a(Integer))",
            ),
            (
                TypeRef::Primitive(PrimitiveType::F64),
                "expect(described_class.probe).to(be_a(Float))",
            ),
        ];
        for (return_type, expected) in cases {
            let api = ApiSurface {
                functions: vec![zero_arg_function("probe", return_type)],
                ..Default::default()
            };
            let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");
            assert!(out.contains(expected), "expected `{expected}`, got:\n{out}");
        }
    }

    /// A function taking parameters cannot be called generically (unknown ownership and
    /// conversion needs per parameter), so the ladder must degrade instead of guessing.
    #[test]
    fn skips_functions_that_take_parameters() {
        let api = ApiSurface {
            functions: vec![FunctionDef {
                params: vec![crate::core::ir::ParamDef {
                    name: "input".to_string(),
                    ty: TypeRef::String,
                    ..Default::default()
                }],
                ..zero_arg_function("greet", TypeRef::String)
            }],
            types: vec![dto("Widget", vec![simple_field("label", TypeRef::String)])],
            ..Default::default()
        };
        let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

        assert!(!out.contains("greet"), "got:\n{out}");
        assert!(
            out.contains("described_class::Widget.new(label: \"alef-scaffold\")"),
            "got:\n{out}"
        );
    }

    /// Async functions run through a Tokio runtime under a differently-named Rust body; the
    /// seed must not be the first thing to exercise that path.
    #[test]
    fn skips_async_functions() {
        let api = ApiSurface {
            functions: vec![FunctionDef {
                is_async: true,
                ..zero_arg_function("fetch", TypeRef::String)
            }],
            ..Default::default()
        };
        let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

        assert!(!out.contains("fetch"), "got:\n{out}");
        assert!(out.contains("described_class::VERSION"), "got:\n{out}");
    }

    /// A `cfg`-gated function is registered only when the extension was compiled with that
    /// feature, which a scaffold-time seed cannot know.
    #[test]
    fn skips_cfg_gated_functions() {
        let api = ApiSurface {
            functions: vec![FunctionDef {
                cfg: Some("feature = \"extra\"".to_string()),
                ..zero_arg_function("extra_ping", TypeRef::String)
            }],
            ..Default::default()
        };
        let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

        assert!(!out.contains("extra_ping"), "got:\n{out}");
    }

    /// A function the Magnus wrapper generator cannot delegate gets an `unimplemented` body
    /// that raises `RuntimeError` when called. It is still registered and callable, so only
    /// this predicate keeps the seed off it — otherwise the example would be permanently red
    /// on a healthy build.
    #[test]
    fn skips_functions_whose_generated_body_only_raises() {
        let api = ApiSurface {
            functions: vec![FunctionDef {
                sanitized: true,
                error_type: Some("Error".to_string()),
                ..zero_arg_function("not_delegatable", TypeRef::String)
            }],
            types: vec![dto("Widget", vec![simple_field("label", TypeRef::String)])],
            ..Default::default()
        };
        let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

        assert!(!out.contains("not_delegatable"), "got:\n{out}");
        assert!(
            out.contains("described_class::Widget.new(label: \"alef-scaffold\")"),
            "got:\n{out}"
        );
    }

    /// A fallible function can raise for reasons that have nothing to do with the binding, so
    /// an infallible candidate wins even when it appears later in the surface.
    #[test]
    fn prefers_an_infallible_function_over_a_fallible_one() {
        let api = ApiSurface {
            functions: vec![
                FunctionDef {
                    error_type: Some("Error".to_string()),
                    ..zero_arg_function("might_fail", TypeRef::String)
                },
                zero_arg_function("always_works", TypeRef::String),
            ],
            ..Default::default()
        };
        let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

        assert!(
            out.contains("    expect(described_class.always_works).to(be_a(String))\n"),
            "got:\n{out}"
        );
        assert!(!out.contains("might_fail"), "got:\n{out}");
    }

    /// When every candidate is fallible the strongest tier still fires: an example that can
    /// fail for a real reason is worth more than degrading to a weaker one.
    #[test]
    fn still_calls_a_fallible_function_when_it_is_the_only_candidate() {
        let api = ApiSurface {
            functions: vec![FunctionDef {
                error_type: Some("Error".to_string()),
                ..zero_arg_function("might_fail", TypeRef::String)
            }],
            ..Default::default()
        };
        let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

        assert!(
            out.contains("    expect(described_class.might_fail).to(be_a(String))\n"),
            "got:\n{out}"
        );
    }

    /// `binding_excluded` functions never reach the generated extension, so the seed must not
    /// call one.
    #[test]
    fn skips_binding_excluded_functions() {
        let api = ApiSurface {
            functions: vec![
                FunctionDef {
                    binding_excluded: true,
                    ..zero_arg_function("hidden", TypeRef::String)
                },
                zero_arg_function("visible", TypeRef::String),
            ],
            ..Default::default()
        };
        let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

        assert!(out.contains("described_class.visible"), "got:\n{out}");
        assert!(!out.contains("hidden"), "got:\n{out}");
    }

    /// `[crates.ruby] exclude_functions` mirrors `MagnusBackend`'s own filter, so a function
    /// excluded there must be skipped here too.
    #[test]
    fn skips_functions_excluded_via_ruby_config() {
        let config = resolve_config(
            r#"
[workspace]
languages = ["ruby"]
[[crates]]
name = "my-lib"
sources = []

[crates.ruby]
exclude_functions = ["ping"]
"#,
        );
        let api = ApiSurface {
            functions: vec![zero_arg_function("ping", TypeRef::String)],
            ..Default::default()
        };
        let out = scaffold_ruby_spec(&api, &config, "my_lib");

        assert!(
            !out.contains("ping"),
            "excluded function must not be referenced, got:\n{out}"
        );
        assert!(out.contains("described_class::VERSION"), "got:\n{out}");
    }

    /// With no callable function, a literal-constructible DTO is built through the generated
    /// keyword constructor and every field read back through its accessor.
    #[test]
    fn constructs_a_simple_dto_and_asserts_every_field() {
        let api = ApiSurface {
            types: vec![dto(
                "Widget",
                vec![
                    simple_field("label", TypeRef::String),
                    simple_field("count", TypeRef::Primitive(PrimitiveType::U32)),
                ],
            )],
            ..Default::default()
        };
        let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

        assert!(
            out.contains("    instance = described_class::Widget.new(label: \"alef-scaffold\", count: 1)\n"),
            "got:\n{out}"
        );
        assert!(
            out.contains("    expect([instance.label, instance.count]).to(eq([\"alef-scaffold\", 1]))\n"),
            "got:\n{out}"
        );
    }

    /// A single-field DTO reads better as a scalar comparison than a one-element array.
    #[test]
    fn asserts_a_single_field_dto_without_an_array() {
        let api = ApiSurface {
            types: vec![dto("Widget", vec![simple_field("label", TypeRef::String)])],
            ..Default::default()
        };
        let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

        assert!(
            out.contains("    expect(instance.label).to(eq(\"alef-scaffold\"))\n"),
            "got:\n{out}"
        );
    }

    /// A `Named` field has no default in the generated constructor, so a partial construction
    /// would raise `ArgumentError`. The whole type is rejected rather than partly built.
    #[test]
    fn falls_back_to_a_constant_reference_for_a_dto_with_a_named_field() {
        let api = ApiSurface {
            types: vec![dto(
                "Widget",
                vec![
                    simple_field("label", TypeRef::String),
                    simple_field("nested", TypeRef::Named("Other".to_string())),
                ],
            )],
            ..Default::default()
        };
        let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

        assert!(!out.contains(".new("), "got:\n{out}");
        assert!(
            out.contains("    expect(described_class.const_get(:Widget)).to(be_a(Module))\n"),
            "got:\n{out}"
        );
    }

    /// Optional fields carry `nil` semantics this seed does not model, so they disqualify the
    /// construction tier rather than being guessed at.
    #[test]
    fn falls_back_to_a_constant_reference_for_a_dto_with_an_optional_field() {
        let api = ApiSurface {
            types: vec![dto(
                "Widget",
                vec![FieldDef {
                    optional: true,
                    ..simple_field("label", TypeRef::String)
                }],
            )],
            ..Default::default()
        };
        let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

        assert!(!out.contains(".new("), "got:\n{out}");
        assert!(out.contains("const_get(:Widget)"), "got:\n{out}");
    }

    /// `[crates.ruby] exclude_types` and `binding_excluded` both remove a class from the
    /// generated extension, so neither may be named by the seed.
    #[test]
    fn skips_types_excluded_by_config_or_binding_exclusion() {
        let config = resolve_config(
            r#"
[workspace]
languages = ["ruby"]
[[crates]]
name = "my-lib"
sources = []

[crates.ruby]
exclude_types = ["Excluded"]
"#,
        );
        let api = ApiSurface {
            types: vec![
                dto("Excluded", vec![simple_field("label", TypeRef::String)]),
                TypeDef {
                    binding_excluded: true,
                    ..dto("Hidden", vec![simple_field("label", TypeRef::String)])
                },
                dto("Visible", vec![simple_field("label", TypeRef::String)]),
            ],
            ..Default::default()
        };
        let out = scaffold_ruby_spec(&api, &config, "my_lib");

        assert!(!out.contains("Excluded"), "got:\n{out}");
        assert!(!out.contains("Hidden"), "got:\n{out}");
        assert!(out.contains("described_class::Visible.new("), "got:\n{out}");
    }

    /// `MagnusBackend::generate_public_api` drops `*Update` and `*Builder` types from the
    /// module's curated re-export list, so a seed naming one may reference nothing.
    #[test]
    fn skips_update_and_builder_types() {
        let api = ApiSurface {
            types: vec![
                dto("WidgetUpdate", vec![simple_field("label", TypeRef::String)]),
                dto("WidgetBuilder", vec![simple_field("label", TypeRef::String)]),
            ],
            ..Default::default()
        };
        let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

        assert!(!out.contains("WidgetUpdate"), "got:\n{out}");
        assert!(!out.contains("WidgetBuilder"), "got:\n{out}");
        assert!(out.contains("described_class::VERSION"), "got:\n{out}");
    }

    /// Enums are not registered as Ruby constants by the Magnus backend, so an enum-only
    /// surface must degrade to the version tier rather than name a constant that is absent.
    #[test]
    fn never_names_an_enum_because_magnus_registers_none_as_constants() {
        let api = ApiSurface {
            enums: vec![crate::core::ir::EnumDef {
                name: "Colour".to_string(),
                ..Default::default()
            }],
            ..Default::default()
        };
        let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

        assert!(!out.contains("Colour"), "got:\n{out}");
        assert!(out.contains("described_class::VERSION"), "got:\n{out}");
    }

    /// An empty API surface still gets a falsifiable example: `VERSION` only resolves once the
    /// gem — and therefore the native extension `native.rb` dlopens — has loaded.
    #[test]
    fn falls_back_to_the_version_assertion_when_the_api_surface_is_empty() {
        let out = scaffold_ruby_spec(&ApiSurface::default(), &minimal_config(), "my_lib");

        assert!(
            out.contains("    expect(described_class::VERSION).to match(/\\A\\d+\\.\\d+\\.\\d+/)\n"),
            "got:\n{out}"
        );
    }

    /// No tier may emit a tautology, and every tier must go through the `require_relative`
    /// that dlopens the native extension — that is the property making even the weakest tier
    /// falsifiable rather than decorative.
    #[test]
    fn no_tier_emits_a_vacuous_or_unlinked_example() {
        let surfaces = [
            ApiSurface {
                functions: vec![zero_arg_function("ping", TypeRef::String)],
                ..Default::default()
            },
            ApiSurface {
                types: vec![dto("Widget", vec![simple_field("label", TypeRef::String)])],
                ..Default::default()
            },
            ApiSurface {
                types: vec![dto(
                    "Widget",
                    vec![simple_field("nested", TypeRef::Named("Other".to_string()))],
                )],
                ..Default::default()
            },
            ApiSurface::default(),
        ];
        for api in surfaces {
            let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");
            assert!(
                out.contains("require_relative \"../lib/my_lib\""),
                "every tier must load the gem, got:\n{out}"
            );
            assert_eq!(out.matches("  it \"").count(), 1, "exactly one example, got:\n{out}");
            for tautology in ["expect(1)", "eq(1 + 1)", "to be_truthy", "to be_falsey"] {
                assert!(!out.contains(tautology), "vacuous assertion `{tautology}` in:\n{out}");
            }
            assert!(
                out.contains("described_class"),
                "the example must assert against the generated module, got:\n{out}"
            );
        }
    }

    /// The seed carries no alef header marker, and must not: the marker is what
    /// `write_scaffold_files_report`'s ownership guard reads as "alef owns this file", which
    /// would let an `overwrite: true` run (e.g. `alef version`) replace a hand-written suite.
    #[test]
    fn seed_content_carries_no_alef_marker() {
        let out = scaffold_ruby_spec(&ApiSurface::default(), &minimal_config(), "my_lib");

        assert!(
            !crate::core::hash::content_has_alef_marker(&out),
            "seed must stay unmarked so it is never reclaimed by an overwrite run, got:\n{out}"
        );
    }

    /// The seed lands at the path the generated `Rakefile`'s `RSpec::Core::RakeTask` already
    /// scans, and is emitted create-only so a real suite is never overwritten.
    #[test]
    fn seed_is_emitted_create_only_at_the_rspec_default_path() {
        let config = minimal_config();
        let api = ApiSurface {
            version: "1.2.3".to_string(),
            ..Default::default()
        };
        let files = scaffold_ruby(&api, &config).expect("scaffold");
        let spec = files
            .iter()
            .find(|f| f.path.to_string_lossy().contains("/spec/"))
            .expect("a spec seed must be emitted");

        assert_eq!(spec.path.to_string_lossy(), "packages/ruby/spec/my_lib_spec.rb");
        assert!(!spec.generated_header, "the seed must stay create-only");
    }

    /// The `~keep` in this seed's rationale is load-bearing, unlike the markers the
    /// render-time strip (`core::keep_marker`) removes from `.jinja` output. The seed is
    /// create-only, so alef never rewrites it and the consumer's own `poly` uncomment pass is
    /// what reads it — without the marker the rationale is deleted by the next `poly fmt`.
    /// Pinned across every tier so a broadening of the strip cannot silently take it. ~keep
    #[test]
    fn every_seed_tier_keeps_its_uncomment_pass_marker() {
        let config = minimal_config();
        let tiers = [
            (
                "call",
                ApiSurface {
                    functions: vec![zero_arg_function("ping", TypeRef::Primitive(PrimitiveType::Bool))],
                    ..Default::default()
                },
            ),
            (
                "construct",
                ApiSurface {
                    types: vec![dto("Widget", vec![simple_field("label", TypeRef::String)])],
                    ..Default::default()
                },
            ),
            (
                "constant",
                ApiSurface {
                    types: vec![dto(
                        "Widget",
                        vec![
                            simple_field("label", TypeRef::String),
                            simple_field("nested", TypeRef::Named("Other".to_string())),
                        ],
                    )],
                    ..Default::default()
                },
            ),
            ("version", ApiSurface::default()),
        ];

        for (tier, api) in tiers {
            let out = scaffold_ruby_spec(&api, &config, "my_lib");
            assert!(
                out.contains("replace it with a real suite. ~keep") || out.contains("break on the next release. ~keep"),
                "the {tier} tier lost its uncomment-pass marker, got:\n{out}"
            );
        }
    }
}