marver 0.0.27

A TUI workspace for AI agent sessions: tmux orchestration, git worktree management, and repo control in one place.
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
//! Provisioning and teardown of the worktrees behind a task.
//!
//! ```text
//! <workspace_root>/<task-id>/
//! ├── repo-a/     ← worktree on marver/<task-id>-<slug>
//! ├── repo-b/     ← same branch name, cut from repo-b's own default
//! └──             ← the tmux session's cwd
//! ```
//!
//! Same branch name in every repo, its own base in each, since "the default
//! branch" means something different per repo.
//!
//! Provisioning is all-or-nothing — a task that half-exists on disk is worse
//! than one that failed — while teardown is best effort, reporting what it could
//! not remove rather than leaving a task undeletable.

use std::collections::HashSet;
use std::path::{Path, PathBuf};

use crate::domain::{Task, TaskRepo};
use crate::git;
use crate::store::Store;

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error(transparent)]
    Git(#[from] git::Error),
    #[error(transparent)]
    Store(#[from] crate::store::Error),
    #[error("io error at {path}: {source}")]
    Io {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
    #[error("task {0} targets no repos")]
    NoRepos(i64),
    #[error("workspace {0} already exists")]
    WorkspaceExists(PathBuf),
}

pub type Result<T> = std::result::Result<T, Error>;

/// Longest slug taken from a task title when naming a branch.
const MAX_SLUG: usize = 40;

/// What to do with the branch a task created, once its worktree is gone.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Branches {
    /// Leave them. Committed work stays reachable after the directory is gone.
    Keep,
    /// Delete the ones git agrees are reachable elsewhere, and keep the rest.
    DeleteMerged,
    /// Delete regardless, discarding any commit that lives only here.
    Discard,
}

/// What teardown managed to do. Never fails as a whole.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Teardown {
    pub removed: Vec<PathBuf>,
    /// Worktrees that resisted removal, with the reason.
    pub failed: Vec<(PathBuf, String)>,
    /// Whether the task's workspace directory is gone.
    pub workspace_removed: bool,
    /// Branches asked for but not deleted, because git found commits on them
    /// that exist nowhere else. Empty unless [`Branches::DeleteMerged`].
    pub kept_branches: Vec<String>,
}

impl Teardown {
    pub fn is_clean(&self) -> bool {
        self.failed.is_empty() && self.workspace_removed
    }
}

/// Branch name for a task: `marver/<id>-<slug>`.
pub fn branch_name(task: &Task) -> String {
    let slug = slugify(&task.title);
    if slug.is_empty() {
        format!("marver/{}", task.id)
    } else {
        format!("marver/{}-{}", task.id, slug)
    }
}

fn slugify(title: &str) -> String {
    let mut out = String::with_capacity(title.len().min(MAX_SLUG));
    let mut last_dash = true; // suppresses a leading dash
    for ch in title.chars() {
        if ch.is_ascii_alphanumeric() {
            out.push(ch.to_ascii_lowercase());
            last_dash = false;
        } else if !last_dash {
            out.push('-');
            last_dash = true;
        }
        if out.len() >= MAX_SLUG {
            break;
        }
    }
    out.trim_matches('-').to_string()
}

pub struct WorktreeManager {
    workspace_root: PathBuf,
}

impl WorktreeManager {
    /// `workspace_root` is the directory task directories are created under.
    pub fn new(workspace_root: impl Into<PathBuf>) -> Self {
        Self {
            workspace_root: workspace_root.into(),
        }
    }

    pub fn workspace_root(&self) -> &Path {
        &self.workspace_root
    }

