brain: Add commit rejection

f0d31e3af012ea06a4c1ff409fb776331668ad9a
Persist commit-level rejection decisions and expose them through the
history and commit views. Render resolved rejection distinctly while
keeping terminal glyph widths aligned.

Assisted-by: Codex:gpt-5.6
Alexis Sellier committed ago 1 parent 044d8040
crates/brain/src/backend.rs +158 -44
188 188
    }
189 189
}
190 190
191 191
/// Authoritative accepted-hunk state for one review.
192 192
pub(crate) type Accepted = BTreeSet<AcceptedHunk>;
193 +
/// Authoritative rejected-commit state for one review.
194 +
type Rejected = BTreeSet<Oid>;
193 195
194 196
/// Persisted state for one resolved target of a selector-keyed review.
195 197
#[derive(Clone, Debug, Eq, PartialEq)]
196 198
struct PersistedState {
197 199
    /// Target commit whose hunks the accepted identities describe.
198 200
    target: Oid,
199 201
    /// Exact hunks accepted by the reviewer.
200 202
    accepted: Accepted,
203 +
    /// Commits rejected by the reviewer.
204 +
    rejected: Rejected,
205 +
}
206 +
207 +
impl PersistedState {
208 +
    /// Creates empty decisions for `target`.
209 +
    fn empty(target: Oid) -> Self {
210 +
        Self {
211 +
            target,
212 +
            accepted: Accepted::new(),
213 +
            rejected: Rejected::new(),
214 +
        }
215 +
    }
201 216
}
202 217
203 218
/// Accepted hunks of one file, ready to apply to the projected tree.
204 219
pub struct FilePatches {
205 220
    /// Every hunk of the file in one patch.
252 267
    /// Commit whose hunks are being reconciled.
253 268
    pub commit: Oid,
254 269
    /// Exact identity per decoded hunk, when the commit's diff is loaded.
255 270
    pub hunks: Option<&'a BTreeMap<HunkId, AcceptedHunk>>,
256 271
}
272 +
/// Final review state of one commit.
273 +
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
274 +
pub enum CommitReviewState {
275 +
    /// The commit still needs a final decision.
276 +
    #[default]
277 +
    Pending,
278 +
    /// Every reviewable change in the commit is accepted.
279 +
    Accepted,
280 +
    /// The reviewer rejected the commit.
281 +
    Rejected,
282 +
}
257 283
258 284
/// Review state of one commit projected from the accepted set.
259 285
pub struct Reconciled {
260 286
    /// Accepted-line progress for the commit.
261 287
    pub progress: ReviewProgress,
288 +
    /// Final review state of the commit.
289 +
    pub state: CommitReviewState,
262 290
    /// Accepted hunks, for commits whose hunk patch ids were supplied.
263 291
    pub accepted: BTreeSet<HunkId>,
264 292
}
265 293
266 294
impl Reconciled {
267 -
    /// Projects exact accepted identities onto commit-local hunk ids.
268 -
    fn for_commits(accepted_state: &Accepted, commits: &[CommitHunks<'_>]) -> Vec<Self> {
295 +
    /// Projects persisted decisions onto commit-local hunk ids.
296 +
    fn for_commits(
297 +
        accepted_state: &Accepted,
298 +
        rejected_state: &Rejected,
299 +
        commits: &[CommitHunks<'_>],
300 +
    ) -> Vec<Self> {
269 301
        // Accepted and total line counts per commit let undecoded commits
270 302
        // retain their progress from persisted totals.
271 303
        let mut totals = BTreeMap::<Oid, (usize, u32)>::new();
272 304
        for identity in accepted_state {
273 305
            let entry = totals
310 342
                        },
311 343
                    );
312 344
                    (progress, BTreeSet::new())
313 345
                }
314 346
            };
315 -
            reconciled.push(Self { progress, accepted });
347 +
            let state = if rejected_state.contains(&commit.commit) {
348 +
                CommitReviewState::Rejected
349 +
            } else if progress.is_complete() {
350 +
                CommitReviewState::Accepted
351 +
            } else {
352 +
                CommitReviewState::Pending
353 +
            };
354 +
            reconciled.push(Self {
355 +
                progress,
356 +
                state,
357 +
                accepted,
358 +
            });
316 359
        }
317 360
        reconciled
318 361
    }
