1mod git;
11
12use git::{
13 best_effort_remove_worktree, collect_diff_stat, git_common_dir, git_dir, git_toplevel,
14 is_pid_alive, map_relative_path, parse_nul_paths, parse_porcelain_z, remove_clean_worktree,
15 run_git_bytes, run_git_stdout, snapshot_working_tree, validate_worktree_git_dir,
16 verify_head_exists,
17};
18use merry_core::SessionId;
19use merry_runtime::{
20 ChildWorkspaceFinalization, ChildWorkspaceLifecycle, PathAccess, PathAccessRule,
21 PathAccessRuleSource, SubagentWorktreeBase, SubagentWorktreeView,
22};
23use std::{
24 collections::BTreeSet,
25 env, fs,
26 path::{Path, PathBuf},
27 sync::{
28 Arc, OnceLock,
29 atomic::{AtomicU64, Ordering},
30 },
31 time::{Duration, SystemTime, UNIX_EPOCH},
32};
33use thiserror::Error;
34
35const MAX_UNTRACKED_FILE_BYTES: u64 = 5 * 1024 * 1024;
37const MAX_UNTRACKED_TOTAL_BYTES: u64 = 20 * 1024 * 1024;
39const SETUP_GIT_TIMEOUT: Duration = Duration::from_secs(15);
41const FINALIZE_GIT_TIMEOUT: Duration = Duration::from_secs(4);
43const INSTANCE_PID_FILE: &str = ".pid";
45const REPO_MARKER_SUFFIX: &str = ".repo";
47
48#[derive(Debug, Error)]
50pub enum WorktreeError {
51 #[error("worktree isolation requires a Git repository at `{}`: {detail}", workspace.display())]
53 NotAGitRepository { workspace: PathBuf, detail: String },
54 #[error("worktree isolation requires at least one commit (HEAD) in `{}`: {detail}", repo_root.display())]
56 NoHeadCommit { repo_root: PathBuf, detail: String },
57 #[error("git command `{command}` failed: {detail}")]
59 GitCommandFailed { command: String, detail: String },
60 #[error("{context}: {source}")]
62 Io {
63 context: String,
64 #[source]
65 source: std::io::Error,
66 },
67 #[error(
69 "refusing unsafe worktree gitdir `{}` outside `{}`",
70 path.display(),
71 common_dir.display()
72 )]
73 InvalidWorktreeAdminDir { path: PathBuf, common_dir: PathBuf },
74 #[error("failed to reattach retained worktree `{}`: {reason}", path.display())]
76 ReattachFailed { path: PathBuf, reason: String },
77}
78
79pub(crate) struct PreparedWorktree {
81 pub(crate) child_workspace_root: PathBuf,
83 pub(crate) git_common_dir: PathBuf,
85 pub(crate) worktree_git_dir: PathBuf,
87 pub(crate) lifecycle: Arc<dyn ChildWorkspaceLifecycle>,
89}
90
91impl PreparedWorktree {
92 #[must_use]
99 pub(crate) fn sandbox_path_rules(&self, workspace_writable: bool) -> Vec<PathAccessRule> {
100 let mut rules = vec![PathAccessRule::new(
101 self.git_common_dir.clone(),
102 PathAccess::ReadOnly,
103 PathAccessRuleSource::GitMetadataBaseline,
104 )];
105 if workspace_writable {
106 rules.push(PathAccessRule::new(
107 self.worktree_git_dir.clone(),
108 PathAccess::ReadWrite,
109 PathAccessRuleSource::GitMetadataBaseline,
110 ));
111 }
112 rules
113 }
114}
115
116#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
118pub struct WorktreeGcReport {
119 pub removed_instances: usize,
121 pub removed_worktrees: usize,
123 pub pruned_repos: usize,
125 pub skipped_live_instances: usize,
127}
128
129#[derive(Debug, Clone)]
131pub struct WorktreeIsolationManager {
132 base_dir: PathBuf,
133 instance_id: String,
134}
135
136impl Default for WorktreeIsolationManager {
137 fn default() -> Self {
138 Self::new()
139 }
140}
141
142impl WorktreeIsolationManager {
143 #[must_use]
147 pub fn new() -> Self {
148 Self {
149 base_dir: default_worktree_base_dir(),
150 instance_id: process_instance_id().to_owned(),
151 }
152 }
153
154 #[must_use]
156 pub fn with_base_dir(base_dir: impl Into<PathBuf>) -> Self {
157 Self {
158 base_dir: base_dir.into(),
159 instance_id: process_instance_id().to_owned(),
160 }
161 }
162
163 #[must_use]
165 pub fn base_dir(&self) -> &Path {
166 &self.base_dir
167 }
168
169 #[must_use]
171 pub fn instance_dir(&self) -> PathBuf {
172 self.base_dir.join(&self.instance_id)
173 }
174
175 pub(crate) fn prepare_or_reattach(
178 &self,
179 workspace_root: &Path,
180 session_id: &SessionId,
181 agent_id: &str,
182 base: SubagentWorktreeBase,
183 existing: Option<&SubagentWorktreeView>,
184 ) -> Result<PreparedWorktree, WorktreeError> {
185 if let Some(existing) = existing
186 && existing.retained
187 {
188 let existing_path = PathBuf::from(&existing.path);
189 if existing_path.is_dir() {
190 return self.reattach_worktree(
191 workspace_root,
192 &existing_path,
193 &existing.baseline_oid,
194 );
195 }
196 }
197 self.create_worktree(workspace_root, session_id, agent_id, base)
198 }
199
200 fn reattach_worktree(
201 &self,
202 workspace_root: &Path,
203 worktree_path: &Path,
204 baseline_oid: &str,
205 ) -> Result<PreparedWorktree, WorktreeError> {
206 let canonical_workspace =
207 fs::canonicalize(workspace_root).unwrap_or_else(|_| workspace_root.to_path_buf());
208 let repo_toplevel = git_toplevel(&canonical_workspace)?;
209 let workspace_subpath = canonical_workspace
210 .strip_prefix(&repo_toplevel)
211 .ok()
212 .filter(|sub| !sub.as_os_str().is_empty())
213 .map(Path::to_path_buf);
214
215 let canonical_worktree =
216 fs::canonicalize(worktree_path).unwrap_or_else(|_| worktree_path.to_path_buf());
217 let git_common_dir =
218 git_common_dir(&canonical_worktree).map_err(|error| WorktreeError::ReattachFailed {
219 path: canonical_worktree.clone(),
220 reason: error.to_string(),
221 })?;
222 let worktree_git_dir =
223 git_dir(&canonical_worktree).map_err(|error| WorktreeError::ReattachFailed {
224 path: canonical_worktree.clone(),
225 reason: error.to_string(),
226 })?;
227 validate_worktree_git_dir(&worktree_git_dir, &git_common_dir)?;
228
229 let child_workspace_root = match &workspace_subpath {
230 Some(sub) => canonical_worktree.join(sub),
231 None => canonical_worktree.clone(),
232 };
233 let repo_marker_path = sibling_repo_marker(&canonical_worktree);
234 let lifecycle: Arc<dyn ChildWorkspaceLifecycle> = Arc::new(WorktreeLifecycle {
235 repo_toplevel,
236 worktree_path: canonical_worktree,
237 repo_marker_path,
238 baseline_oid: baseline_oid.to_owned(),
239 workspace_subpath,
240 });
241 Ok(PreparedWorktree {
242 child_workspace_root,
243 git_common_dir,
244 worktree_git_dir,
245 lifecycle,
246 })
247 }
248
249 fn create_worktree(
250 &self,
251 workspace_root: &Path,
252 session_id: &SessionId,
253 agent_id: &str,
254 base: SubagentWorktreeBase,
255 ) -> Result<PreparedWorktree, WorktreeError> {
256 let canonical_workspace =
257 fs::canonicalize(workspace_root).unwrap_or_else(|_| workspace_root.to_path_buf());
258 let repo_toplevel = git_toplevel(&canonical_workspace)?;
259 let git_common_dir = git_common_dir(&repo_toplevel)?;
260 verify_head_exists(&repo_toplevel)?;
261
262 let workspace_subpath = canonical_workspace
263 .strip_prefix(&repo_toplevel)
264 .ok()
265 .filter(|sub| !sub.as_os_str().is_empty())
266 .map(Path::to_path_buf);
267
268 let instance_dir = self.instance_dir();
269 ensure_instance_pid_file(&instance_dir)?;
270
271 let session_dir = instance_dir.join(sanitize_path_component(session_id.as_str()));
272 fs::create_dir_all(&session_dir).map_err(|source| WorktreeError::Io {
273 context: format!(
274 "failed to create worktree session directory `{}`",
275 session_dir.display()
276 ),
277 source,
278 })?;
279
280 let base_name = sanitize_path_component(agent_id);
281 let worktree_path = allocate_unique_worktree_path(&session_dir, &base_name);
282 let repo_marker_path = sibling_repo_marker(&worktree_path);
283
284 let worktree_arg = worktree_path.to_string_lossy().into_owned();
285 run_git_stdout(
286 &repo_toplevel,
287 &["worktree", "add", "--detach", &worktree_arg, "HEAD"],
288 SETUP_GIT_TIMEOUT,
289 )?;
290
291 let setup_result = (|| -> Result<PreparedWorktree, WorktreeError> {
292 let canonical_worktree =
293 fs::canonicalize(&worktree_path).unwrap_or_else(|_| worktree_path.clone());
294 let worktree_git_dir = git_dir(&canonical_worktree)?;
295 validate_worktree_git_dir(&worktree_git_dir, &git_common_dir)?;
296
297 let _ = fs::write(
300 &repo_marker_path,
301 format!("{}\n", repo_toplevel.to_string_lossy()),
302 );
303
304 if base == SubagentWorktreeBase::WorkingTree {
305 snapshot_working_tree(&repo_toplevel, &canonical_worktree)?;
306 }
307 let baseline_oid = run_git_stdout(
308 &canonical_worktree,
309 &["rev-parse", "HEAD"],
310 SETUP_GIT_TIMEOUT,
311 )?
312 .trim()
313 .to_owned();
314
315 let child_workspace_root = match &workspace_subpath {
316 Some(sub) => canonical_worktree.join(sub),
317 None => canonical_worktree.clone(),
318 };
319 let lifecycle: Arc<dyn ChildWorkspaceLifecycle> = Arc::new(WorktreeLifecycle {
320 repo_toplevel: repo_toplevel.clone(),
321 worktree_path: canonical_worktree,
322 repo_marker_path: repo_marker_path.clone(),
323 baseline_oid,
324 workspace_subpath,
325 });
326 Ok(PreparedWorktree {
327 child_workspace_root,
328 git_common_dir,
329 worktree_git_dir,
330 lifecycle,
331 })
332 })();
333
334 if setup_result.is_err() {
335 best_effort_remove_worktree(&repo_toplevel, &worktree_path, &repo_marker_path);
336 }
337 setup_result
338 }
339}
340
341struct WorktreeLifecycle {
343 repo_toplevel: PathBuf,
344 worktree_path: PathBuf,
345 repo_marker_path: PathBuf,
346 baseline_oid: String,
347 workspace_subpath: Option<PathBuf>,
348}
349
350impl ChildWorkspaceLifecycle for WorktreeLifecycle {
351 fn metadata(&self) -> SubagentWorktreeView {
352 SubagentWorktreeView {
353 path: self.worktree_path.to_string_lossy().into_owned(),
354 baseline_oid: self.baseline_oid.clone(),
355 diff_stat: None,
356 retained: true,
357 }
358 }
359
360 fn finalize(&self, allow_cleanup: bool) -> ChildWorkspaceFinalization {
361 let mut changed_set = BTreeSet::new();
362 let mut untracked_paths = Vec::new();
363 let mut uncertain = false;
364
365 match run_git_bytes(
366 &self.worktree_path,
367 &["status", "--porcelain=v1", "-z"],
368 FINALIZE_GIT_TIMEOUT,
369 ) {
370 Ok(bytes) => {
371 for (status_xy, rel_path) in parse_porcelain_z(&bytes) {
372 if status_xy == "??" {
373 untracked_paths.push(rel_path.clone());
374 }
375 if let Some(mapped) =
376 map_relative_path(&rel_path, self.workspace_subpath.as_deref())
377 {
378 changed_set.insert(mapped);
379 }
380 }
381 }
382 Err(error) => {
383 tracing::warn!(
384 worktree = %self.worktree_path.display(),
385 error = %error,
386 "git status failed during worktree finalization; failing toward keep"
387 );
388 uncertain = true;
389 }
390 }
391
392 match run_git_bytes(
393 &self.worktree_path,
394 &["diff", "--name-only", "-z", &self.baseline_oid],
395 FINALIZE_GIT_TIMEOUT,
396 ) {
397 Ok(bytes) => {
398 for rel_path in parse_nul_paths(&bytes) {
399 if let Some(mapped) =
400 map_relative_path(&rel_path, self.workspace_subpath.as_deref())
401 {
402 changed_set.insert(mapped);
403 }
404 }
405 }
406 Err(error) => {
407 tracing::warn!(
408 worktree = %self.worktree_path.display(),
409 error = %error,
410 "git diff --name-only failed during worktree finalization; failing toward keep"
411 );
412 uncertain = true;
413 }
414 }
415
416 let head_moved = match run_git_stdout(
417 &self.worktree_path,
418 &["rev-parse", "HEAD"],
419 FINALIZE_GIT_TIMEOUT,
420 ) {
421 Ok(head) => head.trim() != self.baseline_oid,
422 Err(error) => {
423 tracing::warn!(
424 worktree = %self.worktree_path.display(),
425 error = %error,
426 "git rev-parse HEAD failed during worktree finalization; failing toward keep"
427 );
428 uncertain = true;
429 false
430 }
431 };
432
433 let changed_paths: Vec<String> = changed_set.into_iter().collect();
434 let has_changes = !changed_paths.is_empty() || head_moved;
435
436 if uncertain || has_changes || !allow_cleanup {
437 let diff_stat = if has_changes {
438 collect_diff_stat(&self.worktree_path, &self.baseline_oid, &untracked_paths)
439 } else {
440 None
441 };
442 return ChildWorkspaceFinalization {
443 changed_paths,
444 worktree: Some(SubagentWorktreeView {
445 path: self.worktree_path.to_string_lossy().into_owned(),
446 baseline_oid: self.baseline_oid.clone(),
447 diff_stat,
448 retained: true,
449 }),
450 };
451 }
452
453 let removed = remove_clean_worktree(
455 &self.repo_toplevel,
456 &self.worktree_path,
457 &self.repo_marker_path,
458 );
459 ChildWorkspaceFinalization {
460 changed_paths: Vec::new(),
461 worktree: Some(SubagentWorktreeView {
462 path: self.worktree_path.to_string_lossy().into_owned(),
463 baseline_oid: self.baseline_oid.clone(),
464 diff_stat: None,
465 retained: !removed,
466 }),
467 }
468 }
469}
470
471pub fn cleanup_orphaned_worktrees_default() -> WorktreeGcReport {
474 cleanup_orphaned_worktrees(&default_worktree_base_dir())
475}
476
477pub fn cleanup_orphaned_worktrees(base_dir: &Path) -> WorktreeGcReport {
480 let mut report = WorktreeGcReport::default();
481 let Ok(entries) = fs::read_dir(base_dir) else {
482 return report;
483 };
484 let mut repos_to_prune = BTreeSet::new();
485 for entry in entries.flatten() {
486 let instance_dir = entry.path();
487 if !instance_dir.is_dir() {
488 continue;
489 }
490 let pid_path = instance_dir.join(INSTANCE_PID_FILE);
491 let Ok(pid_text) = fs::read_to_string(&pid_path) else {
492 report.skipped_live_instances += 1;
494 continue;
495 };
496 let Ok(pid) = pid_text.trim().parse::<u32>() else {
497 report.skipped_live_instances += 1;
498 continue;
499 };
500 if is_pid_alive(pid) {
501 report.skipped_live_instances += 1;
502 continue;
503 }
504
505 if let Ok(session_entries) = fs::read_dir(&instance_dir) {
507 for session_entry in session_entries.flatten() {
508 let session_dir = session_entry.path();
509 if !session_dir.is_dir() {
510 continue;
511 }
512 if let Ok(wt_entries) = fs::read_dir(&session_dir) {
513 for wt_entry in wt_entries.flatten() {
514 let path = wt_entry.path();
515 let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
516 continue;
517 };
518 let Some(worktree_name) = name.strip_suffix(REPO_MARKER_SUFFIX) else {
519 continue;
520 };
521 let Ok(repo_text) = fs::read_to_string(&path) else {
522 continue;
523 };
524 let repo_root = PathBuf::from(repo_text.trim());
525 if repo_root.is_dir() {
526 repos_to_prune.insert(repo_root.clone());
527 let worktree_dir = session_dir.join(worktree_name);
528 if worktree_dir.exists() {
529 let arg = worktree_dir.to_string_lossy().into_owned();
530 if run_git_stdout(
531 &repo_root,
532 &["worktree", "remove", "--force", &arg],
533 FINALIZE_GIT_TIMEOUT,
534 )
535 .is_ok()
536 {
537 report.removed_worktrees += 1;
538 }
539 }
540 }
541 }
542 }
543 }
544 }
545 if fs::remove_dir_all(&instance_dir).is_ok() {
546 report.removed_instances += 1;
547 }
548 }
549
550 for repo_root in repos_to_prune {
551 if run_git_stdout(&repo_root, &["worktree", "prune"], FINALIZE_GIT_TIMEOUT).is_ok() {
552 report.pruned_repos += 1;
553 }
554 }
555 report
556}
557
558#[must_use]
560pub fn default_worktree_base_dir() -> PathBuf {
561 let xdg_cache = env::var_os("XDG_CACHE_HOME").map(PathBuf::from);
562 if let Some(path) = xdg_cache.as_deref().filter(|path| path.is_absolute()) {
563 return path.join("merry").join("worktrees");
564 }
565 let local_appdata = env::var_os("LOCALAPPDATA").map(PathBuf::from);
566 if cfg!(windows)
567 && let Some(path) = local_appdata.as_deref().filter(|path| path.is_absolute())
568 {
569 return path.join("merry").join("worktrees");
570 }
571 if let Some(home) = merry_core::host_paths::user_home_dir() {
572 let cache_base = merry_core::host_paths::platform_cache_base(
573 &home,
574 xdg_cache.as_deref(),
575 local_appdata.as_deref(),
576 );
577 return cache_base.join("merry").join("worktrees");
578 }
579 env::temp_dir().join("merry-worktrees")
580}
581
582fn process_instance_id() -> &'static str {
583 static INSTANCE_ID: OnceLock<String> = OnceLock::new();
584 INSTANCE_ID.get_or_init(|| {
585 let millis = SystemTime::now()
586 .duration_since(UNIX_EPOCH)
587 .map(|d| d.as_millis())
588 .unwrap_or(0);
589 format!("pid-{}-{millis}", std::process::id())
590 })
591}
592
593fn ensure_instance_pid_file(instance_dir: &Path) -> Result<(), WorktreeError> {
594 fs::create_dir_all(instance_dir).map_err(|source| WorktreeError::Io {
595 context: format!(
596 "failed to create worktree instance directory `{}`",
597 instance_dir.display()
598 ),
599 source,
600 })?;
601 let pid_path = instance_dir.join(INSTANCE_PID_FILE);
602 if !pid_path.exists() {
603 fs::write(&pid_path, format!("{}\n", std::process::id())).map_err(|source| {
604 WorktreeError::Io {
605 context: format!("failed to write instance PID file `{}`", pid_path.display()),
606 source,
607 }
608 })?;
609 }
610 Ok(())
611}
612
613fn allocate_unique_worktree_path(session_dir: &Path, base_name: &str) -> PathBuf {
614 static COUNTER: AtomicU64 = AtomicU64::new(1);
615 let primary = session_dir.join(base_name);
616 if !primary.exists() {
617 return primary;
618 }
619 loop {
620 let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
621 let candidate = session_dir.join(format!("{base_name}-{seq}"));
622 if !candidate.exists() {
623 return candidate;
624 }
625 }
626}
627
628fn sibling_repo_marker(worktree_path: &Path) -> PathBuf {
629 let name = worktree_path
630 .file_name()
631 .map(|n| format!("{}{}", n.to_string_lossy(), REPO_MARKER_SUFFIX))
632 .unwrap_or_else(|| format!("worktree{REPO_MARKER_SUFFIX}"));
633 worktree_path.parent().unwrap_or(worktree_path).join(name)
634}
635
636fn sanitize_path_component(raw: &str) -> String {
637 let sanitized: String = raw
638 .chars()
639 .map(|c| {
640 if c.is_ascii_alphanumeric() || matches!(c, '-' | '_') {
641 c
642 } else {
643 '_'
644 }
645 })
646 .take(64)
647 .collect();
648 if sanitized.is_empty() {
649 "subagent".to_owned()
650 } else {
651 sanitized
652 }
653}