marver 0.0.11

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
//! Provisioning and teardown of the worktrees behind a task.
//!
//! A task gets one directory holding one worktree per repo it targets:
//!
//! ```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
//! ```
//!
//! Every repo in a task gets the *same* branch name but its *own* base, since
//! "the default branch" means something different in each repo.
//!
//! Provisioning is all-or-nothing: a task that half-exists on disk is worse than
//! one that failed outright, so a partial failure unwinds what it created.
//! Teardown is the opposite — best effort, reporting what it could not remove,
//! because leaving a task undeletable because one worktree is stuck is worse
//! than a stale directory.

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 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,
}

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

/// Branch name for a task: `marver/<id>-<slug>`.
///
/// The `marver/` prefix keeps generated branches out of the way of hand-made
/// ones, and the id keeps them unique when two tasks share a title.
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.
    ///
    /// Fails if the workspace already exists, so a task cannot be provisioned
    /// twice. On any error the worktrees created so far are removed and the
    /// workspace directory deleted.
    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. When the *first* repo fails nothing has been created, so
        // deriving it left the directory behind — and since provision refuses
        // to run against an existing workspace, the task could never be
        // launched again even once the original cause was fixed.
        let _ = std::fs::remove_dir_all(workspace);
    }

    /// Remove a task's worktrees and its workspace directory.
    ///
    /// `delete_branches` also drops the generated branch from each repo; leave
    /// it off to keep committed work reachable after the workspace is gone.
    ///
    /// Store rows are left alone. `task_repos` is the record of what a task did,
    /// and that stays true after the directory is removed.
    pub fn teardown(&self, store: &Store, task: &Task, delete_branches: bool) -> 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());
                }
            }

            if delete_branches && let Some(branch) = &link.branch {
                let _ = git::branch_delete(&repo.path, branch, true);
            }
        }

        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)
    }
}

/// Directory name for a repo inside a task workspace.
///
/// Two repos with the same basename in different parents would otherwise
/// collide; the loser gets its id appended.
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;
    use crate::git::testing::init_repo;
    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()
        }
    }

    #[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. provision refuses to run against an existing
        // workspace, so the task was then unlaunchable for ever, even after the
        // underlying cause was fixed.
        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. The
        // branch is still there, and `worktree add -b` on an existing branch is
        // a hard error, which then wedged the task via the bug above.
        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, false).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, false).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, true).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, false).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, false).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, false).unwrap();
        assert!(outcome.is_clean());
        assert!(outcome.removed.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
        );
    }
}