alef-e2e 0.10.4

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

use crate::config::E2eConfig;
use crate::escape::{escape_shell, sanitize_filename, sanitize_ident};
use crate::field_access::FieldResolver;
use crate::fixture::{Assertion, Fixture, FixtureGroup};
use alef_core::backend::GeneratedFile;
use alef_core::config::AlefConfig;
use alef_core::hash::{self, CommentStyle};
use anyhow::Result;
use std::fmt::Write as FmtWrite;
use std::path::PathBuf;

use super::E2eCodegen;

/// Brew (Homebrew CLI) e2e code generator.
pub struct BrewCodegen;

impl E2eCodegen for BrewCodegen {
    fn generate(
        &self,
        groups: &[FixtureGroup],
        e2e_config: &E2eConfig,
        _alef_config: &AlefConfig,
    ) -> Result<Vec<GeneratedFile>> {
        let lang = self.language_name();
        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);

        // Resolve call config with overrides for the "brew" language key.
        let call = &e2e_config.call;
        let overrides = call.overrides.get(lang);
        let subcommand = overrides
            .and_then(|o| o.function.as_ref())
            .cloned()
            .unwrap_or_else(|| call.function.clone());

        // Static CLI flags appended to every invocation.
        let static_cli_args: Vec<String> = overrides.map(|o| o.cli_args.clone()).unwrap_or_default();

        // Field-to-flag mapping (fixture input field → CLI flag name).
        let cli_flags: std::collections::HashMap<String, String> =
            overrides.map(|o| o.cli_flags.clone()).unwrap_or_default();

        // Resolve binary name from the "brew" package entry, falling back to call.module.
        let binary_name = e2e_config
            .registry
            .packages
            .get(lang)
            .and_then(|p| p.name.as_ref())
            .cloned()
            .or_else(|| e2e_config.packages.get(lang).and_then(|p| p.name.as_ref()).cloned())
            .unwrap_or_else(|| call.module.clone());

        // Filter active groups (non-skipped fixtures).
        let active_groups: Vec<(&FixtureGroup, Vec<&Fixture>)> = groups
            .iter()
            .filter_map(|group| {
                let active: Vec<&Fixture> = group
                    .fixtures
                    .iter()
                    .filter(|f| f.skip.as_ref().is_none_or(|s| !s.should_skip(lang)))
                    .collect();
                if active.is_empty() { None } else { Some((group, active)) }
            })
            .collect();

        let field_resolver = FieldResolver::new(
            &e2e_config.fields,
            &e2e_config.fields_optional,
            &e2e_config.result_fields,
            &e2e_config.fields_array,
        );

        let mut files = Vec::new();

        // Generate run_tests.sh.
        let category_names: Vec<String> = active_groups
            .iter()
            .map(|(g, _)| sanitize_filename(&g.category))
            .collect();
        files.push(GeneratedFile {
            path: output_base.join("run_tests.sh"),
            content: render_run_tests(&category_names),
            generated_header: true,
        });

        // Generate per-category test files.
        for (group, active) in &active_groups {
            let safe_category = sanitize_filename(&group.category);
            let filename = format!("test_{safe_category}.sh");
            let content = render_category_file(
                &group.category,
                active,
                &binary_name,
                &subcommand,
                &static_cli_args,
                &cli_flags,
                &e2e_config.call.args,
                &field_resolver,
                e2e_config,
            );
            files.push(GeneratedFile {
                path: output_base.join(filename),
                content,
                generated_header: true,
            });
        }

        Ok(files)
    }

    fn language_name(&self) -> &'static str {
        "brew"
    }
}

