interplane.Get Omega
Read in your language

aegis-runtime-mv

Native Rust agent runtime: Axum WebSocket/SSE/REST gateway, heartbeat scheduler, dependency-aware task workflow, SQLite storage. Attachment of AienOS. Pre-alpha.

Brought by drakestapleton

GitHub aien-dev/aegis-runtime-mv#22 (code only)

closed derived 6a332c815f73cf26 #22

Imported from GitHub aien-dev/aegis-runtime-mv#22 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base c52140ded2dfbfcc3495a142d35ade6ae7ee77d6 · Head 368aa5503d3abb3b414f8f0dc405993fdf0f406d

Apply it

git checkout -b patch-6a332c815f73cf26 c52140ded2dfbfcc3495a142d35ade6ae7ee77d6
curl -fsSL https://interplane.io/drakestapleton/aegis-runtime-mv/patches/6a332c815f73cf26.patch | git am

Raw patch (mbox) · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/aegis-runtime-mv
22
368aa5503d3abb3b414f8f0dc405993fdf0f406d
{"kind":"github-import","owner":"aien-dev","repo":"aegis-runtime-mv","number":22,"url":"https://github.com/aien-dev/aegis-runtime-mv/pull/22","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:39:34Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/src/gateway.rs b/src/gateway.rs
index df7908e..16a7a3b 100644
--- a/src/gateway.rs
+++ b/src/gateway.rs
@@ -384,30 +384,23 @@ pub struct ShellResponse {
 }
 
 pub async fn shell_handler(
+    State(state): State<GatewayState>,
     Json(payload): Json<ShellRequest>,
 ) -> Result<impl IntoResponse, (StatusCode, String)> {
-    let output = Command::new("sh")
-        .arg("-c")
-        .arg(&payload.command)
-        .output()
-        .await
-        .map_err(|e| {
-            (
-                StatusCode::INTERNAL_SERVER_ERROR,
-                format!("Failed to execute command: {}", e),
-            )
-        })?;
-
-    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
-    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
-    let exit_code = output.status.code().unwrap_or(-1);
-
-    Ok(Json(ShellResponse {
-        stdout,
-        stderr,
-        exit_code,
-        success: output.status.success(),
-    }))
+    match state.skills.workspace().execute_shell(&payload.command, None, 15) {
+        Ok(stdout) => Ok(Json(ShellResponse {
+            stdout,
+            stderr: String::new(),
+            exit_code: 0,
+            success: true,
+        })),
+        Err(e) => Ok(Json(ShellResponse {
+            stdout: String::new(),
+            stderr: e.to_string(),
+            exit_code: 1,
+            success: false,
+        })),
+    }
 }
 
 // Task endpoints
diff --git a/src/heartbeat.rs b/src/heartbeat.rs
index f7b46e7..332b202 100644
--- a/src/heartbeat.rs
+++ b/src/heartbeat.rs
@@ -9,6 +9,7 @@ use tracing::info;
 
 use crate::inference::InferenceEngine;
 use crate::persistence::Database;
+use crate::security::WorkspaceCapability;
 
 #[derive(Serialize, Deserialize, Clone, Debug)]
 pub struct PulseReceipt {
@@ -25,6 +26,7 @@ pub struct HeartbeatEngine {
     tick_counter: AtomicU64,
     db: Arc<Database>,
     inference: Option<Arc<dyn InferenceEngine>>,
+    workspace: Arc<WorkspaceCapability>,
     is_running: Mutex<bool>,
     tx_pulse: broadcast::Sender<PulseReceipt>,
 }
@@ -37,6 +39,7 @@ impl HeartbeatEngine {
             tick_counter: AtomicU64::new(0),
             db,
             inference: None,
+            workspace: Arc::new(WorkspaceCapability::detect()),
             is_running: Mutex::new(false),
             tx_pulse: tx,
         }
@@ -53,6 +56,7 @@ impl HeartbeatEngine {
             tick_counter: AtomicU64::new(0),
             db,
             inference: Some(inference),
+            workspace: Arc::new(WorkspaceCapability::detect()),
             is_running: Mutex::new(false),
             tx_pulse: tx,
         }
@@ -66,29 +70,42 @@ impl HeartbeatEngine {
         self.tick_counter.load(Ordering::Relaxed)
     }
 
+    pub fn with_workspace(
+        interval_secs: u64,
+        db: Arc<Database>,
+        workspace: WorkspaceCapability,
+    ) -> Self {
+        let (tx, _) = broadcast::channel(128);
+        Self {
+            interval_secs,
+            tick_counter: AtomicU64::new(0),
+            db,
+            inference: None,
+            workspace: Arc::new(workspace),
+            is_running: Mutex::new(false),
+            tx_pulse: tx,
+        }
+    }
+
     pub fn subscribe(&self) -> broadcast::Receiver<PulseReceipt> {
         self.tx_pulse.subscribe()
     }
 
     pub async fn pulse_once(&self) -> PulseReceipt {
-        let tick = self.tick_counter.fetch_add(1, Ordering::Relaxed) + 1;
+        let tick = self.tick_counter.fetch_add(1, Ordering::SeqCst) + 1;
         let now = Utc::now().to_rfc3339();
 
-        let pending = self.db.list_pending_tasks().unwrap_or_default();
-        let tasks_count = pending.len();
+        let pending_tasks = self.db.list_pending_tasks().unwrap_or_default();
+        let tasks_count = pending_tasks.len();
         let mut actions = 0;
 
-        for task in pending {
+        for task in pending_tasks {
             match task.task_type.as_str() {
                 "max_health" => {
                     let is_healthy = if let Some(ref inf) = self.inference {
                         inf.check_health().await
                     } else {
-                        let client = reqwest::Client::builder()
-                            .timeout(Duration::from_secs(2))
-                            .build()
-                            .unwrap_or_default();
-                        client
+                        reqwest::Client::new()
                             .get("http://127.0.0.1:18006/v1/models")
                             .send()
                             .await
@@ -111,46 +128,8 @@ impl HeartbeatEngine {
                         &task.payload
                     };
 
-                    let trimmed = cmd_to_run.trim();
-                    if trimmed.contains("find / ") || trimmed.contains("find / -") || trimmed == "find /" || trimmed.starts_with("rm -rf /") {
-                        let res_text = "Security rejection: broad root scan or destructive command prohibited";
-                        let _ = self.db.complete_task(&task.id, res_text);
-                        actions += 1;
-                        continue;
-                    }
-
-                    let home_dir = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
-                    let workspace_root = std::env::var("OPENCLAW_WORKSPACE")
-                        .unwrap_or_else(|_| format!("{}/workspace", home_dir));
-                    let target_dir = if std::path::Path::new(&workspace_root).exists() {
-                        std::path::PathBuf::from(workspace_root)
-                    } else if let Ok(cwd) = std::env::current_dir() {
-                        cwd
-                    } else {
-                        std::path::PathBuf::from(".")
-                    };
-
-                    let output = Command::new("sh")
-                        .arg("-c")
-                        .arg(cmd_to_run)
-                        .current_dir(&target_dir)
-                        .output()
-                        .await;
-
-                    let res_text = match output {
-                        Ok(o) => {
-                            let stdout = String::from_utf8_lossy(&o.stdout);
-                            let stderr = String::from_utf8_lossy(&o.stderr);
-                            format!(
-                                "Exit code {}: {}",
-                                o.status.code().unwrap_or(-1),
-                                if !stdout.trim().is_empty() {
-                                    stdout.trim()
-                                } else {
-                                    stderr.trim()
-                                }
-                            )
-                        }
+                    let res_text = match self.workspace.execute_shell(cmd_to_run, None, 15) {
+                        Ok(stdout) => format!("Exit code 0: {}", stdout.trim()),
                         Err(e) => format!("Execution failure: {}", e),
                     };
                     let _ = self.db.complete_task(&task.id, &res_text);
@@ -285,7 +264,7 @@ mod tests {
     #[tokio::test]
     async fn test_heartbeat_prohibited_root_command_rejection() {
         let db = Arc::new(Database::open_in_memory().unwrap());
-        db.create_task("hb_sec", "shell_exec", "find / -name secret").unwrap();
+        db.create_task("hb_sec", "shell_exec", "cd /etc && ls").unwrap();
 
         let engine = HeartbeatEngine::new(60, db.clone());
         let receipt = engine.pulse_once().await;
diff --git a/src/lib.rs b/src/lib.rs
index 7ec64a5..c8b08ab 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -4,6 +4,7 @@ pub mod heartbeat;
 pub mod inference;
 pub mod mojo_bridge;
 pub mod persistence;
+pub mod security;
 pub mod skills;
 pub mod vault;
 
@@ -13,5 +14,6 @@ pub use heartbeat::{HeartbeatEngine, PulseReceipt};
 pub use inference::{ChatTurnResponse, EmbeddedInferenceBackend, EmbeddedModel, HttpInferenceBackend, InferenceEngine, ToolCallFunction, ToolCallItem};
 pub use mojo_bridge::MojoSimdBridge;
 pub use persistence::{CrumbRecord, Database, TaskRecord, TurnRecord};
+pub use security::{SecurityError, WorkspaceCapability};
 pub use skills::{SkillDefinition, SkillExecutionRequest, SkillExecutionResponse, SkillRegistry};
 pub use vault::{VaultResolver, REDACTED_MARKER};
diff --git a/src/security.rs b/src/security.rs
new file mode 100644
index 0000000..e8f6d3d
--- /dev/null
+++ b/src/security.rs
@@ -0,0 +1,342 @@
+//! Capability-bound workspace security and canonical path resolution.
+//! Enforces containment for filesystem access and shell execution within authorized workspace roots.
+
+use std::path::{Component, Path, PathBuf};
+use std::process::Command;
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum SecurityError {
+    AccessDenied(String),
+    PathNotFound(String),
+    InvalidPath(String),
+    IoError(String),
+    CommandFailed(String),
+}
+
+impl std::fmt::Display for SecurityError {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        match self {
+            Self::AccessDenied(msg) => write!(f, "Security rejection: {}", msg),
+            Self::PathNotFound(msg) => write!(f, "Path not found: {}", msg),
+            Self::InvalidPath(msg) => write!(f, "{}", msg),
+            Self::IoError(msg) => write!(f, "I/O error: {}", msg),
+            Self::CommandFailed(msg) => write!(f, "Command execution failed: {}", msg),
+        }
+    }
+}
+
+impl std::error::Error for SecurityError {}
+
+#[derive(Debug, Clone)]
+pub struct WorkspaceCapability {
+    root: PathBuf,
+}
+
+impl Default for WorkspaceCapability {
+    fn default() -> Self {
+        Self::detect()
+    }
+}
+
+impl WorkspaceCapability {
+    /// Constructs a capability strictly bound to the specified root directory.
+    pub fn new<P: AsRef<Path>>(root: P) -> Result<Self, SecurityError> {
+        let p = root.as_ref();
+        if !p.exists() {
+            std::fs::create_dir_all(p).map_err(|e| {
+                SecurityError::IoError(format!(
+                    "Failed to create workspace directory {}: {}",
+                    p.display(),
+                    e
+                ))
+            })?;
+        }
+        let canonical = p.canonicalize().map_err(|e| {
+            SecurityError::IoError(format!(
+                "Failed to canonicalize workspace root {}: {}",
+                p.display(),
+                e
+            ))
+        })?;
+        Ok(Self { root: canonical })
+    }
+
+    /// Automatically detects the active workspace root.
+    pub fn detect() -> Self {
+        if let Ok(ws) = std::env::var("OPENCLAW_WORKSPACE") {
+            if let Ok(cap) = Self::new(&ws) {
+                return cap;
+            }
+        }
+        if let Ok(cwd) = std::env::current_dir() {
+            if let Ok(cap) = Self::new(&cwd) {
+                return cap;
+            }
+        }
+        if let Ok(home) = std::env::var("HOME") {
+            let candidate = PathBuf::from(home).join("workspace");
+            if candidate.exists() {
+                if let Ok(cap) = Self::new(&candidate) {
+                    return cap;
+                }
+            }
+        }
+        Self {
+            root: PathBuf::from(".")
+                .canonicalize()
+                .unwrap_or_else(|_| PathBuf::from(".")),
+        }
+    }
+
+    pub fn root(&self) -> &Path {
+        &self.root
+    }
+
+    /// Resolves an existing file path for reading, strictly verifying that it resides within the workspace root.
+    /// Canonicalizes the path and rejects traversal escaping the root.
+    pub fn resolve_read_path(&self, requested: &str) -> Result<PathBuf, SecurityError> {
+        let trimmed = requested.trim();
+        if trimmed.is_empty() {
+            return Err(SecurityError::InvalidPath("Path cannot be empty".to_string()));
+        }
+
+        let candidate = if Path::new(trimmed).is_absolute() {
+            PathBuf::from(trimmed)
+        } else {
+            self.root.join(trimmed)
+        };
+
+        if !candidate.exists() {
+            return Err(SecurityError::PathNotFound(format!(
+                "File does not exist: {}",
+                trimmed
+            )));
+        }
+
+        let canonical = candidate.canonicalize().map_err(|e| {
+            SecurityError::IoError(format!(
+                "Failed to canonicalize path {}: {}",
+                trimmed, e
+            ))
+        })?;
+
+        if !canonical.starts_with(&self.root) {
+            return Err(SecurityError::AccessDenied(format!(
+                "Path {} escapes authorized workspace root {}",
+                canonical.display(),
+                self.root.display()
+            )));
+        }
+
+        Ok(canonical)
+    }
+
+    /// Resolves a file path for writing. For new files, canonicalizes the lowest existing ancestor directory
+    /// and verifies that the normalized target path stays strictly inside the workspace root.
+    pub fn resolve_write_path(&self, requested: &str) -> Result<PathBuf, SecurityError> {
+        let trimmed = requested.trim();
+        if trimmed.is_empty() {
+            return Err(SecurityError::InvalidPath("Path cannot be empty".to_string()));
+        }
+
+        let raw_target = if Path::new(trimmed).is_absolute() {
+            PathBuf::from(trimmed)
+        } else {
+            self.root.join(trimmed)
+        };
+
+        let normalized = normalize_path(&raw_target);
+
+        let mut cur = normalized.as_path();
+        let mut existing_ancestor = None;
+        while let Some(parent) = cur.parent() {
+            if parent.exists() {
+                let canonical_ancestor = parent.canonicalize().map_err(|e| {
+                    SecurityError::IoError(format!(
+                        "Failed to canonicalize ancestor {}: {}",
+                        parent.display(),
+                        e
+                    ))
+                })?;
+                existing_ancestor = Some(canonical_ancestor);
+                break;
+            }
+            cur = parent;
+        }
+
+        let ancestor = existing_ancestor.ok_or_else(|| {
+            SecurityError::AccessDenied(format!(
+                "No valid ancestor directory found for {}",
+                trimmed
+            ))
+        })?;
+
+        if !ancestor.starts_with(&self.root) {
+            return Err(SecurityError::AccessDenied(format!(
+                "Target ancestor {} escapes authorized workspace root {}",
+                ancestor.display(),
+                self.root.display()
+            )));
+        }
+
+        if !normalized.starts_with(&self.root) {
+            return Err(SecurityError::AccessDenied(format!(
+                "Normalized target path {} escapes authorized workspace root {}",
+                normalized.display(),
+                self.root.display()
+            )));
+        }
+
+        Ok(normalized)
+    }
+
+    /// Resolves an existing directory path (for listing or working directory), ensuring it stays within root.
+    pub fn resolve_dir_path(&self, requested: Option<&str>) -> Result<PathBuf, SecurityError> {
+        let target = match requested {
+            Some(d) if !d.trim().is_empty() && d.trim() != "." => {
+                let p = Path::new(d.trim());
+                if p.is_absolute() {
+                    p.to_path_buf()
+                } else {
+                    self.root.join(p)
+                }
+            }
+            _ => self.root.clone(),
+        };
+
+        if !target.exists() {
+            return Err(SecurityError::PathNotFound(format!(
+                "Directory does not exist: {}",
+                target.display()
+            )));
+        }
+
+        let canonical = target.canonicalize().map_err(|e| {
+            SecurityError::IoError(format!(
+                "Failed to canonicalize directory {}: {}",
+                target.display(),
+                e
+            ))
+        })?;
+
+        if !canonical.is_dir() {
+            return Err(SecurityError::InvalidPath(format!(
+                "Path is not a directory: {}",
+                canonical.display()
+            )));
+        }
+
+        if !canonical.starts_with(&self.root) {
+            return Err(SecurityError::AccessDenied(format!(
+                "Directory {} escapes authorized workspace root {}",
+                canonical.display(),
+                self.root.display()
+            )));
+        }
+
+        Ok(canonical)
+    }
+
+    /// Executes a shell command strictly within the validated workspace directory capability.
+    pub fn execute_shell(
+        &self,
+        command: &str,
+        cwd: Option<&str>,
+        timeout_secs: u64,
+    ) -> Result<String, SecurityError> {
+        let trimmed_cmd = command.trim();
+        if trimmed_cmd.is_empty() {
+            return Err(SecurityError::InvalidPath("Command cannot be empty".to_string()));
+        }
+
+        let working_dir = self.resolve_dir_path(cwd)?;
+
+        let escaped_cmd = trimmed_cmd.replace('\'', "'\\''");
+        let wrapped_cmd = format!("timeout {}s bash -c '{}'", timeout_secs, escaped_cmd);
+
+        let output = Command::new("sh")
+            .arg("-c")
+            .arg(&wrapped_cmd)
+            .current_dir(&working_dir)
+            .output()
+            .map_err(|e| SecurityError::CommandFailed(format!("Failed to execute command: {}", e)))?;
+
+        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
+        let stderr = String::from_utf8_lossy(&output.stderr).to_string();
+
+        if !output.status.success() {
+            let code = output.status.code().unwrap_or(-1);
+            if code == 124 {
+                return Err(SecurityError::CommandFailed(format!(
+                    "Command timed out after {} seconds: {}",
+                    timeout_secs, trimmed_cmd
+                )));
+            }
+            return Err(SecurityError::CommandFailed(format!(
+                "Exit code {}: {}",
+                code,
+                if !stderr.trim().is_empty() {
+                    stderr.trim()
+                } else {
+                    stdout.trim()
+                }
+            )));
+        }
+
+        Ok(stdout)
+    }
+}
+
+pub fn normalize_path(path: &Path) -> PathBuf {
+    let mut stack = Vec::new();
+    for comp in path.components() {
+        match comp {
+            Component::CurDir => {}
+            Component::ParentDir => {
+                stack.pop();
+            }
+            c => {
+                stack.push(c.as_os_str());
+            }
+        }
+    }
+    stack.iter().collect()
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use tempfile::tempdir;
+
+    #[test]
+    fn test_workspace_capability_read_write_containment() {
+        let dir = tempdir().unwrap();
+        let cap = WorkspaceCapability::new(dir.path()).unwrap();
+
+        let write_target = cap.resolve_write_path("nested/test.txt").unwrap();
+        assert!(write_target.starts_with(cap.root()));
+        std::fs::create_dir_all(write_target.parent().unwrap()).unwrap();
+        std::fs::write(&write_target, "secure data").unwrap();
+
+        let read_target = cap.resolve_read_path("nested/test.txt").unwrap();
+        assert_eq!(read_target, write_target.canonicalize().unwrap());
+
+        let escape_read = cap.resolve_read_path("../../etc/passwd");
+        assert!(escape_read.is_err());
+
+        let escape_write = cap.resolve_write_path("../../../evil.sh");
+        assert!(escape_write.is_err());
+    }
+
+    #[test]
+    fn test_workspace_capability_shell_execution() {
+        let dir = tempdir().unwrap();
+        let cap = WorkspaceCapability::new(dir.path()).unwrap();
+
+        let out = cap.execute_shell("echo 'contained shell'", None, 5).unwrap();
+        assert!(out.contains("contained shell"));
+
+        let res = cap.execute_shell("ls", Some("/etc"), 5);
+        assert!(res.is_err());
+    }
+}
diff --git a/src/skills.rs b/src/skills.rs
index 8347349..f4eeaa6 100644
--- a/src/skills.rs
+++ b/src/skills.rs
@@ -1,3 +1,4 @@
+use crate::security::WorkspaceCapability;
 use serde::{Deserialize, Serialize};
 use std::collections::HashMap;
 use std::process::Command;
@@ -28,6 +29,7 @@ pub type SkillHandler = Arc<dyn Fn(serde_json::Value) -> Result<String, String>
 #[derive(Clone)]
 pub struct SkillRegistry {
     skills: Arc<RwLock<HashMap<String, (SkillDefinition, SkillHandler)>>>,
+    workspace: Arc<WorkspaceCapability>,
 }
 
 impl Default for SkillRegistry {
@@ -38,13 +40,22 @@ impl Default for SkillRegistry {
 
 impl SkillRegistry {
     pub fn new() -> Self {
+        Self::with_workspace(WorkspaceCapability::detect())
+    }
+
+    pub fn with_workspace(workspace: WorkspaceCapability) -> Self {
         let registry = Self {
             skills: Arc::new(RwLock::new(HashMap::new())),
+            workspace: Arc::new(workspace),
         };
         registry.register_builtin_skills();
         registry
     }
 
+    pub fn workspace(&self) -> &WorkspaceCapability {
+        &self.workspace
+    }
+
     pub fn register<F>(&self, def: SkillDefinition, handler: F)
     where
         F: Fn(serde_json::Value) -> Result<String, String> + Send + Sync + 'static,
@@ -108,142 +119,91 @@ impl SkillRegistry {
 
     fn register_builtin_skills(&self) {
         // Builtin 1: bash_eval
-        let home_dir = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
-        let default_workspace = std::env::var("OPENCLAW_WORKSPACE")
-            .unwrap_or_else(|_| format!("{}/workspace", home_dir));
-
+        let ws_bash = self.workspace.clone();
         let bash_def = SkillDefinition {
             name: "bash_eval".to_string(),
             description: format!(
-                "Execute a command in the local bash shell. Working directory defaults to {}. Timeout is 15 seconds. Broad scans of root (find /) are prohibited.",
-                default_workspace
+                "Execute a command in the local bash shell strictly within authorized workspace root {}. Execution is confined by workspace capability.",
+                ws_bash.root().display()
             ),
             parameters_schema: serde_json::json!({
                 "type": "object",
                 "properties": {
                     "command": { "type": "string", "description": "The command line string to run" },
-                    "cwd": { "type": "string", "description": format!("Optional working directory, defaults to {}", default_workspace) }
+                    "cwd": { "type": "string", "description": format!("Optional working directory inside authorized workspace {}", ws_bash.root().display()) }
                 },
                 "required": ["command"]
             }),
         };
-        let default_ws_clone = default_workspace.clone();
-        let home_clone = home_dir.clone();
         self.register(bash_def, move |args| {
             let cmd = args.get("command").and_then(|c| c.as_str()).unwrap_or("");
-            if cmd.is_empty() {
-                return Err("Command cannot be empty".to_string());
-            }
-
-            let trimmed = cmd.trim();
-            if trimmed.contains("find / ") || trimmed.contains("find / -") || trimmed == "find /" || trimmed.starts_with("rm -rf /") {
-                return Err(format!(
-                    "Safety error: broad scans of root filesystem (find /) are prohibited. Target specific workspace paths under {}.",
-                    default_ws_clone
-                ));
-            }
-
             let cwd = args.get("cwd").and_then(|c| c.as_str());
-
-            let target_dir = match cwd {
-                Some(dir) if std::path::Path::new(dir).exists() => dir.to_string(),
-                Some(dir) => return Err(format!("Specified working directory does not exist: {}", dir)),
-                None => {
-                    if std::path::Path::new(&default_ws_clone).exists() {
-                        default_ws_clone.clone()
-                    } else if std::path::Path::new(&home_clone).exists() {
-                        home_clone.clone()
-                    } else {
-                        ".".to_string()
-                    }
-                }
-            };
-
-            let escaped_cmd = cmd.replace('\'', "'\\''");
-            let wrapped_cmd = format!("timeout 15s bash -c '{}'", escaped_cmd);
-            let output = Command::new("sh")
-                .arg("-c")
-                .arg(&wrapped_cmd)
-                .current_dir(&target_dir)
-                .output()
-                .map_err(|e| format!("Failed to execute command: {}", e))?;
-
-            let stdout = String::from_utf8_lossy(&output.stdout).to_string();
-            let stderr = String::from_utf8_lossy(&output.stderr).to_string();
-            if !output.status.success() {
-                let code = output.status.code().unwrap_or(-1);
-                if code == 124 {
-                    return Err(format!("Command timed out after 15 seconds: {}", cmd));
-                }
-                return Err(format!("Exit code {}: {}", code, stderr));
-            }
-            Ok(stdout)
+            ws_bash.execute_shell(cmd, cwd, 15).map_err(|e| e.to_string())
         });
 
         // Builtin 2: read_file
+        let ws_read = self.workspace.clone();
         let read_def = SkillDefinition {
             name: "read_file".to_string(),
-            description: "Read the contents of a text file from the filesystem".to_string(),
+            description: "Read the contents of a text file strictly within authorized workspace roots".to_string(),
             parameters_schema: serde_json::json!({
                 "type": "object",
                 "properties": {
-                    "path": { "type": "string", "description": "Absolute or relative path to file" }
+                    "path": { "type": "string", "description": "Relative or absolute path inside the workspace root" }
                 },
                 "required": ["path"]
             }),
         };
-        self.register(read_def, |args| {
+        self.register(read_def, move |args| {
             let path_str = args.get("path").and_then(|p| p.as_str()).unwrap_or("");
-            if path_str.is_empty() {
-                return Err("Path cannot be empty".to_string());
-            }
-            std::fs::read_to_string(path_str)
-                .map_err(|e| format!("Failed to read file {}: {}", path_str, e))
+            let resolved = ws_read.resolve_read_path(path_str).map_err(|e| e.to_string())?;
+            std::fs::read_to_string(&resolved)
+                .map_err(|e| format!("Failed to read file {}: {}", resolved.display(), e))
         });
 
         // Builtin 3: write_file
+        let ws_write = self.workspace.clone();
         let write_def = SkillDefinition {
             name: "write_file".to_string(),
-            description: "Write text contents to a file on the filesystem".to_string(),
+            description: "Write text contents to a file strictly within authorized workspace roots".to_string(),
             parameters_schema: serde_json::json!({
                 "type": "object",
                 "properties": {
-                    "path": { "type": "string", "description": "File path to write" },
+                    "path": { "type": "string", "description": "Target file path inside the workspace root" },
                     "content": { "type": "string", "description": "Text content to write" }
                 },
                 "required": ["path", "content"]
             }),
         };
-        self.register(write_def, |args| {
+        self.register(write_def, move |args| {
             let path_str = args.get("path").and_then(|p| p.as_str()).unwrap_or("");
             let content = args.get("content").and_then(|c| c.as_str()).unwrap_or("");
-            if path_str.is_empty() {
-                return Err("Path cannot be empty".to_string());
-            }
-            if let Some(parent) = std::path::Path::new(path_str).parent() {
+            let resolved = ws_write.resolve_write_path(path_str).map_err(|e| e.to_string())?;
+            if let Some(parent) = resolved.parent() {
                 let _ = std::fs::create_dir_all(parent);
             }
-            std::fs::write(path_str, content)
-                .map(|_| format!("Wrote {} bytes to {}", content.len(), path_str))
-                .map_err(|e| format!("Failed to write file {}: {}", path_str, e))
+            std::fs::write(&resolved, content)
+                .map(|_| format!("Wrote {} bytes to {}", content.len(), resolved.display()))
+                .map_err(|e| format!("Failed to write file {}: {}", resolved.display(), e))
         });
 
         // Builtin 4: list_dir
+        let ws_list = self.workspace.clone();
         let list_def = SkillDefinition {
             name: "list_dir".to_string(),
-            description: "List directory contents including files and subdirectories".to_string(),
+            description: "List directory contents strictly within authorized workspace roots".to_string(),
             parameters_schema: serde_json::json!({
                 "type": "object",
                 "properties": {
-                    "path": { "type": "string", "description": "Directory path to list" }
-                },
-                "required": ["path"]
+                    "path": { "type": "string", "description": "Directory path inside workspace root" }
+                }
             }),
         };
-        self.register(list_def, |args| {
-            let path_str = args.get("path").and_then(|p| p.as_str()).unwrap_or(".");
-            let entries = std::fs::read_dir(path_str)
-                .map_err(|e| format!("Failed to read directory {}: {}", path_str, e))?;
+        self.register(list_def, move |args| {
+            let path_str = args.get("path").and_then(|p| p.as_str());
+            let resolved = ws_list.resolve_dir_path(path_str).map_err(|e| e.to_string())?;
+            let entries = std::fs::read_dir(&resolved)
+                .map_err(|e| format!("Failed to read directory {}: {}", resolved.display(), e))?;
             let mut items = Vec::new();
             for entry in entries.flatten() {
                 let fname = entry.file_name().to_string_lossy().to_string();
@@ -255,28 +215,30 @@ impl SkillRegistry {
         });
 
         // Builtin 5: git_status
+        let ws_git = self.workspace.clone();
         let git_def = SkillDefinition {
             name: "git_status".to_string(),
-            description: "Check git status and current commit in repository".to_string(),
+            description: "Check git status and commit in repository strictly within authorized workspace root".to_string(),
             parameters_schema: serde_json::json!({
                 "type": "object",
                 "properties": {
-                    "path": { "type": "string", "description": "Repository path" }
+                    "path": { "type": "string", "description": "Repository path inside workspace root" }
                 }
             }),
         };
-        self.register(git_def, |args| {
-            let path_str = args.get("path").and_then(|p| p.as_str()).unwrap_or(".");
+        self.register(git_def, move |args| {
+            let path_str = args.get("path").and_then(|p| p.as_str());
+            let resolved = ws_git.resolve_dir_path(path_str).map_err(|e| e.to_string())?;
             let output = Command::new("git")
                 .arg("-C")
-                .arg(path_str)
+                .arg(&resolved)
                 .arg("status")
                 .arg("--short")
                 .output()
                 .map_err(|e| format!("Failed to run git status: {}", e))?;
             let log_output = Command::new("git")
                 .arg("-C")
-                .arg(path_str)
+                .arg(&resolved)
                 .arg("log")
                 .arg("-1")
                 .arg("--oneline")
@@ -346,16 +308,15 @@ mod tests {
     }
 
     #[test]
-    fn test_filesystem_skills() {
-        let registry = SkillRegistry::new();
+    fn test_filesystem_skills_with_workspace_containment() {
         let tmp = tempfile::tempdir().unwrap();
-        let fpath = tmp.path().join("test_write.txt");
-        let fpath_str = fpath.to_str().unwrap();
+        let cap = WorkspaceCapability::new(tmp.path()).unwrap();
+        let registry = SkillRegistry::with_workspace(cap);
 
         let w_req = SkillExecutionRequest {
             skill_name: "write_file".to_string(),
             arguments: serde_json::json!({
-                "path": fpath_str,
+                "path": "test_write.txt",
                 "content": "Sovereign native AIEN test content"
             }),
         };
@@ -365,7 +326,7 @@ mod tests {
         let r_req = SkillExecutionRequest {
             skill_name: "read_file".to_string(),
             arguments: serde_json::json!({
-                "path": fpath_str,
+                "path": "test_write.txt",
             }),
         };
         let r_res = registry.execute(&r_req);
@@ -375,11 +336,22 @@ mod tests {
         let l_req = SkillExecutionRequest {
             skill_name: "list_dir".to_string(),
             arguments: serde_json::json!({
-                "path": tmp.path().to_str().unwrap(),
+                "path": ".",
             }),
         };
         let l_res = registry.execute(&l_req);
         assert!(l_res.success);
         assert!(l_res.output.contains("test_write.txt"));
+
+        // Test security escape rejection
+        let escape_req = SkillExecutionRequest {
+            skill_name: "read_file".to_string(),
+            arguments: serde_json::json!({
+                "path": "../../etc/passwd",
+            }),
+        };
+        let escape_res = registry.execute(&escape_req);
+        assert!(!escape_res.success);
+        assert!(escape_res.error.unwrap().contains("Security rejection"));
     }
 }