koda-sandbox 0.2.19

Capability-aware sandbox layer for Koda — kernel-enforced FS/net/exec policies (refs #934)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
//! Workspace provisioning — separates the "where does the slot write?"
//! decision from the "what can the slot do?" policy.
//!
//! Per #934 §4.6 the sandbox runtime is workspace-agnostic. Provider impls
//! land across phases:
//!
//! | Impl                  | Phase | Backend                              |
//! |-----------------------|-------|--------------------------------------|
//! | [`CwdProvider`]       | 0     | Returns `project_root` as-is         |
//! | [`GitWorktreeProvider`]| 2    | `git worktree add` per sub-agent     |
//! | `ClonefileProvider`   | 4     | macOS APFS `clonefile(2)` (CoW)      |
//! | `OverlayfsProvider`   | 4     | Linux overlayfs inside bwrap         |
//!
//! `ClonefileProvider` lives behind `#[cfg(target_os = "macos")]`, so its
//! intra-doc link is omitted from this table to keep Linux rustdoc happy.
//!
//! The pool selects which provider to use at slot acquisition time, based
//! on agent persona + trust mode + git availability.

use anyhow::{Context, Result};
use async_trait::async_trait;
use std::path::{Path, PathBuf};
use tokio::process::Command;

// ── Trait ────────────────────────────────────────────────────────────────────

/// Workspace lifecycle: provision on slot acquire, release on slot drop.
///
/// `slot_id` is supplied by the pool so providers can name their backing
/// storage deterministically (e.g. `~/.koda/worktrees/<slot_id>`).
#[async_trait]
pub trait WorkspaceProvider: Send + Sync {
    /// Provision a writable view for a new slot. Returns the path the
    /// slot should treat as its writable root.
    async fn provision(&self, slot_id: &str) -> Result<PathBuf>;

    /// Release on slot drop. Returns `Some(hint)` when there are unsaved
    /// changes worth surfacing to the user.
    async fn release(&self, slot_id: &str, path: &Path) -> Result<Option<String>>;
}

// ── CwdProvider ──────────────────────────────────────────────────────────────

/// No-op provider: hands back the project root unchanged. Suitable for:
///
/// - Read-only slots (plan/explore/verify personas)
/// - Trust-mode `Auto` on non-git projects
/// - Any scenario where copy-on-write isn't worth the latency
#[derive(Debug, Clone)]
pub struct CwdProvider {
    project_root: PathBuf,
}

impl CwdProvider {
    /// Construct a provider rooted at the given project directory.
    pub fn new(project_root: impl Into<PathBuf>) -> Self {
        Self {
            project_root: project_root.into(),
        }
    }
}

#[async_trait]
impl WorkspaceProvider for CwdProvider {
    async fn provision(&self, _slot_id: &str) -> Result<PathBuf> {
        Ok(self.project_root.clone())
    }

    async fn release(&self, _slot_id: &str, _path: &Path) -> Result<Option<String>> {
        Ok(None)
    }
}

// ── GitWorktreeProvider ───────────────────────────────────────────────────────

/// Isolated workspace via `git worktree add`.
///
/// Each slot gets its own branch (`koda/wt/<agent>-<short-id>`) and a
/// matching worktree directory at `.koda/worktrees/<slot_id>`.
///
/// ## Release behaviour
///
/// | Worktree state | Action                                               |
/// |----------------|------------------------------------------------------|
/// | Clean          | `git worktree remove --force`; delete ephemeral branch |
/// | Dirty          | `git add -A && git commit`; `git worktree remove --force`; **keep branch**; return hint |
///
/// The branch is the permanent record of what the sub-agent did. Users
/// can inspect, merge, or discard it at their discretion:
///
/// ```text
/// Review:  git diff main...koda/wt/<agent>-<id>
/// Merge:   git merge koda/wt/<agent>-<id>
/// Discard: git branch -D koda/wt/<agent>-<id>
/// ```
///
/// ## Fallback
///
/// If `git` is not in `PATH` or the project is not a git repo,
/// `provision` returns the `project_root` unchanged and `release` is a
/// no-op. No error is surfaced — the sub-agent just runs without
/// worktree isolation.
#[derive(Debug, Clone)]
pub struct GitWorktreeProvider {
    project_root: PathBuf,
    agent_name: String,
}

impl GitWorktreeProvider {
    /// Create a provider that will issue worktrees under `project_root`.
    ///
    /// `agent_name` is used for the human-readable branch prefix.
    pub fn new(project_root: impl Into<PathBuf>, agent_name: impl Into<String>) -> Self {
        Self {
            project_root: project_root.into(),
            agent_name: agent_name.into(),
        }
    }

    // ── helpers ──────────────────────────────────────────────────────────────

    /// Sanitise `agent_name` for use in a git branch segment.
    ///
    /// Git branch names can contain most characters but not spaces,
    /// `~`, `^`, `:`, `?`, `*`, `\`, `..`, or leading `-`. We replace
    /// anything outside `[a-zA-Z0-9._-]` with `-` and strip leading `-`.
    fn safe_agent(&self) -> String {
        let sanitised: String = self
            .agent_name
            .chars()
            .map(|c| {
                if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' {
                    c
                } else {
                    '-'
                }
            })
            .collect();
        let trimmed = sanitised.trim_matches('-');
        if trimmed.is_empty() {
            "agent".to_string()
        } else {
            // Cap at 30 chars so the full branch name stays reasonable.
            trimmed.chars().take(30).collect()
        }
    }

    /// Build the branch name for a given slot.
    fn branch_name(&self, slot_id: &str) -> String {
        let short = &slot_id[..slot_id.len().min(8)];
        format!("koda/wt/{}-{short}", self.safe_agent())
    }

    /// `true` when git is reachable and the project is inside a git repo.
    async fn is_git_repo(&self) -> bool {
        let Ok(out) = Command::new("git")
            .args(["rev-parse", "--is-inside-work-tree"])
            .current_dir(&self.project_root)
            .output()
            .await
        else {
            return false;
        };
        out.status.success()
    }

    /// Path of the worktree directory for a given slot.
    fn worktree_path(&self, slot_id: &str) -> PathBuf {
        self.project_root
            .join(".koda")
            .join("worktrees")
            .join(slot_id)
    }
}

