Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core/blob/main/crates/aien-cli/src/sandbox.rs # aien-sovereign-core Autonomous sovereign intelligence engine and runtime core for NVIDIA DGX Spark Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core / crates / aien-cli / src / sandbox.rs` 386 lines ยท 13195 bytes Raw Blame History 1 use std::path::Path; 2 use std::process::Command; 3 use std::fs; 4 use colored::*; 5 use serde_json::{json, Value}; 6 7 pub const SANDBOX_DIR: &str = "/home/drakestapleton/workspace/aien-sandbox"; 8 pub const REPO_DIR: &str = "/home/drakestapleton/workspace/aien-sovereign-core"; 9 10 fn cargo_cmd() -> Command { 11 let cargo_bin = if Path::new("/home/drakestapleton/.cargo/bin/cargo").exists() { 12 "/home/drakestapleton/.cargo/bin/cargo" 13 } else { 14 "cargo" 15 }; 16 let mut cmd = Command::new(cargo_bin); 17 if let Ok(path) = std::env::var("PATH") { 18 cmd.env("PATH", format!("/home/drakestapleton/.cargo/bin:{}", path)); 19 } else { 20 cmd.env("PATH", "/home/drakestapleton/.cargo/bin:/usr/local/bin:/usr/bin:/bin"); 21 } 22 cmd 23 } 24 25 pub fn init_sandbox(branch_opt: Option<&str>) -> Result { 26 let sandbox_path = Path::new(SANDBOX_DIR); 27 let repo_path = Path::new(REPO_DIR); 28 29 if !repo_path.exists() { 30 return Err(format!("Base repository not found at {}", REPO_DIR)); 31 } 32 33 let branch = branch_opt.unwrap_or("sandbox-auto"); 34 35 if sandbox_path.exists() { 36 let _ = clean_sandbox(); 37 } 38 39 let output = Command::new("git") 40 .args(["worktree", "add", "-B", branch, SANDBOX_DIR, "main"]) 41 .current_dir(REPO_DIR) 42 .output() 43 .map_err(|e| format!("Failed to create git worktree: {}", e))?; 44 45 if !output.status.success() { 46 let err = String::from_utf8_lossy(&output.stderr); 47 return Err(format!("git worktree add failed: {}", err)); 48 } 49 50 let crumb_path = sandbox_path.join(".crumb"); 51 if !crumb_path.exists() { 52 let crumb_content = r#"{ 53 "directory": "aien-sandbox", 54 "statement": "Isolated Git worktree sandbox for AIEN autonomous edits and testing.", 55 "above": "/home/drakestapleton/workspace", 56 "below": [] 57 }"#; 58 let _ = fs::write(&crumb_path, crumb_content); 59 } 60 61 Ok(json!({ 62 "status": "ok", 63 "action": "init", 64 "sandbox_dir": SANDBOX_DIR, 65 "branch": branch, 66 "message": format!("Sandbox initialized cleanly at {} on branch {}", SANDBOX_DIR, branch) 67 })) 68 } 69 70 pub fn status_sandbox() -> Result { 71 let sandbox_path = Path::new(SANDBOX_DIR); 72 if !sandbox_path.exists() { 73 return Ok(json!({ 74 "status": "not_initialized", 75 "sandbox_dir": SANDBOX_DIR, 76 "exists": false 77 })); 78 } 79 80 let status_out = Command::new("git") 81 .args(["status", "--porcelain"]) 82 .current_dir(SANDBOX_DIR) 83 .output() 84 .map_err(|e| e.to_string())?; 85 86 let branch_out = Command::new("git") 87 .args(["branch", "--show-current"]) 88 .current_dir(SANDBOX_DIR) 89 .output() 90 .map_err(|e| e.to_string())?; 91 92 let branch = String::from_utf8_lossy(&branch_out.stdout).trim().to_string(); 93 let status_text = String::from_utf8_lossy(&status_out.stdout).to_string(); 94 let modified_files: Vec = status_text 95 .lines() 96 .map(|l| l.trim().to_string()) 97 .filter(|l| !l.is_empty()) 98 .collect(); 99 100 Ok(json!({ 101 "status": "ok", 102 "sandbox_dir": SANDBOX_DIR, 103 "branch": branch, 104 "is_clean": modified_files.is_empty(), 105 "modified_files": modified_files 106 })) 107 } 108 109 pub fn test_sandbox() -> Result { 110 let sandbox_path = Path::new(SANDBOX_DIR); 111 if !sandbox_path.exists() { 112 return Err(format!("Sandbox not found at {}. Run init first.", SANDBOX_DIR)); 113 } 114 115 let mut cmd = cargo_cmd(); 116 cmd.args(["check", "--tests"]).current_dir(SANDBOX_DIR); 117 118 let output = cmd 119 .output() 120 .map_err(|e| format!("Failed to run cargo check in sandbox: {}", e))?; 121 122 let stdout = String::from_utf8_lossy(&output.stdout).to_string(); 123 let stderr = String::from_utf8_lossy(&output.stderr).to_string(); 124 let success = output.status.success(); 125 126 Ok(json!({ 127 "status": if success { "passed" } else { "failed" }, 128 "exit_code": output.status.code().unwrap_or(-1), 129 "stdout": stdout, 130 "stderr": stderr 131 })) 132 } 133 134 pub fn promote_sandbox(commit_msg_opt: Option<&str>) -> Result { 135 let sandbox_path = Path::new(SANDBOX_DIR); 136 if !sandbox_path.exists() { 137 return Err(format!("Sandbox not found at {}", SANDBOX_DIR)); 138 } 139 140 let branch_out = Command::new("git") 141 .args(["branch", "--show-current"]) 142 .current_dir(SANDBOX_DIR) 143 .output() 144 .map_err(|e| e.to_string())?; 145 let branch = String::from_utf8_lossy(&branch_out.stdout).trim().to_string(); 146 147 if branch.is_empty() || branch == "main" { 148 return Err("Cannot promote directly from main or empty branch".to_string()); 149 } 150 151 let _ = Command::new("git") 152 .args(["add", "-A"]) 153 .current_dir(SANDBOX_DIR) 154 .status(); 155 156 let msg = commit_msg_opt.unwrap_or("chore(sandbox): autonomous verified edit by AIEN"); 157 let _ = Command::new("git") 158 .args([ 159 "commit", 160 "-m", msg, 161 "--author=AIEN " 162 ]) 163 .current_dir(SANDBOX_DIR) 164 .status(); 165 166 let merge_out = Command::new("git") 167 .args(["merge", &branch, "--no-ff", "-m", &format!("merge(sandbox): integrate {}", branch)]) 168 .current_dir(REPO_DIR) 169 .output() 170 .map_err(|e| format!("Merge failed: {}", e))?; 171 172 if !merge_out.status.success() { 173 let err = String::from_utf8_lossy(&merge_out.stderr); 174 return Err(format!("Failed to merge {} into main: {}", branch, err)); 175 } 176 177 let mut build_cmd = cargo_cmd(); 178 build_cmd.args(["build", "--release", "-p", "aien-cli"]).current_dir(REPO_DIR); 179 180 let build_out = build_cmd 181 .output() 182 .map_err(|e| format!("cargo build failed: {}", e))?; 183 184 let mut install_success = false; 185 if build_out.status.success() { 186 let ws_bin = format!("{}/target/release/aien-cli", REPO_DIR); 187 let release_bin = if Path::new(&ws_bin).exists() { 188 ws_bin 189 } else { 190 format!("{}/crates/aien-cli/target/release/aien-cli", REPO_DIR) 191 }; 192 let dest_bin = "/home/drakestapleton/.local/bin/aien"; 193 let install_status = Command::new("install") 194 .args(["-m", "755", &release_bin, dest_bin]) 195 .status(); 196 if let Ok(s) = install_status { 197 install_success = s.success(); 198 } 199 } 200 201 let _ = clean_sandbox(); 202 203 Ok(json!({ 204 "status": "promoted", 205 "branch": branch, 206 "merge_success": true, 207 "binary_installed": install_success, 208 "message": format!("Successfully promoted {} into main and updated ~/.local/bin/aien", branch) 209 })) 210 } 211 212 pub fn clean_sandbox() -> Result { 213 let sandbox_path = Path::new(SANDBOX_DIR); 214 if sandbox_path.exists() { 215 let _ = Command::new("git") 216 .args(["worktree", "remove", "--force", SANDBOX_DIR]) 217 .current_dir(REPO_DIR) 218 .status(); 219 220 if sandbox_path.exists() { 221 let _ = fs::remove_dir_all(sandbox_path); 222 } 223 } 224 let _ = Command::new("git") 225 .args(["worktree", "prune"]) 226 .current_dir(REPO_DIR) 227 .status(); 228 229 Ok(format!("Sandbox at {} cleaned successfully", SANDBOX_DIR)) 230 } 231 232 pub fn sandbox_dispatch_tool(args: &Value) -> Value { 233 let action = args.get("action").and_then(Value::as_str).unwrap_or("status"); 234 match action { 235 "init" => { 236 let branch = args.get("branch").and_then(Value::as_str); 237 match init_sandbox(branch) { 238 Ok(v) => v, 239 Err(e) => json!({"status": "error", "error": e}), 240 } 241 } 242 "status" => match status_sandbox() { 243 Ok(v) => v, 244 Err(e) => json!({"status": "error", "error": e}), 245 }, 246 "test" => match test_sandbox() { 247 Ok(v) => v, 248 Err(e) => json!({"status": "error", "error": e}), 249 }, 250 "promote" => { 251 let msg = args.get("message").and_then(Value::as_str); 252 match promote_sandbox(msg) { 253 Ok(v) => v, 254 Err(e) => json!({"status": "error", "error": e}), 255 } 256 } 257 "clean" => match clean_sandbox() { 258 Ok(msg) => json!({"status": "ok", "message": msg}), 259 Err(e) => json!({"status": "error", "error": e}), 260 }, 261 _ => json!({"status": "error", "error": format!("Unknown sandbox action: {}", action)}), 262 } 263 } 264 265 pub fn handle_sandbox_command(parts: &[&str]) { 266 if parts.is_empty() || parts[0] == "status" { 267 match status_sandbox() { 268 Ok(val) => { 269 println!("\n{}", "=== AIEN Sovereign Sandbox Status ===".cyan().bold()); 270 println!("{}", serde_json::to_string_pretty(&val).unwrap_or_default()); 271 } 272 Err(e) => println!("{}", format!("Error: {}", e).red()), 273 } 274 } else if parts[0] == "init" { 275 let branch = if parts.len() > 1 { Some(parts[1]) } else { None }; 276 match init_sandbox(branch) { 277 Ok(val) => { 278 println!("\n{}", "=== AIEN Sandbox Initialized ===".green().bold()); 279 println!("{}", serde_json::to_string_pretty(&val).unwrap_or_default()); 280 } 281 Err(e) => println!("{}", format!("Error: {}", e).red()), 282 } 283 } else if parts[0] == "test" { 284 println!("{}", "Running test suite inside sandbox...".yellow()); 285 match test_sandbox() { 286 Ok(val) => { 287 println!("{}", serde_json::to_string_pretty(&val).unwrap_or_default()); 288 } 289 Err(e) => println!("{}", format!("Error: {}", e).red()), 290 } 291 } else if parts[0] == "promote" { 292 let msg = if parts.len() > 1 { Some(parts[1..].join(" ")) } else { None }; 293 match promote_sandbox(msg.as_deref()) { 294 Ok(val) => { 295 println!("\n{}", "=== Sandbox Promoted to Main ===".green().bold()); 296 println!("{}", serde_json::to_string_pretty(&val).unwrap_or_default()); 297 } 298 Err(e) => println!("{}", format!("Error: {}", e).red()), 299 } 300 } else if parts[0] == "clean" { 301 match clean_sandbox() { 302 Ok(msg) => println!("{}", msg.green()), 303 Err(e) => println!("{}", format!("Error: {}", e).red()), 304 } 305 } else { 306 println!("{}", "Usage: /sandbox ".yellow()); 307 } 308 } 309 310 pub fn browser_dispatch_tool(action: &str, prompt: Option<&str>) -> Value { 311 let py = if Path::new("/home/drakestapleton/max-env/bin/python").exists() { 312 "/home/drakestapleton/max-env/bin/python" 313 } else { 314 "/home/drakestapleton/.skillopt-venv/bin/python" 315 }; 316 let script = "/home/drakestapleton/basecamp/scripts/browser_mirror_test.py"; 317 318 let mut cmd = Command::new(py); 319 cmd.arg(script); 320 321 match action { 322 "mentor" => { 323 cmd.arg("--mentor"); 324 cmd.arg(prompt.unwrap_or("AIEN, verify your sovereign self-improvement status.")); 325 } 326 _ => { 327 cmd.arg("--test"); 328 } 329 } 330 331 match cmd.output() { 332 Ok(out) => { 333 let stdout = String::from_utf8_lossy(&out.stdout).to_string(); 334 if let Ok(parsed) = serde_json::from_str::(&stdout) { 335 parsed 336 } else { 337 json!({ 338 "status": if out.status.success() { "ok" } else { "failed" }, 339 "raw_output": stdout, 340 "stderr": String::from_utf8_lossy(&out.stderr).to_string() 341 }) 342 } 343 } 344 Err(e) => json!({"status": "error", "error": e.to_string()}), 345 } 346 } 347 348 pub fn handle_browser_command(parts: &[&str]) { 349 if !parts.is_empty() && parts[0] == "mentor" { 350 let prompt = if parts.len() > 1 { parts[1..].join(" ") } else { "AIEN, report self-improvement status.".to_string() }; 351 println!("{}", format!("Spawning browser mentor session with prompt: '{}'...", prompt).yellow()); 352 let res = browser_dispatch_tool("mentor", Some(&prompt)); 353 println!("{}", serde_json::to_string_pretty(&res).unwrap_or_default()); 354 } else { 355 println!("{}", "Spawning headless Chrome and running mirror self-test on Cockpit...".yellow()); 356 let res = browser_dispatch_tool("test", None); 357 println!("{}", serde_json::to_string_pretty(&res).unwrap_or_default()); 358 } 359 } 360 361 362 #[cfg(test)] 363 mod tests { 364 use super::*; 365 366 #[test] 367 fn test_sandbox_constants() { 368 assert_eq!(SANDBOX_DIR, "/home/drakestapleton/workspace/aien-sandbox"); 369 assert_eq!(REPO_DIR, "/home/drakestapleton/workspace/aien-sovereign-core"); 370 } 371 372 #[test] 373 fn test_sandbox_dispatch_unknown() { 374 let args = json!({"action": "invalid_action"}); 375 let res = sandbox_dispatch_tool(&args); 376 assert_eq!(res["status"], "error"); 377 } 378 379 #[test] 380 fn test_sandbox_status_serialization() { 381 let res = status_sandbox(); 382 assert!(res.is_ok()); 383 let val = res.unwrap(); 384 assert!(val.get("status").is_some()); 385 } 386 }