From dcb38f6c74d2ca61f1c837efc9596d153710a128 Mon Sep 17 00:00:00 2001 From: AIEN Date: Sat, 19 Sep 2026 08:12:11 -0500 Subject: [PATCH] feat: implement Milestone 1 laboratory isolation and host supervisor --- Cargo.toml | 1 + src/isolation/container.rs | 220 ++++++++++++++++++++++++++++++++ src/isolation/manifest.rs | 226 +++++++++++++++++++++++++++++++++ src/isolation/mod.rs | 9 ++ src/isolation/rollback.rs | 100 +++++++++++++++ src/isolation/root_of_trust.rs | 112 ++++++++++++++++ src/lib.rs | 7 + src/supervisor/mod.rs | 190 +++++++++++++++++++++++++++ 8 files changed, 865 insertions(+) create mode 100644 src/isolation/container.rs create mode 100644 src/isolation/manifest.rs create mode 100644 src/isolation/mod.rs create mode 100644 src/isolation/rollback.rs create mode 100644 src/isolation/root_of_trust.rs create mode 100644 src/supervisor/mod.rs diff --git a/Cargo.toml b/Cargo.toml index 05fe9ba..c01223b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,6 +27,7 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] } sha2 = "0.10" hex = "0.4" uuid = { version = "1.8", features = ["v4"] } +libc = "0.2" [dev-dependencies] tempfile = "3.17" diff --git a/src/isolation/container.rs b/src/isolation/container.rs new file mode 100644 index 0000000..8279413 --- /dev/null +++ b/src/isolation/container.rs @@ -0,0 +1,220 @@ +use std::path::{Path, PathBuf}; +use std::process::Command; + +#[derive(Debug, Clone)] +pub struct SandboxLimits { + pub max_memory_mb: u64, + pub max_cpu_percent: u32, + pub max_pids: u32, + pub timeout_seconds: u64, +} + +impl Default for SandboxLimits { + fn default() -> Self { + Self { + max_memory_mb: 16384, + max_cpu_percent: 800, + max_pids: 256, + timeout_seconds: 180, + } + } +} + +impl SandboxLimits { + pub fn new(max_memory_mb: u64, max_cpu_percent: u32, max_pids: u32, timeout_seconds: u64) -> Self { + Self { + max_memory_mb, + max_cpu_percent, + max_pids, + timeout_seconds, + } + } +} + +#[derive(Debug, Clone)] +pub struct BuildJail { + pub builder_image: String, + pub host_source_dir: PathBuf, + pub host_output_dir: PathBuf, + pub limits: SandboxLimits, +} + +impl BuildJail { + pub fn new(builder_image: &str, host_source: &Path, host_output: &Path) -> Self { + Self { + builder_image: builder_image.to_string(), + host_source_dir: host_source.to_path_buf(), + host_output_dir: host_output.to_path_buf(), + limits: SandboxLimits::default(), + } + } + + pub fn build_docker_args(&self, command: &[&str]) -> Vec { + let uid = unsafe { libc::getuid() }.to_string(); + let gid = unsafe { libc::getgid() }.to_string(); + + let mut args = vec![ + "run".to_string(), + "--rm".to_string(), + "--network".to_string(), + "none".to_string(), + "--read-only".to_string(), + "--cap-drop".to_string(), + "ALL".to_string(), + "--security-opt".to_string(), + "no-new-privileges".to_string(), + "--memory".to_string(), + format!("{}m", self.limits.max_memory_mb), + "--cpus".to_string(), + format!("{:.2}", self.limits.max_cpu_percent as f64 / 100.0), + "--pids-limit".to_string(), + self.limits.max_pids.to_string(), + "-u".to_string(), + format!("{}:{}", uid, gid), + "-v".to_string(), + format!("{}:/workspace/src:ro", self.host_source_dir.display()), + "-v".to_string(), + format!("{}:/output:rw", self.host_output_dir.display()), + "--tmpfs".to_string(), + "/tmp:rw,size=4G,mode=1777".to_string(), + "--tmpfs".to_string(), + "/build:rw,size=8G,mode=1777".to_string(), + "-w".to_string(), + "/build".to_string(), + self.builder_image.clone(), + ]; + + for c in command { + args.push(c.to_string()); + } + + args + } + + pub fn execute(&self, command: &[&str]) -> Result<(bool, String, String), String> { + let args = self.build_docker_args(command); + let output = Command::new("docker") + .args(&args) + .output() + .map_err(|e| format!("Failed to invoke docker container: {}", e))?; + + Ok(( + output.status.success(), + String::from_utf8_lossy(&output.stdout).to_string(), + String::from_utf8_lossy(&output.stderr).to_string(), + )) + } +} + +#[derive(Debug, Clone)] +pub struct GpuEvaluationJail { + pub eval_image: String, + pub host_artifact_dir: PathBuf, + pub host_holdout_dir: PathBuf, + pub cdi_device: String, + pub limits: SandboxLimits, +} + +impl GpuEvaluationJail { + pub fn new(eval_image: &str, artifact_dir: &Path, holdout_dir: &Path) -> Self { + Self { + eval_image: eval_image.to_string(), + host_artifact_dir: artifact_dir.to_path_buf(), + host_holdout_dir: holdout_dir.to_path_buf(), + cdi_device: "nvidia.com/gpu=0".to_string(), + limits: SandboxLimits::new(49152, 800, 256, 300), // 48 GB limit, 300s timeout + } + } + + pub fn build_docker_args(&self, command: &[&str]) -> Vec { + let uid = unsafe { libc::getuid() }.to_string(); + let gid = unsafe { libc::getgid() }.to_string(); + + let mut args = vec![ + "run".to_string(), + "--rm".to_string(), + "--device".to_string(), + self.cdi_device.clone(), + "--read-only".to_string(), + "--cap-drop".to_string(), + "ALL".to_string(), + "--security-opt".to_string(), + "no-new-privileges".to_string(), + "--memory".to_string(), + format!("{}m", self.limits.max_memory_mb), + "--cpus".to_string(), + format!("{:.2}", self.limits.max_cpu_percent as f64 / 100.0), + "-u".to_string(), + format!("{}:{}", uid, gid), + "-v".to_string(), + format!("{}:/artifacts:ro", self.host_artifact_dir.display()), + "-v".to_string(), + format!("{}:/holdouts:ro", self.host_holdout_dir.display()), + "--tmpfs".to_string(), + "/tmp:rw,size=4G,mode=1777".to_string(), + "-w".to_string(), + "/artifacts".to_string(), + self.eval_image.clone(), + ]; + + for c in command { + args.push(c.to_string()); + } + + args + } + + pub fn execute(&self, command: &[&str]) -> Result<(bool, String, String), String> { + let args = self.build_docker_args(command); + let output = Command::new("docker") + .args(&args) + .output() + .map_err(|e| format!("Failed to invoke GPU evaluation container: {}", e))?; + + Ok(( + output.status.success(), + String::from_utf8_lossy(&output.stdout).to_string(), + String::from_utf8_lossy(&output.stderr).to_string(), + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_build_jail_args() { + let jail = BuildJail::new( + "spark-rsi-builder@sha256:123456", + Path::new("/tmp/src"), + Path::new("/tmp/out"), + ); + let args = jail.build_docker_args(&["cargo", "build", "--offline"]); + + assert!(args.contains(&"--network".to_string())); + assert!(args.contains(&"none".to_string())); + assert!(args.contains(&"--read-only".to_string())); + assert!(args.contains(&"--cap-drop".to_string())); + assert!(args.contains(&"ALL".to_string())); + assert!(args.contains(&"/tmp/src:/workspace/src:ro".to_string())); + assert!(args.contains(&"/tmp/out:/output:rw".to_string())); + assert!(args.contains(&"cargo".to_string())); + } + + #[test] + fn test_gpu_eval_jail_args() { + let jail = GpuEvaluationJail::new( + "spark-rsi-eval@sha256:abcdef", + Path::new("/tmp/art"), + Path::new("/var/lib/holdouts"), + ); + let args = jail.build_docker_args(&["./bench_suite", "--iterations", "30"]); + + assert!(args.contains(&"--device".to_string())); + assert!(args.contains(&"nvidia.com/gpu=0".to_string())); + assert!(args.contains(&"/tmp/art:/artifacts:ro".to_string())); + assert!(args.contains(&"/var/lib/holdouts:/holdouts:ro".to_string())); + assert!(args.contains(&"30".to_string())); + } +} diff --git a/src/isolation/manifest.rs b/src/isolation/manifest.rs new file mode 100644 index 0000000..7304b89 --- /dev/null +++ b/src/isolation/manifest.rs @@ -0,0 +1,226 @@ +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct ArtifactRecord { + pub relative_path: String, + pub sha256: String, + pub size_bytes: u64, + pub is_executable: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CandidateManifest { + pub manifest_version: String, + pub candidate_id: String, + pub parent_commit_sha: String, + pub proposal_id: String, + pub code_tier: String, + pub declared_files: Vec, + pub primary_metric: String, + pub expected_delta_pct: f64, + pub timestamp_utc: String, +} + +impl CandidateManifest { + pub fn new( + candidate_id: &str, + parent_commit_sha: &str, + proposal_id: &str, + code_tier: &str, + declared_files: Vec, + primary_metric: &str, + expected_delta_pct: f64, + ) -> Self { + Self { + manifest_version: "1.0.0".to_string(), + candidate_id: candidate_id.to_string(), + parent_commit_sha: parent_commit_sha.to_string(), + proposal_id: proposal_id.to_string(), + code_tier: code_tier.to_string(), + declared_files, + primary_metric: primary_metric.to_string(), + expected_delta_pct, + timestamp_utc: chrono::Utc::now().to_rfc3339(), + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct ArtifactManifest { + pub manifest_version: String, + pub candidate_id: String, + pub builder_image_digest: String, + pub source_bundle_digest: String, + pub artifacts: Vec, + pub manifest_digest: String, + pub timestamp_utc: String, +} + +impl ArtifactManifest { + pub fn compute_file_sha256(path: &Path) -> Result { + let bytes = fs::read(path).map_err(|e| format!("Failed to read file {:?}: {}", path, e))?; + let mut hasher = Sha256::new(); + hasher.update(&bytes); + Ok(hex::encode(hasher.finalize())) + } + + pub fn compute_source_digest(dir: &Path) -> Result { + let mut file_entries = Vec::new(); + Self::collect_files_sorted(dir, dir, &mut file_entries)?; + + let mut hasher = Sha256::new(); + for (rel_path, abs_path) in file_entries { + let file_hash = Self::compute_file_sha256(&abs_path)?; + hasher.update(rel_path.as_bytes()); + hasher.update(file_hash.as_bytes()); + } + + Ok(hex::encode(hasher.finalize())) + } + + fn collect_files_sorted( + base: &Path, + current: &Path, + acc: &mut Vec<(String, PathBuf)>, + ) -> Result<(), String> { + if !current.exists() { + return Ok(()); + } + let mut entries = Vec::new(); + for entry in fs::read_dir(current).map_err(|e| e.to_string())?.flatten() { + entries.push(entry.path()); + } + entries.sort(); + + for path in entries { + let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default(); + if name == "target" || name == ".git" || name == "node_modules" { + continue; + } + if path.is_dir() { + Self::collect_files_sorted(base, &path, acc)?; + } else if path.is_file() { + let rel = path + .strip_prefix(base) + .map_err(|e| e.to_string())? + .to_string_lossy() + .to_string(); + acc.push((rel, path)); + } + } + Ok(()) + } + + pub fn generate_from_output_dir( + candidate_id: &str, + builder_image_digest: &str, + source_bundle_digest: &str, + output_dir: &Path, + ) -> Result { + let mut file_entries = Vec::new(); + Self::collect_files_sorted(output_dir, output_dir, &mut file_entries)?; + + let mut records = Vec::new(); + let mut digest_hasher = Sha256::new(); + digest_hasher.update(candidate_id.as_bytes()); + digest_hasher.update(builder_image_digest.as_bytes()); + digest_hasher.update(source_bundle_digest.as_bytes()); + + for (rel_path, abs_path) in file_entries { + let meta = fs::metadata(&abs_path).map_err(|e| e.to_string())?; + let sha = Self::compute_file_sha256(&abs_path)?; + let is_exec = (meta.permissions().mode() & 0o111) != 0; + + digest_hasher.update(rel_path.as_bytes()); + digest_hasher.update(sha.as_bytes()); + digest_hasher.update(meta.len().to_be_bytes()); + + records.push(ArtifactRecord { + relative_path: rel_path, + sha256: sha, + size_bytes: meta.len(), + is_executable: is_exec, + }); + } + + let manifest_digest = hex::encode(digest_hasher.finalize()); + + Ok(Self { + manifest_version: "1.0.0".to_string(), + candidate_id: candidate_id.to_string(), + builder_image_digest: builder_image_digest.to_string(), + source_bundle_digest: source_bundle_digest.to_string(), + artifacts: records, + manifest_digest, + timestamp_utc: chrono::Utc::now().to_rfc3339(), + }) + } + + pub fn verify_integrity(&self, output_dir: &Path) -> Result { + for record in &self.artifacts { + let full_path = output_dir.join(&record.relative_path); + if !full_path.exists() { + return Ok(false); + } + let actual_sha = Self::compute_file_sha256(&full_path)?; + if actual_sha != record.sha256 { + return Ok(false); + } + } + Ok(true) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_candidate_manifest_creation() { + let manifest = CandidateManifest::new( + "cand-001", + "6ac8ae95cf13fd618c855ca1c0c67e6f8455fc5d", + "hyp-001", + "TARGET", + vec!["src/observe.rs".to_string()], + "latency_p95_us", + -12.5, + ); + assert_eq!(manifest.candidate_id, "cand-001"); + assert_eq!(manifest.code_tier, "TARGET"); + assert_eq!(manifest.expected_delta_pct, -12.5); + } + + #[test] + fn test_artifact_manifest_generation_and_integrity() { + let tmp = tempfile::tempdir().unwrap(); + let file1 = tmp.path().join("libsample.so"); + let file2 = tmp.path().join("config.json"); + + fs::write(&file1, "mock shared library binary content").unwrap(); + fs::write(&file2, "{\"key\":\"value\"}").unwrap(); + + let source_digest = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + let builder_img = "docker.io/library/spark-rsi-builder@sha256:abcd1234"; + + let manifest = ArtifactManifest::generate_from_output_dir( + "cand-test", + builder_img, + source_digest, + tmp.path(), + ) + .unwrap(); + + assert_eq!(manifest.artifacts.len(), 2); + assert!(!manifest.manifest_digest.is_empty()); + assert!(manifest.verify_integrity(tmp.path()).unwrap()); + + // Tamper with file + fs::write(&file1, "tampered content").unwrap(); + assert!(!manifest.verify_integrity(tmp.path()).unwrap()); + } +} diff --git a/src/isolation/mod.rs b/src/isolation/mod.rs new file mode 100644 index 0000000..f954e1f --- /dev/null +++ b/src/isolation/mod.rs @@ -0,0 +1,9 @@ +pub mod container; +pub mod manifest; +pub mod rollback; +pub mod root_of_trust; + +pub use container::{BuildJail, GpuEvaluationJail, SandboxLimits}; +pub use manifest::{ArtifactManifest, ArtifactRecord, CandidateManifest}; +pub use rollback::RollbackCheckpoint; +pub use root_of_trust::RootOfTrust; diff --git a/src/isolation/rollback.rs b/src/isolation/rollback.rs new file mode 100644 index 0000000..f26fe00 --- /dev/null +++ b/src/isolation/rollback.rs @@ -0,0 +1,100 @@ +use std::path::{Path, PathBuf}; +use std::process::Command; + +#[derive(Debug, Clone)] +pub struct RollbackCheckpoint { + pub repo_root: PathBuf, + pub cycle_id: String, + pub base_commit_sha: String, + pub worktree_dir: PathBuf, + pub branch_name: String, + pub ref_name: String, +} + +impl RollbackCheckpoint { + pub fn create(repo_root: &Path, cycle_id: &str) -> Result { + let head_out = Command::new("git") + .arg("-C") + .arg(repo_root) + .args(["rev-parse", "HEAD"]) + .output() + .map_err(|e| format!("Failed to resolve HEAD in {:?}: {}", repo_root, e))?; + + if !head_out.status.success() { + return Err(format!( + "git rev-parse HEAD failed: {}", + String::from_utf8_lossy(&head_out.stderr) + )); + } + + let base_commit_sha = String::from_utf8_lossy(&head_out.stdout).trim().to_string(); + let worktree_dir = PathBuf::from(format!("/tmp/spark-rsi-worktree-{}", cycle_id)); + let branch_name = format!("rsi/candidate-{}", cycle_id); + let ref_name = format!("refs/rsi/checkpoints/{}", cycle_id); + + if worktree_dir.exists() { + let _ = Command::new("git") + .arg("-C") + .arg(repo_root) + .args(["worktree", "remove", "--force", worktree_dir.to_str().unwrap()]) + .output(); + let _ = std::fs::remove_dir_all(&worktree_dir); + } + + let wt_out = Command::new("git") + .arg("-C") + .arg(repo_root) + .args([ + "worktree", + "add", + "-b", + &branch_name, + worktree_dir.to_str().unwrap(), + "HEAD", + ]) + .output() + .map_err(|e| format!("Failed to spawn git worktree add: {}", e))?; + + if !wt_out.status.success() { + return Err(format!( + "Failed to create git worktree: {}", + String::from_utf8_lossy(&wt_out.stderr) + )); + } + + let _ = Command::new("git") + .arg("-C") + .arg(repo_root) + .args(["update-ref", &ref_name, &base_commit_sha]) + .output(); + + Ok(Self { + repo_root: repo_root.to_path_buf(), + cycle_id: cycle_id.to_string(), + base_commit_sha, + worktree_dir, + branch_name, + ref_name, + }) + } + + pub fn teardown(&self) -> Result<(), String> { + let _ = Command::new("git") + .arg("-C") + .arg(&self.repo_root) + .args(["worktree", "remove", "--force", self.worktree_dir.to_str().unwrap()]) + .output(); + + let _ = Command::new("git") + .arg("-C") + .arg(&self.repo_root) + .args(["branch", "-D", &self.branch_name]) + .output(); + + if self.worktree_dir.exists() { + let _ = std::fs::remove_dir_all(&self.worktree_dir); + } + + Ok(()) + } +} diff --git a/src/isolation/root_of_trust.rs b/src/isolation/root_of_trust.rs new file mode 100644 index 0000000..82795d1 --- /dev/null +++ b/src/isolation/root_of_trust.rs @@ -0,0 +1,112 @@ +use std::path::Path; + +pub struct RootOfTrust; + +impl RootOfTrust { + pub const PROTECTED_PATHS: &'static [&'static str] = &[ + "Cargo.toml", + "Cargo.lock", + ".cargo", + "src/isolation", + "src/evaluator", + "src/ledger", + "src/governance", + "src/supervisor", + "src/daemon.rs", + "tests", + ".github", + "CONSTITUTION.md", + "LICENSE", + "agent.json", + ".rsi/ledger.db", + ".rsi/active", + ".rsi/holdouts", + ]; + + pub fn normalize_path(path: &str) -> String { + let p = path.trim_start_matches("./").trim_start_matches('/'); + p.to_string() + } + + pub fn is_protected_path(path: &str) -> bool { + let normalized = Self::normalize_path(path); + let path_obj = Path::new(&normalized); + + for protected in Self::PROTECTED_PATHS { + let prot_obj = Path::new(protected); + if path_obj == prot_obj || path_obj.starts_with(prot_obj) { + return true; + } + } + false + } + + pub fn assert_patch_permitted(target_file: &str, tier: u8) -> Result<(), String> { + let normalized = Self::normalize_path(target_file); + if Self::is_protected_path(&normalized) && tier < 2 { + return Err(format!( + "SECURITY VIOLATION: Target path '{}' is a protected root-of-trust file. Required tier: >= 2, candidate tier: {}", + normalized, tier + )); + } + Ok(()) + } + + pub fn validate_declared_files(declared_files: &[String], tier: u8) -> Result<(), Vec> { + let mut violations = Vec::new(); + for file in declared_files { + if let Err(msg) = Self::assert_patch_permitted(file, tier) { + violations.push(msg); + } + } + + if violations.is_empty() { + Ok(()) + } else { + Err(violations) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_protected_paths_detected() { + assert!(RootOfTrust::is_protected_path("Cargo.toml")); + assert!(RootOfTrust::is_protected_path("./Cargo.toml")); + assert!(RootOfTrust::is_protected_path("src/isolation/container.rs")); + assert!(RootOfTrust::is_protected_path("src/evaluator/stats.rs")); + assert!(RootOfTrust::is_protected_path(".github/workflows/ci.yml")); + assert!(RootOfTrust::is_protected_path("CONSTITUTION.md")); + assert!(RootOfTrust::is_protected_path(".rsi/ledger.db")); + } + + #[test] + fn test_unprotected_target_paths_allowed() { + assert!(!RootOfTrust::is_protected_path("src/observe.rs")); + assert!(!RootOfTrust::is_protected_path("src/propose.rs")); + assert!(!RootOfTrust::is_protected_path("src/models.rs")); + assert!(!RootOfTrust::is_protected_path("docs/PHILOSOPHY.md")); + assert!(!RootOfTrust::is_protected_path("README.md")); + } + + #[test] + fn test_tier_enforcement() { + assert!(RootOfTrust::assert_patch_permitted("src/observe.rs", 0).is_ok()); + assert!(RootOfTrust::assert_patch_permitted("src/isolation/root_of_trust.rs", 0).is_err()); + assert!(RootOfTrust::assert_patch_permitted("src/isolation/root_of_trust.rs", 1).is_err()); + assert!(RootOfTrust::assert_patch_permitted("src/isolation/root_of_trust.rs", 2).is_ok()); + } + + #[test] + fn test_validate_declared_files_batch() { + let valid = vec!["src/observe.rs".to_string(), "README.md".to_string()]; + assert!(RootOfTrust::validate_declared_files(&valid, 0).is_ok()); + + let invalid = vec!["src/observe.rs".to_string(), "Cargo.toml".to_string()]; + let err = RootOfTrust::validate_declared_files(&invalid, 0).unwrap_err(); + assert_eq!(err.len(), 1); + } +} diff --git a/src/lib.rs b/src/lib.rs index c17df0b..798a5ce 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,19 +1,26 @@ pub mod balance; pub mod config; pub mod daemon; +pub mod isolation; pub mod models; pub mod observe; pub mod propose; pub mod ratify; +pub mod supervisor; pub mod verifier; pub use balance::BalanceKernel; pub use config::{EngineConfig, OperatorProfile, SovereignConfig}; pub use daemon::RsiEngine; +pub use isolation::{ + ArtifactManifest, ArtifactRecord, BuildJail, CandidateManifest, GpuEvaluationJail, + RollbackCheckpoint, RootOfTrust, SandboxLimits, +}; pub use models::*; pub use observe::observe_codebase; pub use propose::ProposalGenerator; pub use ratify::Ratifier; +pub use supervisor::{GenerationInfo, GenerationState, HostSupervisor}; pub use verifier::InvariantVerifier; pub fn version() -> &'static str { diff --git a/src/supervisor/mod.rs b/src/supervisor/mod.rs new file mode 100644 index 0000000..4db0c73 --- /dev/null +++ b/src/supervisor/mod.rs @@ -0,0 +1,190 @@ +use serde::{Deserialize, Serialize}; +use std::fs; +use std::path::{Path, PathBuf}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum GenerationState { + Staged, + Starting, + Ready, + CanaryActive, + Durable, + Reverting, + Reverted, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct GenerationInfo { + pub generation_id: String, + pub installed_path: PathBuf, + pub manifest_digest: String, + pub state: GenerationState, + pub pid: Option, + pub canary_transactions: u64, + pub staged_timestamp: String, +} + +pub struct HostSupervisor { + pub active_symlink: PathBuf, + pub generations_root: PathBuf, + pub memory_limit_mb: u64, +} + +impl HostSupervisor { + pub fn new(rsi_root: &Path, memory_limit_mb: u64) -> Self { + Self { + active_symlink: rsi_root.join("active"), + generations_root: rsi_root.join("generations"), + memory_limit_mb, + } + } + + pub fn stage_generation( + &self, + generation_id: &str, + source_dir: &Path, + manifest_digest: &str, + ) -> Result { + let dest = self.generations_root.join(generation_id); + if dest.exists() { + fs::remove_dir_all(&dest).map_err(|e| e.to_string())?; + } + fs::create_dir_all(&dest).map_err(|e| e.to_string())?; + + // Copy artifacts into immutable generation directory + copy_dir_all(source_dir, &dest)?; + + Ok(GenerationInfo { + generation_id: generation_id.to_string(), + installed_path: dest, + manifest_digest: manifest_digest.to_string(), + state: GenerationState::Staged, + pid: None, + canary_transactions: 0, + staged_timestamp: chrono::Utc::now().to_rfc3339(), + }) + } + + pub fn atomic_symlink_swap(&self, generation_id: &str) -> Result<(), String> { + let target_dir = self.generations_root.join(generation_id); + if !target_dir.exists() { + return Err(format!("Target generation directory does not exist: {:?}", target_dir)); + } + + let parent = self + .active_symlink + .parent() + .ok_or_else(|| "No parent dir for active symlink".to_string())?; + fs::create_dir_all(parent).map_err(|e| e.to_string())?; + + let tmp_link = parent.join(format!(".active.tmp.{}", uuid::Uuid::new_v4().simple())); + if tmp_link.exists() { + let _ = fs::remove_file(&tmp_link); + } + + #[cfg(unix)] + std::os::unix::fs::symlink(&target_dir, &tmp_link) + .map_err(|e| format!("Failed to create temporary symlink: {}", e))?; + + fs::rename(&tmp_link, &self.active_symlink) + .map_err(|e| format!("Failed atomic symlink swap: {}", e))?; + + Ok(()) + } + + pub fn check_unified_memory_mb(pid: u32) -> Result { + let statm_path = format!("/proc/{}/statm", pid); + let content = fs::read_to_string(&statm_path) + .map_err(|e| format!("Failed to read statm for pid {}: {}", pid, e))?; + + let parts: Vec<&str> = content.split_whitespace().collect(); + if parts.len() < 2 { + return Err("Malformed statm output".to_string()); + } + + let resident_pages: u64 = parts[1] + .parse() + .map_err(|e| format!("Failed to parse resident pages: {}", e))?; + + let page_size_kb = 4; // standard 4KB pages on Linux ARM64 + let rss_mb = (resident_pages * page_size_kb) / 1024; + Ok(rss_mb) + } + + pub fn is_memory_within_budget(&self, pid: u32) -> Result { + let current_mb = Self::check_unified_memory_mb(pid)?; + Ok(current_mb <= self.memory_limit_mb) + } +} + +fn copy_dir_all(src: &Path, dst: &Path) -> Result<(), String> { + if !dst.exists() { + fs::create_dir_all(dst).map_err(|e| e.to_string())?; + } + for entry in fs::read_dir(src).map_err(|e| e.to_string())?.flatten() { + let path = entry.path(); + let dest = dst.join(entry.file_name()); + if path.is_dir() { + copy_dir_all(&path, &dest)?; + } else { + fs::copy(&path, &dest).map_err(|e| e.to_string())?; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_stage_and_atomic_symlink_swap() { + let tmp = tempfile::tempdir().unwrap(); + let rsi_root = tmp.path().join(".rsi"); + let src = tmp.path().join("src_art"); + fs::create_dir_all(&src).unwrap(); + fs::write(src.join("bin"), "generation binary v1").unwrap(); + + let supervisor = HostSupervisor::new(&rsi_root, 49152); + let gen_info = supervisor + .stage_generation("gen-001", &src, "manifest-sha-001") + .unwrap(); + + assert_eq!(gen_info.state, GenerationState::Staged); + assert!(gen_info.installed_path.exists()); + + supervisor.atomic_symlink_swap("gen-001").unwrap(); + assert!(supervisor.active_symlink.exists()); + + let content = fs::read_to_string(supervisor.active_symlink.join("bin")).unwrap(); + assert_eq!(content, "generation binary v1"); + + // Stage and swap to gen-002 + let src2 = tmp.path().join("src_art2"); + fs::create_dir_all(&src2).unwrap(); + fs::write(src2.join("bin"), "generation binary v2").unwrap(); + + supervisor + .stage_generation("gen-002", &src2, "manifest-sha-002") + .unwrap(); + supervisor.atomic_symlink_swap("gen-002").unwrap(); + + let content2 = fs::read_to_string(supervisor.active_symlink.join("bin")).unwrap(); + assert_eq!(content2, "generation binary v2"); + + // Rollback swap to gen-001 + supervisor.atomic_symlink_swap("gen-001").unwrap(); + let content_rollback = fs::read_to_string(supervisor.active_symlink.join("bin")).unwrap(); + assert_eq!(content_rollback, "generation binary v1"); + } + + #[test] + fn test_memory_budget_check_own_pid() { + let pid = std::process::id(); + let tmp = tempfile::tempdir().unwrap(); + let supervisor = HostSupervisor::new(tmp.path(), 49152); + + let within_budget = supervisor.is_memory_within_budget(pid).unwrap(); + assert!(within_budget); + } +}