319 362
}
320 363
332 375
/// Remaining review status for one commit.
333 376
#[derive(Debug, Default)]
334 377
pub struct CommitStatus {
335 378
    /// Accepted-line progress for the commit.
336 379
    pub progress: ReviewProgress,
380 +
    /// Final review state of the commit.
381 +
    pub state: CommitReviewState,
337 382
    /// Diff statistics from hunks that remain unaccepted.
338 383
    pub stats: DiffStat,
339 384
}
340 385
341 386
impl HistoryStatus {
481 526
/// Returns the user-facing label for `review`.
482 527
fn range_label(review: &ReviewIdentity) -> String {
483 528
    format!("{} .. {}", review.base.as_str(), review.target.as_str())
484 529
}
485 530
486 -
/// Encodes resolved-target metadata and accepted hunks in a synthetic commit message.
531 +
/// Encodes resolved-target metadata, accepted hunks, and rejected commits.
487 532
fn encode_state(state: &PersistedState) -> String {
488 533
    let mut message = format!(
489 534
        "{SYNTHETIC_BRAIN_MESSAGE}\n\n{STATE_SECTION}\ntarget {}\n",
490 535
        state.target
491 536
    );
537 +
    for commit in &state.rejected {
538 +
        message.push_str(&format!("reject {commit}\n"));
539 +
    }
492 540
    for hunk in &state.accepted {
493 541
        message.push_str(&format!(
494 542
            "{} {} {} {} {}\n",
495 543
            hunk.commit, hunk.patch_id, hunk.ordinal, hunk.lines, hunk.commit_lines
496 544
        ));
497 545
    }
498 546
    message
499 547
}
500 548
501 -
/// Decodes resolved-target metadata and accepted hunks from a synthetic commit message.
549 +
/// Decodes resolved-target metadata, accepted hunks, and rejected commits.
502 550
fn decode_state(message: &str) -> Option<PersistedState> {
503 551
    let header = format!("{SYNTHETIC_BRAIN_MESSAGE}\n\n{STATE_SECTION}\n");
504 552
    let mut body = message.strip_prefix(&header)?.lines();
505 553
    let mut metadata = body.next()?.split_whitespace();
506 554
    if metadata.next()? != "target" {
509 557
    let target = metadata.next()?.parse().ok()?;
510 558
    if metadata.next().is_some() {
511 559
        return None;
512 560
    }
513 561
    let mut accepted = BTreeSet::new();
562 +
    let mut rejected = BTreeSet::new();
514 563
    let mut commit_totals = BTreeMap::new();
515 564
516 565
    for line in body.filter(|line| !line.trim().is_empty()) {
566 +
        if let Some(commit) = line.strip_prefix("reject ") {
567 +
            let commit = commit.parse().ok()?;
568 +
            if !rejected.insert(commit) {
569 +
                return None;
570 +
            }
571 +
            continue;
572 +
        }
517 573
        let mut fields = line.split_whitespace();
518 574
        let commit = fields.next()?.parse().ok()?;
519 575
        let patch_id = fields.next()?;
520 576
        let ordinal = fields.next()?;
521 577
        let lines = fields.next()?;
546 602
        }
547 603
        if !accepted.insert(hunk) {
548 604
            return None;
549 605
        }
550 606
    }
551 -
    Some(PersistedState { target, accepted })
607 +
    Some(PersistedState {
608 +
        target,
609 +
        accepted,
610 +
        rejected,
611 +
    })
552 612
}
553 613
554 614
/// Commit hunk identity data used to summarize stored review progress.
555 615
struct SummaryCommit {
556 616
    /// Commit being summarized.
669 729
/// Returns whether `cwd` is inside a Jujutsu workspace.
670 730
fn is_jj_workspace(cwd: &Path) -> bool {
671 731
    cwd.ancestors().any(|path| path.join(JJ_DIR).is_dir())
672 732
}
673 733
674 -
/// Hidden Git state holding one review's acceptance state and comments.
734 +
/// Hidden Git state holding one review's decisions and comments.
675 735
///
676 -
/// Exact accepted-hunk identities are stored in the state commit message. The
677 -
/// commit tree is a best-effort content projection. Comments are stored as a
678 -
/// JSONL blob under a sibling ref. All state lives inside the Git object store.
736 +
/// Exact accepted-hunk identities and rejected commits are stored in the state
737 +
/// commit message. The commit tree is a best-effort content projection.
738 +
/// Comments are stored as a JSONL blob under a sibling ref. All state lives
739 +
/// inside the Git object store.
679 740
#[derive(Clone, Debug)]
680 741
pub struct Brain {
681 742
    /// Git command context.
682 743
    repository: git::Repository,
683 744
    /// Hidden ref storing the synthetic acceptance state commit.
690 751
    target: Oid,
691 752
    /// Current synthetic state commit.
692 753
    commit: Oid,
693 754
    /// Exact hunks accepted by the reviewer.
694 755
    pub(crate) accepted: Accepted,
756 +
    /// Commits rejected by the reviewer.
757 +
    rejected: Rejected,
695 758
}
696 759
697 760
impl Brain {
698 761
    /// Creates a review state handle.
699 762
    fn new(
700 763
        repository: git::Repository,
701 764
        state_ref: Qualified<'static>,
702 765
        comments_ref: Qualified<'static>,
703 766
        base: Oid,
704 -
        target: Oid,
705 767
        commit: Oid,
706 -
        accepted: Accepted,
768 +
        state: PersistedState,
707 769
    ) -> Self {
770 +
        let PersistedState {
771 +
            target,
772 +
            accepted,
773 +
            rejected,
774 +
        } = state;
708 775
        Self {
709 776
            repository,
710 777
            state_ref,
711 778
            comments_ref,
712 779
            base,
713 780
            target,
714 781
            commit,
715 782
            accepted,
783 +
            rejected,
716 784
        }
717 785
    }
718 786
719 787
    /// Returns the hidden Git ref prefix for `namespace`.
720 788
    fn prefix_for(namespace: &'static str) -> Result<Qualified<'static>, Error> {
844 912
            let brain = Brain::new(
845 913
                repository.clone(),
846 914
                reference,
847 915
                comments_ref,
848 916
                base,
849 -
                persisted.target,
850 917
                state,
851 -
                persisted.accepted,
918 +
                persisted,
852 919
            );
853 920
            let comments = brain.comment_status()?;
854 921
            let target = Rev::from(current_target);
855 922
            let progress = brain.summary(&target)?.1;
856 923
            let recency = repository.commit_time(current_target)?;
971 1038
            .map(|((commit, document, _), reconciled)| {
972 1039
                (
973 1040
                    *commit,
974 1041
                    CommitStatus {
975 1042
                        progress: reconciled.progress,
1043 +
                        state: reconciled.state,
976 1044
                        stats: commit_remaining_stats(document, &reconciled.accepted),
977 1045
                    },
978 1046
                )
979 1047
            })
980 1048
            .collect()
1051 1119
                (existing, persisted)
1052 1120
            }
1053 1121
            None => {
1054 1122
                let commit = Brain::fresh_state_commit(&repository, base, target)?;
1055 1123
                repository.update_ref(&state_ref, commit)?;
1056 -
                let persisted = PersistedState {
1057 -
                    target,
1058 -
                    accepted: Accepted::new(),
1059 -
                };
1124 +
                let persisted = PersistedState::empty(target);
1060 1125
                (commit, persisted)
1061 1126
            }
1062 1127
        };
1063 1128
        Ok(Self::new(
1064 1129
            repository,
1065 1130
            state_ref,
1066 1131
            comments_ref,
1067 1132
            base,
1068 -
            persisted.target,
1069 1133
            commit,
1070 -
            persisted.accepted,
1134 +
            persisted,
1071 1135
        ))
1072 1136
    }
1073 1137
1074 1138
    /// Replaces the hidden review state for one review and returns it.
1075 1139
    fn reset(
1086 1150
        Ok(Self::new(
1087 1151
            repository,
1088 1152
            state_ref,
1089 1153
            comments_ref,
1090 1154
            base,
1091 -
            target,
1092 1155
            commit,
1093 -
            Accepted::new(),
1156 +
            PersistedState::empty(target),
1094 1157
        ))
1095 1158
    }
1096 1159
1097 1160
    /// Carries accepted hunks from stored state onto the current review range.
1098 1161
    fn rebase(
1114 1177
                    return Ok(Self::new(
1115 1178
                        repository,
1116 1179
                        state_ref,
1117 1180
                        comments_ref,
1118 1181
                        base,
1119 -
                        target,
1120 1182
                        existing,
1121 -
                        persisted.accepted,
1183 +
                        persisted,
1122 1184
                    ));
1123 1185
                }
1124 -
                persisted.accepted
1186 +
                persisted
1125 1187
            }
1126 -
            None => Accepted::new(),
1188 +
            None => PersistedState::empty(target),
1127 1189
        };