/// Render the main `run_tests.sh` runner script.
fn render_run_tests(categories: &[String]) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "#!/usr/bin/env bash");
    out.push_str(&hash::header(CommentStyle::Hash));
    let _ = writeln!(out, "# shellcheck disable=SC1091");
    let _ = writeln!(out, "set -euo pipefail");
    let _ = writeln!(out);
    let _ = writeln!(out, "# MOCK_SERVER_URL must be set to the base URL of the mock server.");
    let _ = writeln!(out, ": \"${{MOCK_SERVER_URL:?MOCK_SERVER_URL is required}}\"");
    let _ = writeln!(out);
    let _ = writeln!(out, "# Verify that jq is available.");
    let _ = writeln!(out, "if ! command -v jq &>/dev/null; then");
    let _ = writeln!(out, "    echo 'error: jq is required but not found in PATH' >&2");
    let _ = writeln!(out, "    exit 1");
    let _ = writeln!(out, "fi");
    let _ = writeln!(out);
    let _ = writeln!(out, "PASS=0");
    let _ = writeln!(out, "FAIL=0");
    let _ = writeln!(out);

    // Helper functions.
    let _ = writeln!(out, "assert_equals() {{");
    let _ = writeln!(out, "    local actual=\"$1\" expected=\"$2\" label=\"$3\"");
    let _ = writeln!(out, "    if [ \"$actual\" != \"$expected\" ]; then");
    let _ = writeln!(
        out,
        "        echo \"FAIL [$label]: expected '$expected', got '$actual'\" >&2"
    );
    let _ = writeln!(out, "        return 1");
    let _ = writeln!(out, "    fi");
    let _ = writeln!(out, "}}");
    let _ = writeln!(out);
    let _ = writeln!(out, "assert_contains() {{");
    let _ = writeln!(out, "    local actual=\"$1\" expected=\"$2\" label=\"$3\"");
    let _ = writeln!(out, "    if [[ \"$actual\" != *\"$expected\"* ]]; then");
    let _ = writeln!(
        out,
        "        echo \"FAIL [$label]: expected to contain '$expected'\" >&2"
    );
    let _ = writeln!(out, "        return 1");
    let _ = writeln!(out, "    fi");
    let _ = writeln!(out, "}}");
    let _ = writeln!(out);
    let _ = writeln!(out, "assert_not_empty() {{");
    let _ = writeln!(out, "    local actual=\"$1\" label=\"$2\"");
    let _ = writeln!(out, "    if [ -z \"$actual\" ]; then");
    let _ = writeln!(out, "        echo \"FAIL [$label]: expected non-empty value\" >&2");
    let _ = writeln!(out, "        return 1");
    let _ = writeln!(out, "    fi");
    let _ = writeln!(out, "}}");
    let _ = writeln!(out);
    let _ = writeln!(out, "assert_count_min() {{");
    let _ = writeln!(out, "    local count=\"$1\" min=\"$2\" label=\"$3\"");
    let _ = writeln!(out, "    if [ \"$count\" -lt \"$min\" ]; then");
    let _ = writeln!(
        out,
        "        echo \"FAIL [$label]: expected at least $min elements, got $count\" >&2"
    );
    let _ = writeln!(out, "        return 1");
    let _ = writeln!(out, "    fi");
    let _ = writeln!(out, "}}");
    let _ = writeln!(out);
    let _ = writeln!(out, "assert_greater_than() {{");
    let _ = writeln!(out, "    local val=\"$1\" threshold=\"$2\" label=\"$3\"");
    let _ = writeln!(
        out,
        "    if [ \"$(echo \"$val > $threshold\" | bc -l)\" != \"1\" ]; then"
    );
    let _ = writeln!(out, "        echo \"FAIL [$label]: expected $val > $threshold\" >&2");
    let _ = writeln!(out, "        return 1");
    let _ = writeln!(out, "    fi");
    let _ = writeln!(out, "}}");
    let _ = writeln!(out);
    let _ = writeln!(out, "assert_greater_than_or_equal() {{");
    let _ = writeln!(out, "    local actual=\"$1\" expected=\"$2\" label=\"$3\"");
    let _ = writeln!(out, "    if [ \"$actual\" -lt \"$expected\" ]; then");
    let _ = writeln!(out, "        echo \"FAIL [$label]: expected $actual >= $expected\" >&2");
    let _ = writeln!(out, "        return 1");
    let _ = writeln!(out, "    fi");
    let _ = writeln!(out, "}}");
    let _ = writeln!(out);
    let _ = writeln!(out, "assert_is_empty() {{");
    let _ = writeln!(out, "    local actual=\"$1\" label=\"$2\"");
    let _ = writeln!(out, "    if [ -n \"$actual\" ]; then");
    let _ = writeln!(
        out,
        "        echo \"FAIL [$label]: expected empty value, got '$actual'\" >&2"
    );
    let _ = writeln!(out, "        return 1");
    let _ = writeln!(out, "    fi");
    let _ = writeln!(out, "}}");
    let _ = writeln!(out);
    let _ = writeln!(out, "assert_less_than() {{");
    let _ = writeln!(out, "    local actual=\"$1\" expected=\"$2\" label=\"$3\"");
    let _ = writeln!(out, "    if [ \"$actual\" -ge \"$expected\" ]; then");
    let _ = writeln!(out, "        echo \"FAIL [$label]: expected $actual < $expected\" >&2");
    let _ = writeln!(out, "        return 1");
    let _ = writeln!(out, "    fi");
    let _ = writeln!(out, "}}");
    let _ = writeln!(out);
    let _ = writeln!(out, "assert_less_than_or_equal() {{");
    let _ = writeln!(out, "    local actual=\"$1\" expected=\"$2\" label=\"$3\"");
    let _ = writeln!(out, "    if [ \"$actual\" -gt \"$expected\" ]; then");
    let _ = writeln!(out, "        echo \"FAIL [$label]: expected $actual <= $expected\" >&2");
    let _ = writeln!(out, "        return 1");
    let _ = writeln!(out, "    fi");
    let _ = writeln!(out, "}}");
    let _ = writeln!(out);
    let _ = writeln!(out, "assert_not_contains() {{");
    let _ = writeln!(out, "    local actual=\"$1\" expected=\"$2\" label=\"$3\"");
    let _ = writeln!(out, "    if [[ \"$actual\" == *\"$expected\"* ]]; then");
    let _ = writeln!(
        out,
        "        echo \"FAIL [$label]: expected not to contain '$expected'\" >&2"
    );
    let _ = writeln!(out, "        return 1");
    let _ = writeln!(out, "    fi");
    let _ = writeln!(out, "}}");
    let _ = writeln!(out);

    // Source per-category files.
    let script_dir = r#"SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)""#;
    let _ = writeln!(out, "{script_dir}");
    let _ = writeln!(out);
    for category in categories {
        let _ = writeln!(out, "# shellcheck source=test_{category}.sh");
        let _ = writeln!(out, "source \"$SCRIPT_DIR/test_{category}.sh\"");
    }
    let _ = writeln!(out);

    // Run each test function and track pass/fail.
    let _ = writeln!(out, "run_test() {{");
    let _ = writeln!(out, "    local name=\"$1\"");
    let _ = writeln!(out, "    if \"$name\"; then");
    let _ = writeln!(out, "        echo \"PASS: $name\"");
    let _ = writeln!(out, "        PASS=$((PASS + 1))");
    let _ = writeln!(out, "    else");
    let _ = writeln!(out, "        echo \"FAIL: $name\"");
    let _ = writeln!(out, "        FAIL=$((FAIL + 1))");
    let _ = writeln!(out, "    fi");
    let _ = writeln!(out, "}}");
    let _ = writeln!(out);

    // Gather all test function names from category files then call them.
    // We enumerate them at code-generation time so the runner doesn't need
    // introspection at runtime.
    let _ = writeln!(out, "# Run all generated test functions.");
    for category in categories {
        let _ = writeln!(out, "# Category: {category}");
        // We emit a placeholder comment — the actual list is per-category.
        // The run_test calls are emitted inline below based on known IDs.
        let _ = writeln!(out, "run_tests_{category}");
    }
    let _ = writeln!(out);
    let _ = writeln!(out, "echo \"\"");
    let _ = writeln!(out, "echo \"Results: $PASS passed, $FAIL failed\"");
    let _ = writeln!(out, "[ \"$FAIL\" -eq 0 ]");
    out
}