    /// Create a worktree per repo and record each in the store.
    pub fn provision(&self, store: &Store, task: &Task) -> Result<Vec<TaskRepo>> {
        let selection = store.list_task_repos(task.id)?;
        if selection.is_empty() {
            return Err(Error::NoRepos(task.id));
        }
        let repos = selection
            .iter()
            .map(|link| store.get_repo(link.repo_id))
            .collect::<std::result::Result<Vec<_>, _>>()?;
        let repos = &repos[..];
        let workspace = &task.workspace_dir;
        if workspace.exists() {
            return Err(Error::WorkspaceExists(workspace.clone()));
        }
        std::fs::create_dir_all(workspace).map_err(|source| Error::Io {
            path: workspace.clone(),
            source,
        })?;

        let branch = branch_name(task);
        let mut created: Vec<(PathBuf, PathBuf)> = Vec::new(); // (repo path, worktree path)
        let mut result = Vec::with_capacity(repos.len());
        let mut used = HashSet::new();

        for repo in repos {
            let worktree_path = workspace.join(unique_dir_name(&repo.name, repo.id, &mut used));
            let outcome = git::default_branch(&repo.path).and_then(|base| {
                git::worktree_add(&repo.path, &worktree_path, &branch, &base)?;
                Ok(base)
            });

            match outcome {
                Ok(base) => {
                    created.push((repo.path.clone(), worktree_path.clone()));
                    match store.record_worktree(task.id, repo.id, &worktree_path, &branch, &base) {
                        Ok(record) => result.push(record),
                        Err(err) => {
                            self.unwind(workspace, &created, &branch);
                            return Err(err.into());
                        }
                    }
                }
                Err(err) => {
                    self.unwind(workspace, &created, &branch);
                    return Err(err.into());
                }
            }
        }

        Ok(result)
    }

    /// Undo a partial provision. Best effort by construction — it runs while
    /// already handling an error, so there is nothing useful to report upward.
    fn unwind(&self, workspace: &Path, created: &[(PathBuf, PathBuf)], branch: &str) {
        for (repo_path, worktree_path) in created {
            let _ = git::worktree_remove(repo_path, worktree_path, true);
            let _ = git::branch_delete(repo_path, branch, true);
        }
        // The workspace is removed unconditionally, not derived from whatever
        // was created.
        let _ = std::fs::remove_dir_all(workspace);
    }

    /// Remove a task's worktrees and its workspace directory.
    pub fn teardown(&self, store: &Store, task: &Task, branches: Branches) -> Result<Teardown> {
        let mut outcome = Teardown::default();

        for link in store.list_task_repos(task.id)? {
            // A selected but never-provisioned repo has nothing to remove.
            let Some(worktree_path) = link.worktree_path.clone() else {
                continue;
            };
            let repo = match store.get_repo(link.repo_id) {
                Ok(repo) => repo,
                Err(err) => {
                    outcome.failed.push((worktree_path, err.to_string()));
                    continue;
                }
            };

            match git::worktree_remove(&repo.path, &worktree_path, true) {
                Ok(()) => outcome.removed.push(worktree_path.clone()),
                Err(err) => {
                    // The directory may already be gone; prune reconciles
                    // git's records with the filesystem before we call it a
                    // failure.
                    let _ = git::worktree_prune(&repo.path);
                    if worktree_path.exists() {
                        outcome.failed.push((worktree_path, err.to_string()));
                        continue;
                    }
                    outcome.removed.push(worktree_path.clone());
                }
            }

            // After the worktree is gone, never before: git refuses to delete
            // a branch that is checked out somewhere.
            if let Some(branch) = &link.branch {
                match branches {
                    Branches::Keep => {}
                    Branches::Discard => {
                        let _ = git::branch_delete(&repo.path, branch, true);
                    }
                    Branches::DeleteMerged => {
                        if git::branch_delete(&repo.path, branch, false).is_err() {
                            outcome.kept_branches.push(branch.clone());
                        }
                    }
                }
            }
        }

        if outcome.failed.is_empty() {
            match std::fs::remove_dir_all(&task.workspace_dir) {
                Ok(()) => outcome.workspace_removed = true,
                Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                    outcome.workspace_removed = true;
                }
                Err(err) => outcome
                    .failed
                    .push((task.workspace_dir.clone(), err.to_string())),
            }
        }

        Ok(outcome)
    }
}