1128 1190
        let commit = Brain::fresh_state_commit(&repository, base, target)?;
1129 1191
        repository.update_ref(&state_ref, commit)?;
1130 1192
        let mut brain = Self::new(
1131 1193
            repository,
1132 1194
            state_ref,
1133 1195
            comments_ref,
1134 1196
            base,
1135 -
            target,
1136 1197
            commit,
1137 -
            Accepted::new(),
1198 +
            PersistedState::empty(target),
1138 1199
        );
1139 -
        brain.remap(commits, documents, &stored)?;
1200 +
        brain.remap(commits, documents, &stored.accepted, &stored.rejected)?;
1140 1201
1141 1202
        Ok(brain)
1142 1203
    }
1143 1204
1144 1205
    /// Creates an empty accepted-state commit for one resolved review range.
1146 1207
        repository: &git::Repository,
1147 1208
        base: Oid,
1148 1209
        target: Oid,
1149 1210
    ) -> Result<Oid, Error> {
1150 1211
        let tree = repository.tree_id(base)?;
1151 -
        let state = PersistedState {
1152 -
            target,
1153 -
            accepted: Accepted::new(),
1154 -
        };
1212 +
        let state = PersistedState::empty(target);
1155 1213
        let fresh = repository.commit(
1156 1214
            tree,
1157 1215
            base,
1158 1216
            "brain",
1159 1217
            "brain@example.invalid",
1211 1269
        accepted.extend(hunks);
1212 1270
        let mut tree = self.repository.tree_id(self.base)?;
1213 1271
        for file in files {
1214 1272
            tree = self.project_file(tree, &file)?;
1215 1273
        }
1216 -
        self.persist(tree, accepted)
1274 +
        self.persist(tree, accepted, self.rejected.clone())
1217 1275
    }
1218 1276
1219 1277
    /// Marks exact hunks unaccepted and rebuilds the derived tree.
1220 1278
    pub fn reject(
1221 1279
        &mut self,
1226 1284
        accepted.retain(|hunk| !rejected.contains(hunk));
1227 1285
        let mut tree = self.repository.tree_id(self.base)?;
1228 1286
        for file in files {
1229 1287
            tree = self.project_file(tree, &file)?;
1230 1288
        }
1231 -
        self.persist(tree, accepted)
1289 +
        self.persist(tree, accepted, self.rejected.clone())
1290 +
    }
1291 +
1292 +
    /// Toggles the rejected state of one commit.
1293 +
    pub fn toggle_commit_rejected(&mut self, commit: Oid) -> Result<(), Error> {
1294 +
        let mut rejected = self.rejected.clone();
1295 +
        if !rejected.remove(&commit) {
1296 +
            rejected.insert(commit);
1297 +
        }
1298 +
        let tree = self.repository.tree_id(self.commit)?;
1299 +
        self.persist(tree, self.accepted.clone(), rejected)
1232 1300
    }
1233 1301
1234 1302
    /// Applies `patch` to `tree`, keeping `tree` when it does not apply.
1235 1303
    ///
1236 1304
    /// The tree is only a content projection of the accepted set, so a hunk
1260 1328
            tree = self.project(tree, patch)?;
1261 1329
        }
1262 1330
        Ok(tree)
1263 1331
    }
1264 1332
1265 -
    /// Remaps accepted identities onto a moved review range.