/// Render a per-category `test_{category}.sh` file.
#[allow(clippy::too_many_arguments)]
fn render_category_file(
    category: &str,
    fixtures: &[&Fixture],
    binary_name: &str,
    subcommand: &str,
    static_cli_args: &[String],
    cli_flags: &std::collections::HashMap<String, String>,
    args: &[crate::config::ArgMapping],
    field_resolver: &FieldResolver,
    e2e_config: &E2eConfig,
) -> String {
    let safe_category = sanitize_filename(category);
    let mut out = String::new();
    let _ = writeln!(out, "#!/usr/bin/env bash");
    out.push_str(&hash::header(CommentStyle::Hash));
    let _ = writeln!(out, "# E2e tests for category: {category}");
    let _ = writeln!(out, "set -euo pipefail");
    let _ = writeln!(out);

    for fixture in fixtures {
        render_test_function(
            &mut out,
            fixture,
            binary_name,
            subcommand,
            static_cli_args,
            cli_flags,
            args,
            field_resolver,
            e2e_config,
        );
        let _ = writeln!(out);
    }

    // Emit a runner function for this category.
    let _ = writeln!(out, "run_tests_{safe_category}() {{");
    for fixture in fixtures {
        let fn_name = sanitize_ident(&fixture.id);
        let _ = writeln!(out, "    run_test test_{fn_name}");
    }
    let _ = writeln!(out, "}}");
    out
}

