openapi-forge-cli 0.1.24

OpenAPI Forge command-line interface
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
//! `forge` CLI.
//!
//! Two configuration modes:
//!
//! - **Project mode** — read `forge.toml` from the project directory.
//!   Supports per-plugin config blocks and is the recommended layout
//!   for repeatable runs.
//! - **Config-less mode** — pass `--input`, `--transformer`,
//!   `--generator`, and `--out` directly on the command line. Useful
//!   for one-off runs and shell scripting; per-plugin config defaults
//!   to `{}`. Triggered when `--input` is set.
//!
//! Two input forms (project mode supports both via `forge.toml`;
//! config-less mode supports spec only):
//!
//! - spec — parse an OpenAPI 3.0 JSON document through `forge-parser`.
//! - ir — load a canonical `forge_ir::Ir` directly (debugging escape
//!   hatch; bypasses the parser). Only reachable via
//!   `[input] ir = "..."` in `forge.toml`.

use std::path::{Path, PathBuf};

use clap::{Parser, Subcommand};
use forge_host::{Engine, Plugin};
use forge_pipeline::{run as run_pipeline, PipelineConfig, PipelineError};
use serde::Deserialize;

mod oci;

#[derive(Debug, Parser)]
#[command(name = "forge", version, about = "OpenAPI Forge")]
struct Cli {
    #[command(subcommand)]
    command: Cmd,
}

#[derive(Debug, Subcommand)]
enum Cmd {
    /// Run the configured pipeline.
    ///
    /// Without `--input`, reads `forge.toml` from `<project>` (project
    /// mode). With `--input`, builds the config from CLI flags and
    /// ignores `forge.toml` (config-less mode). The pre-parsed IR input
    /// form is reachable via `[input] ir = "..."` in `forge.toml`.
    Generate {
        /// Project directory containing `forge.toml`. Used as the path
        /// resolution base in project mode. Ignored in config-less mode.
        #[arg(default_value = ".")]
        project: PathBuf,
        /// OpenAPI 3.0 JSON spec. Triggers config-less mode.
        #[arg(short = 'i', long = "input", value_name = "SPEC")]
        input: Option<PathBuf>,
        /// Transformer plugin (`.wasm` path or OCI ref). Repeat to chain.
        /// Config-less mode only.
        #[arg(long = "transformer", value_name = "REF")]
        transformer: Vec<String>,
        /// Generator plugin (`.wasm` path or OCI ref). Required in
        /// config-less mode.
        #[arg(long = "generator", value_name = "REF")]
        generator: Option<String>,
        /// Output directory. Required in config-less mode; overrides
        /// `[output] dir` from `forge.toml` in project mode.
        #[arg(short = 'o', long = "out")]
        out: Option<PathBuf>,
    },
    /// Print the version of the IR contract this CLI was built against.
    IrVersion,
}