#[async_trait]
impl WorkspaceProvider for GitWorktreeProvider {
    async fn provision(&self, slot_id: &str) -> Result<PathBuf> {
        // Reject slot_ids that could escape the worktrees directory.
        if slot_id.is_empty() || slot_id.contains('/') || slot_id.contains('\\') {
            anyhow::bail!("Invalid slot_id for worktree: {slot_id:?}");
        }

        if !self.is_git_repo().await {
            tracing::debug!(
                "Not a git repo or git unavailable — skipping worktree isolation for {slot_id}"
            );
            return Ok(self.project_root.clone());
        }

        let wt_path = self.worktree_path(slot_id);
        let branch = self.branch_name(slot_id);

        // Reuse on resume (idempotent).
        if wt_path.exists() {
            tracing::debug!("Reusing existing worktree: {}", wt_path.display());
            return Ok(wt_path);
        }

        std::fs::create_dir_all(wt_path.parent().unwrap_or(&self.project_root))
            .context("Failed to create .koda/worktrees/ directory")?;

        let out = Command::new("git")
            .args([
                "worktree",
                "add",
                "-b",
                &branch,
                &wt_path.to_string_lossy(),
                "HEAD",
            ])
            .current_dir(&self.project_root)
            .output()
            .await
            .context("Failed to spawn git worktree add")?;

        if !out.status.success() {
            let stderr = String::from_utf8_lossy(&out.stderr);
            anyhow::bail!("git worktree add failed: {stderr}");
        }

        tracing::info!(
            "Provisioned worktree {} (branch {branch})",
            wt_path.display()
        );
        Ok(wt_path)
    }

