phoebus_os/installer-rs/crates/phoebus-ai/src/lib.rs
Phoebus 38214ea9e7 chore: import Phoebus OS installer and Rust migration
Initial public import of the proven Bash installer (installer/) and the production Rust workspace (installer-rs/). The reference ISO, build output and local agent transcripts are gitignored.

Verified: installer/tests/run_tests.sh and cargo test --workspace both pass.
2026-09-20 02:07:33 -07:00

191 lines
7.6 KiB
Rust

//! 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 privacy;
use phoebus_core::config::{DesktopProfile, Encryption, Filesystem, InstallConfig, KernelProfile, PackagePolicy};
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),
}
/// A versioned, closed set of configuration changes.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AiProposal {
pub version: u32,
pub changes: Vec<ProposedChange>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[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 },
}
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}"),
}
}
/// Semantic validation against the current configuration.
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.starts_with("/dev/") {
Ok(())
} else {
Err(format!("target disk must be a /dev path: {value}"))
}
}
_ => Ok(()),
}
}
}
/// Parse a proposal from JSON text.
pub fn parse_proposal(text: &str) -> Result<AiProposal, AiError> {
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<Vec<AppliedChange>, 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 } => 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,
}
applied.push(AppliedChange {
description: change.describe(),
});
}
Ok(applied)
}
#[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": "dwl"}
]
}"#;
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::Dwl);
}
#[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());
}
}