//! Typed AI proposals. //! //! The model never receives a shell. It can only emit a structured //! `AiProposal` whose changes deserialize into a closed enum. Unknown actions //! fail closed. Each change is validated semantically before it is merged into //! the typed configuration. Privileged execution is a separate, human-approved //! step performed by the deterministic backend. pub mod assistant; pub mod install; pub mod privacy; pub mod provider; use phoebus_core::config::{ DesktopProfile, Encryption, Filesystem, InstallConfig, KernelProfile, PackagePolicy, PackageUse, }; use phoebus_core::validate; use serde::{Deserialize, Serialize}; #[derive(Debug, thiserror::Error)] pub enum AiError { #[error("proposal JSON is invalid: {0}")] Json(#[from] serde_json::Error), #[error("proposal version {0} is not supported")] UnsupportedVersion(u32), #[error("change rejected: {0}")] Rejected(String), #[error("AI provider unavailable: {0}")] ProviderUnavailable(String), #[error("AI provider error: {0}")] Provider(String), #[error("model context would carry personal data: {0}")] PrivateData(String), } /// A versioned, closed set of configuration changes, each with a rationale. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct AiProposal { pub version: u32, pub changes: Vec, /// One entry per change, naming the action and giving the evidence/reason. #[serde(default)] pub rationale: Vec, } /// Why a change was proposed. Deterministic code requires a non-empty reason /// for every accepted change. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(deny_unknown_fields)] pub struct Rationale { pub action: String, pub reason: String, #[serde(default)] pub evidence: Vec, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)] pub enum ProposedChange { SetHostname { value: String, }, SetTimezone { value: String, }, SetLocale { value: String, }, SetKeymap { value: String, }, SetUsername { value: String, }, SetTargetDisk { value: String, }, SetFilesystem { value: Filesystem, }, SetEncryption { value: Encryption, }, SetKernelProfile { value: KernelProfile, }, SetPackagePolicy { value: PackagePolicy, }, SetDesktopProfile { value: DesktopProfile, }, SetFlatpak { value: bool, }, /// Prefer signed binary packages (still signature-verified). SetBinaryPackages { value: bool, }, /// Explicit Portage `MAKEOPTS -j` value (capped by available memory later). SetBuildJobs { value: u32, }, /// One scoped `package.use` flag for one atom. SetPackageUse { atom: String, flag: String, enabled: bool, }, } impl ProposedChange { pub fn describe(&self) -> String { match self { ProposedChange::SetHostname { value } => format!("hostname = {value}"), ProposedChange::SetTimezone { value } => format!("timezone = {value}"), ProposedChange::SetLocale { value } => format!("locale = {value}"), ProposedChange::SetKeymap { value } => format!("keymap = {value}"), ProposedChange::SetUsername { value } => format!("username = {value}"), ProposedChange::SetTargetDisk { value } => format!("target disk = {value}"), ProposedChange::SetFilesystem { value } => format!("filesystem = {value}"), ProposedChange::SetEncryption { value } => format!("encryption = {value}"), ProposedChange::SetKernelProfile { value } => format!("kernel profile = {value}"), ProposedChange::SetPackagePolicy { value } => format!("package policy = {value}"), ProposedChange::SetDesktopProfile { value } => format!("desktop profile = {value}"), ProposedChange::SetFlatpak { value } => format!("flatpak = {value}"), ProposedChange::SetBinaryPackages { value } => { format!("prefer signed binary packages = {value}") } ProposedChange::SetBuildJobs { value } => format!("build jobs = {value}"), ProposedChange::SetPackageUse { atom, flag, enabled, } => format!( "package.use {atom} {}{flag}", if *enabled { "" } else { "-" } ), } } /// The stable action name (matches the serde tag). pub fn action_name(&self) -> &'static str { match self { ProposedChange::SetHostname { .. } => "set_hostname", ProposedChange::SetTimezone { .. } => "set_timezone", ProposedChange::SetLocale { .. } => "set_locale", ProposedChange::SetKeymap { .. } => "set_keymap", ProposedChange::SetUsername { .. } => "set_username", ProposedChange::SetTargetDisk { .. } => "set_target_disk", ProposedChange::SetFilesystem { .. } => "set_filesystem", ProposedChange::SetEncryption { .. } => "set_encryption", ProposedChange::SetKernelProfile { .. } => "set_kernel_profile", ProposedChange::SetPackagePolicy { .. } => "set_package_policy", ProposedChange::SetDesktopProfile { .. } => "set_desktop_profile", ProposedChange::SetFlatpak { .. } => "set_flatpak", ProposedChange::SetBinaryPackages { .. } => "set_binary_packages", ProposedChange::SetBuildJobs { .. } => "set_build_jobs", ProposedChange::SetPackageUse { .. } => "set_package_use", } } /// A key identifying what this change touches, for conflict detection. pub fn target_key(&self) -> String { match self { ProposedChange::SetHostname { .. } => "system.hostname".into(), ProposedChange::SetTimezone { .. } => "system.timezone".into(), ProposedChange::SetLocale { .. } => "system.locale".into(), ProposedChange::SetKeymap { .. } => "system.keymap".into(), ProposedChange::SetUsername { .. } => "user.username".into(), ProposedChange::SetTargetDisk { .. } => "storage.disk".into(), ProposedChange::SetFilesystem { .. } => "storage.filesystem".into(), ProposedChange::SetEncryption { .. } => "encryption.mode".into(), ProposedChange::SetKernelProfile { .. } => "kernel.profile".into(), ProposedChange::SetPackagePolicy { .. } => "packages.policy".into(), ProposedChange::SetDesktopProfile { .. } => "desktop.profile".into(), ProposedChange::SetFlatpak { .. } => "desktop.flatpak".into(), ProposedChange::SetBinaryPackages { .. } => "packages.binary_packages".into(), ProposedChange::SetBuildJobs { .. } => "packages.build_jobs".into(), ProposedChange::SetPackageUse { atom, flag, .. } => { format!("packages.package_use:{atom}:{flag}") } } } /// Semantic validation. `package.use` changes are validated with the same /// rules the configuration uses. pub fn validate(&self) -> Result<(), String> { match self { ProposedChange::SetHostname { value } => validate::validate_hostname(value), ProposedChange::SetTimezone { value } => validate::validate_timezone(value), ProposedChange::SetLocale { value } => validate::validate_locale(value), ProposedChange::SetKeymap { value } => validate::validate_keymap(value), ProposedChange::SetUsername { value } => validate::validate_username(value), ProposedChange::SetTargetDisk { value } => { if value.is_empty() || value.starts_with("/dev/") { Ok(()) } else { Err(format!("target disk must be a /dev path: {value}")) } } ProposedChange::SetBuildJobs { value } => { if (1..=256).contains(value) { Ok(()) } else { Err(format!("build jobs must be between 1 and 256: {value}")) } } ProposedChange::SetPackageUse { atom, flag, .. } => { validate::validate_package_atom(atom)?; validate::validate_use_flag(flag) } ProposedChange::SetFilesystem { value } => { if *value != Filesystem::Btrfs { Err("Btrfs is the required filesystem for Phoebus OS".into()) } else { Ok(()) } } ProposedChange::SetDesktopProfile { value } => { if *value != DesktopProfile::Mango { Err( "Mango + DankMaterialShell is the required desktop profile for Phoebus OS" .into(), ) } else { Ok(()) } } ProposedChange::SetFlatpak { value } => { if !*value { Err("Flatpak is a required subsystem of Phoebus OS".into()) } else { Ok(()) } } _ => Ok(()), } } } /// Parse a proposal from JSON text. pub fn parse_proposal(text: &str) -> Result { let proposal: AiProposal = serde_json::from_str(text)?; if proposal.version != 1 { return Err(AiError::UnsupportedVersion(proposal.version)); } Ok(proposal) } /// The changes that were applied. #[derive(Debug, Clone)] pub struct AppliedChange { pub description: String, } /// Validate and merge a proposal into the configuration. /// /// If any change fails validation, nothing is applied (fail closed). pub fn apply( config: &mut InstallConfig, proposal: &AiProposal, ) -> Result, AiError> { for change in &proposal.changes { change .validate() .map_err(|e| AiError::Rejected(format!("{}: {e}", change.describe())))?; } let mut applied = Vec::new(); for change in &proposal.changes { match change { ProposedChange::SetHostname { value } => config.system.hostname = value.clone(), ProposedChange::SetTimezone { value } => config.system.timezone = value.clone(), ProposedChange::SetLocale { value } => config.system.locale = value.clone(), ProposedChange::SetKeymap { value } => config.system.keymap = value.clone(), ProposedChange::SetUsername { value } => config.user.username = value.clone(), ProposedChange::SetTargetDisk { value } => { if !value.is_empty() { config.storage.disk = value.clone(); } } ProposedChange::SetFilesystem { value } => config.storage.filesystem = *value, ProposedChange::SetEncryption { value } => config.encryption.mode = *value, ProposedChange::SetKernelProfile { value } => config.kernel.profile = *value, ProposedChange::SetPackagePolicy { value } => config.packages.policy = *value, ProposedChange::SetDesktopProfile { value } => config.desktop.profile = *value, ProposedChange::SetFlatpak { value } => config.desktop.flatpak = *value, ProposedChange::SetBinaryPackages { value } => config.packages.binary_packages = *value, ProposedChange::SetBuildJobs { value } => config.packages.build_jobs = Some(*value), ProposedChange::SetPackageUse { atom, flag, enabled, } => { let entry = PackageUse { atom: atom.clone(), flag: flag.clone(), enabled: *enabled, }; if let Some(existing) = config .packages .package_use .iter_mut() .find(|e| e.atom == *atom && e.flag == *flag) { existing.enabled = *enabled; } else { config.packages.package_use.push(entry); } } } applied.push(AppliedChange { description: change.describe(), }); } Ok(applied) } /// A change that passed review, with the model's stated reason. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ReviewedChange { pub description: String, pub reason: String, pub evidence: Vec, } /// The result of reviewing a proposal: the changes that were applied and the /// rationale behind each. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ReviewOutcome { pub applied: Vec, } impl ReviewOutcome { /// A compact human-readable summary of accepted changes and reasons. pub fn render(&self) -> String { let mut out = String::new(); out.push_str("Accepted AI changes:\n"); if self.applied.is_empty() { out.push_str(" (none)\n"); } for change in &self.applied { out.push_str(&format!(" + {}\n", change.description)); out.push_str(&format!(" reason: {}\n", change.reason)); for item in &change.evidence { out.push_str(&format!(" evidence: {item}\n")); } } out } } /// Changes that would weaken a required, non-negotiable setting. /// /// Phoebus is a LUKS2 + Btrfs system; aggressive kernel profiles are /// speculative. The model may propose these, but a deterministic check refuses /// them so the proven security posture is never traded for convenience. fn fixed_policy_violation(change: &ProposedChange) -> Option { match change { ProposedChange::SetEncryption { value: Encryption::None, } => Some("encryption must remain LUKS2".into()), ProposedChange::SetFilesystem { value: Filesystem::Ext4, } => Some("the filesystem must remain Btrfs".into()), ProposedChange::SetKernelProfile { value: KernelProfile::Aggressive, } => Some("aggressive kernel profiles are not accepted".into()), ProposedChange::SetFlatpak { value: false } => Some( "Flatpak is a required workstation subsystem and cannot be disabled or removed".into(), ), ProposedChange::SetPackageUse { atom, flag, .. } if atom.starts_with("x11-drivers/nvidia-drivers") => { let _ = flag; Some( "the NVIDIA driver branch and kernel-module flavor are selected from the \ detected PCI device IDs and cannot be changed by the model" .into(), ) } _ => None, } } /// Validate a proposal with mandatory evidence, reject conflicts and unsafe /// changes, and apply it atomically (fail closed). This is the path a guided /// install uses; the model never reaches the executor without passing it. pub fn review(config: &mut InstallConfig, proposal: &AiProposal) -> Result { if proposal.version != 1 { return Err(AiError::UnsupportedVersion(proposal.version)); } // Every change needs an explicit, non-empty reason. let reason_for = |change: &ProposedChange| -> Result<&Rationale, AiError> { proposal .rationale .iter() .find(|r| r.action == change.action_name() && !r.reason.trim().is_empty()) .ok_or_else(|| { AiError::Rejected(format!( "{}: missing a non-empty reason", change.action_name() )) }) }; // Reject conflicts before applying anything. let mut seen: Vec = Vec::new(); for change in &proposal.changes { let key = change.target_key(); if seen.contains(&key) { return Err(AiError::Rejected(format!("conflicting changes for {key}"))); } seen.push(key); } // Validate everything; a single failure rejects the whole proposal. for change in &proposal.changes { if let Some(reason) = fixed_policy_violation(change) { return Err(AiError::Rejected(format!( "{}: {reason}", change.action_name() ))); } change.validate().map_err(AiError::Rejected)?; reason_for(change)?; } // Apply only after all checks pass. `apply` repeats validation, which is // harmless and keeps a single merge implementation. let applied = apply(config, proposal)?; let reviewed = proposal .changes .iter() .zip(applied) .filter_map(|(change, applied)| { // Flatpak is enabled by default and cannot be removed; do not clutter // the proposed changes list with redundant no-op mentions. if let ProposedChange::SetFlatpak { value: true } = change { return None; } let rationale = proposal .rationale .iter() .find(|r| r.action == change.action_name()) .expect("reason checked above"); Some(ReviewedChange { description: applied.description, reason: rationale.reason.clone(), evidence: rationale.evidence.clone(), }) }) .collect(); Ok(ReviewOutcome { applied: reviewed }) } #[cfg(test)] mod tests { use super::*; #[test] fn parses_and_applies_a_valid_proposal() { let text = r#"{ "version": 1, "changes": [ {"action": "set_hostname", "value": "box"}, {"action": "set_encryption", "value": "luks2"}, {"action": "set_desktop_profile", "value": "mango"} ] }"#; let proposal = parse_proposal(text).unwrap(); let mut config = InstallConfig::default(); let applied = apply(&mut config, &proposal).unwrap(); assert_eq!(applied.len(), 3); assert_eq!(config.system.hostname, "box"); assert_eq!(config.encryption.mode, Encryption::Luks2); assert_eq!(config.desktop.profile, DesktopProfile::Mango); } #[test] fn non_mango_desktop_or_non_btrfs_rejected() { let text = r#"{ "version": 1, "changes": [ {"action": "set_desktop_profile", "value": "none"} ] }"#; let proposal = parse_proposal(text).unwrap(); let mut config = InstallConfig::default(); assert!(apply(&mut config, &proposal).is_err()); let text2 = r#"{ "version": 1, "changes": [ {"action": "set_filesystem", "value": "ext4"} ] }"#; let proposal2 = parse_proposal(text2).unwrap(); let mut config2 = InstallConfig::default(); assert!(apply(&mut config2, &proposal2).is_err()); } #[test] fn unknown_action_fails_closed() { let text = r#"{"version":1,"changes":[{"action":"run_shell","command":"rm -rf /"}]}"#; assert!(parse_proposal(text).is_err()); } #[test] fn invalid_value_rejects_whole_proposal() { let text = r#"{"version":1,"changes":[ {"action":"set_hostname","value":"good"}, {"action":"set_hostname","value":"bad host"} ]}"#; let proposal = parse_proposal(text).unwrap(); let mut config = InstallConfig::default(); assert!(apply(&mut config, &proposal).is_err()); // Nothing applied. assert_eq!(config.system.hostname, "phoebus"); } #[test] fn unsupported_version_rejected() { let text = r#"{"version":99,"changes":[]}"#; assert!(matches!( parse_proposal(text), Err(AiError::UnsupportedVersion(99)) )); } #[test] fn filesystem_enum_is_validated_by_serde() { let text = r#"{"version":1,"changes":[{"action":"set_filesystem","value":"zfs"}]}"#; assert!(parse_proposal(text).is_err()); } #[test] fn review_applies_scoped_package_use_and_build_jobs() { let text = r#"{ "version": 1, "changes": [ {"action":"set_build_jobs","value":6}, {"action":"set_binary_packages","value":true}, {"action":"set_package_use","atom":"www-client/firefox","flag":"wayland","enabled":true} ], "rationale": [ {"action":"set_build_jobs","reason":"16 GiB of RAM","evidence":["memory_mib=16384"]}, {"action":"set_binary_packages","reason":"signed binhost is available","evidence":["binhost=openrc"]}, {"action":"set_package_use","reason":"wayland desktop","evidence":["desktop=mango"]} ] }"#; let proposal = parse_proposal(text).unwrap(); let mut config = InstallConfig::default(); let outcome = review(&mut config, &proposal).unwrap(); assert_eq!(outcome.applied.len(), 3); assert_eq!(config.packages.build_jobs, Some(6)); assert!(config.packages.binary_packages); assert_eq!(config.packages.package_use.len(), 1); assert_eq!(config.packages.package_use[0].atom, "www-client/firefox"); let rendered = outcome.render(); assert!(rendered.contains("reason:")); assert!(rendered.contains("evidence:")); } #[test] fn review_rejects_a_change_without_a_reason() { let text = r#"{ "version": 1, "changes": [{"action":"set_hostname","value":"box"}], "rationale": [] }"#; let proposal = parse_proposal(text).unwrap(); let mut config = InstallConfig::default(); assert!(matches!( review(&mut config, &proposal), Err(AiError::Rejected(_)) )); // Nothing applied. assert_eq!(config.system.hostname, "phoebus"); } #[test] fn review_rejects_conflicting_changes() { let text = r#"{ "version": 1, "changes": [ {"action":"set_hostname","value":"one"}, {"action":"set_hostname","value":"two"} ], "rationale": [ {"action":"set_hostname","reason":"a"}, {"action":"set_hostname","reason":"b"} ] }"#; let proposal = parse_proposal(text).unwrap(); let mut config = InstallConfig::default(); assert!(matches!( review(&mut config, &proposal), Err(AiError::Rejected(_)) )); assert_eq!(config.system.hostname, "phoebus"); } #[test] fn review_rejects_unsafe_package_use() { let text = r#"{ "version": 1, "changes": [ {"action":"set_package_use","atom":"*/*","flag":"*","enabled":true} ], "rationale": [{"action":"set_package_use","reason":"all"}] }"#; let proposal = parse_proposal(text).unwrap(); let mut config = InstallConfig::default(); assert!(matches!( review(&mut config, &proposal), Err(AiError::Rejected(_)) )); assert!(config.packages.package_use.is_empty()); } #[test] fn review_refuses_to_change_the_nvidia_driver() { let text = r#"{ "version": 1, "changes": [ {"action":"set_package_use","atom":"x11-drivers/nvidia-drivers","flag":"kernel-open","enabled":false} ], "rationale": [{"action":"set_package_use","reason":"force proprietary"}] }"#; let proposal = parse_proposal(text).unwrap(); let mut config = InstallConfig::default(); assert!(matches!( review(&mut config, &proposal), Err(AiError::Rejected(_)) )); assert!(config.packages.package_use.is_empty()); } #[test] fn review_refuses_to_weaken_required_settings() { for (action, value) in [ ("set_encryption", "none"), ("set_filesystem", "ext4"), ("set_kernel_profile", "aggressive"), ] { let text = format!( r#"{{"version":1,"changes":[{{"action":"{action}","value":"{value}"}}],"rationale":[{{"action":"{action}","reason":"x"}}]}}"# ); let proposal = parse_proposal(&text).unwrap(); let mut config = InstallConfig::default(); assert!( matches!(review(&mut config, &proposal), Err(AiError::Rejected(_))), "{action}={value} must be refused" ); // The proven defaults are untouched. assert_eq!(config.encryption.mode, Encryption::Luks2); assert_eq!(config.storage.filesystem, Filesystem::Btrfs); assert_eq!(config.kernel.profile, KernelProfile::Safe); } } #[test] fn review_requires_a_supported_version() { let proposal = parse_proposal(r#"{"version":1,"changes":[]}"#).unwrap(); let mut config = InstallConfig::default(); assert!(review(&mut config, &proposal).is_ok()); let bad = AiProposal { version: 2, changes: vec![], rationale: vec![], }; assert!(matches!( review(&mut config, &bad), Err(AiError::UnsupportedVersion(2)) )); } }