    async fn release(&self, slot_id: &str, path: &Path) -> Result<Option<String>> {
        // Fallback path — provision returned project_root directly.
        if path == self.project_root {
            return Ok(None);
        }

        if !path.exists() {
            return Ok(None);
        }

        let branch = self.branch_name(slot_id);

        // Check for uncommitted changes.
        let status = Command::new("git")
            .args(["status", "--short"])
            .current_dir(path)
            .output()
            .await
            .context("Failed to run git status in worktree")?;
        let is_dirty = !String::from_utf8_lossy(&status.stdout).trim().is_empty();

        if is_dirty {
            // Auto-commit so the work is preserved on the branch.
            Command::new("git")
                .args(["add", "-A"])
                .current_dir(path)
                .output()
                .await
                .context("git add -A in worktree")?;

            let commit_msg = format!("koda: sub-agent '{}' changes", self.agent_name);
            let committed = Command::new("git")
                .args([
                    "-c",
                    "user.name=koda",
                    "-c",
                    "user.email=koda@localhost",
                    "commit",
                    "-m",
                    &commit_msg,
                ])
                .current_dir(path)
                .output()
                .await
                .context("git commit in worktree")?;

            if !committed.status.success() {
                let stderr = String::from_utf8_lossy(&committed.stderr);
                tracing::warn!("Worktree auto-commit failed: {stderr}");
            }

            // Remove the worktree dir but keep the branch.
            self.remove_worktree(path).await;

            let hint = format!(
                "🌿 Sub-agent '{}' left changes on branch {branch}\n\
                 Review:  git diff HEAD...{branch}\n\
                 Merge:   git merge {branch}\n\
                 Discard: git branch -D {branch}",
                self.agent_name
            );
            tracing::info!("Worktree committed to branch {branch}");
            return Ok(Some(hint));
        }

        // Clean — remove worktree and ephemeral branch.
        self.remove_worktree(path).await;
        let _ = Command::new("git")
            .args(["branch", "-D", &branch])
            .current_dir(&self.project_root)
            .output()
            .await;

        tracing::info!("Removed clean worktree for slot {slot_id}");
        Ok(None)
    }
}

impl GitWorktreeProvider {
    /// Best-effort `git worktree remove --force` with rm-rf fallback.
    async fn remove_worktree(&self, path: &Path) {
        let out = Command::new("git")
            .args(["worktree", "remove", "--force", &path.to_string_lossy()])
            .current_dir(&self.project_root)
            .output()
            .await;

        match out {
            Ok(o) if o.status.success() => {}
            Ok(o) => {
                let stderr = String::from_utf8_lossy(&o.stderr);
                tracing::warn!("git worktree remove failed ({stderr}), falling back to rm -rf");
                let _ = tokio::fs::remove_dir_all(path).await;
            }
            Err(e) => {
                tracing::warn!("Could not spawn git worktree remove: {e}");
                let _ = tokio::fs::remove_dir_all(path).await;
            }
        }
    }
}

// ── ClonefileProvider (macOS) ───────────────────────────────────────────

/// Workspace via APFS `clonefile(2)` — the speed champion (Phase 4d of #934).
///
/// Each slot gets a copy-on-write reflink of the project tree at
/// `~/.koda/clones/<project-hash>/<slot_id>/`. Provisioning is O(metadata),
/// not O(content): a 5 GB monorepo clones in **~10 ms** instead of the
/// 1-5 seconds [`GitWorktreeProvider`] takes for a fresh worktree.
///
/// ## Why the clones live OUTSIDE the project root
///
/// `clonefile(2)` is recursive. If clones lived under `<project>/.koda/clones/`,
/// every slot's clone would *contain* every previous slot's clone (matryoshka).
/// Putting them under `~/.koda/clones/<project-hash>/` keeps the source tree
/// pristine and the clone footprint flat.
///
/// `<project-hash>` is a SHA-256 of the canonical project root path,
/// truncated to 16 hex chars. It collides only across projects with the
/// same canonical absolute path, which is impossible in practice.
///
/// ## Failure modes
///
/// - **Non-APFS filesystem** (`ENOTSUP`): caller must fall back to
///   [`GitWorktreeProvider`] or [`CwdProvider`]. The error message
///   names this explicitly so users aren't left guessing.
/// - **Cross-volume** (`EXDEV`): same as above. Happens when `$HOME`
///   and the project live on different APFS volumes (rare on default
///   macOS installs; common on dev VMs with mounted source trees).
/// - **Already exists**: idempotent — returns the existing path.
///   Lets `acquire` for a slot_id that previously crashed mid-flight
///   resume from where it left off.
///
/// We deliberately **do not** auto-fall-back to `GitWorktreeProvider`.
/// The user explicitly wired in `ClonefileProvider` (it's opt-in for at
/// least one release per the issue's roadmap); silently downgrading
/// would hide setup misconfigurations and make perf-debug confusing.
#[cfg(target_os = "macos")]
#[derive(Debug, Clone)]
pub struct ClonefileProvider {
    project_root: PathBuf,
    /// Root under which all this provider's clones live, as in
    /// `<clones_root>/<slot_id>`. Defaults to
    /// `~/.koda/clones/<sha256(project_root)[..16]>/`. Tests override
    /// this so they don't pollute the user's home dir.
    clones_root: PathBuf,
}

