marver 0.0.29

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
//! Getting a task's work off this machine.
//!
//! A task used to end at a local commit, which is a real answer — the work is
//! safe on a branch — but not one anybody else can see. `P` sends the branches
//! to `origin` and `O` opens a pull request for each, both from the task list,
//! because that is where a finished task sits doing nothing.
//!
//! **A task spans repos, so both are plural.** One branch name across N repos
//! means N pushes and N pull requests, each against the base *that repo's*
//! worktree was cut from. There is no combining them: git has no cross-repo
//! push, and a forge has no cross-repo pull request. Every repo is reported on
//! its own line and one failing does not stop the rest — unlike committing,
//! which is all-or-nothing because half a commit has no name. Half a push is
//! just a push, and the other half can be pressed again.
//!
//! **Nothing here is forced and nothing is destructive.** A push that is
//! rejected is reported; a pull request that already exists is found and its
//! URL given back rather than a second one being opened.
//!
//! The description is not invented. A pull request's title is the task's title
//! and its body is the prompt the agent was given, which is the most accurate
//! statement of intent that exists — nothing here asks a model to write prose
//! about a diff it would have to guess at.

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

use crate::domain::Task;
use crate::git;
use crate::store::Store;

/// The program that opens pull requests.
pub const FORGE: &str = "gh";

/// One repo's worktree, and where its branch is going.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Target {
    pub repo: String,
    pub worktree: PathBuf,
    pub branch: String,
    /// What the branch was cut from, recorded when the worktree was made. The
    /// pull request goes back to the same place.
    pub base: String,
}

/// Every provisioned repo of a task, in the order they were selected.
pub fn targets(store: &Store, task: &Task) -> crate::store::Result<Vec<Target>> {
    let mut out = Vec::new();
    for link in store.list_task_repos(task.id)? {
        let (Some(worktree), Some(branch)) = (link.worktree_path, link.branch) else {
            continue;
        };
        let repo = match store.get_repo(link.repo_id) {
            Ok(repo) => repo.name,
            Err(_) => continue,
        };
        out.push(Target {
            repo,
            worktree,
            branch,
            base: link.base_ref.unwrap_or_default(),
        });
    }
    Ok(out)
}

/// What the task list asked for.
#[derive(Debug, Clone)]
pub enum Job {
    Push(Vec<Target>),
    Open {
        targets: Vec<Target>,
        title: String,
        body: String,
    },
}

impl Job {
    /// What to say while it runs.
    pub fn doing(&self) -> String {
        let repos = match self {
            Job::Push(targets) => targets.len(),
            Job::Open { targets, .. } => targets.len(),
        };
        match self {
            Job::Push(_) => format!("pushing {}", crate::tui::plural(repos, "branch")),
            Job::Open { .. } => format!("opening {}", crate::tui::plural(repos, "pull request")),
        }
    }
}

/// What a running job reports, in the order it happens.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Update {
    /// Something for the status line.
    Says(String),
    /// A pull request now exists — whether this run opened it or found it.
    Opened { repo: String, url: String },
    /// Nothing further is coming.
    Done,
}

/// Run a job on its own thread, reporting back down the returned channel.
///
/// Off the interface's thread for the same reason fetching is: this reaches a
/// network, and a screen that stops redrawing until it answers is a screen that
/// looks like it has crashed.
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.
pub fn run(job: Job, tx: &Sender<Update>) {
    match job {
        Job::Push(targets) => {
            for target in &targets {
                let _ = tx.send(match push(target) {
                    Ok(Pushed::Sent) => Update::Says(format!("pushed {}", target.repo)),
                    Ok(Pushed::NoRemote) => {
                        Update::Says(format!("{}: no remote to push to", target.repo))
                    }
                    Err(why) => Update::Says(format!("{}: {why}", target.repo)),
                });
            }
        }
        Job::Open {
            targets,
            title,
            body,
        } => {
            if !available() {
                let _ = tx.send(Update::Says(format!(
                    "{FORGE} is not installed, so there is nothing to open a pull request with"
                )));
                let _ = tx.send(Update::Done);
                return;
            }
            for target in &targets {
                // A pull request cannot describe commits the remote does not
                // have, so this is not an optional first step.
                match push(target) {
                    Ok(Pushed::Sent) => {}
                    Ok(Pushed::NoRemote) => {
                        let _ = tx.send(Update::Says(format!(
                            "{}: no remote, so no pull request",
                            target.repo
                        )));
                        continue;
                    }
                    Err(why) => {
                        let _ = tx.send(Update::Says(format!("{}: {why}", target.repo)));
                        continue;
                    }
                }
                let _ = tx.send(match open(target, &title, &body) {
                    Ok(Opened::Created(url)) => Update::Opened {
                        repo: target.repo.clone(),
                        url,
                    },
                    // Not an error, and not a second pull request: pressing the
                    // key twice is how anyone would ask "did that work?".
                    Ok(Opened::Already(url)) => Update::Opened {
                        repo: target.repo.clone(),
                        url,
                    },
                    Err(why) => Update::Says(format!("{}: {why}", target.repo)),
                });
            }
        }
    }
    let _ = tx.send(Update::Done);
}