#[derive(Debug, Deserialize)]
struct Project {
    input: Input,
    #[serde(default)]
    transformers: Vec<PluginRef>,
    generator: PluginRef,
    output: Output,
    #[serde(default)]
    limits: LimitsSection,
    #[serde(default)]
    hooks: HooksSection,
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum Input {
    /// Parse an OpenAPI 3.0 JSON document through `forge-parser`.
    Spec { spec: PathBuf },
    /// Load a canonical `forge_ir::Ir` JSON directly. Bypasses the parser
    /// — useful when iterating on transformers/generators without a real
    /// spec.
    Ir { ir: PathBuf },
}

#[derive(Debug, Deserialize)]
struct PluginRef {
    #[serde(flatten)]
    source: PluginSource,
    /// Plugin-specific JSON-shaped config. Serialized to JSON and handed
    /// to the plugin as the `config` argument.
    #[serde(default = "empty_config")]
    config: serde_json::Value,
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum PluginSource {
    /// `.wasm` component path, relative to the project directory.
    Wasm { wasm: PathBuf },
    /// OCI reference, e.g. `ghcr.io/org/plugin:1.0.0` or
    /// `registry.example/repo@sha256:...`. Pulled lazily on
    /// `forge generate` and cached under the user's XDG cache dir.
    Oci { oci: String },
}

fn empty_config() -> serde_json::Value {
    serde_json::json!({})
}

#[derive(Debug, Deserialize)]
struct Output {
    dir: PathBuf,
}

/// `[limits]` section: per-stage-kind overrides for the WASM sandbox
/// limits. Every field is optional; anything unset keeps the built-in
/// default from [`forge_host::Limits`]. Unknown keys are rejected so a
/// typo'd limit fails the run instead of silently keeping the default.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct LimitsSection {
    #[serde(default)]
    transformer: LimitOverrides,
    #[serde(default)]
    generator: LimitOverrides,
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct LimitOverrides {
    fuel: Option<u64>,
    memory_bytes: Option<usize>,
    wall_clock_ms: Option<u64>,
    /// Output caps only apply to the generator stage; transformers
    /// return IR, not files.
    output_files_max: Option<u32>,
    output_total_bytes_max: Option<u64>,
    output_per_file_bytes_max: Option<u64>,
}

impl LimitOverrides {
    fn apply(&self, mut base: forge_host::Limits) -> forge_host::Limits {
        if let Some(v) = self.fuel {
            base.fuel = v;
        }
        if let Some(v) = self.memory_bytes {
            base.memory_bytes = v;
        }
        if let Some(v) = self.wall_clock_ms {
            base.wall_clock_ms = v;
        }
        if let Some(v) = self.output_files_max {
            base.output_files_max = v;
        }
        if let Some(v) = self.output_total_bytes_max {
            base.output_total_bytes_max = v;
        }
        if let Some(v) = self.output_per_file_bytes_max {
            base.output_per_file_bytes_max = v;
        }
        base
    }
}

/// `[hooks]` section: commands to run at lifecycle points. Currently
/// only `post_generate`, which runs once all generated files have been
/// written to the output directory — handy for invoking formatters
/// (`prettier --write .`, `cargo fmt`, ...) over the output. Commands
/// run in order, with the output directory as their working directory,
/// and the first non-zero exit aborts the run. Unknown keys are rejected
/// so a typo fails the run instead of silently doing nothing.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct HooksSection {
    #[serde(default)]
    post_generate: Vec<Hook>,
}

/// A single hook entry. Either a bare command (string or argv array) or
/// a table that wraps a command with per-hook options:
///
/// ```toml
/// post_generate = [
///   "cargo fmt",                                          # bare, shell form
///   ["prettier", "--write", "."],                        # bare, exec form
///   { cmd = "optional-linter", continue_on_error = true } # table form
/// ]
/// ```
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum Hook {
    Bare(HookCmd),
    Table(HookTable),
}

/// Table form of a hook: a command plus per-hook options. Unknown keys
/// are rejected so a typo fails the run instead of silently doing
/// nothing.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct HookTable {
    cmd: HookCmd,
    /// When true, a non-zero exit (or a failure to start) logs a warning
    /// and continues to the next hook instead of aborting the run.
    #[serde(default)]
    continue_on_error: bool,
}

/// The command part of a hook, in one of two forms (cf. Docker's shell
/// vs exec form):
///
/// - **shell form** — a string run through the platform shell
///   (`"eslint --fix && prettier --write ."`). Globs, pipes, `&&`,
///   redirection and `$VAR` expansion all work.
/// - **exec form** — an argv array run directly with no shell
///   (`["cargo", "fmt"]`). Arguments pass through literally (no
///   word-splitting or glob/var expansion) and no shell is required.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum HookCmd {
    Shell(String),
    Exec(Vec<String>),
}

