brain: Match status targets by commit

080440f3bb8f168c533de8f9ea27de8044af8c80
Resolve each stored target selector once and join it to a local branch
by commit identity. This keeps symbolic selectors such as HEAD from
producing duplicate status rows.

Assisted-by: Codex:gpt-5.6-sol
Alexis Sellier committed ago 1 parent 2241b22f
crates/brain/src/backend.rs +90 -6
394 394
struct StoredReview {
395 395
    /// Base commit recorded by the review state.
396 396
    base: Oid,
397 397
    /// Current resolution of the base selector, for staleness checks.
398 398
    current_base: Oid,
399 +
    /// Current resolution of the target selector, for branch matching.
400 +
    current_target: Oid,
399 401
    /// Accepted-line progress across the review.
400 402
    progress: ReviewProgress,
401 403
    /// Comment storage status for this review.
402 404
    comments: CommentStatus,
403 405
    /// Head commit timestamp used to order status rows.
692 694
                relation_to_trunk(repository, &trunk_rev, &Rev::from(branch.head))?
693 695
            };
694 696
695 697
            let matched = stored
696 698
                .iter()
697 -
                .filter(|(identity, stored)| {
698 -
                    identity.target.as_str() == branch.name && stored.current_base == trunk.head
699 +
                .filter(|(_, stored)| {
700 +
                    stored.current_target == branch.head && stored.current_base == trunk.head
699 701
                })
700 702
                .max_by_key(|(_, stored)| stored.updated)
701 703
                .map(|(review, _)| review.clone());
702 704
703 705
            if let Some(review) = matched.and_then(|review| stored.remove(&review)) {
754 756
            // A review whose selectors no longer resolve (deleted branch,
755 757
            // rewritten history) is skipped rather than failing the listing.
756 758
            let Ok(current_base) = repository.commit_id(&identity.base) else {
757 759
                continue;
758 760
            };
759 -
            if repository.commit_id(&identity.target).is_err() {
761 +
            let Ok(current_target) = repository.commit_id(&identity.target) else {
760 762
                continue;
761 -
            }
763 +
            };
762 764
            let base = repository.parent(state)?;
763 765
            let comments_ref = Brain::ref_for_identity(COMMENTS_REF_NAMESPACE, &identity)?;
764 766
            let message = repository.commit_message(state)?;
765 767
            let Some(accepted) = decode_state(&message) else {
766 768
                continue;
772 774
                base,
773 775
                state,
774 776
                accepted,
775 777
            );
776 778
            let comments = brain.comment_status()?;
777 -
            let head = repository.commit_id(&identity.target)?;
778 779
            let progress = brain.summary(&identity)?.1;
779 -
            let recency = repository.commit_time(head)?;
780 +
            let recency = repository.commit_time(current_target)?;
780 781
            let updated = repository.commit_time(state)?;
781 782
782 783
            reviews.insert(
783 784
                identity,
784 785
                StoredReview {
785 786
                    base,
786 787
                    current_base,
788 +
                    current_target,
787 789
                    progress,
788 790
                    comments,
789 791
                    recency,
790 792
                    updated,
791 793
                },
1465 1467
1466 1468
#[cfg(test)]
1467 1469
mod tests {
1468 1470
    use super::*;
1469 1471
1472 +
    /// Sequence used to keep parallel fixture paths distinct.
1473 +
    static NEXT_REPOSITORY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1474 +
1475 +
    /// Temporary Git repository removed when its test finishes.
1476 +
    struct TestRepository {
1477 +
        /// Repository worktree path.
1478 +
        path: std::path::PathBuf,
1479 +
    }
1480 +
1481 +
    impl TestRepository {
1482 +
        /// Initializes an empty repository on a local `main` branch.
1483 +
        fn new() -> Self {
1484 +
            let sequence = NEXT_REPOSITORY.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1485 +
            let path = std::env::temp_dir().join(format!(
1486 +
                "rustik-brain-test-{}-{sequence}",
1487 +
                std::process::id()
1488 +
            ));
1489 +
            let output = std::process::Command::new("git")
1490 +
                .args(["init", "-q", "-b", "main"])
1491 +
                .arg(&path)
1492 +
                .output()
1493 +
                .unwrap();
1494 +
            assert!(
1495 +
                output.status.success(),
1496 +
                "git init failed: {}",
1497 +
                String::from_utf8_lossy(&output.stderr)
1498 +
            );
1499 +
            Self { path }
1500 +
        }
1501 +
1502 +
        /// Runs one Git command with deterministic test identity configuration.
1503 +
        fn git(&self, args: &[&str]) {
1504 +
            let output = std::process::Command::new("git")
1505 +
                .args([
1506 +
                    "-c",
1507 +
                    "user.name=Rustik Test",
1508 +
                    "-c",
1509 +
                    "user.email=rustik@example.com",
1510 +
                    "-c",
1511 +
                    "commit.gpgSign=false",
1512 +
                ])
1513 +
                .args(args)
1514 +
                .current_dir(&self.path)
1515 +
                .output()
1516 +
                .unwrap();
1517 +
            assert!(
1518 +
                output.status.success(),
1519 +
                "git {} failed: {}",
1520 +
                args.join(" "),
1521 +
                String::from_utf8_lossy(&output.stderr)
1522 +
            );
1523 +
        }
1524 +
    }
1525 +
1526 +
    impl Drop for TestRepository {
1527 +
        fn drop(&mut self) {
1528 +
            let _ = std::fs::remove_dir_all(&self.path);
1529 +
        }
1530 +
    }
1531 +
1532 +
    #[test]
1533 +
    fn statuses_match_symbolic_target_to_branch_commit() {
1534 +
        let fixture = TestRepository::new();
1535 +
        fixture.git(&["config", "init.defaultBranch", "main"]);
1536 +
        fixture.git(&["commit", "-q", "--allow-empty", "-m", "base"]);
1537 +
        fixture.git(&["commit", "-q", "--allow-empty", "-m", "target"]);
1538 +
        let repository = git::Repository::discover(fixture.path.clone()).unwrap();
1539 +
        let identity = ReviewIdentity::new(
1540 +
            Rev::try_from("main").unwrap(),
1541 +
            Rev::try_from("HEAD").unwrap(),
1542 +
        );
1543 +
        let base = repository.commit_id(&identity.base).unwrap();
1544 +
        let _brain = Brain::reset(repository.clone(), base, &identity).unwrap();
1545 +
1546 +
        let statuses = Brain::statuses(&repository).unwrap();
1547 +
1548 +
        assert_eq!(statuses.len(), 1);
1549 +
        assert_eq!(statuses[0].head, "main");
1550 +
        assert_eq!(statuses[0].head_kind, BrainStatusHead::Branch);
1551 +
        assert_ne!(statuses[0].state, BrainStatusState::NoState);
1552 +
    }
1553 +
1470 1554
    /// Returns an accepted identity for one test commit and hunk.
1471 1555
    fn accepted_hunk(commit: &str, patch: &str, ordinal: u32, total: u32) -> AcceptedHunk {
1472 1556
        AcceptedHunk {
1473 1557
            commit: commit.parse().unwrap(),
1474 1558
            patch_id: PatchId::from(patch.to_owned()),
f +0 -0
new.rs +0 -0
image.png +0 -0