#[cfg(target_os = "macos")]
impl ClonefileProvider {
    /// Standard constructor. Derives `clones_root` from `$HOME` and a
    /// 16-hex-char SHA-256 of the canonical project path.
    ///
    /// Returns `Err` if `$HOME` is unset or the project path can't be
    /// canonicalized — both indicate a setup problem the caller must
    /// surface, not silently work around.
    pub fn new(project_root: impl Into<PathBuf>) -> Result<Self> {
        let project_root = project_root.into();
        let canonical = project_root
            .canonicalize()
            .with_context(|| format!("canonicalize project_root {}", project_root.display()))?;
        let home = std::env::var_os("HOME")
            .map(PathBuf::from)
            .context("$HOME not set; cannot derive ClonefileProvider clones_root")?;
        let hash = Self::project_hash(&canonical);
        let clones_root = home.join(".koda").join("clones").join(hash);
        Ok(Self {
            project_root: canonical,
            clones_root,
        })
    }

    /// Test/advanced constructor: explicit `clones_root`. Lets tests
    /// point at a tempdir without mutating `$HOME`.
    pub fn with_clones_root(
        project_root: impl Into<PathBuf>,
        clones_root: impl Into<PathBuf>,
    ) -> Result<Self> {
        let project_root = project_root.into();
        let canonical = project_root
            .canonicalize()
            .with_context(|| format!("canonicalize project_root {}", project_root.display()))?;
        Ok(Self {
            project_root: canonical,
            clones_root: clones_root.into(),
        })
    }

    /// Where the clone for `slot_id` lives.
    fn clone_path(&self, slot_id: &str) -> PathBuf {
        self.clones_root.join(slot_id)
    }

    /// Stable 16-hex-char FNV-1a hash of the canonical project path.
    /// Stable means: same path → same hash across processes / restarts,
    /// so clones from a previous koda session can be resumed.
    ///
    /// FNV-1a (not SipHash) because `std::hash::DefaultHasher` is
    /// seeded with a random value per process, which would defeat
    /// cross-session resume. We don't need cryptographic strength
    /// here — collision space is "projects on this developer's
    /// machine," which is dozens at most.
    fn project_hash(canonical: &Path) -> String {
        use std::os::unix::ffi::OsStrExt;
        const FNV_OFFSET: u64 = 0xcbf29ce484222325;
        const FNV_PRIME: u64 = 0x100000001b3;
        let mut hash = FNV_OFFSET;
        for byte in canonical.as_os_str().as_bytes() {
            hash ^= u64::from(*byte);
            hash = hash.wrapping_mul(FNV_PRIME);
        }
        format!("{hash:016x}")
    }

    /// Internal: actually invoke `clonefile(2)`. Synchronous; callers
    /// must wrap in `tokio::task::spawn_blocking`. Translates errno
    /// into messages that name the failure mode and the recommended
    /// fallback.
    fn clonefile_sync(src: &Path, dst: &Path) -> Result<()> {
        use std::ffi::CString;
        use std::os::unix::ffi::OsStrExt;

        let src_c = CString::new(src.as_os_str().as_bytes())
            .with_context(|| format!("src path contains NUL: {}", src.display()))?;
        let dst_c = CString::new(dst.as_os_str().as_bytes())
            .with_context(|| format!("dst path contains NUL: {}", dst.display()))?;

        // SAFETY: both pointers are valid CStrings owned for the
        // duration of the call; libc::clonefile takes them by const
        // pointer and copies what it needs synchronously.
        let rc = unsafe { libc::clonefile(src_c.as_ptr(), dst_c.as_ptr(), 0) };
        if rc == 0 {
            return Ok(());
        }

        let err = std::io::Error::last_os_error();
        let raw = err.raw_os_error().unwrap_or(0);
        // Translate the well-known errno values into actionable messages.
        // `ENOTSUP` (45) and `EXDEV` (18) are the ones users actually hit;
        // everything else falls through to the generic message.
        let msg = match raw {
            libc::ENOTSUP => format!(
                "clonefile({}, {}) returned ENOTSUP — destination volume is not APFS. \
                 Use GitWorktreeProvider or CwdProvider on this volume.",
                src.display(),
                dst.display()
            ),
            libc::EXDEV => format!(
                "clonefile({}, {}) returned EXDEV — source and destination are on \
                 different volumes. Either move ~/.koda onto the same volume as the \
                 project, or use GitWorktreeProvider.",
                src.display(),
                dst.display()
            ),
            _ => format!(
                "clonefile({}, {}) failed: {err} (errno {raw})",
                src.display(),
                dst.display()
            ),
        };
        anyhow::bail!(msg)
    }
}

