//! Plan staging and planning APIs: recommendation text, [`PlanStore`], and the //! `plan_*` builders shared by the CLI and the desktop assistant. use std::io::Write; use std::path::{Path, PathBuf}; use phoebus_ai::assistant::{complete_plan, run_assistant, AssistantPlan}; use phoebus_ai::install::Evidence; use phoebus_ai::provider::SystemFacts; use phoebus_core::action::SystemAction; use phoebus_core::effects::ResolvedPlan; use phoebus_core::selection::{Backend, Candidate, SandboxLevel}; use phoebus_executor::actions; use phoebus_executor::chooser; use phoebus_executor::error::{ExecError, Result}; use phoebus_executor::exec::Exec; use phoebus_executor::install::{self, AiInstall, InstallRequest}; use super::validation::{compute_plan_digest, seal_plan}; use super::{ canonical_root, effective_uid, fresh_plan_id, is_safe_plan_id, now_unix, random_token, PlanClaim, PlanKind, PreparedPlan, DEFAULT_PLAN_TTL_SECONDS, }; /// Produce an honest, evidence-based human recommendation for an application candidate. pub fn format_recommendation(candidate: &Candidate, application: &str) -> String { let source_name = match candidate.backend { Backend::PortageBinary => "Gentoo binhost", Backend::PortageSource => "Gentoo Portage", Backend::PortageVendor => "Portage vendor binary", Backend::Flatpak => "Flathub", Backend::Snap => "Snap Store", Backend::Nix => "Nixpkgs", Backend::AppImage => "managed AppImage", Backend::CustomEbuild => "Phoebus custom ebuild", }; let sandbox_desc = match candidate.sandbox { SandboxLevel::Strong => "strong application isolation", SandboxLevel::Partial => "partial confinement", SandboxLevel::None => "direct host integration (unconfined)", }; let build_desc = if let Some(secs) = candidate.build_seconds { if secs < 60 { format!("fast install (~{secs}s)") } else { let mins = secs.div_ceil(60); format!("compiles native binaries (~{mins} min build)") } } else { match candidate.backend { Backend::PortageBinary | Backend::Flatpak | Backend::Snap | Backend::AppImage => { "pre-built binary package".to_string() } Backend::PortageSource => "source compilation (build time unmeasured)".to_string(), _ => "pre-built binary".to_string(), } }; format!( "Install {application} from {source_name}. Recommended for {sandbox_desc} and {build_desc}." ) } // ----------------------------------------------------------------------------- // PlanStore // ----------------------------------------------------------------------------- /// Protected, per-user plan storage. /// /// A plan is written with a 0600 mode inside a 0700 directory owned by the /// reviewing user (or the broker for root). Reloading rejects a symlink, a /// file owned by someone other than the initiator/root, or a group/world /// writable file. Consumption uses an `O_EXCL` marker so two concurrent /// executions cannot both run the same plan. #[derive(Debug, Clone)] pub struct PlanStore { dir: PathBuf, /// The uid a plan is expected to belong to. The privileged broker sets this /// to the initiating user so it can read that user's plan while still /// rejecting a file owned by anyone else. expected_uid: Option, } impl PlanStore { /// Storage for a specific uid. Used by the privileged broker, which /// recomputes the directory from the uid the caller passed rather than /// trusting an arbitrary path. pub fn for_uid(uid: u32) -> Self { if let Ok(dir) = std::env::var("PHOEBUS_PLANS_DIR") { return Self { dir: PathBuf::from(dir), expected_uid: Some(uid), }; } let candidates: Vec = if uid == 0 { vec![PathBuf::from("/run/phoebus/plans")] } else { // Prefer the canonical per-user runtime path so the privileged // broker (which derives the same path from the uid) finds it. let mut v = vec![PathBuf::from(format!("/run/user/{uid}/phoebus/plans"))]; if let Ok(xdg) = std::env::var("XDG_RUNTIME_DIR") { v.push(PathBuf::from(xdg).join("phoebus/plans")); } v }; for dir in candidates { if std::fs::create_dir_all(&dir).is_ok() { return Self { dir, expected_uid: Some(uid), }; } } let temp = std::env::temp_dir().join(format!("phoebus-plans-{uid}")); let _ = std::fs::create_dir_all(&temp); Self { dir: temp, expected_uid: Some(uid), } } pub fn for_current_user() -> Self { Self::for_uid(effective_uid()) } /// Explicit directory, for tests and callers that manage their own store. pub fn with_dir(dir: impl Into) -> Self { Self { dir: dir.into(), expected_uid: None, } } pub fn dir(&self) -> &Path { &self.dir } fn ensure_dir(&self) -> Result<()> { std::fs::create_dir_all(&self.dir).map_err(|e| ExecError::io(self.dir.clone(), e))?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let _ = std::fs::set_permissions(&self.dir, std::fs::Permissions::from_mode(0o700)); } Ok(()) } fn path(&self, plan_id: &str, suffix: &str) -> Result { if !is_safe_plan_id(plan_id) { return Err(ExecError::operation( "service", "plan path", format!("unsafe plan identifier `{plan_id}`"), )); } Ok(self.dir.join(format!("{plan_id}{suffix}"))) } /// Write a plan atomically (temp file -> fsync -> rename) with mode 0600. pub fn save(&self, plan: &mut PreparedPlan) -> Result { seal_plan(plan); let path = self.path(&plan.id, ".json")?; self.ensure_dir()?; let text = serde_json::to_string_pretty(plan) .map_err(|e| ExecError::operation("service", "serialize plan", e.to_string()))?; let tmp = self.dir.join(format!(".{}.tmp", random_token())); { let mut opts = std::fs::OpenOptions::new(); opts.write(true).create_new(true); #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; opts.mode(0o600); } let mut file = opts.open(&tmp).map_err(|e| ExecError::io(tmp.clone(), e))?; file.write_all(text.as_bytes()) .and_then(|_| file.flush()) .and_then(|_| file.sync_all()) .map_err(|e| ExecError::io(tmp.clone(), e))?; } std::fs::rename(&tmp, &path).map_err(|e| { let _ = std::fs::remove_file(&tmp); ExecError::io(path.clone(), e) })?; if let Ok(dir) = std::fs::File::open(&self.dir) { let _ = dir.sync_all(); } Ok(path) } /// Load a plan, rejecting malformed identifiers, symlinks and unsafe /// ownership/permissions. The caller still has to validate the contents. pub fn load(&self, plan_id: &str) -> Result { let path = self.path(plan_id, ".json")?; let meta = std::fs::symlink_metadata(&path).map_err(|_| { ExecError::operation( "service", "load plan", format!("plan `{plan_id}` not found, consumed or expired"), ) })?; if meta.file_type().is_symlink() { return Err(ExecError::operation( "service", "load plan", "plan path is a symlink; refusing to follow it", )); } if !meta.is_file() { return Err(ExecError::operation( "service", "load plan", "plan path is not a regular file", )); } #[cfg(unix)] { use std::os::unix::fs::{MetadataExt, PermissionsExt}; if meta.permissions().mode() & 0o022 != 0 { return Err(ExecError::operation( "service", "load plan", "plan file is group/world writable; refusing to trust it", )); } let owner = meta.uid(); let expected = self.expected_uid.unwrap_or_else(effective_uid); // The broker runs as root but is reading the initiating user's plan, // so the expected owner is the initiator, not root. A plan owned by // a third party is rejected. if owner != expected && owner != 0 { return Err(ExecError::operation( "service", "load plan", format!("plan file is owned by uid {owner}, not the expected uid {expected}"), )); } } let text = std::fs::read_to_string(&path).map_err(|e| ExecError::io(path.clone(), e))?; let plan: PreparedPlan = serde_json::from_str(&text) .map_err(|e| ExecError::operation("service", "deserialize plan", e.to_string()))?; if plan.id != plan_id { return Err(ExecError::operation( "service", "load plan", "plan identifier does not match its storage name", )); } Ok(plan) } /// Atomically claim a plan for execution. Returns a guard that keeps the /// marker on disk; a second claim (or a retry after a crash) fails. pub fn claim(&self, plan_id: &str) -> Result { let marker = self.path(plan_id, ".claim")?; self.ensure_dir()?; let mut opts = std::fs::OpenOptions::new(); opts.write(true).create_new(true); #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; opts.mode(0o600); } opts.open(&marker).map_err(|e| { ExecError::operation( "service", "claim plan", format!("plan `{plan_id}` is already consumed or being executed ({e})"), ) })?; Ok(PlanClaim { marker }) } /// True when a plan has already been claimed (consumed) for execution. pub fn is_claimed(&self, plan_id: &str) -> bool { match self.path(plan_id, ".claim") { Ok(p) => p.exists(), Err(_) => true, } } } // ----------------------------------------------------------------------------- // Planning APIs // ----------------------------------------------------------------------------- /// Plan an installation using AI investigation and policy checks. pub fn plan_install( plans: &PlanStore, exec: &Exec, root: &Path, request: &InstallRequest, session: &dyn phoebus_ai::install::InstallSession, ai: Option<&AiInstall>, facts: &SystemFacts, ) -> Result { let ai = match ai { Some(a) => a, None => { return Err(ExecError::operation( "service", "plan_install", "No AI provider is configured. Specify a model or select deterministic legacy administration (--legacy --).", )); } }; let resolved = install::resolve_with_ai(exec, root, request, session, ai, facts)?; build_install_plan(plans, root, resolved, PlanKind::Install) } /// Plan an installation deterministically without contacting a model. pub fn plan_legacy_install( plans: &PlanStore, exec: &Exec, root: &Path, request: &InstallRequest, ) -> Result { if request.backend.is_none() { return Err(ExecError::operation( "service", "plan_legacy_install", "Legacy install requires an explicit package source flag (--flatpak, --portage, --nix, --snap, --appimage, --ebuild)", )); } let resolved = install::resolve_explicit(exec, root, request)?; build_install_plan(plans, root, resolved, PlanKind::LegacyInstall) } fn build_install_plan( plans: &PlanStore, root: &Path, resolved: install::ResolvedInstall, kind: PlanKind, ) -> Result { let now = now_unix(); let plan_id = fresh_plan_id("inst"); let rec = format_recommendation(&resolved.candidate, &resolved.request.application); let source_display = match resolved.candidate.backend { Backend::PortageBinary => "Gentoo binhost", Backend::PortageSource => "Gentoo Portage", Backend::PortageVendor => "Portage vendor", Backend::Flatpak => "Flathub", Backend::Snap => "Snap Store", Backend::Nix => "Nixpkgs", Backend::AppImage => "managed AppImage", Backend::CustomEbuild => "Phoebus custom ebuild", } .to_string(); let digest = resolved.approval_digest(); let actions = vec![resolved.action.clone()]; let requires_root = resolved.action.is_mutating(); // Normalize the stored effect digest so the per-step binding check sees a // digest that matches the contents. let mut effects = resolved.effects.clone(); effects.recompute_digest(); let step_effects = vec![effects.clone()]; let mut plan = PreparedPlan { id: plan_id, created_unix: now, expires_unix: now + DEFAULT_PLAN_TTL_SECONDS, kind, summary: format!( "install {} via {}", resolved.request.application, resolved.candidate.backend.as_str() ), recommendation: rec, application: Some(resolved.request.application.clone()), candidate: Some(resolved.candidate.clone()), alternatives: resolved.alternatives.clone(), rationale: resolved.rationale.clone(), warnings: resolved.warnings.clone(), actions, effects, step_effects, digest, verification: resolved.verification.clone(), requires_root, source: source_display, executed: false, target_root: canonical_root(root), initiator_uid: effective_uid(), integrity: String::new(), }; plans.save(&mut plan)?; Ok(plan) } /// Deterministically choose which installed copy a removal targets. Shared by /// the legacy and AI-first paths so ownership discovery and the ambiguity /// policy cannot diverge. Ambiguity always requires an explicit lane flag. pub fn select_removal_copy( exec: &Exec, root: &Path, application: &str, backend_filter: Option, ) -> Result { let inspection = chooser::installed_copies(exec, root, application); if inspection.copies.is_empty() { return Err(ExecError::operation( "service", "plan_removal", format!("`{application}` is not installed on this system"), )); } if let Some(b) = backend_filter { return inspection .copies .into_iter() .find(|c| c.backend == b.as_str()) .ok_or_else(|| { ExecError::operation( "service", "plan_removal", format!( "`{application}` is not installed via {} (found in other lanes)", b.as_str() ), ) }); } if inspection.copies.len() > 1 { let details = inspection .copies .iter() .map(|c| format!("{} ({})", c.id, c.backend)) .collect::>() .join(", "); return Err(ExecError::operation( "service", "plan_removal", format!( "`{application}` is installed in multiple lanes: {details}. Specify which one to remove explicitly (e.g. sys remove {application} --flatpak or --portage)." ), )); } inspection.copies.into_iter().next().ok_or_else(|| { ExecError::operation( "service", "plan_removal", format!("`{application}` is not installed on this system"), ) }) } /// Plan an application removal across supported sources preserving user data by /// default, without contacting a model (legacy mode only). pub fn plan_removal( plans: &PlanStore, exec: &Exec, root: &Path, application: &str, backend_filter: Option, ) -> Result { let target_copy = select_removal_copy(exec, root, application, backend_filter)?; build_removal_plan( plans, exec, root, application, &target_copy, Vec::new(), Vec::new(), ) } /// Plan an application removal through the connected model (the default). The /// deterministic discovery and ambiguity policy run first; the model must then /// confirm exactly the discovered target. A model failure, or a proposal that /// does not match the deterministic target, stops the workflow. pub fn plan_removal_with_ai( plans: &PlanStore, exec: &Exec, root: &Path, application: &str, backend_filter: Option, ai: &AiInstall, facts: &SystemFacts, ) -> Result { let target_copy = select_removal_copy(exec, root, application, backend_filter)?; let discovered = chooser::installed_copies(exec, root, application); let list = discovered .copies .iter() .map(|c| format!("{} ({})", c.id, c.backend)) .collect::>() .join(", "); let instruction = format!( "The user asked to remove `{application}`. Read-only discovery found these installed \ copies: [{list}]. The policy-selected target is `{}` in the {} lane. Confirm a removal \ plan for exactly that copy by proposing the matching remove action; if the request is \ ambiguous, propose no action and explain what clarification is needed.", target_copy.id, target_copy.backend ); let assistant_plan: AssistantPlan = complete_plan( ai.provider, &ai.endpoint, &ai.model, facts, &instruction, ai.transport, ) .map_err(|e| ExecError::operation("service", "plan_removal_with_ai", e.to_string()))?; if assistant_plan.actions.len() != 1 || !removal_action_matches(&assistant_plan.actions[0], &target_copy) { return Err(ExecError::operation( "service", "plan_removal_with_ai", format!( "the model did not confirm the discovered removal target `{}` ({}); no removal \ plan was produced", target_copy.id, target_copy.backend ), )); } let mut rationale: Vec = assistant_plan .rationale .into_iter() .map(|r| format!("AI: {}", r.reason)) .collect(); if rationale.is_empty() { rationale.push(format!( "AI confirmed removal of the discovered {} copy", target_copy.backend )); } build_removal_plan( plans, exec, root, application, &target_copy, rationale, Vec::new(), ) } /// Whether a proposed action is the correct removal of the discovered copy. fn removal_action_matches(action: &SystemAction, copy: &chooser::InstalledCopy) -> bool { match (action, copy.backend.as_str()) { (SystemAction::FlatpakRemove { app_id }, "flatpak") => app_id == ©.id, (SystemAction::SnapRemove { name }, "snap") => name == ©.id, (SystemAction::AppImageRemove { name, .. }, "appimage") => name == ©.id, (SystemAction::RemovePackage { atom }, _) if copy.backend != "flatpak" && copy.backend != "snap" && copy.backend != "appimage" => { atom == ©.id } _ => false, } } /// Build a removal plan for a specific, already-discovered installed copy. /// Used by both the deterministic (legacy) path and the AI-first path, so the /// ownership discovery and policy validation are identical. pub fn build_removal_plan( plans: &PlanStore, exec: &Exec, root: &Path, application: &str, target_copy: &chooser::InstalledCopy, rationale: Vec, warnings: Vec, ) -> Result { let action = match target_copy.backend.as_str() { "flatpak" => SystemAction::FlatpakRemove { app_id: target_copy.id.clone(), }, "snap" => SystemAction::SnapRemove { name: target_copy.id.clone(), }, "appimage" => SystemAction::AppImageRemove { name: target_copy.id.clone(), // User data preserved by default purge_data: false, }, _ => SystemAction::RemovePackage { atom: target_copy.id.clone(), }, }; let mut effects = actions::resolve_effects(exec, &action, root)?; effects.recompute_digest(); let now = now_unix(); let plan_id = fresh_plan_id("rem"); let actions_vec = vec![action.clone()]; let step_effects = vec![effects.clone()]; let digest = compute_plan_digest(&actions_vec, None, &effects, &step_effects); let mut rationale = rationale; rationale.insert( 0, format!( "installed package {} detected in {} lane", target_copy.id, target_copy.backend ), ); rationale.push("preserves user configuration and data in home directory by default".into()); let mut plan = PreparedPlan { id: plan_id, created_unix: now, expires_unix: now + DEFAULT_PLAN_TTL_SECONDS, kind: PlanKind::Removal, summary: format!("remove {} ({})", target_copy.id, target_copy.backend), recommendation: format!( "Remove application {} from {}. Application binaries will be uninstalled while user data in the home directory is preserved.", target_copy.id, target_copy.backend ), application: Some(application.to_string()), candidate: None, alternatives: Vec::new(), rationale, warnings, actions: actions_vec, effects, step_effects, digest, verification: format!( "verify that `{}` ({}) is completely removed from the system", target_copy.id, target_copy.backend ), requires_root: action.is_mutating(), source: target_copy.backend.clone(), executed: false, target_root: canonical_root(root), initiator_uid: effective_uid(), integrity: String::new(), }; plans.save(&mut plan)?; Ok(plan) } /// Rewrite a lane-selectable catalogue action to an explicit source, and refuse /// an action that targets a different lane. A spanning action (history, /// snapshots, services) is returned unchanged. pub(super) fn constrain_action( action: SystemAction, constraint: Backend, ) -> std::result::Result { Ok(match action { SystemAction::SearchPackages { query, .. } => SystemAction::SearchPackages { query, backend: Some(constraint), }, SystemAction::ListPackages { filter, .. } => SystemAction::ListPackages { backend: Some(constraint), filter, }, SystemAction::PackageInfo { package, .. } => SystemAction::PackageInfo { package, backend: Some(constraint), }, SystemAction::CheckUpdates { .. } => SystemAction::CheckUpdates { backend: Some(constraint), }, SystemAction::ApplyUpdates { .. } => SystemAction::ApplyUpdates { backend: Some(constraint), }, SystemAction::CleanCache { .. } => SystemAction::CleanCache { backend: Some(constraint), }, // Optional-backend discovery and selection requests must be *rewritten* // to the constraint, not merely filtered afterwards: otherwise the // resolver would still query every lane before the results are // discarded. SystemAction::DiscoverCandidates { query, kind, gui, requires_sandbox, .. } => SystemAction::DiscoverCandidates { query, kind, backend: Some(constraint), gui, requires_sandbox, }, SystemAction::ChoosePackage { name, kind, gui, requires_sandbox, .. } => SystemAction::ChoosePackage { name, kind, backend: Some(constraint), gui, requires_sandbox, }, // `InspectInstallation` has no lane field but probes every lane; under // an explicit constraint it is refused rather than leaking other lanes. SystemAction::InspectInstallation { .. } => { return Err(format!( "inspect_installation spans every package lane, but this request was constrained \ to {}; use a lane-specific inventory instead", constraint.as_str() )); } other => { if let Some(own) = other.backend() { let matches = own == constraint || (own.is_portage() && constraint.is_portage()); if !matches { return Err(format!( "`{}` targets the {} lane, but this request was constrained to {}", other.describe(), own.as_str(), constraint.as_str() )); } } other } }) } /// Plan general system administration tasks via the connected model. /// /// The model may run a bounded, read-only investigation (search, inventory, /// information, update checks) before answering. An explicit `constraint` /// forbids any action that targets a different package lane, so a source flag /// constrains the AI workflow rather than bypassing it. pub fn plan_general( plans: &PlanStore, exec: &Exec, root: &Path, query: &str, facts: &SystemFacts, ai: &AiInstall, constraint: Option, ) -> Result { let instruction = match constraint { Some(backend) => format!( "{query}\n\n[source constraint: only the `{}` lane may be used; do not use \ another lane]", backend.as_str() ), None => query.to_string(), }; let investigate = |requests: &[SystemAction]| -> Vec { requests .iter() .map(|request| { let output = match constraint { Some(backend) => match constrain_action(request.clone(), backend) { Ok(action) => match actions::execute(exec, &action, None, root) { Ok(outcome) => outcome.output, Err(e) => format!("investigation failed: {e}"), }, Err(msg) => format!("refused by the source constraint: {msg}"), }, None => match actions::execute(exec, request, None, root) { Ok(outcome) => outcome.output, Err(e) => format!("investigation failed: {e}"), }, }; Evidence { request: request.describe(), output, } }) .collect() }; let assistant_plan: AssistantPlan = run_assistant( ai.provider, &ai.endpoint, &ai.model, facts, &instruction, ai.transport, &investigate, &ai.limits, ) .map_err(|e| ExecError::operation("service", "run_assistant", e.to_string()))?; // Apply the source constraint to the final actions too: a lane-specific // query is rewritten to the constraint, and an action that targets a // different lane is refused before anything is planned. let actions_list: Vec = match constraint { Some(backend) => assistant_plan .actions .iter() .cloned() .map(|action| { constrain_action(action, backend) .map_err(|msg| ExecError::operation("service", "source constraint", msg)) }) .collect::>>()?, None => assistant_plan.actions.clone(), }; let mut combined_effects = ResolvedPlan { established: true, ..Default::default() }; let mut any_mutating = false; let mut step_effects = Vec::new(); for act in &actions_list { let mut eff = actions::resolve_effects(exec, act, root).map_err(|e| { ExecError::operation( "service", "resolve_effects", format!("could not resolve effects for `{}`: {e}", act.describe()), ) })?; // Normalize the stored digest so the per-step binding check sees a // digest that matches the contents. eff.recompute_digest(); if eff.established { combined_effects.effects.extend(eff.effects.clone()); combined_effects.cleanup.extend(eff.cleanup.clone()); combined_effects.updates.extend(eff.updates.clone()); combined_effects .consequences .extend(eff.consequences.clone()); } step_effects.push(eff); any_mutating |= act.is_mutating(); } combined_effects.recompute_digest(); let now = now_unix(); let plan_id = fresh_plan_id("gen"); let digest = compute_plan_digest(&actions_list, None, &combined_effects, &step_effects); let rationale_strings: Vec = assistant_plan .rationale .into_iter() .map(|r| format!("{}: {}", r.action, r.reason)) .collect(); let mut plan = PreparedPlan { id: plan_id, created_unix: now, expires_unix: now + DEFAULT_PLAN_TTL_SECONDS, kind: PlanKind::General, summary: assistant_plan.summary.clone(), recommendation: assistant_plan.summary, application: None, candidate: None, alternatives: Vec::new(), rationale: rationale_strings, warnings: Vec::new(), actions: actions_list, effects: combined_effects, step_effects, digest, verification: "verify execution of planned actions".into(), requires_root: any_mutating, source: "AI Assistant".into(), executed: false, target_root: canonical_root(root), initiator_uid: effective_uid(), integrity: String::new(), }; plans.save(&mut plan)?; Ok(plan) }