ktstr/cli/
resolve.rs

1//! Kernel-resolution dispatch: cache lookup, version download,
2//! source-tree auto-build, range expansion, git fetch.
3//!
4//! Holds the entry points that turn a `--kernel` spec into a
5//! bootable image path or cache-entry directory:
6//! [`resolve_kernel_image`], [`resolve_kernel_dir`],
7//! [`resolve_kernel_dir_to_entry`], [`resolve_cached_kernel`].
8//! Range and git wrappers live alongside ([`expand_kernel_range`],
9//! [`resolve_git_kernel`]). `--include-files` resolution
10//! ([`resolve_include_files`]) and the rayon-pool sizing helper
11//! ([`resolve_kernel_parallelism`]) share the module because both
12//! are dispatch-time helpers.
13
14use std::path::Path;
15
16use anyhow::{Result, anyhow, bail};
17
18use super::kernel_build::kernel_build_pipeline;
19use super::util::{Spinner, status, success};
20
21/// Pre-flight check for /dev/kvm availability and permissions.
22pub fn check_kvm() -> Result<()> {
23    use std::path::Path;
24    if !Path::new("/dev/kvm").exists() {
25        bail!(
26            "/dev/kvm not found. KVM requires:\n  \
27             - Linux kernel with KVM support (CONFIG_KVM)\n  \
28             - Access to /dev/kvm (check permissions or add user to 'kvm' group)\n  \
29             - Hardware virtualization enabled in BIOS (VT-x/AMD-V)"
30        );
31    }
32    if let Err(e) = std::fs::File::open("/dev/kvm") {
33        if e.kind() == std::io::ErrorKind::PermissionDenied {
34            bail!(
35                "/dev/kvm: permission denied. Add your user to the 'kvm' group:\n  \
36                 sudo usermod -aG kvm $USER\n  \
37                 then log out and back in."
38            );
39        }
40        bail!("/dev/kvm: {e}");
41    }
42    Ok(())
43}
44
45/// Pre-flight check: verify that all required external tools are
46/// present in `$PATH` before starting work.  Collects every missing
47/// tool into a single error so the user sees the full list at once.
48pub fn check_tools(required: &[&str]) -> Result<()> {
49    let missing: Vec<&str> = required
50        .iter()
51        .copied()
52        .filter(|name| resolve_in_path(std::path::Path::new(name)).is_none())
53        .collect();
54    if missing.is_empty() {
55        return Ok(());
56    }
57    let list = missing
58        .iter()
59        .map(|t| format!("  - {t}"))
60        .collect::<Vec<_>>()
61        .join("\n");
62    bail!(
63        "missing required tool(s):\n{list}\n\n\
64         Install them and ensure they are on $PATH before retrying."
65    );
66}
67
68/// Resolve the rayon pool width for `cargo ktstr`'s
69/// `resolve_kernel_set` per-spec fan-out.
70///
71/// Reads [`crate::KTSTR_KERNEL_PARALLELISM_ENV`] first; if the env
72/// var is set to a non-zero, parseable `usize`, that value wins.
73/// Otherwise falls back to [`std::thread::available_parallelism`]
74/// — the host's logical CPU count, the right ceiling for
75/// download-bound work that should not outnumber the threads the
76/// host can drive without thrashing the local network. Final
77/// fallback is `1` if `available_parallelism` errors (a sandboxed
78/// or container-limited host), preserving forward progress.
79///
80/// Sentinel handling: `0` and unparseable values fall through
81/// (`from_str` errs on non-digits, and the explicit `n > 0`
82/// guard rejects the parsed-zero case). A typoed export
83/// (`KTSTR_KERNEL_PARALLELISM=abc` or `=0`) degrades to the
84/// host-CPU default rather than disabling parallelism — a
85/// disabled-pool resolve would serialize multi-spec invocations
86/// with no observable signal that the env var was the cause.
87/// The fall-through path emits a `tracing::warn!` carrying the
88/// raw value so the operator sees their typo'd export was
89/// ignored; the default still applies so forward progress is
90/// preserved. Leading/trailing whitespace is trimmed before
91/// parsing so a shell-quoted `=" 8 "` behaves the same as the
92/// unquoted form.
93///
94/// Extracted from cargo-ktstr's `resolve_kernel_set` so the
95/// parsing rules live in one place; the cargo-ktstr binary
96/// invokes this and feeds the result into
97/// [`rayon::ThreadPoolBuilder::num_threads`]. Lives in the
98/// `cli` module rather than in the binary so it's reachable
99/// from rustdoc and from the lib's unit-test harness.
100pub fn resolve_kernel_parallelism() -> usize {
101    if let Ok(raw) = std::env::var(crate::KTSTR_KERNEL_PARALLELISM_ENV) {
102        let trimmed = raw.trim();
103        match trimmed.parse::<usize>() {
104            Ok(n) if n > 0 => return n,
105            _ => {
106                tracing::warn!(
107                    env_var = crate::KTSTR_KERNEL_PARALLELISM_ENV,
108                    value = %raw,
109                    "KTSTR_KERNEL_PARALLELISM={raw:?} failed to parse, using default",
110                );
111            }
112        }
113    }
114    std::thread::available_parallelism()
115        .map(|n| n.get())
116        .unwrap_or(1)
117}
118
119/// Search PATH for a bare executable name.
120fn resolve_in_path(name: &std::path::Path) -> Option<std::path::PathBuf> {
121    use std::os::unix::fs::PermissionsExt;
122    let path_var = std::env::var_os("PATH")?;
123    for dir in std::env::split_paths(&path_var) {
124        let candidate = dir.join(name);
125        if let Ok(meta) = std::fs::metadata(&candidate)
126            && meta.is_file()
127            && meta.permissions().mode() & 0o111 != 0
128        {
129            return Some(candidate);
130        }
131    }
132    None
133}
134
135/// Resolve `--include-files` arguments into `(archive_path, host_path)` pairs.
136///
137/// Each path is resolved as follows:
138/// - Explicit paths (starting with `/`, `.`, `..`, or containing `/`): must exist.
139/// - Bare names: searched in PATH.
140/// - Directories: walked recursively via `walkdir`, following symlinks.
141///   The directory's basename becomes the root under `include-files/`.
142///   Non-regular files (sockets, pipes, device nodes) are skipped.
143///   Empty directories produce a warning to stderr.
144/// - Regular files: included directly as `include-files/<filename>`.
145pub fn resolve_include_files(
146    paths: &[std::path::PathBuf],
147) -> Result<Vec<(String, std::path::PathBuf)>> {
148    use std::path::{Component, PathBuf};
149
150    let mut resolved_includes: Vec<(String, PathBuf)> = Vec::new();
151    for path in paths {
152        let is_explicit_path = {
153            matches!(
154                path.components().next(),
155                Some(Component::RootDir | Component::CurDir | Component::ParentDir)
156            ) || path.components().count() > 1
157        };
158        let resolved = if is_explicit_path {
159            anyhow::ensure!(
160                path.exists(),
161                "--include-files path not found: {}",
162                path.display()
163            );
164            path.clone()
165        } else {
166            // Bare name: search PATH.
167            if path.exists() {
168                path.clone()
169            } else {
170                resolve_in_path(path).ok_or_else(|| {
171                    anyhow::anyhow!("-i {}: not found in filesystem or PATH", path.display())
172                })?
173            }
174        };
175        if resolved.is_dir() {
176            let dir_name = resolved
177                .file_name()
178                .ok_or_else(|| {
179                    anyhow::anyhow!("include directory has no name: {}", resolved.display())
180                })?
181                .to_string_lossy()
182                .to_string();
183            let prefix = format!("include-files/{dir_name}");
184            let mut count = 0usize;
185            for entry in walkdir::WalkDir::new(&resolved).follow_links(true) {
186                let entry = entry.map_err(|e| anyhow::anyhow!("-i {}: {e}", resolved.display()))?;
187                if !entry.file_type().is_file() {
188                    continue;
189                }
190                let rel = entry
191                    .path()
192                    .strip_prefix(&resolved)
193                    .expect("walkdir entry is under root");
194                let archive_path = format!("{prefix}/{}", rel.display());
195                resolved_includes.push((archive_path, entry.into_path()));
196                count += 1;
197            }
198            if count == 0 {
199                eprintln!(
200                    "warning: -i {}: directory contains no regular files",
201                    resolved.display()
202                );
203            }
204        } else {
205            let file_name = resolved
206                .file_name()
207                .ok_or_else(|| {
208                    anyhow::anyhow!("include file has no filename: {}", resolved.display())
209                })?
210                .to_string_lossy();
211            let archive_path = format!("include-files/{file_name}");
212            resolved_includes.push((archive_path, resolved));
213        }
214    }
215
216    // Detect duplicate archive paths (e.g. `-i ./a/dir -i ./b/dir` both
217    // containing the same relative file). The cpio format silently
218    // overwrites earlier entries, so duplicates must be caught here.
219    let mut seen = std::collections::HashMap::<&str, &std::path::Path>::new();
220    for (archive_path, host_path) in &resolved_includes {
221        if let Some(prev) = seen.insert(archive_path.as_str(), host_path.as_path()) {
222            anyhow::bail!(
223                "duplicate include path '{}': provided by both {} and {}",
224                archive_path,
225                prev.display(),
226                host_path.display(),
227            );
228        }
229    }
230
231    Ok(resolved_includes)
232}
233
234/// Look up a cache key, checking local first, then remote (if enabled).
235///
236/// `cli_label` prefixes diagnostic output (e.g. `"ktstr"` or
237/// `"cargo ktstr"`).
238pub fn cache_lookup(
239    cache: &crate::cache::CacheDir,
240    cache_key: &str,
241    cli_label: &str,
242) -> Option<crate::cache::CacheEntry> {
243    // `CacheDir::lookup` emits the per-lookup "unstripped vmlinux"
244    // warning on any local hit whose entry was stored via the
245    // strip-fallback path. The remote-lookup path here funnels
246    // downloads through `CacheDir::store`, which runs its own strip
247    // pipeline and reports via `tracing::warn!` at store time — so the
248    // warning coverage is uniform across local and remote cache
249    // hits without an additional check here.
250    if let Some(entry) = cache.lookup(cache_key) {
251        return Some(entry);
252    }
253
254    if crate::remote_cache::is_enabled() {
255        return crate::remote_cache::remote_lookup(cache, cache_key, cli_label);
256    }
257
258    None
259}
260
261/// Resolve a Version or CacheKey identifier to a cache entry directory.
262///
263/// Lookup order: local cache, then the remote GHA cache when
264/// `remote_cache::is_enabled()` returns true. Miss behavior differs
265/// by variant:
266/// - **Version**: major.minor prefixes (e.g. `"6.14"`) resolve to
267///   the latest patch via [`crate::fetch::fetch_version_for_prefix`]
268///   first. On full miss, downloads the kernel from kernel.org,
269///   builds it, and stores it in the cache via
270///   [`download_and_cache_version`].
271/// - **CacheKey**: errors on miss — cache keys are content-hashes
272///   and not downloadable. The error hint suggests running
273///   `{cli_label} kernel list`.
274///
275/// `cli_label` is the human-facing command name (`"ktstr"` or
276/// `"cargo ktstr"`) threaded into status output and error messages.
277pub fn resolve_cached_kernel(
278    id: &crate::kernel_path::KernelId,
279    cli_label: &str,
280    mp: Option<&crate::cli::FetchProgress>,
281) -> Result<std::path::PathBuf> {
282    use crate::kernel_path::KernelId;
283    match id {
284        KernelId::Version(ver) => {
285            // Major.minor prefix (e.g. "6.14") → resolve to latest patch.
286            let resolved = if crate::fetch::is_major_minor_prefix(ver) {
287                crate::fetch::fetch_version_for_prefix(
288                    crate::fetch::shared_client(),
289                    ver,
290                    cli_label,
291                )?
292            } else {
293                ver.clone()
294            };
295            let cache = crate::cache::CacheDir::new()?;
296            let (arch, _) = crate::fetch::arch_info();
297            let cache_key = format!("{resolved}-tarball-{arch}-kc{}", crate::cache_key_suffix());
298            if let Some(entry) = cache_lookup(&cache, &cache_key, cli_label) {
299                // lookup() returns Some only for valid-metadata entries.
300                return Ok(entry.path);
301            }
302            // Cache miss: download and build the requested version.
303            // cpu_cap is None here — resolve_cached_kernel is reached
304            // from test/coverage/shell/run/verifier (via
305            // resolve_kernel_image), and --cpu-cap is scoped to the
306            // explicit `kernel build` / `shell --no-perf-mode` paths
307            // only; the auto-build-on-miss codepath is outside that
308            // scope by design.
309            download_and_cache_version(&resolved, cli_label, None, mp)
310        }
311        KernelId::CacheKey(key) => {
312            let cache = crate::cache::CacheDir::new()?;
313            if let Some(entry) = cache_lookup(&cache, key, cli_label) {
314                return Ok(entry.path);
315            }
316            bail!(
317                "cache key {key} not found. \
318                 Run `{cli_label} kernel list` to see available entries."
319            )
320        }
321        KernelId::Path(_) => bail!("resolve_cached_kernel called with Path variant"),
322        // Multi-kernel specs cannot resolve to a single cache entry.
323        // This function returns one path; range/git fan-out belongs
324        // upstream in the dispatch loop that iterates kernels. Bail
325        // with an actionable redirect that cites the value the user
326        // wrote — `KernelId::Display` renders Range as `start..=end`
327        // (or `start..end`) and Git as `git+URL#tag=NAME` /
328        // `#branch=NAME` / `#sha=HASH` (a bare `git+URL#REF` only for
329        // the rejected Unknown kind), matching the sibling cache-key
330        // bail above that cites `{key}`.
331        //
332        // Run `validate()` first so an inverted range surfaces the
333        // specific "swap the endpoints" diagnostic before the
334        // generic "not yet supported" redirect masks it. Operators
335        // with a typo see the actionable fix; valid-but-unsupported
336        // specs get the redirect.
337        KernelId::Range { .. } | KernelId::Git { .. } => {
338            id.validate()
339                .map_err(|e| anyhow::anyhow!("--kernel {id}: {e}"))?;
340            bail!(
341                "--kernel {id}: kernel ranges and git sources are not \
342                 yet supported in this context — use a single kernel \
343                 version, cache key, or path"
344            )
345        }
346        // Local packages and distro kernels acquire into the cache
347        // (download + extract, or unpack local files) and resolve to
348        // the resulting entry directory. Validate first so a malformed
349        // distro release surfaces its specific diagnostic.
350        KernelId::Package { path } => {
351            id.validate()
352                .map_err(|e| anyhow::anyhow!("--kernel {id}: {e}"))?;
353            crate::distro::acquire::acquire_package_kernel(std::slice::from_ref(path))
354        }
355        KernelId::Distro { kind, release } => {
356            id.validate()
357                .map_err(|e| anyhow::anyhow!("--kernel {id}: {e}"))?;
358            crate::distro::acquire::acquire_distro_kernel(*kind, release.as_deref(), cli_label, mp)
359        }
360    }
361}
362
363/// Policy controlling `resolve_kernel_image` behavior across binaries.
364///
365/// The resolution pipeline — directory auto-build, version
366/// auto-download, cache lookup — is shared. `KernelResolvePolicy`
367/// carries the per-binary knobs documented on each field.
368pub struct KernelResolvePolicy<'a> {
369    /// Accept raw kernel image files (e.g. `bzImage`, `Image`) passed
370    /// as `--kernel`. `ktstr` uses `false` (rejects); `cargo ktstr`
371    /// uses `true` (accepts).
372    pub accept_raw_image: bool,
373    /// CLI label for diagnostic status messages (e.g. `"ktstr"`,
374    /// `"cargo ktstr"`), threaded into auto-build and auto-download
375    /// status output.
376    pub cli_label: &'a str,
377}
378
379/// Resolve a kernel identifier to a bootable image path.
380///
381/// Handles `KernelId` variants: directory (auto-build), version
382/// string, and cache key. Raw image file acceptance is controlled by
383/// `policy.accept_raw_image`. The `None` case resolves automatically
384/// via cache then filesystem, falling back to auto-download.
385pub fn resolve_kernel_image(
386    kernel: Option<&str>,
387    policy: &KernelResolvePolicy<'_>,
388) -> Result<std::path::PathBuf> {
389    use crate::kernel_path::KernelId;
390
391    if let Some(val) = kernel {
392        match KernelId::parse(val) {
393            KernelId::Path(p) => {
394                let path = std::path::PathBuf::from(&p);
395                if path.is_dir() {
396                    // `None` for cpu_cap: resolve_kernel_image is
397                    // called by test/coverage/shell/run/verifier —
398                    // subcommands where --cpu-cap is not exposed.
399                    // The two kernel-build entry points
400                    // (ktstr/cargo-ktstr `kernel build`) call
401                    // resolve_kernel_dir directly with their flag-
402                    // derived cap and do NOT go through
403                    // resolve_kernel_image.
404                    resolve_kernel_dir(&path, policy.cli_label, None)
405                } else if path.is_file() {
406                    if policy.accept_raw_image {
407                        Ok(path)
408                    } else {
409                        // Raw kernel image file — reject. Use a source
410                        // directory or version string so kconfig validation
411                        // and caching work correctly.
412                        bail!(
413                            "--kernel {}: raw image files are not supported. \
414                             Pass a source directory, version, or cache key.",
415                            path.display()
416                        )
417                    }
418                } else {
419                    bail!("kernel path not found: {}", path.display())
420                }
421            }
422            id @ (KernelId::Version(_) | KernelId::CacheKey(_)) => {
423                let cache_dir = resolve_cached_kernel(&id, policy.cli_label, None)?;
424                crate::kernel_path::find_image_in_dir(&cache_dir).ok_or_else(|| {
425                    anyhow::anyhow!("no kernel image found in {}", cache_dir.display())
426                })
427            }
428            // Multi-kernel specs cannot resolve to a single image
429            // here. The dispatch loop that fans out range expansion
430            // and git fetch lives one level up at the test/coverage/
431            // verifier subcommand entry; this resolver is the
432            // single-kernel leaf. Bail with an actionable redirect
433            // so the user knows the spec is recognised but the
434            // calling subcommand hasn't wired up the multi-kernel
435            // pipeline yet.
436            //
437            // Run `validate()` first so an inverted range surfaces
438            // the specific "swap the endpoints" diagnostic before
439            // the generic "not yet supported" redirect masks it.
440            id @ (KernelId::Range { .. } | KernelId::Git { .. }) => {
441                id.validate()
442                    .map_err(|e| anyhow::anyhow!("--kernel {val}: {e}"))?;
443                bail!(
444                    "--kernel {val}: kernel ranges and git sources are not \
445                     yet supported in this context — use a single kernel \
446                     version, cache key, or path"
447                )
448            }
449            id @ (KernelId::Package { .. } | KernelId::Distro { .. }) => {
450                id.validate()
451                    .map_err(|e| anyhow::anyhow!("--kernel {val}: {e}"))?;
452                let cache_dir = resolve_cached_kernel(&id, policy.cli_label, None)?;
453                crate::kernel_path::find_image_in_dir(&cache_dir).ok_or_else(|| {
454                    anyhow::anyhow!("no kernel image found in {}", cache_dir.display())
455                })
456            }
457        }
458    } else {
459        match crate::find_kernel()? {
460            Some(image) => Ok(image),
461            None => auto_download_kernel(policy.cli_label),
462        }
463    }
464}
465
466/// Auto-download, build, and cache the latest stable kernel.
467///
468/// Called when no --kernel is specified and no kernel is found via
469/// cache or filesystem. Resolves the latest stable version and
470/// delegates to [`download_and_cache_version`]. `cli_label` prefixes
471/// status output (e.g. `"ktstr"`, `"cargo ktstr"`).
472pub fn auto_download_kernel(cli_label: &str) -> Result<std::path::PathBuf> {
473    status(&format!(
474        "{cli_label}: no kernel found, downloading latest stable"
475    ));
476
477    let sp = Spinner::start("Fetching latest kernel version...");
478    let ver = crate::fetch::fetch_latest_stable_version(crate::fetch::shared_client(), cli_label)?;
479    sp.finish(format!("Latest stable: {ver}"));
480
481    let cache_dir = download_and_cache_version(&ver, cli_label, None, None)?;
482    let (_, image_name) = crate::fetch::arch_info();
483    Ok(cache_dir.join(image_name))
484}
485
486/// Download a specific kernel version, build it, and store in the
487/// cache. Returns the cache entry directory path (NOT the image path).
488///
489/// Checks the cache one more time with the resolved version to cover
490/// races and prefix-resolved entries. Delegates to
491/// [`kernel_build_pipeline`] for configure/build/validate/cache.
492///
493/// `cpu_cap` forwards the resource-budget cap to the pipeline so
494/// the LLC flock + cgroup sandbox phases honour it. `None` means
495/// "reserve 30% of the allowed-CPU set" (see
496/// [`CpuCap::resolve`](crate::vmm::host_topology::CpuCap::resolve)).
497///
498/// `mp` is the progress group spanning BOTH the download and the build:
499/// the parallel resolve's shared group, or `None` for a single-shot
500/// caller (shell auto-fetch, monitor, auto-download), in which case a
501/// local group is created here and passed through to
502/// `kernel_build_pipeline`. The build renders through this same group
503/// (as `step_bar` spinners), so the group stays live across the build
504/// with no standalone `Spinner` to collide with.
505pub fn download_and_cache_version(
506    version: &str,
507    cli_label: &str,
508    cpu_cap: Option<crate::vmm::host_topology::CpuCap>,
509    mp: Option<&crate::cli::FetchProgress>,
510) -> Result<std::path::PathBuf> {
511    let (arch, _) = crate::fetch::arch_info();
512    let cache_key = format!("{version}-tarball-{arch}-kc{}", crate::cache_key_suffix());
513
514    // Check cache one more time with the resolved version.
515    if let Ok(cache) = crate::cache::CacheDir::new()
516        && let Some(entry) = cache_lookup(&cache, &cache_key, cli_label)
517    {
518        return Ok(entry.path);
519    }
520
521    let tmp_dir = tempfile::TempDir::new()?;
522
523    // One progress group spans BOTH the download and the build: the
524    // parallel resolve's shared group via `mp`, or a local group for
525    // single-shot callers (`mp == None`). The build now renders through
526    // this same group rather than a standalone Spinner, so the group
527    // legitimately stays live across the build with no Spinner to
528    // collide with.
529    //
530    // `skip_sha256 = false`: the auto-resolve path (test/coverage
531    // /llvm-cov / shell auto-fetch) never bypasses checksum
532    // verification. The bypass is reachable only via the explicit
533    // `kernel build --skip-sha256` flag — auto-resolution must keep
534    // the strong manifest guarantee since the operator has not
535    // opted into the unverified fallback.
536    let owned_group;
537    let group = match mp {
538        Some(fp) => fp,
539        None => {
540            owned_group = crate::cli::FetchProgress::new();
541            &owned_group
542        }
543    };
544    let acquired = crate::fetch::download_tarball(
545        crate::fetch::shared_client(),
546        version,
547        tmp_dir.path(),
548        cli_label,
549        false,
550        Some(group),
551    )?;
552
553    let cache = crate::cache::CacheDir::new()?;
554    let result = kernel_build_pipeline(
555        &acquired,
556        &cache,
557        cli_label,
558        false,
559        false,
560        false,
561        cpu_cap,
562        None,
563        Some(group),
564    )?;
565
566    match result.entry {
567        Some(entry) => Ok(entry.path),
568        None => bail!(
569            "kernel built but cache store failed — cannot return image from temporary directory"
570        ),
571    }
572}
573
574/// Expand a kernel-version range to the list of stable / longterm
575/// releases that fall inside `[start, end]` inclusive.
576///
577/// Fetches kernel.org's `releases.json` once via
578/// `crate::fetch::cached_releases`, filters to rows whose `moniker`
579/// is `stable` or `longterm` (matching the policy
580/// [`crate::fetch::fetch_latest_stable_version`] uses for "is this a
581/// production release we want to test against"), drops any version
582/// outside the inclusive interval, and returns the surviving versions
583/// sorted ascending by `(major, minor, patch, rc)` tuple. Empty result
584/// is a hard error — an empty range either reflects a typo (start/end
585/// don't bracket any active series) or releases.json missing rows
586/// the operator expected, and silently iterating over zero kernels
587/// would mask both. The `KernelId::Range` doc comment promises "every
588/// release in the range" which a quiet no-op contradicts.
589///
590/// Range endpoints are NOT required to appear in releases.json — the
591/// interval is half-the-numeric, half-presence: `6.10..6.16` selects
592/// every stable release inside that span, regardless of whether `6.10`
593/// and `6.16` themselves are still listed (e.g. one has been pruned
594/// from active maintenance). This matches the inclusive-numeric-comparison
595/// semantics in [`crate::kernel_path::KernelId::validate`] and lets a
596/// range from an EOL series survive even after the endpoint version
597/// itself becomes unavailable.
598///
599/// Endpoint granularity is series-inclusive on BOTH ends: a 2-component
600/// `MAJOR.MINOR` endpoint names the whole series, so `6.11..6.14`
601/// includes every `6.14.N` (not just `6.14.0`). START is series-inclusive
602/// because its `.0` is the series floor; END is widened to the series
603/// ceiling by `range_bounds`. An explicit-patch endpoint (`6.14.2`) is
604/// an exact bound — `6.11..6.14.2` stops at `6.14.2`.
605///
606/// `cli_label` prefixes the kernel.org-fetch status line so the
607/// diagnostic matches the binary that triggered the lookup
608/// (`"ktstr"` vs `"cargo ktstr"`).
609///
610/// When `include_eol` is set, the maintained set from `releases.json`
611/// is unioned with EOL `stable` series enumerated from the gregkh
612/// linux-stable mirror's tags (`crate::fetch::cached_stable_tags`),
613/// then the highest patch of each `(major, minor)` series is taken
614/// across both sources (`select_series_latest_in_range`). Without it
615/// a series dropped from `releases.json` is silently absent —
616/// `6.11..6.14` collapses to just the 6.11 series if 6.12/6.13 are
617/// EOL. If the mirror tag list cannot be fetched, expansion proceeds
618/// against the active-release set alone with a warning; the
619/// empty-result error hints `--include-eol` only when it was not
620/// already set.
621///
622/// Pre-release filter: `mainline` and `linux-next` rows are
623/// excluded by the moniker filter; rc tags carrying a stable
624/// moniker would also be excluded but kernel.org publishes rcs
625/// under `mainline`, so the filter is double-coverage in practice.
626/// Operators who want to test against an rc spell it out as a
627/// single `--kernel 6.16-rc3` rather than expecting the range
628/// expansion to surface it.
629pub fn expand_kernel_range(
630    start: &str,
631    end: &str,
632    cli_label: &str,
633    include_eol: bool,
634) -> Result<Vec<String>> {
635    let (start_key, end_key) = range_bounds(start, end)?;
636
637    crate::ktstr_status!(
638        "{cli_label}: expanding kernel range {start}..{end}{eol}",
639        eol = if include_eol {
640            " (including EOL series)"
641        } else {
642            ""
643        },
644    );
645    // Cached fetch: peer Range specs running in parallel under
646    // `cargo ktstr`'s `resolve_kernel_set` rayon pipeline share
647    // one network round-trip. The first Range to reach this
648    // helper populates [`crate::fetch::RELEASES_CACHE`]; every
649    // subsequent `--kernel A..B` call clones the cached vector
650    // and skips the kernel.org GET. A transient outage on the
651    // first call returns Err and leaves the cache un-populated,
652    // so the next caller re-attempts the network — failures
653    // never poison the cache.
654    let releases = crate::fetch::cached_releases()?;
655    let maintained = filter_and_sort_range(&releases, start_key, end_key);
656
657    // Under `--include-eol`, also enumerate the gregkh stable mirror's
658    // tags. `None` = the ls-remote failed; warn and fall back to the
659    // maintained set alone. The fetch is cached
660    // (`crate::fetch::cached_stable_tags`) so peer ranges share one
661    // ls-remote.
662    let mirror_tags = if include_eol {
663        let tags = crate::fetch::cached_stable_tags();
664        if tags.is_none() {
665            crate::ktstr_status!(
666                "{cli_label}: --include-eol: could not enumerate release tags \
667                 from the stable mirror (ls-remote failed); EOL series may be \
668                 missing from this range"
669            );
670        }
671        tags
672    } else {
673        None
674    };
675    let versions = combine_range_versions(maintained, mirror_tags, start_key, end_key, include_eol);
676
677    if versions.is_empty() {
678        bail!(
679            "kernel range {start}..{end} expanded to 0 stable releases.{hint} \
680             Verify the endpoints, or use a single `--kernel <version>` if you \
681             want a pre-release or archived version.",
682            hint = empty_range_hint(include_eol),
683        );
684    }
685
686    crate::ktstr_status!(
687        "{cli_label}: range expanded to {n} kernel(s): {list}",
688        n = versions.len(),
689        list = versions.join(", "),
690    );
691    Ok(versions)
692}
693
694/// Version-comparison key: `(major, minor, patch, rc)`, ordered so a
695/// release (rc slot `u64::MAX`) sorts above its own release candidates.
696type VersionKey = (u64, u64, u64, u64);
697
698/// Decompose a range's `start` / `end` endpoints into comparison keys,
699/// widening a 2-component `MAJOR.MINOR` END to cover its whole series.
700///
701/// [`decompose_version_for_compare`](crate::kernel_path::decompose_version_for_compare)
702/// maps a missing patch to 0, so a 2-component END like `6.14` becomes
703/// `(6, 14, 0, u64::MAX)` — which as an inclusive upper bound would
704/// exclude every `6.14.N` (N >= 1), since `(6,14,N,MAX) > (6,14,0,MAX)`.
705/// But a `MAJOR.MINOR` END names the whole END series, not just its `.0`
706/// release, so its patch and rc slots are widened to `u64::MAX` to make
707/// the END series-inclusive. This matches START, whose 2-component form
708/// is already series-inclusive because `.0` is the series floor. An
709/// explicit-patch END (`6.14.2`) or an `-rc` END keeps its exact bound.
710///
711/// The END widening is delegated to
712/// [`crate::kernel_path::range_end_key`], which
713/// [`crate::kernel_path::KernelId::validate`] ALSO uses for its
714/// inversion check — so the pre-expansion validation and the expansion
715/// agree on where a range ends (a valid same-series spelling like
716/// `6.14.5..6.14` is not falsely rejected as inverted).
717///
718/// Pure — no I/O — so the endpoint-widening is unit-testable. Errors
719/// name the offending endpoint with the accepted grammar.
720fn range_bounds(start: &str, end: &str) -> Result<(VersionKey, VersionKey)> {
721    use crate::kernel_path::{decompose_version_for_compare, range_end_key};
722
723    let start_key = decompose_version_for_compare(start).ok_or_else(|| {
724        anyhow!(
725            "kernel range start `{start}` is not a parseable version. \
726             Endpoints must match `MAJOR.MINOR[.PATCH][-rcN]`."
727        )
728    })?;
729    let end_key = range_end_key(end).ok_or_else(|| {
730        anyhow!(
731            "kernel range end `{end}` is not a parseable version. \
732             Endpoints must match `MAJOR.MINOR[.PATCH][-rcN]`."
733        )
734    })?;
735    Ok((start_key, end_key))
736}
737
738/// The `--include-eol` hint appended to the empty-range error, present
739/// only when the flag was NOT set — setting it already consulted the
740/// EOL mirror, so suggesting it again would be misleading. Split out so
741/// the conditional is unit-testable without a network round-trip.
742fn empty_range_hint(include_eol: bool) -> &'static str {
743    if include_eol {
744        ""
745    } else {
746        " Pass --include-eol to also expand EOL series absent from releases.json."
747    }
748}
749
750/// Combine the maintained (releases.json) versions with the optional
751/// EOL mirror tags into the final expanded set.
752///
753/// Pure — the I/O-free core of [`expand_kernel_range`]'s selection,
754/// split out so the union / best-data-wins / EOL-fallback behavior is
755/// unit-testable without the network. When `include_eol` is false the
756/// maintained set is returned verbatim. When true, the maintained set is
757/// unioned with `mirror_tags` (`None` = the mirror ls-remote failed, so
758/// fall back to the maintained set alone) and
759/// [`select_series_latest_in_range`] re-selects the highest patch per
760/// `(major, minor)` across BOTH sources — so a mirror patch newer than
761/// releases.json wins, and a stale mirror never regresses a maintained
762/// version.
763fn combine_range_versions(
764    maintained: Vec<String>,
765    mirror_tags: Option<&[String]>,
766    start_key: VersionKey,
767    end_key: VersionKey,
768    include_eol: bool,
769) -> Vec<String> {
770    if !include_eol {
771        return maintained;
772    }
773    let Some(tags) = mirror_tags else {
774        return maintained;
775    };
776    let mut all = maintained;
777    all.extend(select_series_latest_in_range(tags, start_key, end_key));
778    select_series_latest_in_range(&all, start_key, end_key)
779}
780
781/// Filter [`Release`](crate::fetch::Release) rows to stable+longterm
782/// versions inside `[start_key, end_key]` and return them sorted
783/// ascending by version tuple.
784///
785/// Separated from [`expand_kernel_range`] so the pure filter+sort
786/// logic — moniker rejection, version-tuple bounds check, sort
787/// order — is testable without hitting the network. The wrapper is
788/// a thin adapter that fetches `releases.json` and reports the
789/// outcome to stderr; this helper carries no I/O. Mirrors the
790/// `active_prefixes_from_releases` split applied above.
791fn filter_and_sort_range(
792    releases: &[crate::fetch::Release],
793    start_key: VersionKey,
794    end_key: VersionKey,
795) -> Vec<String> {
796    use crate::kernel_path::decompose_version_for_compare;
797
798    let mut selected: Vec<(String, VersionKey)> = Vec::new();
799    for r in releases {
800        if r.moniker != "stable" && r.moniker != "longterm" {
801            continue;
802        }
803        let Some(key) = decompose_version_for_compare(&r.version) else {
804            continue;
805        };
806        if key < start_key || key > end_key {
807            continue;
808        }
809        selected.push((r.version.clone(), key));
810    }
811    selected.sort_by_key(|s| s.1);
812    selected.into_iter().map(|(v, _)| v).collect()
813}
814
815/// From release version strings (`X.Y.Z`), take the latest patch of each
816/// `(major, minor)` series inside `[start_key, end_key]`, dropping
817/// `-rc*` pre-releases, sorted ascending by version tuple.
818///
819/// Pure — the `--include-eol` counterpart to [`filter_and_sort_range`],
820/// run over the gregkh stable-mirror tags
821/// ([`crate::fetch::cached_stable_tags`]) unioned with the releases.json
822/// versions so an EOL series (dropped from releases.json) still
823/// contributes its highest point release. Uses the SAME
824/// `[start_key, end_key]` tuple bounds as `filter_and_sort_range`, so
825/// maintained and EOL series expand identically.
826fn select_series_latest_in_range(
827    versions: &[String],
828    start_key: VersionKey,
829    end_key: VersionKey,
830) -> Vec<String> {
831    use crate::kernel_path::decompose_version_for_compare;
832    use std::collections::HashMap;
833
834    // (major, minor) -> (patch, version string) of the highest release.
835    let mut best: HashMap<(u64, u64), (u64, String)> = HashMap::new();
836    for v in versions {
837        let Some(key) = decompose_version_for_compare(v) else {
838            continue;
839        };
840        // Drop pre-releases: a release maps its rc slot to u64::MAX (see
841        // decompose_version_for_compare), so `key.3 != MAX` marks an
842        // `-rcN` tag.
843        if key.3 != u64::MAX {
844            continue;
845        }
846        if key < start_key || key > end_key {
847            continue;
848        }
849        let series = (key.0, key.1);
850        let patch = key.2;
851        match best.get(&series) {
852            Some((p, _)) if *p >= patch => {}
853            _ => {
854                best.insert(series, (patch, v.clone()));
855            }
856        }
857    }
858    let mut out: Vec<(VersionKey, String)> = best
859        .into_values()
860        .map(|(_, v)| {
861            let key = decompose_version_for_compare(&v).expect("re-parses: it parsed once above");
862            (key, v)
863        })
864        .collect();
865    out.sort_by_key(|(k, _)| *k);
866    out.into_iter().map(|(_, v)| v).collect()
867}
868
869/// Resolve a `git+URL#tag=/#branch=/#sha=` kernel spec to a cache-entry
870/// directory.
871///
872/// Mirrors [`download_and_cache_version`] for the git source path.
873/// Branch/tag acquisition connects and prepares exactly once, reads the
874/// advertised peeled id from that `Prepare`, then probes the cache and
875/// elects one cross-process producer before receiving any pack. A cache
876/// hit drops the prepared connection; the winner reuses it for receive.
877///
878/// On a cache miss the fetch is routed by ref kind:
879/// - **Branch/tag**: a kind-directed, exact-ref, depth-one in-process
880///   gix fetch into a temp directory (`crate::fetch::git_clone_kinded`
881///   → `git_clone_tag` for a tag, `git_clone` for a branch). GitHub uses
882///   this same path; its codeload endpoint must not silently replace a
883///   requested git ref with an archive acquisition.
884/// - **Explicit immutable GitHub SHA** (`github.com/OWNER/REPO`, via
885///   `crate::fetch::github_archive_url`): a codeload `tar.gz` snapshot
886///   of that commit (`crate::fetch::download_github_archive`). A `sha`
887///   remains unsupported on remotes without a commit-snapshot endpoint.
888///
889/// On a final miss it delegates to [`kernel_build_pipeline`] for
890/// configure/build/validate/cache. Returns the cache entry directory
891/// path — the same shape `download_and_cache_version` returns and
892/// callers feed into the [`crate::KTSTR_KERNEL_ENV`] export.
893///
894/// The cache key contains the ref kind, a fixed-seed ahash of the
895/// length-delimited raw ref, and the full resolved commit. This avoids
896/// filesystem-hostile names and sanitized-ref collisions while keeping
897/// tag, branch, and archive-SHA acquisition identities distinct.
898///
899/// `cli_label` matches the contract the sibling helpers
900/// (`download_and_cache_version`, `resolve_kernel_dir`) use:
901/// it prefixes diagnostic status output and is threaded into
902/// [`kernel_build_pipeline`].
903///
904/// `mp` is the progress group the download/clone bar is added to (the
905/// parallel resolve's shared group). Forwarded to codeload/gix; `None`
906/// uses the standalone non-TTY heartbeat reporter.
907///
908/// Build flags shared with `cargo ktstr kernel build --kernel git+…`:
909/// `force` ignores a preexisting entry when it wins election, so the ref
910/// is refetched and rebuilt without a separate discovery handshake. A
911/// contending force caller coalesces with the already-active exact-key
912/// producer and reuses its publication;
913/// `clean`, `cpu_cap`, and `extra_kconfig` thread into
914/// [`kernel_build_pipeline`] (an `extra_kconfig` fragment also appends
915/// its `-xkc{hash}` suffix to the cache key so an extras build lands a
916/// distinct slot). The auto-discovery test path passes `false` / `None`
917/// for all four; only `kernel build` populates them.
918enum GitResolveElection {
919    Builder {
920        cache_key: String,
921        guard: crate::cache::GitBuilderLockGuard,
922    },
923    Cached(std::path::PathBuf),
924    Contended {
925        cache_key: String,
926    },
927}
928
929fn git_cache_key_with_extra(
930    ref_kind: crate::kernel_path::GitRefKind,
931    git_ref: &str,
932    commit_hash: &str,
933    extra_kconfig: Option<&str>,
934) -> String {
935    let mut key = crate::fetch::git_cache_key(ref_kind, git_ref, commit_hash);
936    crate::cli::append_extra_kconfig_suffix(&mut key, extra_kconfig);
937    key
938}
939
940fn report_git_builder_wait(
941    cli_label: &str,
942    cache_key: &str,
943    elapsed: std::time::Duration,
944    mp: Option<&crate::cli::FetchProgress>,
945) {
946    let line = format!(
947        "{cli_label}: waiting for peer building {cache_key} (elapsed {})",
948        humantime::format_duration(elapsed)
949    );
950    match mp {
951        Some(fp) => fp.println(&line),
952        None => super::print_status_line(&line),
953    }
954}
955
956/// Wait until the content-key producer exits. The acquired guard is
957/// returned to the waiter, which first checks for the peer's published
958/// cache entry and retains the guard for failure takeover on a miss.
959fn wait_for_git_builder(
960    cache: &crate::cache::CacheDir,
961    cache_key: &str,
962    cli_label: &str,
963    mp: Option<&crate::cli::FetchProgress>,
964) -> Result<crate::cache::GitBuilderLockGuard> {
965    const POLL: std::time::Duration = std::time::Duration::from_millis(100);
966    const HEARTBEAT: std::time::Duration = std::time::Duration::from_secs(10);
967    let started = std::time::Instant::now();
968    let mut next_heartbeat = std::time::Duration::ZERO;
969    loop {
970        if crate::fetch::git_operation_interrupted() {
971            bail!("source acquisition interrupted while waiting for peer builder");
972        }
973        if let Some(guard) = cache.try_acquire_git_builder_lock(cache_key)? {
974            return Ok(guard);
975        }
976        let elapsed = started.elapsed();
977        if elapsed >= next_heartbeat {
978            report_git_builder_wait(cli_label, cache_key, elapsed, mp);
979            next_heartbeat = elapsed + HEARTBEAT;
980        }
981        std::thread::sleep(POLL);
982    }
983}
984
985#[allow(clippy::too_many_arguments)]
986pub fn resolve_git_kernel(
987    url: &str,
988    git_ref: &str,
989    ref_kind: crate::kernel_path::GitRefKind,
990    cli_label: &str,
991    mp: Option<&crate::cli::FetchProgress>,
992    force: bool,
993    clean: bool,
994    cpu_cap: Option<crate::cli::CpuCap>,
995    extra_kconfig: Option<&str>,
996) -> Result<std::path::PathBuf> {
997    let cache = crate::cache::CacheDir::new()?;
998    let tmp_dir = tempfile::TempDir::new()?;
999    let (acquired, _builder_guard) = match ref_kind {
1000        crate::kernel_path::GitRefKind::Branch | crate::kernel_path::GitRefKind::Tag => {
1001            // A waiter that observes a failed producer retains that
1002            // content key's guard and reconnects. If the ref moved while
1003            // waiting, the next gate drops the stale-key guard and
1004            // independently elects on the newly advertised key.
1005            let mut takeover: Option<(String, crate::cache::GitBuilderLockGuard)> = None;
1006            loop {
1007                let pending = takeover.take();
1008                let outcome = crate::fetch::git_clone_kinded_gated(
1009                    url,
1010                    git_ref,
1011                    ref_kind,
1012                    tmp_dir.path(),
1013                    cli_label,
1014                    mp,
1015                    |commit_id| {
1016                        let commit_hash = format!("{commit_id}");
1017                        let cache_key = git_cache_key_with_extra(
1018                            ref_kind,
1019                            git_ref,
1020                            &commit_hash,
1021                            extra_kconfig,
1022                        );
1023
1024                        if let Some((held_key, guard)) = pending {
1025                            if held_key == cache_key {
1026                                return Ok(crate::fetch::ExactRefGate::Fetch(
1027                                    GitResolveElection::Builder { cache_key, guard },
1028                                ));
1029                            }
1030                            drop(guard);
1031                        }
1032
1033                        if !force && let Some(entry) = cache_lookup(&cache, &cache_key, cli_label) {
1034                            return Ok(crate::fetch::ExactRefGate::Skip(
1035                                GitResolveElection::Cached(entry.path),
1036                            ));
1037                        }
1038                        match cache.try_acquire_git_builder_lock(&cache_key)? {
1039                            Some(guard) => {
1040                                // Close the race between the first probe
1041                                // and election. Force intentionally
1042                                // ignores an entry that predated its own
1043                                // successful election.
1044                                if !force
1045                                    && let Some(entry) = cache_lookup(&cache, &cache_key, cli_label)
1046                                {
1047                                    Ok(crate::fetch::ExactRefGate::Skip(
1048                                        GitResolveElection::Cached(entry.path),
1049                                    ))
1050                                } else {
1051                                    Ok(crate::fetch::ExactRefGate::Fetch(
1052                                        GitResolveElection::Builder { cache_key, guard },
1053                                    ))
1054                                }
1055                            }
1056                            None => Ok(crate::fetch::ExactRefGate::Skip(
1057                                GitResolveElection::Contended { cache_key },
1058                            )),
1059                        }
1060                    },
1061                )?;
1062
1063                match outcome {
1064                    crate::fetch::GitCloneOutcome::Fetched {
1065                        mut acquired,
1066                        token: GitResolveElection::Builder { cache_key, guard },
1067                    } => {
1068                        acquired.cache_key = cache_key;
1069                        break (acquired, guard);
1070                    }
1071                    crate::fetch::GitCloneOutcome::Fetched { .. } => {
1072                        unreachable!("only an elected builder may fetch")
1073                    }
1074                    crate::fetch::GitCloneOutcome::Skipped {
1075                        token: GitResolveElection::Cached(path),
1076                        commit_hash,
1077                    } => {
1078                        let short = &commit_hash[..7.min(commit_hash.len())];
1079                        let msg =
1080                            format!("{cli_label}: git+{url} -> {short} cached; skipping fetch");
1081                        match mp {
1082                            Some(fp) => fp.println(&msg),
1083                            None => super::print_status_line(&msg),
1084                        }
1085                        return Ok(path);
1086                    }
1087                    crate::fetch::GitCloneOutcome::Skipped {
1088                        token: GitResolveElection::Contended { cache_key },
1089                        ..
1090                    } => {
1091                        let guard = wait_for_git_builder(&cache, &cache_key, cli_label, mp)?;
1092                        if let Some(entry) = cache_lookup(&cache, &cache_key, cli_label) {
1093                            return Ok(entry.path);
1094                        }
1095                        takeover = Some((cache_key, guard));
1096                    }
1097                    crate::fetch::GitCloneOutcome::Skipped { .. } => {
1098                        unreachable!("builder token cannot skip")
1099                    }
1100                }
1101            }
1102        }
1103        crate::kernel_path::GitRefKind::Sha => {
1104            let commit_hash = git_ref.to_ascii_lowercase();
1105            let cache_key =
1106                git_cache_key_with_extra(ref_kind, git_ref, &commit_hash, extra_kconfig);
1107            if !force && let Some(entry) = cache_lookup(&cache, &cache_key, cli_label) {
1108                return Ok(entry.path);
1109            }
1110            let builder_guard = match cache.try_acquire_git_builder_lock(&cache_key)? {
1111                Some(guard) => guard,
1112                None => {
1113                    let guard = wait_for_git_builder(&cache, &cache_key, cli_label, mp)?;
1114                    if let Some(entry) = cache_lookup(&cache, &cache_key, cli_label) {
1115                        return Ok(entry.path);
1116                    }
1117                    guard
1118                }
1119            };
1120            if !force && let Some(entry) = cache_lookup(&cache, &cache_key, cli_label) {
1121                return Ok(entry.path);
1122            }
1123            let archive_url =
1124                crate::fetch::github_archive_url(url, &commit_hash).ok_or_else(|| {
1125                    anyhow::anyhow!(
1126                        "git+{url}#sha={git_ref}: commit snapshots are supported only for \
1127                     github.com/OWNER/REPO remotes; use a #tag= or #branch= here"
1128                    )
1129                })?;
1130            let short = &commit_hash[..7.min(commit_hash.len())];
1131            let msg = format!(
1132                "{cli_label}: fetching explicit immutable GitHub commit {short} as a source snapshot"
1133            );
1134            match mp {
1135                Some(fp) => fp.println(&msg),
1136                None => super::print_status_line(&msg),
1137            }
1138            let mut acquired = crate::fetch::download_github_archive(
1139                crate::fetch::shared_client(),
1140                &archive_url,
1141                git_ref,
1142                &commit_hash,
1143                tmp_dir.path(),
1144                cli_label,
1145                mp,
1146            )?;
1147            acquired.cache_key = cache_key;
1148            (acquired, builder_guard)
1149        }
1150        crate::kernel_path::GitRefKind::Unknown => {
1151            bail!("git+{url}: ref kind could not be determined")
1152        }
1153    };
1154
1155    // `--force` fail-fast: if tests are holding the cache-entry lock,
1156    // bail with the PID list rather than silently waiting to stomp the
1157    // in-use entry (mirrors kernel_build_one). The guard drops before
1158    // the pipeline runs.
1159    if force {
1160        let _force_check = cache.try_acquire_exclusive_lock(&acquired.cache_key)?;
1161    }
1162
1163    // is_local_source = false: a freshly cloned tree is treated the same
1164    // as a tarball download — no `make mrproper` skip-warning, no
1165    // compile_commands.json generation (acquired.is_temp gates that
1166    // inside the pipeline). `clean`, `cpu_cap`, and `extra_kconfig` come
1167    // from `cargo ktstr kernel build`; the auto-discovery test path
1168    // passes false / None.
1169    let result = kernel_build_pipeline(
1170        &acquired,
1171        &cache,
1172        cli_label,
1173        clean,
1174        false,
1175        false,
1176        cpu_cap,
1177        extra_kconfig,
1178        mp,
1179    )?;
1180
1181    match result.entry {
1182        Some(entry) => Ok(entry.path),
1183        None => bail!(
1184            "kernel built from git+{url}#{git_ref} but cache store failed — \
1185             cannot return image from temporary directory"
1186        ),
1187    }
1188}
1189
1190/// Cache-hit signal returned from [`resolve_kernel_dir_to_entry`]
1191/// when a clean source tree's cache entry was found and reused
1192/// without invoking [`kernel_build_pipeline`].
1193///
1194/// Carries the cache key and the persisted `built_at` ISO-8601
1195/// timestamp so callers can render a user-facing line that names
1196/// both the cache identity and the build age. `None`
1197/// ([`KernelDirOutcome::cache_hit`] returns `None`) means the build
1198/// pipeline ran — either to populate the cache (clean-tree cache
1199/// miss) or to build directly without storing (dirty-tree path).
1200#[derive(Debug, Clone)]
1201pub struct KernelDirCacheHit {
1202    /// Cache key that resolved to this entry, e.g.
1203    /// `local-abc1234-x86_64-kc{suffix}` or
1204    /// `local-abc1234-x86_64-cfgdeadbeef-kc{suffix}` when the source
1205    /// tree carried a user `.config`.
1206    pub cache_key: String,
1207    /// ISO-8601 timestamp recorded in the entry's `metadata.json`
1208    /// at store time. Suitable for `humantime::parse_rfc3339`.
1209    pub built_at: String,
1210}
1211
1212/// Result bundle from [`resolve_kernel_dir_to_entry`].
1213///
1214/// Bundles the resolved boot-image directory, the cache-hit
1215/// signal, and the dirty-tree flag so callers do not have to
1216/// re-run `gix::open` to learn whether the build was reproducible.
1217/// The dirty flag is the single source of truth for downstream
1218/// label decoration ([`crate::test_support::sanitize_kernel_label`]'s
1219/// upstream caller appends `_dirty` so test reports show the run
1220/// used a non-reproducible build).
1221///
1222/// `non_exhaustive` so a future field (e.g. cache miss vs cache
1223/// store-failed distinction) can land without breaking external
1224/// destructuring. Construction goes through field literals at the
1225/// definition site only — every external consumer reads via the
1226/// public field accessors.
1227#[derive(Debug, Clone)]
1228#[non_exhaustive]
1229pub struct KernelDirOutcome {
1230    /// Directory that holds the resolved boot image.
1231    ///
1232    /// - Clean tree: cache entry directory under one of the
1233    ///   `local-{hash7}-{arch}[-cfg{user_config}]-kc{suffix}` or
1234    ///   `local-unknown-{path_hash}-{arch}-kc{suffix}` shapes (see
1235    ///   [`crate::fetch::compose_local_cache_key`]); boot image at
1236    ///   `<dir>/<image_name>`.
1237    /// - Dirty tree: canonical source-tree directory, boot image at
1238    ///   `<dir>/arch/x86/boot/bzImage` (x86_64) or
1239    ///   `<dir>/arch/arm64/boot/Image` (aarch64) — the kernel
1240    ///   build-tree arch subdir (`x86`/`arm64`), not the
1241    ///   arch_info() name (`x86_64`/`aarch64`).
1242    ///
1243    /// Both shapes are valid inputs to
1244    /// [`crate::kernel_path::find_image_in_dir`].
1245    pub dir: std::path::PathBuf,
1246    /// `Some` when the resolution short-circuited on a cache hit —
1247    /// the build pipeline did not run. `None` when the build
1248    /// pipeline ran (clean-tree miss-then-build OR dirty-tree
1249    /// build-without-store). [`is_dirty`](Self::is_dirty)
1250    /// distinguishes the two `None` cases.
1251    pub cache_hit: Option<KernelDirCacheHit>,
1252    /// Whether the source tree was non-reproducible. Union of two
1253    /// signals:
1254    ///
1255    /// - Acquire-time inspection by
1256    ///   [`crate::fetch::local_source`] (uncommitted modifications
1257    ///   before the build started, OR a non-git tree that has no
1258    ///   commit hash to record).
1259    /// - Post-build re-check from
1260    ///   [`crate::fetch::inspect_local_source_state`] (worktree
1261    ///   edited, branch flipped, or commit landed during `make`).
1262    ///
1263    /// Either signal flips this to `true`. Always `false` on a cache
1264    /// hit — the cache lookup gate requires a clean tree at acquire
1265    /// time and the build pipeline does not run.
1266    pub is_dirty: bool,
1267}
1268
1269/// Resolve a source-tree path through the local-kernel cache,
1270/// returning a [`KernelDirOutcome`] that carries the boot-image
1271/// directory, the cache-hit signal, and the dirty-tree flag.
1272///
1273/// For a clean source tree:
1274///   - Cache hit → `outcome.dir` is the cache entry directory,
1275///     `outcome.cache_hit` is `Some(KernelDirCacheHit)`,
1276///     `outcome.is_dirty` is `false`. The build pipeline does not
1277///     run.
1278///   - Cache miss, no mid-build mutation → runs
1279///     [`kernel_build_pipeline`] which builds in the source tree and
1280///     stores a stripped vmlinux + boot image under the cache entry;
1281///     `outcome.dir` is the cache entry directory,
1282///     `outcome.cache_hit` is `None`, `outcome.is_dirty` is `false`.
1283///   - Cache miss, mid-build mutation observed by the pipeline's
1284///     post-build re-check → the cache store is skipped to avoid
1285///     recording a stale identity, `outcome.dir` is the canonical
1286///     source-tree directory, `outcome.cache_hit` is `None`,
1287///     `outcome.is_dirty` is `true`.
1288///
1289/// For a dirty source tree:
1290///   - [`kernel_build_pipeline`] skips the cache store
1291///     (`is_dirty` short-circuit at the cache-store boundary) and
1292///     returns the source-tree image. `outcome.dir` is the
1293///     canonical source-tree directory (boot image at
1294///     `<source>/arch/x86/boot/bzImage` (x86_64) or
1295///     `<source>/arch/arm64/boot/Image` (aarch64) — the kernel
1296///     build-tree arch subdir (`x86`/`arm64`), not the
1297///     arch_info() name),
1298///     `outcome.cache_hit` is `None`, `outcome.is_dirty` is
1299///     `true`. Callers use the dirty flag to mark the run as
1300///     non-reproducible in test reports — e.g. `cargo-ktstr`'s
1301///     Path-spec resolver appends `_dirty` to the kernel label
1302///     so a `path_linux_a3b1c2_dirty` row in the gauntlet output
1303///     surfaces the divergence from the cache-stored
1304///     `path_linux_a3b1c2` clean variant.
1305///
1306/// Both directory return shapes are valid inputs to
1307/// [`crate::kernel_path::find_image_in_dir`], which probes both
1308/// layouts. Callers that need the boot-image FILE path (not the
1309/// directory) should use [`resolve_kernel_dir`] instead — that
1310/// function applies the same pipeline but returns the image path.
1311///
1312/// Used by `cargo-ktstr`'s Path-spec resolver to wire `--kernel
1313/// PATH` invocations through the same cache pipeline that
1314/// Version/CacheKey/Git specs use, so a clean source-tree rebuild
1315/// hits the cache instead of re-running `make`.
1316///
1317/// `cli_label` prefixes status output and is threaded into
1318/// [`kernel_build_pipeline`]'s diagnostic surface. `cpu_cap`
1319/// forwards the resource-budget cap; `None` keeps the
1320/// 30%-of-allowed default. See [`resolve_kernel_dir`] for the
1321/// matching image-returning sibling's `cpu_cap` rationale —
1322/// identical here because both functions reach the same pipeline.
1323pub fn resolve_kernel_dir_to_entry(
1324    path: &std::path::Path,
1325    cli_label: &str,
1326    cpu_cap: Option<crate::vmm::host_topology::CpuCap>,
1327) -> Result<KernelDirOutcome> {
1328    let acquired = acquire_local_source_tree(path)?;
1329    let cache_key = acquired.cache_key.clone();
1330    let is_dirty = acquired.is_dirty;
1331    // Open the cache once and reuse for both the clean-tree
1332    // lookup and the post-build store. Both legs need the same
1333    // root resolution; opening twice is wasted work and risks
1334    // a TOCTOU split if `KTSTR_CACHE_DIR` changes between calls.
1335    // A failure here is fatal — we cannot proceed without a cache
1336    // root for either lookup or store.
1337    let cache = crate::cache::CacheDir::new()?;
1338
1339    // Clean trees: cache lookup before build.
1340    if !is_dirty && let Some(entry) = cache_lookup(&cache, &cache_key, cli_label) {
1341        // `entry.path` is the cache entry directory; the boot
1342        // image lives at `<entry.path>/<image_name>`. Verify the
1343        // image is actually present before returning, so a
1344        // partially-corrupt entry doesn't bypass the
1345        // build-and-restore path.
1346        if entry.image_path().exists() {
1347            let hit = KernelDirCacheHit {
1348                cache_key: cache_key.clone(),
1349                built_at: entry.metadata.built_at.clone(),
1350            };
1351            return Ok(KernelDirOutcome {
1352                dir: entry.path,
1353                cache_hit: Some(hit),
1354                // Cache-hit gate already required clean tree —
1355                // restate the invariant in the outcome instead of
1356                // reading `is_dirty` again, so the bit cannot drift
1357                // if the gate condition above evolves.
1358                is_dirty: false,
1359            });
1360        }
1361    }
1362
1363    // extra_kconfig = None: this path serves cargo ktstr
1364    // test/coverage/llvm-cov / shell / verifier resolution, none of
1365    // which expose `--extra-kconfig`. The flag is `cargo ktstr
1366    // kernel build`-only and feeds extras directly through that
1367    // dispatch.
1368    let result = kernel_build_pipeline(
1369        &acquired, &cache, cli_label, false, false, true, cpu_cap, None, None,
1370    )?;
1371
1372    // Prefer the cached entry directory (stable across rebuilds).
1373    // For dirty trees, `entry` is `None` — fall back to the
1374    // canonical source directory, which `local_source` already
1375    // resolved into `acquired.source_dir`.
1376    let dir = match result.entry {
1377        Some(entry) => entry.path,
1378        None => acquired.source_dir,
1379    };
1380    // The pipeline observes the dirty signal twice: once at acquire
1381    // time (captured in `is_dirty` above) and once via the post-build
1382    // re-check that detects mid-build mutations. Either source
1383    // flipping the bit means the run is non-reproducible — surface
1384    // the union here so the kernel-label downstream gets the `_dirty`
1385    // suffix even when the tree was clean at acquire and only
1386    // dirtied during `make`.
1387    Ok(KernelDirOutcome {
1388        dir,
1389        cache_hit: None,
1390        is_dirty: is_dirty || result.post_build_is_dirty,
1391    })
1392}
1393
1394/// Resolve a kernel directory: auto-build from source tree.
1395///
1396/// Requires Makefile + Kconfig. Checks cache for clean trees,
1397/// delegates to [`kernel_build_pipeline`] on miss. `cli_label`
1398/// prefixes status output and is passed through to
1399/// [`kernel_build_pipeline`] as the diagnostic label.
1400///
1401/// `cpu_cap` forwards the resource-budget cap to the pipeline.
1402/// `None` is the default for non-kernel-build callers
1403/// (test/coverage/shell auto-build paths) — `--cpu-cap` lives on
1404/// the explicit kernel-build entrypoint, not test-running
1405/// commands, because the auto-build-on-miss path already runs
1406/// inside a test invocation where perf-mode constraints dominate.
1407pub fn resolve_kernel_dir(
1408    path: &std::path::Path,
1409    cli_label: &str,
1410    cpu_cap: Option<crate::vmm::host_topology::CpuCap>,
1411) -> Result<std::path::PathBuf> {
1412    let acquired = acquire_local_source_tree(path)?;
1413    let cache_key = acquired.cache_key.clone();
1414    // Open the cache once and reuse for both the clean-tree
1415    // lookup and the post-build store. Both legs need the same
1416    // root resolution; opening twice is wasted work and risks
1417    // a TOCTOU split if `KTSTR_CACHE_DIR` changes between calls.
1418    // A failure here is fatal — we cannot proceed without a cache
1419    // root for either lookup or store. Mirrors the same hoist
1420    // applied in [`resolve_kernel_dir_to_entry`].
1421    let cache = crate::cache::CacheDir::new()?;
1422
1423    // Clean trees: cache lookup before build.
1424    // Dirty trees: skip cache, always build.
1425    if !acquired.is_dirty
1426        && let Some(entry) = cache_lookup(&cache, &cache_key, cli_label)
1427    {
1428        let image = entry.image_path();
1429        if image.exists() {
1430            success(&format!("{cli_label}: using cached kernel {cache_key}"));
1431            return Ok(image);
1432        }
1433    }
1434
1435    // extra_kconfig = None: matches the sibling
1436    // `resolve_kernel_dir_to_entry` rationale — `--extra-kconfig` is
1437    // a `cargo ktstr kernel build`-only flag.
1438    let result = kernel_build_pipeline(
1439        &acquired, &cache, cli_label, false, false, true, cpu_cap, None, None,
1440    )?;
1441
1442    // Prefer the cached image path (stable across rebuilds).
1443    match result.entry {
1444        Some(entry) => Ok(entry.image_path()),
1445        None => Ok(result.image_path),
1446    }
1447}
1448
1449/// Validate `path` is a kernel source tree (Makefile + Kconfig at
1450/// the root) and return the [`AcquiredSource`](crate::fetch::AcquiredSource)
1451/// computed by [`crate::fetch::local_source`].
1452///
1453/// Shared across [`resolve_kernel_dir`] and
1454/// [`resolve_kernel_dir_to_entry`] so the validation diagnostic
1455/// and `local_source` error stringification live in one place.
1456fn acquire_local_source_tree(path: &Path) -> Result<crate::fetch::AcquiredSource> {
1457    if !is_kernel_source_tree(path) {
1458        bail!(
1459            "no kernel image found in {} (not a kernel source tree — \
1460             missing Makefile or Kconfig)",
1461            path.display()
1462        );
1463    }
1464    crate::fetch::local_source(path).map_err(|e| anyhow::anyhow!("{e}"))
1465}
1466
1467/// Whether `path` is the root of a Linux kernel source tree.
1468///
1469/// Uses the same Makefile + Kconfig heuristic that
1470/// `acquire_local_source_tree` gates on, so a directory this
1471/// predicate accepts is exactly one `--kernel <path>` would auto-build
1472/// from. Shared with the `shell` subcommand's cwd auto-selection
1473/// ([`shell_kernel_or_cwd`]) to keep detection and resolution in sync.
1474pub fn is_kernel_source_tree(path: &Path) -> bool {
1475    path.join("Makefile").exists() && path.join("Kconfig").exists()
1476}
1477
1478/// Default the `shell` subcommand's `--kernel` to the current
1479/// directory when it is a kernel source tree.
1480///
1481/// When `kernel` is already set the operator's choice is returned
1482/// unchanged. When it is `None` and the process's cwd is a kernel
1483/// source tree (per [`is_kernel_source_tree`]), the cwd is returned as
1484/// the kernel spec and an info line naming it is printed. Otherwise
1485/// `None` is returned so [`resolve_kernel_image`] falls through to its
1486/// cache / auto-download behavior.
1487///
1488/// Scoped to `shell`: the test/build/run flows keep their existing
1489/// no-`--kernel` defaults. `cli_label` prefixes the status line
1490/// (`"ktstr"` / `"cargo ktstr"`).
1491pub fn shell_kernel_or_cwd(kernel: Option<String>, cli_label: &str) -> Option<String> {
1492    if kernel.is_some() {
1493        return kernel;
1494    }
1495    match std::env::current_dir() {
1496        Ok(cwd) if is_kernel_source_tree(&cwd) => {
1497            status(&format!(
1498                "{cli_label}: no --kernel given, using kernel source tree at {}",
1499                cwd.display()
1500            ));
1501            Some(cwd.to_string_lossy().into_owned())
1502        }
1503        _ => None,
1504    }
1505}
1506
1507#[cfg(test)]
1508mod tests {
1509    use super::*;
1510
1511    /// Unset env: returns the host-CPU fallback, never zero.
1512    #[test]
1513    fn resolve_kernel_parallelism_unset_returns_host_default() {
1514        use crate::test_support::test_helpers::{EnvVarGuard, lock_env};
1515        let _lock = lock_env();
1516        let _guard = EnvVarGuard::remove(crate::KTSTR_KERNEL_PARALLELISM_ENV);
1517        let n = resolve_kernel_parallelism();
1518        assert!(
1519            n >= 1,
1520            "fallback must yield at least 1; got {n} which would defeat \
1521             ThreadPoolBuilder::num_threads",
1522        );
1523    }
1524
1525    /// Valid usize override: env-supplied value wins.
1526    #[test]
1527    fn resolve_kernel_parallelism_valid_override_wins() {
1528        use crate::test_support::test_helpers::{EnvVarGuard, lock_env};
1529        let _lock = lock_env();
1530        let _guard = EnvVarGuard::set(crate::KTSTR_KERNEL_PARALLELISM_ENV, "4");
1531        assert_eq!(
1532            resolve_kernel_parallelism(),
1533            4,
1534            "valid usize env value must override the host-CPU default",
1535        );
1536    }
1537
1538    /// Zero is sentinel — falls through to default.
1539    #[test]
1540    fn resolve_kernel_parallelism_zero_falls_through_to_default() {
1541        use crate::test_support::test_helpers::{EnvVarGuard, lock_env};
1542        let _lock = lock_env();
1543        let _guard = EnvVarGuard::set(crate::KTSTR_KERNEL_PARALLELISM_ENV, "0");
1544        let n = resolve_kernel_parallelism();
1545        assert!(
1546            n >= 1,
1547            "zero env value must fall through to host-CPU default; got {n}",
1548        );
1549    }
1550
1551    /// Unparseable falls through.
1552    #[test]
1553    fn resolve_kernel_parallelism_unparseable_falls_through_to_default() {
1554        use crate::test_support::test_helpers::{EnvVarGuard, lock_env};
1555        let _lock = lock_env();
1556        let _guard = EnvVarGuard::set(crate::KTSTR_KERNEL_PARALLELISM_ENV, "abc");
1557        let n = resolve_kernel_parallelism();
1558        assert!(n >= 1);
1559    }
1560
1561    /// Negative falls through.
1562    #[test]
1563    fn resolve_kernel_parallelism_negative_falls_through_to_default() {
1564        use crate::test_support::test_helpers::{EnvVarGuard, lock_env};
1565        let _lock = lock_env();
1566        let _guard = EnvVarGuard::set(crate::KTSTR_KERNEL_PARALLELISM_ENV, "-1");
1567        let n = resolve_kernel_parallelism();
1568        assert!(n >= 1);
1569    }
1570
1571    /// Trims whitespace.
1572    #[test]
1573    fn resolve_kernel_parallelism_trims_surrounding_whitespace() {
1574        use crate::test_support::test_helpers::{EnvVarGuard, lock_env};
1575        let _lock = lock_env();
1576        let _guard = EnvVarGuard::set(crate::KTSTR_KERNEL_PARALLELISM_ENV, "  8  ");
1577        assert_eq!(resolve_kernel_parallelism(), 8);
1578    }
1579
1580    /// Pin env-var name literal.
1581    #[test]
1582    fn ktstr_kernel_parallelism_env_const_matches_literal() {
1583        assert_eq!(
1584            crate::KTSTR_KERNEL_PARALLELISM_ENV,
1585            "KTSTR_KERNEL_PARALLELISM",
1586        );
1587    }
1588
1589    #[test]
1590    fn resolve_in_path_finds_sh() {
1591        let result = resolve_in_path(std::path::Path::new("sh"));
1592        assert!(result.is_some(), "sh should be in PATH");
1593        assert!(result.unwrap().exists());
1594    }
1595
1596    #[test]
1597    fn resolve_in_path_nonexistent() {
1598        let result = resolve_in_path(std::path::Path::new("nonexistent_binary_xyz_12345"));
1599        assert!(result.is_none());
1600    }
1601
1602    #[test]
1603    fn resolve_include_files_single_file() {
1604        let dir = tempfile::TempDir::new().unwrap();
1605        let file = dir.path().join("test.txt");
1606        std::fs::write(&file, "hello").unwrap();
1607        let result = resolve_include_files(&[file]).unwrap();
1608        assert_eq!(result.len(), 1);
1609        assert!(result[0].0.contains("test.txt"));
1610    }
1611
1612    #[test]
1613    fn resolve_include_files_nonexistent() {
1614        let result = resolve_include_files(&[std::path::PathBuf::from("/nonexistent/file.txt")]);
1615        assert!(result.is_err());
1616    }
1617
1618    #[test]
1619    fn resolve_include_files_bare_name_in_path() {
1620        let result = resolve_include_files(&[std::path::PathBuf::from("sh")]);
1621        assert!(result.is_ok());
1622        let entries = result.unwrap();
1623        assert_eq!(entries.len(), 1);
1624        assert!(entries[0].0.contains("sh"));
1625    }
1626
1627    /// Inverted-range diagnostic must surface ahead of the generic
1628    /// "not yet supported" bail when resolve_cached_kernel sees a Range.
1629    #[test]
1630    fn resolve_cached_kernel_surfaces_inverted_range_diagnostic() {
1631        let id = crate::kernel_path::KernelId::Range {
1632            start: "6.16".to_string(),
1633            end: "6.12".to_string(),
1634            syntax_inclusive: false,
1635        };
1636        let err =
1637            resolve_cached_kernel(&id, "ktstr-test", None).expect_err("inverted range must error");
1638        let msg = format!("{err:#}");
1639        assert!(
1640            msg.contains("inverted kernel range"),
1641            "validate() diagnostic must surface ahead of the generic \
1642             'not yet supported' bail; got: {msg}",
1643        );
1644        assert!(msg.contains("6.12..6.16"));
1645        assert!(!msg.contains("not yet supported in this context"));
1646    }
1647
1648    /// Same wiring guarantee for resolve_kernel_image.
1649    #[test]
1650    fn resolve_kernel_image_surfaces_inverted_range_diagnostic() {
1651        let policy = KernelResolvePolicy {
1652            cli_label: "ktstr-test",
1653            accept_raw_image: false,
1654        };
1655        let err = resolve_kernel_image(Some("6.16..6.12"), &policy)
1656            .expect_err("inverted range must error");
1657        let msg = format!("{err:#}");
1658        assert!(
1659            msg.contains("inverted kernel range"),
1660            "validate() diagnostic must surface ahead of the generic bail; got: {msg}",
1661        );
1662        assert!(msg.contains("6.12..6.16"));
1663        assert!(!msg.contains("not yet supported in this context"));
1664    }
1665
1666    fn release(moniker: &str, version: &str) -> crate::fetch::Release {
1667        crate::fetch::Release {
1668            moniker: moniker.to_string(),
1669            version: version.to_string(),
1670        }
1671    }
1672
1673    /// Stable+longterm rows inside the interval are kept; mainline,
1674    /// linux-next, and rows outside the interval are dropped.
1675    #[test]
1676    fn filter_and_sort_range_basic() {
1677        use crate::kernel_path::decompose_version_for_compare;
1678        let releases = vec![
1679            release("mainline", "6.18-rc2"),
1680            release("stable", "6.16.5"),
1681            release("longterm", "6.12.40"),
1682            release("linux-next", "6.18-rc2-next-20260420"),
1683            release("longterm", "6.6.99"),
1684            release("stable", "6.14.10"),
1685            release("stable", "6.10.0"),
1686        ];
1687        let start_key = decompose_version_for_compare("6.12").unwrap();
1688        let end_key = decompose_version_for_compare("6.16.5").unwrap();
1689        let out = filter_and_sort_range(&releases, start_key, end_key);
1690        assert_eq!(
1691            out,
1692            vec![
1693                "6.12.40".to_string(),
1694                "6.14.10".to_string(),
1695                "6.16.5".to_string(),
1696            ],
1697        );
1698    }
1699
1700    /// Endpoints absent from releases.json still bracket correctly.
1701    #[test]
1702    fn filter_and_sort_range_endpoints_absent_from_releases() {
1703        use crate::kernel_path::decompose_version_for_compare;
1704        let releases = vec![
1705            release("stable", "6.12.5"),
1706            release("stable", "6.14.2"),
1707            release("stable", "6.15.0"),
1708        ];
1709        let start_key = decompose_version_for_compare("6.10").unwrap();
1710        let end_key = decompose_version_for_compare("6.16").unwrap();
1711        let out = filter_and_sort_range(&releases, start_key, end_key);
1712        assert_eq!(
1713            out,
1714            vec![
1715                "6.12.5".to_string(),
1716                "6.14.2".to_string(),
1717                "6.15.0".to_string(),
1718            ],
1719        );
1720    }
1721
1722    /// Inclusive at both endpoints.
1723    #[test]
1724    fn filter_and_sort_range_inclusive_both_endpoints() {
1725        use crate::kernel_path::decompose_version_for_compare;
1726        let releases = vec![
1727            release("stable", "6.12.5"),
1728            release("stable", "6.13.0"),
1729            release("stable", "6.14.2"),
1730        ];
1731        let start_key = decompose_version_for_compare("6.12.5").unwrap();
1732        let end_key = decompose_version_for_compare("6.14.2").unwrap();
1733        let out = filter_and_sort_range(&releases, start_key, end_key);
1734        assert_eq!(
1735            out,
1736            vec![
1737                "6.12.5".to_string(),
1738                "6.13.0".to_string(),
1739                "6.14.2".to_string(),
1740            ],
1741        );
1742    }
1743
1744    /// rc-as-MAX ordering for rc tags under stable moniker.
1745    #[test]
1746    fn filter_and_sort_range_rc_under_stable_moniker_orders_after_release() {
1747        use crate::kernel_path::decompose_version_for_compare;
1748        let releases = vec![
1749            release("stable", "6.14.0-rc3"),
1750            release("stable", "6.14.0"),
1751            release("stable", "6.13.0"),
1752        ];
1753        let start_key = decompose_version_for_compare("6.13").unwrap();
1754        let end_key = decompose_version_for_compare("6.15").unwrap();
1755        let out = filter_and_sort_range(&releases, start_key, end_key);
1756        assert_eq!(
1757            out,
1758            vec![
1759                "6.13.0".to_string(),
1760                "6.14.0-rc3".to_string(),
1761                "6.14.0".to_string(),
1762            ],
1763        );
1764    }
1765
1766    /// Empty interval returns empty vec.
1767    #[test]
1768    fn filter_and_sort_range_empty_when_no_overlap() {
1769        use crate::kernel_path::decompose_version_for_compare;
1770        let releases = vec![release("stable", "5.10.0"), release("stable", "5.15.0")];
1771        let start_key = decompose_version_for_compare("6.10").unwrap();
1772        let end_key = decompose_version_for_compare("6.16").unwrap();
1773        let out = filter_and_sort_range(&releases, start_key, end_key);
1774        assert!(out.is_empty(), "no overlap → empty result, got {out:?}");
1775    }
1776
1777    /// Mainline/linux-next monikers are dropped even when in interval.
1778    #[test]
1779    fn filter_and_sort_range_drops_non_stable_monikers() {
1780        use crate::kernel_path::decompose_version_for_compare;
1781        let releases = vec![
1782            release("mainline", "6.14.0"),
1783            release("linux-next", "6.14.0-next-20260420"),
1784            release("stable", "6.14.5"),
1785        ];
1786        let start_key = decompose_version_for_compare("6.14").unwrap();
1787        let end_key = decompose_version_for_compare("6.15").unwrap();
1788        let out = filter_and_sort_range(&releases, start_key, end_key);
1789        assert_eq!(out, vec!["6.14.5".to_string()]);
1790    }
1791
1792    /// Unparseable versions silently dropped.
1793    #[test]
1794    fn filter_and_sort_range_drops_unparseable_versions() {
1795        use crate::kernel_path::decompose_version_for_compare;
1796        let releases = vec![
1797            release("stable", "6.14.0"),
1798            release("stable", "embargoed-cve-tag"),
1799            release("stable", "6.14.5"),
1800        ];
1801        let start_key = decompose_version_for_compare("6.14").unwrap();
1802        let end_key = decompose_version_for_compare("6.15").unwrap();
1803        let out = filter_and_sort_range(&releases, start_key, end_key);
1804        assert_eq!(out, vec!["6.14.0".to_string(), "6.14.5".to_string()]);
1805    }
1806
1807    /// `select_series_latest_in_range` keeps only the highest patch of
1808    /// each `(major, minor)` series — the `--include-eol` path collapses
1809    /// a mirror's full per-series tag history to one release per series.
1810    #[test]
1811    fn select_series_latest_in_range_picks_highest_patch_per_series() {
1812        use crate::kernel_path::decompose_version_for_compare;
1813        let versions = vec![
1814            "6.11.0".to_string(),
1815            "6.11.5".to_string(),
1816            "6.11.2".to_string(),
1817            "6.12.0".to_string(),
1818            "6.12.10".to_string(),
1819            "6.13.1".to_string(),
1820        ];
1821        let start_key = decompose_version_for_compare("6.10").unwrap();
1822        let end_key = decompose_version_for_compare("6.16").unwrap();
1823        let out = select_series_latest_in_range(&versions, start_key, end_key);
1824        assert_eq!(
1825            out,
1826            vec![
1827                "6.11.5".to_string(),
1828                "6.12.10".to_string(),
1829                "6.13.1".to_string()
1830            ],
1831            "one release per series, highest patch, ascending",
1832        );
1833    }
1834
1835    /// `-rc` pre-releases are dropped: a release maps its rc slot to
1836    /// `u64::MAX`, so `key.3 != MAX` marks an rc, which the selector
1837    /// skips (mirrors the moniker filter on the non-EOL path).
1838    #[test]
1839    fn select_series_latest_in_range_drops_rc() {
1840        use crate::kernel_path::decompose_version_for_compare;
1841        let versions = vec![
1842            "6.12.5".to_string(),
1843            "6.16-rc1".to_string(),
1844            "6.13.2".to_string(),
1845        ];
1846        let start_key = decompose_version_for_compare("6.10").unwrap();
1847        let end_key = decompose_version_for_compare("6.20").unwrap();
1848        let out = select_series_latest_in_range(&versions, start_key, end_key);
1849        assert_eq!(
1850            out,
1851            vec!["6.12.5".to_string(), "6.13.2".to_string()],
1852            "rc tag must be excluded",
1853        );
1854    }
1855
1856    /// Bounds are honored: series below `start_key` or above `end_key`
1857    /// are dropped, matching `filter_and_sort_range`'s interval so the
1858    /// EOL and maintained sets expand over the same span.
1859    #[test]
1860    fn select_series_latest_in_range_respects_bounds() {
1861        use crate::kernel_path::decompose_version_for_compare;
1862        let versions = vec![
1863            "6.9.9".to_string(),
1864            "6.12.5".to_string(),
1865            "6.20.0".to_string(),
1866        ];
1867        let start_key = decompose_version_for_compare("6.10").unwrap();
1868        let end_key = decompose_version_for_compare("6.16").unwrap();
1869        let out = select_series_latest_in_range(&versions, start_key, end_key);
1870        assert_eq!(out, vec!["6.12.5".to_string()]);
1871    }
1872
1873    /// Unparseable tag strings are dropped rather than aborting the
1874    /// whole expansion (a mirror may carry non-version tags).
1875    #[test]
1876    fn select_series_latest_in_range_drops_unparseable() {
1877        use crate::kernel_path::decompose_version_for_compare;
1878        let versions = vec![
1879            "6.12.5".to_string(),
1880            "embargoed-cve-tag".to_string(),
1881            "6.13.0".to_string(),
1882        ];
1883        let start_key = decompose_version_for_compare("6.10").unwrap();
1884        let end_key = decompose_version_for_compare("6.16").unwrap();
1885        let out = select_series_latest_in_range(&versions, start_key, end_key);
1886        assert_eq!(out, vec!["6.12.5".to_string(), "6.13.0".to_string()]);
1887    }
1888
1889    /// `range_bounds` widens a 2-component `MAJOR.MINOR` END to the
1890    /// whole series (patch/rc → u64::MAX) while START keeps its natural
1891    /// `.0` floor — the task-that-makes-`6.11..6.14`-cover-`6.14.x` pin.
1892    #[test]
1893    fn range_bounds_widens_two_component_end() {
1894        let (start_key, end_key) = range_bounds("6.11", "6.14").expect("valid endpoints");
1895        assert_eq!(start_key, (6, 11, 0, u64::MAX), "START floor is .0");
1896        assert_eq!(
1897            end_key,
1898            (6, 14, u64::MAX, u64::MAX),
1899            "2-component END widened to series ceiling",
1900        );
1901    }
1902
1903    /// An explicit-patch END is an exact bound, NOT widened.
1904    #[test]
1905    fn range_bounds_three_component_end_is_exact() {
1906        let (_, end_key) = range_bounds("6.11", "6.14.2").expect("valid endpoints");
1907        assert_eq!(end_key, (6, 14, 2, u64::MAX), "explicit patch is exact");
1908    }
1909
1910    /// An `-rc` END keeps its exact rc bound (not widened).
1911    #[test]
1912    fn range_bounds_rc_end_is_exact() {
1913        let (_, end_key) = range_bounds("6.11", "6.16-rc3").expect("valid endpoints");
1914        assert_eq!(end_key, (6, 16, 0, 3), "rc END keeps its rc slot");
1915    }
1916
1917    /// `range_bounds` rejects unparseable endpoints (both sides).
1918    #[test]
1919    fn range_bounds_rejects_unparseable() {
1920        assert!(range_bounds("garbage", "6.14").is_err());
1921        assert!(range_bounds("6.10", "garbage").is_err());
1922    }
1923
1924    /// End-to-end of the widening: with `range_bounds("6.11","6.14")`,
1925    /// `select_series_latest_in_range` keeps the HIGHEST 6.14 patch, not
1926    /// just `6.14.0`. This is the regression pin for the END series being
1927    /// series-inclusive (the `6.11..6.14 → whole 6.14 series` fix).
1928    #[test]
1929    fn range_bounds_end_series_covers_high_patch() {
1930        let (start_key, end_key) = range_bounds("6.11", "6.14").expect("valid endpoints");
1931        let versions = vec![
1932            "6.11.0".to_string(),
1933            "6.14.0".to_string(),
1934            "6.14.9".to_string(),
1935        ];
1936        let out = select_series_latest_in_range(&versions, start_key, end_key);
1937        assert_eq!(
1938            out,
1939            vec!["6.11.0".to_string(), "6.14.9".to_string()],
1940            "END series contributes its HIGHEST patch, not just .0",
1941        );
1942    }
1943
1944    /// `combine_range_versions` with `include_eol=false` returns the
1945    /// maintained set verbatim, ignoring any mirror tags.
1946    #[test]
1947    fn combine_range_versions_ignores_mirror_when_eol_off() {
1948        let (start_key, end_key) = range_bounds("6.10", "6.20").unwrap();
1949        let maintained = vec!["6.11.5".to_string()];
1950        let tags = vec!["6.12.10".to_string()];
1951        let out = combine_range_versions(
1952            maintained.clone(),
1953            Some(tags.as_slice()),
1954            start_key,
1955            end_key,
1956            false,
1957        );
1958        assert_eq!(out, maintained, "eol off must ignore mirror tags");
1959    }
1960
1961    /// `--include-eol` union fills a releases.json gap with EOL series
1962    /// from the mirror.
1963    #[test]
1964    fn combine_range_versions_union_fills_gap() {
1965        let (start_key, end_key) = range_bounds("6.10", "6.14").unwrap();
1966        let maintained = vec!["6.11.5".to_string()];
1967        let tags = vec!["6.12.10".to_string(), "6.13.2".to_string()];
1968        let out =
1969            combine_range_versions(maintained, Some(tags.as_slice()), start_key, end_key, true);
1970        assert_eq!(
1971            out,
1972            vec![
1973                "6.11.5".to_string(),
1974                "6.12.10".to_string(),
1975                "6.13.2".to_string()
1976            ],
1977        );
1978    }
1979
1980    /// Best-data-wins: the higher patch is kept regardless of which
1981    /// source carries it (mirror newer than releases.json, and vice
1982    /// versa — a stale mirror never regresses a maintained version).
1983    #[test]
1984    fn combine_range_versions_best_data_wins() {
1985        let (start_key, end_key) = range_bounds("6.10", "6.20").unwrap();
1986        // Mirror newer than releases.json.
1987        let out = combine_range_versions(
1988            vec!["6.14.5".to_string()],
1989            Some(["6.14.9".to_string()].as_slice()),
1990            start_key,
1991            end_key,
1992            true,
1993        );
1994        assert_eq!(out, vec!["6.14.9".to_string()], "mirror-newer wins");
1995        // Stale mirror must not regress the maintained version.
1996        let out = combine_range_versions(
1997            vec!["6.14.9".to_string()],
1998            Some(["6.14.5".to_string()].as_slice()),
1999            start_key,
2000            end_key,
2001            true,
2002        );
2003        assert_eq!(
2004            out,
2005            vec!["6.14.9".to_string()],
2006            "stale mirror never regresses"
2007        );
2008    }
2009
2010    /// Mirror-fetch failure (`None`) with `include_eol=true` falls back
2011    /// to the maintained set alone.
2012    #[test]
2013    fn combine_range_versions_mirror_failure_falls_back() {
2014        let (start_key, end_key) = range_bounds("6.10", "6.20").unwrap();
2015        let maintained = vec!["6.11.5".to_string()];
2016        let out = combine_range_versions(maintained.clone(), None, start_key, end_key, true);
2017        assert_eq!(out, maintained, "mirror failure falls back to maintained");
2018    }
2019
2020    /// The empty-range `--include-eol` hint fires only when the flag was
2021    /// NOT set (setting it already consulted the mirror).
2022    #[test]
2023    fn empty_range_hint_only_when_flag_unset() {
2024        assert!(empty_range_hint(false).contains("--include-eol"));
2025        assert_eq!(empty_range_hint(true), "");
2026    }
2027
2028    /// expand_kernel_range rejects unparseable start endpoint.
2029    #[test]
2030    fn expand_kernel_range_rejects_unparseable_start() {
2031        let err = expand_kernel_range("garbage", "6.14", "ktstr-test", false)
2032            .expect_err("unparseable start must error");
2033        let msg = format!("{err:#}");
2034        assert!(msg.contains("kernel range start `garbage`"));
2035    }
2036
2037    #[test]
2038    fn expand_kernel_range_rejects_unparseable_end() {
2039        let err = expand_kernel_range("6.10", "garbage", "ktstr-test", false)
2040            .expect_err("unparseable end must error");
2041        let msg = format!("{err:#}");
2042        assert!(msg.contains("kernel range end `garbage`"));
2043    }
2044
2045    // ---------------------------------------------------------------
2046    // resolve_kernel_dir_to_entry — success-path tests
2047    // ---------------------------------------------------------------
2048    //
2049    // Error paths (nonexistent path, not-a-source-tree) live next to
2050    // [`resolve_path_kernel`] in `bin/cargo_ktstr/kernel/mod.rs`. The success
2051    // paths exercise the full resolve → cache-lookup → outcome
2052    // pipeline with a real Makefile / Kconfig fixture, an
2053    // isolated `KTSTR_CACHE_DIR`, and a pre-populated cache entry
2054    // for the cache-hit case. The cache-miss + dirty-tree branches
2055    // are exercised through their predicate (`is_dirty=true` ⇒
2056    // skip cache lookup) without actually invoking
2057    // `kernel_build_pipeline`'s `make` subprocess — that would
2058    // require a real kernel toolchain and exceed unit-test scope.
2059    // The `is_dirty` branch is exercised by mutating the worktree
2060    // after commit and asserting the cache lookup is skipped (the
2061    // pre-populated entry is still present, so a successful lookup
2062    // would land it as the outcome — failing to do so proves the
2063    // dirty short-circuit fires).
2064
2065    /// Initialise a git repo with one committed file, mirroring
2066    /// the helper in `fetch.rs`. Inlined here so the
2067    /// `resolve_kernel_dir_to_entry` tests are self-contained
2068    /// rather than reaching across the test-module boundary.
2069    /// `dir` MUST exist; the helper does not create it.
2070    fn init_repo_with_commit_for_resolve_test(dir: &std::path::Path) {
2071        use std::process::Command;
2072        let run = |args: &[&str]| {
2073            let out = Command::new("git")
2074                .args(args)
2075                .current_dir(dir)
2076                .env("GIT_CONFIG_GLOBAL", "/dev/null")
2077                .env("GIT_CONFIG_SYSTEM", "/dev/null")
2078                .env("GIT_AUTHOR_NAME", "ktstr-test")
2079                .env("GIT_AUTHOR_EMAIL", "ktstr-test@localhost")
2080                .env("GIT_COMMITTER_NAME", "ktstr-test")
2081                .env("GIT_COMMITTER_EMAIL", "ktstr-test@localhost")
2082                .output()
2083                .expect("spawn git");
2084            assert!(
2085                out.status.success(),
2086                "git {:?} failed: {}",
2087                args,
2088                String::from_utf8_lossy(&out.stderr)
2089            );
2090        };
2091        run(&["init", "-q", "-b", "main"]);
2092        std::fs::write(dir.join("Makefile"), "# kernel makefile fixture\n").unwrap();
2093        std::fs::write(dir.join("Kconfig"), "# kernel kconfig fixture\n").unwrap();
2094        std::fs::write(dir.join("README"), "fixture\n").unwrap();
2095        run(&["add", "Makefile", "Kconfig", "README"]);
2096        run(&[
2097            "-c",
2098            "commit.gpgsign=false",
2099            "commit",
2100            "-q",
2101            "-m",
2102            "initial",
2103        ]);
2104    }
2105
2106    /// Pre-populate a cache entry under `cache_root/{cache_key}/`
2107    /// containing a synthetic boot image and a `metadata.json`
2108    /// marking the entry as a [`crate::cache::KernelSource::Local`]
2109    /// build. Returns the entry path. The metadata's
2110    /// `source_tree_path` is NOT pinned to the test's source tree
2111    /// — `resolve_kernel_dir_to_entry`'s lookup gates only on
2112    /// cache key match, so any persisted metadata that round-trips
2113    /// is sufficient for the cache-hit assertion.
2114    fn populate_cache_entry_for_resolve_test(
2115        cache_root: &std::path::Path,
2116        cache_key: &str,
2117    ) -> std::path::PathBuf {
2118        let cache = crate::cache::CacheDir::with_root(cache_root.to_path_buf());
2119        let (arch, image_name) = crate::fetch::arch_info();
2120        let staging = tempfile::TempDir::new().expect("staging tempdir");
2121        let fake_image = staging.path().join(image_name);
2122        std::fs::write(&fake_image, b"fake kernel image bytes").expect("write fake image");
2123        let metadata = crate::cache::KernelMetadata::new(
2124            crate::cache::KernelSource::Local {
2125                source_tree_path: None,
2126                git_hash: None,
2127            },
2128            arch,
2129            image_name,
2130            "2026-04-12T10:00:00Z",
2131        );
2132        let artifacts = crate::cache::CacheArtifacts::new(&fake_image);
2133        let entry = cache
2134            .store(cache_key, &artifacts, &metadata)
2135            .expect("pre-populate cache entry");
2136        entry.path
2137    }
2138
2139    /// Cache hit — clean tree whose `local_source` cache key
2140    /// resolves to a pre-populated entry must short-circuit the
2141    /// build pipeline and surface `KernelDirOutcome` with
2142    /// `cache_hit = Some(...)`, `is_dirty = false`, and `dir`
2143    /// pointing at the cache entry directory (NOT the source
2144    /// tree).
2145    #[test]
2146    fn resolve_kernel_dir_to_entry_clean_tree_cache_hit() {
2147        if std::process::Command::new("git")
2148            .arg("--version")
2149            .output()
2150            .is_err()
2151        {
2152            skip!("git CLI unavailable");
2153        }
2154        let _lock = crate::test_support::test_helpers::lock_env();
2155        let cache_tmp = tempfile::TempDir::new().expect("cache tempdir");
2156        let _cache_env = crate::test_support::test_helpers::EnvVarGuard::set(
2157            crate::KTSTR_CACHE_DIR_ENV,
2158            cache_tmp.path(),
2159        );
2160        let src_tmp = tempfile::TempDir::new().expect("src tempdir");
2161        init_repo_with_commit_for_resolve_test(src_tmp.path());
2162
2163        let acquired =
2164            crate::fetch::local_source(src_tmp.path()).expect("local_source must succeed");
2165        assert!(!acquired.is_dirty, "fixture must be clean before lookup");
2166        let cache_key = acquired.cache_key.clone();
2167
2168        let entry_path = populate_cache_entry_for_resolve_test(cache_tmp.path(), &cache_key);
2169
2170        let outcome = resolve_kernel_dir_to_entry(src_tmp.path(), "test", None)
2171            .expect("resolve must succeed on cache hit");
2172        assert_eq!(
2173            outcome.dir, entry_path,
2174            "cache-hit path must return the cache entry directory, NOT the source tree"
2175        );
2176        let hit = outcome
2177            .cache_hit
2178            .expect("cache hit must produce KernelDirCacheHit");
2179        assert_eq!(
2180            hit.cache_key, cache_key,
2181            "cache hit must report the resolved key"
2182        );
2183        assert_eq!(
2184            hit.built_at, "2026-04-12T10:00:00Z",
2185            "cache hit must surface the persisted built_at timestamp",
2186        );
2187        assert!(
2188            !outcome.is_dirty,
2189            "cache-hit gate requires a clean tree; outcome.is_dirty must be false",
2190        );
2191    }
2192
2193    /// Dirty-tree resolve must short-circuit the cache lookup
2194    /// even when an entry under the dirty tree's would-be key
2195    /// already exists. `is_dirty=true` flips `outcome.is_dirty`
2196    /// so the caller (cargo-ktstr) appends `_dirty` to the
2197    /// kernel label and the test report distinguishes the
2198    /// non-reproducible run from a subsequent clean rebuild.
2199    #[test]
2200    fn resolve_kernel_dir_to_entry_dirty_tree_skips_cache_lookup() {
2201        if std::process::Command::new("git")
2202            .arg("--version")
2203            .output()
2204            .is_err()
2205        {
2206            skip!("git CLI unavailable");
2207        }
2208        if std::process::Command::new("make")
2209            .arg("--version")
2210            .output()
2211            .is_err()
2212        {
2213            skip!("make not in PATH");
2214        }
2215        let _lock = crate::test_support::test_helpers::lock_env();
2216        let cache_tmp = tempfile::TempDir::new().expect("cache tempdir");
2217        let _cache_env = crate::test_support::test_helpers::EnvVarGuard::set(
2218            crate::KTSTR_CACHE_DIR_ENV,
2219            cache_tmp.path(),
2220        );
2221        let _bypass_env = crate::test_support::test_helpers::EnvVarGuard::set(
2222            crate::KTSTR_BYPASS_LLC_LOCKS_ENV,
2223            "1",
2224        );
2225        let src_tmp = tempfile::TempDir::new().expect("src tempdir");
2226        init_repo_with_commit_for_resolve_test(src_tmp.path());
2227
2228        std::fs::write(src_tmp.path().join("README"), "modified\n").expect("dirty README");
2229        let dirty_acquired = crate::fetch::local_source(src_tmp.path())
2230            .expect("local_source on dirty tree must succeed");
2231        assert!(
2232            dirty_acquired.is_dirty,
2233            "post-mutation tree must be dirty for the test to be meaningful"
2234        );
2235        populate_cache_entry_for_resolve_test(cache_tmp.path(), &dirty_acquired.cache_key);
2236
2237        let result = resolve_kernel_dir_to_entry(src_tmp.path(), "test", None);
2238        match result {
2239            Ok(outcome) => panic!(
2240                "dirty tree must skip the cache lookup, but resolve returned \
2241                 Ok with dir={:?}, cache_hit={:?}, is_dirty={}",
2242                outcome.dir, outcome.cache_hit, outcome.is_dirty,
2243            ),
2244            Err(_) => {
2245                let entry_dir = cache_tmp.path().join(&dirty_acquired.cache_key);
2246                assert!(
2247                    entry_dir.is_dir(),
2248                    "pre-populated entry must still be present after the \
2249                     dirty resolve; the gate proved short-circuit by NOT \
2250                     returning this directory as the outcome.dir",
2251                );
2252            }
2253        }
2254    }
2255
2256    /// Cache miss on a clean tree must surface as a build attempt
2257    /// rather than as a successful shortcut. Pinned through the
2258    /// build's eventual failure on a fixture without a real kernel
2259    /// toolchain — same shape as the dirty-tree test, but proves
2260    /// the cache MISS path also fans out to the pipeline (rather
2261    /// than a silent no-op that would erase the per-tree
2262    /// invariant).
2263    #[test]
2264    fn resolve_kernel_dir_to_entry_clean_tree_cache_miss_attempts_build() {
2265        if std::process::Command::new("git")
2266            .arg("--version")
2267            .output()
2268            .is_err()
2269        {
2270            skip!("git CLI unavailable");
2271        }
2272        if std::process::Command::new("make")
2273            .arg("--version")
2274            .output()
2275            .is_err()
2276        {
2277            skip!("make not in PATH");
2278        }
2279        let _lock = crate::test_support::test_helpers::lock_env();
2280        let cache_tmp = tempfile::TempDir::new().expect("cache tempdir");
2281        let _cache_env = crate::test_support::test_helpers::EnvVarGuard::set(
2282            crate::KTSTR_CACHE_DIR_ENV,
2283            cache_tmp.path(),
2284        );
2285        let _bypass_env = crate::test_support::test_helpers::EnvVarGuard::set(
2286            crate::KTSTR_BYPASS_LLC_LOCKS_ENV,
2287            "1",
2288        );
2289        let src_tmp = tempfile::TempDir::new().expect("src tempdir");
2290        init_repo_with_commit_for_resolve_test(src_tmp.path());
2291
2292        let acquired =
2293            crate::fetch::local_source(src_tmp.path()).expect("local_source must succeed");
2294        assert!(!acquired.is_dirty, "fixture must be clean before resolve");
2295
2296        let result = resolve_kernel_dir_to_entry(src_tmp.path(), "test", None);
2297        assert!(
2298            result.is_err(),
2299            "cache miss without a real kernel toolchain must surface the build failure, \
2300             got Ok({:?})",
2301            result.as_ref().ok().map(|o| &o.dir),
2302        );
2303    }
2304
2305    /// Positive: a directory with both Makefile and Kconfig at its
2306    /// root is detected as a kernel source tree — the same pair
2307    /// `acquire_local_source_tree` gates on, so cwd auto-selection
2308    /// and explicit `--kernel <path>` agree.
2309    #[test]
2310    fn is_kernel_source_tree_detects_makefile_plus_kconfig() {
2311        let dir = tempfile::TempDir::new().expect("tempdir");
2312        std::fs::write(dir.path().join("Makefile"), "# fixture\n").unwrap();
2313        std::fs::write(dir.path().join("Kconfig"), "# fixture\n").unwrap();
2314        assert!(
2315            is_kernel_source_tree(dir.path()),
2316            "Makefile + Kconfig at the root must detect as a kernel tree",
2317        );
2318    }
2319
2320    /// Negative: a Makefile without a Kconfig is not a kernel tree —
2321    /// a lone build file (e.g. a plain project) must not be
2322    /// auto-selected.
2323    #[test]
2324    fn is_kernel_source_tree_rejects_makefile_without_kconfig() {
2325        let dir = tempfile::TempDir::new().expect("tempdir");
2326        std::fs::write(dir.path().join("Makefile"), "# fixture\n").unwrap();
2327        assert!(
2328            !is_kernel_source_tree(dir.path()),
2329            "a Makefile alone (no Kconfig) must not detect as a kernel tree",
2330        );
2331    }
2332
2333    /// Negative: an empty (non-kernel) directory is not a kernel tree.
2334    #[test]
2335    fn is_kernel_source_tree_rejects_empty_dir() {
2336        let dir = tempfile::TempDir::new().expect("tempdir");
2337        assert!(
2338            !is_kernel_source_tree(dir.path()),
2339            "an empty directory must not detect as a kernel tree",
2340        );
2341    }
2342
2343    /// `shell_kernel_or_cwd` returns the operator's `--kernel`
2344    /// unchanged — cwd auto-selection never overrides an explicit
2345    /// choice.
2346    #[test]
2347    fn shell_kernel_or_cwd_preserves_explicit_kernel() {
2348        let explicit = Some("6.14".to_string());
2349        assert_eq!(
2350            shell_kernel_or_cwd(explicit.clone(), "ktstr"),
2351            explicit,
2352            "an explicit --kernel must pass through untouched",
2353        );
2354    }
2355
2356    /// `shell_kernel_or_cwd` with no `--kernel` in a non-kernel cwd
2357    /// returns `None`, preserving the cache / auto-download fallthrough.
2358    #[test]
2359    fn shell_kernel_or_cwd_none_in_non_kernel_cwd_returns_none() {
2360        let _lock = crate::test_support::test_helpers::lock_env();
2361        let dir = tempfile::TempDir::new().expect("tempdir");
2362        let restore = std::env::current_dir().ok();
2363        std::env::set_current_dir(dir.path()).expect("chdir into non-kernel tempdir");
2364        let result = shell_kernel_or_cwd(None, "ktstr");
2365        if let Some(prev) = restore {
2366            std::env::set_current_dir(prev).expect("restore cwd");
2367        }
2368        assert_eq!(
2369            result, None,
2370            "a non-kernel cwd with no --kernel must not auto-select a kernel",
2371        );
2372    }
2373
2374    /// `shell_kernel_or_cwd` with no `--kernel` in a kernel-tree cwd
2375    /// auto-selects that cwd as the kernel spec.
2376    #[test]
2377    fn shell_kernel_or_cwd_none_in_kernel_cwd_selects_cwd() {
2378        let _lock = crate::test_support::test_helpers::lock_env();
2379        let dir = tempfile::TempDir::new().expect("tempdir");
2380        std::fs::write(dir.path().join("Makefile"), "# fixture\n").unwrap();
2381        std::fs::write(dir.path().join("Kconfig"), "# fixture\n").unwrap();
2382        let restore = std::env::current_dir().ok();
2383        std::env::set_current_dir(dir.path()).expect("chdir into kernel tempdir");
2384        let result = shell_kernel_or_cwd(None, "ktstr");
2385        let cwd = std::env::current_dir().ok();
2386        if let Some(prev) = restore {
2387            std::env::set_current_dir(prev).expect("restore cwd");
2388        }
2389        // Compare against the cwd as observed inside the tempdir:
2390        // TempDir paths can be symlinked (e.g. /tmp -> /private/tmp),
2391        // so the canonicalized cwd, not `dir.path()`, is the spec
2392        // the helper returns.
2393        let expected = cwd.map(|p| p.to_string_lossy().into_owned());
2394        assert_eq!(
2395            result, expected,
2396            "a kernel-tree cwd with no --kernel must auto-select the cwd",
2397        );
2398    }
2399}