#[cfg(target_os = "macos")]
#[async_trait]
impl WorkspaceProvider for ClonefileProvider {
    async fn provision(&self, slot_id: &str) -> Result<PathBuf> {
        // Same slot_id sanity as GitWorktreeProvider: empty or
        // path-separator-bearing slot_ids would let a caller escape
        // the clones_root directory.
        if slot_id.is_empty() || slot_id.contains('/') || slot_id.contains('\\') {
            anyhow::bail!("Invalid slot_id for clonefile: {slot_id:?}");
        }

        let dst = self.clone_path(slot_id);

        // Idempotent resume: if the clone already exists, reuse it.
        // Matches GitWorktreeProvider's behavior so callers can retry
        // a crashed slot without first running release().
        if dst.exists() {
            tracing::debug!("Reusing existing clone: {}", dst.display());
            return Ok(dst);
        }

        // Ensure the parent dir exists; clonefile won't create it.
        if let Some(parent) = dst.parent() {
            tokio::fs::create_dir_all(parent)
                .await
                .with_context(|| format!("create clones_root {}", parent.display()))?;
        }

        // clonefile(2) is synchronous. Wrap in spawn_blocking so we
        // don't park the tokio worker on a 5 GB metadata clone.
        let src = self.project_root.clone();
        let dst_clone = dst.clone();
        tokio::task::spawn_blocking(move || Self::clonefile_sync(&src, &dst_clone))
            .await
            .context("spawn_blocking for clonefile")??;

        tracing::info!("Provisioned clone {} for slot {slot_id}", dst.display());
        Ok(dst)
    }

