Skip to main content

limitless_cli/modules/
runtime_validator.rs

1//! Runtime version validation for Limitless CLI.
2//!
3//! Checks an installed runtime version against per-stack requirements and
4//! returns a [`VersionReport`] carrying a [`CheckStatus`] plus actionable
5//! feedback. Thresholds follow the Limitless spec:
6//!
7//! | Stack  | Minimum      | Recommended    |
8//! |--------|--------------|----------------|
9//! | Node   | 14.0.0 (warn) | >= 18.0.0     |
10//! | Python | 3.8.0 (warn)  | >= 3.9.0      |
11//! | Rust   | 1.56.0        | —              |
12//!
13//! Project-specific requirements are honoured when available:
14//! `package.json` `engines.node`, `pyproject.toml` `requires-python`, and
15//! the `rust-toolchain` / `rust-toolchain.toml` channel.
16//!
17//! # Example outputs
18//!
19//! ```text
20//! PASS  "Node v18.12.0 meets the recommended version (>= 18.0.0)."
21//! WARN  "Node v16.3.1 works, but Node >= 18.0.0 is recommended."
22//! FAIL  "Node v12.22.0 is too old. Node 14.0.0 or newer is required."
23//! FAIL  "engines.node requires Node 20.0.0+, but v18.12.0 is installed."
24//! ```
25
26use colored::Colorize;
27use std::fmt;
28use std::path::Path;
29use std::process::Command;
30
31use crate::models::{CheckStatus, ProjectStack};
32use crate::modules::stack_detector::{
33    detect_stack, extract_version, parse_key_value, python_version_from_pyproject, read_clean,
34};
35
36/// Node hard minimum: anything below this fails.
37const NODE_MIN: SemVer = SemVer::new(14, 0, 0);
38/// Node recommended floor: at/above this passes (subject to engines).
39const NODE_RECOMMENDED: SemVer = SemVer::new(18, 0, 0);
40/// Python hard minimum.
41const PYTHON_MIN: SemVer = SemVer::new(3, 8, 0);
42/// Python recommended floor.
43const PYTHON_RECOMMENDED: SemVer = SemVer::new(3, 9, 0);
44/// Rust hard minimum (Rust 2021 edition baseline).
45const RUST_MIN: SemVer = SemVer::new(1, 56, 0);
46
47/// The outcome of a [`validate_runtime_version`] call.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct VersionReport {
50    /// Pass / Warn / Fail classification.
51    pub status: CheckStatus,
52    /// The installed version that was validated (as given, renormalized).
53    pub actual_version: String,
54    /// The requirement that drove the outcome, when applicable.
55    pub required_version: Option<String>,
56    /// Clear, human-readable explanation (required vs. actual).
57    pub message: String,
58    /// A concrete next step, when a resolution exists.
59    pub remediation: Option<String>,
60}
61
62impl VersionReport {
63    /// Whether the report is a Pass.
64    pub fn is_pass(&self) -> bool {
65        self.status == CheckStatus::Pass
66    }
67
68    /// Colored terminal label for the status.
69    pub fn status_label(&self) -> String {
70        match self.status {
71            CheckStatus::Pass => "PASS".green().bold().to_string(),
72            CheckStatus::Warn => "WARN".yellow().bold().to_string(),
73            CheckStatus::Fail => "FAIL".red().bold().to_string(),
74        }
75    }
76}
77
78/// Core validation. Applies the spec thresholds for the given stack using
79/// only the installed version — no project files are consulted.
80///
81/// ```
82/// use limitless_cli::models::{CheckStatus, ProjectStack};
83/// use limitless_cli::modules::runtime_validator::validate_runtime_version;
84///
85/// let report = validate_runtime_version(
86///     &ProjectStack::Node { version: String::new(), package_manager: "npm".into() },
87///     "16.3.1",
88/// );
89/// assert_eq!(report.status, CheckStatus::Warn);
90/// assert!(report.message.contains("16.3.1"));
91/// ```
92pub fn validate_runtime_version(stack: &ProjectStack, actual: &str) -> VersionReport {
93    match stack {
94        ProjectStack::Node { .. } => check_node(actual, None),
95        ProjectStack::Python { .. } => check_python(actual, None),
96        ProjectStack::Rust { .. } => check_rust(actual, None),
97        ProjectStack::Go { .. } | ProjectStack::Java { .. } => report_pass(actual, "Runtime version is valid for this stack.", None, None),
98        ProjectStack::Docker => report_warn(
99            actual,
100            "Docker is a container runtime — there is no runtime version to validate.",
101            None,
102            None,
103        ),
104        ProjectStack::Unknown => report_warn(
105            actual,
106            "No recognizable stack detected, so the runtime version could not be validated.",
107            None,
108            None,
109        ),
110    }
111}
112
113/// Validates an installed version against a repository's own requirements
114/// files (`engines.node`, `requires-python`, `rust-toolchain`) in addition
115/// to the spec thresholds.
116///
117/// If the referenced files are absent, this falls back to the same logic as
118/// [`validate_runtime_version`].
119///
120/// ```
121/// use limitless_cli::models::{CheckStatus, ProjectStack};
122/// use limitless_cli::modules::runtime_validator::validate_project_runtime;
123///
124/// // This crate's Cargo.toml has no rust-version pin, so 1.56+ passes.
125/// let report = validate_project_runtime(
126///     env!("CARGO_MANIFEST_DIR"),
127///     &ProjectStack::Rust { version: String::new() },
128///     "1.85.0",
129/// );
130/// assert_eq!(report.status, CheckStatus::Pass);
131/// ```
132pub fn validate_project_runtime(
133    repo_root: &str,
134    stack: &ProjectStack,
135    actual: &str,
136) -> VersionReport {
137    let root = Path::new(repo_root);
138    match stack {
139        ProjectStack::Node { .. } => check_node(actual, read_engines_node(root).as_deref()),
140        ProjectStack::Python { .. } => {
141            check_python(actual, read_pyproject_requirement(root).as_deref())
142        }
143        ProjectStack::Rust { .. } => {
144            check_rust(actual, read_rust_toolchain_requirement(root).as_deref())
145        }
146        _ => validate_runtime_version(stack, actual),
147    }
148}
149
150/// Convenience wrapper for `limit check`: detects the current directory's
151/// stack, probes the installed tool, and validates it against the repo.
152/// Returns `None` when there is nothing to validate (unknown/Docker stack
153/// or the relevant tool binary is not installed).
154pub fn validate_installed_runtime(repo_root: &str) -> Option<VersionReport> {
155    let stack = detect_stack(repo_root);
156    let probes: &[(&str, &str)] = match stack {
157        ProjectStack::Node { .. } => &[("node", "--version")],
158        ProjectStack::Python { .. } => &[("python", "--version"), ("python3", "--version")],
159        ProjectStack::Rust { .. } => &[("rustc", "--version")],
160        _ => return None,
161    };
162
163    for (cmd, flag) in probes {
164        if let Ok(output) = Command::new(cmd).arg(flag).output() {
165            let raw = String::from_utf8_lossy(&output.stdout);
166            let raw_stderr = String::from_utf8_lossy(&output.stderr);
167            let combined = if raw.trim().is_empty() {
168                raw_stderr.to_string()
169            } else {
170                raw.to_string()
171            };
172            let actual = extract_version(&combined)?;
173            return Some(validate_project_runtime(repo_root, &stack, &actual));
174        }
175    }
176    None
177}
178
179// ---------------------------------------------------------------------------
180// Per-stack evaluation
181// ---------------------------------------------------------------------------
182
183fn check_node(actual: &str, engines_req: Option<&str>) -> VersionReport {
184    let parsed = match SemVer::parse(actual) {
185        Some(v) => v,
186        None => {
187            return report_fail(
188                actual,
189                &format!(
190                    "Node could not be validated: '{actual}' is not a valid semantic version."
191                ),
192                None,
193                None,
194            );
195        }
196    };
197
198    if parsed < NODE_MIN {
199        return report_fail(
200            actual,
201            &format!(
202                "Node v{parsed} is too old. Node {} or newer is required.",
203                required_label(NODE_MIN)
204            ),
205            Some("14.0.0".to_string()),
206            Some("Install a supported Node runtime: `nvm install 18 && nvm use 18`"),
207        );
208    }
209
210    if let Some(req) = semver_floor(engines_req) {
211        if parsed < req {
212            return report_fail(
213                actual,
214                &format!(
215                    "engines.node requires Node {engines}, but v{parsed} is installed.",
216                    engines = engines_req.unwrap_or_default()
217                ),
218                Some(req.to_string()),
219                Some("Upgrade Node to match engines.node or relax the pin in package.json"),
220            );
221        }
222    }
223
224    if parsed < NODE_RECOMMENDED {
225        return report_warn(
226            actual,
227            &format!("Node v{parsed} works, but Node 18.0.0+ is recommended.",),
228            Some(format!("{}", NODE_RECOMMENDED)),
229            Some("Consider installing Node 18+: `nvm install 18 && nvm use 18`"),
230        );
231    }
232
233    report_pass(
234        actual,
235        &format!("Node v{parsed} meets the recommended version (>= 18.0.0)"),
236        Some(format!("{}", NODE_RECOMMENDED)),
237        None,
238    )
239}
240
241fn check_python(actual: &str, pyproject_req: Option<&str>) -> VersionReport {
242    let parsed = match SemVer::parse(actual) {
243        Some(v) => v,
244        None => {
245            return report_fail(
246                actual,
247                &format!(
248                    "Python could not be validated: '{actual}' is not a valid semantic version."
249                ),
250                None,
251                None,
252            );
253        }
254    };
255
256    if parsed < PYTHON_MIN {
257        return report_fail(
258            actual,
259            &format!(
260                "Python v{parsed} is too old. Python {} or newer is required.",
261                required_label(PYTHON_MIN)
262            ),
263            Some("3.8.0".to_string()),
264            Some("Install a supported Python: https://www.python.org/downloads/"),
265        );
266    }
267
268    if let Some(req) = semver_floor(pyproject_req) {
269        if parsed < req {
270            return report_fail(
271                actual,
272                &format!(
273                    "pyproject.toml requires Python {pyproject}, but v{parsed} is installed.",
274                    pyproject = pyproject_req.unwrap_or_default()
275                ),
276                Some(req.to_string()),
277                Some("Install the version pinned by your project (pyenv recommended)"),
278            );
279        }
280    }
281
282    if parsed < PYTHON_RECOMMENDED {
283        return report_warn(
284            actual,
285            &format!("Python v{parsed} works, but Python 3.9.0+ is recommended."),
286            Some(format!("{}", PYTHON_RECOMMENDED)),
287            Some("Consider installing Python 3.9+: https://www.python.org/downloads/"),
288        );
289    }
290
291    report_pass(
292        actual,
293        &format!("Python v{parsed} meets the recommended version (>= 3.9.0)"),
294        Some(format!("{}", PYTHON_RECOMMENDED)),
295        None,
296    )
297}
298
299fn check_rust(actual: &str, toolchain_req: Option<&str>) -> VersionReport {
300    let parsed = match SemVer::parse(actual) {
301        Some(v) => v,
302        None => {
303            return report_fail(
304                actual,
305                &format!(
306                    "Rust could not be validated: '{actual}' is not a valid semantic version."
307                ),
308                None,
309                None,
310            );
311        }
312    };
313
314    if parsed < RUST_MIN {
315        return report_fail(
316            actual,
317            &format!(
318                "Rust v{parsed} is too old. Rust {} or newer is required.",
319                required_label(RUST_MIN)
320            ),
321            Some("1.56.0".to_string()),
322            Some("Update your toolchain: `rustup update stable`"),
323        );
324    }
325
326    if let Some(req) = semver_floor(toolchain_req) {
327        if parsed < req {
328            return report_fail(
329                actual,
330                &format!(
331                    "rust-toolchain pins Rust {toolchain}, but v{parsed} is installed.",
332                    toolchain = toolchain_req
333                        .map(|t| t.split_whitespace().next().unwrap_or(t))
334                        .unwrap_or_default()
335                ),
336                Some(req.to_string()),
337                Some("Run `rustup toolchain install <pinned-version>` to match rust-toolchain"),
338            );
339        }
340    }
341
342    report_pass(
343        actual,
344        &format!("Rust v{parsed} meets the minimum requirement (>= 1.56.0)"),
345        Some(format!("{}", RUST_MIN)),
346        None,
347    )
348}
349
350// ---------------------------------------------------------------------------
351// Requirement readers (project marker files)
352// ---------------------------------------------------------------------------
353
354/// Reads `engines.node` from `package.json`, if present.
355fn read_engines_node(root: &Path) -> Option<String> {
356    let content = read_clean(root.join("package.json")).ok()?;
357    let json: serde_json::Value = serde_json::from_str(&content).ok()?;
358    json.pointer("/engines/node")
359        .and_then(|v| v.as_str())
360        .map(str::to_string)
361}
362
363/// Reads the Python requirement from `pyproject.toml`.
364fn read_pyproject_requirement(root: &Path) -> Option<String> {
365    let content = read_clean(root.join("pyproject.toml")).ok()?;
366    python_version_from_pyproject(&content)
367}
368
369/// Reads the pinned channel from `rust-toolchain.toml` or `rust-toolchain`.
370fn read_rust_toolchain_requirement(root: &Path) -> Option<String> {
371    // rustup prefers the .toml form when both exist.
372    if let Ok(content) = read_clean(root.join("rust-toolchain.toml")) {
373        let mut in_toolchain = false;
374        for line in content.lines() {
375            let trimmed = line.trim();
376            if trimmed.starts_with('[') {
377                in_toolchain = trimmed == "[toolchain]";
378                continue;
379            }
380            if in_toolchain {
381                if let Some(channel) = parse_key_value(trimmed, "channel") {
382                    if !channel.is_empty() {
383                        return Some(channel);
384                    }
385                }
386            }
387        }
388    }
389
390    if let Ok(content) = read_clean(root.join("rust-toolchain")) {
391        let trimmed = content.trim();
392        if !trimmed.is_empty() {
393            return Some(trimmed.to_string());
394        }
395    }
396
397    None
398}
399
400/// Extracts the lower-bound version from a requirement expression such as
401/// `">=18 <20"`, `"^20.0.0"`, or `"3.12"`. Returns `None` when the
402/// expression contains no numeric version.
403fn semver_floor(requirement: Option<&str>) -> Option<SemVer> {
404    let raw = extract_version(requirement?)?;
405    SemVer::parse(&raw)
406}
407
408// ---------------------------------------------------------------------------
409// Semantic version support
410// ---------------------------------------------------------------------------
411
412/// A strict `major.minor.patch` semantic version with ordering support.
413///
414/// Pre-release (`-beta.1`) and build (`+sha`) suffixes are ignored for
415/// comparison, matching how runtime tools report stable versions.
416#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
417pub struct SemVer {
418    major: u64,
419    minor: u64,
420    patch: u64,
421}
422
423impl SemVer {
424    const fn new(major: u64, minor: u64, patch: u64) -> Self {
425        Self {
426            major,
427            minor,
428            patch,
429        }
430    }
431
432    /// Parses `"v18.12.0"`, `"18.12.0"`, `"18.2"`, or `"18"` (missing parts
433    /// default to `0`). Returns `None` for non-version strings.
434    ///
435    /// ```
436    /// use limitless_cli::modules::runtime_validator::SemVer;
437    ///
438    /// assert!(SemVer::parse("v18.12.0").is_some());
439    /// assert!(SemVer::parse("18").is_some());
440    /// assert!(SemVer::parse("lts").is_none());
441    ///
442    /// assert!(SemVer::parse("18.12.0").unwrap() > SemVer::parse("18.2.0").unwrap());
443    /// assert!(SemVer::parse("1.85.0").unwrap() > SemVer::parse("1.56.0").unwrap());
444    /// ```
445    pub fn parse(raw: &str) -> Option<SemVer> {
446        let core = raw
447            .trim()
448            .trim_start_matches('v')
449            .split(['-', '+'])
450            .next()?;
451        if core.is_empty() {
452            return None;
453        }
454
455        let parts: Vec<&str> = core.split('.').collect();
456        if parts.len() > 3
457            || parts
458                .iter()
459                .any(|p| p.is_empty() || !p.chars().all(|c| c.is_ascii_digit()))
460        {
461            return None;
462        }
463
464        let mut nums = [0u64; 3];
465        for (i, part) in parts.iter().enumerate() {
466            nums[i] = part.parse().ok()?;
467        }
468
469        Some(SemVer::new(nums[0], nums[1], nums[2]))
470    }
471}
472
473impl fmt::Display for SemVer {
474    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
475        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
476    }
477}
478
479/// `"v18.12.0"` => `"v18.12.0"`; also renders `NODE_MIN` style labels.
480fn required_label(version: SemVer) -> String {
481    format!("v{version}")
482}
483
484// ---------------------------------------------------------------------------
485// Report constructors
486// ---------------------------------------------------------------------------
487
488fn report_pass(
489    actual: &str,
490    message: &str,
491    required: Option<String>,
492    remediation: Option<&str>,
493) -> VersionReport {
494    VersionReport {
495        status: CheckStatus::Pass,
496        actual_version: actual.to_string(),
497        required_version: required,
498        message: message.to_string(),
499        remediation: remediation.map(str::to_string),
500    }
501}
502
503fn report_warn(
504    actual: &str,
505    message: &str,
506    required: Option<String>,
507    remediation: Option<&str>,
508) -> VersionReport {
509    VersionReport {
510        status: CheckStatus::Warn,
511        actual_version: actual.to_string(),
512        required_version: required,
513        message: message.to_string(),
514        remediation: remediation.map(str::to_string),
515    }
516}
517
518fn report_fail(
519    actual: &str,
520    message: &str,
521    required: Option<String>,
522    remediation: Option<&str>,
523) -> VersionReport {
524    VersionReport {
525        status: CheckStatus::Fail,
526        actual_version: actual.to_string(),
527        required_version: required,
528        message: message.to_string(),
529        remediation: remediation.map(str::to_string),
530    }
531}
532
533#[cfg(test)]
534mod tests {
535    use super::*;
536
537    fn node() -> ProjectStack {
538        ProjectStack::Node {
539            version: String::new(),
540            package_manager: "npm".to_string(),
541        }
542    }
543
544    fn python() -> ProjectStack {
545        ProjectStack::Python {
546            version: String::new(),
547        }
548    }
549
550    fn rust() -> ProjectStack {
551        ProjectStack::Rust {
552            version: String::new(),
553        }
554    }
555
556    // --- SemVer parser ----------------------------------------------------
557
558    #[test]
559    fn parses_full_partial_and_prefixed_versions() {
560        assert_eq!(SemVer::parse("18.12.0"), Some(SemVer::new(18, 12, 0)));
561        assert_eq!(SemVer::parse("v18.12.0"), Some(SemVer::new(18, 12, 0)));
562        assert_eq!(SemVer::parse("18.2"), Some(SemVer::new(18, 2, 0)));
563        assert_eq!(SemVer::parse("18"), Some(SemVer::new(18, 0, 0)));
564        assert_eq!(SemVer::parse(" 3.10.9 "), Some(SemVer::new(3, 10, 9)));
565    }
566
567    #[test]
568    fn rejects_non_version_strings() {
569        assert_eq!(SemVer::parse("lts"), None);
570        assert_eq!(SemVer::parse("stable"), None);
571        assert_eq!(SemVer::parse(""), None);
572        assert_eq!(SemVer::parse("a.b.c"), None);
573        assert_eq!(SemVer::parse("18.12.0.1"), None);
574        assert_eq!(SemVer::parse("18..0"), None);
575    }
576
577    #[test]
578    fn orders_versions_correctly() {
579        let v = |s: &str| SemVer::parse(s).unwrap();
580        assert!(v("18.12.0") > v("18.2.0"));
581        assert!(v("18.2.0") > v("18.0.9"));
582        assert!(v("18.0.0") > v("17.99.99"));
583        assert!(v("3.9.0") > v("3.8.9"));
584        assert!(v("1.85.0") > v("1.56.0"));
585        assert!(v("1.56.0") == v("1.56"));
586    }
587
588    // --- Node -------------------------------------------------------------
589
590    #[test]
591    fn node_pass_when_recommended() {
592        let report = validate_runtime_version(&node(), "18.12.0");
593        assert_eq!(report.status, CheckStatus::Pass);
594        assert!(report.message.contains("18.12.0"));
595    }
596
597    #[test]
598    fn node_warns_when_below_recommended_but_above_min() {
599        let report = validate_runtime_version(&node(), "16.3.1");
600        assert_eq!(report.status, CheckStatus::Warn);
601        assert!(report.message.contains("recommended"));
602    }
603
604    #[test]
605    fn node_fails_below_hard_minimum() {
606        let report = validate_runtime_version(&node(), "12.22.0");
607        assert_eq!(report.status, CheckStatus::Fail);
608        assert!(report.message.contains("14.0.0"));
609        assert!(report.remediation.is_some());
610    }
611
612    #[test]
613    fn node_engines_floor_is_enforced() {
614        // Simulate engines.node = ">=20.0.0" directly.
615        let report = check_node("18.12.0", Some(">=20.0.0"));
616        assert_eq!(report.status, CheckStatus::Fail);
617        assert!(report.message.contains("engines.node"));
618        assert!(report.message.contains("20.0.0"));
619
620        // engines ">=16 <20" allows 16 but stays below recommended -> Warn.
621        let report = check_node("16.4.0", Some(">=16.0.0 <20"));
622        assert_eq!(report.status, CheckStatus::Warn);
623
624        // engines "^18.0.0" with 19 installed -> Pass (>= recommended here too).
625        let report = check_node("19.0.0", Some("^18.0.0"));
626        assert_eq!(report.status, CheckStatus::Pass);
627    }
628
629    #[test]
630    fn node_rejects_invalid_version() {
631        let report = validate_runtime_version(&node(), "latest");
632        assert_eq!(report.status, CheckStatus::Fail);
633        assert!(report.message.contains("not a valid semantic version"));
634    }
635
636    // --- Python -----------------------------------------------------------
637
638    #[test]
639    fn python_pass_when_recommended() {
640        let report = validate_runtime_version(&python(), "3.12.0");
641        assert_eq!(report.status, CheckStatus::Pass);
642    }
643
644    #[test]
645    fn python_warns_when_below_recommended() {
646        let report = validate_runtime_version(&python(), "3.8.5");
647        assert_eq!(report.status, CheckStatus::Warn);
648        assert!(report.message.contains("3.9.0"));
649    }
650
651    #[test]
652    fn python_fails_below_hard_minimum() {
653        let report = validate_runtime_version(&python(), "3.7.9");
654        assert_eq!(report.status, CheckStatus::Fail);
655        assert!(report.message.contains("3.8.0"));
656    }
657
658    #[test]
659    fn python_pyproject_floor_is_enforced() {
660        // requires-python = ">=3.11" with 3.10 installed -> Fail.
661        let report = check_python("3.10.0", Some(">=3.11"));
662        assert_eq!(report.status, CheckStatus::Fail);
663        assert!(report.message.contains("pyproject.toml"));
664
665        // requires-python = ">=3.9" with 3.10 installed -> Pass.
666        let report = check_python("3.10.0", Some(">=3.9"));
667        assert_eq!(report.status, CheckStatus::Pass);
668    }
669
670    // --- Rust -------------------------------------------------------------
671
672    #[test]
673    fn rust_pass_when_above_minimum() {
674        let report = validate_runtime_version(&rust(), "1.85.0");
675        assert_eq!(report.status, CheckStatus::Pass);
676    }
677
678    #[test]
679    fn rust_fails_below_minimum() {
680        let report = validate_runtime_version(&rust(), "1.55.0");
681        assert_eq!(report.status, CheckStatus::Fail);
682        assert!(report.message.contains("1.56.0"));
683    }
684
685    #[test]
686    fn rust_toolchain_floor_is_enforced() {
687        let report = check_rust("1.76.0", Some("1.80.0"));
688        assert_eq!(report.status, CheckStatus::Fail);
689        assert!(report.message.contains("1.80.0"));
690
691        let report = check_rust("1.80.0", Some("1.80.0"));
692        assert_eq!(report.status, CheckStatus::Pass);
693    }
694
695    #[test]
696    fn rust_nightly_channel_is_not_a_version_gate() {
697        // "nightly-2026-01-01" has no numeric version -> no extra floor.
698        let report = check_rust("1.76.0", Some("nightly-2026-01-01"));
699        assert_eq!(report.status, CheckStatus::Pass);
700    }
701
702    // --- Other stacks -----------------------------------------------------
703
704    #[test]
705    fn docker_and_unknown_are_warns() {
706        let docker = validate_runtime_version(&ProjectStack::Docker, "1.0.0");
707        assert_eq!(docker.status, CheckStatus::Warn);
708
709        let unknown = validate_runtime_version(&ProjectStack::Unknown, "1.0.0");
710        assert_eq!(unknown.status, CheckStatus::Warn);
711    }
712
713    #[test]
714    fn validate_project_runtime_reads_engines_from_fixture() {
715        // Build a tiny fixture on the fly to prove the file readers work.
716        let dir =
717            std::env::temp_dir().join(format!("runtime_validator_fixture_{}", std::process::id()));
718        std::fs::create_dir_all(&dir).expect("create fixture");
719        std::fs::write(
720            dir.join("package.json"),
721            r#"{ "engines": { "node": ">=20.0.0" } }"#,
722        )
723        .expect("write fixture");
724
725        let report = validate_project_runtime(dir.to_str().expect("utf8"), &node(), "18.12.0");
726        assert_eq!(report.status, CheckStatus::Fail);
727        assert!(report.message.contains("engines.node"));
728
729        let _ = std::fs::remove_dir_all(&dir);
730    }
731
732    // --- Example outputs --------------------------------------------------
733
734    #[test]
735    fn examples_of_pass_warn_fail_outputs() {
736        let stacks = [
737            ("Node", node(), "18.12.0"),
738            ("Node", node(), "16.3.1"),
739            ("Node", node(), "12.22.0"),
740            ("Python", python(), "3.12.0"),
741            ("Python", python(), "3.8.5"),
742            ("Python", python(), "3.7.9"),
743            ("Rust", rust(), "1.85.0"),
744            ("Rust", rust(), "1.55.0"),
745        ];
746
747        for (label, stack, version) in stacks {
748            let report = validate_runtime_version(&stack, version);
749            eprintln!(
750                "  {} {} — {}",
751                report.status_label(),
752                format!("{label} v{version}").bold(),
753                report.message
754            );
755        }
756    }
757}