/// Render a single `test_{id}()` function for a fixture.
#[allow(clippy::too_many_arguments)]
fn render_test_function(
    out: &mut String,
    fixture: &Fixture,
    binary_name: &str,
    subcommand: &str,
    static_cli_args: &[String],
    cli_flags: &std::collections::HashMap<String, String>,
    _args: &[crate::config::ArgMapping],
    field_resolver: &FieldResolver,
    e2e_config: &E2eConfig,
) {
    let fn_name = sanitize_ident(&fixture.id);
    let description = &fixture.description;

    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");

    let _ = writeln!(out, "test_{fn_name}() {{");
    let _ = writeln!(out, "    # {description}");

    // Resolve fixture-specific call config if provided, otherwise use defaults.
    let call_config = e2e_config.resolve_call(fixture.call.as_deref());

    // Build the CLI command using the resolved call config.
    let cmd_parts = build_cli_command(
        fixture,
        binary_name,
        subcommand,
        static_cli_args,
        cli_flags,
        &call_config.args,
    );

    if expects_error {
        let cmd = cmd_parts.join(" ");
        let _ = writeln!(out, "    if {cmd} >/dev/null 2>&1; then");
        let _ = writeln!(
            out,
            "        echo 'FAIL [error]: expected command to fail but it succeeded' >&2"
        );
        let _ = writeln!(out, "        return 1");
        let _ = writeln!(out, "    fi");
        let _ = writeln!(out, "}}");
        return;
    }

    // Check if any assertion will actually emit code (not be skipped).
    let has_active_assertions = fixture.assertions.iter().any(|a| {
        a.field
            .as_ref()
            .is_none_or(|f| f.is_empty() || field_resolver.is_valid_for_result(f))
    });

    // Capture output (only if there are active assertions that reference it).
    let cmd = cmd_parts.join(" ");
    if has_active_assertions {
        let _ = writeln!(out, "    local output");
        let _ = writeln!(out, "    output=$({cmd})");
    } else {
        let _ = writeln!(out, "    {cmd} >/dev/null");
    }
    let _ = writeln!(out);

    // Emit assertions.
    for assertion in &fixture.assertions {
        render_assertion(out, assertion, field_resolver);
    }

    let _ = writeln!(out, "}}");
}

/// Build the shell CLI invocation as a list of tokens.
///
/// Tokens are returned unquoted where safe (flag names) or single-quoted
/// (string values from the fixture).
fn build_cli_command(
    fixture: &Fixture,
    binary_name: &str,
    subcommand: &str,
    static_cli_args: &[String],
    cli_flags: &std::collections::HashMap<String, String>,
    args: &[crate::config::ArgMapping],
) -> Vec<String> {
    let mut parts: Vec<String> = vec![binary_name.to_string(), subcommand.to_string()];

    for arg in args {
        match arg.arg_type.as_str() {
            "mock_url" => {
                // Positional URL argument.
                parts.push(format!("\"${{MOCK_SERVER_URL}}/fixtures/{}\"", fixture.id));
            }
            "handle" => {
                // CLI manages its own engine; skip handle args.
            }
            _ => {
                // Check if there is a cli_flags mapping for this field.
                if let Some(flag) = cli_flags.get(&arg.field) {
                    let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
                    if let Some(val) = fixture.input.get(field) {
                        if !val.is_null() {
                            let val_str = json_value_to_shell_arg(val);
                            parts.push(flag.clone());
                            parts.push(val_str);
                        }
                    }
                }
            }
        }
    }

    // Append static CLI args last.
    for static_arg in static_cli_args {
        parts.push(static_arg.clone());
    }

    parts
}

/// Convert a JSON value to a shell argument string.
///
/// Strings are wrapped in single quotes with embedded single quotes escaped.
/// Numbers and booleans are emitted verbatim.
fn json_value_to_shell_arg(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::String(s) => format!("'{}'", escape_shell(s)),
        serde_json::Value::Bool(b) => b.to_string(),
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::Null => "''".to_string(),
        other => format!("'{}'", escape_shell(&other.to_string())),
    }
}

/// Convert a fixture field path to a jq expression.
///
/// A path like `metadata.title` becomes `.metadata.title`.
/// An array field like `links` becomes `.links`.
/// The pseudo-property `length` (also `count`, `size`) becomes `| length`
/// because jq uses pipe syntax for the `length` builtin.
fn field_to_jq_path(resolved: &str) -> String {
    // Check if the path ends with a length/count/size pseudo-property.
    // E.g., "pages.length" → ".pages | length"
    if let Some((prefix, suffix)) = resolved.rsplit_once('.') {
        if suffix == "length" || suffix == "count" || suffix == "size" {
            return format!(".{prefix} | length");
        }
    }
    // Handle bare "length" / "count" / "size" (top-level array).
    if resolved == "length" || resolved == "count" || resolved == "size" {
        return ". | length".to_string();
    }
    format!(".{resolved}")
}