    async fn release(&self, slot_id: &str, path: &Path) -> Result<Option<String>> {
        // Defense in depth: only delete if `path` is genuinely under
        // our clones_root. A bug in caller code that hands us
        // `project_root` would otherwise rm -rf the user's source.
        let canonical = match path.canonicalize() {
            Ok(c) => c,
            Err(_) => return Ok(None), // already gone
        };
        // Canonicalize `clones_root` for the comparison too — on macOS,
        // `/var` is a symlink to `/private/var`, so a non-canonicalized
        // `starts_with` check would spuriously refuse legitimate releases
        // when `clones_root` is under a tempdir. We tolerate the case
        // where `clones_root` doesn't yet exist (release-before-any-
        // provision) by treating it as "nothing to compare against, so
        // refuse" — safer than guessing.
        let canonical_root = self.clones_root.canonicalize().with_context(|| {
            format!(
                "canonicalize clones_root {} for release safety check",
                self.clones_root.display()
            )
        })?;
        if !canonical.starts_with(&canonical_root) {
            anyhow::bail!(
                "refusing to release {} — not under clones_root {}",
                canonical.display(),
                canonical_root.display()
            );
        }

        // Best-effort removal. CoW means free space comes back
        // automatically as soon as the inode refcount hits zero.
        if let Err(e) = tokio::fs::remove_dir_all(&canonical).await {
            // EBUSY / EACCES on individual files inside the clone
            // shouldn't tank the whole release — log and move on.
            tracing::warn!(
                "clonefile release of slot {slot_id} at {} hit error: {e}",
                canonical.display()
            );
        }
        Ok(None)
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    // ── CwdProvider ──────────────────────────────────────────────────────────

    #[tokio::test]
    async fn cwd_provider_returns_root_unchanged() {
        let root = PathBuf::from("/tmp/some-project");
        let p = CwdProvider::new(&root);
        assert_eq!(p.provision("slot-1").await.unwrap(), root);
    }

    #[tokio::test]
    async fn cwd_provider_release_is_noop() {
        let p = CwdProvider::new("/tmp/x");
        assert!(
            p.release("slot-1", Path::new("/tmp/x"))
                .await
                .unwrap()
                .is_none()
        );
    }

    #[tokio::test]
    async fn cwd_provider_provision_is_idempotent() {
        let p = CwdProvider::new("/tmp/x");
        let a = p.provision("slot-1").await.unwrap();
        let b = p.provision("slot-1").await.unwrap();
        assert_eq!(a, b);
    }

    // ── GitWorktreeProvider helpers ───────────────────────────────────────────

    #[test]
    fn safe_agent_strips_bad_chars() {
        let p = GitWorktreeProvider::new("/tmp/proj", "my agent/name!");
        // spaces, slashes, and punctuation become hyphens; trailing hyphens stripped
        assert_eq!(p.safe_agent(), "my-agent-name");
        // all-punctuation collapses to the fallback
        let p2 = GitWorktreeProvider::new("/tmp/proj", "!!!");
        assert_eq!(p2.safe_agent(), "agent");
    }

    #[test]
    fn branch_name_is_readable() {
        let p = GitWorktreeProvider::new("/tmp/proj", "refactor");
        let b = p.branch_name("abcdef1234567890");
        assert_eq!(b, "koda/wt/refactor-abcdef12");
    }

    #[test]
    fn invalid_slot_id_rejected() {
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        let p = GitWorktreeProvider::new("/tmp/x", "agent");
        rt.block_on(async {
            assert!(p.provision("").await.is_err());
            assert!(p.provision("foo/bar").await.is_err());
            assert!(p.provision("foo\\bar").await.is_err());
        });
    }

    // ── GitWorktreeProvider end-to-end (requires git in PATH) ────────────────

    async fn init_repo(path: &Path) {
        for args in [
            vec!["init"],
            vec![
                "-c",
                "user.name=test",
                "-c",
                "user.email=t@t",
                "commit",
                "--allow-empty",
                "-m",
                "init",
            ],
        ] {
            Command::new("git")
                .args(&args)
                .current_dir(path)
                .output()
                .await
                .unwrap();
        }
    }

    #[tokio::test]
    async fn provision_not_git_repo_falls_back() {
        let tmp = tempfile::tempdir().unwrap();
        let p = GitWorktreeProvider::new(tmp.path(), "agent");
        let result = p.provision("slot-abc").await.unwrap();
        assert_eq!(result, tmp.path());
    }

    #[tokio::test]
    async fn provision_in_git_repo() {
        let tmp = tempfile::tempdir().unwrap();
        init_repo(tmp.path()).await;

        let p = GitWorktreeProvider::new(tmp.path(), "my-agent");
        let wt = p.provision("slot-001").await.unwrap();

        assert!(wt.exists());
        assert!(wt.ends_with("slot-001"));
        // Should have a git HEAD inside the worktree
        assert!(
            wt.join(".git").exists() || wt.join("HEAD").exists() || {
                // git ≥2.5 worktrees have a .git file (not dir) pointing at main
                std::fs::read_to_string(wt.join(".git"))
                    .map(|s| s.contains("gitdir"))
                    .unwrap_or(false)
            }
        );
    }

    #[tokio::test]
    async fn provision_reuses_existing_worktree() {
        let tmp = tempfile::tempdir().unwrap();
        init_repo(tmp.path()).await;

        let p = GitWorktreeProvider::new(tmp.path(), "agent");
        let a = p.provision("slot-reuse").await.unwrap();
        let b = p.provision("slot-reuse").await.unwrap();
        assert_eq!(a, b);
    }

    #[tokio::test]
    async fn release_clean_worktree_removes_it() {
        let tmp = tempfile::tempdir().unwrap();
        init_repo(tmp.path()).await;

        let p = GitWorktreeProvider::new(tmp.path(), "agent");
        let wt = p.provision("slot-clean").await.unwrap();
        assert!(wt.exists());

        let hint = p.release("slot-clean", &wt).await.unwrap();
        assert!(hint.is_none(), "clean worktree should leave no hint");
        assert!(!wt.exists(), "clean worktree dir should be removed");
    }

    #[tokio::test]
    async fn release_dirty_worktree_commits_and_hints() {
        let tmp = tempfile::tempdir().unwrap();
        init_repo(tmp.path()).await;

        let p = GitWorktreeProvider::new(tmp.path(), "refactor");
        let wt = p.provision("slot-dirty").await.unwrap();

        // Write a file so the worktree is dirty.
        std::fs::write(wt.join("output.rs"), "// generated").unwrap();

        let hint = p.release("slot-dirty", &wt).await.unwrap();
        let hint = hint.expect("dirty release must return a hint");

        // Worktree dir is gone…
        assert!(!wt.exists(), "worktree dir should be removed after commit");
        // …but the branch exists and the hint is well-formed.
        let branch = "koda/wt/refactor-slot-dir"; // first 8 chars of "slot-dirty"
        assert!(hint.contains(branch), "{hint}");
        assert!(hint.contains("git diff HEAD"), "{hint}");
        assert!(hint.contains("git merge"), "{hint}");
    }

    #[tokio::test]
    async fn release_fallback_path_is_noop() {
        let tmp = tempfile::tempdir().unwrap();
        let p = GitWorktreeProvider::new(tmp.path(), "agent");
        // path == project_root → must be no-op even if not a git repo
        let hint = p.release("slot-x", tmp.path()).await.unwrap();
        assert!(hint.is_none());
    }

    // ── ClonefileProvider (macOS only) ───────────────────────────────────
    //
    // These tests exercise the real clonefile(2) syscall against a
    // tempdir. They will SKIP (assertion-free early return) if the
    // tempdir's volume isn't APFS, so they're safe in CI on any
    // macOS runner but pass with full coverage on developer machines
    // (where /tmp is APFS by default).

    #[cfg(target_os = "macos")]
    mod clonefile {
        use super::*;

        /// Probe whether `clonefile(2)` is supported on the volume
        /// hosting `dir`. Returns `true` iff a 1-file clone succeeds.
        /// Lets the rest of the suite skip cleanly on filesystems
        /// where the syscall is unavailable (e.g. an HFS+ tempdir).
        async fn clonefile_supported_at(dir: &Path) -> bool {
            let src = dir.join(".probe-src");
            let dst = dir.join(".probe-dst");
            tokio::fs::write(&src, b"x").await.unwrap();
            // Use the same syscall the provider uses, so support is
            // tested via the actual code path.
            let result = tokio::task::spawn_blocking({
                let src = src.clone();
                let dst = dst.clone();
                move || ClonefileProvider::clonefile_sync(&src, &dst)
            })
            .await
            .unwrap();
            let _ = tokio::fs::remove_file(&src).await;
            let _ = tokio::fs::remove_file(&dst).await;
            result.is_ok()
        }

        /// Build a (project_root, clones_root, provider) triple in one
        /// tempdir. Both roots live under the same parent so they're
        /// guaranteed on the same volume — EXDEV won't surprise us.
        fn make_provider(tmp: &Path) -> (PathBuf, PathBuf, ClonefileProvider) {
            let project = tmp.join("project");
            let clones = tmp.join("clones");
            std::fs::create_dir_all(&project).unwrap();
            std::fs::write(project.join("hello.txt"), "world").unwrap();
            let p = ClonefileProvider::with_clones_root(&project, &clones).unwrap();
            (project, clones, p)
        }

        #[tokio::test]
        async fn project_hash_is_stable_and_pathlike() {
            let tmp = tempfile::tempdir().unwrap();
            let canonical = tmp.path().canonicalize().unwrap();
            let a = ClonefileProvider::project_hash(&canonical);
            let b = ClonefileProvider::project_hash(&canonical);
            assert_eq!(a, b, "hash must be deterministic across calls");
            assert_eq!(a.len(), 16, "hash must be 16 hex chars");
            assert!(
                a.chars().all(|c| c.is_ascii_hexdigit()),
                "hash must be hex-only: {a}"
            );
        }

        #[tokio::test]
        async fn project_hash_differs_for_different_paths() {
            let a = ClonefileProvider::project_hash(Path::new("/tmp/proj-a"));
            let b = ClonefileProvider::project_hash(Path::new("/tmp/proj-b"));
            assert_ne!(a, b);
        }

        #[tokio::test]
        async fn invalid_slot_id_rejected() {
            let tmp = tempfile::tempdir().unwrap();
            let (_, _, p) = make_provider(tmp.path());
            assert!(p.provision("").await.is_err());
            assert!(p.provision("foo/bar").await.is_err());
            assert!(p.provision("foo\\bar").await.is_err());
        }

        #[tokio::test]
        async fn provision_clones_project_tree() {
            let tmp = tempfile::tempdir().unwrap();
            if !clonefile_supported_at(tmp.path()).await {
                eprintln!("skipping: tempdir is not on an APFS volume");
                return;
            }
            let (_, clones, p) = make_provider(tmp.path());

            let dst = p.provision("slot-1").await.unwrap();

            assert_eq!(dst, clones.join("slot-1"));
            assert!(dst.exists(), "clone dir should exist");
            // The cloned tree must contain the source content.
            let cloned = std::fs::read_to_string(dst.join("hello.txt")).unwrap();
            assert_eq!(cloned, "world");
        }

        #[tokio::test]
        async fn provision_is_copy_on_write() {
            // The whole point of clonefile is that mutations on the
            // clone don't leak back to the source. Pin that down so a
            // future refactor (e.g. swapping in `cp -R`) gets caught.
            let tmp = tempfile::tempdir().unwrap();
            if !clonefile_supported_at(tmp.path()).await {
                eprintln!("skipping: tempdir is not on an APFS volume");
                return;
            }
            let (project, _, p) = make_provider(tmp.path());

            let dst = p.provision("slot-cow").await.unwrap();
            std::fs::write(dst.join("hello.txt"), "clobbered").unwrap();
            std::fs::write(dst.join("new.txt"), "only-in-clone").unwrap();

            // Source must be untouched.
            let src_hello = std::fs::read_to_string(project.join("hello.txt")).unwrap();
            assert_eq!(src_hello, "world");
            assert!(!project.join("new.txt").exists());
        }

        #[tokio::test]
        async fn provision_is_idempotent() {
            // Re-provisioning the same slot_id (e.g. resuming after a
            // crash) must reuse the existing clone rather than
            // erroring or wastefully cloning again.
            let tmp = tempfile::tempdir().unwrap();
            if !clonefile_supported_at(tmp.path()).await {
                eprintln!("skipping: tempdir is not on an APFS volume");
                return;
            }
            let (_, _, p) = make_provider(tmp.path());

            let a = p.provision("slot-resume").await.unwrap();
            std::fs::write(a.join("marker.txt"), "persisted").unwrap();
            let b = p.provision("slot-resume").await.unwrap();

            assert_eq!(a, b);
            // The marker we wrote between provisions must still be
            // there — proving we reused, not re-cloned.
            assert_eq!(
                std::fs::read_to_string(b.join("marker.txt")).unwrap(),
                "persisted"
            );
        }

        #[tokio::test]
        async fn release_removes_clone() {
            let tmp = tempfile::tempdir().unwrap();
            if !clonefile_supported_at(tmp.path()).await {
                eprintln!("skipping: tempdir is not on an APFS volume");
                return;
            }
            let (_, _, p) = make_provider(tmp.path());

            let dst = p.provision("slot-rm").await.unwrap();
            assert!(dst.exists());

            let hint = p.release("slot-rm", &dst).await.unwrap();
            // ClonefileProvider doesn't preserve work onto a branch
            // (no git semantics), so release returns no hint.
            assert!(hint.is_none());
            assert!(!dst.exists(), "clone dir should be gone");
        }

        #[tokio::test]
        async fn release_missing_path_is_ok() {
            // If the clone is already gone (e.g. user manually rm'd
            // ~/.koda/clones), release should not error — idempotent
            // cleanup is the contract.
            let tmp = tempfile::tempdir().unwrap();
            let (_, clones, p) = make_provider(tmp.path());
            let phantom = clones.join("never-existed");
            let result = p.release("never-existed", &phantom).await.unwrap();
            assert!(result.is_none());
        }

        #[tokio::test]
        async fn release_refuses_path_outside_clones_root() {
            // The provider should refuse to delete anything that
            // isn't under its clones_root — critical defense against a
            // caller bug that would otherwise rm -rf the user's
            // source tree.
            let tmp = tempfile::tempdir().unwrap();
            let (project, _, p) = make_provider(tmp.path());
            let result = p.release("slot-bad", &project).await;
            assert!(
                result.is_err(),
                "release of a path outside clones_root must error"
            );
            // And the source must still exist — belt and suspenders.
            assert!(project.join("hello.txt").exists());
        }
    }
}