marver 0.0.2

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
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
//! Reviewing and committing what an agent produced.
//!
//! The last step of a task: see the diff, stage what you want, commit. This
//! module is the data and operations behind that; drawing it is the TUI's job.
//!
//! Two things shape the design:
//!
//! - **A task can span repos**, so a review is the union of several worktrees
//!   and a commit happens in each that has staged changes — one message, one
//!   logical change, several commits.
//! - **Untracked files are first-class.** `git diff` ignores them entirely, so
//!   a review built only from diffs would silently omit every file the agent
//!   created, which is usually most of the interesting work.

use std::path::PathBuf;

use chrono::{DateTime, Utc};

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

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error(transparent)]
    Git(#[from] git::Error),
    #[error(transparent)]
    Store(#[from] crate::store::Error),
    #[error("task {0} has no worktrees to review")]
    NotProvisioned(i64),
    #[error("nothing is staged")]
    NothingStaged,
    #[error("{path} has an unresolved conflict in {}", worktree.display())]
    Unmerged { worktree: PathBuf, path: String },
    #[error("a commit message is required")]
    EmptyMessage,
}

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

/// What happened to a file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Change {
    Added,
    Modified,
    Deleted,
    Renamed,
    Copied,
    /// Not yet known to git at all.
    Untracked,
    /// A status this version does not model.
    Other,
}

impl Change {
    fn from_status(entry: &git::StatusEntry) -> Self {
        if entry.is_untracked() {
            return Self::Untracked;
        }
        // The index character wins when both are set: it is what a commit
        // would actually record.
        let code = if entry.index != ' ' {
            entry.index
        } else {
            entry.worktree
        };
        match code {
            'A' => Self::Added,
            'M' => Self::Modified,
            'D' => Self::Deleted,
            'R' => Self::Renamed,
            'C' => Self::Copied,
            _ => Self::Other,
        }
    }
}

/// One changed file within one of a task's worktrees.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileChange {
    pub repo_id: i64,
    /// Which worktree it lives in.
    pub worktree: PathBuf,
    /// Path relative to the worktree root.
    pub path: String,
    pub change: Change,
    pub staged: bool,
    pub unstaged: bool,
    /// Previous path, for renames.
    pub original: Option<String>,
}

impl FileChange {
    /// Absolute path on disk.
    pub fn absolute(&self) -> PathBuf {
        self.worktree.join(&self.path)
    }
}

/// Everything a task changed, across every repo it targets.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Review {
    pub files: Vec<FileChange>,
    /// How many of the task's repos actually had a worktree to look at.
    ///
    /// Zero and "no files changed" are different answers to different
    /// questions, and only this field can tell them apart: a task whose repos
    /// are selected but not yet provisioned reports no changes, which reads as
    /// "the agent produced nothing" when the agent has not run.
    pub worktrees: usize,
}

impl Review {
    pub fn is_empty(&self) -> bool {
        self.files.is_empty()
    }

    /// Whether there is anything to review at all yet.
    pub fn is_provisioned(&self) -> bool {
        self.worktrees > 0
    }

    pub fn staged(&self) -> impl Iterator<Item = &FileChange> {
        self.files.iter().filter(|f| f.staged)
    }

    pub fn has_staged(&self) -> bool {
        self.files.iter().any(|f| f.staged)
    }
}

