marver 0.0.20

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
//! Where each known repo stands, and the two commands that move it.
//!
//! The task list answers "what are the agents doing". This answers the question
//! asked just before that one — "what am I starting from" — for every repo the
//! scan found: what is checked out, how far it has drifted from the branch it
//! tracks and from the repo's default branch, and whether anything is
//! uncommitted.
//!
//! # Why this is not done on the interface's thread
//!
//! A row costs five or six git subprocesses, and a fetch costs a network round
//! trip against a host that may be slow, unreachable, or asking for a passphrase
//! that will never come. Doing any of that between two frames would freeze the
//! screen for as long as it took, so [`spawn`] runs a [`Job`] on a thread and
//! reports [`Update`]s back down a channel. The view drains them on its tick and
//! is never blocked by any of it.
//!
//! [`run`] is that same work without the thread, which is what the tests drive.
//!
//! # Reading before writing
//!
//! Nothing here is destructive. `fetch` only adds remote-tracking refs and
//! `pull` is `--ff-only`, so the worst either can do to a repo an agent is
//! working in is nothing at all. That is deliberate: these run on one keystroke
//! against a repo that is not on screen.

use std::path::{Path, PathBuf};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::thread;

use crate::domain::Repo;
use crate::git;

/// How far one ref has drifted from another.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Divergence {
    /// What the comparison was against, as `origin/main`. Shown, because
    /// "behind" means nothing without saying behind *what*.
    pub reference: String,
    pub ahead: u32,
    pub behind: u32,
}

impl Divergence {
    pub fn is_level(&self) -> bool {
        self.ahead == 0 && self.behind == 0
    }
}

/// What the repo screen knows about one repo.
///
/// Every field is optional or empty-able and nothing here returns an error: a
/// repo that git will not talk about still gets a row, with [`Self::trouble`]
/// saying why it is blank. A row that vanished would be the worse answer, since
/// the repo has not vanished — the information has.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RepoStatus {
    pub repo_id: i64,
    pub name: String,
    pub path: PathBuf,
    /// `None` when `HEAD` is detached — which is an answer, not a gap, and so
    /// leaves [`Self::trouble`] alone.
    pub branch: Option<String>,
    /// The branch this one tracks, and the gap. `None` when it tracks nothing.
    pub upstream: Option<Divergence>,
    /// The repo's default branch, and the gap to it.
    ///
    /// `None` when the default branch is what [`Self::upstream`] already
    /// compared against — on `main` tracking `origin/main` the two columns hold
    /// the same number, and a number printed twice reads as two facts.
    pub default: Option<Divergence>,
    /// Files with uncommitted changes, staged or not.
    pub dirty: usize,
    /// Why this row is blank: the directory has gone, or git will not talk
    /// about it. Never set for anything the other fields already express.
    pub trouble: Option<String>,
}

impl RepoStatus {
    fn blank(repo: &Repo) -> Self {
        Self {
            repo_id: repo.id,
            name: repo.name.clone(),
            path: repo.path.clone(),
            branch: None,
            upstream: None,
            default: None,
            dirty: 0,
            trouble: None,
        }
    }
}

/// Read where a repo stands. Local only — this never reaches a network.
///
/// Infallible by construction. Each answer is looked up on its own and a
/// failure costs that answer alone, because the alternative — one `?` turning a
/// missing `origin/HEAD` into a repo with no row — loses the branch and the
/// uncommitted-file count that were sitting right there.
pub fn status(repo: &Repo) -> RepoStatus {
    let mut row = RepoStatus::blank(repo);
    let path = repo.path.as_path();

    if !git::is_repo(path) {
        // Scans record what they found and never delete, so a repo moved or
        // removed since the last one is expected rather than exceptional.
        row.trouble = Some(if path.exists() {
            "not a git repo any more".into()
        } else {
            "gone from disk".into()
        });
        return row;
    }

    row.branch = git::head_branch(path).ok().flatten();
    row.dirty = git::status(path).map(|entries| entries.len()).unwrap_or(0);

    let upstream = git::upstream(path).ok().flatten();
    if let Some(reference) = &upstream
        && let Ok(Some((ahead, behind))) = git::ahead_behind(path, "HEAD", reference)
    {
        row.upstream = Some(Divergence {
            reference: reference.clone(),
            ahead,
            behind,
        });
    }

    if let Some(reference) = default_ref(path)
        // The upstream column already carries this comparison.
        && upstream.as_deref() != Some(reference.as_str())
        && let Ok(Some((ahead, behind))) = git::ahead_behind(path, "HEAD", &reference)
    {
        row.default = Some(Divergence {
            reference,
            ahead,
            behind,
        });
    }

    row
}

