//! Typed system actions. //! //! This is the schema the AI (or a deterministic front-end) may emit. There is //! deliberately no `run_shell`/`run_command` action: privileged work is //! expressed as closed, validated verbs that a policy engine can classify, //! preview and (after approval) execute. Unknown actions fail closed. use serde::{Deserialize, Serialize}; #[derive(Debug, thiserror::Error)] pub enum ActionError { #[error("invalid action JSON: {0}")] Json(#[from] serde_json::Error), #[error("invalid action: {0}")] Invalid(String), } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Risk { Low, Medium, High, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)] pub enum SystemAction { InspectService { name: String }, EnableService { name: String }, DisableService { name: String }, InspectPackage { atom: String }, InstallPackage { atom: String }, CreateSnapshot { operation: String }, History, UpdateSystem, PrepareUpdates, InspectUpdates, } impl SystemAction { pub fn describe(&self) -> String { match self { SystemAction::InspectService { name } => format!("inspect service {name}"), SystemAction::EnableService { name } => format!("enable service {name} at boot"), SystemAction::DisableService { name } => { format!("disable service {name} at boot") } SystemAction::InspectPackage { atom } => format!("inspect package {atom}"), SystemAction::InstallPackage { atom } => format!("install package {atom}"), SystemAction::CreateSnapshot { operation } => { format!("create a Btrfs snapshot before: {operation}") } SystemAction::History => "show system transaction history".to_string(), SystemAction::PrepareUpdates => { "prepare background updates (fetch + build binary packages, do not activate)" .to_string() } SystemAction::InspectUpdates => "show background update preparation status".to_string(), SystemAction::UpdateSystem => "update the system".to_string(), } } /// Risk classification used by the policy engine to decide whether a /// snapshot and/or stronger confirmation is required. pub fn risk(&self) -> Risk { match self { SystemAction::InspectService { .. } | SystemAction::InspectPackage { .. } => Risk::Low, SystemAction::History => Risk::Low, SystemAction::InspectUpdates => Risk::Low, SystemAction::PrepareUpdates => Risk::Medium, SystemAction::EnableService { .. } | SystemAction::DisableService { .. } | SystemAction::CreateSnapshot { .. } => Risk::Medium, SystemAction::InstallPackage { .. } | SystemAction::UpdateSystem => Risk::High, } } /// Whether this action modifies the system (and therefore needs /// authorization and, for High risk, a snapshot). pub fn is_mutating(&self) -> bool { !matches!( self, SystemAction::InspectService { .. } | SystemAction::InspectPackage { .. } | SystemAction::History | SystemAction::InspectUpdates ) } pub fn validate(&self) -> Result<(), String> { let valid_token = |s: &str| { !s.is_empty() && s.len() <= 128 && s.chars() .all(|c| c.is_ascii_alphanumeric() || "@._+-".contains(c)) }; match self { SystemAction::InspectService { name } | SystemAction::EnableService { name } | SystemAction::DisableService { name } => { if valid_token(name) { Ok(()) } else { Err(format!("invalid service name: {name}")) } } SystemAction::InspectPackage { atom } | SystemAction::InstallPackage { atom } => { let ok = atom.split('/').count() == 2 && atom .chars() .all(|c| c.is_ascii_alphanumeric() || "/*._+-".contains(c)); if ok { Ok(()) } else { Err(format!("invalid package atom: {atom}")) } } SystemAction::CreateSnapshot { operation } => { if operation.is_empty() { Err("snapshot operation must not be empty".into()) } else { Ok(()) } } SystemAction::History | SystemAction::UpdateSystem | SystemAction::PrepareUpdates | SystemAction::InspectUpdates => Ok(()), } } } /// A small deterministic parser for common `sys` phrases. /// /// Free-form requests that do not match are left to the AI path /// (`--action-file`), which still produces the same typed schema. pub fn parse_natural(text: &str) -> Option { let t = text.trim().to_lowercase(); let rest = |prefix: &str| t.strip_prefix(prefix).map(|r| r.trim().to_string()); if t == "history" || t.contains("history") { return Some(SystemAction::History); } if t == "update" || t == "update system" || t == "sys update" { return Some(SystemAction::UpdateSystem); } if t.contains("prepare") && t.contains("update") { return Some(SystemAction::PrepareUpdates); } if t.contains("what are you compiling") || t.contains("update status") { return Some(SystemAction::InspectUpdates); } if let Some(name) = rest("enable ") { if !name.is_empty() { return Some(SystemAction::EnableService { name }); } } if let Some(name) = rest("disable ") { if !name.is_empty() { return Some(SystemAction::DisableService { name }); } } if let Some(atom) = rest("install ") { if atom.contains('/') { return Some(SystemAction::InstallPackage { atom }); } } if let Some(name) = rest("inspect ") { if !name.is_empty() { return Some(SystemAction::InspectService { name }); } } None } pub fn parse_action(json: &str) -> Result { let action: SystemAction = serde_json::from_str(json)?; action.validate().map_err(ActionError::Invalid)?; Ok(action) } #[cfg(test)] mod tests { use super::*; #[test] fn parses_typed_actions() { let a = parse_action(r#"{"action":"enable_service","name":"sshd"}"#).unwrap(); assert_eq!( a, SystemAction::EnableService { name: "sshd".into() } ); assert!(a.is_mutating()); assert_eq!(a.risk(), Risk::Medium); } #[test] fn rejects_shell_action() { let err = parse_action(r#"{"action":"run_shell","command":"rm -rf /"}"#); assert!(err.is_err()); } #[test] fn rejects_unknown_fields_and_bad_values() { assert!(parse_action(r#"{"action":"install_package","atom":"steam","extra":1}"#).is_err()); assert!(parse_action(r#"{"action":"install_package","atom":"notanatom"}"#).is_err()); assert!(parse_action(r#"{"action":"enable_service","name":"bad name"}"#).is_err()); } #[test] fn natural_language_maps_to_typed_actions() { assert_eq!( parse_natural("enable sshd"), Some(SystemAction::EnableService { name: "sshd".into() }) ); assert_eq!(parse_natural("history"), Some(SystemAction::History)); assert_eq!( parse_natural("install app-editors/vim"), Some(SystemAction::InstallPackage { atom: "app-editors/vim".into() }) ); assert_eq!(parse_natural("why is my audio broken"), None); } #[test] fn risk_levels() { assert_eq!( parse_action(r#"{"action":"history"}"#).unwrap().risk(), Risk::Low ); assert_eq!( parse_action(r#"{"action":"update_system"}"#) .unwrap() .risk(), Risk::High ); } }