/// One line of a unified diff.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiffLine {
    Context(String),
    Added(String),
    Removed(String),
    /// `\ No newline at end of file` and similar annotations.
    Note(String),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Hunk {
    /// The `@@ ... @@` line, verbatim.
    pub header: String,
    pub lines: Vec<DiffLine>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileDiff {
    pub path: String,
    pub hunks: Vec<Hunk>,
    /// Git reported the file as binary; there is nothing to show.
    pub binary: bool,
    /// An unmerged file, shown as a combined diff against both parents.
    pub conflicted: bool,
}

impl FileDiff {
    pub fn is_empty(&self) -> bool {
        self.hunks.is_empty() && !self.binary
    }
}

/// Parse unified diff text into per-file hunks.
///
/// Tolerant by design: anything unrecognised outside a hunk is skipped rather
/// than treated as an error, since git emits `index`, `similarity`, and mode
/// lines this does not need.
pub fn parse_diff(text: &str) -> Vec<FileDiff> {
    let mut files: Vec<FileDiff> = Vec::new();
    // How many marker columns the current hunk's lines carry. An ordinary diff
    // has one; a combined diff has one per parent.
    let mut markers = 1usize;

    for line in text.lines() {
        if let Some(rest) = line.strip_prefix("diff --git ") {
            markers = 1;
            files.push(FileDiff {
                path: path_from_diff_header(rest),
                hunks: Vec::new(),
                binary: false,
                conflicted: false,
            });
            continue;
        }
        // What git emits for an unmerged file. Matching only `diff --git` meant
        // a conflicted file parsed to nothing at all — a blank diff for the one
        // file that most needs looking at.
        if let Some(rest) = line
            .strip_prefix("diff --cc ")
            .or_else(|| line.strip_prefix("diff --combined "))
        {
            markers = 2;
            files.push(FileDiff {
                path: rest.trim().to_string(),
                hunks: Vec::new(),
                binary: false,
                conflicted: true,
            });
            continue;
        }

        let Some(file) = files.last_mut() else {
            continue;
        };

        if line.starts_with("Binary files ") || line.starts_with("GIT binary patch") {
            file.binary = true;
            continue;
        }
        if line.starts_with("@@") {
            // `@@ ... @@` has one marker column, `@@@ ... @@@` two, and so on.
            markers = line.chars().take_while(|&c| c == '@').count().max(2) - 1;
            file.hunks.push(Hunk {
                header: line.to_string(),
                lines: Vec::new(),
            });
            continue;
        }

        let Some(hunk) = file.hunks.last_mut() else {
            // Header noise between files: index, ---, +++, mode changes.
            continue;
        };
        if line.is_empty() {
            // A completely empty line inside a hunk is an empty context line.
            hunk.lines.push(DiffLine::Context(String::new()));
            continue;
        }
        if line.starts_with('\\') {
            hunk.lines.push(DiffLine::Note(line.to_string()));
            continue;
        }

        // By chars, not bytes. Slicing `line[1..]` panicked outright when a
        // line began with a multi-byte character, and the fallback arm below
        // exists precisely because the leading character may be unexpected.
        let prefix: String = line.chars().take(markers).collect();
        let body: String = line.chars().skip(markers).collect();
        hunk.lines.push(if prefix.contains('+') {
            DiffLine::Added(body)
        } else if prefix.contains('-') {
            DiffLine::Removed(body)
        } else if prefix.chars().all(|c| c == ' ') {
            DiffLine::Context(body)
        } else {
            DiffLine::Context(line.to_string())
        });
    }

    files
}

/// Pull the path out of `a/some/file b/some/file`.
///
/// Prefers the `b/` side so renames report where the file ended up.
fn path_from_diff_header(rest: &str) -> String {
    if let Some(index) = rest.find(" b/") {
        return rest[index + 3..].to_string();
    }
    rest.strip_prefix("a/").unwrap_or(rest).to_string()
}

/// What a commit produced, per repo.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RepoCommit {
    pub repo_id: i64,
    pub worktree: PathBuf,
    /// Short hash of the new commit.
    pub commit: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Committed {
    pub commits: Vec<RepoCommit>,
}

pub struct Reviewer;

impl Reviewer {
    /// Every change across a task's worktrees.
    ///
    /// Repos the task selected but never provisioned are skipped: a queued task
    /// has nothing to review.
    pub fn review(store: &Store, task: &Task) -> Result<Review> {
        let mut files = Vec::new();
        let mut worktrees = 0;
        for link in store.list_task_repos(task.id)? {
            let Some(worktree) = link.worktree_path.clone() else {
                continue;
            };
            worktrees += 1;
            for entry in git::status(&worktree)? {
                files.push(FileChange {
                    repo_id: link.repo_id,
                    worktree: worktree.clone(),
                    change: Change::from_status(&entry),
                    staged: entry.is_staged(),
                    unstaged: entry.is_unstaged(),
                    original: entry.original.clone(),
                    path: entry.path,
                });
            }
        }
        // Stable ordering so a redraw does not shuffle the list under the
        // user's cursor.
        files.sort_by(|a, b| (&a.worktree, &a.path).cmp(&(&b.worktree, &b.path)));
        Ok(Review { files, worktrees })
    }

    /// The diff for one file, parsed for display.
    ///
    /// `staged` shows what would be committed rather than what is on disk.
    /// Untracked files are diffed against nothing, since `git diff` skips them.
    pub fn file_diff(file: &FileChange, staged: bool) -> Result<FileDiff> {
        let text = if file.change == Change::Untracked {
            git::diff_untracked(&file.worktree, &file.path)?
        } else {
            git::diff(&file.worktree, Some(&file.path), staged)?
        };
        Ok(parse_diff(&text)
            .into_iter()
            .next()
            .unwrap_or_else(|| FileDiff {
                path: file.path.clone(),
                hunks: Vec::new(),
                binary: false,
                conflicted: false,
            }))
    }

    pub fn stage(file: &FileChange) -> Result<()> {
        git::stage(&file.worktree, &file.path)?;
        Ok(())
    }

    pub fn unstage(file: &FileChange) -> Result<()> {
        git::unstage(&file.worktree, &file.path)?;
        Ok(())
    }

    /// Stage everything in every provisioned worktree.
    pub fn stage_all(store: &Store, task: &Task) -> Result<()> {
        for worktree in Self::worktrees(store, task)? {
            git::stage_all(&worktree)?;
        }
        Ok(())
    }

    /// Commit the staged changes in every worktree that has any, then move the
    /// task to `committed`.
    ///
    /// One message across all repos: it is one logical change that happens to
    /// span several repositories. A repo with nothing staged is skipped rather
    /// than producing an empty commit.
    pub fn commit(
        store: &mut Store,
        task: &Task,
        message: &str,
        now: DateTime<Utc>,
    ) -> Result<Committed> {
        if message.trim().is_empty() {
            return Err(Error::EmptyMessage);
        }

        let links = store.list_task_repos(task.id)?;
        let mut pending = Vec::new();
        for link in &links {
            let Some(worktree) = link.worktree_path.clone() else {
                continue;
            };
            // An unmerged file counts as staged to `has_staged_changes`, so the
            // commit was offered and then died on a raw `fatal: Exiting because
            // of an unresolved conflict`. Checked across every worktree before
            // any commit lands, since a commit here is not undoable.
            if let Some(entry) = git::status(&worktree)?.iter().find(|e| e.is_unmerged()) {
                return Err(Error::Unmerged {
                    worktree,
                    path: entry.path.clone(),
                });
            }
            if git::has_staged_changes(&worktree)? {
                pending.push((link.repo_id, worktree));
            }
        }
        if pending.is_empty() {
            return Err(Error::NothingStaged);
        }

        let mut commits = Vec::new();
        for (repo_id, worktree) in pending {
            let hash = git::commit(&worktree, message)?;
            commits.push(RepoCommit {
                repo_id,
                worktree,
                commit: hash,
            });
        }

        // The store rejects this if the task was not awaiting review, which
        // stops a stale screen committing a task the user already cancelled.
        store.transition(task.id, TaskState::Committed, Transition::Plain, now)?;
        Ok(Committed { commits })
    }

    fn worktrees(store: &Store, task: &Task) -> Result<Vec<PathBuf>> {
        let paths: Vec<PathBuf> = store
            .list_task_repos(task.id)?
            .into_iter()
            .filter_map(|link| link.worktree_path)
            .collect();
        if paths.is_empty() {
            return Err(Error::NotProvisioned(task.id));
        }
        Ok(paths)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::Repo;
    use crate::git::testing::init_repo;
    use tempfile::TempDir;

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

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

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

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

        /// A task with a worktree per repo, walked to `awaiting-review`.
        fn task_with_worktrees(&mut self, repos: &[Repo]) -> Task {
            let ids: Vec<i64> = repos.iter().map(|r| r.id).collect();
            let task = self
                .store
                .create_task("Fix it", "p", &self.tasks_dir, &ids, at(0))
                .unwrap();

            for repo in repos {
                let worktree = task.workspace_dir.join(&repo.name);
                std::fs::create_dir_all(&task.workspace_dir).unwrap();
                git::worktree_add(&repo.path, &worktree, &format!("t{}", task.id), "main").unwrap();
                self.store
                    .record_worktree(
                        task.id,
                        repo.id,
                        &worktree,
                        &format!("t{}", task.id),
                        "main",
                    )
                    .unwrap();
            }

            self.store
                .transition(task.id, TaskState::Running, Transition::Plain, at(1))
                .unwrap();
            self.store
                .transition(task.id, TaskState::AwaitingReview, Transition::Plain, at(2))
                .unwrap();
            self.store.get_task(task.id).unwrap()
        }

        fn worktree(&self, task: &Task, repo: &Repo) -> PathBuf {
            task.workspace_dir.join(&repo.name)
        }
    }

    // ---- diff parsing ----

    #[test]
    fn parses_a_simple_diff() {
        let text = "diff --git a/src/main.rs b/src/main.rs\n\
                    index 83db48f..bf269f4 100644\n\
                    --- a/src/main.rs\n\
                    +++ b/src/main.rs\n\
                    @@ -1,3 +1,4 @@\n\
                     fn main() {\n\
                    -    old();\n\
                    +    new();\n\
                    +    extra();\n\
                     }\n";
        let files = parse_diff(text);

        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "src/main.rs");
        assert_eq!(files[0].hunks.len(), 1);
        assert_eq!(files[0].hunks[0].header, "@@ -1,3 +1,4 @@");
        assert_eq!(
            files[0].hunks[0].lines,
            [
                DiffLine::Context("fn main() {".into()),
                DiffLine::Removed("    old();".into()),
                DiffLine::Added("    new();".into()),
                DiffLine::Added("    extra();".into()),
                DiffLine::Context("}".into()),
            ]
        );
    }

    #[test]
    fn parses_several_files_and_hunks() {
        let text = "diff --git a/a.txt b/a.txt\n\
                    @@ -1 +1 @@\n\
                    -one\n\
                    +ONE\n\
                    @@ -10 +10 @@\n\
                    -ten\n\
                    +TEN\n\
                    diff --git a/b.txt b/b.txt\n\
                    @@ -1 +1 @@\n\
                    -two\n\
                    +TWO\n";
        let files = parse_diff(text);
        assert_eq!(files.len(), 2);
        assert_eq!(files[0].hunks.len(), 2);
        assert_eq!(files[1].path, "b.txt");
    }

    #[test]
    fn a_rename_reports_where_the_file_ended_up() {
        let files = parse_diff("diff --git a/old/name.rs b/new/name.rs\n@@ -1 +1 @@\n x\n");
        assert_eq!(files[0].path, "new/name.rs");
    }

    #[test]
    fn a_conflicted_file_parses_as_a_combined_diff() {
        // Verbatim from a real merge conflict. Only `diff --git` was matched,
        // so this parsed to nothing: a blank diff for the one file that most
        // needs looking at.
        let text = "diff --cc c.txt\n\
                    index ba2906d,e45c9c2..0000000\n\
                    --- a/c.txt\n\
                    +++ b/c.txt\n\
                    @@@ -1,1 -1,1 +1,5 @@@\n\
                    ++<<<<<<< HEAD\n\
                    \x20+main\n\
                    ++=======\n\
                    + other\n\
                    ++>>>>>>> other\n";
        let files = parse_diff(text);

        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "c.txt");
        assert!(files[0].conflicted);
        assert!(!files[0].is_empty(), "a conflict is not an empty diff");
        // Two marker columns, so the body starts after both.
        assert_eq!(
            files[0].hunks[0].lines,
            [
                DiffLine::Added("<<<<<<< HEAD".into()),
                DiffLine::Added("main".into()),
                DiffLine::Added("=======".into()),
                DiffLine::Added("other".into()),
                DiffLine::Added(">>>>>>> other".into()),
            ]
        );
    }

    #[test]
    fn a_multibyte_leading_character_does_not_panic() {
        // `line[1..]` was a byte slice, so any line beginning with a multi-byte
        // character crashed the whole TUI. The fallback arm exists precisely
        // because the leading character may be unexpected.
        let files = parse_diff("diff --git a/a.txt b/a.txt\n@@ -1 +1 @@\nédge\n");
        assert_eq!(files[0].hunks[0].lines.len(), 1);
    }

    #[test]
    fn binary_files_are_flagged_rather_than_parsed() {
        let text = "diff --git a/logo.png b/logo.png\n\
                    Binary files a/logo.png and b/logo.png differ\n";
        let files = parse_diff(text);
        assert!(files[0].binary);
        assert!(files[0].hunks.is_empty());
    }

    #[test]
    fn a_missing_trailing_newline_is_kept_as_a_note() {
        let text = "diff --git a/a b/a\n@@ -1 +1 @@\n-x\n\\ No newline at end of file\n+y\n";
        let lines = &parse_diff(text)[0].hunks[0].lines;
        assert!(matches!(lines[1], DiffLine::Note(_)));
    }

    #[test]
    fn an_empty_context_line_is_not_dropped() {
        // git emits a bare "" for a blank context line rather than " ".
        let text = "diff --git a/a b/a\n@@ -1,3 +1,3 @@\n one\n\n+two\n";
        let lines = &parse_diff(text)[0].hunks[0].lines;
        assert_eq!(lines[1], DiffLine::Context(String::new()));
        assert_eq!(lines[2], DiffLine::Added("two".into()));
    }

    #[test]
    fn header_noise_between_files_is_ignored() {
        let text = "diff --git a/a b/a\n\
                    old mode 100644\n\
                    new mode 100755\n\
                    similarity index 95%\n\
                    index 1234567..89abcde 100644\n\
                    --- a/a\n\
                    +++ b/a\n\
                    @@ -1 +1 @@\n\
                    -x\n\
                    +y\n";
        let files = parse_diff(text);
        assert_eq!(files[0].hunks.len(), 1);
        assert_eq!(files[0].hunks[0].lines.len(), 2, "only the +/- lines");
    }

    #[test]
    fn empty_input_yields_nothing() {
        assert!(parse_diff("").is_empty());
    }

    // ---- review against real repos ----

    #[test]
    fn an_untouched_worktree_has_nothing_to_review() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task_with_worktrees(std::slice::from_ref(&repo));
        assert!(Reviewer::review(&fx.store, &task).unwrap().is_empty());
    }

    #[test]
    fn modified_and_new_files_both_appear() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task_with_worktrees(std::slice::from_ref(&repo));
        let wt = fx.worktree(&task, &repo);

        std::fs::write(wt.join("README.md"), "changed\n").unwrap();
        std::fs::write(wt.join("new.rs"), "fn new() {}\n").unwrap();

        let review = Reviewer::review(&fx.store, &task).unwrap();
        let paths: Vec<&str> = review.files.iter().map(|f| f.path.as_str()).collect();
        assert_eq!(paths, ["README.md", "new.rs"]);
        assert_eq!(review.files[0].change, Change::Modified);
        assert_eq!(
            review.files[1].change,
            Change::Untracked,
            "a file git has never seen is most of what an agent produces"
        );
    }

    #[test]
    fn staging_moves_a_file_from_unstaged_to_staged() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task_with_worktrees(std::slice::from_ref(&repo));
        let wt = fx.worktree(&task, &repo);
        std::fs::write(wt.join("README.md"), "changed\n").unwrap();

        let before = Reviewer::review(&fx.store, &task).unwrap();
        assert!(!before.files[0].staged && before.files[0].unstaged);

        Reviewer::stage(&before.files[0]).unwrap();

        let after = Reviewer::review(&fx.store, &task).unwrap();
        assert!(after.files[0].staged);
        assert!(after.has_staged());
    }

    #[test]
    fn unstaging_puts_it_back() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task_with_worktrees(std::slice::from_ref(&repo));
        let wt = fx.worktree(&task, &repo);
        std::fs::write(wt.join("README.md"), "changed\n").unwrap();

        let review = Reviewer::review(&fx.store, &task).unwrap();
        Reviewer::stage(&review.files[0]).unwrap();
        let staged = Reviewer::review(&fx.store, &task).unwrap();
        Reviewer::unstage(&staged.files[0]).unwrap();

        let after = Reviewer::review(&fx.store, &task).unwrap();
        assert!(!after.files[0].staged);
        assert!(!after.has_staged());
    }

    #[test]
    fn an_untracked_file_still_has_a_viewable_diff() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task_with_worktrees(std::slice::from_ref(&repo));
        let wt = fx.worktree(&task, &repo);
        std::fs::write(wt.join("new.rs"), "fn added() {}\n").unwrap();

        let review = Reviewer::review(&fx.store, &task).unwrap();
        let diff = Reviewer::file_diff(&review.files[0], false).unwrap();

        assert!(
            diff.hunks
                .iter()
                .any(|h| h.lines.contains(&DiffLine::Added("fn added() {}".into()))),
            "git diff alone would show nothing here: {diff:?}"
        );
    }

    #[test]
    fn a_modified_file_diffs_against_the_index_or_the_tree() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task_with_worktrees(std::slice::from_ref(&repo));
        let wt = fx.worktree(&task, &repo);
        std::fs::write(wt.join("README.md"), "# changed\n").unwrap();

        let review = Reviewer::review(&fx.store, &task).unwrap();
        let unstaged = Reviewer::file_diff(&review.files[0], false).unwrap();
        assert!(!unstaged.hunks.is_empty(), "the working tree differs");

        let staged = Reviewer::file_diff(&review.files[0], true).unwrap();
        assert!(staged.is_empty(), "nothing is staged yet");
    }

    #[test]
    fn committing_records_a_commit_and_finishes_the_task() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task_with_worktrees(std::slice::from_ref(&repo));
        let wt = fx.worktree(&task, &repo);
        std::fs::write(wt.join("README.md"), "changed\n").unwrap();
        Reviewer::stage_all(&fx.store, &task).unwrap();

        let committed = Reviewer::commit(&mut fx.store, &task, "fix the thing", at(5)).unwrap();

        assert_eq!(committed.commits.len(), 1);
        assert!(!committed.commits[0].commit.is_empty());
        assert_eq!(
            fx.store.get_task(task.id).unwrap().state,
            TaskState::Committed
        );
        // The commit is real.
        let log = git::run(&wt, &["log", "-1", "--pretty=%s"]).unwrap();
        assert_eq!(log, "fix the thing");
        assert!(Reviewer::review(&fx.store, &task).unwrap().is_empty());
    }

    #[test]
    fn committing_a_conflicted_worktree_is_refused_before_anything_lands() {
        // An unmerged file counts as staged to `has_staged_changes`, so commit
        // was offered and then died on a raw `fatal: Exiting because of an
        // unresolved conflict` with no explanation the user could act on.
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task_with_worktrees(std::slice::from_ref(&repo));
        let wt = fx.worktree(&task, &repo);

        // Produce a real conflict in the worktree.
        std::fs::write(wt.join("c.txt"), "base\n").unwrap();
        git::stage_all(&wt).unwrap();
        git::commit(&wt, "seed").unwrap();
        git::run(&wt, &["checkout", "-q", "-b", "side"]).unwrap();
        std::fs::write(wt.join("c.txt"), "side\n").unwrap();
        git::stage_all(&wt).unwrap();
        git::commit(&wt, "side").unwrap();
        git::run(&wt, &["checkout", "-q", &format!("t{}", task.id)]).unwrap();
        std::fs::write(wt.join("c.txt"), "mine\n").unwrap();
        git::stage_all(&wt).unwrap();
        git::commit(&wt, "mine").unwrap();
        assert!(
            git::run(&wt, &["merge", "side"]).is_err(),
            "the merge should have conflicted"
        );

        let err = Reviewer::commit(&mut fx.store, &task, "resolve it", at(5)).unwrap_err();

        assert!(matches!(err, Error::Unmerged { .. }), "got {err:?}");
        assert_eq!(
            fx.store.get_task(task.id).unwrap().state,
            TaskState::AwaitingReview,
            "a refused commit must not move the task"
        );

        // And the conflict is visible rather than a blank diff.
        let review = Reviewer::review(&fx.store, &task).unwrap();
        let file = review.files.iter().find(|f| f.path == "c.txt").unwrap();
        let diff = Reviewer::file_diff(file, false).unwrap();
        assert!(diff.conflicted, "{diff:?}");
        assert!(!diff.is_empty(), "the conflict must be shown: {diff:?}");
    }

    #[test]
    fn committing_with_nothing_staged_is_refused() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task_with_worktrees(std::slice::from_ref(&repo));
        std::fs::write(fx.worktree(&task, &repo).join("README.md"), "changed\n").unwrap();

        assert!(matches!(
            Reviewer::commit(&mut fx.store, &task, "msg", at(5)),
            Err(Error::NothingStaged)
        ));
        assert_eq!(
            fx.store.get_task(task.id).unwrap().state,
            TaskState::AwaitingReview,
            "a refused commit must not finish the task"
        );
    }

    #[test]
    fn an_empty_message_is_refused() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task_with_worktrees(std::slice::from_ref(&repo));
        std::fs::write(fx.worktree(&task, &repo).join("README.md"), "x\n").unwrap();
        Reviewer::stage_all(&fx.store, &task).unwrap();

        assert!(matches!(
            Reviewer::commit(&mut fx.store, &task, "   ", at(5)),
            Err(Error::EmptyMessage)
        ));
    }

    #[test]
    fn a_multi_repo_task_commits_once_per_repo_with_one_message() {
        let mut fx = Fixture::new();
        let api = fx.repo("api");
        let web = fx.repo("web");
        let task = fx.task_with_worktrees(&[api.clone(), web.clone()]);

        std::fs::write(fx.worktree(&task, &api).join("README.md"), "api\n").unwrap();
        std::fs::write(fx.worktree(&task, &web).join("README.md"), "web\n").unwrap();
        Reviewer::stage_all(&fx.store, &task).unwrap();

        let committed = Reviewer::commit(&mut fx.store, &task, "cross-cutting", at(5)).unwrap();

        assert_eq!(committed.commits.len(), 2);
        for repo in [&api, &web] {
            let log = git::run(&fx.worktree(&task, repo), &["log", "-1", "--pretty=%s"]).unwrap();
            assert_eq!(log, "cross-cutting");
        }
    }

    #[test]
    fn a_repo_with_nothing_staged_gets_no_empty_commit() {
        let mut fx = Fixture::new();
        let api = fx.repo("api");
        let web = fx.repo("web");
        let task = fx.task_with_worktrees(&[api.clone(), web.clone()]);

        // Only one repo changed.
        std::fs::write(fx.worktree(&task, &api).join("README.md"), "api\n").unwrap();
        Reviewer::stage_all(&fx.store, &task).unwrap();

        let committed = Reviewer::commit(&mut fx.store, &task, "one repo only", at(5)).unwrap();

        assert_eq!(committed.commits.len(), 1);
        assert_eq!(committed.commits[0].repo_id, api.id);
        let web_log = git::run(&fx.worktree(&task, &web), &["log", "-1", "--pretty=%s"]).unwrap();
        assert_eq!(web_log, "initial", "the untouched repo gained no commit");
    }

    #[test]
    fn a_review_lists_every_worktree_a_task_spans() {
        let mut fx = Fixture::new();
        let api = fx.repo("api");
        let web = fx.repo("web");
        let task = fx.task_with_worktrees(&[api.clone(), web.clone()]);
        std::fs::write(fx.worktree(&task, &api).join("a.txt"), "a\n").unwrap();
        std::fs::write(fx.worktree(&task, &web).join("b.txt"), "b\n").unwrap();

        let review = Reviewer::review(&fx.store, &task).unwrap();
        assert_eq!(review.files.len(), 2);
        assert_ne!(
            review.files[0].worktree, review.files[1].worktree,
            "changes from different repos must stay distinguishable"
        );
    }

    #[test]
    fn deleted_files_are_reported() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task_with_worktrees(std::slice::from_ref(&repo));
        std::fs::remove_file(fx.worktree(&task, &repo).join("README.md")).unwrap();

        let review = Reviewer::review(&fx.store, &task).unwrap();
        assert_eq!(review.files[0].change, Change::Deleted);
    }

    #[test]
    fn a_path_with_spaces_survives_status_parsing() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task_with_worktrees(std::slice::from_ref(&repo));
        let wt = fx.worktree(&task, &repo);
        std::fs::write(wt.join("a file with spaces.txt"), "x\n").unwrap();

        let review = Reviewer::review(&fx.store, &task).unwrap();
        assert_eq!(
            review.files[0].path, "a file with spaces.txt",
            "the default status format would quote this"
        );
    }

    #[test]
    fn files_inside_a_new_directory_are_listed_individually() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.task_with_worktrees(std::slice::from_ref(&repo));
        let wt = fx.worktree(&task, &repo);
        std::fs::create_dir_all(wt.join("src/deep")).unwrap();
        std::fs::write(wt.join("src/deep/one.rs"), "1\n").unwrap();
        std::fs::write(wt.join("src/deep/two.rs"), "2\n").unwrap();

        let review = Reviewer::review(&fx.store, &task).unwrap();
        let paths: Vec<&str> = review.files.iter().map(|f| f.path.as_str()).collect();
        assert_eq!(
            paths,
            ["src/deep/one.rs", "src/deep/two.rs"],
            "collapsing to the directory would hide the agent's work"
        );
    }

    #[test]
    fn an_unprovisioned_task_has_nothing_to_review() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx
            .store
            .create_task("q", "p", &fx.tasks_dir, &[repo.id], at(0))
            .unwrap();
        assert!(Reviewer::review(&fx.store, &task).unwrap().is_empty());
        assert!(matches!(
            Reviewer::stage_all(&fx.store, &task),
            Err(Error::NotProvisioned(_))
        ));
    }
}