Skip to main content

alef_e2e/codegen/
ruby.rs

1//! Ruby e2e test generator using RSpec.
2//!
3//! Generates `e2e/ruby/Gemfile` and `spec/{category}_spec.rb` files from
4//! JSON fixtures, driven entirely by `E2eConfig` and `CallConfig`.
5
6use crate::codegen::resolve_field;
7use crate::config::E2eConfig;
8use crate::escape::{ruby_string_literal, ruby_template_to_interpolation, sanitize_filename, sanitize_ident};
9use crate::field_access::FieldResolver;
10use crate::fixture::{Assertion, CallbackAction, Fixture, FixtureGroup, ValidationErrorExpectation};
11use alef_core::backend::GeneratedFile;
12use alef_core::config::ResolvedCrateConfig;
13use alef_core::hash::{self, CommentStyle};
14use alef_core::template_versions as tv;
15use anyhow::Result;
16use heck::ToSnakeCase;
17use std::collections::HashMap;
18use std::fmt::Write as FmtWrite;
19use std::path::PathBuf;
20
21use super::E2eCodegen;
22use super::client;
23
24/// Ruby e2e code generator.
25pub struct RubyCodegen;
26
27impl E2eCodegen for RubyCodegen {
28    fn generate(
29        &self,
30        groups: &[FixtureGroup],
31        e2e_config: &E2eConfig,
32        config: &ResolvedCrateConfig,
33        _type_defs: &[alef_core::ir::TypeDef],
34    ) -> Result<Vec<GeneratedFile>> {
35        let lang = self.language_name();
36        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
37
38        let mut files = Vec::new();
39
40        // Resolve call config with overrides.
41        let call = &e2e_config.call;
42        let overrides = call.overrides.get(lang);
43        let module_path = overrides
44            .and_then(|o| o.module.as_ref())
45            .cloned()
46            .unwrap_or_else(|| call.module.clone());
47        let class_name = overrides.and_then(|o| o.class.as_ref()).cloned();
48        let options_type = overrides.and_then(|o| o.options_type.clone());
49        let empty_enum_fields = HashMap::new();
50        let enum_fields = overrides.map(|o| &o.enum_fields).unwrap_or(&empty_enum_fields);
51        let result_is_simple = call.result_is_simple || overrides.is_some_and(|o| o.result_is_simple);
52
53        // Resolve package config.
54        let ruby_pkg = e2e_config.resolve_package("ruby");
55        let gem_name = ruby_pkg
56            .as_ref()
57            .and_then(|p| p.name.as_ref())
58            .cloned()
59            .unwrap_or_else(|| config.name.replace('-', "_"));
60        let gem_path = ruby_pkg
61            .as_ref()
62            .and_then(|p| p.path.as_ref())
63            .cloned()
64            .unwrap_or_else(|| "../../packages/ruby".to_string());
65        let gem_version = ruby_pkg
66            .as_ref()
67            .and_then(|p| p.version.as_ref())
68            .cloned()
69            .or_else(|| config.resolved_version())
70            .unwrap_or_else(|| "0.1.0".to_string());
71
72        // Generate Gemfile.
73        files.push(GeneratedFile {
74            path: output_base.join("Gemfile"),
75            content: render_gemfile(&gem_name, &gem_path, &gem_version, e2e_config.dep_mode),
76            generated_header: false,
77        });
78
79        // Generate .rubocop.yaml for linting generated specs.
80        files.push(GeneratedFile {
81            path: output_base.join(".rubocop.yaml"),
82            content: render_rubocop_yaml(),
83            generated_header: false,
84        });
85
86        // Check if any fixture is an HTTP test (needs mock server bootstrap).
87        let has_http_fixtures = groups
88            .iter()
89            .flat_map(|g| g.fixtures.iter())
90            .any(|f| f.needs_mock_server());
91
92        // Check if any fixture uses file_path or bytes args (needs chdir to test_documents).
93        let has_file_fixtures = groups.iter().flat_map(|g| g.fixtures.iter()).any(|f| {
94            let cc = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
95            cc.args
96                .iter()
97                .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
98        });
99
100        // Always generate spec/spec_helper.rb when file-based or HTTP fixtures are present.
101        if has_file_fixtures || has_http_fixtures {
102            files.push(GeneratedFile {
103                path: output_base.join("spec").join("spec_helper.rb"),
104                content: render_spec_helper(
105                    has_file_fixtures,
106                    has_http_fixtures,
107                    &e2e_config.test_documents_relative_from(1),
108                ),
109                generated_header: true,
110            });
111        }
112
113        // Generate spec files per category.
114        let spec_base = output_base.join("spec");
115
116        for group in groups {
117            let active: Vec<&Fixture> = group
118                .fixtures
119                .iter()
120                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
121                .collect();
122
123            if active.is_empty() {
124                continue;
125            }
126
127            let field_resolver_pre = FieldResolver::new(
128                &e2e_config.fields,
129                &e2e_config.fields_optional,
130                &e2e_config.result_fields,
131                &e2e_config.fields_array,
132                &std::collections::HashSet::new(),
133            );
134            // Skip the entire file if no fixture in this category produces output.
135            let has_any_output = active.iter().any(|f| {
136                // HTTP tests always produce output.
137                if f.is_http_test() {
138                    return true;
139                }
140                let expects_error = f.assertions.iter().any(|a| a.assertion_type == "error");
141                let has_not_error = f.assertions.iter().any(|a| a.assertion_type == "not_error");
142                expects_error || has_not_error || has_usable_assertion(f, &field_resolver_pre, result_is_simple)
143            });
144            if !has_any_output {
145                continue;
146            }
147
148            let filename = format!("{}_spec.rb", sanitize_filename(&group.category));
149            let field_resolver = FieldResolver::new(
150                &e2e_config.fields,
151                &e2e_config.fields_optional,
152                &e2e_config.result_fields,
153                &e2e_config.fields_array,
154                &std::collections::HashSet::new(),
155            );
156            let content = render_spec_file(
157                &group.category,
158                &active,
159                &module_path,
160                class_name.as_deref(),
161                &gem_name,
162                &field_resolver,
163                options_type.as_deref(),
164                enum_fields,
165                result_is_simple,
166                e2e_config,
167                has_file_fixtures || has_http_fixtures,
168            );
169            files.push(GeneratedFile {
170                path: spec_base.join(filename),
171                content,
172                generated_header: true,
173            });
174        }
175
176        Ok(files)
177    }
178
179    fn language_name(&self) -> &'static str {
180        "ruby"
181    }
182}
183
184// ---------------------------------------------------------------------------
185// Rendering
186// ---------------------------------------------------------------------------
187
188fn render_gemfile(
189    gem_name: &str,
190    gem_path: &str,
191    gem_version: &str,
192    dep_mode: crate::config::DependencyMode,
193) -> String {
194    let gem_line = match dep_mode {
195        crate::config::DependencyMode::Registry => format!("gem '{gem_name}', '{gem_version}'"),
196        crate::config::DependencyMode::Local => format!("gem '{gem_name}', path: '{gem_path}'"),
197    };
198    crate::template_env::render(
199        "ruby/Gemfile.jinja",
200        minijinja::context! {
201            gem_line => gem_line,
202            rspec => tv::gem::RSPEC_E2E,
203            rubocop => tv::gem::RUBOCOP_E2E,
204            rubocop_rspec => tv::gem::RUBOCOP_RSPEC_E2E,
205            faraday => tv::gem::FARADAY,
206        },
207    )
208}
209
210fn render_spec_helper(has_file_fixtures: bool, has_http_fixtures: bool, test_documents_path: &str) -> String {
211    let header = hash::header(CommentStyle::Hash);
212    let mut out = header;
213    out.push_str("# frozen_string_literal: true\n");
214
215    if has_file_fixtures {
216        let _ = writeln!(out);
217        let _ = writeln!(
218            out,
219            "# Change to the configured test-documents directory so that fixture file paths like"
220        );
221        let _ = writeln!(
222            out,
223            "# \"pdf/fake_memo.pdf\" resolve correctly when running rspec from e2e/ruby/."
224        );
225        let _ = writeln!(
226            out,
227            "# spec_helper.rb lives in e2e/ruby/spec/; the fixtures dir resolves three directories up."
228        );
229        let _ = writeln!(
230            out,
231            "_test_documents = File.expand_path('{test_documents_path}', __dir__)"
232        );
233        let _ = writeln!(out, "Dir.chdir(_test_documents) if Dir.exist?(_test_documents)");
234    }
235
236    if has_http_fixtures {
237        out.push_str(
238            r#"
239require 'json'
240require 'open3'
241
242# Spawn the mock-server binary and set MOCK_SERVER_URL for all tests.
243RSpec.configure do |config|
244  config.before(:suite) do
245    bin = File.expand_path('../../rust/target/release/mock-server', __dir__)
246    fixtures_dir = File.expand_path('../../../fixtures', __dir__)
247    unless File.exist?(bin)
248      warn "mock-server binary not found at #{bin} — run: cargo build --manifest-path e2e/rust/Cargo.toml --bin mock-server --release"
249    end
250    stdin, stdout, _stderr, _wait = Open3.popen3(bin, fixtures_dir)
251    # Read startup lines: MOCK_SERVER_URL= then optional MOCK_SERVERS=.
252    url = nil
253    8.times do
254      line = stdout.readline.strip rescue break
255      if line.start_with?('MOCK_SERVER_URL=')
256        url = line.split('=', 2).last
257        ENV['MOCK_SERVER_URL'] = url
258      elsif line.start_with?('MOCK_SERVERS=')
259        json_val = line.split('=', 2).last
260        ENV['MOCK_SERVERS'] = json_val
261        JSON.parse(json_val).each do |fid, furl|
262          ENV["MOCK_SERVER_#{fid.upcase}"] = furl
263        end
264        break
265      elsif url
266        break
267      end
268    end
269    # Drain stdout in background.
270    Thread.new { stdout.read }
271    # Store stdin so we can close it on teardown.
272    @_mock_server_stdin = stdin
273  end
274
275  config.after(:suite) do
276    @_mock_server_stdin&.close
277  end
278end
279"#,
280        );
281    }
282
283    out
284}
285
286fn render_rubocop_yaml() -> String {
287    crate::template_env::render("ruby/rubocop.yml.jinja", minijinja::context! {})
288}
289
290#[allow(clippy::too_many_arguments)]
291fn render_spec_file(
292    category: &str,
293    fixtures: &[&Fixture],
294    module_path: &str,
295    class_name: Option<&str>,
296    gem_name: &str,
297    field_resolver: &FieldResolver,
298    options_type: Option<&str>,
299    enum_fields: &HashMap<String, String>,
300    result_is_simple: bool,
301    e2e_config: &E2eConfig,
302    needs_spec_helper: bool,
303) -> String {
304    // Resolve client_factory from ruby override.
305    let client_factory = e2e_config
306        .call
307        .overrides
308        .get("ruby")
309        .and_then(|o| o.client_factory.as_deref());
310
311    // Build requires list
312    let require_name = if module_path.is_empty() { gem_name } else { module_path };
313    let mut requires = vec![require_name.replace('-', "_"), "json".to_string()];
314
315    let has_http = fixtures.iter().any(|f| f.is_http_test());
316    if needs_spec_helper || has_http {
317        requires.push("spec_helper".to_string());
318    }
319
320    // Build the Ruby module/class qualifier for calls.
321    let call_receiver = class_name
322        .map(|s| s.to_string())
323        .unwrap_or_else(|| ruby_module_name(module_path));
324
325    // Check for array contains assertions
326    let has_array_contains = fixtures.iter().any(|fixture| {
327        fixture.assertions.iter().any(|a| {
328            matches!(a.assertion_type.as_str(), "contains" | "contains_all" | "not_contains")
329                && a.field
330                    .as_deref()
331                    .is_some_and(|f| !f.is_empty() && field_resolver.is_array(field_resolver.resolve(f)))
332        })
333    });
334
335    // Build examples
336    let mut examples = Vec::new();
337    for fixture in fixtures {
338        if fixture.http.is_some() {
339            // HTTP example is handled separately (uses shared driver)
340            let mut out = String::new();
341            render_http_example(&mut out, fixture);
342            examples.push(out);
343        } else {
344            // Resolve per-fixture call config so we can detect streaming up front.
345            let fixture_call = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
346            let fixture_call_overrides = fixture_call.overrides.get("ruby");
347            let raw_function_name = fixture_call_overrides
348                .and_then(|o| o.function.as_ref())
349                .cloned()
350                .unwrap_or_else(|| fixture_call.function.clone());
351
352            let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
353            let has_not_error = fixture.assertions.iter().any(|a| a.assertion_type == "not_error");
354            let has_usable = has_usable_assertion(fixture, field_resolver, result_is_simple);
355            let is_streaming = raw_function_name == "chat_stream";
356
357            // Non-HTTP, non-streaming fixtures with no usable assertions stay pending.
358            // A fixture whose only assertion is `not_error` is still testable — it
359            // verifies the call does not raise, so route it to render_example.
360            if !expects_error && !has_usable && !has_not_error && !is_streaming {
361                let test_name = sanitize_ident(&fixture.id);
362                let description = fixture.description.replace('\'', "\\'");
363                let mut out = String::new();
364                out.push_str(&format!("  it '{test_name}: {description}' do\n"));
365                out.push_str("    skip 'Non-HTTP fixture cannot be tested via Net::HTTP'\n");
366                out.push_str("  end\n");
367                examples.push(out);
368            } else {
369                // Streaming methods do not take the `_async` suffix — Magnus emits
370                // `chat_stream` as a block-yielding method. All other async Rust
371                // methods are bound with the `_async` suffix.
372                let fixture_function_name = if is_streaming {
373                    raw_function_name
374                } else if fixture_call.r#async && !raw_function_name.ends_with("_async") {
375                    format!("{raw_function_name}_async")
376                } else {
377                    raw_function_name
378                };
379                let fixture_result_var = &fixture_call.result_var;
380                let fixture_args = &fixture_call.args;
381                let fixture_client_factory = fixture_call_overrides
382                    .and_then(|o| o.client_factory.as_deref())
383                    .or(client_factory);
384                let fixture_options_type = fixture_call_overrides
385                    .and_then(|o| o.options_type.as_deref())
386                    .or(options_type);
387
388                let fixture_extra_args: Vec<String> =
389                    fixture_call_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
390                // Use per-fixture-call result_is_simple so per-call overrides like
391                // `speech` (returns bytes) take precedence over the top-level call default.
392                let fixture_result_is_simple =
393                    fixture_call.result_is_simple || fixture_call_overrides.is_some_and(|o| o.result_is_simple);
394                // Per-call enum_fields take precedence — e.g. `[crates.e2e.calls.create_batch.overrides.ruby] enum_fields`
395                // labels `status = "BatchStatus"` for the batch lifecycle, but the global
396                // `[crates.e2e.call.overrides.ruby]` map only carries chat-shape entries.
397                let fixture_enum_fields: &HashMap<String, String> =
398                    fixture_call_overrides.map(|o| &o.enum_fields).unwrap_or(enum_fields);
399                let example = if is_streaming {
400                    render_chat_stream_example(
401                        fixture,
402                        &fixture_function_name,
403                        &call_receiver,
404                        fixture_args,
405                        fixture_options_type,
406                        fixture_enum_fields,
407                        e2e_config,
408                        fixture_client_factory,
409                        &fixture_extra_args,
410                    )
411                } else {
412                    render_example(
413                        fixture,
414                        &fixture_function_name,
415                        &call_receiver,
416                        fixture_result_var,
417                        fixture_args,
418                        field_resolver,
419                        fixture_options_type,
420                        fixture_enum_fields,
421                        fixture_result_is_simple,
422                        e2e_config,
423                        fixture_client_factory,
424                        &fixture_extra_args,
425                    )
426                };
427                examples.push(example);
428            }
429        }
430    }
431
432    let header = hash::header(CommentStyle::Hash);
433    crate::template_env::render(
434        "ruby/test_file.jinja",
435        minijinja::context! {
436            category => category,
437            requires => requires,
438            has_array_contains => has_array_contains,
439            has_http => has_http,
440            examples => examples,
441            header => header,
442        },
443    )
444}
445
446/// Check if a fixture has at least one assertion that will produce an executable
447/// expect() call (not just a skip comment).
448fn has_usable_assertion(fixture: &Fixture, field_resolver: &FieldResolver, result_is_simple: bool) -> bool {
449    fixture.assertions.iter().any(|a| {
450        // not_error is implicit (call succeeding), error is handled separately.
451        if a.assertion_type == "not_error" || a.assertion_type == "error" {
452            return false;
453        }
454        // Check field validity.
455        if let Some(f) = &a.field {
456            if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
457                return false;
458            }
459            // When result_is_simple, skip non-content fields.
460            if result_is_simple {
461                let f_lower = f.to_lowercase();
462                if !f.is_empty()
463                    && f_lower != "content"
464                    && (f_lower.starts_with("metadata")
465                        || f_lower.starts_with("document")
466                        || f_lower.starts_with("structure"))
467                {
468                    return false;
469                }
470            }
471        }
472        true
473    })
474}
475
476// ---------------------------------------------------------------------------
477// HTTP test rendering — shared-driver integration
478// ---------------------------------------------------------------------------
479
480/// Thin renderer that emits RSpec `describe` + `it` blocks targeting a mock server
481/// via `Net::HTTP`. Satisfies [`client::TestClientRenderer`] so the shared
482/// [`client::http_call::render_http_test`] driver drives the call sequence.
483struct RubyTestClientRenderer;
484
485impl client::TestClientRenderer for RubyTestClientRenderer {
486    fn language_name(&self) -> &'static str {
487        "ruby"
488    }
489
490    /// Emit `describe '{fn_name}' do` + inner `it '{description}' do`.
491    ///
492    /// `fn_name` is the sanitised fixture id used as the describe label.
493    /// When `skip_reason` is `Some`, the inner `it` block gets a `skip` call so
494    /// the shared driver short-circuits before emitting any assertions.
495    fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
496        let escaped_description = description.replace('\'', "\\'");
497        let rendered = crate::template_env::render(
498            "ruby/http_test.jinja",
499            minijinja::context! {
500                fn_name => fn_name,
501                description => escaped_description,
502                skip_reason => skip_reason,
503            },
504        );
505        out.push_str(&rendered);
506    }
507
508    /// Close the inner `it` block and the outer `describe` block.
509    fn render_test_close(&self, out: &mut String) {
510        let rendered = crate::template_env::render("ruby/http_test_close.jinja", minijinja::context! {});
511        out.push_str(&rendered);
512    }
513
514    /// Emit a `Net::HTTP` request to the mock server using the path from `ctx`.
515    fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
516        let method = ctx.method.to_uppercase();
517        let method_class = http_method_class(&method);
518
519        let has_body = ctx
520            .body
521            .is_some_and(|b| !matches!(b, serde_json::Value::String(s) if s.is_empty()));
522
523        let ruby_body = if has_body {
524            json_to_ruby(ctx.body.unwrap())
525        } else {
526            String::new()
527        };
528
529        let headers: Vec<minijinja::Value> = ctx
530            .headers
531            .iter()
532            .filter(|(k, _)| {
533                // Skip Content-Type when already set from the body above.
534                !(has_body && k.to_lowercase() == "content-type")
535            })
536            .map(|(k, v)| {
537                minijinja::context! {
538                    key_literal => ruby_string_literal(k),
539                    value_literal => ruby_string_literal(v),
540                }
541            })
542            .collect();
543
544        let rendered = crate::template_env::render(
545            "ruby/http_request.jinja",
546            minijinja::context! {
547                method_class => method_class,
548                path => ctx.path,
549                has_body => has_body,
550                ruby_body => ruby_body,
551                headers => headers,
552                response_var => ctx.response_var,
553            },
554        );
555        out.push_str(&rendered);
556    }
557
558    /// Emit `expect(response.code.to_i).to eq(status)`.
559    ///
560    /// Net::HTTP returns the HTTP status as a `String`; `.to_i` converts it for
561    /// comparison with the integer literal from the fixture.
562    fn render_assert_status(&self, out: &mut String, response_var: &str, status: u16) {
563        out.push_str(&format!("      expect({response_var}.code.to_i).to eq({status})\n"));
564    }
565
566    /// Emit a header assertion using `response[header_key]`.
567    ///
568    /// Handles the three special tokens: `<<present>>`, `<<absent>>`, `<<uuid>>`.
569    fn render_assert_header(&self, out: &mut String, response_var: &str, name: &str, expected: &str) {
570        let header_key = name.to_lowercase();
571        let header_expr = format!("{response_var}[{}]", ruby_string_literal(&header_key));
572        let assertion = match expected {
573            "<<present>>" => {
574                format!("      expect({header_expr}).not_to be_nil\n")
575            }
576            "<<absent>>" => {
577                format!("      expect({header_expr}).to be_nil\n")
578            }
579            "<<uuid>>" => {
580                format!(
581                    "      expect({header_expr}).to match(/\\A[0-9a-f]{{8}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{12}}\\z/i)\n"
582                )
583            }
584            literal => {
585                let ruby_val = ruby_string_literal(literal);
586                format!("      expect({header_expr}).to eq({ruby_val})\n")
587            }
588        };
589        out.push_str(&assertion);
590    }
591
592    /// Emit a full JSON body equality assertion.
593    ///
594    /// Plain string bodies are compared as raw text; structured bodies are parsed
595    /// with `JSON.parse` and compared as Ruby Hash/Array values.
596    fn render_assert_json_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
597        match expected {
598            serde_json::Value::String(s) => {
599                let ruby_val = ruby_string_literal(s);
600                out.push_str(&format!("      expect({response_var}.body).to eq({ruby_val})\n"));
601            }
602            _ => {
603                let ruby_val = json_to_ruby(expected);
604                out.push_str(&format!(
605                    "      _body = {response_var}.body && !{response_var}.body.empty? ? JSON.parse({response_var}.body) : nil\n"
606                ));
607                out.push_str(&format!("      expect(_body).to eq({ruby_val})\n"));
608            }
609        }
610    }
611
612    /// Emit partial body assertions: one `expect(_body[key]).to eq(val)` per field.
613    fn render_assert_partial_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
614        if let Some(obj) = expected.as_object() {
615            out.push_str(&format!("      _body = JSON.parse({response_var}.body)\n"));
616            for (key, val) in obj {
617                let ruby_key = ruby_string_literal(key);
618                let ruby_val = json_to_ruby(val);
619                out.push_str(&format!("      expect(_body[{ruby_key}]).to eq({ruby_val})\n"));
620            }
621        }
622    }
623
624    /// Emit validation-error assertions, checking each expected `msg` against the
625    /// parsed body's `errors` array.
626    fn render_assert_validation_errors(
627        &self,
628        out: &mut String,
629        response_var: &str,
630        errors: &[ValidationErrorExpectation],
631    ) {
632        for err in errors {
633            let msg_lit = ruby_string_literal(&err.msg);
634            out.push_str(&format!("      _body = JSON.parse({response_var}.body)\n"));
635            out.push_str("      _errors = _body['errors'] || []\n");
636            out.push_str(&format!(
637                "      expect(_errors.map {{ |e| e['msg'] }}).to include({msg_lit})\n"
638            ));
639        }
640    }
641}
642
643/// Render an RSpec example for an HTTP server test fixture via the shared driver.
644///
645/// Delegates to [`client::http_call::render_http_test`] after handling the one
646/// Ruby-specific pre-condition: HTTP 101 (WebSocket upgrade) cannot be exercised
647/// via `Net::HTTP` and is emitted as a pending `it` block directly.
648fn render_http_example(out: &mut String, fixture: &Fixture) {
649    // HTTP 101 (WebSocket upgrade) cannot be tested via Net::HTTP.
650    // Emit the skip block directly rather than pushing a skip directive through
651    // the shared driver, which would require a full `fixture.skip` entry.
652    if fixture
653        .http
654        .as_ref()
655        .is_some_and(|h| h.expected_response.status_code == 101)
656    {
657        if let Some(http) = fixture.http.as_ref() {
658            let description = fixture.description.replace('\'', "\\'");
659            let method = http.request.method.to_uppercase();
660            let path = &http.request.path;
661            let rendered = crate::template_env::render(
662                "ruby/http_101_skip.jinja",
663                minijinja::context! {
664                    method => method,
665                    path => path,
666                    description => description,
667                },
668            );
669            out.push_str(&rendered);
670        }
671        return;
672    }
673
674    client::http_call::render_http_test(out, &RubyTestClientRenderer, fixture);
675}
676
677/// Convert an uppercase HTTP method string to Ruby's Net::HTTP class name.
678/// Ruby uses title-cased names: Get, Post, Put, Delete, Patch, Head, Options, Trace.
679fn http_method_class(method: &str) -> String {
680    let mut chars = method.chars();
681    match chars.next() {
682        None => String::new(),
683        Some(first) => first.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase(),
684    }
685}
686
687// ---------------------------------------------------------------------------
688// Chat-stream test rendering — block iteration with local aggregation
689// ---------------------------------------------------------------------------
690
691/// Render an RSpec example for a `chat_stream` fixture.
692///
693/// The Ruby binding's `chat_stream` is block-yielding: each yielded value is a
694/// `LiterLlm::ChatCompletionChunk`. The codegen builds local aggregator vars
695/// (`chunks`, `stream_content`, `stream_complete`, plus optional
696/// `last_finish_reason`, `tool_calls_json`, `total_tokens`) inside the block and
697/// then emits assertions on those locals — never on response pseudo-fields.
698#[allow(clippy::too_many_arguments)]
699fn render_chat_stream_example(
700    fixture: &Fixture,
701    function_name: &str,
702    call_receiver: &str,
703    args: &[crate::config::ArgMapping],
704    options_type: Option<&str>,
705    enum_fields: &HashMap<String, String>,
706    e2e_config: &E2eConfig,
707    client_factory: Option<&str>,
708    extra_args: &[String],
709) -> String {
710    let test_name = sanitize_ident(&fixture.id);
711    let description = fixture.description.replace('\'', "\\'");
712    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
713    let fixture_id = fixture.id.clone();
714
715    let (mut setup_lines, args_str) = build_args_and_setup(
716        &fixture.input,
717        args,
718        call_receiver,
719        options_type,
720        enum_fields,
721        false,
722        fixture,
723    );
724
725    let mut final_args = args_str;
726    if !extra_args.is_empty() {
727        let extra_str = extra_args.join(", ");
728        if final_args.is_empty() {
729            final_args = extra_str;
730        } else {
731            final_args = format!("{final_args}, {extra_str}");
732        }
733    }
734
735    // Detect which aggregators a fixture's assertions actually need so we don't
736    // emit unused locals (rubocop trips on assigned-but-unread vars).
737    let mut needs_finish_reason = false;
738    let mut needs_tool_calls_json = false;
739    let mut needs_tool_calls_0_function_name = false;
740    let mut needs_total_tokens = false;
741    for a in &fixture.assertions {
742        if let Some(f) = a.field.as_deref() {
743            match f {
744                "finish_reason" => needs_finish_reason = true,
745                "tool_calls" => needs_tool_calls_json = true,
746                "tool_calls[0].function.name" => needs_tool_calls_0_function_name = true,
747                "usage.total_tokens" => needs_total_tokens = true,
748                _ => {}
749            }
750        }
751    }
752
753    let mut out = String::new();
754    out.push_str(&format!("  it '{test_name}: {description}' do\n"));
755
756    // Client construction.
757    let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
758    let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
759    if let Some(cf) = client_factory {
760        if has_mock && let Some(key_var) = api_key_var {
761            let mock_url_expr = format!("\"#{{ENV['MOCK_SERVER_URL']}}/fixtures/{fixture_id}\"");
762            out.push_str(&format!("    api_key = ENV['{key_var}']\n"));
763            out.push_str("    if api_key && !api_key.empty?\n");
764            out.push_str(&format!(
765                "      warn \"{test_name}: using real API ({key_var} is set)\"\n"
766            ));
767            out.push_str(&format!("      client = {call_receiver}.{cf}(api_key)\n"));
768            out.push_str("    else\n");
769            out.push_str(&format!(
770                "      warn \"{test_name}: using mock server ({key_var} not set)\"\n"
771            ));
772            out.push_str(&format!("      mock_url = {mock_url_expr}\n"));
773            out.push_str(&format!("      client = {call_receiver}.{cf}('test-key', mock_url)\n"));
774            out.push_str("    end\n");
775        } else if has_mock {
776            let base_url_expr = if fixture.has_host_root_route() {
777                let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
778                format!("(ENV.fetch('{env_key}', nil) || ENV.fetch('MOCK_SERVER_URL') + '/fixtures/{fixture_id}')")
779            } else {
780                format!("ENV.fetch('MOCK_SERVER_URL') + '/fixtures/{fixture_id}'")
781            };
782            out.push_str(&format!(
783                "    client = {call_receiver}.{cf}('test-key', {base_url_expr})\n"
784            ));
785        } else if let Some(key_var) = api_key_var {
786            out.push_str(&format!("    api_key = ENV['{key_var}']\n"));
787            out.push_str(&format!("    skip '{key_var} not set' unless api_key\n"));
788            out.push_str(&format!("    client = {call_receiver}.{cf}(api_key)\n"));
789        } else {
790            out.push_str(&format!("    client = {call_receiver}.{cf}('test-key')\n"));
791        }
792    }
793
794    // Visitor (rare for streaming, but support it for parity).
795    if let Some(visitor_spec) = &fixture.visitor {
796        let _ = build_ruby_visitor(&mut setup_lines, visitor_spec);
797    }
798    for line in &setup_lines {
799        out.push_str(&format!("    {line}\n"));
800    }
801
802    let call_expr = if client_factory.is_some() {
803        format!("client.{function_name}({final_args})")
804    } else {
805        format!("{call_receiver}.{function_name}({final_args})")
806    };
807
808    if expects_error {
809        out.push_str(&format!("    expect {{ {call_expr} {{ |_chunk| }} }}.to raise_error\n"));
810        out.push_str("  end\n");
811        return out;
812    }
813
814    // Build aggregators inside a block so the iterator drives the stream synchronously.
815    out.push_str("    chunks = []\n");
816    out.push_str("    stream_content = ''.dup\n");
817    out.push_str("    stream_complete = false\n");
818    if needs_finish_reason {
819        out.push_str("    last_finish_reason = nil\n");
820    }
821    if needs_tool_calls_json {
822        out.push_str("    tool_calls_json = nil\n");
823    }
824    if needs_tool_calls_0_function_name {
825        out.push_str("    tool_calls_0_function_name = nil\n");
826    }
827    if needs_total_tokens {
828        out.push_str("    total_tokens = nil\n");
829    }
830    out.push_str(&format!("    {call_expr} do |chunk|\n"));
831    out.push_str("      chunks << chunk\n");
832    out.push_str("      choice = chunk.choices && chunk.choices[0]\n");
833    out.push_str("      if choice\n");
834    out.push_str("        delta = choice.delta\n");
835    out.push_str("        if delta && delta.content\n");
836    out.push_str("          stream_content << delta.content\n");
837    out.push_str("        end\n");
838    if needs_finish_reason {
839        out.push_str("        if choice.finish_reason\n");
840        out.push_str("          last_finish_reason = choice.finish_reason.to_s\n");
841        out.push_str("        end\n");
842    }
843    if needs_tool_calls_json || needs_tool_calls_0_function_name {
844        out.push_str("        tcs = delta && delta.tool_calls\n");
845        out.push_str("        if tcs && !tcs.empty?\n");
846        if needs_tool_calls_json {
847            out.push_str(
848                "          tool_calls_json ||= tcs.map { |tc| { 'function' => { 'name' => (tc.function && tc.function.name rescue nil) } } }.to_json\n",
849            );
850        }
851        if needs_tool_calls_0_function_name {
852            out.push_str(
853                "          tool_calls_0_function_name ||= (tcs[0].function && tcs[0].function.name rescue nil)\n",
854            );
855        }
856        out.push_str("        end\n");
857    }
858    out.push_str("      end\n");
859    if needs_total_tokens {
860        out.push_str("      if chunk.usage && chunk.usage.total_tokens\n");
861        out.push_str("        total_tokens = chunk.usage.total_tokens\n");
862        out.push_str("      end\n");
863    }
864    out.push_str("    end\n");
865    out.push_str("    stream_complete = true\n");
866
867    // Render assertions on the local aggregator vars.
868    for assertion in &fixture.assertions {
869        emit_chat_stream_assertion(&mut out, assertion, e2e_config);
870    }
871
872    // Always assert that the stream completed cleanly so non-empty test bodies
873    // are guaranteed by RSpec's at-least-one-expectation requirement.
874    if !fixture
875        .assertions
876        .iter()
877        .any(|a| a.field.as_deref() == Some("stream_complete"))
878    {
879        out.push_str("    expect(stream_complete).to be(true)\n");
880    }
881
882    out.push_str("  end\n");
883    out
884}
885
886/// Map a streaming fixture assertion to an `expect` call on the local aggregator
887/// variable produced by [`render_chat_stream_example`]. Pseudo-fields like
888/// `chunks` / `stream_content` / `stream_complete` resolve to the in-block locals,
889/// not response accessors.
890fn emit_chat_stream_assertion(out: &mut String, assertion: &Assertion, _e2e_config: &E2eConfig) {
891    let atype = assertion.assertion_type.as_str();
892    if atype == "not_error" || atype == "error" {
893        return;
894    }
895    let field = assertion.field.as_deref().unwrap_or("");
896
897    enum Kind {
898        Chunks,
899        Bool,
900        Str,
901        IntTokens,
902        Json,
903        Unsupported,
904    }
905
906    let (expr, kind) = match field {
907        "chunks" => ("chunks", Kind::Chunks),
908        "stream_content" => ("stream_content", Kind::Str),
909        "stream_complete" => ("stream_complete", Kind::Bool),
910        "no_chunks_after_done" => ("stream_complete", Kind::Bool),
911        "finish_reason" => ("last_finish_reason", Kind::Str),
912        "tool_calls" => ("tool_calls_json", Kind::Json),
913        "tool_calls[0].function.name" => ("tool_calls_0_function_name", Kind::Str),
914        "usage.total_tokens" => ("total_tokens", Kind::IntTokens),
915        _ => ("", Kind::Unsupported),
916    };
917
918    if matches!(kind, Kind::Unsupported) {
919        out.push_str(&format!(
920            "    # skipped: streaming assertion on unsupported field '{field}'\n"
921        ));
922        return;
923    }
924
925    match (atype, &kind) {
926        ("count_min", Kind::Chunks) => {
927            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
928                out.push_str(&format!("    expect({expr}.length).to be >= {n}\n"));
929            }
930        }
931        ("count_equals", Kind::Chunks) => {
932            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
933                out.push_str(&format!("    expect({expr}.length).to eq({n})\n"));
934            }
935        }
936        ("equals", Kind::Str) => {
937            if let Some(val) = &assertion.value {
938                let rb_val = json_to_ruby(val);
939                out.push_str(&format!("    expect({expr}.to_s).to eq({rb_val})\n"));
940            }
941        }
942        ("contains", Kind::Str) => {
943            if let Some(val) = &assertion.value {
944                let rb_val = json_to_ruby(val);
945                out.push_str(&format!("    expect({expr}.to_s).to include({rb_val})\n"));
946            }
947        }
948        ("not_empty", Kind::Str) => {
949            out.push_str(&format!("    expect({expr}.to_s).not_to be_empty\n"));
950        }
951        ("not_empty", Kind::Json) => {
952            out.push_str(&format!("    expect({expr}).not_to be_nil\n"));
953        }
954        ("is_empty", Kind::Str) => {
955            out.push_str(&format!("    expect({expr}.to_s).to be_empty\n"));
956        }
957        ("is_true", Kind::Bool) => {
958            out.push_str(&format!("    expect({expr}).to be(true)\n"));
959        }
960        ("is_false", Kind::Bool) => {
961            out.push_str(&format!("    expect({expr}).to be(false)\n"));
962        }
963        ("greater_than_or_equal", Kind::IntTokens) => {
964            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
965                out.push_str(&format!("    expect({expr}).to be >= {n}\n"));
966            }
967        }
968        ("equals", Kind::IntTokens) => {
969            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
970                out.push_str(&format!("    expect({expr}).to eq({n})\n"));
971            }
972        }
973        _ => {
974            out.push_str(&format!(
975                "    # skipped: streaming assertion '{atype}' on field '{field}' not supported\n"
976            ));
977        }
978    }
979}
980
981// ---------------------------------------------------------------------------
982// Function-call test rendering
983// ---------------------------------------------------------------------------
984
985#[allow(clippy::too_many_arguments)]
986fn render_example(
987    fixture: &Fixture,
988    function_name: &str,
989    call_receiver: &str,
990    result_var: &str,
991    args: &[crate::config::ArgMapping],
992    field_resolver: &FieldResolver,
993    options_type: Option<&str>,
994    enum_fields: &HashMap<String, String>,
995    result_is_simple: bool,
996    e2e_config: &E2eConfig,
997    client_factory: Option<&str>,
998    extra_args: &[String],
999) -> String {
1000    let test_name = sanitize_ident(&fixture.id);
1001    let description = fixture.description.replace('\'', "\\'");
1002    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
1003    let fixture_id = fixture.id.clone();
1004
1005    let (mut setup_lines, args_str) = build_args_and_setup(
1006        &fixture.input,
1007        args,
1008        call_receiver,
1009        options_type,
1010        enum_fields,
1011        result_is_simple,
1012        fixture,
1013    );
1014
1015    // Build visitor if present and add to setup
1016    let mut visitor_arg = String::new();
1017    if let Some(visitor_spec) = &fixture.visitor {
1018        visitor_arg = build_ruby_visitor(&mut setup_lines, visitor_spec);
1019    }
1020
1021    let mut final_args = if visitor_arg.is_empty() {
1022        args_str
1023    } else if args_str.is_empty() {
1024        visitor_arg
1025    } else {
1026        format!("{args_str}, {visitor_arg}")
1027    };
1028
1029    // Append per-fixture extra_args (e.g. trailing `nil` for `list_files(purpose)`).
1030    if !extra_args.is_empty() {
1031        let extra_str = extra_args.join(", ");
1032        if final_args.is_empty() {
1033            final_args = extra_str;
1034        } else {
1035            final_args = format!("{final_args}, {extra_str}");
1036        }
1037    }
1038
1039    // When client_factory is configured, create a client instance and call methods on it.
1040    let call_expr = if client_factory.is_some() {
1041        format!("client.{function_name}({final_args})")
1042    } else {
1043        format!("{call_receiver}.{function_name}({final_args})")
1044    };
1045
1046    // Check if any non-error assertion actually uses the result variable.
1047    let has_usable = has_usable_assertion(fixture, field_resolver, result_is_simple);
1048
1049    // Render all assertions upfront into a string
1050    let mut assertions_rendered = String::new();
1051    for assertion in &fixture.assertions {
1052        render_assertion(
1053            &mut assertions_rendered,
1054            assertion,
1055            result_var,
1056            field_resolver,
1057            result_is_simple,
1058            e2e_config,
1059            enum_fields,
1060        );
1061    }
1062
1063    let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
1064    let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
1065    let has_mock_and_key = has_mock && api_key_var.is_some();
1066    crate::template_env::render(
1067        "ruby/test_function.jinja",
1068        minijinja::context! {
1069            test_name => test_name,
1070            description => description,
1071            expects_error => expects_error,
1072            setup_lines => setup_lines,
1073            call_expr => call_expr,
1074            result_var => result_var,
1075            assertions_rendered => assertions_rendered,
1076            has_usable => has_usable,
1077            client_factory => client_factory,
1078            fixture_id => fixture_id,
1079            call_receiver => call_receiver,
1080            has_mock => has_mock,
1081            api_key_var => api_key_var,
1082            has_mock_and_key => has_mock_and_key,
1083        },
1084    )
1085}
1086
1087/// Build setup lines (e.g. handle creation) and the argument list for the function call.
1088///
1089/// Returns `(setup_lines, args_string)`.
1090/// Emit Ruby batch item constructors for BatchBytesItem or BatchFileItem arrays.
1091fn emit_ruby_batch_item_array(arr: &serde_json::Value, elem_type: &str) -> String {
1092    if let Some(items) = arr.as_array() {
1093        let item_strs: Vec<String> = items
1094            .iter()
1095            .filter_map(|item| {
1096                if let Some(obj) = item.as_object() {
1097                    match elem_type {
1098                        "BatchBytesItem" => {
1099                            let content = obj.get("content").and_then(|v| v.as_array());
1100                            let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
1101                            let config = obj.get("config");
1102                            let content_code = if let Some(arr) = content {
1103                                let bytes: Vec<String> =
1104                                    arr.iter().filter_map(|v| v.as_u64().map(|n| n.to_string())).collect();
1105                                // Pass as Ruby array - Magnus will convert Array<u8> to Vec<u8>
1106                                format!("[{}]", bytes.join(", "))
1107                            } else {
1108                                "[]".to_string()
1109                            };
1110                            let config_arg = if let Some(cfg) = config {
1111                                if cfg.is_null() {
1112                                    "nil".to_string()
1113                                } else {
1114                                    json_to_ruby(cfg)
1115                                }
1116                            } else {
1117                                "nil".to_string()
1118                            };
1119                            Some(format!(
1120                                "Kreuzberg::{}.new(content: {}, mime_type: \"{}\", config: {})",
1121                                elem_type, content_code, mime_type, config_arg
1122                            ))
1123                        }
1124                        "BatchFileItem" => {
1125                            let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1126                            let config = obj.get("config");
1127                            let config_arg = if let Some(cfg) = config {
1128                                if cfg.is_null() {
1129                                    "nil".to_string()
1130                                } else {
1131                                    json_to_ruby(cfg)
1132                                }
1133                            } else {
1134                                "nil".to_string()
1135                            };
1136                            Some(format!(
1137                                "Kreuzberg::{}.new(path: \"{}\", config: {})",
1138                                elem_type, path, config_arg
1139                            ))
1140                        }
1141                        _ => None,
1142                    }
1143                } else {
1144                    None
1145                }
1146            })
1147            .collect();
1148        format!("[{}]", item_strs.join(", "))
1149    } else {
1150        "[]".to_string()
1151    }
1152}
1153
1154fn build_args_and_setup(
1155    input: &serde_json::Value,
1156    args: &[crate::config::ArgMapping],
1157    call_receiver: &str,
1158    options_type: Option<&str>,
1159    enum_fields: &HashMap<String, String>,
1160    result_is_simple: bool,
1161    fixture: &crate::fixture::Fixture,
1162) -> (Vec<String>, String) {
1163    let fixture_id = &fixture.id;
1164    if args.is_empty() {
1165        // No args config: pass the whole input only when it's non-empty.
1166        // Functions with no parameters have empty input and must be called
1167        // with no arguments — not with `{}` or `nil`.
1168        let is_empty_input = match input {
1169            serde_json::Value::Null => true,
1170            serde_json::Value::Object(m) => m.is_empty(),
1171            _ => false,
1172        };
1173        if is_empty_input {
1174            return (Vec::new(), String::new());
1175        }
1176        return (Vec::new(), json_to_ruby(input));
1177    }
1178
1179    let mut setup_lines: Vec<String> = Vec::new();
1180    let mut parts: Vec<String> = Vec::new();
1181    // Track optional args that were skipped; if a later arg is emitted we must back-fill nil
1182    // to preserve positional correctness (e.g. extract_file(path, nil, config)).
1183    let mut skipped_optional_count: usize = 0;
1184
1185    for arg in args {
1186        if arg.arg_type == "mock_url" {
1187            // Flush any pending nil placeholders for skipped optionals before this positional arg.
1188            for _ in 0..skipped_optional_count {
1189                parts.push("nil".to_string());
1190            }
1191            skipped_optional_count = 0;
1192            if fixture.has_host_root_route() {
1193                let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1194                setup_lines.push(format!(
1195                    "{} = ENV.fetch('{env_key}', nil) || \"#{{ENV.fetch('MOCK_SERVER_URL')}}/fixtures/{fixture_id}\"",
1196                    arg.name,
1197                ));
1198            } else {
1199                setup_lines.push(format!(
1200                    "{} = \"#{{ENV.fetch('MOCK_SERVER_URL')}}/fixtures/{fixture_id}\"",
1201                    arg.name,
1202                ));
1203            }
1204            parts.push(arg.name.clone());
1205            continue;
1206        }
1207
1208        // Handle bytes arguments: load from file if needed
1209        if arg.arg_type == "bytes" {
1210            // Flush any pending nil placeholders for skipped optionals before this positional arg.
1211            for _ in 0..skipped_optional_count {
1212                parts.push("nil".to_string());
1213            }
1214            skipped_optional_count = 0;
1215            let resolved = resolve_field(input, &arg.field);
1216            if let Some(s) = resolved.as_str() {
1217                if is_file_path(s) {
1218                    // File path: load with File.read and convert to bytes array
1219                    setup_lines.push(format!("{} = File.read(\"{}\").bytes", arg.name, s));
1220                } else if is_base64(s) {
1221                    // Base64: decode it
1222                    setup_lines.push(format!("{} = Base64.decode64(\"{}\").bytes", arg.name, s));
1223                } else {
1224                    // Inline text: encode to binary and convert to bytes array
1225                    let escaped = ruby_string_literal(s);
1226                    setup_lines.push(format!("{} = {}.b.bytes", arg.name, escaped));
1227                }
1228                parts.push(arg.name.clone());
1229            } else {
1230                parts.push("nil".to_string());
1231            }
1232            continue;
1233        }
1234
1235        // Handle file_path arguments: pass the path string as-is
1236        if arg.arg_type == "file_path" {
1237            // Flush any pending nil placeholders for skipped optionals before this positional arg.
1238            for _ in 0..skipped_optional_count {
1239                parts.push("nil".to_string());
1240            }
1241            skipped_optional_count = 0;
1242            let resolved = resolve_field(input, &arg.field);
1243            if let Some(s) = resolved.as_str() {
1244                let escaped = ruby_string_literal(s);
1245                parts.push(escaped);
1246            } else if arg.optional {
1247                skipped_optional_count += 1;
1248                continue;
1249            } else {
1250                parts.push("''".to_string());
1251            }
1252            continue;
1253        }
1254
1255        if arg.arg_type == "handle" {
1256            // Flush any pending nil placeholders for skipped optionals before this positional arg.
1257            for _ in 0..skipped_optional_count {
1258                parts.push("nil".to_string());
1259            }
1260            skipped_optional_count = 0;
1261            // Generate a create_engine (or equivalent) call and pass the variable.
1262            let constructor_name = format!("create_{}", arg.name.to_snake_case());
1263            let config_value = resolve_field(input, &arg.field);
1264            if config_value.is_null()
1265                || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1266            {
1267                setup_lines.push(format!("{} = {call_receiver}.{constructor_name}(nil)", arg.name,));
1268            } else {
1269                let literal = json_to_ruby(config_value);
1270                let name = &arg.name;
1271                setup_lines.push(format!("{name}_config = {literal}"));
1272                setup_lines.push(format!(
1273                    "{} = {call_receiver}.{constructor_name}({name}_config.to_json)",
1274                    arg.name,
1275                    name = name,
1276                ));
1277            }
1278            parts.push(arg.name.clone());
1279            continue;
1280        }
1281
1282        let resolved = resolve_field(input, &arg.field);
1283        let val = if resolved.is_null() { None } else { Some(resolved) };
1284        match val {
1285            None | Some(serde_json::Value::Null) if arg.optional => {
1286                // Optional arg with no fixture value: defer; emit nil only if a later arg is present.
1287                skipped_optional_count += 1;
1288                continue;
1289            }
1290            None | Some(serde_json::Value::Null) => {
1291                // Required arg with no fixture value: flush deferred nils, then pass a default.
1292                for _ in 0..skipped_optional_count {
1293                    parts.push("nil".to_string());
1294                }
1295                skipped_optional_count = 0;
1296                let default_val = match arg.arg_type.as_str() {
1297                    "string" => "''".to_string(),
1298                    "int" | "integer" => "0".to_string(),
1299                    "float" | "number" => "0.0".to_string(),
1300                    "bool" | "boolean" => "false".to_string(),
1301                    _ => "nil".to_string(),
1302                };
1303                parts.push(default_val);
1304            }
1305            Some(v) => {
1306                // Flush deferred nil placeholders for skipped optional args that precede this one.
1307                for _ in 0..skipped_optional_count {
1308                    parts.push("nil".to_string());
1309                }
1310                skipped_optional_count = 0;
1311                // For json_object args with options_type, construct a typed options object.
1312                // When result_is_simple, the binding accepts a plain Hash (no wrapper class).
1313                if arg.arg_type == "json_object" && !v.is_null() {
1314                    // Check for batch item arrays (element_type set to BatchBytesItem/BatchFileItem)
1315                    if let Some(elem_type) = &arg.element_type {
1316                        if (elem_type == "BatchBytesItem" || elem_type == "BatchFileItem") && v.is_array() {
1317                            parts.push(emit_ruby_batch_item_array(v, elem_type));
1318                            continue;
1319                        }
1320                    }
1321                    // Otherwise handle regular options_type objects
1322                    if let (Some(opts_type), Some(obj)) = (options_type, v.as_object()) {
1323                        let kwargs: Vec<String> = obj
1324                            .iter()
1325                            .map(|(k, vv)| {
1326                                let snake_key = k.to_snake_case();
1327                                let rb_val = if enum_fields.contains_key(k) {
1328                                    if let Some(s) = vv.as_str() {
1329                                        let snake_val = s.to_snake_case();
1330                                        format!("'{snake_val}'")
1331                                    } else {
1332                                        json_to_ruby(vv)
1333                                    }
1334                                } else {
1335                                    json_to_ruby(vv)
1336                                };
1337                                format!("{snake_key}: {rb_val}")
1338                            })
1339                            .collect();
1340                        if result_is_simple {
1341                            parts.push(format!("{{{}}}", kwargs.join(", ")));
1342                        } else {
1343                            parts.push(format!("{opts_type}.new({})", kwargs.join(", ")));
1344                        }
1345                        continue;
1346                    }
1347                }
1348                parts.push(json_to_ruby(v));
1349            }
1350        }
1351    }
1352
1353    (setup_lines, parts.join(", "))
1354}
1355
1356fn render_assertion(
1357    out: &mut String,
1358    assertion: &Assertion,
1359    result_var: &str,
1360    field_resolver: &FieldResolver,
1361    result_is_simple: bool,
1362    e2e_config: &E2eConfig,
1363    per_call_enum_fields: &HashMap<String, String>,
1364) {
1365    // For simple-result methods (e.g. `speech` returning bytes), every field-based
1366    // assertion targets the result itself — there's no struct to access. Drop
1367    // length-only assertions onto the result directly and skip anything else.
1368    if result_is_simple {
1369        if let Some(f) = &assertion.field {
1370            if !f.is_empty() {
1371                match assertion.assertion_type.as_str() {
1372                    "not_empty" => {
1373                        out.push_str(&format!("    expect({result_var}.to_s).not_to be_empty\n"));
1374                        return;
1375                    }
1376                    "is_empty" => {
1377                        out.push_str(&format!("    expect({result_var}.to_s).to be_empty\n"));
1378                        return;
1379                    }
1380                    "count_equals" => {
1381                        if let Some(val) = &assertion.value {
1382                            let rb_val = json_to_ruby(val);
1383                            out.push_str(&format!("    expect({result_var}.length).to eq({rb_val})\n"));
1384                        }
1385                        return;
1386                    }
1387                    "count_min" => {
1388                        if let Some(val) = &assertion.value {
1389                            let rb_val = json_to_ruby(val);
1390                            out.push_str(&format!("    expect({result_var}.length).to be >= {rb_val}\n"));
1391                        }
1392                        return;
1393                    }
1394                    _ => {
1395                        out.push_str(&format!(
1396                            "    # skipped: field '{f}' not applicable for simple result type\n"
1397                        ));
1398                        return;
1399                    }
1400                }
1401            }
1402        }
1403    }
1404    // Handle synthetic / derived fields before the is_valid_for_result check
1405    // so they are never treated as struct attribute accesses on the result.
1406    if let Some(f) = &assertion.field {
1407        match f.as_str() {
1408            "chunks_have_content" => {
1409                let pred = format!("({result_var}.chunks || []).all? {{ |c| c.content && !c.content.empty? }}");
1410                match assertion.assertion_type.as_str() {
1411                    "is_true" => {
1412                        out.push_str(&format!("    expect({pred}).to be(true)\n"));
1413                    }
1414                    "is_false" => {
1415                        out.push_str(&format!("    expect({pred}).to be(false)\n"));
1416                    }
1417                    _ => {
1418                        out.push_str(&format!(
1419                            "    # skipped: unsupported assertion type on synthetic field '{f}'\n"
1420                        ));
1421                    }
1422                }
1423                return;
1424            }
1425            "chunks_have_embeddings" => {
1426                let pred =
1427                    format!("({result_var}.chunks || []).all? {{ |c| !c.embedding.nil? && !c.embedding.empty? }}");
1428                match assertion.assertion_type.as_str() {
1429                    "is_true" => {
1430                        out.push_str(&format!("    expect({pred}).to be(true)\n"));
1431                    }
1432                    "is_false" => {
1433                        out.push_str(&format!("    expect({pred}).to be(false)\n"));
1434                    }
1435                    _ => {
1436                        out.push_str(&format!(
1437                            "    # skipped: unsupported assertion type on synthetic field '{f}'\n"
1438                        ));
1439                    }
1440                }
1441                return;
1442            }
1443            // ---- EmbedResponse virtual fields ----
1444            // embed_texts returns Array<Array<Float>> in Ruby — no wrapper struct.
1445            // result_var is the embedding matrix; use it directly.
1446            "embeddings" => {
1447                match assertion.assertion_type.as_str() {
1448                    "count_equals" => {
1449                        if let Some(val) = &assertion.value {
1450                            let rb_val = json_to_ruby(val);
1451                            out.push_str(&format!("    expect({result_var}.length).to eq({rb_val})\n"));
1452                        }
1453                    }
1454                    "count_min" => {
1455                        if let Some(val) = &assertion.value {
1456                            let rb_val = json_to_ruby(val);
1457                            out.push_str(&format!("    expect({result_var}.length).to be >= {rb_val}\n"));
1458                        }
1459                    }
1460                    "not_empty" => {
1461                        out.push_str(&format!("    expect({result_var}).not_to be_empty\n"));
1462                    }
1463                    "is_empty" => {
1464                        out.push_str(&format!("    expect({result_var}).to be_empty\n"));
1465                    }
1466                    _ => {
1467                        out.push_str("    # skipped: unsupported assertion type on synthetic field 'embeddings'\n");
1468                    }
1469                }
1470                return;
1471            }
1472            "embedding_dimensions" => {
1473                let expr = format!("({result_var}.empty? ? 0 : {result_var}[0].length)");
1474                match assertion.assertion_type.as_str() {
1475                    "equals" => {
1476                        if let Some(val) = &assertion.value {
1477                            let rb_val = json_to_ruby(val);
1478                            out.push_str(&format!("    expect({expr}).to eq({rb_val})\n"));
1479                        }
1480                    }
1481                    "greater_than" => {
1482                        if let Some(val) = &assertion.value {
1483                            let rb_val = json_to_ruby(val);
1484                            out.push_str(&format!("    expect({expr}).to be > {rb_val}\n"));
1485                        }
1486                    }
1487                    _ => {
1488                        out.push_str(
1489                            "    # skipped: unsupported assertion type on synthetic field 'embedding_dimensions'\n",
1490                        );
1491                    }
1492                }
1493                return;
1494            }
1495            "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
1496                let pred = match f.as_str() {
1497                    "embeddings_valid" => {
1498                        format!("{result_var}.all? {{ |e| !e.empty? }}")
1499                    }
1500                    "embeddings_finite" => {
1501                        format!("{result_var}.all? {{ |e| e.all? {{ |v| v.finite? }} }}")
1502                    }
1503                    "embeddings_non_zero" => {
1504                        format!("{result_var}.all? {{ |e| e.any? {{ |v| v != 0.0 }} }}")
1505                    }
1506                    "embeddings_normalized" => {
1507                        format!("{result_var}.all? {{ |e| n = e.sum {{ |v| v * v }}; (n - 1.0).abs < 1e-3 }}")
1508                    }
1509                    _ => unreachable!(),
1510                };
1511                match assertion.assertion_type.as_str() {
1512                    "is_true" => {
1513                        out.push_str(&format!("    expect({pred}).to be(true)\n"));
1514                    }
1515                    "is_false" => {
1516                        out.push_str(&format!("    expect({pred}).to be(false)\n"));
1517                    }
1518                    _ => {
1519                        out.push_str(&format!(
1520                            "    # skipped: unsupported assertion type on synthetic field '{f}'\n"
1521                        ));
1522                    }
1523                }
1524                return;
1525            }
1526            // ---- keywords / keywords_count ----
1527            // Ruby ExtractionResult does not expose extracted_keywords; skip.
1528            "keywords" | "keywords_count" => {
1529                out.push_str(&format!(
1530                    "    # skipped: field '{f}' not available on Ruby ExtractionResult\n"
1531                ));
1532                return;
1533            }
1534            _ => {}
1535        }
1536    }
1537
1538    // Skip assertions on fields that don't exist on the result type.
1539    if let Some(f) = &assertion.field {
1540        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1541            out.push_str(&format!("    # skipped: field '{f}' not available on result type\n"));
1542            return;
1543        }
1544    }
1545
1546    // When result_is_simple, skip assertions that reference non-content fields.
1547    if result_is_simple {
1548        if let Some(f) = &assertion.field {
1549            let f_lower = f.to_lowercase();
1550            if !f.is_empty()
1551                && f_lower != "content"
1552                && (f_lower.starts_with("metadata")
1553                    || f_lower.starts_with("document")
1554                    || f_lower.starts_with("structure"))
1555            {
1556                return;
1557            }
1558        }
1559    }
1560
1561    // result_is_simple: treat the result itself as the content string, but only
1562    // when there is no explicit field (or the field is "content"). Count/length
1563    // assertions on named fields (e.g. "warnings") must still walk the field path.
1564    let field_expr = match &assertion.field {
1565        Some(f) if !f.is_empty() && (!result_is_simple || !f.eq_ignore_ascii_case("content")) => {
1566            field_resolver.accessor(f, "ruby", result_var)
1567        }
1568        _ => result_var.to_string(),
1569    };
1570
1571    // For string equality, strip trailing whitespace to handle trailing newlines
1572    // from the converter. Ruby enum fields (Magnus binds Rust enums as Symbols),
1573    // are coerced to String via .to_s so `eq("stop")` matches `:stop`. Look up the
1574    // field in both the global `[crates.e2e] fields_enum` set AND the per-call
1575    // override `[crates.e2e.calls.<x>.overrides.<lang>] enum_fields = { ... }` —
1576    // downstream config that already labels e.g. `status = "BatchStatus"` for the
1577    // Java/C#/Python sides should apply here too without a Ruby-only duplicate.
1578    let field_is_enum = assertion.field.as_deref().filter(|f| !f.is_empty()).is_some_and(|f| {
1579        let resolved = field_resolver.resolve(f);
1580        e2e_config.fields_enum.contains(f)
1581            || e2e_config.fields_enum.contains(resolved)
1582            || per_call_enum_fields.contains_key(f)
1583            || per_call_enum_fields.contains_key(resolved)
1584    });
1585    let stripped_field_expr = if result_is_simple {
1586        format!("{field_expr}.to_s.strip")
1587    } else if field_is_enum {
1588        format!("{field_expr}.to_s")
1589    } else {
1590        field_expr.clone()
1591    };
1592
1593    // Detect whether the assertion field resolves to an array type so that
1594    // contains assertions can iterate items instead of calling .to_s on the array.
1595    let field_is_array = assertion
1596        .field
1597        .as_deref()
1598        .filter(|f| !f.is_empty())
1599        .is_some_and(|f| field_resolver.is_array(field_resolver.resolve(f)));
1600
1601    match assertion.assertion_type.as_str() {
1602        "equals" => {
1603            if let Some(expected) = &assertion.value {
1604                let is_boolean_val = expected.as_bool().is_some();
1605                let bool_val = expected
1606                    .as_bool()
1607                    .map(|b| if b { "true" } else { "false" })
1608                    .unwrap_or("");
1609                let rb_val = json_to_ruby(expected);
1610
1611                let rendered = crate::template_env::render(
1612                    "ruby/assertion.jinja",
1613                    minijinja::context! {
1614                        assertion_type => "equals",
1615                        stripped_field_expr => stripped_field_expr.clone(),
1616                        is_boolean_val => is_boolean_val,
1617                        bool_val => bool_val,
1618                        expected_val => rb_val,
1619                    },
1620                );
1621                out.push_str(&rendered);
1622            }
1623        }
1624        "contains" => {
1625            if let Some(expected) = &assertion.value {
1626                let rb_val = json_to_ruby(expected);
1627                let rendered = crate::template_env::render(
1628                    "ruby/assertion.jinja",
1629                    minijinja::context! {
1630                        assertion_type => "contains",
1631                        field_expr => field_expr.clone(),
1632                        field_is_array => field_is_array && expected.is_string(),
1633                        expected_val => rb_val,
1634                    },
1635                );
1636                out.push_str(&rendered);
1637            }
1638        }
1639        "contains_all" => {
1640            if let Some(values) = &assertion.values {
1641                let values_list: Vec<String> = values.iter().map(json_to_ruby).collect();
1642                let rendered = crate::template_env::render(
1643                    "ruby/assertion.jinja",
1644                    minijinja::context! {
1645                        assertion_type => "contains_all",
1646                        field_expr => field_expr.clone(),
1647                        field_is_array => field_is_array,
1648                        values_list => values_list,
1649                    },
1650                );
1651                out.push_str(&rendered);
1652            }
1653        }
1654        "not_contains" => {
1655            if let Some(expected) = &assertion.value {
1656                let rb_val = json_to_ruby(expected);
1657                let rendered = crate::template_env::render(
1658                    "ruby/assertion.jinja",
1659                    minijinja::context! {
1660                        assertion_type => "not_contains",
1661                        field_expr => field_expr.clone(),
1662                        field_is_array => field_is_array && expected.is_string(),
1663                        expected_val => rb_val,
1664                    },
1665                );
1666                out.push_str(&rendered);
1667            }
1668        }
1669        "not_empty" => {
1670            let rendered = crate::template_env::render(
1671                "ruby/assertion.jinja",
1672                minijinja::context! {
1673                    assertion_type => "not_empty",
1674                    field_expr => field_expr.clone(),
1675                },
1676            );
1677            out.push_str(&rendered);
1678        }
1679        "is_empty" => {
1680            let rendered = crate::template_env::render(
1681                "ruby/assertion.jinja",
1682                minijinja::context! {
1683                    assertion_type => "is_empty",
1684                    field_expr => field_expr.clone(),
1685                },
1686            );
1687            out.push_str(&rendered);
1688        }
1689        "contains_any" => {
1690            if let Some(values) = &assertion.values {
1691                let items: Vec<String> = values.iter().map(json_to_ruby).collect();
1692                let rendered = crate::template_env::render(
1693                    "ruby/assertion.jinja",
1694                    minijinja::context! {
1695                        assertion_type => "contains_any",
1696                        field_expr => field_expr.clone(),
1697                        values_list => items,
1698                    },
1699                );
1700                out.push_str(&rendered);
1701            }
1702        }
1703        "greater_than" => {
1704            if let Some(val) = &assertion.value {
1705                let rb_val = json_to_ruby(val);
1706                let rendered = crate::template_env::render(
1707                    "ruby/assertion.jinja",
1708                    minijinja::context! {
1709                        assertion_type => "greater_than",
1710                        field_expr => field_expr.clone(),
1711                        expected_val => rb_val,
1712                    },
1713                );
1714                out.push_str(&rendered);
1715            }
1716        }
1717        "less_than" => {
1718            if let Some(val) = &assertion.value {
1719                let rb_val = json_to_ruby(val);
1720                let rendered = crate::template_env::render(
1721                    "ruby/assertion.jinja",
1722                    minijinja::context! {
1723                        assertion_type => "less_than",
1724                        field_expr => field_expr.clone(),
1725                        expected_val => rb_val,
1726                    },
1727                );
1728                out.push_str(&rendered);
1729            }
1730        }
1731        "greater_than_or_equal" => {
1732            if let Some(val) = &assertion.value {
1733                let rb_val = json_to_ruby(val);
1734                let rendered = crate::template_env::render(
1735                    "ruby/assertion.jinja",
1736                    minijinja::context! {
1737                        assertion_type => "greater_than_or_equal",
1738                        field_expr => field_expr.clone(),
1739                        expected_val => rb_val,
1740                    },
1741                );
1742                out.push_str(&rendered);
1743            }
1744        }
1745        "less_than_or_equal" => {
1746            if let Some(val) = &assertion.value {
1747                let rb_val = json_to_ruby(val);
1748                let rendered = crate::template_env::render(
1749                    "ruby/assertion.jinja",
1750                    minijinja::context! {
1751                        assertion_type => "less_than_or_equal",
1752                        field_expr => field_expr.clone(),
1753                        expected_val => rb_val,
1754                    },
1755                );
1756                out.push_str(&rendered);
1757            }
1758        }
1759        "starts_with" => {
1760            if let Some(expected) = &assertion.value {
1761                let rb_val = json_to_ruby(expected);
1762                let rendered = crate::template_env::render(
1763                    "ruby/assertion.jinja",
1764                    minijinja::context! {
1765                        assertion_type => "starts_with",
1766                        field_expr => field_expr.clone(),
1767                        expected_val => rb_val,
1768                    },
1769                );
1770                out.push_str(&rendered);
1771            }
1772        }
1773        "ends_with" => {
1774            if let Some(expected) = &assertion.value {
1775                let rb_val = json_to_ruby(expected);
1776                let rendered = crate::template_env::render(
1777                    "ruby/assertion.jinja",
1778                    minijinja::context! {
1779                        assertion_type => "ends_with",
1780                        field_expr => field_expr.clone(),
1781                        expected_val => rb_val,
1782                    },
1783                );
1784                out.push_str(&rendered);
1785            }
1786        }
1787        "min_length" | "max_length" | "count_min" | "count_equals" => {
1788            if let Some(val) = &assertion.value {
1789                if let Some(n) = val.as_u64() {
1790                    let rendered = crate::template_env::render(
1791                        "ruby/assertion.jinja",
1792                        minijinja::context! {
1793                            assertion_type => assertion.assertion_type.as_str(),
1794                            field_expr => field_expr.clone(),
1795                            check_n => n,
1796                        },
1797                    );
1798                    out.push_str(&rendered);
1799                }
1800            }
1801        }
1802        "is_true" => {
1803            let rendered = crate::template_env::render(
1804                "ruby/assertion.jinja",
1805                minijinja::context! {
1806                    assertion_type => "is_true",
1807                    field_expr => field_expr.clone(),
1808                },
1809            );
1810            out.push_str(&rendered);
1811        }
1812        "is_false" => {
1813            let rendered = crate::template_env::render(
1814                "ruby/assertion.jinja",
1815                minijinja::context! {
1816                    assertion_type => "is_false",
1817                    field_expr => field_expr.clone(),
1818                },
1819            );
1820            out.push_str(&rendered);
1821        }
1822        "method_result" => {
1823            if let Some(method_name) = &assertion.method {
1824                // Derive call_receiver for module-level helper calls.
1825                let lang = "ruby";
1826                let call = &e2e_config.call;
1827                let overrides = call.overrides.get(lang);
1828                let module_path = overrides
1829                    .and_then(|o| o.module.as_ref())
1830                    .cloned()
1831                    .unwrap_or_else(|| call.module.clone());
1832                let call_receiver = ruby_module_name(&module_path);
1833
1834                let call_expr =
1835                    build_ruby_method_call(&call_receiver, result_var, method_name, assertion.args.as_ref());
1836                let check = assertion.check.as_deref().unwrap_or("is_true");
1837
1838                let (check_val_str, is_boolean_check, bool_check_val, check_n_val) = match check {
1839                    "equals" => {
1840                        if let Some(val) = &assertion.value {
1841                            let is_bool = val.as_bool().is_some();
1842                            let bool_str = val.as_bool().map(|b| if b { "true" } else { "false" }).unwrap_or("");
1843                            let rb_val = json_to_ruby(val);
1844                            (rb_val, is_bool, bool_str.to_string(), 0)
1845                        } else {
1846                            (String::new(), false, String::new(), 0)
1847                        }
1848                    }
1849                    "greater_than_or_equal" => {
1850                        if let Some(val) = &assertion.value {
1851                            (json_to_ruby(val), false, String::new(), 0)
1852                        } else {
1853                            (String::new(), false, String::new(), 0)
1854                        }
1855                    }
1856                    "count_min" => {
1857                        if let Some(val) = &assertion.value {
1858                            let n = val.as_u64().unwrap_or(0);
1859                            (String::new(), false, String::new(), n)
1860                        } else {
1861                            (String::new(), false, String::new(), 0)
1862                        }
1863                    }
1864                    "contains" => {
1865                        if let Some(val) = &assertion.value {
1866                            (json_to_ruby(val), false, String::new(), 0)
1867                        } else {
1868                            (String::new(), false, String::new(), 0)
1869                        }
1870                    }
1871                    _ => (String::new(), false, String::new(), 0),
1872                };
1873
1874                let rendered = crate::template_env::render(
1875                    "ruby/assertion.jinja",
1876                    minijinja::context! {
1877                        assertion_type => "method_result",
1878                        call_expr => call_expr,
1879                        check => check,
1880                        check_val => check_val_str,
1881                        is_boolean_check => is_boolean_check,
1882                        bool_check_val => bool_check_val,
1883                        check_n => check_n_val,
1884                    },
1885                );
1886                out.push_str(&rendered);
1887            } else {
1888                panic!("Ruby e2e generator: method_result assertion missing 'method' field");
1889            }
1890        }
1891        "matches_regex" => {
1892            if let Some(expected) = &assertion.value {
1893                let rb_val = json_to_ruby(expected);
1894                let rendered = crate::template_env::render(
1895                    "ruby/assertion.jinja",
1896                    minijinja::context! {
1897                        assertion_type => "matches_regex",
1898                        field_expr => field_expr.clone(),
1899                        expected_val => rb_val,
1900                    },
1901                );
1902                out.push_str(&rendered);
1903            }
1904        }
1905        "not_error" => {
1906            // Already handled by the call succeeding without exception.
1907        }
1908        "error" => {
1909            // Handled at the example level.
1910        }
1911        other => {
1912            panic!("Ruby e2e generator: unsupported assertion type: {other}");
1913        }
1914    }
1915}
1916
1917/// Build a Ruby call expression for a `method_result` assertion on a tree-sitter Tree.
1918/// Maps method names to the appropriate Ruby method or module-function calls.
1919fn build_ruby_method_call(
1920    call_receiver: &str,
1921    result_var: &str,
1922    method_name: &str,
1923    args: Option<&serde_json::Value>,
1924) -> String {
1925    match method_name {
1926        "root_child_count" => format!("{result_var}.root_node.child_count"),
1927        "root_node_type" => format!("{result_var}.root_node.type"),
1928        "named_children_count" => format!("{result_var}.root_node.named_child_count"),
1929        "has_error_nodes" => format!("{call_receiver}.tree_has_error_nodes({result_var})"),
1930        "error_count" | "tree_error_count" => format!("{call_receiver}.tree_error_count({result_var})"),
1931        "tree_to_sexp" => format!("{call_receiver}.tree_to_sexp({result_var})"),
1932        "contains_node_type" => {
1933            let node_type = args
1934                .and_then(|a| a.get("node_type"))
1935                .and_then(|v| v.as_str())
1936                .unwrap_or("");
1937            format!("{call_receiver}.tree_contains_node_type({result_var}, \"{node_type}\")")
1938        }
1939        "find_nodes_by_type" => {
1940            let node_type = args
1941                .and_then(|a| a.get("node_type"))
1942                .and_then(|v| v.as_str())
1943                .unwrap_or("");
1944            format!("{call_receiver}.find_nodes_by_type({result_var}, \"{node_type}\")")
1945        }
1946        "run_query" => {
1947            let query_source = args
1948                .and_then(|a| a.get("query_source"))
1949                .and_then(|v| v.as_str())
1950                .unwrap_or("");
1951            let language = args
1952                .and_then(|a| a.get("language"))
1953                .and_then(|v| v.as_str())
1954                .unwrap_or("");
1955            format!("{call_receiver}.run_query({result_var}, \"{language}\", \"{query_source}\", source)")
1956        }
1957        _ => format!("{result_var}.{method_name}"),
1958    }
1959}
1960
1961/// Convert a module path (e.g., "html_to_markdown") to Ruby PascalCase module name
1962/// (e.g., "HtmlToMarkdown").
1963fn ruby_module_name(module_path: &str) -> String {
1964    use heck::ToUpperCamelCase;
1965    module_path.to_upper_camel_case()
1966}
1967
1968/// Convert a `serde_json::Value` to a Ruby literal string, preferring single quotes.
1969fn json_to_ruby(value: &serde_json::Value) -> String {
1970    match value {
1971        serde_json::Value::String(s) => ruby_string_literal(s),
1972        serde_json::Value::Bool(true) => "true".to_string(),
1973        serde_json::Value::Bool(false) => "false".to_string(),
1974        serde_json::Value::Number(n) => n.to_string(),
1975        serde_json::Value::Null => "nil".to_string(),
1976        serde_json::Value::Array(arr) => {
1977            let items: Vec<String> = arr.iter().map(json_to_ruby).collect();
1978            format!("[{}]", items.join(", "))
1979        }
1980        serde_json::Value::Object(map) => {
1981            let items: Vec<String> = map
1982                .iter()
1983                .map(|(k, v)| format!("{} => {}", ruby_string_literal(k), json_to_ruby(v)))
1984                .collect();
1985            format!("{{ {} }}", items.join(", "))
1986        }
1987    }
1988}
1989
1990// ---------------------------------------------------------------------------
1991// Visitor generation
1992// ---------------------------------------------------------------------------
1993
1994/// Build a Ruby visitor object and add setup lines. Returns the visitor expression.
1995fn build_ruby_visitor(setup_lines: &mut Vec<String>, visitor_spec: &crate::fixture::VisitorSpec) -> String {
1996    setup_lines.push("visitor = Class.new do".to_string());
1997    for (method_name, action) in &visitor_spec.callbacks {
1998        emit_ruby_visitor_method(setup_lines, method_name, action);
1999    }
2000    setup_lines.push("end.new".to_string());
2001    "visitor".to_string()
2002}
2003
2004/// Emit a Ruby visitor method for a callback action.
2005fn emit_ruby_visitor_method(setup_lines: &mut Vec<String>, method_name: &str, action: &CallbackAction) {
2006    let params = match method_name {
2007        "visit_link" => "ctx, href, text, title",
2008        "visit_image" => "ctx, src, alt, title",
2009        "visit_heading" => "ctx, level, text, id",
2010        "visit_code_block" => "ctx, lang, code",
2011        "visit_code_inline"
2012        | "visit_strong"
2013        | "visit_emphasis"
2014        | "visit_strikethrough"
2015        | "visit_underline"
2016        | "visit_subscript"
2017        | "visit_superscript"
2018        | "visit_mark"
2019        | "visit_button"
2020        | "visit_summary"
2021        | "visit_figcaption"
2022        | "visit_definition_term"
2023        | "visit_definition_description" => "ctx, text",
2024        "visit_text" => "ctx, text",
2025        "visit_list_item" => "ctx, ordered, marker, text",
2026        "visit_blockquote" => "ctx, content, depth",
2027        "visit_table_row" => "ctx, cells, is_header",
2028        "visit_custom_element" => "ctx, tag_name, html",
2029        "visit_form" => "ctx, action_url, method",
2030        "visit_input" => "ctx, input_type, name, value",
2031        "visit_audio" | "visit_video" | "visit_iframe" => "ctx, src",
2032        "visit_details" => "ctx, is_open",
2033        "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => "ctx, output",
2034        "visit_list_start" => "ctx, ordered",
2035        "visit_list_end" => "ctx, ordered, output",
2036        _ => "ctx",
2037    };
2038
2039    // Pre-compute action type and values
2040    let (action_type, action_value) = match action {
2041        CallbackAction::Skip => ("skip", String::new()),
2042        CallbackAction::Continue => ("continue", String::new()),
2043        CallbackAction::PreserveHtml => ("preserve_html", String::new()),
2044        CallbackAction::Custom { output } => {
2045            let escaped = ruby_string_literal(output);
2046            ("custom", escaped)
2047        }
2048        CallbackAction::CustomTemplate { template } => {
2049            let interpolated = ruby_template_to_interpolation(template);
2050            ("custom", format!("\"{interpolated}\""))
2051        }
2052    };
2053
2054    let rendered = crate::template_env::render(
2055        "ruby/visitor_method.jinja",
2056        minijinja::context! {
2057            method_name => method_name,
2058            params => params,
2059            action_type => action_type,
2060            action_value => action_value,
2061        },
2062    );
2063    for line in rendered.lines() {
2064        setup_lines.push(line.to_string());
2065    }
2066}
2067
2068/// Classify a fixture string value that maps to a `bytes` argument.
2069///
2070/// Returns true if the value looks like a file path (e.g. "pdf/fake_memo.pdf").
2071/// File paths have the pattern: alphanumeric/something.extension
2072fn is_file_path(s: &str) -> bool {
2073    if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
2074        return false;
2075    }
2076
2077    let first = s.chars().next().unwrap_or('\0');
2078    if first.is_ascii_alphanumeric() || first == '_' {
2079        if let Some(slash_pos) = s.find('/') {
2080            if slash_pos > 0 {
2081                let after_slash = &s[slash_pos + 1..];
2082                if after_slash.contains('.') && !after_slash.is_empty() {
2083                    return true;
2084                }
2085            }
2086        }
2087    }
2088
2089    false
2090}
2091
2092/// Check if a string looks like base64-encoded data.
2093/// If it's not a file path or inline text, assume it's base64.
2094fn is_base64(s: &str) -> bool {
2095    if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
2096        return false;
2097    }
2098
2099    if is_file_path(s) {
2100        return false;
2101    }
2102
2103    true
2104}