/// Build a CLI command for a method_result assertion.
///
/// Maps method names to the appropriate tree-sitter-language-pack CLI commands.
/// The result is returned as a command string (not quoted) to be captured in a variable.
fn build_brew_method_call(method_name: &str, args: Option<&serde_json::Value>) -> String {
    match method_name {
        "root_child_count" => "tree_sitter_language_pack tree-root-child-count \"$output\"".to_string(),
        "root_node_type" => "tree_sitter_language_pack tree-root-node-type \"$output\"".to_string(),
        "named_children_count" => "tree_sitter_language_pack tree-named-children-count \"$output\"".to_string(),
        "has_error_nodes" => "tree_sitter_language_pack tree-has-error-nodes \"$output\"".to_string(),
        "error_count" | "tree_error_count" => "tree_sitter_language_pack tree-error-count \"$output\"".to_string(),
        "tree_to_sexp" => "tree_sitter_language_pack tree-to-sexp \"$output\"".to_string(),
        "contains_node_type" => {
            let node_type = args
                .and_then(|a| a.get("node_type"))
                .and_then(|v| v.as_str())
                .unwrap_or("");
            format!("tree_sitter_language_pack tree-contains-node-type \"$output\" '{node_type}'")
        }
        "find_nodes_by_type" => {
            let node_type = args
                .and_then(|a| a.get("node_type"))
                .and_then(|v| v.as_str())
                .unwrap_or("");
            format!("tree_sitter_language_pack tree-find-nodes-by-type \"$output\" '{node_type}'")
        }
        "run_query" => {
            let query_source = args
                .and_then(|a| a.get("query_source"))
                .and_then(|v| v.as_str())
                .unwrap_or("");
            let language = args
                .and_then(|a| a.get("language"))
                .and_then(|v| v.as_str())
                .unwrap_or("");
            format!("tree_sitter_language_pack tree-run-query \"$output\" '{language}' '{query_source}'")
        }
        _ => {
            if let Some(args_val) = args {
                let arg_str = args_val
                    .as_object()
                    .map(|obj| {
                        obj.iter()
                            .map(|(k, v)| {
                                let val_str = match v {
                                    serde_json::Value::String(s) => format!("'{}'", escape_shell(s)),
                                    other => other.to_string(),
                                };
                                format!("--{k} {val_str}")
                            })
                            .collect::<Vec<_>>()
                            .join(" ")
                    })
                    .unwrap_or_default();
                format!("tree_sitter_language_pack {method_name} \"$output\" {arg_str}")
            } else {
                format!("tree_sitter_language_pack {method_name} \"$output\"")
            }
        }
    }
}

