Skip to main content

everruns_core/
workspace_roots.rs

1use std::collections::HashSet;
2use std::path::{Component, Path, PathBuf};
3
4use crate::error::{AgentLoopError, Result};
5use crate::mount_fs::WORKSPACE_MOUNT;
6
7pub const PRIMARY_WORKSPACE_ROOT_NAME: &str = "workspace";
8pub const ADDITIONAL_ROOTS_MOUNT: &str = "/workspace/roots";
9
10#[derive(Clone, Debug, PartialEq, Eq)]
11pub struct WorkspaceRoot {
12    pub name: String,
13    pub path: PathBuf,
14}
15
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub struct WorkspaceRootSet {
18    pub primary: WorkspaceRoot,
19    pub additional: Vec<WorkspaceRoot>,
20}
21
22#[derive(Clone, Debug, PartialEq, Eq)]
23pub struct ResolvedPath {
24    pub root_name: String,
25    pub relative: RelPath,
26}
27
28#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]
29pub struct RelPath(String);
30
31impl RelPath {
32    pub fn as_relative(&self) -> &str {
33        &self.0
34    }
35
36    pub fn to_session_path(&self) -> String {
37        if self.0.is_empty() {
38            "/".to_string()
39        } else {
40            format!("/{}", self.0)
41        }
42    }
43
44    fn from_path(relative: &Path) -> Result<Self> {
45        let mut segments = Vec::new();
46        for component in relative.components() {
47            match component {
48                Component::CurDir => {}
49                Component::Normal(segment) => {
50                    let segment = segment.to_str().ok_or_else(|| {
51                        AgentLoopError::tool(format!(
52                            "non-UTF-8 path component: {}",
53                            relative.display()
54                        ))
55                    })?;
56                    segments.push(segment.to_string());
57                }
58                Component::ParentDir => {
59                    return Err(AgentLoopError::tool(format!(
60                        "path traversal rejected: {}",
61                        relative.display()
62                    )));
63                }
64                Component::RootDir | Component::Prefix(_) => {
65                    return Err(AgentLoopError::tool(format!(
66                        "absolute path component rejected: {}",
67                        relative.display()
68                    )));
69                }
70            }
71        }
72        Ok(Self(segments.join("/")))
73    }
74
75    fn from_str(input: &str) -> Result<Self> {
76        let mut segments = Vec::new();
77        for part in input.split('/') {
78            match part {
79                "" | "." => {}
80                ".." => {
81                    return Err(AgentLoopError::tool(format!(
82                        "path traversal rejected: {input}"
83                    )));
84                }
85                segment => segments.push(segment.to_string()),
86            }
87        }
88        Ok(Self(segments.join("/")))
89    }
90}
91
92impl WorkspaceRootSet {
93    pub fn from_primary(path: impl Into<PathBuf>) -> Result<Self> {
94        Self::new(path, Vec::<(String, PathBuf)>::new())
95    }
96
97    pub fn new<I, P>(primary: impl Into<PathBuf>, additional: I) -> Result<Self>
98    where
99        I: IntoIterator<Item = (String, P)>,
100        P: Into<PathBuf>,
101    {
102        let primary = WorkspaceRoot {
103            name: PRIMARY_WORKSPACE_ROOT_NAME.to_string(),
104            path: canonicalize_root(primary.into())?,
105        };
106        let mut additional_roots = Vec::new();
107        let mut names = HashSet::new();
108        for (name, path) in additional {
109            validate_additional_name(&name)?;
110            if !names.insert(name.clone()) {
111                return Err(AgentLoopError::config(format!(
112                    "duplicate workspace root name: {name}"
113                )));
114            }
115            additional_roots.push(WorkspaceRoot {
116                name,
117                path: canonicalize_root(path.into())?,
118            });
119        }
120
121        let root_set = Self {
122            primary,
123            additional: additional_roots,
124        };
125        root_set.reject_overlaps()?;
126        Ok(root_set)
127    }
128
129    pub fn parse_vfs_path(&self, input: &str) -> Result<ResolvedPath> {
130        let trimmed = input.trim();
131        let candidate = Path::new(trimmed);
132        if candidate.is_absolute() && !trimmed.starts_with("/workspace") {
133            if let Some((root, relative)) = self.resolve_host_path(candidate)? {
134                return Ok(ResolvedPath {
135                    root_name: root.name.clone(),
136                    relative,
137                });
138            }
139            return Err(AgentLoopError::tool(format!(
140                "host path is outside registered workspace roots: {trimmed}"
141            )));
142        }
143
144        let session = if trimmed == WORKSPACE_MOUNT || trimmed == "workspace" {
145            "/".to_string()
146        } else if let Some(rest) = trimmed.strip_prefix("/workspace/") {
147            format!("/{rest}")
148        } else if trimmed.starts_with('/') {
149            trimmed.to_string()
150        } else {
151            format!("/{trimmed}")
152        };
153
154        if session == "/" || !session.starts_with("/roots/") {
155            return Ok(ResolvedPath {
156                root_name: self.primary.name.clone(),
157                relative: RelPath::from_str(&session)?,
158            });
159        }
160
161        let rest = session.strip_prefix("/roots/").unwrap_or_default();
162        let (name, relative) = rest.split_once('/').unwrap_or((rest, ""));
163        let root = self
164            .additional
165            .iter()
166            .find(|root| root.name == name)
167            .ok_or_else(|| AgentLoopError::tool(format!("unknown workspace root: {name}")))?;
168        Ok(ResolvedPath {
169            root_name: root.name.clone(),
170            relative: RelPath::from_str(relative)?,
171        })
172    }
173
174    pub fn parse_host_scope(&self, root: &str, relative: Option<&str>) -> Result<PathBuf> {
175        let workspace_root = self.root_by_name(root)?;
176        let rel = RelPath::from_str(relative.unwrap_or(""))?;
177        let joined = if rel.as_relative().is_empty() {
178            workspace_root.path.clone()
179        } else {
180            workspace_root.path.join(rel.as_relative())
181        };
182        if !joined.starts_with(&workspace_root.path) {
183            return Err(AgentLoopError::tool(format!(
184                "path escapes workspace root: {}",
185                joined.display()
186            )));
187        }
188        Ok(joined)
189    }
190
191    pub fn primary_host_root(&self) -> &Path {
192        &self.primary.path
193    }
194
195    pub fn set_primary_host_root(&mut self, path: PathBuf) -> Result<()> {
196        self.primary.path = canonicalize_root(path)?;
197        self.reject_overlaps()
198    }
199
200    pub fn spawn_cwd(&self) -> Result<PathBuf> {
201        canonicalize_root(self.primary.path.clone())
202    }
203
204    pub fn contains_host_path(&self, path: &Path) -> bool {
205        let Ok(canonical) = canonicalize_existing_or_parent(path) else {
206            return false;
207        };
208        self.all_roots()
209            .any(|root| canonical == root.path || canonical.starts_with(&root.path))
210    }
211
212    pub fn additional_mount_point(root_name: &str) -> String {
213        format!("{ADDITIONAL_ROOTS_MOUNT}/{root_name}")
214    }
215
216    fn all_roots(&self) -> impl Iterator<Item = &WorkspaceRoot> {
217        std::iter::once(&self.primary).chain(self.additional.iter())
218    }
219
220    fn root_by_name(&self, name: &str) -> Result<&WorkspaceRoot> {
221        if name == self.primary.name {
222            return Ok(&self.primary);
223        }
224        self.additional
225            .iter()
226            .find(|root| root.name == name)
227            .ok_or_else(|| AgentLoopError::tool(format!("unknown workspace root: {name}")))
228    }
229
230    fn resolve_host_path(&self, path: &Path) -> Result<Option<(&WorkspaceRoot, RelPath)>> {
231        let canonical = canonicalize_existing_or_parent(path)?;
232        for root in self.all_roots() {
233            if let Ok(relative) = canonical.strip_prefix(&root.path) {
234                return Ok(Some((root, RelPath::from_path(relative)?)));
235            }
236        }
237        Ok(None)
238    }
239
240    fn reject_overlaps(&self) -> Result<()> {
241        let roots: Vec<&WorkspaceRoot> = self.all_roots().collect();
242        for (idx, left) in roots.iter().enumerate() {
243            for right in roots.iter().skip(idx + 1) {
244                if left.path == right.path
245                    || left.path.starts_with(&right.path)
246                    || right.path.starts_with(&left.path)
247                {
248                    return Err(AgentLoopError::config(format!(
249                        "workspace roots must not overlap: {} ({}) and {} ({})",
250                        left.name,
251                        left.path.display(),
252                        right.name,
253                        right.path.display()
254                    )));
255                }
256            }
257        }
258        Ok(())
259    }
260}
261
262fn validate_additional_name(name: &str) -> Result<()> {
263    if name.is_empty()
264        || name == "."
265        || name == ".."
266        || name == PRIMARY_WORKSPACE_ROOT_NAME
267        || name == "roots"
268        || name.contains('/')
269        || name.contains('\\')
270    {
271        return Err(AgentLoopError::config(format!(
272            "invalid workspace root name: {name}"
273        )));
274    }
275    Ok(())
276}
277
278fn canonicalize_root(root: PathBuf) -> Result<PathBuf> {
279    let canonical = std::fs::canonicalize(&root).map_err(|e| {
280        AgentLoopError::config(format!(
281            "failed to canonicalize workspace root {}: {e}",
282            root.display()
283        ))
284    })?;
285    if !canonical.is_dir() {
286        return Err(AgentLoopError::config(format!(
287            "workspace root is not a directory: {}",
288            canonical.display()
289        )));
290    }
291    Ok(canonical)
292}
293
294fn canonicalize_existing_or_parent(path: &Path) -> Result<PathBuf> {
295    match std::fs::canonicalize(path) {
296        Ok(path) => Ok(path),
297        Err(_) => {
298            let parent = path.parent().ok_or_else(|| {
299                AgentLoopError::tool(format!("path has no parent: {}", path.display()))
300            })?;
301            let canonical_parent = std::fs::canonicalize(parent).map_err(|e| {
302                AgentLoopError::tool(format!(
303                    "failed to canonicalize parent {}: {e}",
304                    parent.display()
305                ))
306            })?;
307            let name = path.file_name().ok_or_else(|| {
308                AgentLoopError::tool(format!("path has no file name: {}", path.display()))
309            })?;
310            Ok(canonical_parent.join(name))
311        }
312    }
313}
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318    use tempfile::TempDir;
319
320    fn roots() -> (WorkspaceRootSet, TempDir, TempDir) {
321        let primary = TempDir::new().unwrap();
322        let backend = TempDir::new().unwrap();
323        let set = WorkspaceRootSet::new(
324            primary.path(),
325            [("backend".to_string(), backend.path().to_path_buf())],
326        )
327        .unwrap();
328        (set, primary, backend)
329    }
330
331    #[test]
332    fn canonicalizes_and_rejects_overlapping_roots() {
333        let primary = TempDir::new().unwrap();
334        let nested = primary.path().join("nested");
335        std::fs::create_dir(&nested).unwrap();
336
337        let err =
338            WorkspaceRootSet::new(primary.path(), [("nested".to_string(), nested)]).unwrap_err();
339        assert!(err.to_string().contains("must not overlap"));
340    }
341
342    #[test]
343    fn rejects_duplicate_names() {
344        let primary = TempDir::new().unwrap();
345        let a = TempDir::new().unwrap();
346        let b = TempDir::new().unwrap();
347
348        let err = WorkspaceRootSet::new(
349            primary.path(),
350            [
351                ("backend".to_string(), a.path().to_path_buf()),
352                ("backend".to_string(), b.path().to_path_buf()),
353            ],
354        )
355        .unwrap_err();
356        assert!(err.to_string().contains("duplicate workspace root name"));
357    }
358
359    #[test]
360    fn parses_primary_aliases_and_rejects_traversal() {
361        let (set, _primary, _backend) = roots();
362
363        assert_eq!(
364            set.parse_vfs_path("/workspace/src/lib.rs").unwrap(),
365            ResolvedPath {
366                root_name: "workspace".to_string(),
367                relative: RelPath("src/lib.rs".to_string())
368            }
369        );
370        assert_eq!(
371            set.parse_vfs_path("workspace").unwrap().relative,
372            RelPath::default()
373        );
374        assert!(set.parse_vfs_path("../outside").is_err());
375    }
376
377    #[test]
378    fn parses_additional_root_mounts_only() {
379        let (set, _primary, _backend) = roots();
380
381        assert_eq!(
382            set.parse_vfs_path("/workspace/roots/backend/src/lib.rs")
383                .unwrap(),
384            ResolvedPath {
385                root_name: "backend".to_string(),
386                relative: RelPath("src/lib.rs".to_string())
387            }
388        );
389        assert!(set.parse_vfs_path("/workspace/roots/missing/file").is_err());
390    }
391
392    #[test]
393    fn repoints_primary_without_touching_additional() {
394        let (mut set, _primary, backend) = roots();
395        let next = TempDir::new().unwrap();
396        set.set_primary_host_root(next.path().to_path_buf())
397            .unwrap();
398
399        assert_eq!(
400            set.spawn_cwd().unwrap(),
401            std::fs::canonicalize(next.path()).unwrap()
402        );
403        assert_eq!(
404            set.parse_host_scope("backend", Some("Cargo.toml")).unwrap(),
405            std::fs::canonicalize(backend.path())
406                .unwrap()
407                .join("Cargo.toml")
408        );
409    }
410}