/// What to compare against for "how far behind main am I".
///
/// `origin/main` when the clone has it, because the question is about the
/// branch everyone else is pushing to and the local `main` is only as fresh as
/// the last pull. The local branch is the fallback for a repo with no remote,
/// where it is the only main there is.
fn default_ref(repo: &Path) -> Option<String> {
    let default = git::default_branch(repo).ok()?;
    let remote = format!("origin/{default}");
    match git::ref_exists(repo, &remote) {
        Ok(true) => Some(remote),
        _ => Some(default),
    }
}

/// A piece of work the repo screen wants done off its thread.
#[derive(Debug, Clone)]
pub enum Job {
    /// Read every repo's state. What opening the screen and `r` both ask for.
    Refresh(Vec<Repo>),
    /// Fetch one repo, then re-read it.
    Fetch(Repo),
    /// Fast-forward one repo, then re-read it.
    Pull(Repo),
}

impl Job {
    /// What to say while it runs. Present tense — it has not happened yet.
    pub fn doing(&self) -> String {
        match self {
            Self::Refresh(repos) => format!("reading {} repos", repos.len()),
            Self::Fetch(repo) => format!("fetching {}", repo.name),
            Self::Pull(repo) => format!("pulling {}", repo.name),
        }
    }

    /// What to say once it has. Past tense, and only worth saying for the two
    /// that changed something — a refresh announces itself by the rows moving.
    pub fn did(&self) -> Option<String> {
        match self {
            Self::Refresh(_) => None,
            Self::Fetch(repo) => Some(format!("fetched {}", repo.name)),
            Self::Pull(repo) => Some(format!("pulled {}", repo.name)),
        }
    }
}

/// What a running job reports, in the order it happens.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Update {
    /// A row that is now known, replacing whatever the screen had for it.
    ///
    /// Sent per repo rather than as one batch at the end, so a refresh over
    /// thirty repos fills the screen as it goes instead of showing nothing for
    /// as long as the slowest one takes.
    Row(Box<RepoStatus>),
    /// Something for the status line. A failure, in practice.
    Says(String),
    /// Nothing further is coming.
    Done,
}

/// Run a job on its own thread, reporting back down the returned channel.
///
/// The thread stops early if the receiver is dropped, which is what closing the
/// screen mid-fetch does.
pub fn spawn(job: Job) -> Receiver<Update> {
    let (tx, rx) = channel();
    thread::spawn(move || run(job, &tx));
    rx
}

/// The body of [`spawn`], without the thread.
///
/// Sends are checked: a dropped receiver means the screen has gone, and there
/// is no reason to keep fetching for a view nobody is looking at.
pub fn run(job: Job, tx: &Sender<Update>) {
    match &job {
        Job::Refresh(repos) => {
            for repo in repos {
                if tx.send(Update::Row(Box::new(status(repo)))).is_err() {
                    return;
                }
            }
        }
        Job::Fetch(repo) | Job::Pull(repo) => {
            let outcome = match &job {
                Job::Pull(_) => git::pull(&repo.path),
                _ => git::fetch(&repo.path),
            };
            if let Err(err) = outcome {
                // Reported, and then the row is read anyway. A fetch that half
                // succeeded across several remotes still moved something, and
                // the state after a failure is exactly what the user now wants
                // to see.
                let _ = tx.send(Update::Says(format!("{}: {}", repo.name, brief(&err))));
            }
            if tx.send(Update::Row(Box::new(status(repo)))).is_err() {
                return;
            }
        }
    }
    let _ = tx.send(Update::Done);
}