/// Render a single assertion as shell code.
fn render_assertion(out: &mut String, assertion: &Assertion, field_resolver: &FieldResolver) {
    // Skip assertions on fields not available on the result type.
    if let Some(f) = &assertion.field {
        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
            let _ = writeln!(out, "    # skipped: field '{f}' not available on result type");
            return;
        }
    }

    match assertion.assertion_type.as_str() {
        "equals" => {
            if let Some(field) = &assertion.field {
                if let Some(expected) = &assertion.value {
                    let resolved = field_resolver.resolve(field);
                    let jq_path = field_to_jq_path(resolved);
                    let expected_str = json_value_to_shell_string(expected);
                    let safe_field = sanitize_ident(field);
                    let _ = writeln!(out, "    local val_{safe_field}");
                    let _ = writeln!(out, "    val_{safe_field}=$(echo \"$output\" | jq -r '{jq_path}')");
                    let _ = writeln!(
                        out,
                        "    assert_equals \"$val_{safe_field}\" '{expected_str}' '{field}'"
                    );
                }
            }
        }
        "contains" => {
            if let Some(field) = &assertion.field {
                if let Some(expected) = &assertion.value {
                    let resolved = field_resolver.resolve(field);
                    let jq_path = field_to_jq_path(resolved);
                    let expected_str = json_value_to_shell_string(expected);
                    let safe_field = sanitize_ident(field);
                    let _ = writeln!(out, "    local val_{safe_field}");
                    let _ = writeln!(out, "    val_{safe_field}=$(echo \"$output\" | jq -r '{jq_path}')");
                    let _ = writeln!(
                        out,
                        "    assert_contains \"$val_{safe_field}\" '{expected_str}' '{field}'"
                    );
                }
            }
        }
        "not_empty" | "tree_not_null" => {
            if let Some(field) = &assertion.field {
                let resolved = field_resolver.resolve(field);
                let jq_path = field_to_jq_path(resolved);
                let safe_field = sanitize_ident(field);
                let _ = writeln!(out, "    local val_{safe_field}");
                let _ = writeln!(out, "    val_{safe_field}=$(echo \"$output\" | jq -r '{jq_path}')");
                let _ = writeln!(out, "    assert_not_empty \"$val_{safe_field}\" '{field}'");
            }
        }
        "count_min" | "root_child_count_min" => {
            if let Some(field) = &assertion.field {
                if let Some(val) = &assertion.value {
                    if let Some(min) = val.as_u64() {
                        let resolved = field_resolver.resolve(field);
                        let jq_path = field_to_jq_path(resolved);
                        let safe_field = sanitize_ident(field);
                        let _ = writeln!(out, "    local count_{safe_field}");
                        let _ = writeln!(
                            out,
                            "    count_{safe_field}=$(echo \"$output\" | jq '{jq_path} | length')"
                        );
                        let _ = writeln!(out, "    assert_count_min \"$count_{safe_field}\" {min} '{field}'");
                    }
                }
            }
        }
        "greater_than" => {
            if let Some(field) = &assertion.field {
                if let Some(val) = &assertion.value {
                    let resolved = field_resolver.resolve(field);
                    let jq_path = field_to_jq_path(resolved);
                    let threshold = json_value_to_shell_string(val);
                    let safe_field = sanitize_ident(field);
                    let _ = writeln!(out, "    local val_{safe_field}");
                    let _ = writeln!(out, "    val_{safe_field}=$(echo \"$output\" | jq -r '{jq_path}')");
                    let _ = writeln!(
                        out,
                        "    assert_greater_than \"$val_{safe_field}\" '{threshold}' '{field}'"
                    );
                }
            }
        }
        "greater_than_or_equal" => {
            if let Some(field) = &assertion.field {
                if let Some(val) = &assertion.value {
                    let resolved = field_resolver.resolve(field);
                    let jq_path = field_to_jq_path(resolved);
                    let threshold = json_value_to_shell_string(val);
                    let safe_field = sanitize_ident(field);
                    let _ = writeln!(out, "    local val_{safe_field}");
                    let _ = writeln!(out, "    val_{safe_field}=$(echo \"$output\" | jq -r '{jq_path}')");
                    let _ = writeln!(
                        out,
                        "    assert_greater_than_or_equal \"$val_{safe_field}\" '{threshold}' '{field}'"
                    );
                }
            }
        }
        "contains_all" => {
            if let Some(field) = &assertion.field {
                if let Some(serde_json::Value::Array(items)) = &assertion.value {
                    let resolved = field_resolver.resolve(field);
                    let jq_path = field_to_jq_path(resolved);
                    let safe_field = sanitize_ident(field);
                    let _ = writeln!(out, "    local val_{safe_field}");
                    let _ = writeln!(out, "    val_{safe_field}=$(echo \"$output\" | jq -r '{jq_path}')");
                    for (index, item) in items.iter().enumerate() {
                        let item_str = json_value_to_shell_string(item);
                        let _ = writeln!(
                            out,
                            "    assert_contains \"$val_{safe_field}\" '{item_str}' '{field}[{index}]'"
                        );
                    }
                }
            }
        }
        "is_empty" => {
            if let Some(field) = &assertion.field {
                let resolved = field_resolver.resolve(field);
                let jq_path = field_to_jq_path(resolved);
                let safe_field = sanitize_ident(field);
                let _ = writeln!(out, "    local val_{safe_field}");
                let _ = writeln!(out, "    val_{safe_field}=$(echo \"$output\" | jq -r '{jq_path}')");
                let _ = writeln!(out, "    assert_is_empty \"$val_{safe_field}\" '{field}'");
            }
        }
        "less_than" => {
            if let Some(field) = &assertion.field {
                if let Some(val) = &assertion.value {
                    let resolved = field_resolver.resolve(field);
                    let jq_path = field_to_jq_path(resolved);
                    let threshold = json_value_to_shell_string(val);
                    let safe_field = sanitize_ident(field);
                    let _ = writeln!(out, "    local val_{safe_field}");
                    let _ = writeln!(out, "    val_{safe_field}=$(echo \"$output\" | jq -r '{jq_path}')");
                    let _ = writeln!(
                        out,
                        "    assert_less_than \"$val_{safe_field}\" '{threshold}' '{field}'"
                    );
                }
            }
        }
        "not_contains" => {
            if let Some(field) = &assertion.field {
                if let Some(expected) = &assertion.value {
                    let resolved = field_resolver.resolve(field);
                    let jq_path = field_to_jq_path(resolved);
                    let expected_str = json_value_to_shell_string(expected);
                    let safe_field = sanitize_ident(field);
                    let _ = writeln!(out, "    local val_{safe_field}");
                    let _ = writeln!(out, "    val_{safe_field}=$(echo \"$output\" | jq -r '{jq_path}')");
                    let _ = writeln!(
                        out,
                        "    assert_not_contains \"$val_{safe_field}\" '{expected_str}' '{field}'"
                    );
                }
            }
        }
        "count_equals" => {
            if let Some(field) = &assertion.field {
                if let Some(val) = &assertion.value {
                    if let Some(n) = val.as_u64() {
                        let resolved = field_resolver.resolve(field);
                        let jq_path = field_to_jq_path(resolved);
                        let safe_field = sanitize_ident(field);
                        let _ = writeln!(out, "    local count_{safe_field}");
                        let _ = writeln!(
                            out,
                            "    count_{safe_field}=$(echo \"$output\" | jq '{jq_path} | length')"
                        );
                        let _ = writeln!(out, "    [ \"$count_{safe_field}\" -eq {n} ] || exit 1");
                    }
                }
            }
        }
        "is_true" => {
            if let Some(field) = &assertion.field {
                let resolved = field_resolver.resolve(field);
                let jq_path = field_to_jq_path(resolved);
                let safe_field = sanitize_ident(field);
                let _ = writeln!(out, "    local val_{safe_field}");
                let _ = writeln!(out, "    val_{safe_field}=$(echo \"$output\" | jq -r '{jq_path}')");
                let _ = writeln!(out, "    [ \"$val_{safe_field}\" = \"true\" ] || exit 1");
            }
        }
        "is_false" => {
            if let Some(field) = &assertion.field {
                let resolved = field_resolver.resolve(field);
                let jq_path = field_to_jq_path(resolved);
                let safe_field = sanitize_ident(field);
                let _ = writeln!(out, "    local val_{safe_field}");
                let _ = writeln!(out, "    val_{safe_field}=$(echo \"$output\" | jq -r '{jq_path}')");
                let _ = writeln!(out, "    [ \"$val_{safe_field}\" = \"false\" ] || exit 1");
            }
        }
        "less_than_or_equal" => {
            if let Some(field) = &assertion.field {
                if let Some(val) = &assertion.value {
                    let resolved = field_resolver.resolve(field);
                    let jq_path = field_to_jq_path(resolved);
                    let threshold = json_value_to_shell_string(val);
                    let safe_field = sanitize_ident(field);
                    let _ = writeln!(out, "    local val_{safe_field}");
                    let _ = writeln!(out, "    val_{safe_field}=$(echo \"$output\" | jq -r '{jq_path}')");
                    let _ = writeln!(
                        out,
                        "    assert_less_than_or_equal \"$val_{safe_field}\" '{threshold}' '{field}'"
                    );
                }
            }
        }
        "method_result" => {
            if let Some(method_name) = &assertion.method {
                let check = assertion.check.as_deref().unwrap_or("is_true");
                let cmd = build_brew_method_call(method_name, assertion.args.as_ref());
                // For is_error, skip capturing the result — just run the command and check
                // the exit code so we don't execute the method twice.
                if check == "is_error" {
                    let _ = writeln!(out, "    if {cmd} >/dev/null 2>&1; then");
                    let _ = writeln!(
                        out,
                        "        echo 'FAIL [method_result]: expected method to raise error but it succeeded' >&2"
                    );
                    let _ = writeln!(out, "        return 1");
                    let _ = writeln!(out, "    fi");
                } else {
                    let method_var = format!("method_result_{}", sanitize_ident(method_name));
                    let _ = writeln!(out, "    local {method_var}");
                    let _ = writeln!(out, "    {method_var}=$({cmd})");
                    match check {
                        "equals" => {
                            if let Some(val) = &assertion.value {
                                let expected = json_value_to_shell_string(val);
                                let _ = writeln!(out, "    [ \"${method_var}\" = '{expected}' ] || exit 1");
                            }
                        }
                        "is_true" => {
                            let _ = writeln!(out, "    [ \"${method_var}\" = \"true\" ] || exit 1");
                        }
                        "is_false" => {
                            let _ = writeln!(out, "    [ \"${method_var}\" = \"false\" ] || exit 1");
                        }
                        "greater_than_or_equal" => {
                            if let Some(val) = &assertion.value {
                                if let Some(n) = val.as_u64() {
                                    let _ = writeln!(out, "    [ \"${method_var}\" -ge {n} ] || exit 1");
                                }
                            }
                        }
                        "count_min" => {
                            if let Some(val) = &assertion.value {
                                if let Some(n) = val.as_u64() {
                                    let _ = writeln!(
                                        out,
                                        "    local count_from_method_result=$(echo \"${method_var}\" | jq 'length')"
                                    );
                                    let _ = writeln!(out, "    [ \"$count_from_method_result\" -ge {n} ] || exit 1");
                                }
                            }
                        }
                        "contains" => {
                            if let Some(val) = &assertion.value {
                                let expected = json_value_to_shell_string(val);
                                let _ = writeln!(out, "    [[ \"${method_var}\" == *'{expected}'* ]] || exit 1");
                            }
                        }
                        other_check => {
                            panic!("Brew e2e generator: unsupported method_result check type: {other_check}");
                        }
                    }
                }
            } else {
                panic!("method_result assertion missing 'method' field");
            }
        }
        "min_length" => {
            if let Some(field) = &assertion.field {
                if let Some(val) = &assertion.value {
                    if let Some(n) = val.as_u64() {
                        let resolved = field_resolver.resolve(field);
                        let jq_path = field_to_jq_path(resolved);
                        let safe_field = sanitize_ident(field);
                        let _ = writeln!(out, "    local val_{safe_field}");
                        let _ = writeln!(out, "    val_{safe_field}=$(echo \"$output\" | jq -r '{jq_path}')");
                        let _ = writeln!(
                            out,
                            "    [ \"${{#val_{safe_field}}}\" -ge {n} ] || {{ echo \"FAIL [{field}]: expected length >= {n}\" >&2; return 1; }}"
                        );
                    }
                }
            }
        }
        "max_length" => {
            if let Some(field) = &assertion.field {
                if let Some(val) = &assertion.value {
                    if let Some(n) = val.as_u64() {
                        let resolved = field_resolver.resolve(field);
                        let jq_path = field_to_jq_path(resolved);
                        let safe_field = sanitize_ident(field);
                        let _ = writeln!(out, "    local val_{safe_field}");
                        let _ = writeln!(out, "    val_{safe_field}=$(echo \"$output\" | jq -r '{jq_path}')");
                        let _ = writeln!(
                            out,
                            "    [ \"${{#val_{safe_field}}}\" -le {n} ] || {{ echo \"FAIL [{field}]: expected length <= {n}\" >&2; return 1; }}"
                        );
                    }
                }
            }
        }
        "ends_with" => {
            if let Some(field) = &assertion.field {
                if let Some(expected) = &assertion.value {
                    let resolved = field_resolver.resolve(field);
                    let jq_path = field_to_jq_path(resolved);
                    let expected_str = json_value_to_shell_string(expected);
                    let safe_field = sanitize_ident(field);
                    let _ = writeln!(out, "    local val_{safe_field}");
                    let _ = writeln!(out, "    val_{safe_field}=$(echo \"$output\" | jq -r '{jq_path}')");
                    let _ = writeln!(
                        out,
                        "    [[ \"$val_{safe_field}\" == *'{expected_str}' ]] || {{ echo \"FAIL [{field}]: expected to end with '{expected_str}'\" >&2; return 1; }}"
                    );
                }
            }
        }
        "matches_regex" => {
            if let Some(field) = &assertion.field {
                if let Some(expected) = &assertion.value {
                    if let Some(pattern) = expected.as_str() {
                        let resolved = field_resolver.resolve(field);
                        let jq_path = field_to_jq_path(resolved);
                        let safe_field = sanitize_ident(field);
                        let _ = writeln!(out, "    local val_{safe_field}");
                        let _ = writeln!(out, "    val_{safe_field}=$(echo \"$output\" | jq -r '{jq_path}')");
                        let _ = writeln!(
                            out,
                            "    [[ \"$val_{safe_field}\" =~ {pattern} ]] || {{ echo \"FAIL [{field}]: expected to match /{pattern}/\" >&2; return 1; }}"
                        );
                    }
                }
            }
        }
        "not_error" => {
            // No-op: reaching this point means the call succeeded.
        }
        "error" => {
            // Handled at the function level (early return above).
        }
        other => {
            panic!("Brew e2e generator: unsupported assertion type: {other}");
        }
    }
}

/// Convert a JSON value to a plain string suitable for use in shell assertions.
///
/// Returns the bare string content (no quotes) — callers wrap in single quotes.
fn json_value_to_shell_string(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::String(s) => escape_shell(s),
        serde_json::Value::Bool(b) => b.to_string(),
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::Null => String::new(),
        other => escape_shell(&other.to_string()),
    }
}