interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-cli / src / sandbox.rs

518 lines · 16480 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use colored::*;
17use serde_json::{json, Value};
18use std::fs;
19use std::path::{Path, PathBuf};
20use std::process::Command;
21
22pub fn get_sandbox_dir() -> PathBuf {
23 crate::platform::PlatformContext::detect()
24 .home_dir
25 .join("workspace/aien-sandbox")
26}
27
28pub fn get_repo_dir() -> PathBuf {
29 crate::platform::PlatformContext::detect()
30 .home_dir
31 .join("workspace/aien-sovereign-core")
32}
33
34fn cargo_cmd() -> Command {
35 let platform = crate::platform::PlatformContext::detect();
36 let user_cargo = platform.home_dir.join(".cargo/bin/cargo");
37 let cargo_bin = if user_cargo.exists() {
38 user_cargo.to_string_lossy().to_string()
39 } else {
40 "cargo".to_string()
41 };
42 let mut cmd = Command::new(cargo_bin);
43 let cargo_bin_dir = platform.home_dir.join(".cargo/bin");
44 if let Ok(path) = std::env::var("PATH") {
45 cmd.env("PATH", format!("{}:{}", cargo_bin_dir.display(), path));
46 } else {
47 cmd.env(
48 "PATH",
49 format!("{}:/usr/local/bin:/usr/bin:/bin", cargo_bin_dir.display()),
50 );
51 }
52 cmd
53}
54
55pub fn init_sandbox(branch_opt: Option<&str>) -> Result<Value, String> {
56 let sb_dir = get_sandbox_dir();
57 let rp_dir = get_repo_dir();
58 let sandbox_path = sb_dir.as_path();
59 let repo_path = rp_dir.as_path();
60
61 if !repo_path.exists() {
62 return Err(format!("Base repository not found at {}", rp_dir.display()));
63 }
64
65 let branch = branch_opt.unwrap_or("sandbox-auto");
66
67 if sandbox_path.exists() {
68 let _ = clean_sandbox();
69 }
70
71 let output = Command::new("git")
72 .args([
73 "worktree",
74 "add",
75 "-B",
76 branch,
77 sb_dir.to_str().unwrap_or(""),
78 "main",
79 ])
80 .current_dir(&rp_dir)
81 .output()
82 .map_err(|e| format!("Failed to create git worktree: {}", e))?;
83
84 if !output.status.success() {
85 let err = String::from_utf8_lossy(&output.stderr);
86 return Err(format!("git worktree add failed: {}", err));
87 }
88
89 let crumb_path = sandbox_path.join(".crumb");
90 if !crumb_path.exists() {
91 let above = sb_dir
92 .parent()
93 .map(|p| p.to_string_lossy().to_string())
94 .unwrap_or_default();
95 let crumb_content = format!(
96 r#"{{
97 "directory": "aien-sandbox",
98 "statement": "Isolated Git worktree sandbox for AIEN autonomous edits and testing.",
99 "above": "{}",
100 "below": []
101}}"#,
102 above
103 );
104 let _ = crate::crumbs::write_new_crumb(&crumb_path, &crumb_content);
105 }
106
107 Ok(json!({
108 "status": "ok",
109 "action": "init",
110 "sandbox_dir": sb_dir.to_string_lossy(),
111 "branch": branch,
112 "message": format!("Sandbox initialized cleanly at {} on branch {}", sb_dir.display(), branch)
113 }))
114}
115
116pub fn status_sandbox() -> Result<Value, String> {
117 let sb_dir = get_sandbox_dir();
118 let sandbox_path = sb_dir.as_path();
119 if !sandbox_path.exists() {
120 return Ok(json!({
121 "status": "not_initialized",
122 "sandbox_dir": sb_dir.to_string_lossy(),
123 "exists": false
124 }));
125 }
126
127 let status_out = Command::new("git")
128 .args(["status", "--porcelain"])
129 .current_dir(&sb_dir)
130 .output()
131 .map_err(|e| e.to_string())?;
132
133 let branch_out = Command::new("git")
134 .args(["branch", "--show-current"])
135 .current_dir(&sb_dir)
136 .output()
137 .map_err(|e| e.to_string())?;
138
139 let branch = String::from_utf8_lossy(&branch_out.stdout)
140 .trim()
141 .to_string();
142 let status_text = String::from_utf8_lossy(&status_out.stdout).to_string();
143 let modified_files: Vec<String> = status_text
144 .lines()
145 .map(|l| l.trim().to_string())
146 .filter(|l| !l.is_empty())
147 .collect();
148
149 Ok(json!({
150 "status": "ok",
151 "sandbox_dir": sb_dir.to_string_lossy(),
152 "branch": branch,
153 "is_clean": modified_files.is_empty(),
154 "modified_files": modified_files
155 }))
156}
157
158pub fn test_sandbox() -> Result<Value, String> {
159 let sb_dir = get_sandbox_dir();
160 let sandbox_path = sb_dir.as_path();
161 if !sandbox_path.exists() {
162 return Err(format!(
163 "Sandbox not found at {}. Run init first.",
164 sb_dir.display()
165 ));
166 }
167
168 let mut cmd = cargo_cmd();
169 cmd.args(["check", "--tests"]).current_dir(&sb_dir);
170 let output = cmd
171 .output()
172 .map_err(|e| format!("Failed to run cargo check: {}", e))?;
173
174 let stdout = String::from_utf8_lossy(&output.stdout).to_string();
175 let stderr = String::from_utf8_lossy(&output.stderr).to_string();
176 let success = output.status.success();
177
178 Ok(json!({
179 "status": if success { "passed" } else { "failed" },
180 "action": "check",
181 "stdout": stdout,
182 "stderr": stderr
183 }))
184}
185
186pub fn promote_sandbox(commit_msg: &str) -> Result<Value, String> {
187 let sb_dir = get_sandbox_dir();
188 let rp_dir = get_repo_dir();
189 let sandbox_path = sb_dir.as_path();
190 if !sandbox_path.exists() {
191 return Err(format!("Sandbox not found at {}", sb_dir.display()));
192 }
193
194 // 1. Stage and commit in sandbox
195 let _ = Command::new("git")
196 .args(["add", "-A"])
197 .current_dir(&sb_dir)
198 .output();
199
200 let commit_out = Command::new("git")
201 .args(["commit", "-m", commit_msg])
202 .current_dir(&sb_dir)
203 .output()
204 .map_err(|e| format!("Commit failed: {}", e))?;
205
206 if !commit_out.status.success() {
207 let err = String::from_utf8_lossy(&commit_out.stderr);
208 return Err(format!("git commit in sandbox failed: {}", err));
209 }
210
211 // 2. Fast-forward or merge into main repo
212 let branch_out = Command::new("git")
213 .args(["branch", "--show-current"])
214 .current_dir(&sb_dir)
215 .output()
216 .map_err(|e| e.to_string())?;
217 let branch = String::from_utf8_lossy(&branch_out.stdout)
218 .trim()
219 .to_string();
220
221 let merge_out = Command::new("git")
222 .args(["merge", &branch, "--ff-only"])
223 .current_dir(&rp_dir)
224 .output()
225 .map_err(|e| format!("Merge into base failed: {}", e))?;
226
227 let promoted_ok = merge_out.status.success();
228
229 // 3. Trigger release build and self-update if aien-cli was modified
230 let mut install_success = false;
231 if promoted_ok {
232 let mut build_cmd = cargo_cmd();
233 build_cmd
234 .args(["build", "--release", "-p", "aien-cli"])
235 .current_dir(&rp_dir);
236 let _ = build_cmd.output();
237
238 let release_bin = {
239 let ws_bin = format!("{}/target/release/aien-cli", rp_dir.display());
240 if Path::new(&ws_bin).exists() {
241 ws_bin
242 } else {
243 format!(
244 "{}/crates/aien-cli/target/release/aien-cli",
245 rp_dir.display()
246 )
247 }
248 };
249 let dest_path = crate::platform::PlatformContext::detect()
250 .home_dir
251 .join(".local/bin/aien");
252 let dest_bin = dest_path.to_str().unwrap_or("aien");
253 let install_status = Command::new("install")
254 .args(["-m", "755", &release_bin, dest_bin])
255 .status();
256 if let Ok(s) = install_status {
257 install_success = s.success();
258 }
259 }
260
261 Ok(json!({
262 "status": if promoted_ok { "promoted" } else { "merge_failed" },
263 "branch": branch,
264 "binary_updated": install_success,
265 "merge_output": String::from_utf8_lossy(&merge_out.stdout).to_string(),
266 "merge_error": String::from_utf8_lossy(&merge_out.stderr).to_string()
267 }))
268}
269
270pub fn clean_sandbox() -> Result<String, String> {
271 let sb_dir = get_sandbox_dir();
272 let rp_dir = get_repo_dir();
273 let sandbox_path = sb_dir.as_path();
274 if sandbox_path.exists() {
275 let _ = Command::new("git")
276 .args([
277 "worktree",
278 "remove",
279 "--force",
280 sb_dir.to_str().unwrap_or(""),
281 ])
282 .current_dir(&rp_dir)
283 .output();
284
285 if sandbox_path.exists() {
286 let _ = fs::remove_dir_all(sandbox_path);
287 }
288 }
289
290 let _ = Command::new("git")
291 .args(["worktree", "prune"])
292 .current_dir(&rp_dir)
293 .output();
294
295 Ok(format!(
296 "Sandbox at {} cleaned successfully",
297 sb_dir.display()
298 ))
299}
300
301pub fn format_sandbox_tui() -> String {
302 match status_sandbox() {
303 Ok(v) => {
304 let status = v.get("status").and_then(Value::as_str).unwrap_or("unknown");
305 if status == "not_initialized" {
306 format!(
307 " {} Sandbox: Not initialized (run /sandbox init)
308",
309 "○".yellow()
310 )
311 } else {
312 let branch = v.get("branch").and_then(Value::as_str).unwrap_or("none");
313 let is_clean = v.get("is_clean").and_then(Value::as_bool).unwrap_or(false);
314 let clean_str = if is_clean {
315 "Clean".green()
316 } else {
317 "Modified".yellow().bold()
318 };
319 format!(
320 " {} Sandbox: Active [branch: {}] • Status: {}
321",
322 "●".green(),
323 branch.cyan(),
324 clean_str
325 )
326 }
327 }
328 Err(e) => format!(
329 " {} Sandbox: Error ({})
330",
331 "✗".red(),
332 e
333 ),
334 }
335}
336
337pub fn sandbox_dispatch_tool(args: &Value) -> Value {
338 let action = args
339 .get("action")
340 .and_then(Value::as_str)
341 .unwrap_or("status");
342 match action {
343 "status" => match status_sandbox() {
344 Ok(v) => v,
345 Err(e) => json!({"status": "error", "error": e}),
346 },
347 "init" => {
348 let branch = args.get("branch").and_then(Value::as_str);
349 match init_sandbox(branch) {
350 Ok(v) => v,
351 Err(e) => json!({"status": "error", "error": e}),
352 }
353 }
354 "test" | "check" => match test_sandbox() {
355 Ok(v) => v,
356 Err(e) => json!({"status": "error", "error": e}),
357 },
358 "promote" => {
359 let msg = args
360 .get("message")
361 .and_then(Value::as_str)
362 .unwrap_or("Autonomous sandbox promotion");
363 match promote_sandbox(msg) {
364 Ok(v) => v,
365 Err(e) => json!({"status": "error", "error": e}),
366 }
367 }
368 "clean" => match clean_sandbox() {
369 Ok(msg) => json!({"status": "ok", "message": msg}),
370 Err(e) => json!({"status": "error", "error": e}),
371 },
372 other => json!({"status": "error", "error": format!("Unknown sandbox action '{}'", other)}),
373 }
374}
375
376pub fn browser_dispatch_tool(action: &str, prompt: Option<&str>) -> Value {
377 browser_dispatch_tool_at(action, prompt, None, None)
378}
379
380/// Browser mirror with an explicit Cockpit URL and output directory.
381/// `None` falls back to the Cockpit default (127.0.0.1:18095) and
382/// `~/basecamp/ui-tests`. The AIEN_COCKPIT_URL environment variable
383/// overrides the default URL.
384pub fn browser_dispatch_tool_at(
385 action: &str,
386 prompt: Option<&str>,
387 url: Option<&str>,
388 out_dir: Option<&std::path::Path>,
389) -> Value {
390 use aien_cli::browser_mirror as bm;
391 let env_url = std::env::var("AIEN_COCKPIT_URL").ok();
392 let url = url
393 .map(str::to_string)
394 .or(env_url)
395 .unwrap_or_else(|| bm::DEFAULT_URL.to_string());
396 let out = out_dir
397 .map(std::path::Path::to_path_buf)
398 .unwrap_or_else(bm::default_out_dir);
399 bm::dispatch(action, prompt, &url, &out)
400}
401
402pub fn handle_sandbox_command(parts: &[&str]) {
403 if parts.is_empty() || parts[0] == "status" {
404 match status_sandbox() {
405 Ok(val) => {
406 println!(
407 "
408{}",
409 "=== AIEN Sovereign Sandbox Status ===".cyan().bold()
410 );
411 println!("{}", serde_json::to_string_pretty(&val).unwrap_or_default());
412 }
413 Err(e) => println!("{}", format!("Error: {}", e).red()),
414 }
415 } else if parts[0] == "init" {
416 let branch = if parts.len() > 1 {
417 Some(parts[1])
418 } else {
419 None
420 };
421 match init_sandbox(branch) {
422 Ok(val) => {
423 println!(
424 "
425{}",
426 "=== AIEN Sandbox Initialized ===".green().bold()
427 );
428 println!("{}", serde_json::to_string_pretty(&val).unwrap_or_default());
429 }
430 Err(e) => println!("{}", format!("Error: {}", e).red()),
431 }
432 } else if parts[0] == "test" {
433 println!("{}", "Running test suite inside sandbox...".yellow());
434 match test_sandbox() {
435 Ok(val) => {
436 println!("{}", serde_json::to_string_pretty(&val).unwrap_or_default());
437 }
438 Err(e) => println!("{}", format!("Error: {}", e).red()),
439 }
440 } else if parts[0] == "promote" {
441 let msg = if parts.len() > 1 {
442 parts[1..].join(" ")
443 } else {
444 "Autonomous sandbox promotion".to_string()
445 };
446 match promote_sandbox(&msg) {
447 Ok(val) => {
448 println!(
449 "
450{}",
451 "=== Sandbox Promoted to Main ===".green().bold()
452 );
453 println!("{}", serde_json::to_string_pretty(&val).unwrap_or_default());
454 }
455 Err(e) => println!("{}", format!("Error: {}", e).red()),
456 }
457 } else if parts[0] == "clean" {
458 match clean_sandbox() {
459 Ok(msg) => println!("{}", msg.green()),
460 Err(e) => println!("{}", format!("Error: {}", e).red()),
461 }
462 } else {
463 println!("Usage: /sandbox [status | init [branch] | test | promote [commit msg] | clean]");
464 }
465}
466
467pub fn handle_browser_command(parts: &[&str]) {
468 let action = parts.first().copied().unwrap_or("test");
469 let rest = if parts.len() > 1 {
470 Some(parts[1..].join(" "))
471 } else {
472 None
473 };
474 let note = match action {
475 "mentor" => format!(
476 "Spawning browser mentor session with prompt: '{}'...",
477 rest.as_deref()
478 .unwrap_or("AIEN, report self-improvement status.")
479 ),
480 "screenshot" => "Spawning headless Chrome for a Cockpit screenshot...".to_string(),
481 "eval" => "Spawning headless Chrome to evaluate JavaScript on the Cockpit...".to_string(),
482 _ => "Spawning headless Chrome and running mirror self-test on Cockpit...".to_string(),
483 };
484 println!("{}", note.yellow());
485 let res = browser_dispatch_tool(action, rest.as_deref());
486 println!("{}", serde_json::to_string_pretty(&res).unwrap_or_default());
487}
488
489#[cfg(test)]
490mod tests {
491 use super::*;
492
493 #[test]
494 fn test_sandbox_constants() {
495 let platform = crate::platform::PlatformContext::detect();
496 assert_eq!(
497 get_sandbox_dir(),
498 platform.home_dir.join("workspace/aien-sandbox")
499 );
500 assert_eq!(
501 get_repo_dir(),
502 platform.home_dir.join("workspace/aien-sovereign-core")
503 );
504 }
505
506 #[test]
507 fn test_sandbox_dispatch_unknown() {
508 let args = json!({"action": "invalid_action"});
509 let res = sandbox_dispatch_tool(&args);
510 assert_eq!(res.get("status").unwrap().as_str().unwrap(), "error");
511 }
512
513 #[test]
514 fn test_sandbox_status_serialization() {
515 let res = status_sandbox();
516 assert!(res.is_ok());
517 }
518}