1333 +
    /// Remaps accepted identities and exact rejected commits onto a moved range.
1266 1334
    fn remap(
1267 1335
        &mut self,
1268 1336
        commits: &[Commit],
1269 1337
        documents: &[DiffDocument],
1270 1338
        stored: &Accepted,
1339 +
        stored_rejected: &Rejected,
1271 1340
    ) -> Result<(), Error> {
1272 1341
        debug_assert_eq!(commits.len(), documents.len(), "one document per commit");
1273 1342
1274 1343
        // Hunks of the moved range in range order, grouped by file so the
1275 1344
        // projection can apply a whole file at once.
1301 1370
            if hunks.is_empty() {
1302 1371
                continue;
1303 1372
            }
1304 1373
            tree = self.project_file(tree, &FilePatches::new(file, hunks)?)?;
1305 1374
        }
1306 -
        self.persist(tree, accepted)
1375 +
        let current_commits = commits
1376 +
            .iter()
1377 +
            .map(|commit| commit.id)
1378 +
            .collect::<BTreeSet<_>>();
1379 +
        let rejected = stored_rejected
1380 +
            .intersection(&current_commits)
1381 +
            .copied()
1382 +
            .collect();
1383 +
        self.persist(tree, accepted, rejected)
1307 1384
    }
1308 1385
1309 -
    /// Persists exact acceptance and its derived tree in one commit.
1310 -
    fn persist(&mut self, tree: Oid, accepted: Accepted) -> Result<(), Error> {
1386 +
    /// Persists review decisions and the derived tree in one commit.
1387 +
    fn persist(&mut self, tree: Oid, accepted: Accepted, rejected: Rejected) -> Result<(), Error> {
1311 1388
        let state = PersistedState {
1312 1389
            target: self.target,
1313 1390
            accepted,
1391 +
            rejected,
1314 1392
        };
1315 1393
        let message = encode_state(&state);
1316 1394
        let commit =
1317 1395
            self.repository
1318 1396
                .commit(tree, self.base, "brain", "brain@example.invalid", &message)?;
1319 1397
        self.repository.update_ref(&self.state_ref, commit)?;
1320 1398
        self.commit = commit;
1321 1399
        self.accepted = state.accepted;
1400 +
        self.rejected = state.rejected;
1322 1401
1323 1402
        Ok(())
1324 1403
    }
1325 1404
1326 1405
    /// Projects exact acceptance onto the current commit list.
1327 1406
    pub fn reconcile(&self, commits: &[CommitHunks<'_>]) -> Vec<Reconciled> {
1328 -
        Reconciled::for_commits(&self.accepted, commits)
1407 +
        Reconciled::for_commits(&self.accepted, &self.rejected, commits)
1329 1408
    }
1330 1409
}
1331 1410
1332 1411
/// Returns statistics for the unaccepted hunks in `document`.
1333 1412
pub fn commit_remaining_stats(document: &DiffDocument, accepted: &BTreeSet<HunkId>) -> DiffStat {
1699 1778
            brain.repository.optional_ref(&brain.comments_ref).unwrap(),
1700 1779
            Some(comments)
1701 1780
        );
1702 1781
    }
1703 1782
1783 +
    #[test]
1784 +
    fn commit_rejection_persists_and_toggles() {
1785 +
        let repository = TestRepository::new();
1786 +
        let reviewed = repository.path.join("reviewed.txt");
1787 +
        fs::write(&reviewed, "base\n").unwrap();
1788 +
        repository.git(&["add", "reviewed.txt"]);
1789 +
        repository.git(&["commit", "-q", "-m", "base"]);
1790 +
        repository.git(&["switch", "-q", "-c", "topic"]);
1791 +
        fs::write(&reviewed, "change\n").unwrap();
1792 +
        repository.git(&["commit", "-q", "-am", "change"]);
1793 +
1794 +
        let base = Rev::try_from("main").unwrap();
1795 +
        let target = Rev::try_from("topic").unwrap();
1796 +
        let backend = GitBackend::new(&repository.path, base, target).unwrap();
1797 +
        let commit = backend.commits().unwrap().pop().unwrap().id;
1798 +
        let mut brain = backend.reset_brain().unwrap();
1799 +
1800 +
        brain.toggle_commit_rejected(commit).unwrap();
1801 +
        assert_eq!(backend.brain().unwrap().rejected, Rejected::from([commit]));
1802 +
1803 +
        brain.toggle_commit_rejected(commit).unwrap();
1804 +
        assert!(backend.brain().unwrap().rejected.is_empty());
1805 +
    }
1806 +
1704 1807
    #[test]
1705 1808
    fn rebase_keeps_unchanged_hunk_acceptance_after_amend() {
1706 1809
        let repository = TestRepository::new();
1707 1810
        let reviewed = repository.path.join("reviewed.txt");
1708 1811
        let amended = repository.path.join("amended.txt");
1936 2039
            target: "2222222222222222222222222222222222222222".parse().unwrap(),
1937 2040
            accepted: Accepted::from([
1938 2041
                accepted_hunk("1111111111111111111111111111111111111111", "alpha", 0, 2),
1939 2042
                accepted_hunk("1111111111111111111111111111111111111111", "beta", 0, 2),
1940 2043
            ]),
2044 +
            rejected: Rejected::from(["3333333333333333333333333333333333333333".parse().unwrap()]),
1941 2045
        };
1942 2046
        let message = encode_state(&state);
1943 2047
1944 2048
        assert!(message.starts_with("brain state\n\nbrain-v1\ntarget "));
1945 2049
        assert_eq!(decode_state(&message), Some(state));