enum Pushed {
    Sent,
    /// Nothing to push to. Ordinary for a repo that was never given a remote.
    NoRemote,
}

fn push(target: &Target) -> std::result::Result<Pushed, String> {
    match git::has_remote(&target.worktree) {
        Ok(true) => {}
        Ok(false) => return Ok(Pushed::NoRemote),
        Err(err) => return Err(err.to_string()),
    }
    git::push(&target.worktree, &target.branch)
        .map(|()| Pushed::Sent)
        .map_err(|err| trim(&err.to_string()))
}

enum Opened {
    Created(String),
    Already(String),
}

/// Whether the forge CLI is on the path.
pub fn available() -> bool {
    Command::new(FORGE)
        .arg("--version")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok_and(|status| status.success())
}

fn open(target: &Target, title: &str, body: &str) -> std::result::Result<Opened, String> {
    if let Some(url) = existing(target) {
        return Ok(Opened::Already(url));
    }
    let mut command = Command::new(FORGE);
    command
        .current_dir(&target.worktree)
        .args(["pr", "create"])
        .args(["--head", &target.branch])
        .args(["--title", title])
        .args(["--body", body]);
    // A base recorded as empty means the worktree predates it being written
    // down; the forge's own default is a better guess than a wrong branch.
    if !target.base.is_empty() {
        command.args(["--base", &target.base]);
    }

    let output = command.output().map_err(|err| err.to_string())?;
    if !output.status.success() {
        return Err(trim(&String::from_utf8_lossy(&output.stderr)));
    }
    // `gh` prints the URL of what it made, and nothing else worth keeping.
    let url = String::from_utf8_lossy(&output.stdout)
        .lines()
        .rev()
        .find(|line| line.starts_with("http"))
        .unwrap_or_default()
        .to_string();
    Ok(Opened::Created(url))
}

/// The pull request already open for this branch, if there is one.
fn existing(target: &Target) -> Option<String> {
    let output = Command::new(FORGE)
        .current_dir(&target.worktree)
        .args([
            "pr",
            "view",
            &target.branch,
            "--json",
            "url",
            "--jq",
            ".url",
        ])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let url = String::from_utf8_lossy(&output.stdout).trim().to_string();
    url.starts_with("http").then_some(url)
}

/// The last line of a program's complaint, which is the part that says what
/// went wrong. `git push` and `gh` both print several, and the status line has
/// room for one.
fn trim(stderr: &str) -> String {
    stderr
        .lines()
        .map(str::trim)
        .rfind(|line| !line.is_empty())
        .unwrap_or("failed")
        .to_string()
}

/// The event recording that a pull request exists, so the URL outlives the
/// status line that announced it. Read back by [`crate::brief`].
pub const OPENED_EVENT: &str = "pr.opened";

/// Write down that a pull request exists.
pub fn record(store: &Store, task_id: i64, repo: &str, url: &str) {
    let _ = store.append_event(
        Some(task_id),
        OPENED_EVENT,
        &serde_json::json!({ "repo": repo, "url": url }),
        chrono::Utc::now(),
    );
}

/// A pull request's title and body, from what the task was asked to do.
pub fn description(task: &Task) -> (String, String) {
    let title = task.title.trim();
    let title = if title.is_empty() {
        format!("marver task {}", task.id)
    } else {
        title.to_string()
    };
    let mut body = task.prompt.trim().to_string();
    if body.is_empty() {
        body.push_str("_No prompt was recorded._");
    }
    body.push_str(&format!("\n\n---\nmarver task {}\n", task.id));
    (title, body)
}

