phoebus_os/installer-rs/crates/phoebus-core/src/selection.rs
Phoebus f30b99d272
Some checks are pending
ci / test (push) Waiting to run
feat(admin): implement AI-first administration across CLI and desktop GUI
- Default natural-language and conversational routing for sys install, sys please install, and sys ask through shared AI workflow
- Constrain AI candidate evaluation when source flags are supplied without bypassing the model
- Enforce explicit --legacy flag for deterministic administration; legacy install without a source flag refuses execution and offers choices
- Audit --action and --action-file entry points to require --legacy or --broker
- Provide truthful guidance on absent or failing AI models without silent mutation or unverified fallback
- Implement package correctness safeguards: Nix attribute evaluation probe, Portage binary check with source compile abort guard, cross-source installed application tracking, and data preservation on removal
- Provide Quickshell desktop assistant (phoebus-assistant) backed by stdio JSON-RPC bridge (sys --assistant-bridge) and desktop integration
- Implement unified multi-source update checking across all package lanes
- Implement quiet proactive assistance monitor with alert deduplication and snoozing
- Expand acceptance suite in installer/tests/vm/sys-acceptance.sh to 22 cases (22/22 PASS)
2026-09-24 16:38:38 -07:00

1413 lines
51 KiB
Rust

//! Hardware- and preference-aware package selection across every Phoebus
//! software lane.
//!
//! This is the shared, inspectable policy used by both the deterministic `sys`
//! front-end and the assistant. It is pure: it consumes already-resolved
//! [Candidate]s (real backend metadata gathered by `phoebus-executor`) plus
//! hardware facts and user preferences, and returns a reproducible decision
//! with the reasons alternatives were rejected.
//!
//! Design rules, in priority order:
//!
//! 1. **Hard compatibility constraints beat preferences.** An architecture
//! mismatch, a required sandbox that a lane cannot provide, insufficient
//! storage, or a base-system component are never overridden by a preference.
//! 2. **Base components stay Portage.** Kernel, drivers, systemd, the host
//! graphics/audio stack and boot tooling may only resolve to a Portage lane
//! (source, official binary, or a native vendor-binary ebuild).
//! 3. **Explicit compatible user choices win.** An explicit backend for an
//! application is honoured when a compatible candidate exists, and is
//! reported as an error when it does not — never silently switched.
//! 4. **No automatic category routing.** A desktop app is not sent to Flatpak
//! and a developer tool is not sent to Nix merely because of its category;
//! suitability is decided by the candidate evidence.
//! 5. **No silent migration.** If an application is already installed through a
//! lane, that lane is preferred so the same app is not duplicated or moved.
//! 6. **Honest estimates.** Compile time and sizes are labelled as measured or
//! estimated; compilation is not assumed to be faster or worth its cost.
//!
//! The decision for the same facts, metadata and preferences is deterministic.
use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use crate::hardware::GpuVendor;
/// A software lane. Each maps to a real backend with distinct guarantees.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum Backend {
/// Gentoo source ebuild compiled locally.
#[serde(rename = "portage-source")]
PortageSource,
/// A signed binary package from the official Gentoo binhost.
#[serde(rename = "portage-binary")]
PortageBinary,
/// A native vendor-binary ebuild (`-bin`/`-launcher`), e.g. google-chrome.
#[serde(rename = "portage-vendor")]
PortageVendor,
/// Nix (developer tools, alternate versions, reproducible environments).
#[serde(rename = "nix")]
Nix,
/// Flatpak (sandboxed GUI applications).
#[serde(rename = "flatpak")]
Flatpak,
/// Snap (sandboxed applications with channel/refresh semantics).
#[serde(rename = "snap")]
Snap,
/// A managed AppImage (single-file, user-run, no built-in sandbox).
#[serde(rename = "appimage")]
AppImage,
/// A Phoebus-managed custom ebuild in the dedicated overlay.
#[serde(rename = "custom-ebuild")]
CustomEbuild,
}
impl Backend {
pub fn as_str(self) -> &'static str {
match self {
Backend::PortageSource => "portage-source",
Backend::PortageBinary => "portage-binary",
Backend::PortageVendor => "portage-vendor",
Backend::Nix => "nix",
Backend::Flatpak => "flatpak",
Backend::Snap => "snap",
Backend::AppImage => "appimage",
Backend::CustomEbuild => "custom-ebuild",
}
}
pub fn parse(value: &str) -> Option<Self> {
match value.trim().to_ascii_lowercase().as_str() {
"portage" | "portage-source" | "source" | "emerge" => Some(Backend::PortageSource),
"portage-binary" | "binary" | "binpkg" | "binhost" => Some(Backend::PortageBinary),
"portage-vendor" | "vendor" | "vendor-binary" | "bin" => Some(Backend::PortageVendor),
"nix" | "nixpkgs" => Some(Backend::Nix),
"flatpak" => Some(Backend::Flatpak),
"snap" | "snapd" => Some(Backend::Snap),
"appimage" => Some(Backend::AppImage),
"custom" | "custom-ebuild" | "ebuild" | "overlay" => Some(Backend::CustomEbuild),
_ => None,
}
}
/// Whether this lane is owned by Portage (and therefore allowed to provide
/// base system components).
pub fn is_portage(self) -> bool {
matches!(
self,
Backend::PortageSource | Backend::PortageBinary | Backend::PortageVendor
)
}
/// Whether this lane provides a genuine application sandbox.
pub fn is_sandboxed(self) -> bool {
matches!(self, Backend::Flatpak | Backend::Snap)
}
pub fn all() -> &'static [Backend] {
&[
Backend::PortageSource,
Backend::PortageBinary,
Backend::PortageVendor,
Backend::Nix,
Backend::Flatpak,
Backend::Snap,
Backend::AppImage,
Backend::CustomEbuild,
]
}
}
/// What is being installed. Used for hard rules and as a suitability hint, not
/// as an automatic routing decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum PackageKind {
/// Kernel, drivers, systemd, host graphics/audio, boot — Portage only.
#[serde(rename = "base-system")]
BaseSystem,
/// A graphical desktop application.
#[serde(rename = "desktop-app")]
DesktopApp,
/// A developer tool, runtime or per-project environment.
#[serde(rename = "developer-tool")]
DeveloperTool,
/// A command-line administration or utility tool.
#[serde(rename = "cli-tool")]
CliTool,
#[default]
#[serde(rename = "unclassified")]
Unclassified,
}
impl PackageKind {
pub fn parse(value: &str) -> Option<Self> {
match value.trim().to_ascii_lowercase().as_str() {
"" | "auto" | "unclassified" | "unknown" => Some(PackageKind::Unclassified),
"base" | "base-system" | "system" | "kernel" | "driver" | "service" => {
Some(PackageKind::BaseSystem)
}
"desktop" | "desktop-app" | "gui" | "app" | "application" => {
Some(PackageKind::DesktopApp)
}
"dev" | "developer" | "developer-tool" | "toolchain" | "runtime" => {
Some(PackageKind::DeveloperTool)
}
"cli" | "cli-tool" | "utility" => Some(PackageKind::CliTool),
_ => None,
}
}
pub fn as_str(self) -> &'static str {
match self {
PackageKind::BaseSystem => "base-system",
PackageKind::DesktopApp => "desktop-app",
PackageKind::DeveloperTool => "developer-tool",
PackageKind::CliTool => "cli-tool",
PackageKind::Unclassified => "unclassified",
}
}
}
/// A relative capability, so the caller can distinguish "supported",
/// "partial" and "absent" without pretending they are equal.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Capability {
No,
Partial,
Yes,
}
/// The strength of a lane's application isolation. This is a *relative* label,
/// not a certification (AppImage and a source build have no sandbox).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SandboxLevel {
None,
Partial,
Strong,
}
/// How reliably a lane keeps a package updated.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UpdateReliability {
Unknown,
Manual,
Automatic,
}
/// Bounded hardware facts relevant to package selection.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HardwareFacts {
pub arch: String,
pub cores: u32,
pub memory_mib: u64,
pub storage_free_mib: u64,
pub gpus: Vec<GpuVendor>,
pub wayland: bool,
pub binhost_available: bool,
/// Lanes whose tooling is actually present and usable on this system.
pub available_backends: BTreeSet<Backend>,
/// Measured compile seconds keyed by atom, when a history exists.
pub compile_history: BTreeMap<String, u64>,
}
impl Default for HardwareFacts {
fn default() -> Self {
let mut available = BTreeSet::new();
available.insert(Backend::PortageSource);
Self {
arch: "x86_64".into(),
cores: 4,
memory_mib: 8192,
storage_free_mib: 32 * 1024,
gpus: vec![GpuVendor::Unknown],
wayland: true,
binhost_available: true,
available_backends: available,
compile_history: BTreeMap::new(),
}
}
}
impl HardwareFacts {
pub fn backend_available(&self, backend: Backend) -> bool {
self.available_backends.contains(&backend)
}
/// A conservative estimate for a source build, preferring measured history.
pub fn estimated_build_seconds(&self, atom: &str) -> Option<u64> {
if let Some(secs) = self.compile_history.get(atom) {
return Some(*secs);
}
None
}
}
/// Preference profile guiding package selection tradeoffs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PreferenceProfile {
#[default]
Balanced,
FastInstallation,
NativeIntegration,
ApplicationIsolation,
}
impl PreferenceProfile {
pub fn as_str(self) -> &'static str {
match self {
PreferenceProfile::Balanced => "balanced",
PreferenceProfile::FastInstallation => "fast-installation",
PreferenceProfile::NativeIntegration => "native-integration",
PreferenceProfile::ApplicationIsolation => "application-isolation",
}
}
pub fn parse(val: &str) -> Option<Self> {
match val.trim().to_ascii_lowercase().as_str() {
"balanced" => Some(PreferenceProfile::Balanced),
"fast" | "fast-installation" | "fast_installation" | "speed" => {
Some(PreferenceProfile::FastInstallation)
}
"native" | "native-integration" | "native_integration" | "portage" => {
Some(PreferenceProfile::NativeIntegration)
}
"isolated"
| "isolation"
| "application-isolation"
| "application_isolation"
| "sandbox" => Some(PreferenceProfile::ApplicationIsolation),
_ => None,
}
}
}
/// Global and per-application preferences.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Preferences {
/// A global backend preference. `None` means "decide by suitability".
pub default: Option<Backend>,
/// Explicit per-application backend choices (persisted user preference).
pub per_app: BTreeMap<String, Backend>,
/// Permit proprietary/vendor software.
pub allow_proprietary: bool,
/// Favour source over binaries (the `source_first` install policy).
pub prefer_source: bool,
/// High-level preference profile (fast install vs native integration vs application isolation).
pub profile: PreferenceProfile,
/// Project-specific tool versions (project path -> tool name -> pinned version).
pub project_environments: BTreeMap<String, BTreeMap<String, String>>,
/// Keep an already installed application on its existing source.
pub keep_existing_source: bool,
/// Inferred suggestions tracked separately before user confirmation.
pub inferred_preferences: BTreeMap<String, Backend>,
}
impl Default for Preferences {
fn default() -> Self {
Self {
default: None,
per_app: BTreeMap::new(),
allow_proprietary: true,
prefer_source: false,
profile: PreferenceProfile::Balanced,
project_environments: BTreeMap::new(),
keep_existing_source: true,
inferred_preferences: BTreeMap::new(),
}
}
}
impl Preferences {
/// The explicit backend for a request: the per-app override, else the
/// global default.
pub fn explicit_backend(&self, name: &str) -> Option<Backend> {
self.per_app.get(name).copied().or(self.default)
}
}
/// Requirements and constraints for one request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct Need {
pub name: String,
pub kind: PackageKind,
/// The request needs a real isolation boundary (e.g. an untrusted app).
pub requires_sandbox: bool,
/// Only a vendor/proprietary binary satisfies the need.
pub requires_proprietary: bool,
/// The request is a graphical application.
pub gui: bool,
/// Free-form capability tags the candidate must advertise.
pub requires_features: Vec<String>,
/// An explicit backend for this request (overrides preferences).
pub explicit_backend: Option<Backend>,
/// A candidate whose install set exceeds this is rejected.
pub max_install_mib: Option<u64>,
}
impl Need {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
..Default::default()
}
}
pub fn kind(mut self, kind: PackageKind) -> Self {
self.kind = kind;
self
}
pub fn gui(mut self, gui: bool) -> Self {
self.gui = gui;
self
}
pub fn requires_sandbox(mut self) -> Self {
self.requires_sandbox = true;
self
}
pub fn explicit_backend(mut self, backend: Backend) -> Self {
self.explicit_backend = Some(backend);
self
}
}
/// One concrete, backend-resolved candidate.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Candidate {
pub backend: Backend,
/// The backend-native identity (atom, Flatpak app id, Snap name, nixpkgs
/// attribute, installed AppImage id, or custom-ebuild atom).
pub id: String,
pub version: Option<String>,
/// Where the artifact actually comes from (repo, URL, overlay).
pub provenance: String,
/// Whether provenance/integrity can be verified (signature or hash).
pub verified: bool,
/// Whether the candidate is currently resolvable (metadata present).
pub available: bool,
/// Estimated or measured download size.
pub download_mib: Option<u64>,
/// Estimated installed size (including shared runtime when new).
pub install_mib: Option<u64>,
/// Estimated or measured source-compile seconds.
pub build_seconds: Option<u64>,
/// Whether `build_seconds` came from measured history (vs an estimate).
pub build_measured: bool,
pub sandbox: SandboxLevel,
pub wayland: Capability,
pub desktop_integration: Capability,
/// GPU vendors this candidate supports. Empty means "no specific GPU need".
pub gpu_vendors: Vec<GpuVendor>,
/// Architecture this candidate targets (`x86_64`, `aarch64`, ...).
pub arch: String,
/// Permissions/privileges the application requests (for the reviewed plan).
pub permissions: Vec<String>,
pub update_reliability: UpdateReliability,
/// Extra runtime/download a shared runtime would cost if not already present.
pub shared_runtime_mib: Option<u64>,
/// Free-form, human-readable notes shown in the review.
pub notes: Vec<String>,
}
impl Candidate {
pub fn new(backend: Backend, id: impl Into<String>, provenance: impl Into<String>) -> Self {
Self {
backend,
id: id.into(),
version: None,
provenance: provenance.into(),
verified: false,
available: true,
download_mib: None,
install_mib: None,
build_seconds: None,
build_measured: false,
sandbox: if backend.is_sandboxed() {
SandboxLevel::Strong
} else {
SandboxLevel::None
},
wayland: Capability::Yes,
desktop_integration: Capability::Yes,
gpu_vendors: Vec::new(),
arch: "x86_64".into(),
permissions: Vec::new(),
update_reliability: UpdateReliability::Unknown,
shared_runtime_mib: None,
notes: Vec::new(),
}
}
}
/// Why a candidate was not chosen.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RejectReason {
/// A base-system component may only come from Portage.
BaseSystemIsPortageOnly,
ArchitectureMismatch,
/// The lane cannot satisfy a required isolation boundary.
SandboxRequired,
/// The request needs a vendor/proprietary package and the lane cannot.
ProprietaryRequired,
/// The candidate's GPU support does not match the machine.
GpuUnsupported,
/// Not enough free storage for the resolved sizes.
InsufficientStorage,
/// The install size exceeds the caller's explicit ceiling.
ExceedsSizeCeiling,
/// The candidate's backend tooling is not present/usable.
BackendUnavailable,
/// The candidate is not resolvable from real metadata.
CandidateUnavailable,
/// The user asked for a specific backend and this is a different one.
BackendNotRequested,
/// A declared permission is unacceptable for this lane.
UnsafePermissions,
/// A lower-scoring but compatible candidate.
LowerSuitability(i64),
}
impl RejectReason {
pub fn explain(&self) -> String {
match self {
RejectReason::BaseSystemIsPortageOnly => {
"base system components are owned by Portage (kernel, drivers, systemd, \
graphics/audio, boot)"
.into()
}
RejectReason::ArchitectureMismatch => "architecture does not match this machine".into(),
RejectReason::SandboxRequired => {
"a required sandbox is not provided by this lane".into()
}
RejectReason::ProprietaryRequired => {
"only a vendor/proprietary artifact satisfies the request".into()
}
RejectReason::GpuUnsupported => {
"the candidate does not support this machine's GPU".into()
}
RejectReason::InsufficientStorage => {
"the machine does not have enough free storage".into()
}
RejectReason::ExceedsSizeCeiling => {
"the resolved install size exceeds the requested ceiling".into()
}
RejectReason::BackendUnavailable => {
"the backend is not installed or its daemon is not ready".into()
}
RejectReason::CandidateUnavailable => {
"no resolvable candidate was found from this backend".into()
}
RejectReason::BackendNotRequested => {
"a different backend was explicitly requested".into()
}
RejectReason::UnsafePermissions => {
"the candidate requests permissions this lane cannot audit".into()
}
RejectReason::LowerSuitability(score) => {
format!("a compatible candidate scored higher (this would be {score})")
}
}
}
}
/// A rejected alternative with its reason.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Rejected {
pub backend: Backend,
pub id: String,
pub reason: RejectReason,
}
/// The selected candidate and the review material.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Selection {
pub need: Need,
pub chosen: Candidate,
pub score: i64,
pub rationale: Vec<String>,
pub rejected: Vec<Rejected>,
/// True when the choice came from an explicit preference, not suitability.
pub from_preference: bool,
/// True when the candidate is already installed through this backend.
pub already_installed: bool,
}
impl Selection {
/// A complete, human-readable review: identity, source, version, tradeoffs
/// and why the alternatives were rejected.
pub fn render(&self) -> String {
let c = &self.chosen;
let mut out = String::new();
out.push_str(&format!(
"Selected package: {} ({})\n",
c.id,
c.backend.as_str()
));
out.push_str(&format!(
" version: {}\n",
c.version
.as_deref()
.unwrap_or("(resolved at build/install time)")
));
out.push_str(&format!(" source: {}\n", c.provenance));
out.push_str(&format!(
" integrity: {}\n",
if c.verified {
"verified (signature/hash)"
} else {
"UNVERIFIED — provenance not cryptographic"
}
));
out.push_str(&format!(
" sandbox: {} wayland: {} desktop: {}\n",
sandbox_str(c.sandbox),
cap_str(c.wayland),
cap_str(c.desktop_integration)
));
if c.build_seconds.is_some() {
out.push_str(&format!(
" build: ~{}s ({})\n",
c.build_seconds.unwrap_or(0),
if c.build_measured {
"measured"
} else {
"estimate"
}
));
}
if let Some(mib) = c.download_mib {
out.push_str(&format!(" download: ~{mib} MiB\n"));
}
if let Some(mib) = c.install_mib {
out.push_str(&format!(" on disk: ~{mib} MiB\n"));
}
if let Some(mib) = c.shared_runtime_mib {
out.push_str(&format!(
" shared runtime: ~{mib} MiB (only if not already present)\n"
));
}
if !c.permissions.is_empty() {
out.push_str(&format!(" permissions: {}\n", c.permissions.join(", ")));
}
out.push_str(&format!(
" updates: {}\n",
match c.update_reliability {
UpdateReliability::Automatic => "automatic",
UpdateReliability::Manual => "manual",
UpdateReliability::Unknown => "unknown",
}
));
if self.already_installed {
out.push_str(" note: already installed through this backend; reusing it\n");
}
if self.from_preference {
out.push_str(" note: chosen by an explicit user/preference rule\n");
}
out.push_str("Why:\n");
for line in &self.rationale {
out.push_str(&format!(" - {line}\n"));
}
if !self.rejected.is_empty() {
out.push_str("Rejected alternatives:\n");
for r in &self.rejected {
out.push_str(&format!(
" - {} ({}): {}\n",
r.id,
r.backend.as_str(),
r.reason.explain()
));
}
}
out
}
}
fn sandbox_str(level: SandboxLevel) -> &'static str {
match level {
SandboxLevel::None => "none",
SandboxLevel::Partial => "partial",
SandboxLevel::Strong => "strong",
}
}
fn cap_str(cap: Capability) -> &'static str {
match cap {
Capability::No => "no",
Capability::Partial => "partial",
Capability::Yes => "yes",
}
}
/// A selection could not be made. The message always names the reason and the
/// alternatives, so callers (and the assistant) never fall back silently.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SelectionError {
pub message: String,
pub rejected: Vec<Rejected>,
}
impl std::fmt::Display for SelectionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message)?;
for r in &self.rejected {
write!(f, "; {} ({})", r.reason.explain(), r.backend.as_str())?;
}
Ok(())
}
}
impl std::error::Error for SelectionError {}
/// The hard constraints. Returns the reason a candidate is impossible, or
/// `None` when it is compatible.
fn hard_reject(
c: &Candidate,
need: &Need,
facts: &HardwareFacts,
prefs: &Preferences,
) -> Option<RejectReason> {
// Base-system components are Portage-only, regardless of preferences. This
// is the ADR 0006 ownership rule.
if need.kind == PackageKind::BaseSystem && !c.backend.is_portage() {
return Some(RejectReason::BaseSystemIsPortageOnly);
}
// A lane that cannot provide the required isolation is out.
if need.requires_sandbox && !c.backend.is_sandboxed() {
return Some(RejectReason::SandboxRequired);
}
// A proprietary/vendor need cannot be met by a source or community lane.
if need.requires_proprietary && c.backend != Backend::PortageVendor {
return Some(RejectReason::ProprietaryRequired);
}
// GPU compatibility, when the candidate advertises support.
if !c.gpu_vendors.is_empty() {
for gpu in &facts.gpus {
if *gpu == GpuVendor::Unknown {
continue;
}
if !c.gpu_vendors.contains(gpu) {
return Some(RejectReason::GpuUnsupported);
}
}
}
// An explicit backend is a hard filter; an incompatible explicit choice is
// an error, not a silent switch.
if let Some(explicit) = need
.explicit_backend
.or_else(|| prefs.explicit_backend(&need.name))
{
if c.backend != explicit {
return Some(RejectReason::BackendNotRequested);
}
}
// Architecture.
if !c.arch.is_empty() && c.arch != facts.arch {
return Some(RejectReason::ArchitectureMismatch);
}
// Storage.
let needed_mib = c
.install_mib
.unwrap_or(0)
.saturating_add(c.shared_runtime_mib.unwrap_or(0));
if needed_mib > 0 && needed_mib > facts.storage_free_mib {
return Some(RejectReason::InsufficientStorage);
}
if let Some(max) = need.max_install_mib {
if needed_mib > max {
return Some(RejectReason::ExceedsSizeCeiling);
}
}
// Only a candidate that is genuinely resolvable can be chosen.
if !c.available {
return Some(RejectReason::CandidateUnavailable);
}
None
}
/// Score a compatible candidate. Higher is better. The score is a transparent
/// heuristic over measurable evidence, not a performance claim.
fn score(
c: &Candidate,
need: &Need,
facts: &HardwareFacts,
prefs: &Preferences,
installed_backend: Option<Backend>,
) -> (i64, Vec<String>) {
let mut s = 0i64;
let mut why = Vec::new();
// Reuse an already-installed lane: no duplicate, no silent migration.
if installed_backend == Some(c.backend) {
s += 60;
why.push(format!(
"{} already owns an installed copy; reusing it avoids duplication",
c.backend.as_str()
));
}
// Portage owns the base system; give its lanes primacy for base needs.
if need.kind == PackageKind::BaseSystem && c.backend.is_portage() {
s += 40;
}
// Verified provenance is worth more than an unverified artifact.
if c.verified {
s += 20;
} else {
s -= 30;
why.push("provenance cannot be cryptographically verified".into());
}
// A required feature must be advertised; otherwise, minor preference.
if need.requires_sandbox && c.sandbox != SandboxLevel::None {
s += 25;
} else if c.sandbox == SandboxLevel::Strong {
// A sandbox is a mild plus when it was not required. It must not become
// an automatic category rule that always routes GUI apps to Flatpak or
// Snap; native integration and provenance weigh at least as much.
s += 3;
}
// Wayland/desktop integration matters for GUI requests.
if need.gui {
s += match c.wayland {
Capability::Yes => 15,
Capability::Partial => 5,
Capability::No => -15,
};
s += match c.desktop_integration {
Capability::Yes => 10,
Capability::Partial => 3,
Capability::No => -10,
};
if c.wayland == Capability::No {
why.push("poor Wayland integration for a GUI application".into());
}
}
// Resource pressure: heavy source builds on low-memory machines are risky,
// and compile cost is only a benefit when it is genuinely cheap.
if let Some(secs) = c.build_seconds {
let heavy = secs > 900;
if heavy && facts.memory_mib > 0 && facts.memory_mib < 4096 {
s -= 25;
why.push(format!(
"a ~{secs}s source build on {}-MiB RAM risks thrashing",
facts.memory_mib
));
} else if heavy {
s -= 12;
} else if secs <= 120 {
s += 10;
why.push(format!("a cheap ~{secs}s source build is a good fit"));
}
if prefs.prefer_source {
s += 15;
}
}
// Tight storage: penalise large downloads and shared runtimes.
if let Some(mib) = c.download_mib {
if facts.storage_free_mib < 8 * 1024 && mib > 512 {
s -= 10;
}
}
if let Some(runtime) = c.shared_runtime_mib {
if runtime > 0 {
s -= 5;
why.push(format!(
"adds a ~{runtime} MiB shared runtime if it is not already present"
));
}
}
// Nix is a good fit for reproducible/alternate developer environments, but
// that is a suitability signal, never an automatic category rule.
if c.backend == Backend::Nix {
let reproducible = need
.requires_features
.iter()
.any(|f| f == "reproducible" || f == "alternate-version" || f == "per-project");
if reproducible {
s += 15;
why.push(
"reproducible/alternate-version developer environments are Nix's strength".into(),
);
} else {
s -= 10;
}
}
// Explicit global preference is a mild tiebreaker; an explicit per-request
// backend is a hard filter handled earlier.
if prefs.default == Some(c.backend) {
s += 12;
}
// High-level preference profile adjustments.
match prefs.profile {
PreferenceProfile::Balanced => {}
PreferenceProfile::FastInstallation => {
if c.backend == Backend::PortageBinary
|| c.backend == Backend::Flatpak
|| c.backend == Backend::Snap
{
s += 20;
why.push(format!(
"preference profile favours fast installation ({})",
c.backend.as_str()
));
} else if c.backend == Backend::PortageSource {
s -= 20;
}
}
PreferenceProfile::NativeIntegration => {
if c.backend.is_portage() {
s += 20;
why.push("preference profile favours native Portage integration".into());
} else {
s -= 15;
}
}
PreferenceProfile::ApplicationIsolation => {
if c.backend.is_sandboxed() {
s += 25;
why.push("preference profile favours sandboxed application isolation".into());
} else if need.gui {
s -= 15;
}
}
}
// Update reliability.
s += match c.update_reliability {
UpdateReliability::Automatic => 6,
UpdateReliability::Manual => 2,
UpdateReliability::Unknown => 0,
};
(s, why)
}
/// Decide which candidate to use. This is the single shared entry point.
pub fn select(
need: &Need,
candidates: &[Candidate],
facts: &HardwareFacts,
prefs: &Preferences,
installed_backend: Option<Backend>,
) -> Result<Selection, SelectionError> {
let explicit = need
.explicit_backend
.or_else(|| prefs.explicit_backend(&need.name));
let mut compatible: Vec<(i64, Vec<String>, Candidate)> = Vec::new();
let mut rejected: Vec<Rejected> = Vec::new();
for c in candidates {
// Unavailable backend tooling is reported distinctly from an
// incompatible candidate.
if !facts.backend_available(c.backend) {
rejected.push(Rejected {
backend: c.backend,
id: c.id.clone(),
reason: RejectReason::BackendUnavailable,
});
continue;
}
if let Some(reason) = hard_reject(c, need, facts, prefs) {
rejected.push(Rejected {
backend: c.backend,
id: c.id.clone(),
reason,
});
continue;
}
let (score, mut why) = score(c, need, facts, prefs, installed_backend);
if c.version.is_some() {
why.push(format!("version {}", c.version.clone().unwrap_or_default()));
}
compatible.push((score, why, c.clone()));
}
if compatible.is_empty() {
// An explicit choice that could not be met is the most useful message.
if let Some(explicit) = explicit {
return Err(SelectionError {
message: format!(
"no compatible `{}` candidate satisfies this request for `{}`",
explicit.as_str(),
need.name
),
rejected,
});
}
return Err(SelectionError {
message: format!("no compatible candidate found for `{}`", need.name),
rejected,
});
}
// Deterministic ordering: score desc, then backend order, then id. This
// makes the result reproducible for the same facts and metadata.
compatible.sort_by(|a, b| {
b.0.cmp(&a.0)
.then_with(|| a.2.backend.cmp(&b.2.backend))
.then_with(|| a.2.id.cmp(&b.2.id))
});
let (best_score, mut rationale, chosen) = compatible.remove(0);
// Everything else is a rejected lower-suitability alternative.
for (score, _why, c) in compatible {
rejected.push(Rejected {
backend: c.backend,
id: c.id,
reason: RejectReason::LowerSuitability(score),
});
}
let from_preference = explicit == Some(chosen.backend);
let already_installed = installed_backend == Some(chosen.backend);
if from_preference {
rationale.insert(
0,
format!(
"explicit backend choice `{}` was requested and is compatible",
chosen.backend.as_str()
),
);
}
if chosen.backend.is_portage() && need.kind == PackageKind::BaseSystem {
rationale.insert(0, "base system components stay under Portage".into());
}
// Keep the rejected list deterministic too.
rejected.sort_by(|a, b| {
a.backend
.cmp(&b.backend)
.then_with(|| a.id.cmp(&b.id))
.then_with(|| format!("{:?}", a.reason).cmp(&format!("{:?}", b.reason)))
});
// De-duplicate a candidate that appears in both hard-reject and
// lower-suitability paths (it cannot, but keep the list tidy).
rejected.dedup_by(|a, b| a.backend == b.backend && a.id == b.id && a.reason == b.reason);
Ok(Selection {
need: need.clone(),
chosen,
score: best_score,
rationale,
rejected,
from_preference,
already_installed,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn facts() -> HardwareFacts {
let mut f = HardwareFacts {
arch: "x86_64".into(),
cores: 8,
memory_mib: 16384,
storage_free_mib: 64 * 1024,
gpus: vec![GpuVendor::Intel],
wayland: true,
binhost_available: true,
..Default::default()
};
for b in [
Backend::PortageSource,
Backend::PortageBinary,
Backend::PortageVendor,
Backend::Nix,
Backend::Flatpak,
Backend::Snap,
Backend::AppImage,
Backend::CustomEbuild,
] {
f.available_backends.insert(b);
}
f
}
fn portage_source(id: &str, secs: u64) -> Candidate {
let mut c = Candidate::new(Backend::PortageSource, id, "gentoo:/var/db/repos");
c.verified = true;
c.build_seconds = Some(secs);
c.build_measured = true;
c.update_reliability = UpdateReliability::Automatic;
c
}
fn portage_binary(id: &str, download: u64) -> Candidate {
let mut c = Candidate::new(Backend::PortageBinary, id, "https://distfiles.gentoo.org");
c.verified = true;
c.download_mib = Some(download);
c.install_mib = Some(download + 50);
c.update_reliability = UpdateReliability::Automatic;
c
}
fn flatpak(id: &str) -> Candidate {
let mut c = Candidate::new(Backend::Flatpak, id, "flathub");
c.verified = true;
c.sandbox = SandboxLevel::Strong;
c.wayland = Capability::Yes;
c.desktop_integration = Capability::Yes;
c.download_mib = Some(120);
c.install_mib = Some(700);
c.shared_runtime_mib = Some(400);
c.update_reliability = UpdateReliability::Automatic;
c
}
#[test]
fn base_system_never_leaves_portage() {
let need = Need::new("sys-kernel/gentoo-kernel").kind(PackageKind::BaseSystem);
let candidates = vec![
flatpak("org.example.Kernel"),
portage_source("sys-kernel/gentoo-kernel", 200),
portage_binary("sys-kernel/gentoo-kernel-bin", 180),
];
let sel = select(&need, &candidates, &facts(), &Preferences::default(), None).unwrap();
assert!(sel.chosen.backend.is_portage());
let rejected = sel
.rejected
.iter()
.find(|r| r.backend == Backend::Flatpak)
.expect("flatpak rejected");
assert_eq!(rejected.reason, RejectReason::BaseSystemIsPortageOnly);
}
#[test]
fn low_memory_prefers_the_binary_over_an_expensive_source_build() {
let mut f = facts();
f.memory_mib = 2048;
let need = Need::new("www-client/firefox").kind(PackageKind::DesktopApp);
let candidates = vec![
portage_source("www-client/firefox", 4200),
portage_binary("www-client/firefox", 90),
];
let sel = select(&need, &candidates, &f, &Preferences::default(), None).unwrap();
assert_eq!(sel.chosen.backend, Backend::PortageBinary);
// The expensive source build must be recorded as a rejected alternative.
assert!(sel
.rejected
.iter()
.any(|r| r.backend == Backend::PortageSource
&& matches!(r.reason, RejectReason::LowerSuitability(_))));
}
#[test]
fn high_core_machine_can_choose_a_cheap_source_build() {
let mut f = facts();
f.cores = 32;
let need = Need::new("app-editors/vim").kind(PackageKind::CliTool);
let candidates = vec![
portage_source("app-editors/vim", 45),
portage_binary("app-editors/vim", 8),
];
let sel = select(&need, &candidates, &f, &Preferences::default(), None).unwrap();
assert_eq!(sel.chosen.backend, Backend::PortageSource);
assert!(sel.rationale.iter().any(|r| r.contains("cheap")));
}
#[test]
fn gui_app_with_required_sandbox_rejects_portage_and_picks_flatpak_or_snap() {
let need = Need::new("com.spotify.Client")
.kind(PackageKind::DesktopApp)
.gui(true)
.requires_sandbox();
let candidates = vec![
portage_source("media-sound/spotify", 300),
flatpak("com.spotify.Client"),
];
let sel = select(&need, &candidates, &facts(), &Preferences::default(), None).unwrap();
assert_eq!(sel.chosen.backend, Backend::Flatpak);
let rejected = sel
.rejected
.iter()
.find(|r| r.backend == Backend::PortageSource)
.unwrap();
assert_eq!(rejected.reason, RejectReason::SandboxRequired);
}
#[test]
fn snap_unavailable_is_reported_and_flatpak_wins() {
let mut f = facts();
f.available_backends.remove(&Backend::Snap);
let need = Need::new("some-app")
.kind(PackageKind::DesktopApp)
.gui(true)
.requires_sandbox();
let candidates = vec![flatpak("org.example.App"), {
let mut c = Candidate::new(Backend::Snap, "some-app", "snapcraft");
c.sandbox = SandboxLevel::Strong;
c
}];
let sel = select(&need, &candidates, &f, &Preferences::default(), None).unwrap();
assert_eq!(sel.chosen.backend, Backend::Flatpak);
assert!(sel
.rejected
.iter()
.any(|r| r.backend == Backend::Snap && r.reason == RejectReason::BackendUnavailable));
}
#[test]
fn developer_tool_only_prefers_nix_when_reproducibility_is_requested() {
let mut f = facts();
f.available_backends.insert(Backend::Nix);
let mut nix = Candidate::new(Backend::Nix, "nodejs", "nixpkgs");
nix.verified = true;
nix.update_reliability = UpdateReliability::Automatic;
let mut plain = Need::new("nodejs").kind(PackageKind::DeveloperTool);
plain.requires_features = vec!["elixir".into()];
let candidates = vec![
portage_source("dev-lang/nodejs", 1800),
portage_binary("dev-lang/nodejs", 40),
nix.clone(),
];
let sel = select(&plain, &candidates, &f, &Preferences::default(), None).unwrap();
assert_eq!(sel.chosen.backend, Backend::PortageBinary);
let mut repro = Need::new("nodejs").kind(PackageKind::DeveloperTool);
repro.requires_features = vec!["reproducible".into()];
let sel = select(&repro, &candidates, &f, &Preferences::default(), None).unwrap();
assert_eq!(sel.chosen.backend, Backend::Nix);
}
#[test]
fn explicit_compatible_preference_is_honoured() {
let need = Need::new("firefox").kind(PackageKind::DesktopApp).gui(true);
let candidates = vec![
portage_source("www-client/firefox", 4200),
flatpak("org.mozilla.firefox"),
];
let mut prefs = Preferences::default();
prefs.per_app.insert("firefox".into(), Backend::Flatpak);
let sel = select(&need, &candidates, &facts(), &prefs, None).unwrap();
assert_eq!(sel.chosen.backend, Backend::Flatpak);
assert!(sel.from_preference);
}
#[test]
fn an_incompatible_explicit_choice_is_an_error_not_a_silent_switch() {
// Base system can never be moved to Flatpak, even if asked.
let need = Need::new("sys-apps/systemd")
.kind(PackageKind::BaseSystem)
.explicit_backend(Backend::Flatpak);
let candidates = vec![
portage_source("sys-apps/systemd", 420),
flatpak("org.example.Systemd"),
];
let err = select(&need, &candidates, &facts(), &Preferences::default(), None).unwrap_err();
assert!(err.message.contains("flatpak"));
assert!(err
.rejected
.iter()
.any(|r| r.reason == RejectReason::BaseSystemIsPortageOnly));
}
#[test]
fn requesting_an_unavailable_backend_fails_loudly() {
let mut f = facts();
f.available_backends.remove(&Backend::Nix);
let need = Need::new("nodejs")
.kind(PackageKind::DeveloperTool)
.explicit_backend(Backend::Nix);
let nix = Candidate::new(Backend::Nix, "nodejs", "nixpkgs");
let err = select(&need, &[nix], &f, &Preferences::default(), None).unwrap_err();
assert!(err
.rejected
.iter()
.any(|r| r.reason == RejectReason::BackendUnavailable));
}
#[test]
fn architecture_mismatch_and_insufficient_storage_are_hard_rejections() {
let mut f = facts();
f.storage_free_mib = 256;
let mut appimage = Candidate::new(Backend::AppImage, "tool.AppImage", "vendor url");
appimage.arch = "aarch64".into();
appimage.install_mib = Some(100);
let mut big = Candidate::new(Backend::AppImage, "big.AppImage", "vendor url");
big.arch = "x86_64".into();
big.install_mib = Some(4096);
let need = Need::new("tool").kind(PackageKind::CliTool);
let candidates = vec![appimage, big];
let err = select(&need, &candidates, &f, &Preferences::default(), None).unwrap_err();
assert!(err
.rejected
.iter()
.any(|r| r.reason == RejectReason::ArchitectureMismatch));
assert!(err
.rejected
.iter()
.any(|r| r.reason == RejectReason::InsufficientStorage));
}
#[test]
fn gpu_mismatch_is_rejected() {
let mut f = facts();
f.gpus = vec![GpuVendor::Nvidia];
let mut c = Candidate::new(Backend::Flatpak, "org.example.Cuda", "flathub");
c.gpu_vendors = vec![GpuVendor::Amd];
let need = Need::new("cuda-tool").kind(PackageKind::DesktopApp);
let err = select(&need, &[c], &f, &Preferences::default(), None).unwrap_err();
assert!(err
.rejected
.iter()
.any(|r| r.reason == RejectReason::GpuUnsupported));
}
#[test]
fn an_already_installed_lane_is_reused_over_a_higher_base_score() {
let need = Need::new("vim").kind(PackageKind::CliTool);
// Flatpak scores high normally, but vim already lives in Portage.
let candidates = vec![
portage_source("app-editors/vim", 45),
flatpak("org.vim.Vim"),
];
let sel = select(
&need,
&candidates,
&facts(),
&Preferences::default(),
Some(Backend::PortageSource),
)
.unwrap();
assert_eq!(sel.chosen.backend, Backend::PortageSource);
assert!(sel.already_installed);
}
#[test]
fn selection_is_reproducible_for_identical_inputs() {
let need = Need::new("firefox").kind(PackageKind::DesktopApp).gui(true);
let candidates = vec![
portage_source("www-client/firefox", 4200),
portage_binary("www-client/firefox", 90),
flatpak("org.mozilla.firefox"),
];
let f = facts();
let p = Preferences::default();
let a = select(&need, &candidates, &f, &p, None).unwrap();
let b = select(&need, &candidates, &f, &p, None).unwrap();
assert_eq!(a, b);
// And stable when the metadata order changes.
let mut shuffled = candidates.clone();
shuffled.reverse();
let c = select(&need, &shuffled, &f, &p, None).unwrap();
assert_eq!(a.chosen, c.chosen);
}
#[test]
fn render_states_identity_source_and_rejections() {
let need = Need::new("firefox").kind(PackageKind::DesktopApp).gui(true);
let candidates = vec![
portage_binary("www-client/firefox", 90),
flatpak("org.mozilla.firefox"),
];
let sel = select(&need, &candidates, &facts(), &Preferences::default(), None).unwrap();
let text = sel.render();
assert!(text.contains("Selected package:"));
assert!(text.contains("source:"));
assert!(text.contains("Rejected alternatives:"));
assert!(text.contains("integrity:"));
}
#[test]
fn proprietary_requirement_only_accepts_a_vendor_ebuild() {
let need = Need::new("google-chrome")
.kind(PackageKind::DesktopApp)
.gui(true);
let mut need = need;
need.requires_proprietary = true;
let candidates = vec![portage_source("www-client/google-chrome", 0), {
let mut c =
Candidate::new(Backend::PortageVendor, "www-client/google-chrome", "vendor");
c.verified = true;
c
}];
// The source lane is a stand-in; require_proprietary rejects anything
// but the vendor lane.
let sel = select(&need, &candidates, &facts(), &Preferences::default(), None).unwrap();
assert_eq!(sel.chosen.backend, Backend::PortageVendor);
}
#[test]
fn missing_hardware_information_does_not_fabricate_a_rejection() {
// An unknown GPU, zero memory and zero storage report must not reject a
// candidate that could actually work; unknowns are not failures.
let mut f = facts();
f.gpus = vec![GpuVendor::Unknown];
f.memory_mib = 0;
f.storage_free_mib = 0;
let mut c = Candidate::new(Backend::PortageBinary, "app-editors/vim", "binhost");
c.verified = true;
c.gpu_vendors = vec![GpuVendor::Intel];
let need = Need::new("vim").kind(PackageKind::CliTool);
let sel = select(&need, &[c], &f, &Preferences::default(), None).unwrap();
assert_eq!(sel.chosen.backend, Backend::PortageBinary);
}
#[test]
fn limited_storage_favours_the_smaller_candidate() {
let mut f = facts();
// Enough for the small candidate (and its runtime), not for the large.
f.storage_free_mib = 1500;
let small = flatpak("org.example.Small");
let mut large = flatpak("org.example.Large");
large.install_mib = Some(5000);
large.download_mib = Some(3000);
let need = Need::new("editor").kind(PackageKind::DesktopApp).gui(true);
let sel = select(&need, &[small, large], &f, &Preferences::default(), None).unwrap();
assert_eq!(sel.chosen.id, "org.example.Small");
assert!(sel
.rejected
.iter()
.any(|r| r.id == "org.example.Large" && r.reason == RejectReason::InsufficientStorage));
}
/// The same application resolves to different lanes on different machines
/// and for different requirements — the point of ADR 0006's revision.
#[test]
fn the_same_application_diverges_by_machine_and_requirement() {
let candidates = vec![
portage_source("www-client/firefox", 4200),
portage_binary("www-client/firefox", 90),
flatpak("org.mozilla.firefox"),
];
// Low-memory laptop, no sandbox requirement: the signed binary wins.
let mut low = facts();
low.memory_mib = 2048;
let need = Need::new("firefox").kind(PackageKind::DesktopApp).gui(true);
let sel = select(&need, &candidates, &low, &Preferences::default(), None).unwrap();
assert_eq!(sel.chosen.backend, Backend::PortageBinary);
// A machine where the user prefers source: source wins.
let prefs = Preferences {
prefer_source: true,
..Default::default()
};
let sel = select(&need, &candidates, &facts(), &prefs, None).unwrap();
assert_eq!(sel.chosen.backend, Backend::PortageSource);
// An untrusted-download requirement: only the sandboxed lane can win.
let sandboxed = Need::new("firefox")
.kind(PackageKind::DesktopApp)
.gui(true)
.requires_sandbox();
let sel = select(
&sandboxed,
&candidates,
&facts(),
&Preferences::default(),
None,
)
.unwrap();
assert_eq!(sel.chosen.backend, Backend::Flatpak);
}
}