1949 2053
    #[test]
1950 2054
    fn empty_accepted_state_roundtrips_through_commit_message() {
1951 2055
        let state = PersistedState {
1952 2056
            target: "2222222222222222222222222222222222222222".parse().unwrap(),
1953 2057
            accepted: Accepted::new(),
2058 +
            rejected: Rejected::new(),
1954 2059
        };
1955 2060
        let message = encode_state(&state);
1956 2061
1957 2062
        assert_eq!(decode_state(&message), Some(state.clone()));
1958 2063
        // Git terminates `%B` output with its own newline.
2005 2110
                commit: second.commit,
2006 2111
                hunks: Some(&second_hunks),
2007 2112
            },
2008 2113
        ];
2009 2114
2010 -
        let fresh = Reconciled::for_commits(&Accepted::new(), &commits);
2115 +
        let fresh = Reconciled::for_commits(&Accepted::new(), &Rejected::new(), &commits);
2011 2116
        assert!(fresh.iter().all(|state| state.accepted.is_empty()));
2012 2117
        assert!(fresh.iter().all(|state| state.progress
2013 2118
            == ReviewProgress {
2014 2119
                accepted: 0,
2015 2120
                total: 1,
2016 2121
            }));
2017 2122
2018 -
        let remaining = Reconciled::for_commits(&Accepted::from([second]), &commits);
2123 +
        let remaining =
2124 +
            Reconciled::for_commits(&Accepted::from([second]), &Rejected::new(), &commits);
2019 2125
        assert!(remaining[0].accepted.is_empty());
2020 2126
        assert_eq!(remaining[1].accepted, BTreeSet::from([HunkId::new(0)]));
2021 2127
        assert!(remaining[1].progress.is_complete());
2128 +
2129 +
        let rejected =
2130 +
            Reconciled::for_commits(&Accepted::new(), &Rejected::from([first.commit]), &commits);
2131 +
        assert_eq!(rejected[0].state, CommitReviewState::Rejected);
2132 +
        assert_eq!(rejected[1].state, CommitReviewState::Pending);
2022 2133
    }
2023 2134
2024 2135
    #[test]
2025 2136
    fn reconciliation_weights_undecoded_progress_by_changed_lines() {
2026 2137
        let first = AcceptedHunk {
2035 2146
        let commits = [CommitHunks {
2036 2147
            commit: first.commit,
2037 2148
            hunks: None,
2038 2149
        }];
2039 2150
2040 -
        let partial = Reconciled::for_commits(&Accepted::from([first.clone()]), &commits);
2151 +
        let partial =
2152 +
            Reconciled::for_commits(&Accepted::from([first.clone()]), &Rejected::new(), &commits);
2041 2153
        assert_eq!(
2042 2154
            partial[0].progress,
2043 2155
            ReviewProgress {
2044 2156
                accepted: 3,
2045 2157
                total: 4,
2046 2158
            }
2047 2159
        );
2048 2160
        assert!(partial[0].accepted.is_empty());
2049 2161
2050 -
        let full = Reconciled::for_commits(&Accepted::from([first, second]), &commits);
2162 +
        let full =
2163 +
            Reconciled::for_commits(&Accepted::from([first, second]), &Rejected::new(), &commits);
2051 2164
        assert!(full[0].progress.is_complete());
2052 2165
        assert!(full[0].accepted.is_empty());
2053 2166
    }
2054 2167
2055 2168
    #[test]
2056 2169
    fn hunkless_commit_is_complete_without_accepted_identity() {
2057 2170
        let commit = "1111111111111111111111111111111111111111".parse().unwrap();
2058 2171
        let identities = BTreeMap::new();
2059 2172
        let reconciled = Reconciled::for_commits(
2060 2173
            &Accepted::new(),
2174 +
            &Rejected::new(),
2061 2175
            &[CommitHunks {
2062 2176
                commit,
2063 2177
                hunks: Some(&identities),
2064 2178
            }],
2065 2179
        );
f +0 -0
new.rs +0 -0
image.png +0 -0
new.txt +0 -0
crates/brain/src/session.rs +37 -5
16 16
    Backend as TuiBackend, Constraint, Control, Event, Key, Line, List, ListState, Mouse,
17 17
    MouseButton, Rect, ScrollView, Style, Table, TableOptions, Terminal,
18 18
};
19 19
use rustik_tui_termion as tui_termion;
20 20
21 -
use crate::backend::{Accepted, Backend, Brain, Commit, CommitHunks, FilePatches, HistoryStatus};
21 +
use crate::backend::{
22 +
    Accepted, Backend, Brain, Commit, CommitHunks, CommitReviewState, FilePatches, HistoryStatus,
23 +
};
22 24
use crate::comments::ReviewComments;
23 25
use crate::error::Error;
24 26
use crate::review::{FileVisibility, HunkVisibility, Visibility};
25 27
26 28
mod commit;
145 147
        let slots = reviewed
146 148
            .into_iter()
147 149
            .map(|(commit, document, identities)| {
148 150
                let status = history.commits.entry(commit.id).or_default();
149 151
                let progress = status.progress;
152 +
                let state = status.state;
150 153
                let remaining_stats = status.stats;
151 154
                CommitSlot {
152 155
                    commit,
153 156
                    progress,
157 +
                    state,
154 158
                    remaining_stats,
155 159
                    document: Some(document),
156 160
                    identities: Some(identities),
157 161
                    loaded: None,
158 162
                }
164 168
            .into_iter()
165 169
            .map(|commit| CommitSlot {
166 170
                remaining_stats: commit.stats,
167 171
                commit,
168 172
                progress: ReviewProgress::default(),
173 +
                state: CommitReviewState::Pending,
169 174
                document: None,
170 175
                identities: None,
171 176
                loaded: None,
172 177
            })
173 178
            .collect::<Vec<_>>();
456 461
            }
457 462
            Event::Key(Key::Char('A')) => {
458 463
                self.toggle_focused_file(area)?;
459 464
                Ok(Control::Redraw)
460 465
            }
466 +
            Event::Key(Key::Char('r')) => {
467 +
                if matches!(
468 +
                    self.current()?.viewer.state().focus,
469 +
                    Some(DiffFocus::Commit)
470 +
                ) {
471 +
                    self.toggle_commit_rejected(self.current)?;
472 +
                }
473 +
                Ok(Control::Redraw)
474 +
            }
461 475
            Event::Key(Key::Char('v')) => {
462 476
                self.hunk_visibility.toggle();
463 477
                self.refresh_visibility()?;
464 478
                Ok(Control::Redraw)
465 479
            }
538 552
            Event::Key(Key::Char('k') | Key::Up)
539 553
            | Event::Mouse(Mouse::Press {
540 554
                button: MouseButton::WheelUp,
541 555
                ..
542 556
            }) => -1,
557 +
            Event::Key(Key::Char('r')) => {
558 +
                self.toggle_commit_rejected(self.list.selected())?;
559 +
                return Ok(Control::Redraw);
560 +
            }
543 561
            Event::Key(Key::Enter) => {
544 562
                self.select_commit(self.list.selected())?;
545 563
                return Ok(Control::Redraw);
546 564
            }
547 565
            Event::Key(Key::Tab) => {
556 574
        } else {
557 575
            Ok(Control::Continue)
558 576
        }
559 577
    }
560 578
579 +
    /// Toggles the rejected state of one commit after pending persistence settles.
580 +
    fn toggle_commit_rejected(&mut self, index: usize) -> Result<(), Error> {
581 +
        self.sync_acceptance()?;
582 +
        if self.error.is_some() {
583 +
            return Ok(());
584 +
        }
585 +
        let commit = self.commits[index].commit.id;
586 +
        self.brain.toggle_commit_rejected(commit)?;
587 +
        self.reconcile_state();
588 +
        Ok(())
589 +
    }
590 +
561 591
    /// Toggles acceptance of the focused hunk.
562 592
    fn toggle_focused_hunk(&mut self, area: Rect) -> Result<(), Error> {
563 593
        let current = self.current;
564 594
        let before = self.current()?.viewer.state().clone();
565 595
        let loaded = self.current()?;
889 919
                .collect::<Result<Vec<_>, Error>>()?;
890 920
            let status = HistoryStatus::for_commits(&self.brain, &status_inputs);
891 921
            for slot in &mut self.commits {
892 922
                if let Some(commit) = status.commits.get(&slot.commit.id) {
893 923
                    slot.progress = commit.progress;
924 +
                    slot.state = commit.state;
894 925
                    slot.remaining_stats = commit.stats;
895 926
                }
896 927
            }
897 928
            self.history_status = Some(status);
898 929
        }
1177 1208
        loaded.viewer.replace_file_diffs_anchored(files, area);
1178 1209
1179 1210
        Ok(())
1180 1211
    }