/// Whether a path is inside a worktree that still exists. A task whose
/// directory has been reclaimed has nothing left to push.
pub fn is_live(target: &Target) -> bool {
    Path::new(&target.worktree).exists()
}

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

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

    fn task_with(title: &str, prompt: &str) -> Task {
        let mut store = Store::open_in_memory().unwrap();
        store
            .create_task(title, prompt, Path::new("/tmp/tasks"), &[], at(0))
            .unwrap()
    }

    /// A repo with a bare `origin` beside it, so a push has somewhere to go.
    fn repo_with_origin(root: &Path, name: &str) -> (PathBuf, PathBuf) {
        let repo = root.join(name);
        init_repo(&repo, "main");
        let origin = root.join(format!("{name}.git"));
        std::process::Command::new("git")
            .args(["init", "--bare", "--initial-branch=main"])
            .arg(&origin)
            .output()
            .expect("git init --bare");
        git::run(
            &repo,
            &["remote", "add", "origin", origin.to_str().unwrap()],
        )
        .unwrap();
        (repo, origin)
    }

    #[test]
    fn a_description_comes_from_what_the_task_was_asked_to_do() {
        // Not from a model asked to write prose about a diff it would have to
        // guess at. The prompt is the most accurate statement of intent there
        // is.
        let task = task_with(
            "Fix the auth flow",
            "Sessions drop after an hour.\nFind out why.",
        );
        let (title, body) = description(&task);

        assert_eq!(title, "Fix the auth flow");
        assert!(body.starts_with("Sessions drop after an hour."), "{body}");
        assert!(body.contains("Find out why."), "every line of it: {body}");
        assert!(body.contains(&format!("marver task {}", task.id)), "{body}");
    }

    #[test]
    fn a_task_with_no_title_still_gets_one() {
        let task = task_with("", "do the thing");
        let (title, _) = description(&task);
        assert_eq!(title, format!("marver task {}", task.id));
    }

    #[test]
    fn a_task_with_no_prompt_still_gets_a_body() {
        // An empty body is refused by every forge there is.
        let task = task_with("Something", "");
        let (_, body) = description(&task);
        assert!(!body.trim().is_empty());
        assert!(body.contains("No prompt"), "{body}");
    }

    #[test]
    fn a_branch_reaches_the_remote() {
        let tmp = TempDir::new().unwrap();
        let (repo, origin) = repo_with_origin(tmp.path(), "api");
        git::run(&repo, &["checkout", "-q", "-b", "marver/1-thing"]).unwrap();
        std::fs::write(repo.join("new.rs"), "fn f() {}\n").unwrap();
        git::stage_all(&repo).unwrap();
        git::commit(&repo, "agent work").unwrap();

        let target = Target {
            repo: "api".to_string(),
            worktree: repo.clone(),
            branch: "marver/1-thing".to_string(),
            base: "main".to_string(),
        };
        let (tx, rx) = channel();
        run(Job::Push(vec![target]), &tx);

        // Dropped first: `rx.iter()` runs until the channel disconnects, and
        // this is the last sender.
        drop(tx);
        let said: Vec<Update> = rx.iter().collect();
        assert_eq!(
            said,
            vec![Update::Says("pushed api".to_string()), Update::Done],
            "{said:?}"
        );
        assert!(
            git::ref_exists(&origin, "refs/heads/marver/1-thing").unwrap(),
            "the branch must be on the remote"
        );
    }

    #[test]
    fn a_repo_with_no_remote_is_said_rather_than_failed() {
        // Ordinary: a repo nobody ever gave a remote to.
        let tmp = TempDir::new().unwrap();
        let repo = tmp.path().join("local");
        init_repo(&repo, "main");

        let (tx, rx) = channel();
        run(
            Job::Push(vec![Target {
                repo: "local".to_string(),
                worktree: repo,
                branch: "main".to_string(),
                base: "main".to_string(),
            }]),
            &tx,
        );

        // Dropped first: `rx.iter()` runs until the channel disconnects, and
        // this is the last sender.
        drop(tx);
        let said: Vec<Update> = rx.iter().collect();
        assert_eq!(
            said[0],
            Update::Says("local: no remote to push to".to_string())
        );
    }

    #[test]
    fn one_repo_failing_does_not_stop_the_others() {
        // Unlike committing, which is all or nothing. Half a push is just a
        // push, and the other half can be pressed again.
        let tmp = TempDir::new().unwrap();
        let (good, _) = repo_with_origin(tmp.path(), "api");
        git::run(&good, &["checkout", "-q", "-b", "marver/1-x"]).unwrap();
        let broken = tmp.path().join("broken");
        std::fs::create_dir_all(&broken).unwrap();

        let (tx, rx) = channel();
        run(
            Job::Push(vec![
                Target {
                    repo: "broken".to_string(),
                    worktree: broken,
                    branch: "marver/1-x".to_string(),
                    base: "main".to_string(),
                },
                Target {
                    repo: "api".to_string(),
                    worktree: good,
                    branch: "marver/1-x".to_string(),
                    base: "main".to_string(),
                },
            ]),
            &tx,
        );

        // Dropped first: `rx.iter()` runs until the channel disconnects, and
        // this is the last sender.
        drop(tx);
        let said: Vec<Update> = rx.iter().collect();
        assert_eq!(said.len(), 3, "one line each, then Done: {said:?}");
        assert_eq!(said[2], Update::Done);
        assert!(
            matches!(&said[1], Update::Says(line) if line == "pushed api"),
            "the second repo still went: {said:?}"
        );
    }

    #[test]
    fn a_push_that_is_rejected_says_what_the_remote_said() {
        let tmp = TempDir::new().unwrap();
        let (repo, origin) = repo_with_origin(tmp.path(), "api");
        // The remote moves ahead of us, so a plain push cannot fast-forward.
        git::push(&repo, "main").unwrap();
        let other = tmp.path().join("other");
        std::process::Command::new("git")
            .args(["clone", "-q", origin.to_str().unwrap()])
            .arg(&other)
            .output()
            .unwrap();
        git::run(&other, &["config", "user.email", "t@m"]).unwrap();
        git::run(&other, &["config", "user.name", "t"]).unwrap();
        std::fs::write(other.join("theirs.rs"), "fn g() {}\n").unwrap();
        git::stage_all(&other).unwrap();
        git::commit(&other, "someone else").unwrap();
        git::push(&other, "main").unwrap();

        std::fs::write(repo.join("ours.rs"), "fn f() {}\n").unwrap();
        git::stage_all(&repo).unwrap();
        git::commit(&repo, "ours").unwrap();

        let (tx, rx) = channel();
        run(
            Job::Push(vec![Target {
                repo: "api".to_string(),
                worktree: repo,
                branch: "main".to_string(),
                base: "main".to_string(),
            }]),
            &tx,
        );

        // Dropped first: `rx.iter()` runs until the channel disconnects, and
        // this is the last sender.
        drop(tx);
        let said: Vec<Update> = rx.iter().collect();
        let Update::Says(line) = &said[0] else {
            panic!("expected a complaint: {said:?}");
        };
        assert!(line.starts_with("api: "), "named: {line}");
        assert!(
            !git::ref_exists(
                std::path::Path::new(&origin),
                "refs/heads/definitely-not-there"
            )
            .unwrap()
        );
    }

    #[test]
    fn opening_without_the_forge_installed_says_so_once() {
        // Rather than once per repo, which for a five-repo task is five copies
        // of the same sentence in a status line that shows one.
        if available() {
            return; // gh is here, so there is nothing to simulate
        }
        let (tx, rx) = channel();
        run(
            Job::Open {
                targets: vec![
                    Target {
                        repo: "a".into(),
                        worktree: PathBuf::from("/tmp"),
                        branch: "b".into(),
                        base: "main".into(),
                    },
                    Target {
                        repo: "b".into(),
                        worktree: PathBuf::from("/tmp"),
                        branch: "b".into(),
                        base: "main".into(),
                    },
                ],
                title: "t".into(),
                body: "b".into(),
            },
            &tx,
        );
        // Dropped first: `rx.iter()` runs until the channel disconnects, and
        // this is the last sender.
        drop(tx);
        let said: Vec<Update> = rx.iter().collect();
        assert_eq!(said.len(), 2, "one complaint and Done: {said:?}");
        let Update::Says(line) = &said[0] else {
            panic!("{said:?}")
        };
        assert!(line.contains(FORGE), "{line}");
    }

    #[test]
    fn targets_skip_a_repo_that_was_never_provisioned() {
        let tmp = TempDir::new().unwrap();
        let mut store = Store::open_in_memory().unwrap();
        let path = tmp.path().join("api");
        init_repo(&path, "main");
        let repo = store.upsert_repo(&path, "api", at(0)).unwrap();
        let task = store
            .create_task("t", "p", tmp.path(), &[repo.id], at(0))
            .unwrap();

        assert!(
            targets(&store, &task).unwrap().is_empty(),
            "selected is not provisioned"
        );

        store
            .record_worktree(task.id, repo.id, &path, "marver/1-t", "main")
            .unwrap();
        let found = targets(&store, &task).unwrap();
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].repo, "api");
        assert_eq!(found[0].branch, "marver/1-t");
        assert_eq!(found[0].base, "main");
    }

    #[test]
    fn a_pull_request_url_outlives_the_line_that_announced_it() {
        // The status line lasts 500ms and a URL is the whole point.
        let tmp = TempDir::new().unwrap();
        let mut store = Store::open_in_memory().unwrap();
        let task = store.create_task("t", "p", tmp.path(), &[], at(0)).unwrap();

        record(&store, task.id, "api", "https://example.test/pr/1");

        let events = store.list_events(task.id).unwrap();
        let found = events
            .iter()
            .find(|e| e.kind == OPENED_EVENT)
            .expect("recorded");
        assert_eq!(found.payload["repo"], "api");
        assert_eq!(found.payload["url"], "https://example.test/pr/1");
        assert_eq!(TaskState::Queued, store.get_task(task.id).unwrap().state);
    }
}