/// A finished task whose worktrees are still on disk.
#[derive(Debug, Clone)]
pub struct Candidate {
    pub task: Task,
    /// Worktrees still recorded against it, whether or not they still exist.
    pub worktrees: Vec<PathBuf>,
    /// Those holding changes no commit would preserve. Removing one destroys
    /// work, so cleanup skips them unless told otherwise.
    pub dirty: Vec<PathBuf>,
}

impl Candidate {
    /// Whether removing this task's worktrees would lose anything.
    pub fn is_clean(&self) -> bool {
        self.dirty.is_empty()
    }
}

/// Finished tasks that still hold worktrees, oldest first.
pub fn reclaimable(store: &Store) -> Result<Vec<Candidate>> {
    let mut candidates = Vec::new();
    for task in store.list_tasks()? {
        if !task.state.is_terminal() {
            continue;
        }
        let worktrees: Vec<PathBuf> = store
            .list_task_repos(task.id)?
            .into_iter()
            .filter_map(|link| link.worktree_path)
            .collect();
        if worktrees.is_empty() {
            continue;
        }
        let dirty = worktrees
            .iter()
            .filter(|path| holds_changes(path))
            .cloned()
            .collect();
        candidates.push(Candidate {
            task,
            worktrees,
            dirty,
        });
    }
    Ok(candidates)
}

/// A task's worktrees that hold something a removal would destroy.
pub fn dirty_worktrees(store: &Store, task: &Task) -> Vec<PathBuf> {
    let Ok(links) = store.list_task_repos(task.id) else {
        return Vec::new();
    };
    links
        .into_iter()
        .filter_map(|link| link.worktree_path)
        .filter(|path| holds_changes(path))
        .collect()
}

/// Whether a worktree holds anything a removal would destroy.
fn holds_changes(path: &Path) -> bool {
    if !path.exists() {
        return false;
    }
    match git::status(path) {
        Ok(entries) => !entries.is_empty(),
        Err(_) => true,
    }
}

