Skip to main content

keel_enforce/
worktree.rs

1//! `local-worktree` backend: isolate agent writes in a git worktree or directory copy.
2//!
3//! ## Behavior
4//!
5//! 1. On `apply`, create an isolated workspace under `~/.keel/worktrees/<id>/`.
6//! 2. Prefer `git worktree add` when `workspace` is inside a git repo.
7//! 3. Fall back to a lightweight directory overlay (copy of essential layout / empty root).
8//! 4. Spawns run with `cwd` rewritten into the worktree; soft FS checks use remapped paths.
9//! 5. Optionally wraps an inner backend (`ProcessGuard` or `LocalProcess`) for extra enforcement.
10
11use crate::backend::{BackendInfo, EnforceBackend, SpawnRequest, SpawnedProcess};
12use crate::error::{EnforceError, EnforceResult};
13use crate::process_guard::{self, ProcessGuardBackend};
14use async_trait::async_trait;
15use chrono::Utc;
16use keel_policy::{Policy, SpaceId};
17use keel_record::{EventKind, RecordEvent, RecordSink};
18use std::path::{Path, PathBuf};
19use std::process::Command;
20use std::sync::atomic::{AtomicBool, Ordering};
21use std::sync::{Arc, Mutex};
22use tracing::{info, warn};
23
24/// Options for [`WorktreeBackend`].
25#[derive(Debug, Clone)]
26pub struct WorktreeOptions {
27    /// Directory root for worktrees (`$KEEL_HOME/worktrees` by default).
28    pub worktrees_root: Option<PathBuf>,
29    /// If true, remove the worktree on destroy (default true for ephemeral tasks).
30    pub cleanup_on_destroy: bool,
31    /// Prefer git worktree when possible (default true).
32    pub prefer_git: bool,
33}
34
35impl Default for WorktreeOptions {
36    fn default() -> Self {
37        Self {
38            worktrees_root: None,
39            cleanup_on_destroy: true,
40            prefer_git: true,
41        }
42    }
43}
44
45#[derive(Debug, Clone)]
46struct WorktreeState {
47    /// Isolated path agents should use as cwd / write root.
48    path: PathBuf,
49    /// Original workspace from the policy.
50    origin: PathBuf,
51    /// Whether we used `git worktree add`.
52    git: bool,
53    /// Branch/ref name for git worktrees.
54    branch: Option<String>,
55}
56
57/// Worktree isolation backend (optionally layered on another backend).
58pub struct WorktreeBackend {
59    opts: WorktreeOptions,
60    inner: Arc<dyn EnforceBackend>,
61    state: Mutex<Option<WorktreeState>>,
62    applied: AtomicBool,
63}
64
65impl WorktreeBackend {
66    pub fn new() -> Self {
67        Self::with_inner(Arc::new(ProcessGuardBackend::new()), WorktreeOptions::default())
68    }
69
70    pub fn with_options(opts: WorktreeOptions) -> Self {
71        Self::with_inner(Arc::new(ProcessGuardBackend::new()), opts)
72    }
73
74    pub fn with_inner(inner: Arc<dyn EnforceBackend>, opts: WorktreeOptions) -> Self {
75        Self {
76            opts,
77            inner,
78            state: Mutex::new(None),
79            applied: AtomicBool::new(false),
80        }
81    }
82
83    pub fn worktree_path(&self) -> Option<PathBuf> {
84        self.state.lock().ok()?.as_ref().map(|s| s.path.clone())
85    }
86
87    fn worktrees_root(&self) -> PathBuf {
88        self.opts.worktrees_root.clone().unwrap_or_else(|| {
89            if let Ok(h) = std::env::var("KEEL_HOME") {
90                return PathBuf::from(h).join("worktrees");
91            }
92            dirs::home_dir()
93                .unwrap_or_else(|| PathBuf::from("/tmp"))
94                .join(".keel")
95                .join("worktrees")
96        })
97    }
98
99    fn remap_to_worktree(&self, path: &Path) -> PathBuf {
100        let guard = self.state.lock().unwrap();
101        let Some(st) = guard.as_ref() else {
102            return path.to_path_buf();
103        };
104        if path.is_absolute() {
105            if let Ok(rel) = path.strip_prefix(&st.origin) {
106                return st.path.join(rel);
107            }
108            return path.to_path_buf();
109        }
110        st.path.join(path)
111    }
112
113    fn create_worktree(&self, policy: &Policy, space_tag: &str) -> EnforceResult<WorktreeState> {
114        let origin = if policy.workspace.is_absolute() {
115            policy.workspace.clone()
116        } else {
117            std::env::current_dir()
118                .unwrap_or_else(|_| PathBuf::from("."))
119                .join(&policy.workspace)
120        };
121        let origin = dunce::canonicalize(&origin).unwrap_or(origin);
122
123        let root = self.worktrees_root();
124        std::fs::create_dir_all(&root)?;
125        let dir_name = format!(
126            "{}-{}",
127            space_tag.chars().take(24).collect::<String>(),
128            std::process::id()
129        );
130        let path = root.join(dir_name);
131
132        if self.opts.prefer_git {
133            if let Some(state) = try_git_worktree(&origin, &path)? {
134                return Ok(state);
135            }
136        }
137
138        // Fallback: empty isolated directory (agent starts clean; can still read
139        // origin via soft default_read / system paths depending on policy).
140        std::fs::create_dir_all(&path)?;
141        // Drop a pointer file so tools/humans can find the origin.
142        let _ = std::fs::write(
143            path.join(".keel-worktree-origin"),
144            format!("{}\n", origin.display()),
145        );
146        info!(
147            path = %path.display(),
148            origin = %origin.display(),
149            "created directory worktree (non-git fallback)"
150        );
151        Ok(WorktreeState {
152            path,
153            origin,
154            git: false,
155            branch: None,
156        })
157    }
158}
159
160impl Default for WorktreeBackend {
161    fn default() -> Self {
162        Self::new()
163    }
164}
165
166fn try_git_worktree(origin: &Path, path: &Path) -> EnforceResult<Option<WorktreeState>> {
167    // Find git top-level for origin.
168    let out = Command::new("git")
169        .args(["-C", &origin.to_string_lossy(), "rev-parse", "--show-toplevel"])
170        .output();
171    let Ok(out) = out else {
172        return Ok(None);
173    };
174    if !out.status.success() {
175        return Ok(None);
176    }
177    let toplevel = String::from_utf8_lossy(&out.stdout).trim().to_string();
178    if toplevel.is_empty() {
179        return Ok(None);
180    }
181
182    let branch = format!(
183        "keel/{}",
184        path.file_name()
185            .and_then(|s| s.to_str())
186            .unwrap_or("task")
187    );
188
189    // git worktree add -b branch path HEAD
190    let status = Command::new("git")
191        .args([
192            "-C",
193            &toplevel,
194            "worktree",
195            "add",
196            "-b",
197            &branch,
198            &path.to_string_lossy(),
199            "HEAD",
200        ])
201        .status()
202        .map_err(|e| EnforceError::ApplyFailed(format!("git worktree add: {e}")))?;
203
204    if !status.success() {
205        warn!(
206            path = %path.display(),
207            "git worktree add failed; will use directory fallback"
208        );
209        // Clean partial path if created.
210        let _ = std::fs::remove_dir_all(path);
211        return Ok(None);
212    }
213
214    info!(
215        path = %path.display(),
216        branch = %branch,
217        "created git worktree"
218    );
219    Ok(Some(WorktreeState {
220        path: path.to_path_buf(),
221        origin: PathBuf::from(toplevel),
222        git: true,
223        branch: Some(branch),
224    }))
225}
226
227fn cleanup_worktree(st: &WorktreeState) {
228    if st.git {
229        if let Some(branch) = &st.branch {
230            let _ = Command::new("git")
231                .args([
232                    "-C",
233                    &st.origin.to_string_lossy(),
234                    "worktree",
235                    "remove",
236                    "--force",
237                    &st.path.to_string_lossy(),
238                ])
239                .status();
240            let _ = Command::new("git")
241                .args(["-C", &st.origin.to_string_lossy(), "branch", "-D", branch])
242                .status();
243        }
244    }
245    let _ = std::fs::remove_dir_all(&st.path);
246}
247
248#[async_trait]
249impl EnforceBackend for WorktreeBackend {
250    fn info(&self) -> BackendInfo {
251        let inner = self.inner.info();
252        BackendInfo {
253            name: "local-worktree",
254            kernel_fs: inner.kernel_fs,
255            child_network: inner.child_network,
256        }
257    }
258
259    async fn apply(&self, policy: &Policy, sink: Arc<dyn RecordSink>) -> EnforceResult<()> {
260        if policy.is_expired(Utc::now()) {
261            return Err(EnforceError::PolicyExpired);
262        }
263        policy.validate()?;
264
265        let tag = policy
266            .task_id
267            .as_ref()
268            .map(|t| t.as_str().to_string())
269            .unwrap_or_else(|| policy.id.as_str().to_string());
270        let st = self.create_worktree(policy, &tag)?;
271
272        // Policy for the inner backend: rewrite workspace to the worktree path.
273        let mut inner_policy = policy.clone();
274        inner_policy.workspace = st.path.clone();
275        // Ensure the worktree itself is writable in soft rules.
276        if !inner_policy
277            .fs
278            .iter()
279            .any(|r| r.path == st.path && r.access == keel_policy::FsAccess::ReadWrite)
280        {
281            inner_policy
282                .fs
283                .push(keel_policy::FsRule::read_write(st.path.clone()));
284        }
285
286        *self.state.lock().unwrap() = Some(st.clone());
287        self.inner.apply(&inner_policy, sink.clone()).await?;
288        self.applied.store(true, Ordering::Release);
289
290        let _ = sink
291            .emit(RecordEvent::new(
292                SpaceId::from_string("pending"),
293                policy.id.clone(),
294                policy.task_id.clone(),
295                EventKind::Note {
296                    message: format!(
297                        "worktree ready at {} (git={}, origin={})",
298                        st.path.display(),
299                        st.git,
300                        st.origin.display()
301                    ),
302                },
303            ))
304            .await;
305        Ok(())
306    }
307
308    async fn check_fs(&self, policy: &Policy, path: &Path, write: bool) -> EnforceResult<bool> {
309        let mapped = self.remap_to_worktree(path);
310        // Soft check against a policy whose workspace is the worktree when applied.
311        let mut p = policy.clone();
312        if let Some(st) = self.state.lock().unwrap().as_ref() {
313            p.workspace = st.path.clone();
314        }
315        let allowed = process_guard::soft_fs_allowed(&p, &mapped, write);
316        Ok(allowed)
317    }
318
319    async fn spawn(
320        &self,
321        space_id: &SpaceId,
322        policy: &Policy,
323        mut req: SpawnRequest,
324        sink: Arc<dyn RecordSink>,
325    ) -> EnforceResult<SpawnedProcess> {
326        let mut inner_policy = policy.clone();
327        if let Some(st) = self.state.lock().unwrap().as_ref() {
328            inner_policy.workspace = st.path.clone();
329            // Default cwd to worktree unless caller set one under the worktree.
330            match &req.cwd {
331                None => req.cwd = Some(st.path.clone()),
332                Some(cwd) => {
333                    if let Ok(rel) = cwd.strip_prefix(&st.origin) {
334                        req.cwd = Some(st.path.join(rel));
335                    } else if !cwd.starts_with(&st.path) && !cwd.is_absolute() {
336                        req.cwd = Some(st.path.join(cwd));
337                    }
338                }
339            }
340        }
341        self.inner
342            .spawn(space_id, &inner_policy, req, sink)
343            .await
344    }
345
346    async fn destroy(&self, policy: &Policy, sink: Arc<dyn RecordSink>) -> EnforceResult<()> {
347        let _ = self.inner.destroy(policy, sink).await;
348        if self.opts.cleanup_on_destroy {
349            if let Ok(mut guard) = self.state.lock() {
350                if let Some(st) = guard.take() {
351                    cleanup_worktree(&st);
352                    info!(path = %st.path.display(), "worktree cleaned up");
353                }
354            }
355        }
356        self.applied.store(false, Ordering::Release);
357        Ok(())
358    }
359}
360
361#[cfg(test)]
362mod tests {
363    use super::*;
364    use keel_policy::profile_workspace;
365    use keel_record::MemorySink;
366
367    #[tokio::test]
368    async fn creates_directory_worktree() {
369        let origin = tempfile::tempdir().unwrap();
370        // Not a git repo → directory fallback.
371        let policy = profile_workspace(origin.path()).unwrap();
372        let root = tempfile::tempdir().unwrap();
373        let backend = WorktreeBackend::with_options(WorktreeOptions {
374            worktrees_root: Some(root.path().to_path_buf()),
375            cleanup_on_destroy: true,
376            prefer_git: true,
377        });
378        let sink = Arc::new(MemorySink::new());
379        backend.apply(&policy, sink.clone()).await.unwrap();
380        let wt = backend.worktree_path().unwrap();
381        assert!(wt.is_dir());
382        assert!(wt.join(".keel-worktree-origin").is_file());
383        backend.destroy(&policy, sink).await.unwrap();
384        assert!(!wt.exists() || !self_exists(&wt));
385    }
386
387    fn self_exists(p: &Path) -> bool {
388        p.exists()
389    }
390}