Skip to main content

warble_cli/
lib.rs

1//! `warble_cli` — the native host library behind the `warble` binary.
2//!
3//! Holds the pieces the binary and the golden integration tests share. The headline is
4//! [`compile_project_to_ir`]: the real front-end host path — read a Warble project's files, build
5//! the MDL [`ContextLoader`] over the bound wren project, and run the sans-IO core compiler with it
6//! injected. (The binary's `dispatch`/`render`/`manifest`/`eval` subcommands stay in `main.rs`.)
7//!
8//! [`blast_radius_for_project`] reuses the same project-resolution path to answer a `blast_radius`
9//! query without running a full compile — the host side of the `warble blast-radius` subcommand.
10//!
11//! Component *resolution* — turning a profile's `use: <id>` mount into a directory to read
12//! `component.yml`/steps from — is entirely a host concern (see [`ComponentSource`] /
13//! `resolve_component_dir`): the core compiler never touches a filesystem, it only ever sees the
14//! already-resolved `HashMap<String, ComponentFile>` this module builds.
15//!
16//! This is the crate that becomes the `warble` binary itself — end users install just this one.
17//! It links in both dispatcher back-ends (`warble-claude-code`, `warble-vercel`) and the
18//! `warble-mdl-context` binding directly; none of those three crates is a standalone tool, and
19//! `warble dispatch --target ...` simply selects which linked-in back-end handles the compiled
20//! IR.
21
22pub mod gate;
23pub mod hub_fetch;
24
25use std::collections::HashMap;
26use std::fmt;
27use std::path::{Path, PathBuf};
28
29use warble::{BindingFile, ComponentFile, ContextLoader, ProfileFile};
30use warble_claude_code::ir::SUPPORTED_IR_VERSION;
31use warble_mdl_context::{read_project_dir, read_raw_dir, MdlContext, RawSourceContext};
32
33/// The precedence class a [`ComponentSource`] belongs to. Precedence is a fixed rule *between*
34/// kinds — `Local` always outranks `Hub` — not derived from the order sources happen to be listed
35/// in. There is deliberately no rule *within* a kind: if the same component id is found in two
36/// sources of the same kind, `resolve_component_dir` treats that as ambiguous rather than
37/// guessing (e.g. "first in the list wins"), because nothing declares which of two equally-ranked
38/// sources should win.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum SourceKind {
41    /// A host- or product-specific component directory — e.g. a profile's own `components/`
42    /// override, or an external component library a consumer mounts alongside the Hub. Wins over
43    /// `Hub` whenever both define the same id.
44    Local,
45    /// The shared, generic Warble component library (this checkout's `hub/components`, or an
46    /// externally-supplied equivalent). The fallback tier: consulted only for ids no `Local`
47    /// source defines.
48    Hub,
49}
50
51impl fmt::Display for SourceKind {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        f.write_str(match self {
54            SourceKind::Local => "local",
55            SourceKind::Hub => "hub",
56        })
57    }
58}
59
60/// One explicitly-configured place a mounted component's files may live: `components_dir` is a
61/// directory whose immediate children are `<id>/component.yml` (+ its `steps/*`). The host builds
62/// the full ordered/kinded list up front (see [`compile_project_to_ir_with_sources`]) — resolution
63/// never discovers sources on its own (no ancestor/filesystem-root walk).
64#[derive(Debug, Clone)]
65pub struct ComponentSource {
66    pub kind: SourceKind,
67    pub components_dir: PathBuf,
68}
69
70impl ComponentSource {
71    pub fn local(components_dir: impl Into<PathBuf>) -> Self {
72        ComponentSource {
73            kind: SourceKind::Local,
74            components_dir: components_dir.into(),
75        }
76    }
77
78    pub fn hub(components_dir: impl Into<PathBuf>) -> Self {
79        ComponentSource {
80            kind: SourceKind::Hub,
81            components_dir: components_dir.into(),
82        }
83    }
84
85    fn candidate(&self, id: &str) -> PathBuf {
86        self.components_dir.join(id)
87    }
88}
89
90/// This checkout's own Hub component library — a fixed sibling of the `cli` crate's manifest dir,
91/// known at compile time (`CARGO_MANIFEST_DIR`), never discovered by walking the filesystem at
92/// runtime. This is what backs [`compile_project_to_ir`]'s default source list, so every in-repo
93/// example/eval profile keeps resolving its Hub-mounted components exactly as before.
94fn in_repo_hub_dir() -> PathBuf {
95    Path::new(env!("CARGO_MANIFEST_DIR"))
96        .join("..")
97        .join("hub")
98        .join("components")
99}
100
101/// The Hub source used when no `--hub-dir` override is given: this checkout's own
102/// `hub/components/` if it exists on disk, otherwise the per-user cache of the Hub release
103/// matching `hub_version` (or this binary's own version, when `hub_version` is `None`), fetching
104/// it over the network first if the cache doesn't already hold a verified copy.
105///
106/// The in-repo check comes first and is unconditional: an in-repo Hub directory always wins and
107/// never triggers a fetch, even when `hub_version` names a different version than this binary's
108/// own — "there is a Hub checked out right here" is decisive, not one input among several. This is also what keeps every in-repo example/eval profile (and the CLI's own
109/// integration tests) resolving offline, with no network access, when run from within this
110/// checkout.
111fn default_hub_source(hub_version: Option<&str>) -> Result<ComponentSource, String> {
112    let in_repo = in_repo_hub_dir();
113    if in_repo.is_dir() {
114        return Ok(ComponentSource::hub(in_repo));
115    }
116    let version = hub_version.unwrap_or(env!("CARGO_PKG_VERSION"));
117    let cached_dir = hub_fetch::ensure_cached_hub(version)?;
118    Ok(ComponentSource::hub(cached_dir))
119}
120
121/// The default two-source list used by [`compile_project_to_ir`]: the project's own `components/`
122/// (`Local`, highest precedence — lets a profile deliberately diverge from the Hub, e.g. an
123/// eval/demo substrate with intentionally different anatomy) plus the Hub (`Hub`, fallback) — see
124/// the crate's private `default_hub_source` helper for how the Hub source itself is resolved. A
125/// host mounting an *additional* local component library (e.g. a product-specific one, alongside
126/// the Hub) extends this list — see [`compile_project_to_ir_with_sources`].
127///
128/// Fallible since v0.7.0: resolving the Hub source can now require a network fetch (via that same
129/// `default_hub_source` helper), which can fail. Callers that previously relied on this being
130/// infallible need a `?` or `.expect(...)`.
131pub fn default_component_sources(project_dir: &Path) -> Result<Vec<ComponentSource>, String> {
132    default_component_sources_with_hub_version(project_dir, None)
133}
134
135/// Same as [`default_component_sources`], but lets the caller pick which Hub version to fetch
136/// when default resolution needs the network (i.e. no in-repo `hub/components` on disk). This is
137/// the seam the CLI's `--hub-version` flag threads through; `None` means "this binary's own
138/// version", the ordinary default.
139pub fn default_component_sources_with_hub_version(
140    project_dir: &Path,
141    hub_version: Option<&str>,
142) -> Result<Vec<ComponentSource>, String> {
143    Ok(vec![
144        ComponentSource::local(project_dir.join("components")),
145        default_hub_source(hub_version)?,
146    ])
147}
148
149/// Resolve where a mounted component's directory lives, against an explicit, ordered set of
150/// sources — never by walking the filesystem. Within the highest-precedence [`SourceKind`] that
151/// contains a match, exactly one source must define `id`; more than one is **ambiguous** (loud
152/// fail — no rule picks between equally-ranked sources) and zero across every source is
153/// **unresolved** (loud fail, listing everywhere it looked).
154fn resolve_component_dir(sources: &[ComponentSource], id: &str) -> Result<PathBuf, String> {
155    for kind in [SourceKind::Local, SourceKind::Hub] {
156        let matches: Vec<&ComponentSource> = sources
157            .iter()
158            .filter(|source| source.kind == kind)
159            .filter(|source| source.candidate(id).join("component.yml").is_file())
160            .collect();
161
162        match matches.as_slice() {
163            [] => continue,
164            [only] => return Ok(only.candidate(id)),
165            many => {
166                let dirs: Vec<String> = many
167                    .iter()
168                    .map(|s| s.candidate(id).display().to_string())
169                    .collect();
170                return Err(format!(
171                    "component '{id}' is ambiguous: found in {} '{kind}' sources ({}) — no \
172                     precedence rule distinguishes sources of the same kind",
173                    many.len(),
174                    dirs.join(", ")
175                ));
176            }
177        }
178    }
179
180    let searched: Vec<String> = sources
181        .iter()
182        .map(|s| format!("{} ({})", s.kind, s.candidate(id).display()))
183        .collect();
184    Err(format!(
185        "component '{id}' not found in any configured source: {}",
186        searched.join("; ")
187    ))
188}
189
190/// Turns a parsed `context/binding.yml` into the [`ContextLoader`] the compiler probes.
191///
192/// The counterpart of [`ComponentSource`] for context: components could already be supplied by a
193/// host, context could not. A host implements this to bind a semantic layer this checkout cannot
194/// read itself — one held by a service, for instance — without warble learning anything about it.
195///
196/// **A resolver is free to do no I/O at all, and `warble compile` must stay runnable offline and
197/// without credentials.** A host binding a remote layer is expected to resolve from a snapshot it
198/// pulled earlier, or to return a loader that declines the schema probes
199/// (`ContextLoader::can_answer`) rather than reaching for the network mid-compile.
200pub trait ContextResolver {
201    /// Build the loader for `binding`. `project_dir` is the Warble project directory, so a resolver
202    /// reading from disk can resolve a relative `binding.project` against it.
203    fn resolve(
204        &self,
205        binding: &BindingFile,
206        project_dir: &Path,
207    ) -> Result<Box<dyn ContextLoader>, String>;
208}
209
210/// The context kinds this checkout can read itself: `wren_project` and `raw_source`. A host that
211/// needs another kind wraps this — delegating the two it knows and handling its own.
212pub struct BuiltinContextResolver;
213
214impl ContextResolver for BuiltinContextResolver {
215    fn resolve(
216        &self,
217        binding: &BindingFile,
218        project_dir: &Path,
219    ) -> Result<Box<dyn ContextLoader>, String> {
220        // `external` names a layer that is not on this machine, so it must be resolved before any
221        // path is built — joining a locator like `remote-service://analytics` onto a directory would produce
222        // nonsense, and reading anything at all would break the offline guarantee.
223        if binding.kind == BindingFile::EXTERNAL {
224            return Ok(Box::new(warble::ExternalContext::new()));
225        }
226        // The remaining built-in kinds read a directory, so `project` is a path for them. A host
227        // kind's `project` may be anything at all, which is why this resolution lives per-kind
228        // rather than in the caller.
229        let path = project_dir.join(&binding.project);
230        match binding.kind.as_str() {
231            BindingFile::WREN_PROJECT => {
232                if let Some(sources) = read_project_dir(&path)
233                    .map_err(|e| format!("failed to read {}: {e}", path.display()))?
234                {
235                    // Use the error-preserving `try_from_sources` (not `from_sources`) so a real
236                    // assembly failure's text survives into the `mdl_parseable` precondition message
237                    // instead of being silently dropped in favor of only the generic floor message.
238                    return Ok(Box::new(match MdlContext::try_from_sources(&sources) {
239                        Ok(ctx) => ctx,
240                        Err(e) => MdlContext::unparseable_with_error(Some(e.to_string())),
241                    }));
242                }
243                // Before kinds were declared, this directory would have been silently accepted as a
244                // raw source. Guessing across kinds is exactly what declaring one is meant to stop,
245                // so say what to write instead.
246                if path.join("schema.json").is_file() {
247                    return Err(format!(
248                        "{} holds a raw source (schema.json), not a wren project — declare \
249                         `kind: {}` in the binding to bind it",
250                        path.display(),
251                        BindingFile::RAW_SOURCE
252                    ));
253                }
254                // No wren project and no raw source: an unparseable context, so the failure surfaces
255                // as the `mdl_parseable` precondition rather than as an I/O error here.
256                Ok(Box::new(MdlContext::unparseable()))
257            }
258            BindingFile::RAW_SOURCE => {
259                let raw = read_raw_dir(&path)
260                    .map_err(|e| format!("failed to read {}: {e}", path.display()))?
261                    .ok_or_else(|| {
262                        format!(
263                            "binding declares `kind: {}` but {} has no schema.json",
264                            BindingFile::RAW_SOURCE,
265                            path.display()
266                        )
267                    })?;
268                Ok(Box::new(RawSourceContext::from_sources(&raw)))
269            }
270            other => Err(format!(
271                "unknown context kind '{other}' (this build resolves '{}', '{}' and '{}'). A host \
272                 that defines '{other}' must supply a ContextResolver for it — see \
273                 `compile_project_to_ir_with`.",
274                BindingFile::WREN_PROJECT,
275                BindingFile::RAW_SOURCE,
276                BindingFile::EXTERNAL
277            )),
278        }
279    }
280}
281
282/// Compile a Warble project directory into its IR JSON, using the real MDL `ContextLoader` over the
283/// bound wren project and the default component source list (project-local `components/` + this
284/// checkout's Hub — see [`default_component_sources`]). This is what every in-repo example/eval
285/// profile and integration test compiles through.
286pub fn compile_project_to_ir(project_dir: &Path) -> Result<serde_json::Value, String> {
287    compile_project_to_ir_with_sources(project_dir, &default_component_sources(project_dir)?)
288}
289
290/// Compile a Warble project directory into its IR JSON, resolving mounted components against an
291/// explicit, caller-supplied source list instead of the in-repo default (see [`ComponentSource`]).
292/// This is the seam a host outside this checkout uses to mount its own local component library
293/// alongside (or instead of) the Hub — e.g. `[ComponentSource::local(my_components),
294/// ComponentSource::hub(path_to_warble_hub)]`. All filesystem reads happen here; the core compiler
295/// stays sans-IO — it only ever receives the resolved `HashMap<String, ComponentFile>` built below.
296pub fn compile_project_to_ir_with_sources(
297    project_dir: &Path,
298    sources: &[ComponentSource],
299) -> Result<serde_json::Value, String> {
300    compile_project_to_ir_with(project_dir, sources, &BuiltinContextResolver)
301}
302
303/// As [`compile_project_to_ir_with_sources`], resolving the context binding through a
304/// caller-supplied [`ContextResolver`] instead of [`BuiltinContextResolver`]. This is the seam a
305/// host uses to bind a context kind this checkout cannot read — the context-side counterpart of
306/// passing your own [`ComponentSource`] list.
307pub fn compile_project_to_ir_with(
308    project_dir: &Path,
309    sources: &[ComponentSource],
310    resolver: &dyn ContextResolver,
311) -> Result<serde_json::Value, String> {
312    let profile_path = project_dir.join("profile.yml");
313    let profile: ProfileFile = serde_yaml::from_str(&read_file(&profile_path)?)
314        .map_err(|e| format!("failed to parse {}: {e}", profile_path.display()))?;
315
316    let binding_path = project_dir.join(&profile.context.project);
317    let binding: BindingFile = serde_yaml::from_str(&read_file(&binding_path)?)
318        .map_err(|e| format!("failed to parse {}: {e}", binding_path.display()))?;
319
320    let context = resolver.resolve(&binding, project_dir)?;
321
322    let mut components: HashMap<String, ComponentFile> = HashMap::new();
323    let mut step_contents: HashMap<String, HashMap<String, String>> = HashMap::new();
324
325    for mount in &profile.components {
326        let component_dir = resolve_component_dir(sources, &mount.use_id)?;
327        let component_path = component_dir.join("component.yml");
328        let component: ComponentFile = serde_yaml::from_str(&read_file(&component_path)?)
329            .map_err(|e| format!("failed to parse {}: {e}", component_path.display()))?;
330
331        let mut steps: HashMap<String, String> = HashMap::new();
332        for step in &component.llm_steps {
333            let step_path = component_dir.join(&step.prompt_ref);
334            steps.insert(step.name.clone(), read_file(&step_path)?);
335        }
336        step_contents.insert(component.id.clone(), steps);
337        components.insert(component.id.clone(), component);
338    }
339
340    warble::compile(
341        &profile,
342        &components,
343        &binding.project,
344        context.as_ref(),
345        &step_contents,
346    )
347    .map_err(|e| e.to_string())
348}
349
350fn read_file(path: &Path) -> Result<String, String> {
351    std::fs::read_to_string(path).map_err(|e| format!("failed to read {}: {e}", path.display()))
352}
353
354/// Compute the [`warble::BlastRadius`] of `node` in a Warble project's bound wren project. Resolves
355/// the project the same way [`compile_project_to_ir`] does (profile.yml → context binding →
356/// wren project → `MdlContext`), but stops short of a full compile — just the lineage query.
357pub fn blast_radius_for_project(
358    project_dir: &Path,
359    node: &str,
360) -> Result<warble::BlastRadius, String> {
361    blast_radius_for_project_with(project_dir, node, &BuiltinContextResolver)
362}
363
364/// As [`blast_radius_for_project`], resolving the context binding through a caller-supplied
365/// [`ContextResolver`]. Kept in step with [`compile_project_to_ir_with`] so a host kind is bindable
366/// on both paths — a lineage query over a context only the host can load is no less valid than a
367/// compile over it.
368pub fn blast_radius_for_project_with(
369    project_dir: &Path,
370    node: &str,
371    resolver: &dyn ContextResolver,
372) -> Result<warble::BlastRadius, String> {
373    let profile_path = project_dir.join("profile.yml");
374    let profile: ProfileFile = serde_yaml::from_str(&read_file(&profile_path)?)
375        .map_err(|e| format!("failed to parse {}: {e}", profile_path.display()))?;
376
377    let binding_path = project_dir.join(&profile.context.project);
378    let binding: BindingFile = serde_yaml::from_str(&read_file(&binding_path)?)
379        .map_err(|e| format!("failed to parse {}: {e}", binding_path.display()))?;
380
381    let context = resolver.resolve(&binding, project_dir)?;
382
383    if !context.is_parseable() {
384        return Err(format!(
385            "bound context '{}' is not parseable — cannot compute blast radius",
386            binding.project
387        ));
388    }
389
390    Ok(context.lineage().blast_radius(node))
391}
392
393#[cfg(test)]
394mod component_source_tests {
395    use super::{resolve_component_dir, ComponentSource};
396    use std::fs;
397    use std::path::Path;
398
399    /// Create `<dir>/<id>/component.yml` (contents are irrelevant — resolution only checks the
400    /// file exists) so a source directory "defines" `id`.
401    fn stub_component(dir: &Path, id: &str) {
402        let component_dir = dir.join(id);
403        fs::create_dir_all(&component_dir).unwrap();
404        fs::write(component_dir.join("component.yml"), "id: placeholder\n").unwrap();
405    }
406
407    #[test]
408    fn resolves_from_the_only_source_that_defines_it() {
409        let hub = tempfile::tempdir().unwrap();
410        stub_component(hub.path(), "answer_query");
411
412        let sources = vec![ComponentSource::hub(hub.path())];
413        let resolved = resolve_component_dir(&sources, "answer_query").unwrap();
414        assert_eq!(resolved, hub.path().join("answer_query"));
415    }
416
417    #[test]
418    fn local_overrides_hub_when_both_define_the_same_id() {
419        let local = tempfile::tempdir().unwrap();
420        let hub = tempfile::tempdir().unwrap();
421        stub_component(local.path(), "answer_query");
422        stub_component(hub.path(), "answer_query");
423
424        let sources = vec![
425            ComponentSource::local(local.path()),
426            ComponentSource::hub(hub.path()),
427        ];
428        let resolved = resolve_component_dir(&sources, "answer_query").unwrap();
429        assert_eq!(
430            resolved,
431            local.path().join("answer_query"),
432            "a Local source must win over a Hub source defining the same id"
433        );
434    }
435
436    #[test]
437    fn falls_back_to_hub_when_local_does_not_define_the_id() {
438        let local = tempfile::tempdir().unwrap();
439        let hub = tempfile::tempdir().unwrap();
440        stub_component(hub.path(), "answer_query");
441
442        let sources = vec![
443            ComponentSource::local(local.path()),
444            ComponentSource::hub(hub.path()),
445        ];
446        let resolved = resolve_component_dir(&sources, "answer_query").unwrap();
447        assert_eq!(resolved, hub.path().join("answer_query"));
448    }
449
450    #[test]
451    fn unresolved_id_is_a_loud_fail_naming_every_source_searched() {
452        let local = tempfile::tempdir().unwrap();
453        let hub = tempfile::tempdir().unwrap();
454
455        let sources = vec![
456            ComponentSource::local(local.path()),
457            ComponentSource::hub(hub.path()),
458        ];
459        let err = resolve_component_dir(&sources, "missing").unwrap_err();
460        assert!(err.contains("missing"));
461        assert!(err.contains(&local.path().display().to_string()));
462        assert!(err.contains(&hub.path().display().to_string()));
463    }
464
465    #[test]
466    fn same_id_in_two_same_kind_sources_is_ambiguous_not_first_match_wins() {
467        let local_a = tempfile::tempdir().unwrap();
468        let local_b = tempfile::tempdir().unwrap();
469        stub_component(local_a.path(), "answer_query");
470        stub_component(local_b.path(), "answer_query");
471
472        let sources = vec![
473            ComponentSource::local(local_a.path()),
474            ComponentSource::local(local_b.path()),
475        ];
476        let err = resolve_component_dir(&sources, "answer_query").unwrap_err();
477        assert!(err.contains("ambiguous"));
478        assert!(err.contains(&local_a.path().display().to_string()));
479        assert!(err.contains(&local_b.path().display().to_string()));
480    }
481
482    #[test]
483    fn ambiguous_same_kind_sources_do_not_fall_through_to_a_lower_kind() {
484        // Even though `hub` alone would resolve `answer_query` unambiguously, an ambiguous match
485        // at the higher-precedence `Local` kind must fail loud rather than silently falling back.
486        let local_a = tempfile::tempdir().unwrap();
487        let local_b = tempfile::tempdir().unwrap();
488        let hub = tempfile::tempdir().unwrap();
489        stub_component(local_a.path(), "answer_query");
490        stub_component(local_b.path(), "answer_query");
491        stub_component(hub.path(), "answer_query");
492
493        let sources = vec![
494            ComponentSource::local(local_a.path()),
495            ComponentSource::local(local_b.path()),
496            ComponentSource::hub(hub.path()),
497        ];
498        let err = resolve_component_dir(&sources, "answer_query").unwrap_err();
499        assert!(err.contains("ambiguous"));
500    }
501}
502
503/// `warble_eval_runner::ComplianceIr` (the type `eval compliance` deserializes into) is
504/// *deliberately* narrower than `WarbleIr` — its own doc comment says so, so a compiled-in
505/// `warble_ir_version` field never belongs on that type. But `eval compliance` is not fed an
506/// arbitrary subset: every real caller hands it the same complete `ir.json` `dispatch`/`manifest`
507/// consume (confirmed by `eval/golden/compliance/ground_truth.yaml`'s own comment — its two golden
508/// IRs, `examples/mutate-agent/ir.golden.json` and `examples/analysis-agent/ir.golden.json`, are "reused
509/// as-is, not new fixtures"). So the version gate belongs here, at the CLI boundary, checked on the
510/// raw JSON before `ComplianceIr` ever sees it — against the same
511/// `warble_claude_code::ir::SUPPORTED_IR_VERSION` that the binary's own `load_ir` already gates
512/// `dispatch`/`manifest` against, so every CLI-level IR consumer rejects an out-of-range version
513/// the same way.
514pub fn check_compliance_ir_version(raw: &str, path: &Path) -> Result<(), String> {
515    let parsed: serde_json::Value = serde_json::from_str(raw).map_err(|e| {
516        format!(
517            "failed to parse IR {} for version check: {e}",
518            path.display()
519        )
520    })?;
521    // Absent and present-but-not-a-string are reported separately on purpose: collapsing them sends
522    // someone whose IR *does* carry the field looking for a missing key that is right there.
523    match parsed.get("warble_ir_version") {
524        None => Err(format!(
525            "IR {} has no warble_ir_version field — eval compliance requires a complete compiled \
526             IR, not a hand-written subset",
527            path.display()
528        )),
529        Some(serde_json::Value::String(v)) if v == SUPPORTED_IR_VERSION => Ok(()),
530        Some(serde_json::Value::String(v)) => Err(format!(
531            "unsupported warble_ir_version '{v}' in {} (eval compliance understands: {SUPPORTED_IR_VERSION})",
532            path.display()
533        )),
534        Some(other) => Err(format!(
535            "warble_ir_version in {} is {}, not a string — eval compliance understands: \
536             {SUPPORTED_IR_VERSION}",
537            path.display(),
538            match other {
539                serde_json::Value::Null => "null",
540                serde_json::Value::Bool(_) => "a boolean",
541                serde_json::Value::Number(_) => "a number",
542                serde_json::Value::Array(_) => "an array",
543                _ => "an object",
544            }
545        )),
546    }
547}
548
549#[cfg(test)]
550mod compliance_ir_version_tests {
551    use super::{check_compliance_ir_version, SUPPORTED_IR_VERSION};
552    use std::path::Path;
553
554    fn check(raw: &str) -> Result<(), String> {
555        check_compliance_ir_version(raw, Path::new("ir.json"))
556    }
557
558    #[test]
559    fn the_supported_version_passes() {
560        let raw = format!(r#"{{"warble_ir_version": "{SUPPORTED_IR_VERSION}", "components": []}}"#);
561        assert!(check(&raw).is_ok(), "got: {:?}", check(&raw));
562    }
563
564    #[test]
565    fn a_missing_field_is_reported_as_missing() {
566        let err = check(r#"{"components": []}"#).expect_err("must reject");
567        assert!(err.contains("has no warble_ir_version"), "got: {err}");
568    }
569
570    #[test]
571    fn an_out_of_range_version_is_reported_as_unsupported() {
572        let err = check(r#"{"warble_ir_version": "0.2", "components": []}"#).expect_err("reject");
573        assert!(
574            err.contains("unsupported warble_ir_version '0.2'"),
575            "got: {err}"
576        );
577        assert!(
578            err.contains(SUPPORTED_IR_VERSION),
579            "must name what it does accept: {err}"
580        );
581    }
582
583    #[test]
584    fn a_version_that_merely_starts_with_the_supported_one_is_rejected() {
585        // Guards against a `starts_with` regression: "0.30" is not "0.3".
586        let raw = format!(r#"{{"warble_ir_version": "{SUPPORTED_IR_VERSION}0"}}"#);
587        let err = check(&raw).expect_err("a superstring is a different version");
588        assert!(err.contains("unsupported warble_ir_version"), "got: {err}");
589    }
590
591    /// The matrix this module exists for: every non-string JSON type must be reported as a *type*
592    /// error naming what it actually is — never as "the field is missing", which would send someone
593    /// looking for a key that is sitting right there. `null` is the one that regressed before.
594    #[test]
595    fn every_non_string_type_is_reported_as_a_type_error() {
596        for (literal, expected) in [
597            ("null", "is null"),
598            ("true", "is a boolean"),
599            ("3", "is a number"),
600            ("[]", "is an array"),
601            ("{}", "is an object"),
602        ] {
603            let raw = format!(r#"{{"warble_ir_version": {literal}}}"#);
604            let err = check(&raw).expect_err(&format!("{literal} must be rejected"));
605            assert!(
606                err.contains(expected),
607                "for {literal} expected '{expected}', got: {err}"
608            );
609            assert!(
610                !err.contains("has no warble_ir_version"),
611                "for {literal} the field is present, not missing: {err}"
612            );
613        }
614    }
615
616    #[test]
617    fn unparseable_json_is_reported_as_a_parse_failure() {
618        let err = check("not json at all").expect_err("must reject");
619        assert!(err.contains("failed to parse IR"), "got: {err}");
620    }
621}