//! Resolve real backend metadata into selection candidates and apply the //! shared, hardware-aware policy. //! //! This module is the bridge between the pure policy in `phoebus-core::selection` //! and the actual system. It only reads: it never installs anything. Backend //! metadata that cannot be resolved (offline, daemon down, package absent) is //! reported as an *unavailable* candidate so the review explains why a lane was //! not chosen instead of silently inventing availability. use std::path::Path; use phoebus_core::selection::{ select, Backend, Candidate, HardwareFacts, Need, PackageKind, Preferences, SandboxLevel, Selection, UpdateReliability, }; use crate::command::CommandSpec; use crate::error::{ExecError, Result}; use crate::exec::Exec; use crate::personal::UserStorage; /// System-wide defaults live here, relative to the target root. Root-owned and /// changed only through an authenticated typed action. pub const PREFERENCES_REL: &str = "etc/phoebus/package-preferences.toml"; /// Personal preferences live here, relative to the user's home. pub const PERSONAL_PREFERENCES_FILE: &str = "package-preferences.toml"; /// Load the root-owned system default preferences (no personal layer). pub fn load_system_preferences(root: &Path) -> Preferences { let path = root.join(PREFERENCES_REL); std::fs::read_to_string(&path) .ok() .and_then(|text| toml::from_str(&text).ok()) .unwrap_or_default() } /// Load a user's personal preferences, if the file exists. pub fn load_personal_preferences(storage: &UserStorage) -> Option { let path = storage.config_file(PERSONAL_PREFERENCES_FILE); std::fs::read_to_string(&path) .ok() .and_then(|text| toml::from_str(&text).ok()) } /// Personal explicit choices win; system defaults fill anything the user has /// not overridden. Per-application entries are unioned with the user's choice /// taking precedence, so a system default for one app never hides a user choice /// for another. pub fn merge_preferences(system: Preferences, personal: Option) -> Preferences { let Some(personal) = personal else { return system; }; let mut merged = system; merged.default = personal.default.or(merged.default); for (app, backend) in personal.per_app { merged.per_app.insert(app, backend); } merged.allow_proprietary = personal.allow_proprietary; merged.prefer_source = personal.prefer_source; merged.profile = personal.profile; for (path, env) in personal.project_environments { merged.project_environments.insert(path, env); } merged.keep_existing_source = personal.keep_existing_source; for (app, backend) in personal.inferred_preferences { merged.inferred_preferences.insert(app, backend); } merged } /// Resolve the effective preferences for the initiating user: system defaults /// overlaid with that user's personal choices. pub fn load_preferences(root: &Path) -> Preferences { let system = load_system_preferences(root); let personal = load_personal_preferences(&UserStorage::for_initiating_user()); merge_preferences(system, personal) } /// Persist root-owned system defaults (system-wide policy). pub fn save_system_preferences(exec: &Exec, root: &Path, prefs: &Preferences) -> Result<()> { let path = root.join(PREFERENCES_REL); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).map_err(|e| ExecError::io(parent.to_path_buf(), e))?; } let text = toml::to_string_pretty(prefs) .map_err(|e| ExecError::operation("sys", "save preferences", e.to_string()))?; if exec.dry_run { exec.logger .info("[dry-run] would persist package preferences"); return Ok(()); } std::fs::write(&path, text).map_err(|e| ExecError::io(path, e)) } /// Persist the initiating user's personal preferences privately (0600 in 0700), /// atomically, so an unprivileged desktop account can save without touching /// `/etc`. pub fn save_personal_preferences(storage: &UserStorage, prefs: &Preferences) -> Result<()> { let text = toml::to_string_pretty(prefs) .map_err(|e| ExecError::operation("sys", "save preferences", e.to_string()))?; let dir = storage.config_dir(); let file = storage.config_file(PERSONAL_PREFERENCES_FILE); storage.write_private(&dir, &file, text.as_bytes()) } /// Backwards-compatible alias for the system-wide writer. New code should use /// [`save_system_preferences`] or [`save_personal_preferences`] explicitly. pub fn save_preferences(exec: &Exec, root: &Path, prefs: &Preferences) -> Result<()> { save_system_preferences(exec, root, prefs) } /// Build a command rooted at the intended target: directly for the running /// root, or inside the target chroot for an alternate root. fn rooted(root: &Path, stage: &str, operation: &str, program: &str, args: &[&str]) -> CommandSpec { let owned: Vec = args.iter().map(|s| s.to_string()).collect(); crate::actions::target_spec(root, stage, operation, program, &owned) } /// Snap acts on the running daemon and cannot be redirected to a target. fn snap_on_host(root: &Path) -> bool { root == Path::new("/") } /// Read free storage for the filesystem containing `root` using `df -Pk`. fn free_mib(exec: &Exec, root: &Path) -> u64 { let path = if root.exists() { root.to_string_lossy().to_string() } else { "/".to_string() }; let out = exec.runner.execute( &CommandSpec::new("sys", "probe free space", "df") .args(["-Pk"]) .arg(path), ); match out { Ok(out) if out.success => out .stdout_lossy() .lines() .nth(1) .and_then(|line| line.split_whitespace().nth(3)) .and_then(|kb| kb.parse::().ok()) .map(|kb| kb / 1024) .unwrap_or(0), _ => 0, } } /// Assemble the bounded hardware facts the policy consumes. pub fn hardware_facts(exec: &Exec, root: &Path) -> HardwareFacts { let hw = crate::probe::probe_hardware(exec.runner.as_ref()); let arch = match std::env::consts::ARCH { "x86_64" => "x86_64", "aarch64" => "aarch64", "x86" => "x86", "arm" => "arm", "riscv64" => "riscv64", other => other, } .to_string(); let cores = std::thread::available_parallelism() .map(|n| n.get() as u32) .unwrap_or(1); let gpus = hw.gpu_vendors(); let wayland = std::env::var("XDG_SESSION_TYPE") .map(|v| v.eq_ignore_ascii_case("wayland")) .unwrap_or(true); let binhost_available = root.join("etc/portage/binrepos.conf").exists(); let mut available_backends = std::collections::BTreeSet::new(); available_backends.insert(Backend::PortageSource); if binhost_available { available_backends.insert(Backend::PortageBinary); } available_backends.insert(Backend::PortageVendor); available_backends.insert(Backend::AppImage); available_backends.insert(Backend::CustomEbuild); if crate::nix::installed(root) { available_backends.insert(Backend::Nix); } if crate::exec::tool_in_target(root, "flatpak") { available_backends.insert(Backend::Flatpak); } if snap_on_host(root) && matches!(crate::snap::status(exec), Ok(status) if status.usable()) { available_backends.insert(Backend::Snap); } let history = phoebus_core::load_history(&root.join("var/lib/phoebus/compile-times.tsv")); HardwareFacts { arch, cores, memory_mib: hw.memory_mib, storage_free_mib: free_mib(exec, root), gpus, wayland, binhost_available, available_backends, compile_history: history.into_iter().collect(), } } /// Parse the first `cat/pkg-version` token from an `emerge --pretend` line. pub fn parse_pretend_version(text: &str) -> Option { for line in text.lines() { let trimmed = line.trim_start(); if !trimmed.starts_with('[') { continue; } let close = trimmed.find(']')?; let rest = trimmed[close + 1..].trim(); let atom = rest.split_whitespace().next()?; if atom.contains('/') { return Some(atom.to_string()); } } None } /// Pick the requested package from a Portage plan, not its first dependency. /// Portage prints dependencies before the target for larger installs. pub fn parse_pretend_target_version(text: &str, requested: &str) -> Option { text.lines() .filter_map(|line| { let trimmed = line.trim_start(); let rest = trimmed.strip_prefix('[')?.split_once(']')?.1.trim(); let versioned = rest.split_whitespace().next()?; let (atom, _) = split_atom_version(versioned); let matches = if requested.contains('/') { atom == requested } else { atom.rsplit_once('/').map(|(_, name)| name) == Some(requested) }; matches.then(|| versioned.to_string()) }) .next_back() } /// Split an `emerge`-reported `category/package-version` token into the plain /// atom and the version. `emerge` rejects a bare versioned atom /// (`app-misc/hello-2.12.3` is not a valid atom), so the plain atom is the /// install identifier and the version is recorded separately. Gentoo versions /// always start with a digit, so the version begins at the last `-` followed /// by a digit. pub fn split_atom_version(versioned: &str) -> (String, Option) { // Drop a `:slot`/`::repo` suffix if present. let token = versioned.split(':').next().unwrap_or(versioned); let (category, rest) = match token.split_once('/') { Some((c, r)) => (Some(c), r), None => (None, token), }; let bytes = rest.as_bytes(); let mut split_at: Option = None; for i in 1..bytes.len() { if bytes[i - 1] == b'-' && bytes[i].is_ascii_digit() { split_at = Some(i - 1); } } match split_at { Some(i) => { let package = &rest[..i]; let version = rest[i + 1..].to_string(); let atom = match category { Some(c) => format!("{c}/{package}"), None => package.to_string(), }; (atom, Some(version)) } None => (token.to_string(), None), } } /// A rough capability profile for a plain Portage source/binary candidate. fn portage_candidate( id: &str, binary: bool, version: Option<&str>, facts: &HardwareFacts, ) -> Candidate { let mut c = Candidate::new( if binary { Backend::PortageBinary } else { Backend::PortageSource }, id, if binary { "official signed Gentoo binhost" } else { "Gentoo source tree (/var/db/repos)" }, ); c.verified = true; c.arch = facts.arch.clone(); c.version = version.map(str::to_string); c.update_reliability = UpdateReliability::Automatic; if !binary { c.build_seconds = facts.estimated_build_seconds(id); c.build_measured = c.build_seconds.is_some(); } c } /// Build the candidate set for a request from real backend metadata. /// /// Every candidate reflects something the backend actually reported. When a /// backend cannot be reached, the candidate is marked unavailable with a note. pub fn resolve_candidates(exec: &Exec, root: &Path, need: &Need) -> Vec { let facts = hardware_facts(exec, root); let mut out = Vec::new(); let name = &need.name; // --- Portage ------------------------------------------------------ let pretend = exec.runner.execute(&rooted( root, "sys", "resolve Portage candidate", "emerge", &["--pretend", "--quiet", "--color=n", "--", name.as_str()], )); match pretend { Ok(resolved) if resolved.success => { let text = resolved.stdout_lossy(); let (atom, version) = parse_pretend_target_version(&text, name) .map(|v| split_atom_version(&v)) .unwrap_or_else(|| (name.clone(), None)); out.push(portage_candidate(&atom, false, version.as_deref(), &facts)); if facts.binhost_available { let bin_check = exec.runner.execute(&rooted( root, "sys", "check Portage binpkg", "emerge", &[ "--pretend", "--quiet", "--color=n", "--usepkgonly", "--", name.as_str(), ], )); let bin_available = match bin_check { Ok(res) if res.success => { let out = res.stdout_lossy(); out.contains("[binary") || out.contains("[binpkg") || parse_pretend_version(&out).is_some() } _ => false, }; let mut bin_c = portage_candidate(&atom, true, version.as_deref(), &facts); if !bin_available { bin_c.available = false; bin_c.notes.push( "no matching prebuilt binary found on the binhost; source build required" .into(), ); } out.push(bin_c); } } _ => { let mut c = portage_candidate(name, false, None, &facts); c.available = false; c.notes .push("emerge could not resolve this name from the Gentoo tree".into()); out.push(c); } } // --- Nix ---------------------------------------------------------- if crate::nix::installed(root) { let mut c = Candidate::new(Backend::Nix, name, "nixpkgs (pinned)"); c.verified = true; c.update_reliability = UpdateReliability::Automatic; c.sandbox = SandboxLevel::None; if !phoebus_core::action::valid_nix_attribute(name) { c.available = false; c.notes .push("not a bounded nixpkgs attribute (URLs/flakes are refused)".into()); } else if !crate::nix::verify_attribute(exec, root, name) { c.available = false; c.notes .push(format!("attribute `{name}` does not exist in nixpkgs")); } else { c.notes.push("Nix provides a pinned development environment, not a permanent global installation".into()); } out.push(c); } // --- Flatpak ------------------------------------------------------ if crate::exec::tool_in_target(root, "flatpak") { let mut c = Candidate::new(Backend::Flatpak, name, "flathub"); c.sandbox = SandboxLevel::Strong; c.update_reliability = UpdateReliability::Automatic; c.verified = true; c.shared_runtime_mib = Some(400); if !phoebus_core::action::valid_flatpak_app_id(name) { c.available = false; c.notes .push("not a reverse-DNS Flatpak application id".into()); } else { // Confirm the id actually exists in the configured remotes. let found = exec.runner.execute(&rooted( root, "sys", "resolve Flatpak candidate", "flatpak", &["search", "--columns=application", "--", name.as_str()], )); match found { Ok(o) if o.success && o.stdout_lossy().contains(name) => { c.verified = true; } _ => { c.available = false; c.notes.push( "flathub could not confirm this application id (offline or unknown)".into(), ); } } } out.push(c); } // --- Snap --------------------------------------------------------- if let Some(confinement) = snap_confinement_if_ready(exec, root) { let mut c = Candidate::new(Backend::Snap, name, "Snap Store"); c.sandbox = snap_sandbox(confinement); c.update_reliability = UpdateReliability::Automatic; c.verified = true; c.shared_runtime_mib = Some(200); if !phoebus_core::action::valid_snap_name(name) { c.available = false; c.notes.push("not a valid snap name".into()); } else { // Confirm the snap exists in the store rather than assuming it. let found = exec.runner.execute( &CommandSpec::new("sys", "resolve snap candidate", "snap").args([ "find", "--color=never", "--", name, ]), ); let confirmed = found .map(|o| { o.success && o.stdout_lossy() .lines() .any(|l| l.split_whitespace().next() == Some(name)) }) .unwrap_or(false); if !confirmed { c.available = false; c.notes .push("the Snap Store could not confirm this snap (offline or unknown)".into()); } } out.push(c); } // --- AppImage (only when already managed) ------------------------- if let Ok(record) = crate::appimage::info(root, name) { let mut c = Candidate::new( Backend::AppImage, record.name.clone(), record.provenance.clone(), ); c.version = Some(record.version.clone()); c.verified = true; c.sandbox = SandboxLevel::None; c.update_reliability = UpdateReliability::Manual; c.arch = record.arch.clone(); c.install_mib = Some(record.size_bytes / (1024 * 1024)); out.push(c); } // --- Custom ebuild (only when staged in the Phoebus overlay) ------- if crate::ebuild::staged(root, name).is_some() { let mut c = Candidate::new( Backend::CustomEbuild, name, "Phoebus overlay (/var/db/repos/phoebus)", ); c.verified = false; c.sandbox = SandboxLevel::None; c.update_reliability = UpdateReliability::Manual; c.notes .push("generated ebuild; treated as untrusted until reviewed".into()); out.push(c); } out } /// Determine which backend (if any) already owns an installed copy of `name`. pub fn installed_backend(exec: &Exec, root: &Path, name: &str) -> Option { // AppImage: a managed record. if crate::appimage::info(root, name).is_ok() { return Some(Backend::AppImage); } // Flatpak: parse the installed list in the intended target. if crate::exec::tool_in_target(root, "flatpak") { if let Ok(out) = exec.runner.execute(&rooted( root, "sys", "detect installed flatpak", "flatpak", &["list", "--app", "--columns=application"], )) { if out.success && out.stdout_lossy().lines().any(|l| l.trim() == name) { return Some(Backend::Flatpak); } } } // Snap: parse the installed list (host only; snap has no target scope). if snap_on_host(root) { if let Ok(entries) = crate::snap::list(exec) { if entries.iter().any(|e| e.name == name) { return Some(Backend::Snap); } } } // Portage: a VDB entry for the package (bare name or full atom). if portage_installed(root, name) { return Some(Backend::PortageSource); } None } fn portage_installed(root: &Path, name: &str) -> bool { let vdb = root.join("var/db/pkg"); let (category, package) = match name.split_once('/') { Some((c, p)) => (Some(c.to_string()), p.to_string()), None => (None, name.to_string()), }; let Ok(categories) = std::fs::read_dir(&vdb) else { return false; }; for category_entry in categories.flatten() { let category_name = category_entry.file_name().to_string_lossy().to_string(); if let Some(want) = &category { if &category_name != want { continue; } } let Ok(pkgs) = std::fs::read_dir(category_entry.path()) else { continue; }; for pkg in pkgs.flatten() { let dir = pkg.file_name().to_string_lossy().to_string(); // VDB dirs are `name-version`; match the name prefix. if dir == package || dir.starts_with(&format!("{package}-")) { return true; } } } false } /// Decide the backend for a request using the shared policy. pub fn choose(exec: &Exec, root: &Path, need: &Need) -> Result { let facts = hardware_facts(exec, root); let prefs = load_preferences(root); let installed = installed_backend(exec, root, &need.name); let candidates = resolve_candidates(exec, root, need); select(need, &candidates, &facts, &prefs, installed) .map_err(|e| ExecError::operation("sys", "choose package", e.to_string())) } /// Convenience: the kind inferred from the request when the caller did not /// classify it. Kept conservative — `Unclassified` never forces a lane. pub fn infer_kind(_name: &str) -> PackageKind { PackageKind::Unclassified } // --------------------------------------------------------------------------- // Structured, read-only evidence for the AI installation workflow. // --------------------------------------------------------------------------- /// A candidate plus the extra, backend-specific evidence that is only fetched /// on demand (dependencies, confinement, channels). #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] pub struct CandidateDetail { #[serde(flatten)] pub candidate: Candidate, /// The transitive merge/dependency set, when the backend can report it. pub dependencies: Vec, /// Snap confinement (`strict`/`partial`/`none`), when applicable. #[serde(skip_serializing_if = "Option::is_none")] pub confinement: Option, /// Snap channel, when applicable. #[serde(skip_serializing_if = "Option::is_none")] pub channel: Option, } /// Whether a lane is installed and ready on the intended system. #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] pub struct BackendStatus { pub backend: String, pub available: bool, /// A bounded, human-readable explanation (never invented). pub detail: String, } /// One existing installation of an application. #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] pub struct InstalledCopy { pub backend: String, pub id: String, pub version: String, } /// What is already installed for an application, and whether it is duplicated /// across lanes (which must never be created silently). #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] pub struct InstallationInspection { pub application: String, pub copies: Vec, pub duplicate: bool, } /// Inspect one candidate's metadata, using only what the backend actually /// reports. A candidate that cannot be resolved is returned as unavailable /// rather than invented. pub fn candidate_detail(exec: &Exec, root: &Path, backend: Backend, id: &str) -> CandidateDetail { let need = Need::new(id); let mut candidate = resolve_candidates(exec, root, &need) .into_iter() .find(|c| c.backend == backend && c.id == id); let mut dependencies = Vec::new(); let mut confinement = None; let mut channel = None; match backend { Backend::PortageSource | Backend::PortageBinary | Backend::PortageVendor => { // Declared dependencies come from authoritative metadata: the VDB // when installed, otherwise `qdepends` (portage-utils). An // `emerge --pretend` merge plan is deliberately not used, because it // describes pending merges rather than the dependency graph. if let Some(record) = crate::portage::installed_packages(root) .into_iter() .find(|p| p.atom == id || p.atom.ends_with(&format!("/{id}"))) { for text in [&record.depend, &record.rdepend, &record.bdepend] .into_iter() .flatten() { dependencies.extend( crate::portage::parse_dependencies(text) .into_iter() .map(|d| d.raw), ); } dependencies.sort(); dependencies.dedup(); } else if crate::exec::tool_in_target(root, "qdepends") { if let Ok(out) = exec.runner.execute(&rooted( root, "sys", "inspect candidate dependencies", "qdepends", &["-Q", "--", id], )) { if out.success { dependencies = crate::portage::parse_dependencies(&out.stdout_lossy()) .into_iter() .map(|d| d.raw) .collect(); } } } } Backend::Snap => { if !snap_on_host(root) { // Snap has no alternate-root scope. } else if let Ok(out) = exec.runner.execute( &CommandSpec::new("sys", "inspect snap candidate", "snap").args([ "info", id, "--color=never", ]), ) { if out.success { let text = out.stdout_lossy(); let (version, chan, conf) = crate::snap::parse_info_summary(&text); if let Some(c) = candidate.as_mut() { if c.version.is_none() { c.version = version; } } channel = chan; confinement = Some(conf.as_str().to_string()); } } } Backend::Flatpak | Backend::Nix | Backend::AppImage | Backend::CustomEbuild => {} } let candidate = candidate.unwrap_or_else(|| { let mut c = Candidate::new(backend, id, "(unresolved)"); c.available = false; c.notes .push("this backend could not resolve the candidate from real metadata".into()); c }); CandidateDetail { candidate, dependencies, confinement, channel, } } /// The result of resolving a friendly application name within one lane. #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] pub struct BackendResolution { pub backend: String, pub candidates: Vec, /// Every identifier that matched a friendly name, when it was not itself an /// exact identifier and more than one candidate matched. A non-empty list /// means the caller must ask the user which one is intended. pub ambiguous: Vec, } impl BackendResolution { pub fn unambiguous(&self) -> Option<&Candidate> { if self.ambiguous.is_empty() && self.candidates.len() == 1 { self.candidates.first() } else { None } } pub fn is_ambiguous(&self) -> bool { !self.ambiguous.is_empty() || self.candidates.len() > 1 } } /// Resolve an application name within one lane, including friendly names where /// the lane exposes an authoritative search. Only real metadata is used; an /// unknown name yields no candidate (never a fabricated one). pub fn resolve_for_backend( exec: &Exec, root: &Path, backend: Backend, application: &str, ) -> BackendResolution { let mut candidates: Vec = Vec::new(); let mut ambiguous: Vec = Vec::new(); let exact = |id: &str| id == application; match backend { Backend::Flatpak => { if crate::exec::tool_in_target(root, "flatpak") { if let Ok(out) = exec.runner.execute(&rooted( root, "sys", "resolve flatpak name", "flatpak", &["search", "--columns=application,version", "--", application], )) { if out.success { let mut matches: Vec<(String, String)> = Vec::new(); for line in out.stdout_lossy().lines() { let mut cols = line.split_whitespace(); if let (Some(id), Some(version)) = (cols.next(), cols.next()) { if id.contains('.') { matches.push((id.to_string(), version.to_string())); } } } let exact_matches: Vec<_> = matches .iter() .filter(|(id, _)| exact(id)) .cloned() .collect(); if !exact_matches.is_empty() { for (id, version) in exact_matches { let mut c = Candidate::new(Backend::Flatpak, id, "flathub"); c.version = Some(version); c.verified = true; c.sandbox = SandboxLevel::Strong; c.update_reliability = UpdateReliability::Automatic; candidates.push(c); } } else if matches.len() == 1 { let (id, version) = matches.pop().unwrap(); let mut c = Candidate::new(Backend::Flatpak, id, "flathub"); c.version = Some(version); c.verified = true; c.sandbox = SandboxLevel::Strong; c.update_reliability = UpdateReliability::Automatic; c.notes .push(format!("matched the friendly name `{application}`")); candidates.push(c); } else if matches.len() > 1 { ambiguous = matches.into_iter().map(|(id, _)| id).collect(); } } } } } Backend::Snap => { if let Some(confinement) = snap_confinement_if_ready(exec, root) { if let Ok(out) = exec.runner.execute( &CommandSpec::new("sys", "resolve snap name", "snap").args([ "find", "--color=never", "--", application, ]), ) { if out.success { let found = crate::snap::parse_find(&out.stdout_lossy()); let exact_matches: Vec<_> = found.iter().filter(|c| exact(&c.name)).cloned().collect(); if !exact_matches.is_empty() { for hit in exact_matches { candidates.push(snap_candidate(hit.name, hit.version, confinement)); } } else if found.len() == 1 { let hit = &found[0]; let mut c = snap_candidate(hit.name.clone(), hit.version.clone(), confinement); c.notes .push(format!("matched the friendly name `{application}`")); candidates.push(c); } else if found.len() > 1 { ambiguous = found.into_iter().map(|c| c.name).collect(); } } } } } Backend::PortageSource | Backend::PortageBinary | Backend::PortageVendor => { // Portage resolves bare names itself; confirm the atom is real. if let Ok(out) = exec.runner.execute(&rooted( root, "sys", "resolve portage name", "emerge", &["--pretend", "--quiet", "--color=n", "--", application], )) { if out.success { let (atom, version) = parse_pretend_target_version(&out.stdout_lossy(), application) .map(|v| split_atom_version(&v)) .unwrap_or_else(|| (application.to_string(), None)); if backend == Backend::PortageBinary { let bin_check = exec.runner.execute(&rooted( root, "sys", "check Portage binpkg", "emerge", &[ "--pretend", "--quiet", "--color=n", "--usepkgonly", "--", application, ], )); let bin_available = match bin_check { Ok(res) if res.success => { let out = res.stdout_lossy(); out.contains("[binary") || out.contains("[binpkg") || parse_pretend_version(&out).is_some() } _ => false, }; if bin_available { candidates.push(portage_candidate( &atom, true, version.as_deref(), &hardware_facts(exec, root), )); } } else { candidates.push(portage_candidate( &atom, false, version.as_deref(), &hardware_facts(exec, root), )); } } } } Backend::Nix => { if crate::nix::installed(root) && phoebus_core::action::valid_nix_attribute(application) && crate::nix::verify_attribute(exec, root, application) { let mut c = Candidate::new(Backend::Nix, application, "nixpkgs (pinned)"); c.verified = true; c.update_reliability = UpdateReliability::Automatic; c.notes.push("Nix provides a pinned development environment, not a permanent global installation".into()); candidates.push(c); } } Backend::AppImage => { if let Ok(record) = crate::appimage::info(root, application) { let mut c = Candidate::new( Backend::AppImage, record.name.clone(), record.provenance.clone(), ); c.version = Some(record.version.clone()); c.verified = true; c.sandbox = SandboxLevel::None; c.arch = record.arch.clone(); candidates.push(c); } } Backend::CustomEbuild => { let staged = crate::ebuild::list(root); let matches: Vec<_> = staged .into_iter() .filter(|s| s.atom == application || s.package_name() == application) .collect(); if matches.len() == 1 { let s = &matches[0]; let mut c = Candidate::new( Backend::CustomEbuild, s.atom.clone(), "Phoebus overlay (/var/db/repos/phoebus)", ); c.version = Some(s.version.clone()); candidates.push(c); } else if matches.len() > 1 { ambiguous = matches.into_iter().map(|s| s.atom).collect(); } } } BackendResolution { backend: backend.as_str().to_string(), candidates, ambiguous, } } fn snap_sandbox(confinement: crate::snap::Confinement) -> SandboxLevel { match confinement { crate::snap::Confinement::Strict => SandboxLevel::Strong, crate::snap::Confinement::Partial => SandboxLevel::Partial, crate::snap::Confinement::None => SandboxLevel::None, } } fn snap_confinement_if_ready(exec: &Exec, root: &Path) -> Option { if !snap_on_host(root) { return None; } crate::snap::status(exec) .ok() .filter(crate::snap::SnapdStatus::usable) .map(|status| status.confinement) } fn snap_candidate( name: String, version: String, confinement: crate::snap::Confinement, ) -> Candidate { let mut c = Candidate::new(Backend::Snap, name, "Snap Store"); c.version = Some(version); c.verified = true; c.sandbox = snap_sandbox(confinement); c.update_reliability = UpdateReliability::Automatic; c } /// Report whether a lane is present and ready. pub fn backend_status(exec: &Exec, root: &Path, backend: Backend) -> BackendStatus { let facts = hardware_facts(exec, root); let available = facts.backend_available(backend); let detail = match backend { Backend::PortageSource | Backend::PortageVendor => { if crate::exec::tool_in_target(root, "emerge") { "Portage (emerge) is present".into() } else { "emerge is not available in the target".into() } } Backend::PortageBinary => { if root.join("etc/portage/binrepos.conf").exists() { "a signed binary host is configured".into() } else { "no binhost is configured; source builds would be used".into() } } Backend::Nix => { if crate::nix::installed(root) { "the Nix store is present".into() } else { "Nix is not installed in this target".into() } } Backend::Flatpak => { if crate::exec::tool_in_target(root, "flatpak") { "the flatpak client is present in the target".into() } else { "flatpak is not available in the target".into() } } Backend::Snap => { if !snap_on_host(root) { "Snap cannot be inspected for an alternate root".into() } else { match crate::snap::status(exec) { Ok(s) => format!( "snap client present: {}, daemon active: {}, confinement: {}", s.client_present, s.daemon_ready, s.confinement.as_str() ), Err(_) => "snapd state could not be determined".into(), } } } Backend::AppImage => "AppImages can be imported or downloaded locally".into(), Backend::CustomEbuild => { if crate::ebuild::list(root).is_empty() { "no custom ebuilds are staged".into() } else { "the Phoebus overlay is present with staged ebuilds".into() } } }; BackendStatus { backend: backend.as_str().to_string(), available, detail, } } /// Whether a lane is covered by an optional source filter. fn lane_selected(filter: Option, lane: Backend) -> bool { match filter { Some(f) => f == lane || (f.is_portage() && lane.is_portage()), None => true, } } /// Inspect what is already installed for an application across lanes. Never /// invents a copy; every entry comes from a real backend inventory. pub fn installed_copies(exec: &Exec, root: &Path, application: &str) -> InstallationInspection { installed_copies_filtered(exec, root, application, None) } /// Like [`installed_copies`], but an explicit lane filter skips querying every /// other backend, so a source-constrained request never probes a foreign lane. pub fn installed_copies_filtered( exec: &Exec, root: &Path, application: &str, filter: Option, ) -> InstallationInspection { let mut copies = Vec::new(); // Flatpak (in the intended target). if lane_selected(filter, Backend::Flatpak) && crate::exec::tool_in_target(root, "flatpak") { if let Ok(out) = exec.runner.execute(&rooted( root, "sys", "inspect installed flatpaks", "flatpak", &["list", "--app", "--columns=application,name,version"], )) { if out.success { let app_lower = application.to_ascii_lowercase(); for line in out.stdout_lossy().lines() { let parts: Vec<&str> = line.split('\t').collect(); let (id, name, version) = if parts.len() >= 3 { (parts[0].trim(), parts[1].trim(), parts[2].trim()) } else { let ws: Vec<&str> = line.split_whitespace().collect(); if ws.len() >= 3 { (ws[0], ws[1], ws[2]) } else if ws.len() == 2 { (ws[0], ws[0], ws[1]) } else { ("", "", "") } }; if !id.is_empty() { let id_lower = id.to_ascii_lowercase(); let name_lower = name.to_ascii_lowercase(); if id_lower == app_lower || name_lower == app_lower || id_lower.ends_with(&format!(".{app_lower}")) { copies.push(InstalledCopy { backend: Backend::Flatpak.as_str().into(), id: id.to_string(), version: if version.is_empty() { "installed".into() } else { version.to_string() }, }); } } } } } } // Snap (host only). if lane_selected(filter, Backend::Snap) && snap_on_host(root) { if let Ok(entries) = crate::snap::list(exec) { for entry in entries { if entry.name.eq_ignore_ascii_case(application) { copies.push(InstalledCopy { backend: Backend::Snap.as_str().into(), id: entry.name, version: entry.version, }); } } } } // AppImage (managed record). if lane_selected(filter, Backend::AppImage) { if let Ok(records) = crate::appimage::list(root) { for record in records { if record.name.eq_ignore_ascii_case(application) { copies.push(InstalledCopy { backend: Backend::AppImage.as_str().into(), id: record.name, version: record.version, }); } } } else if let Ok(record) = crate::appimage::info(root, application) { copies.push(InstalledCopy { backend: Backend::AppImage.as_str().into(), id: record.name, version: record.version, }); } } // Portage (VDB). if lane_selected(filter, Backend::PortageSource) { if let Some((atom, version)) = portage_installed_atom_and_version(root, application) { copies.push(InstalledCopy { backend: Backend::PortageSource.as_str().into(), id: atom, version, }); } } // De-duplicate any multiple matches within the same backend copies.dedup_by(|a, b| a.backend == b.backend && a.id == b.id); let duplicate = copies.len() > 1; InstallationInspection { application: application.to_string(), copies, duplicate, } } /// The installed version and full atom of a Portage package from the VDB, if present. fn portage_installed_atom_and_version(root: &Path, name: &str) -> Option<(String, String)> { let vdb = root.join("var/db/pkg"); let (category, package) = match name.split_once('/') { Some((c, p)) => (Some(c.to_string()), p.to_string()), None => (None, name.to_string()), }; let categories = std::fs::read_dir(&vdb).ok()?; for category_entry in categories.flatten() { let category_name = category_entry.file_name().to_string_lossy().to_string(); if let Some(want) = &category { if &category_name != want { continue; } } let pkgs = std::fs::read_dir(category_entry.path()).ok()?; for pkg in pkgs.flatten() { let dir = pkg.file_name().to_string_lossy().to_string(); if let Some(rest) = dir.strip_prefix(&format!("{package}-")) { let atom = format!("{category_name}/{package}"); return Some((atom, rest.to_string())); } } } None } /// The installed version of a Portage package from the VDB, if present. #[allow(dead_code)] pub(crate) fn portage_installed_version(root: &Path, name: &str) -> Option { portage_installed_atom_and_version(root, name).map(|(_, v)| v) } /// A plain-text inventory of the available lanes, for `sys choose` with no /// request and for diagnostics. pub fn lanes_report(exec: &Exec, root: &Path) -> String { let facts = hardware_facts(exec, root); let mut out = format!( "arch={} cores={} memory={}MiB free={}MiB wayland={} binhost={}\n", facts.arch, facts.cores, facts.memory_mib, facts.storage_free_mib, facts.wayland, facts.binhost_available ); for backend in Backend::all() { let state = if facts.backend_available(*backend) { "available" } else { "unavailable" }; out.push_str(&format!(" {:<16} {state}\n", backend.as_str())); } let _ = exec; out } #[cfg(test)] mod tests { use super::*; use crate::command::{CommandOutput, RecordingRunner}; use crate::log::Logger; use phoebus_core::Redactor; use std::time::Duration; fn make_exec(runner: RecordingRunner) -> Exec { let path = tempfile::tempdir().unwrap().keep(); let logger = Logger::open(path.join("l.log"), Redactor::new(), false); Exec::new(Box::new(runner), logger, false, path.join("root"), path) } fn ok(stdout: &str) -> CommandOutput { CommandOutput { status: 0, success: true, stdout: stdout.as_bytes().to_vec(), stderr: Vec::new(), duration: Duration::from_millis(1), } } #[test] fn pretend_version_parses_the_atom() { let text = "Calculating dependencies... done!\n[ebuild N ] www-client/firefox-128.0\n"; assert_eq!( parse_pretend_version(text).as_deref(), Some("www-client/firefox-128.0") ); assert_eq!(parse_pretend_version("nothing here"), None); } #[test] fn portage_target_is_not_the_first_dependency() { let plan = "[ebuild N ] dev-lang/go-bootstrap-1.24.6\n\ [ebuild N ] sys-fs/squashfs-tools-4.7.5\n\ [ebuild N ] app-containers/snapd-2.63\n"; assert_eq!( parse_pretend_target_version(plan, "app-containers/snapd").as_deref(), Some("app-containers/snapd-2.63") ); assert_eq!( parse_pretend_target_version(plan, "snapd").as_deref(), Some("app-containers/snapd-2.63") ); assert_eq!(parse_pretend_target_version(plan, "missing"), None); } #[test] fn split_atom_version_recovers_the_plain_install_atom() { // emerge rejects `cat/pkg-version`, so the install id must stay plain. assert_eq!( split_atom_version("app-misc/hello-2.12.3"), ("app-misc/hello".to_string(), Some("2.12.3".to_string())) ); assert_eq!( split_atom_version("dev-lang/python-3.12.6:3.12"), ("dev-lang/python".to_string(), Some("3.12.6".to_string())) ); assert_eq!( split_atom_version("www-client/firefox-128.0::gentoo"), ("www-client/firefox".to_string(), Some("128.0".to_string())) ); assert_eq!( split_atom_version("sys-apps/foo-bar-1.0-r1"), ("sys-apps/foo-bar".to_string(), Some("1.0-r1".to_string())) ); assert_eq!(split_atom_version("vim"), ("vim".to_string(), None)); } #[test] fn portage_candidate_keeps_a_valid_install_atom() { let runner = RecordingRunner::new(); // An alternate root runs Portage inside the target chroot; the mock // runner therefore answers the `chroot` wrapper. runner.set_response( "chroot", ok("Calculating dependencies... done!\n[ebuild N ] dev-libs/example-1.0\n[ebuild N ] app-misc/hello-2.12.3 USE=\"nls\"\n"), ); let exec = make_exec(runner.clone()); let root = tempfile::tempdir().unwrap(); let need = Need::new("app-misc/hello"); let candidates = resolve_candidates(&exec, root.path(), &need); let portage = candidates .iter() .find(|c| c.backend == Backend::PortageSource && c.available) .expect("portage candidate"); assert_eq!(portage.id, "app-misc/hello"); assert_eq!(portage.version.as_deref(), Some("2.12.3")); // And the id is a valid package spec that emerge accepts. assert!(phoebus_core::action::valid_package_spec(&portage.id)); // The query must have been rooted in the target, never the host. let recorded = runner.recorded(); let emerge = recorded .iter() .find(|s| s.program == "chroot" && s.args.iter().any(|a| a == "emerge")) .expect("a chrooted emerge"); assert_eq!(emerge.args[0], root.path().to_string_lossy()); } #[test] fn snap_candidate_uses_detected_confinement() { use crate::snap::Confinement; assert_eq!( snap_candidate("notes".into(), "1".into(), Confinement::Strict).sandbox, SandboxLevel::Strong ); assert_eq!( snap_candidate("notes".into(), "1".into(), Confinement::Partial).sandbox, SandboxLevel::Partial ); assert_eq!( snap_candidate("notes".into(), "1".into(), Confinement::None).sandbox, SandboxLevel::None ); } #[test] fn system_preferences_roundtrip_through_disk() { let root = tempfile::tempdir().unwrap(); let mut prefs = Preferences::default(); prefs.per_app.insert("firefox".into(), Backend::Flatpak); prefs.default = Some(Backend::PortageBinary); let exec = make_exec(RecordingRunner::new()); save_system_preferences(&exec, root.path(), &prefs).unwrap(); let back = load_system_preferences(root.path()); assert_eq!(back, prefs); } #[test] fn missing_preferences_file_is_the_default() { let root = tempfile::tempdir().unwrap(); assert_eq!(load_system_preferences(root.path()), Preferences::default()); } #[test] fn personal_preferences_roundtrip_and_are_not_system_owned() { let base = tempfile::tempdir().unwrap(); let storage = crate::personal::UserStorage::with_base(crate::personal::effective_uid(), base.path()); let mut prefs = Preferences::default(); prefs.per_app.insert("vlc".into(), Backend::Snap); save_personal_preferences(&storage, &prefs).unwrap(); let back = load_personal_preferences(&storage).unwrap(); assert_eq!(back.per_app.get("vlc"), Some(&Backend::Snap)); // The personal file lives under the user's config dir, never under the // target root's /etc. assert!(storage .config_file(PERSONAL_PREFERENCES_FILE) .starts_with(base.path())); } #[test] fn personal_choices_take_precedence_over_system_defaults() { let mut system = Preferences::default(); system .per_app .insert("firefox".into(), Backend::PortageBinary); system.per_app.insert("gimp".into(), Backend::Flatpak); system.default = Some(Backend::PortageBinary); system.allow_proprietary = true; let mut personal = Preferences::default(); personal.per_app.insert("firefox".into(), Backend::Flatpak); personal.default = Some(Backend::Flatpak); personal.allow_proprietary = false; let merged = merge_preferences(system, Some(personal)); // User's explicit choice wins for the same app... assert_eq!(merged.per_app.get("firefox"), Some(&Backend::Flatpak)); // ...system defaults still apply to apps the user did not set... assert_eq!(merged.per_app.get("gimp"), Some(&Backend::Flatpak)); assert_eq!(merged.default, Some(Backend::Flatpak)); // ...and the user's scalar policy wins. assert!(!merged.allow_proprietary); } #[test] fn portage_installed_matches_vdb_directories() { let root = tempfile::tempdir().unwrap(); let vdb = root.path().join("var/db/pkg/www-client"); std::fs::create_dir_all(vdb.join("firefox-128.0")).unwrap(); std::fs::create_dir_all(vdb.join("firefox-bin-128.0")).unwrap(); assert!(portage_installed(root.path(), "www-client/firefox")); assert!(portage_installed(root.path(), "firefox")); assert!(!portage_installed(root.path(), "www-client/chromium")); } #[test] fn resolve_includes_a_portage_candidate_from_real_metadata() { let runner = RecordingRunner::new(); runner.set_response( "chroot", ok("Calculating dependencies... done!\n[ebuild N ] app-editors/vim-9.1.0\n"), ); let exec = make_exec(runner); let root = tempfile::tempdir().unwrap(); let need = Need::new("vim").kind(PackageKind::CliTool); let candidates = resolve_candidates(&exec, root.path(), &need); assert!(candidates .iter() .any(|c| c.backend == Backend::PortageSource && c.available)); } #[test] fn unresolved_portage_candidate_is_marked_unavailable() { let runner = RecordingRunner::new(); runner.fail("chroot", "no such package"); let exec = make_exec(runner); let root = tempfile::tempdir().unwrap(); let need = Need::new("not-a-real-package"); let candidates = resolve_candidates(&exec, root.path(), &need); let portage = candidates .iter() .find(|c| c.backend == Backend::PortageSource) .unwrap(); assert!(!portage.available); assert!(!portage.notes.is_empty()); } #[test] fn lanes_report_names_every_backend() { let exec = make_exec(RecordingRunner::new()); let root = tempfile::tempdir().unwrap(); let report = lanes_report(&exec, root.path()); for backend in Backend::all() { assert!(report.contains(backend.as_str()), "missing {backend:?}"); } } #[test] fn target_facts_are_read_from_the_target_not_the_host() { // A binhost configured in one root must not appear in another: the // host's own configuration must never leak into a target's facts. let exec = make_exec(RecordingRunner::new()); let with_binhost = tempfile::tempdir().unwrap(); std::fs::create_dir_all(with_binhost.path().join("etc/portage")).unwrap(); std::fs::write(with_binhost.path().join("etc/portage/binrepos.conf"), "x").unwrap(); let without = tempfile::tempdir().unwrap(); let a = hardware_facts(&exec, with_binhost.path()); let b = hardware_facts(&exec, without.path()); assert!(a.binhost_available); assert!(!b.binhost_available); assert!(a.available_backends.contains(&Backend::PortageBinary)); assert!(!b.available_backends.contains(&Backend::PortageBinary)); } #[test] fn installed_copies_reports_duplication_and_versions() { use std::os::unix::fs::PermissionsExt; let runner = RecordingRunner::new(); runner.set_response("chroot", ok("org.mozilla.firefox\tFirefox\t128\n")); let exec = make_exec(runner.clone()); let root = tempfile::tempdir().unwrap(); // A Flatpak present only in the target must be discovered there. let bin = root.path().join("usr/bin"); std::fs::create_dir_all(&bin).unwrap(); let flatpak = bin.join("flatpak"); std::fs::write(&flatpak, "#!/bin/sh\n").unwrap(); std::fs::set_permissions(&flatpak, std::fs::Permissions::from_mode(0o755)).unwrap(); let inspection = installed_copies(&exec, root.path(), "org.mozilla.firefox"); assert_eq!(inspection.copies.len(), 1); assert_eq!(inspection.copies[0].version, "128"); assert!(!inspection.duplicate); // The target Flatpak, not the host's, was queried. assert_eq!(runner.recorded()[0].program, "chroot"); } }