/// Directory name for a repo inside a task workspace.
fn unique_dir_name(name: &str, repo_id: i64, used: &mut HashSet<String>) -> String {
    let base = if name.is_empty() {
        format!("repo-{repo_id}")
    } else {
        name.to_string()
    };
    if used.insert(base.clone()) {
        return base;
    }
    let disambiguated = format!("{base}-{repo_id}");
    used.insert(disambiguated.clone());
    disambiguated
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::{Repo, TaskState};
    use crate::git::testing::init_repo;
    use crate::store::Transition;
    use chrono::{DateTime, Utc};
    use tempfile::TempDir;

    fn at(secs: i64) -> DateTime<Utc> {
        DateTime::from_timestamp(secs, 0).expect("valid timestamp")
    }

    struct Fixture {
        _tmp: TempDir,
        repos_dir: PathBuf,
        store: Store,
        manager: WorktreeManager,
    }

    impl Fixture {
        fn new() -> Self {
            let tmp = TempDir::new().unwrap();
            let repos_dir = tmp.path().join("repos");
            let workspace_root = tmp.path().join("tasks");
            std::fs::create_dir_all(&repos_dir).unwrap();
            Self {
                repos_dir,
                store: Store::open_in_memory().unwrap(),
                manager: WorktreeManager::new(workspace_root),
                _tmp: tmp,
            }
        }

        fn repo(&self, name: &str, default_branch: &str) -> Repo {
            let path = self.repos_dir.join(name);
            init_repo(&path, default_branch);
            self.store.upsert_repo(&path, name, at(0)).unwrap()
        }

        /// A task targeting `repos`, as creation would record it.
        fn task(&mut self, title: &str, repos: &[Repo]) -> Task {
            let root = self.manager.workspace_root().to_path_buf();
            let ids: Vec<i64> = repos.iter().map(|r| r.id).collect();
            self.store
                .create_task(title, "do the thing", &root, &ids, at(0))
                .unwrap()
        }

        /// Walk a task to a terminal state the way the daemon would.
        fn finish(&mut self, task: &Task, end: TaskState) -> Task {
            let path: &[TaskState] = match end {
                TaskState::Cancelled => &[TaskState::Cancelled],
                TaskState::Committed => &[
                    TaskState::Running,
                    TaskState::AwaitingReview,
                    TaskState::Committed,
                ],
                other => panic!("no walk to {other}"),
            };
            let mut last = task.clone();
            for &state in path {
                last = self
                    .store
                    .transition(task.id, state, Transition::Plain, at(1))
                    .unwrap();
            }
            last
        }
    }

    #[test]
    fn slugs_are_branch_safe() {
        assert_eq!(slugify("Fix the auth flow"), "fix-the-auth-flow");
        assert_eq!(slugify("  Weird!! chars??  "), "weird-chars");
        assert_eq!(slugify("CAPS and 123"), "caps-and-123");
        assert_eq!(slugify("!!!"), "");
        assert!(slugify(&"x".repeat(200)).len() <= MAX_SLUG);
    }

    #[test]
    fn branch_names_are_namespaced_and_unique() {
        let mut fx = Fixture::new();
        let a = fx.task("Fix the auth flow", &[]);
        let b = fx.task("Fix the auth flow", &[]);
        assert_eq!(
            branch_name(&a),
            format!("marver/{}-fix-the-auth-flow", a.id)
        );
        assert_ne!(
            branch_name(&a),
            branch_name(&b),
            "same title, different tasks"
        );
    }

    #[test]
    fn a_title_with_no_usable_characters_still_yields_a_branch() {
        let mut fx = Fixture::new();
        let task = fx.task("!!!", &[]);
        assert_eq!(branch_name(&task), format!("marver/{}", task.id));
    }

    #[test]
    fn provisions_a_single_repo() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api", "main");
        let task = fx.task("Fix the auth flow", std::slice::from_ref(&repo));

        let links = fx.manager.provision(&fx.store, &task).unwrap();

        assert_eq!(links.len(), 1);
        assert_eq!(links[0].base_ref.as_deref(), Some("main"));
        assert_eq!(
            links[0].branch.as_deref(),
            Some(branch_name(&task).as_str())
        );
        assert!(
            links[0]
                .worktree_path
                .as_ref()
                .unwrap()
                .join("README.md")
                .exists()
        );
        assert_eq!(
            links[0].worktree_path.as_deref(),
            Some(task.workspace_dir.join("api").as_path())
        );
        assert_eq!(fx.store.list_task_repos(task.id).unwrap().len(), 1);
    }

    #[test]
    fn each_repo_branches_from_its_own_default() {
        let mut fx = Fixture::new();
        let api = fx.repo("api", "main");
        let web = fx.repo("web", "develop");
        let task = fx.task("Cross cutting change", &[api, web]);

        let links = fx.manager.provision(&fx.store, &task).unwrap();

        assert_eq!(links.len(), 2);
        assert_eq!(links[0].base_ref.as_deref(), Some("main"));
        assert_eq!(links[1].base_ref.as_deref(), Some("develop"));
        assert_eq!(
            links[0].branch, links[1].branch,
            "one branch name across the task"
        );
        assert!(task.workspace_dir.join("api").exists());
        assert!(task.workspace_dir.join("web").exists());
    }

    #[test]
    fn repos_sharing_a_name_do_not_collide() {
        let mut fx = Fixture::new();
        let a = {
            let path = fx.repos_dir.join("org-a/shared");
            init_repo(&path, "main");
            fx.store.upsert_repo(&path, "shared", at(0)).unwrap()
        };
        let b = {
            let path = fx.repos_dir.join("org-b/shared");
            init_repo(&path, "main");
            fx.store.upsert_repo(&path, "shared", at(0)).unwrap()
        };
        let task = fx.task("Touch both", &[a, b.clone()]);

        let links = fx.manager.provision(&fx.store, &task).unwrap();

        assert_eq!(
            links[0].worktree_path.as_deref(),
            Some(task.workspace_dir.join("shared").as_path())
        );
        assert_eq!(
            links[1].worktree_path.as_deref(),
            Some(
                task.workspace_dir
                    .join(format!("shared-{}", b.id))
                    .as_path()
            )
        );
    }

    #[test]
    fn a_task_with_no_repos_is_rejected() {
        let mut fx = Fixture::new();
        let task = fx.task("Nothing to do", &[]);
        assert!(matches!(
            fx.manager.provision(&fx.store, &task),
            Err(Error::NoRepos(_))
        ));
        assert!(!task.workspace_dir.exists(), "nothing should be created");
    }

    #[test]
    fn provisioning_twice_is_refused() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api", "main");
        let task = fx.task("Fix it", std::slice::from_ref(&repo));
        fx.manager.provision(&fx.store, &task).unwrap();

        assert!(matches!(
            fx.manager.provision(&fx.store, &task),
            Err(Error::WorkspaceExists(_))
        ));
    }

    #[test]
    fn a_partial_failure_leaves_nothing_behind() {
        let mut fx = Fixture::new();
        let good = fx.repo("api", "main");
        // Registered in the store but never initialised as a git repo, so the
        // second worktree_add fails after the first has succeeded.
        let broken_path = fx.repos_dir.join("broken");
        std::fs::create_dir_all(&broken_path).unwrap();
        let broken = fx.store.upsert_repo(&broken_path, "broken", at(0)).unwrap();
        let task = fx.task("Will fail", &[good.clone(), broken]);

        let err = fx.manager.provision(&fx.store, &task).unwrap_err();

        assert!(matches!(err, Error::Git(_)));
        assert!(
            !task.workspace_dir.exists(),
            "the workspace must be cleaned up"
        );
        assert!(
            !git::branch_exists(&good.path, &branch_name(&task)).unwrap(),
            "the branch created for the successful repo must be removed"
        );
    }

    #[test]
    fn a_failure_on_the_first_repo_also_leaves_nothing_behind() {
        // The mirror of the test above, and the one that mattered: unwind
        // derived the workspace from the first worktree it had created, so
        // when the *first* repo failed there was nothing to derive it from and
        // the directory survived.
        let mut fx = Fixture::new();
        let broken_path = fx.repos_dir.join("broken");
        std::fs::create_dir_all(&broken_path).unwrap();
        let broken = fx.store.upsert_repo(&broken_path, "broken", at(0)).unwrap();
        let good = fx.repo("api", "main");
        let task = fx.task("Will fail", &[broken, good]);

        let err = fx.manager.provision(&fx.store, &task).unwrap_err();
        assert!(!matches!(err, Error::WorkspaceExists(_)));
        assert!(
            !task.workspace_dir.exists(),
            "the workspace must be cleaned up even when nothing was created"
        );

        // And the proof that it matters: a retry gets a real attempt, not
        // WorkspaceExists.
        let again = fx.manager.provision(&fx.store, &task).unwrap_err();
        assert!(
            !matches!(again, Error::WorkspaceExists(_)),
            "a retry must not be blocked by the last failure's leftovers"
        );
    }

    #[test]
    fn a_task_can_be_provisioned_again_after_a_teardown_that_kept_its_branch() {
        // Stop a task, keep the work, start it again — the ordinary path.
        let mut fx = Fixture::new();
        let repo = fx.repo("api", "main");
        let task = fx.task("Fix it", std::slice::from_ref(&repo));
        let created = fx.manager.provision(&fx.store, &task).unwrap();

        // Commit something so the kept branch has work worth keeping.
        let wt = created[0].worktree_path.clone().unwrap();
        std::fs::write(wt.join("new.rs"), "fn f() {}\n").unwrap();
        git::stage_all(&wt).unwrap();
        git::commit(&wt, "agent work").unwrap();

        fx.manager
            .teardown(&fx.store, &task, Branches::Keep)
            .unwrap();
        fx.store.clear_worktrees(task.id).unwrap();
        assert!(git::branch_exists(&repo.path, &branch_name(&task)).unwrap());

        let again = fx.manager.provision(&fx.store, &task).unwrap();

        let wt = again[0].worktree_path.clone().unwrap();
        assert!(
            wt.join("new.rs").exists(),
            "reprovisioning must pick the branch back up, not start over"
        );
    }

    #[test]
    fn teardown_removes_worktrees_and_the_workspace() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api", "main");
        let task = fx.task("Fix it", std::slice::from_ref(&repo));
        fx.manager.provision(&fx.store, &task).unwrap();

        let outcome = fx
            .manager
            .teardown(&fx.store, &task, Branches::Keep)
            .unwrap();

        assert!(outcome.is_clean());
        assert_eq!(outcome.removed.len(), 1);
        assert!(!task.workspace_dir.exists());
        assert!(
            git::branch_exists(&repo.path, &branch_name(&task)).unwrap(),
            "the branch survives by default"
        );
        assert_eq!(
            fx.store.list_task_repos(task.id).unwrap().len(),
            1,
            "the record of what the task did is kept"
        );
    }

    #[test]
    fn teardown_can_delete_the_branches_too() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api", "main");
        let task = fx.task("Abandoned", std::slice::from_ref(&repo));
        fx.manager.provision(&fx.store, &task).unwrap();

        fx.manager
            .teardown(&fx.store, &task, Branches::Discard)
            .unwrap();

        assert!(!git::branch_exists(&repo.path, &branch_name(&task)).unwrap());
    }

    #[test]
    fn teardown_discards_uncommitted_work() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api", "main");
        let task = fx.task("Dirty", std::slice::from_ref(&repo));
        let links = fx.manager.provision(&fx.store, &task).unwrap();
        std::fs::write(
            links[0].worktree_path.as_ref().unwrap().join("README.md"),
            "edited\n",
        )
        .unwrap();

        let outcome = fx
            .manager
            .teardown(&fx.store, &task, Branches::Keep)
            .unwrap();
        assert!(
            outcome.is_clean(),
            "a dirty worktree must not block teardown"
        );
    }

    #[test]
    fn teardown_tolerates_an_already_deleted_worktree() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api", "main");
        let task = fx.task("Vanished", std::slice::from_ref(&repo));
        let links = fx.manager.provision(&fx.store, &task).unwrap();
        // Someone removed it by hand, leaving git's records stale.
        std::fs::remove_dir_all(links[0].worktree_path.as_ref().unwrap()).unwrap();

        let outcome = fx
            .manager
            .teardown(&fx.store, &task, Branches::Keep)
            .unwrap();
        assert!(outcome.is_clean(), "{:?}", outcome.failed);
        assert!(!task.workspace_dir.exists());
    }

    #[test]
    fn teardown_of_an_unprovisioned_task_is_harmless() {
        let mut fx = Fixture::new();
        let task = fx.task("Never started", &[]);
        let outcome = fx
            .manager
            .teardown(&fx.store, &task, Branches::Keep)
            .unwrap();
        assert!(outcome.is_clean());
        assert!(outcome.removed.is_empty());
    }

    #[test]
    fn only_finished_tasks_are_offered_for_reclaiming() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api", "main");
        let live = fx.task("Still working", std::slice::from_ref(&repo));
        let done = fx.task("Finished", std::slice::from_ref(&repo));
        fx.manager.provision(&fx.store, &live).unwrap();
        fx.manager.provision(&fx.store, &done).unwrap();
        fx.store
            .transition(live.id, TaskState::Running, Transition::Plain, at(1))
            .unwrap();
        fx.finish(&done, TaskState::Committed);

        let found = reclaimable(&fx.store).unwrap();

        assert_eq!(found.len(), 1, "a running task is in use, not litter");
        assert_eq!(found[0].task.id, done.id);
        assert!(found[0].is_clean());
    }

    #[test]
    fn a_task_that_never_reached_a_worktree_is_not_offered() {
        // Cancelled while still queued: it selected repos and owns nothing.
        let mut fx = Fixture::new();
        let repo = fx.repo("api", "main");
        let task = fx.task("Never started", std::slice::from_ref(&repo));
        fx.finish(&task, TaskState::Cancelled);

        assert!(reclaimable(&fx.store).unwrap().is_empty());
    }

    #[test]
    fn a_worktree_holding_changes_is_offered_but_flagged() {
        // The whole reason cleanup is a separate act: the state says finished,
        // and the directory says otherwise.
        let mut fx = Fixture::new();
        let repo = fx.repo("api", "main");
        let task = fx.task("Cancelled mid-edit", std::slice::from_ref(&repo));
        let links = fx.manager.provision(&fx.store, &task).unwrap();
        let wt = links[0].worktree_path.clone().unwrap();
        std::fs::write(wt.join("half-done.rs"), "fn f() {}\n").unwrap();
        fx.finish(&task, TaskState::Cancelled);

        let found = reclaimable(&fx.store).unwrap();

        assert_eq!(found.len(), 1);
        assert!(!found[0].is_clean(), "an untracked file is unreviewed work");
        assert_eq!(found[0].dirty, vec![wt]);
    }

    #[test]
    fn a_worktree_removed_by_hand_is_not_mistaken_for_dirty() {
        // Still offered, so the store record catches up with the disk.
        let mut fx = Fixture::new();
        let repo = fx.repo("api", "main");
        let task = fx.task("Tidied already", std::slice::from_ref(&repo));
        let links = fx.manager.provision(&fx.store, &task).unwrap();
        std::fs::remove_dir_all(links[0].worktree_path.as_ref().unwrap()).unwrap();
        fx.finish(&task, TaskState::Cancelled);

        let found = reclaimable(&fx.store).unwrap();

        assert_eq!(found.len(), 1);
        assert!(
            found[0].is_clean(),
            "a directory that is gone holds nothing"
        );
    }

    #[test]
    fn deleting_merged_branches_keeps_the_one_holding_the_work() {
        // marver commits onto the task branch and merges it nowhere, so for a
        // committed task that branch is the only copy.
        let mut fx = Fixture::new();
        let repo = fx.repo("api", "main");
        let task = fx.task("Committed work", std::slice::from_ref(&repo));
        let links = fx.manager.provision(&fx.store, &task).unwrap();
        let wt = links[0].worktree_path.clone().unwrap();
        std::fs::write(wt.join("new.rs"), "fn f() {}\n").unwrap();
        git::stage_all(&wt).unwrap();
        git::commit(&wt, "agent work").unwrap();

        let outcome = fx
            .manager
            .teardown(&fx.store, &task, Branches::DeleteMerged)
            .unwrap();

        assert!(outcome.is_clean(), "the directory still goes");
        assert!(
            git::branch_exists(&repo.path, &branch_name(&task)).unwrap(),
            "deleting this branch would destroy the commit"
        );
        assert_eq!(outcome.kept_branches, vec![branch_name(&task)]);
    }

    #[test]
    fn deleting_merged_branches_removes_the_one_that_did_nothing() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api", "main");
        let task = fx.task("Nothing came of it", std::slice::from_ref(&repo));
        fx.manager.provision(&fx.store, &task).unwrap();

        let outcome = fx
            .manager
            .teardown(&fx.store, &task, Branches::DeleteMerged)
            .unwrap();

        assert!(!git::branch_exists(&repo.path, &branch_name(&task)).unwrap());
        assert!(outcome.kept_branches.is_empty());
    }

    #[test]
    fn a_provisioned_worktree_is_not_seen_as_a_repo_by_the_scanner() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api", "main");
        let task = fx.task("Fix it", std::slice::from_ref(&repo));
        fx.manager.provision(&fx.store, &task).unwrap();

        let scan = crate::scan::Scanner::new(fx.manager.workspace_root())
            .walk()
            .unwrap();
        assert!(
            scan.repos.is_empty(),
            "marver must not rediscover its own worktrees: {:?}",
            scan.repos
        );
    }
}