1181 1212
1182 -
    /// Reconciles per-commit review state from exact accepted identities.
1213 +
    /// Reconciles per-commit review state from persisted decisions.
1183 1214
    ///
1184 -
    /// This is the only place that replaces `Review` sets and reviewed marks.
1185 -
    /// Keeping it as a full recomputation keeps the persisted accepted set,
1215 +
    /// This is the only place that replaces `Review` sets and commit states.
1216 +
    /// Keeping it as a full recomputation keeps the persisted decisions,
1186 1217
    /// current commit list, and per-viewer decorations consistent. Persisted
1187 -
    /// hunk totals provide the reviewed mark for commits not yet decoded.
1218 +
    /// hunk totals provide progress for commits not yet decoded.
1188 1219
    fn reconcile_state(&mut self) {
1189 1220
        let commits = self
1190 1221
            .commits
1191 1222
            .iter()
1192 1223
            .map(|slot| CommitHunks {
1195 1226
            })
1196 1227
            .collect::<Vec<_>>();
1197 1228
        let reconciled = self.brain.reconcile(&commits);
1198 1229
        for (slot, reconciled) in self.commits.iter_mut().zip(reconciled) {
1199 1230
            slot.progress = reconciled.progress;
1231 +
            slot.state = reconciled.state;
1200 1232
            if let Some(loaded) = &mut slot.loaded {
1201 1233
                loaded.review.replace(reconciled.accepted);
1202 1234
                loaded.refresh_decorations();
1203 1235
            }
1204 1236
        }
a.rs +0 -0
crates/brain/src/session/commit.rs +3 -1
6 6
    ContextUpdate, DiffDocument, DiffOptions, DiffViewer, FileId, FileStats, HunkId, ReviewProgress,
7 7
};
8 8
use rustik_repo::DiffStat;
9 9
use rustik_tui::Rect;
10 10
11 -
use crate::backend::{AcceptedHunk, Brain, Commit, commit_remaining_stats};
11 +
use crate::backend::{AcceptedHunk, Brain, Commit, CommitReviewState, commit_remaining_stats};
12 12
use crate::comments::{CommentTarget, Comments, ReviewComments};
13 13
use crate::decorate::Decorations;
14 14
use crate::error::Error;
15 15
use crate::review::Review;
16 16
20 20
    pub(super) commit: Commit,