#[derive(Debug, thiserror::Error)]
enum CliError {
    #[error("failed to read {path}: {source}")]
    Read {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
    #[error("failed to parse forge.toml: {0}")]
    Toml(#[from] toml::de::Error),
    #[error("failed to parse {path} as IR JSON: {source}")]
    BadIr {
        path: PathBuf,
        #[source]
        source: serde_json::Error,
    },
    #[error("parser failed: {0}")]
    Parse(#[from] forge_parser::ParseError),
    #[error("parser produced {count} error-severity diagnostic(s); halting")]
    ParseDiagnostics { count: usize },
    #[error("engine init: {0}")]
    Engine(String),
    #[error("plugin load ({origin}): {reason}")]
    PluginLoad { origin: String, reason: String },
    #[error("oci pull ({reference}): {source}")]
    Oci {
        reference: String,
        #[source]
        source: oci::OciError,
    },
    #[error("plugin {plugin}: invalid config_schema(): {reason}")]
    ConfigSchemaInvalid { plugin: String, reason: String },
    #[error("plugin {plugin}: config validation failed:\n  - {}", errors.join("\n  - "))]
    ConfigValidation { plugin: String, errors: Vec<String> },
    #[error("pipeline: {0}")]
    Pipeline(#[from] forge_pipeline::PipelineError),
    #[error("output guard: {0}")]
    Output(#[from] forge_host::filesystem::OutputError),
    #[error("io: {0}")]
    Io(#[from] std::io::Error),
    #[error("--generator is required in config-less mode (when --input is set)")]
    MissingGenerator,
    #[error("--out is required in config-less mode (when --input is set)")]
    MissingOut,
    #[error("post_generate hook could not start ({command}): {source}")]
    PostGenHookSpawn {
        command: String,
        #[source]
        source: std::io::Error,
    },
    #[error("post_generate hook failed (exit {code}): {command}")]
    PostGenHookFailed { command: String, code: String },
}

impl CliError {
    /// Process exit code for this error. Post-generate hook failures get
    /// their own code (3) so callers can tell "a hook failed" apart from
    /// "forge itself failed" (2) — generation succeeded and files are on
    /// disk in the hook case.
    fn exit_code(&self) -> i32 {
        match self {
            CliError::PostGenHookFailed { .. } | CliError::PostGenHookSpawn { .. } => 3,
            _ => 2,
        }
    }
}

fn main() {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
        )
        .with_writer(std::io::stderr)
        .init();

    let cli = Cli::parse();
    let result = match cli.command {
        Cmd::Generate {
            project,
            input,
            transformer,
            generator,
            out,
        } => match input {
            Some(spec) => {
                generate_from_args(spec, &transformer, generator.as_deref(), out.as_deref())
            }
            None => generate_from_project(&project, out.as_deref()),
        },
        Cmd::IrVersion => {
            println!("{}", env!("CARGO_PKG_VERSION"));
            Ok(())
        }
    };
    if let Err(e) = result {
        eprintln!("error: {e}");
        let mut src = std::error::Error::source(&e);
        while let Some(err) = src {
            eprintln!("  caused by: {err}");
            src = err.source();
        }
        std::process::exit(e.exit_code());
    }
}

/// Project mode: read `forge.toml` from `project`, then run.
fn generate_from_project(project: &Path, out_override: Option<&Path>) -> Result<(), CliError> {
    let manifest_path = project.join("forge.toml");
    let manifest_str = std::fs::read_to_string(&manifest_path).map_err(|e| CliError::Read {
        path: manifest_path.clone(),
        source: e,
    })?;
    let cfg: Project = toml::from_str(&manifest_str)?;
    run_generate(project, &cfg, out_override)
}

/// Config-less mode: build a `Project` from CLI flags. Plugin paths
/// are resolved relative to the current working directory.
fn generate_from_args(
    spec: PathBuf,
    transformer: &[String],
    generator: Option<&str>,
    out_override: Option<&Path>,
) -> Result<(), CliError> {
    let generator = generator.ok_or(CliError::MissingGenerator)?;
    let out_dir = out_override.ok_or(CliError::MissingOut)?.to_path_buf();

    let cfg = Project {
        input: Input::Spec { spec },
        transformers: transformer
            .iter()
            .map(|s| PluginRef {
                source: parse_plugin_arg(s),
                config: empty_config(),
            })
            .collect(),
        generator: PluginRef {
            source: parse_plugin_arg(generator),
            config: empty_config(),
        },
        output: Output {
            dir: out_dir.clone(),
        },
        limits: LimitsSection::default(),
        hooks: HooksSection::default(),
    };

    // In config-less mode, paths in CLI args are relative to CWD; pass
    // `.` as the resolution base. The output dir is already absolute or
    // CWD-relative, so we forward it as the override too.
    run_generate(Path::new("."), &cfg, Some(&out_dir))
}

/// `s` is either a `.wasm` path on disk or an OCI reference. Heuristic:
/// if it ends in `.wasm` or names an existing file, treat as a path;
/// otherwise treat as an OCI ref. The OCI puller will surface a parse
/// error if the string is neither.
fn parse_plugin_arg(s: &str) -> PluginSource {
    let path = Path::new(s);
    let looks_like_wasm = s.ends_with(".wasm") || path.is_file();
    if looks_like_wasm {
        PluginSource::Wasm {
            wasm: path.to_path_buf(),
        }
    } else {
        PluginSource::Oci { oci: s.to_owned() }
    }
}

fn run_generate(
    project: &Path,
    cfg: &Project,
    out_override: Option<&Path>,
) -> Result<(), CliError> {
    let ir = load_ir(project, &cfg.input)?;

    let engine = build_engine()?;

    let mut transformers: Vec<Plugin> = Vec::with_capacity(cfg.transformers.len());
    let mut configs: Vec<String> = Vec::with_capacity(cfg.transformers.len() + 1);
    for t in &cfg.transformers {
        let (bytes, label) = load_plugin_bytes(project, &t.source)?;
        let plugin =
            Plugin::load_transformer(&engine, &bytes).map_err(|e| CliError::PluginLoad {
                origin: label.clone(),
                reason: e.to_string(),
            })?;
        validate_config(plugin.config_schema(), &t.config, &label)?;
        transformers.push(plugin);
        configs.push(t.config.to_string());
    }

    let (gen_bytes, gen_label) = load_plugin_bytes(project, &cfg.generator.source)?;
    let generator =
        Plugin::load_generator(&engine, &gen_bytes).map_err(|e| CliError::PluginLoad {
            origin: gen_label.clone(),
            reason: e.to_string(),
        })?;
    validate_config(generator.config_schema(), &cfg.generator.config, &gen_label)?;
    configs.push(cfg.generator.config.to_string());

    let generator_limits = cfg.limits.generator.apply(forge_host::Limits::generator());
    let pipe_cfg = PipelineConfig {
        configs,
        transformer_limits: cfg
            .limits
            .transformer
            .apply(forge_host::Limits::transformer()),
        generator_limits,
        ..Default::default()
    };
    let xforms: Vec<&Plugin> = transformers.iter().collect();
    let out = match run_pipeline(&engine, ir, &xforms, &generator, &pipe_cfg) {
        Ok(out) => out,
        // A stage that halts the pipeline with error-severity diagnostics
        // carries them out; print each one (same rendering as parse-time
        // diagnostics) so the failure says *what* was wrong, not just how
        // many things were.
        Err(e) => {
            if let PipelineError::StageErrors { diagnostics, .. } = &e {
                print_diagnostics(diagnostics);
            }
            return Err(e.into());
        }
    };

    // Validate output before writing. Use the generator's limits to seed
    // the caps; this matches what the host enforced inside the WASM call.
    let caps = forge_host::filesystem::Caps::from_limits(generator_limits);
    forge_host::filesystem::validate_output(&out.generation.files, caps)?;

    let out_dir = out_override
        .map(|p| p.to_path_buf())
        .unwrap_or_else(|| project.join(&cfg.output.dir));
    std::fs::create_dir_all(&out_dir)?;
    for f in &out.generation.files {
        let target = out_dir.join(&f.path);
        if let Some(parent) = target.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(&target, &f.content)?;
    }

    println!(
        "wrote {} file(s) to {} ({} diagnostic(s))",
        out.generation.files.len(),
        out_dir.display(),
        out.diagnostics.len(),
    );

    run_post_generate_hooks(&cfg.hooks, &out_dir)?;
    Ok(())
}

impl Hook {
    /// The command to run, regardless of bare vs table form.
    fn cmd(&self) -> &HookCmd {
        match self {
            Hook::Bare(c) => c,
            Hook::Table(t) => &t.cmd,
        }
    }

    /// Whether a failure of this hook should be tolerated. Only the table
    /// form can opt in; bare hooks always abort the run on failure.
    fn continue_on_error(&self) -> bool {
        match self {
            Hook::Bare(_) => false,
            Hook::Table(t) => t.continue_on_error,
        }
    }
}

impl HookCmd {
    /// A human-readable rendering of the command, used in log lines and
    /// error messages.
    fn label(&self) -> String {
        match self {
            HookCmd::Shell(s) => s.clone(),
            HookCmd::Exec(argv) => argv.join(" "),
        }
    }

    /// Build the process to spawn. Shell form goes through the platform
    /// shell; exec form runs the argv directly. Returns `None` for an
    /// empty exec array, which has no program to run.
    fn command(&self) -> Option<std::process::Command> {
        match self {
            HookCmd::Shell(s) => Some(shell_command(s)),
            HookCmd::Exec(argv) => {
                let (program, args) = argv.split_first()?;
                let mut c = std::process::Command::new(program);
                c.args(args);
                Some(c)
            }
        }
    }
}

/// Run `[hooks] post_generate` commands in order, once generated files
/// are on disk. Each command runs with the output directory as its
/// working directory and inherits stdio, so a formatter's output reaches
/// the user. `FORGE_OUT_DIR` is exported for commands that need the path
/// explicitly. The first command to exit non-zero aborts the run.
fn run_post_generate_hooks(hooks: &HooksSection, out_dir: &Path) -> Result<(), CliError> {
    for hook in &hooks.post_generate {
        let label = hook.cmd().label();
        // An empty exec array is malformed config, not a runtime failure;
        // reject it regardless of continue_on_error.
        let mut command = hook
            .cmd()
            .command()
            .ok_or_else(|| CliError::PostGenHookFailed {
                command: "[]".to_owned(),
                code: "empty command".to_owned(),
            })?;
        println!("running post_generate hook: {label}");
        let outcome = command
            .current_dir(out_dir)
            .env("FORGE_OUT_DIR", out_dir)
            .status();
        match outcome {
            Ok(status) if status.success() => {}
            Ok(status) => {
                let code = status
                    .code()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "signal".to_owned());
                if hook.continue_on_error() {
                    eprintln!(
                        "warning: post_generate hook failed (exit {code}), continuing: {label}"
                    );
                } else {
                    return Err(CliError::PostGenHookFailed {
                        command: label,
                        code,
                    });
                }
            }
            Err(source) => {
                if hook.continue_on_error() {
                    eprintln!(
                        "warning: post_generate hook could not start ({label}), continuing: {source}"
                    );
                } else {
                    return Err(CliError::PostGenHookSpawn {
                        command: label,
                        source,
                    });
                }
            }
        }
    }
    Ok(())
}

/// Build a shell invocation for a hook command line.
#[cfg(unix)]
fn shell_command(command: &str) -> std::process::Command {
    let mut c = std::process::Command::new("sh");
    c.arg("-c").arg(command);
    c
}

#[cfg(windows)]
fn shell_command(command: &str) -> std::process::Command {
    let mut c = std::process::Command::new("cmd");
    c.arg("/C").arg(command);
    c
}

/// Build the wasmtime engine, backed by an on-disk compilation cache so
/// plugin components aren't recompiled from scratch on every run (the
/// dominant per-invocation cost). The cache lives alongside the OCI plugin
/// store under the forge cache dir. If the cache directory can't be set up
/// (e.g. no resolvable cache dir), fall back to an uncached engine with a
/// warning rather than failing the run — caching is an optimisation, not a
/// correctness requirement.
fn build_engine() -> Result<Engine, CliError> {
    match oci::compiled_cache_dir() {
        Ok(dir) => match Engine::with_cache(&dir) {
            Ok(engine) => return Ok(engine),
            Err(e) => tracing::warn!(
                "compilation cache disabled ({e}); plugins will be recompiled each run"
            ),
        },
        Err(e) => tracing::warn!(
            "compilation cache disabled (no cache dir: {e}); plugins will be recompiled each run"
        ),
    }
    Engine::new().map_err(|e| CliError::Engine(e.to_string()))
}

/// Load the IR for the configured `[input]`, branching on whether the
/// project asks for a parsed spec or raw IR JSON.
fn load_ir(project: &Path, input: &Input) -> Result<forge_ir::Ir, CliError> {
    match input {
        Input::Spec { spec } => {
            let spec_path = project.join(spec);
            // `parse_path` enables the file-based $ref resolver so specs
            // that split components / paths across sibling files (the
            // common multi-document layout) work. The in-memory
            // `parse_str_with_file` rejects external $refs outright;
            // using it here would regress split-document support shipped
            // in #56.
            let out = forge_parser::parse_path(&spec_path)?;
            print_diagnostics(&out.diagnostics);
            let errs = out
                .diagnostics
                .iter()
                .filter(|d| d.severity == forge_ir::Severity::Error)
                .count();
            if errs > 0 {
                return Err(CliError::ParseDiagnostics { count: errs });
            }
            out.spec
                .ok_or(CliError::ParseDiagnostics { count: errs.max(1) })
        }
        Input::Ir { ir } => {
            let ir_path = project.join(ir);
            let ir_str = std::fs::read_to_string(&ir_path).map_err(|e| CliError::Read {
                path: ir_path.clone(),
                source: e,
            })?;
            serde_json::from_str(&ir_str).map_err(|e| CliError::BadIr {
                path: ir_path,
                source: e,
            })
        }
    }
}

/// Friendly label for diagnostics — the wasm filename, falling back to the
/// full path if it has no filename component.
fn plugin_label(path: &Path) -> String {
    path.file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| path.display().to_string())
}

/// Resolve a `PluginSource` to raw component bytes plus a human label
/// for diagnostics. Filesystem refs read from `project`-relative paths;
/// OCI refs are pulled (or served from cache) by `oci::fetch_to_bytes`.
fn load_plugin_bytes(project: &Path, source: &PluginSource) -> Result<(Vec<u8>, String), CliError> {
    match source {
        PluginSource::Wasm { wasm } => {
            let path = project.join(wasm);
            let bytes = std::fs::read(&path).map_err(|e| CliError::Read {
                path: path.clone(),
                source: e,
            })?;
            Ok((bytes, plugin_label(&path)))
        }
        PluginSource::Oci { oci } => {
            let bytes = oci::fetch_to_bytes(oci).map_err(|source| CliError::Oci {
                reference: oci.clone(),
                source,
            })?;
            Ok((bytes, oci.clone()))
        }
    }
}

/// Validate `config` against the JSON Schema returned by a plugin's
/// `config_schema()` export. The schema is parsed once per plugin load; on
/// validation failure we surface every error so the user can fix them in one
/// pass instead of re-running for each.
fn validate_config(
    schema_str: &str,
    config: &serde_json::Value,
    plugin_label: &str,
) -> Result<(), CliError> {
    let schema_value: serde_json::Value =
        serde_json::from_str(schema_str).map_err(|e| CliError::ConfigSchemaInvalid {
            plugin: plugin_label.to_owned(),
            reason: e.to_string(),
        })?;
    let validator =
        jsonschema::validator_for(&schema_value).map_err(|e| CliError::ConfigSchemaInvalid {
            plugin: plugin_label.to_owned(),
            reason: e.to_string(),
        })?;
    let errors: Vec<String> = validator
        .iter_errors(config)
        .map(|e| format!("{} (at {})", e, e.instance_path()))
        .collect();
    if !errors.is_empty() {
        return Err(CliError::ConfigValidation {
            plugin: plugin_label.to_owned(),
            errors,
        });
    }
    Ok(())
}

fn print_diagnostics(diagnostics: &[forge_ir::Diagnostic]) {
    use forge_ir::Severity;
    for d in diagnostics {
        let label = match d.severity {
            Severity::Error => "error",
            Severity::Warning => "warning",
            Severity::Info => "info",
            Severity::Hint => "hint",
        };
        let location = d
            .location
            .as_ref()
            .map(|l| {
                if let Some(file) = &l.file {
                    format!("{}#{}", file, l.pointer)
                } else {
                    l.pointer.clone()
                }
            })
            .unwrap_or_default();
        eprintln!("{label} [{}] {} ({})", d.code, d.message, location);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const BASE_MANIFEST: &str = r#"
[input]
spec = "openapi.json"

[generator]
wasm = "gen.wasm"

[output]
dir = "out"
"#;

    #[test]
    fn limits_section_defaults_when_absent() {
        let cfg: Project = toml::from_str(BASE_MANIFEST).unwrap();
        let defaults = forge_host::Limits::generator();
        let resolved = cfg.limits.generator.apply(defaults);
        assert_eq!(resolved.fuel, defaults.fuel);
        assert_eq!(
            resolved.output_total_bytes_max,
            defaults.output_total_bytes_max
        );
    }

    #[test]
    fn limits_overrides_apply_per_stage_kind() {
        let manifest = format!(
            "{BASE_MANIFEST}\n\
             [limits.transformer]\n\
             fuel = 9000000000\n\n\
             [limits.generator]\n\
             fuel = 100000000000\n\
             output_files_max = 50000\n\
             output_total_bytes_max = 1073741824\n\
             output_per_file_bytes_max = 134217728\n\
             memory_bytes = 1073741824\n\
             wall_clock_ms = 60000\n"
        );
        let cfg: Project = toml::from_str(&manifest).unwrap();

        let t = cfg
            .limits
            .transformer
            .apply(forge_host::Limits::transformer());
        assert_eq!(t.fuel, 9_000_000_000);
        // Untouched fields keep the built-in defaults.
        assert_eq!(
            t.memory_bytes,
            forge_host::Limits::transformer().memory_bytes
        );

        let g = cfg.limits.generator.apply(forge_host::Limits::generator());
        assert_eq!(g.fuel, 100_000_000_000);
        assert_eq!(g.output_files_max, 50_000);
        assert_eq!(g.output_total_bytes_max, 1024 * 1024 * 1024);
        assert_eq!(g.output_per_file_bytes_max, 128 * 1024 * 1024);
        assert_eq!(g.memory_bytes, 1024 * 1024 * 1024);
        assert_eq!(g.wall_clock_ms, 60_000);
    }

    #[test]
    fn limits_unknown_key_is_rejected() {
        let manifest = format!("{BASE_MANIFEST}\n[limits.generator]\nfeul = 1\n");
        let err = toml::from_str::<Project>(&manifest).unwrap_err();
        assert!(err.to_string().contains("feul"), "{err}");
    }

    #[test]
    fn hooks_default_to_empty_when_absent() {
        let cfg: Project = toml::from_str(BASE_MANIFEST).unwrap();
        assert!(cfg.hooks.post_generate.is_empty());
    }

    #[test]
    fn hooks_post_generate_parses_all_forms_in_order() {
        let manifest = format!(
            "{BASE_MANIFEST}\n\
             [hooks]\n\
             post_generate = [\
               \"prettier --write .\", \
               [\"cargo\", \"fmt\"], \
               {{ cmd = \"optional-linter\", continue_on_error = true }}\
             ]\n"
        );
        let cfg: Project = toml::from_str(&manifest).unwrap();
        let hooks = &cfg.hooks.post_generate;
        let labels: Vec<String> = hooks.iter().map(|h| h.cmd().label()).collect();
        assert_eq!(
            labels,
            vec!["prettier --write .", "cargo fmt", "optional-linter"]
        );
        assert!(matches!(hooks[0], Hook::Bare(HookCmd::Shell(_))));
        assert!(matches!(hooks[1], Hook::Bare(HookCmd::Exec(_))));
        assert!(matches!(hooks[2], Hook::Table(_)));
        // continue_on_error only the table form opts into.
        assert_eq!(
            hooks
                .iter()
                .map(Hook::continue_on_error)
                .collect::<Vec<_>>(),
            vec![false, false, true]
        );
    }

    #[test]
    fn hooks_table_continue_on_error_defaults_false() {
        let manifest = format!("{BASE_MANIFEST}\n[hooks]\npost_generate = [{{ cmd = \"x\" }}]\n");
        let cfg: Project = toml::from_str(&manifest).unwrap();
        assert!(!cfg.hooks.post_generate[0].continue_on_error());
    }

    #[test]
    fn hooks_table_supports_exec_form_cmd() {
        let manifest = format!(
            "{BASE_MANIFEST}\n[hooks]\npost_generate = [{{ cmd = [\"cargo\", \"fmt\"] }}]\n"
        );
        let cfg: Project = toml::from_str(&manifest).unwrap();
        assert!(matches!(
            cfg.hooks.post_generate[0],
            Hook::Table(HookTable {
                cmd: HookCmd::Exec(_),
                ..
            })
        ));
    }

    #[test]
    fn hooks_empty_exec_form_has_no_command() {
        // An empty argv array parses but produces no program to run; the
        // runner turns this into an error rather than spawning nothing.
        let cmd = HookCmd::Exec(vec![]);
        assert!(cmd.command().is_none());
    }

    #[test]
    fn hooks_unknown_key_is_rejected() {
        let manifest = format!("{BASE_MANIFEST}\n[hooks]\npost_gen = [\"x\"]\n");
        let err = toml::from_str::<Project>(&manifest).unwrap_err();
        assert!(err.to_string().contains("post_gen"), "{err}");
    }

    #[test]
    fn hooks_table_unknown_key_is_rejected() {
        // A typo'd option inside the table form must not be silently
        // ignored. (Reached through an untagged enum, so the message is
        // generic — the important property is that it errors.)
        let manifest = format!(
            "{BASE_MANIFEST}\n[hooks]\npost_generate = [{{ cmd = \"x\", contineu_on_error = true }}]\n"
        );
        assert!(toml::from_str::<Project>(&manifest).is_err());
    }
}