/// A git failure in one line.
///
/// git's stderr is several lines of advice ending in the sentence that matters,
/// and a status line has room for one of them. The last non-empty line is the
/// error itself in every case that reaches here; the rest is what to do about
/// it, which is written for a shell the user is not at.
fn brief(err: &git::Error) -> String {
    let text = err.to_string();
    let last = text
        .lines()
        .rev()
        .map(str::trim)
        .find(|line| !line.is_empty());
    crate::tui::first_words(last.unwrap_or("failed"), 12)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::git::testing::init_repo;
    use chrono::{TimeZone, Utc};
    use std::process::Command;
    use tempfile::TempDir;

    fn repo_at(path: &Path, id: i64) -> Repo {
        let now = Utc.timestamp_opt(0, 0).unwrap();
        Repo {
            id,
            path: path.to_path_buf(),
            name: path
                .file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_default(),
            ignored: false,
            discovered_at: now,
            last_seen_at: now,
        }
    }

    fn git_in(repo: &Path, args: &[&str]) {
        let out = Command::new("git")
            .arg("-C")
            .arg(repo)
            .args(args)
            .output()
            .expect("git");
        assert!(out.status.success(), "git {args:?}: {out:?}");
    }

    fn commit(repo: &Path, name: &str) {
        std::fs::write(repo.join(name), name).unwrap();
        git_in(repo, &["add", "."]);
        git_in(repo, &["commit", "-q", "-m", name]);
    }

    /// An origin and a clone of it, both real, both on disk. `file://` remotes
    /// are ordinary remotes to git, so fetch and pull are exercised for real
    /// without a network.
    fn origin_and_clone(tmp: &TempDir) -> (PathBuf, PathBuf) {
        let origin = tmp.path().join("origin");
        init_repo(&origin, "main");
        let clone = tmp.path().join("clone");
        let out = Command::new("git")
            .args(["clone", "-q"])
            .arg(&origin)
            .arg(&clone)
            .output()
            .expect("git clone");
        assert!(out.status.success(), "clone failed: {out:?}");
        git_in(&clone, &["config", "user.email", "test@marver.invalid"]);
        git_in(&clone, &["config", "user.name", "marver tests"]);
        (origin, clone)
    }

    #[test]
    fn a_fresh_clone_is_level_with_its_upstream() {
        let tmp = TempDir::new().unwrap();
        let (_, clone) = origin_and_clone(&tmp);

        let row = status(&repo_at(&clone, 1));
        assert_eq!(row.branch.as_deref(), Some("main"));
        let upstream = row.upstream.expect("a clone tracks its origin");
        assert_eq!(upstream.reference, "origin/main");
        assert!(upstream.is_level(), "{upstream:?}");
        assert_eq!(row.dirty, 0);
        assert_eq!(row.trouble, None);
    }

    #[test]
    fn the_default_column_is_empty_when_it_would_repeat_the_upstream() {
        // On `main` tracking `origin/main` both comparisons are the same one,
        // and printing the number twice would read as two separate facts.
        let tmp = TempDir::new().unwrap();
        let (_, clone) = origin_and_clone(&tmp);

        let row = status(&repo_at(&clone, 1));
        assert!(row.upstream.is_some());
        assert_eq!(row.default, None, "{row:?}");
    }

    #[test]
    fn ahead_and_behind_are_counted_separately() {
        let tmp = TempDir::new().unwrap();
        let (origin, clone) = origin_and_clone(&tmp);
        commit(&origin, "theirs-one");
        commit(&origin, "theirs-two");
        commit(&clone, "ours");
        git_in(&clone, &["fetch", "-q"]);

        let upstream = status(&repo_at(&clone, 1)).upstream.expect("tracking");
        assert_eq!((upstream.ahead, upstream.behind), (1, 2));
        assert!(!upstream.is_level());
    }

    #[test]
    fn a_feature_branch_is_measured_against_the_default_too() {
        let tmp = TempDir::new().unwrap();
        let (origin, clone) = origin_and_clone(&tmp);
        commit(&origin, "theirs");
        git_in(&clone, &["fetch", "-q"]);
        git_in(&clone, &["checkout", "-q", "-b", "feature"]);
        commit(&clone, "mine");

        let row = status(&repo_at(&clone, 1));
        assert_eq!(row.branch.as_deref(), Some("feature"));
        assert_eq!(row.upstream, None, "a new branch tracks nothing yet");
        let default = row.default.expect("still comparable to main");
        assert_eq!(default.reference, "origin/main");
        assert_eq!((default.ahead, default.behind), (1, 1));
    }

    #[test]
    fn uncommitted_files_are_counted() {
        let tmp = TempDir::new().unwrap();
        let repo = tmp.path().join("solo");
        init_repo(&repo, "main");
        std::fs::write(repo.join("README.md"), "changed").unwrap();
        std::fs::write(repo.join("new.txt"), "untracked").unwrap();

        assert_eq!(status(&repo_at(&repo, 1)).dirty, 2);
    }

    #[test]
    fn a_repo_with_no_remote_is_compared_against_its_local_default() {
        let tmp = TempDir::new().unwrap();
        let repo = tmp.path().join("solo");
        init_repo(&repo, "main");
        git_in(&repo, &["checkout", "-q", "-b", "work"]);
        commit(&repo, "one");

        let row = status(&repo_at(&repo, 1));
        assert_eq!(row.upstream, None);
        let default = row.default.expect("main is still there to compare with");
        assert_eq!(default.reference, "main", "no origin to prefer");
        assert_eq!((default.ahead, default.behind), (1, 0));
    }

    #[test]
    fn a_detached_head_has_no_branch_and_no_trouble() {
        // Detached is where the repo is, not a failure to find out where it is,
        // and the screen says so in the branch column. `trouble` is reserved
        // for a row that could not be read at all.
        let tmp = TempDir::new().unwrap();
        let repo = tmp.path().join("solo");
        init_repo(&repo, "main");
        commit(&repo, "two");
        git_in(&repo, &["checkout", "-q", "HEAD~1"]);

        let row = status(&repo_at(&repo, 1));
        assert_eq!(row.branch, None);
        assert_eq!(row.trouble, None);
        assert_eq!(row.dirty, 0);
    }

    #[test]
    fn a_repo_that_has_gone_still_gets_a_row() {
        // Scans never delete, so a moved repo outlives the record of it.
        let tmp = TempDir::new().unwrap();
        let row = status(&repo_at(&tmp.path().join("was-here"), 7));

        assert_eq!(row.repo_id, 7);
        assert_eq!(row.name, "was-here");
        assert_eq!(row.trouble.as_deref(), Some("gone from disk"));
    }

    #[test]
    fn refresh_reports_a_row_each_and_then_stops() {
        let tmp = TempDir::new().unwrap();
        let one = tmp.path().join("one");
        let two = tmp.path().join("two");
        init_repo(&one, "main");
        init_repo(&two, "main");

        let (tx, rx) = channel();
        run(Job::Refresh(vec![repo_at(&one, 1), repo_at(&two, 2)]), &tx);
        drop(tx);

        let updates: Vec<_> = rx.iter().collect();
        assert_eq!(updates.len(), 3, "two rows and a done: {updates:?}");
        assert_eq!(updates[2], Update::Done);
        assert!(matches!(&updates[0], Update::Row(row) if row.repo_id == 1));
        assert!(matches!(&updates[1], Update::Row(row) if row.repo_id == 2));
    }

    #[test]
    fn fetching_updates_the_counts_without_moving_the_branch() {
        let tmp = TempDir::new().unwrap();
        let (origin, clone) = origin_and_clone(&tmp);
        commit(&origin, "theirs");

        let before = status(&repo_at(&clone, 1)).upstream.expect("tracking");
        assert!(before.is_level(), "nothing fetched yet: {before:?}");

        let (tx, rx) = channel();
        run(Job::Fetch(repo_at(&clone, 1)), &tx);
        drop(tx);

        let after = rows(rx).pop().expect("a row").upstream.expect("tracking");
        assert_eq!((after.ahead, after.behind), (0, 1), "it is now behind");
        assert_eq!(
            git::head_branch(&clone).unwrap().as_deref(),
            Some("main"),
            "fetch moves no branch"
        );
    }

    #[test]
    fn pulling_fast_forwards_and_the_row_says_so() {
        let tmp = TempDir::new().unwrap();
        let (origin, clone) = origin_and_clone(&tmp);
        commit(&origin, "theirs");

        let (tx, rx) = channel();
        run(Job::Pull(repo_at(&clone, 1)), &tx);
        drop(tx);

        let row = rows(rx).pop().expect("a row");
        assert!(row.upstream.expect("tracking").is_level(), "caught up");
        assert!(clone.join("theirs").exists(), "the work arrived");
    }

    #[test]
    fn a_pull_that_cannot_fast_forward_is_refused_and_reported() {
        // Both sides moved. `--ff-only` is what keeps this from leaving
        // conflict markers in a repo the user is not looking at.
        let tmp = TempDir::new().unwrap();
        let (origin, clone) = origin_and_clone(&tmp);
        commit(&origin, "theirs");
        commit(&clone, "ours");

        let (tx, rx) = channel();
        run(Job::Pull(repo_at(&clone, 1)), &tx);
        drop(tx);

        let updates: Vec<_> = rx.iter().collect();
        assert!(
            updates.iter().any(|u| matches!(u, Update::Says(_))),
            "the refusal must be reported: {updates:?}"
        );
        assert!(
            updates
                .iter()
                .any(|u| matches!(u, Update::Row(row) if row.upstream.is_some())),
            "and the row read anyway: {updates:?}"
        );
        assert!(clone.join("ours").exists(), "local work is untouched");
    }

    #[test]
    fn a_job_stops_when_the_screen_it_was_for_has_gone() {
        let tmp = TempDir::new().unwrap();
        let repo = tmp.path().join("one");
        init_repo(&repo, "main");

        let (tx, rx) = channel();
        drop(rx);
        // The point is that it returns rather than panicking on the send.
        run(Job::Refresh(vec![repo_at(&repo, 1)]), &tx);
    }

    fn rows(rx: Receiver<Update>) -> Vec<RepoStatus> {
        rx.iter()
            .filter_map(|update| match update {
                Update::Row(row) => Some(*row),
                _ => None,
            })
            .collect()
    }
}