21 21
    /// Accepted-line progress for this commit.
22 22
    ///
23 23
    /// Persisted line totals provide progress before the diff is decoded.
24 24
    pub(super) progress: ReviewProgress,
25 +
    /// Final review state of this commit.
26 +
    pub(super) state: CommitReviewState,
25 27
    /// Remaining diff statistics for this commit.
26 28
    pub(super) remaining_stats: DiffStat,
27 29
    /// Split diff document retained from history progress calculation.
28 30
    pub(super) document: Option<DiffDocument>,
29 31
    /// Exact hunk identities retained from history progress calculation.
a.rs +0 -0
crates/brain/src/session/status.rs +49 -15
2 2
3 3
use std::cmp::Ordering;
4 4
use std::time::{SystemTime, UNIX_EPOCH};
5 5
6 6
use rustik_diff::{
7 -
    DiffPalette, ReviewProgress, diffstat, file_count, progress_bar, recoverable_error,
7 +
    DiffPalette, ReviewProgress, diffstat, file_count, full_progress_bar, progress_bar,
8 +
    recoverable_error,
8 9
};
9 10
use rustik_repo::DiffStat;
10 11
use rustik_tui::{
11 12
    Border, Buffer, Color, Constraint, HStack, Label, Line, Rect, Size, Style, Table, TableOptions,
12 13
    Widget, colors,
13 14
};
14 15
16 +
use crate::backend::CommitReviewState;
15 17
use crate::comments::Comment;
16 18
use crate::review::{FileVisibility, HunkVisibility, Visibility};
17 19
18 20
use super::commit::CommitSlot;
19 21
47 49
const SELECTED_COMMENT_BORDER: Color = Color::Fixed(239);
48 50
/// Background color for the selected commit, matching the active file row.
49 51
pub(super) const SELECTED_COMMIT_BG: Color = Color::Fixed(235);
50 52
/// Marker shown beside a commit whose hunks have all been accepted: โœ”.
51 53
const REVIEWED_MARK: char = 'โœ”';
54 +
/// Marker shown beside a rejected commit: โœ—.
55 +
const REJECTED_MARK: char = 'โœ—';
52 56
/// Marker highlighted when all hunks are visible in the footer: โœ”.
53 57
const ALL_HUNKS_MODE_ICON: &str = "โœ”";
54 58
/// Marker shown when full-file mode is visible in the footer: โ†•.
55 59
const FULL_FILE_MODE_ICON: &str = "โ†•";
56 60
/// Separator shown between footer status segments: ยท.
74 78
/// Action hints shown in commit-list mode.
75 79
const COMMITS_ACTIONS: &[(&str, &str)] = &[
76 80
    (TAB_KEY, "commit"),
77 81
    ("j/k", "select"),
78 82
    (RETURN_KEY, "open"),
83 +
    ("r", "reject commit"),
79 84
    ("q", "quit"),
80 85
];
81 86
/// Action hints shown in commit diff mode.
82 87
const COMMIT_ACTIONS: &[(&str, &str)] = &[
83 88
    (TAB_KEY, "history"),
84 89
    ("j/k", "hunk"),
85 90
    ("n/p", "file"),
86 91
    ("a", "accept hunk"),
92 +
    ("r", "reject commit"),
87 93
    ("u", "undo"),
88 94
    ("c", "comment"),
89 95
];
90 96
/// Action hints shown while browsing hunk comments.
91 97
const HUNK_BROWSE_ACTIONS: &[(&str, &str)] = &[
362 368
    now: u64,
363 369
    largest_change_count: usize,
364 370
    max_graph_width: usize,
365 371
) -> [Line; 5] {
366 372
    let stats = slot.remaining_stats();
367 -
    let diffstat = if slot.progress.is_complete() {
368 -
        Line::blank()
369 -
    } else {
370 -
        history_diffstat(stats, largest_change_count, max_graph_width, palette)
373 +
    let diffstat = match slot.state {
374 +
        CommitReviewState::Pending => {
375 +
            history_diffstat(stats, largest_change_count, max_graph_width, palette)
376 +
        }
377 +
        CommitReviewState::Accepted | CommitReviewState::Rejected => Line::blank(),
371 378
    };
372 -
    let status = if slot.progress.is_complete() {
373 -
        Label::from_char(REVIEWED_MARK).fg(palette.positive_fg)
374 -
    } else {
375 -
        Label::space()
379 +
    let (status, progress) = match slot.state {
380 +
        CommitReviewState::Accepted => (
381 +
            Label::from_char(REVIEWED_MARK).fg(palette.positive_fg),
382 +
            progress_bar(slot.progress, palette, FOOTER_FG),
383 +
        ),
384 +
        CommitReviewState::Rejected => (
385 +
            Label::from_char(REJECTED_MARK).fg(palette.negative_fg),
386 +
            full_progress_bar(palette.negative_fg),
387 +
        ),
388 +
        CommitReviewState::Pending => (
389 +
            Label::space(),
390 +
            progress_bar(slot.progress, palette, FOOTER_FG),
391 +
        ),
376 392
    };
377 -
    let progress = Line::new(status).item(Label::space()).extend(progress_bar(
378 -
        slot.progress,
379 -
        palette,
380 -
        FOOTER_FG,
381 -
    ));
393 +
    let progress = Line::new(status).item(Label::space()).extend(progress);
382 394
383 395
    [
384 396
        Line::new(Label::new(slot.commit.author.as_str()).fg(HISTORY_VALUE_FG)),
385 397
        Line::new(
386 398
            Label::from(relative_time(
587 599
            ActionContext::Commit
588 600
                .actions()
589 601
                .iter()
590 602
                .any(|(_, label)| *label == "accept hunk")
591 603
        );
604 +
        assert!(
605 +
            ActionContext::Commits
606 +
                .actions()
607 +
                .iter()
608 +
                .any(|(_, label)| *label == "reject commit")
609 +
        );
592 610
        assert!(
593 611
            ActionContext::HunkEdit
594 612
                .actions()
595 613
                .iter()
596 614
                .any(|(_, label)| *label == "save")
659 677
        let stats = DiffStat {
660 678
            files_changed: 1,
661 679
            insertions: 2,
662 680
            deletions: 3,
663 681
        };
664 -
        let slot = CommitSlot {
682 +
        let mut slot = CommitSlot {
665 683
            commit: Commit {
666 684
                id: "0123456789abcdef0123456789abcdef01234567".parse().unwrap(),
667 685
                summary: "A commit summary that cannot fit in the remaining width".to_owned(),
668 686
                author: "Alice".to_owned(),
669 687
                branches: vec!["main".to_owned()],
672 690
            },
673 691
            progress: ReviewProgress {
674 692
                accepted: 0,
675 693
                total: 1,
676 694
            },
695 +
            state: CommitReviewState::Pending,
677 696
            remaining_stats: stats,
678 697
            document: None,
679 698
            identities: None,
680 699
            loaded: None,
681 700
        };
732 751
                .pop()
733 752
                .unwrap()
734 753
                .to_string()
735 754
                .contains("Alice")
736 755
        );
756 +
757 +
        for state in [CommitReviewState::Accepted, CommitReviewState::Rejected] {
758 +
            slot.state = state;
759 +
            assert!(
760 +
                commit_row_suffix(
761 +
                    &slot,
762 +
                    DiffPalette::default(),
763 +
                    now as u64,
764 +
                    stats.insertions + stats.deletions,
765 +
                    8,
766 +
                )[3]
767 +
                .to_string()
768 +
                .is_empty()
769 +
            );
770 +
        }
737 771
    }
738 772
739 773
    #[test]
740 774
    fn history_diffstat_scales_against_largest_commit() {
741 775
        let palette = DiffPalette::default();
crates/diff/src/lib.rs +2 -1
45 45
    HighlightRequest, HighlightResult, HighlightSource,
46 46
};
47 47
#[cfg(feature = "builtins")]
48 48
pub use highlighter::{HighlightOutput, Highlighter, spawn_highlighter};
49 49
pub use status::{
50 -
    REVIEW_PROGRESS_BAR_GLYPH, diffstat, file_count, progress_bar, recoverable_error,
50 +
    REVIEW_PROGRESS_BAR_GLYPH, diffstat, file_count, full_progress_bar, progress_bar,
51 +
    recoverable_error,
51 52
};
52 53
pub use viewer::{
53 54
    ContextRequest, ContextUpdate, DiffAction, DiffFocus, DiffOptions, DiffPalette, DiffState,
54 55
    DiffViewer, FileTree, FileTreeMode, FileTreeTarget, HunkFocus, ViewChange,
55 56
};
crates/diff/src/status.rs +5 -0
40 40
41 41
    Line::blank()
42 42
        .item(Label::new(&REVIEW_PROGRESS_BAR_GLYPH.repeat(filled)).fg(palette.positive_fg))
43 43
        .item(Label::new(&REVIEW_PROGRESS_BAR_GLYPH.repeat(empty)).fg(empty_fg))
44 44
}
45 +
46 +
/// Returns a fully filled standard review progress bar in `fg`.
47 +
pub fn full_progress_bar(fg: Color) -> Line {
48 +
    Line::new(Label::new(&REVIEW_PROGRESS_BAR_GLYPH.repeat(REVIEW_PROGRESS_BAR_WIDTH)).fg(fg))
49 +
}
crates/tui-core/src/cell.rs +2 -1
221 221
pub(crate) fn char_width(ch: char) -> usize {
222 222
    if ch == '\u{fe0f}' || ch == '\u{fe0e}' || ch.is_control() {
223 223
        0
224 224
    // TODO: Move these glyphs somewhere and make them configurable, or include the
225 225
    // full set of unicode glyphs.
226 -
    } else if matches!(ch, 'โœ“' | 'โœ”' | '๐Ÿ—ฉ' | '๐Ÿž„') {
226 +
    } else if matches!(ch, 'โœ“' | 'โœ”' | 'โœ—' | '๐Ÿ—ฉ' | '๐Ÿž„') {
227 227
        1
228 228
    } else if matches!(
229 229
        ch as u32,
230 230
        0x1100..=0x115f
231 231
            | 0x2329..=0x232a
253 253
    #[test]
254 254
    fn test_width() {
255 255
        assert_eq!("abc".width(), 3);
256 256
        assert_eq!("โœ“".width(), 1);
257 257
        assert_eq!("โœ”".width(), 1);
258 +
        assert_eq!("โœ—".width(), 1);
258 259
        assert_eq!("๐Ÿ—ฉ".width(), 1);
259 260
        assert_eq!("๐Ÿž„".width(), 1);
260 261
        assert_eq!("2 โœ” ยท 4 hunks left".width(), 18);
261 262
        assert_eq!("โค๏ธ".width(), 2);
262 263
        assert_eq!("๐Ÿชต".width(), 2);