brain: Reconcile moved review targets

bcb3dd01a5d574be0ed0376cbbf4c993703c0bd9
Record the resolved target alongside accepted hunk identities. Rebase
now remaps acceptance when a selector moves even if the base commit
stays unchanged.

Assisted-by: Codex:gpt-5.6-sol
Alexis Sellier committed ago 1 parent 3cbeb21c
crates/brain/src/backend.rs +186 -90
29 29
30 30
/// Directory marking a Jujutsu workspace.
31 31
const JJ_DIR: &str = ".jj";
32 32
/// Commit message used for synthetic brain state commits.
33 33
const SYNTHETIC_BRAIN_MESSAGE: &str = "brain state";
34 -
/// Commit-message section for accepted-hunk state.
34 +
/// Commit-message section for accepted-hunk state and its resolved target.
35 35
const STATE_SECTION: &str = "brain-v1";
36 36
/// Hidden Git ref category holding all review state.
37 37
const BRAIN_REF_CATEGORY: &str = "brain";
38 38
/// Namespace under the brain category for acceptance state commits.
39 39
const STATE_REF_NAMESPACE: &str = "state";
188 188
}
189 189
190 190
/// Authoritative accepted-hunk state for one review.
191 191
type Accepted = BTreeSet<AcceptedHunk>;
192 192
193 +
/// Persisted state for one resolved target of a selector-keyed review.
194 +
#[derive(Clone, Debug, Eq, PartialEq)]
195 +
struct PersistedState {
196 +
    /// Target commit whose hunks the accepted identities describe.
197 +
    target: Oid,
198 +
    /// Exact hunks accepted by the reviewer.
199 +
    accepted: Accepted,
200 +
}
201 +
193 202
/// Accepted hunks of one file, ready to apply to the projected tree.
194 203
pub struct FilePatches {
195 204
    /// Every hunk of the file in one patch.
196 205
    pub combined: String,
197 206
    /// The same hunks as individual patches, used when `combined` fails.
447 456
/// Returns the user-facing label for `review`.
448 457
fn range_label(review: &ReviewIdentity) -> String {
449 458
    format!("{} .. {}", review.base.as_str(), review.target.as_str())
450 459
}
451 460
452 -
/// Encodes exact accepted-hunk state in a synthetic commit message.
453 -
fn encode_state(accepted: &Accepted) -> String {
454 -
    let mut message = format!("{SYNTHETIC_BRAIN_MESSAGE}\n\n{STATE_SECTION}\n");
455 -
    for hunk in accepted {
461 +
/// Encodes resolved-target metadata and accepted hunks in a synthetic commit message.
462 +
fn encode_state(state: &PersistedState) -> String {
463 +
    let mut message = format!(
464 +
        "{SYNTHETIC_BRAIN_MESSAGE}\n\n{STATE_SECTION}\ntarget {}\n",
465 +
        state.target
466 +
    );
467 +
    for hunk in &state.accepted {
456 468
        message.push_str(&format!(
457 469
            "{} {} {} {} {}\n",
458 470
            hunk.commit, hunk.patch_id, hunk.ordinal, hunk.lines, hunk.commit_lines
459 471
        ));
460 472
    }
461 473
    message
462 474
}
463 475
464 -
/// Decodes exact accepted-hunk state from a synthetic commit message.
465 -
///
466 -
/// Returns `None` for malformed state.
467 -
fn decode_state(message: &str) -> Option<Accepted> {
476 +
/// Decodes resolved-target metadata and accepted hunks from a synthetic commit message.
477 +
fn decode_state(message: &str) -> Option<PersistedState> {
468 478
    let header = format!("{SYNTHETIC_BRAIN_MESSAGE}\n\n{STATE_SECTION}\n");
469 -
    let body = message.strip_prefix(&header)?;
479 +
    let mut body = message.strip_prefix(&header)?.lines();
480 +
    let mut metadata = body.next()?.split_whitespace();
481 +
    if metadata.next()? != "target" {
482 +
        return None;
483 +
    }
484 +
    let target = metadata.next()?.parse().ok()?;
485 +
    if metadata.next().is_some() {
486 +
        return None;
487 +
    }
470 488
    let mut accepted = BTreeSet::new();
471 489
    let mut commit_totals = BTreeMap::new();
472 490
473 -
    for line in body.lines().filter(|line| !line.trim().is_empty()) {
491 +
    for line in body.filter(|line| !line.trim().is_empty()) {
474 492
        let mut fields = line.split_whitespace();
475 493
        let commit = fields.next()?.parse().ok()?;
476 494
        let patch_id = fields.next()?;
477 495
        let ordinal = fields.next()?;
478 496
        let lines = fields.next()?;
503 521
        }
504 522
        if !accepted.insert(hunk) {
505 523
            return None;
506 524
        }
507 525
    }
508 -
    Some(accepted)
526 +
    Some(PersistedState { target, accepted })
509 527
}
510 528
511 529
/// Commit hunk identity data used to summarize stored review progress.
512 530
struct SummaryCommit {
513 531
    /// Commit being summarized.
628 646
    state_ref: Qualified<'static>,
629 647
    /// Hidden ref storing the review's comments blob.
630 648
    comments_ref: Qualified<'static>,
631 649
    /// Base commit used as the parent of synthetic state commits.
632 650
    base: Oid,
651 +
    /// Target commit whose hunks the accepted identities describe.
652 +
    target: Oid,
633 653
    /// Current synthetic state commit.
634 654
    commit: Oid,
635 655
    /// Exact hunks accepted by the reviewer.
636 656
    accepted: Accepted,
637 657
}
641 661
    fn new(
642 662
        repository: git::Repository,
643 663
        state_ref: Qualified<'static>,
644 664
        comments_ref: Qualified<'static>,
645 665
        base: Oid,
666 +
        target: Oid,
646 667
        commit: Oid,
647 668
        accepted: Accepted,
648 669
    ) -> Self {
649 670
        Self {
650 671
            repository,
651 672
            state_ref,
652 673
            comments_ref,
653 674
            base,
675 +
            target,
654 676
            commit,
655 677
            accepted,
656 678
        }
657 679
    }
658 680
762 784
                continue;
763 785
            };
764 786
            let base = repository.parent(state)?;
765 787
            let comments_ref = Brain::ref_for_identity(COMMENTS_REF_NAMESPACE, &identity)?;
766 788
            let message = repository.commit_message(state)?;
767 -
            let Some(accepted) = decode_state(&message) else {
789 +
            let Some(persisted) = decode_state(&message) else {
768 790
                continue;
769 791
            };
792 +
770 793
            let brain = Brain::new(
771 794
                repository.clone(),
772 795
                reference,
773 796
                comments_ref,
774 797
                base,
798 +
                persisted.target,
775 799
                state,
776 -
                accepted,
800 +
                persisted.accepted,
777 801
            );
778 802
            let comments = brain.comment_status()?;
779 803
            let progress = brain.summary(&identity)?.1;
780 804
            let recency = repository.commit_time(current_target)?;
781 805
            let updated = repository.commit_time(state)?;
955 979
956 980
    /// Loads or initializes the hidden review state for one review.
957 981
    fn load(
958 982
        repository: git::Repository,
959 983
        base: Oid,
984 +
        target: Oid,
960 985
        identity: &ReviewIdentity,
961 986
    ) -> Result<Self, Error> {
962 987
        let state_ref = Brain::ref_for_identity(STATE_REF_NAMESPACE, identity)?;
963 988
        let comments_ref = Brain::ref_for_identity(COMMENTS_REF_NAMESPACE, identity)?;
964 -
        let (commit, accepted) = match repository.optional_ref(&state_ref)? {
989 +
        let (commit, persisted) = match repository.optional_ref(&state_ref)? {
965 990
            Some(existing) => {
966 991
                let parent = repository.parent(existing)?;
967 992
                if parent != base {
968 993
                    return Err(Error::StaleReviewState {
969 994
                        stored_base: parent,
970 995
                        current_base: base,
971 996
                    });
972 997
                }
973 998
                let message = repository.commit_message(existing)?;
974 -
                let accepted = decode_state(&message).ok_or(Error::InvalidReviewState)?;
975 -
                (existing, accepted)
999 +
                let persisted = decode_state(&message).ok_or(Error::InvalidReviewState)?;
1000 +
                (existing, persisted)
1001 +
            }
1002 +
            None => {
1003 +
                let commit = Brain::write_fresh_state(&repository, base, target, &state_ref)?;
1004 +
                let persisted = PersistedState {
1005 +
                    target,
1006 +
                    accepted: Accepted::new(),
1007 +
                };
1008 +
                (commit, persisted)
976 1009
            }
977 -
            None => (
978 -
                Brain::write_fresh_state(&repository, base, &state_ref)?,
979 -
                Accepted::new(),
980 -
            ),
981 1010
        };
982 1011
        Ok(Self::new(
983 1012
            repository,
984 1013
            state_ref,
985 1014
            comments_ref,
986 1015
            base,
1016 +
            persisted.target,
987 1017
            commit,
988 -
            accepted,
1018 +
            persisted.accepted,
989 1019
        ))
990 1020
    }
991 1021
992 1022
    /// Replaces the hidden review state for one review and returns it.
993 1023
    fn reset(
994 1024
        repository: git::Repository,
995 1025
        base: Oid,
1026 +
        target: Oid,
996 1027
        identity: &ReviewIdentity,
997 1028
    ) -> Result<Self, Error> {
998 1029
        let state_ref = Brain::ref_for_identity(STATE_REF_NAMESPACE, identity)?;
999 1030
        let comments_ref = Brain::ref_for_identity(COMMENTS_REF_NAMESPACE, identity)?;
1000 -
        let commit = Brain::write_fresh_state(&repository, base, &state_ref)?;
1031 +
        let commit = Brain::write_fresh_state(&repository, base, target, &state_ref)?;
1001 1032
1002 1033
        Ok(Self::new(
1003 1034
            repository,
1004 1035
            state_ref,
1005 1036
            comments_ref,
1006 1037
            base,
1038 +
            target,
1007 1039
            commit,
1008 1040
            Accepted::new(),
1009 1041
        ))
1010 1042
    }
1011 1043
1012 -
    /// Carries accepted hunks from stored state onto the current base.
1044 +
    /// Carries accepted hunks from stored state onto the current review range.
1013 1045
    fn rebase(
1014 1046
        repository: git::Repository,
1015 1047
        base: Oid,
1048 +
        target: Oid,
1016 1049
        identity: &ReviewIdentity,
1017 1050
        commits: &[Commit],
1018 1051
        documents: &[DiffDocument],
1019 1052
    ) -> Result<Self, Error> {
1020 1053
        let state_ref = Brain::ref_for_identity(STATE_REF_NAMESPACE, identity)?;
1021 1054
        let comments_ref = Brain::ref_for_identity(COMMENTS_REF_NAMESPACE, identity)?;
1022 1055
        let stored = match repository.optional_ref(&state_ref)? {
1023 1056
            Some(existing) => {
1024 1057
                let parent = repository.parent(existing)?;
1025 1058
                let message = repository.commit_message(existing)?;
1026 -
                let accepted = decode_state(&message).ok_or(Error::InvalidReviewState)?;
1027 -
                if parent == base {
1059 +
                let persisted = decode_state(&message).ok_or(Error::InvalidReviewState)?;
1060 +
                if parent == base && persisted.target == target {
1028 1061
                    return Ok(Self::new(
1029 1062
                        repository,
1030 1063
                        state_ref,
1031 1064
                        comments_ref,
1032 1065
                        base,
1066 +
                        target,
1033 1067
                        existing,
1034 -
                        accepted,
1068 +
                        persisted.accepted,
1035 1069
                    ));
1036 1070
                }
1037 -
                accepted
1071 +
                persisted.accepted
1038 1072
            }
1039 1073
            None => Accepted::new(),
1040 1074
        };
1041 -
        let commit = Brain::write_fresh_state(&repository, base, &state_ref)?;
1075 +
        let commit = Brain::write_fresh_state(&repository, base, target, &state_ref)?;
1042 1076
        let mut brain = Self::new(
1043 1077
            repository,
1044 1078
            state_ref,
1045 1079
            comments_ref,
1046 1080
            base,
1081 +
            target,
1047 1082
            commit,
1048 1083
            Accepted::new(),
1049 1084
        );
1050 1085
        brain.remap(commits, documents, &stored)?;
1051 1086
1052 1087
        Ok(brain)
1053 1088
    }
1054 1089
1055 -
    /// Writes an empty accepted-state commit at `base`.
1090 +
    /// Writes an empty accepted-state commit for one resolved review range.
1056 1091
    fn write_fresh_state(
1057 1092
        repository: &git::Repository,
1058 1093
        base: Oid,
1094 +
        target: Oid,
1059 1095
        state_ref: &Qualified<'_>,
1060 1096
    ) -> Result<Oid, Error> {
1061 1097
        let tree = repository.tree_id(base)?;
1098 +
        let state = PersistedState {
1099 +
            target,
1100 +
            accepted: Accepted::new(),
1101 +
        };
1062 1102
        let fresh = repository.commit(
1063 1103
            tree,
1064 1104
            base,
1065 1105
            "brain",
1066 1106
            "brain@example.invalid",
1067 -
            &encode_state(&Accepted::new()),
1107 +
            &encode_state(&state),
1068 1108
        )?;
1069 1109
        repository.update_ref(state_ref, fresh)?;
1070 1110
1071 1111
        Ok(fresh)
1072 1112
    }
1208 1248
        self.persist(tree, accepted)
1209 1249
    }
1210 1250
1211 1251
    /// Persists exact acceptance and its derived tree in one commit.
1212 1252
    fn persist(&mut self, tree: Oid, accepted: Accepted) -> Result<(), Error> {
1213 -
        let message = encode_state(&accepted);
1253 +
        let state = PersistedState {
1254 +
            target: self.target,
1255 +
            accepted,
1256 +
        };
1257 +
        let message = encode_state(&state);
1214 1258
        let commit =
1215 1259
            self.repository
1216 1260
                .commit(tree, self.base, "brain", "brain@example.invalid", &message)?;
1217 1261
        self.repository.update_ref(&self.state_ref, commit)?;
1218 1262
        self.commit = commit;
1219 -
        self.accepted = accepted;
1263 +
        self.accepted = state.accepted;
1220 1264
1221 1265
        Ok(())
1222 1266
    }
1223 1267
1224 1268
    /// Projects exact acceptance onto the current commit list.
1356 1400
        Ok(DiffDocument::decode_bytes(&bytes)?.files)
1357 1401
    }
1358 1402
1359 1403
    fn brain(&self) -> Result<Brain, Error> {
1360 1404
        let base = self.repository.commit_id(&self.review.base)?;
1361 -
        Brain::load(self.repository.clone(), base, &self.review)
1405 +
        let target = self.repository.commit_id(&self.review.target)?;
1406 +
        Brain::load(self.repository.clone(), base, target, &self.review)
1362 1407
    }
1363 1408
1364 1409
    fn reset_brain(&self) -> Result<Brain, Error> {
1365 1410
        let base = self.repository.commit_id(&self.review.base)?;
1366 -
        Brain::reset(self.repository.clone(), base, &self.review)
1411 +
        let target = self.repository.commit_id(&self.review.target)?;
1412 +
        Brain::reset(self.repository.clone(), base, target, &self.review)
1367 1413
    }
1368 1414
1369 1415
    fn rebase_brain(&self) -> Result<Brain, Error> {
1370 1416
        let base = self.repository.commit_id(&self.review.base)?;
1417 +
        let target = self.repository.commit_id(&self.review.target)?;
1371 1418
        let commits = self.commits()?;
1372 1419
        let documents = commits
1373 1420
            .iter()
1374 1421
            .map(|commit| Ok(self.diff_document(commit.id)?.split_hunks()))
1375 1422
            .collect::<Result<Vec<_>, Error>>()?;
1376 1423
        Brain::rebase(
1377 1424
            self.repository.clone(),
1378 1425
            base,
1426 +
            target,
1379 1427
            &self.review,
1380 1428
            &commits,
1381 1429
            &documents,
1382 1430
        )
1383 1431
    }
1434 1482
        Ok(DiffDocument::decode_bytes(&bytes)?.files)
1435 1483
    }
1436 1484
1437 1485
    fn brain(&self) -> Result<Brain, Error> {
1438 1486
        let base = self.jj.resolve(&self.review.base)?;
1439 -
        Brain::load(self.repository.clone(), base, &self.review)
1487 +
        let target = self.jj.resolve(&self.review.target)?;
1488 +
        Brain::load(self.repository.clone(), base, target, &self.review)
1440 1489
    }
1441 1490
1442 1491
    fn reset_brain(&self) -> Result<Brain, Error> {
1443 1492
        let base = self.jj.resolve(&self.review.base)?;
1444 -
        Brain::reset(self.repository.clone(), base, &self.review)
1493 +
        let target = self.jj.resolve(&self.review.target)?;
1494 +
        Brain::reset(self.repository.clone(), base, target, &self.review)
1445 1495
    }
1446 1496
1447 1497
    fn rebase_brain(&self) -> Result<Brain, Error> {
1448 1498
        let base = self.jj.resolve(&self.review.base)?;
1499 +
        let target = self.jj.resolve(&self.review.target)?;
1449 1500
        let commits = self.commits()?;
1450 1501
        let documents = commits
1451 1502
            .iter()
1452 1503
            .map(|commit| Ok(self.diff_document(commit.id)?.split_hunks()))
1453 1504
            .collect::<Result<Vec<_>, Error>>()?;
1454 1505
        Brain::rebase(
1455 1506
            self.repository.clone(),
1456 1507
            base,
1508 +
            target,
1457 1509
            &self.review,
1458 1510
            &commits,
1459 1511
            &documents,
1460 1512
        )
1461 1513
    }
1466 1518
}
1467 1519
1468 1520
#[cfg(test)]
1469 1521
mod tests {
1470 1522
    use super::*;
1471 -
1472 -
    /// Sequence used to keep parallel fixture paths distinct.
1473 -
    static NEXT_REPOSITORY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1523 +
    use std::fs;
1524 +
    use std::process::Command;
1525 +
    use std::time::{SystemTime, UNIX_EPOCH};
1474 1526
1475 1527
    /// Temporary Git repository removed when its test finishes.
1476 1528
    struct TestRepository {
1477 -
        /// Repository worktree path.
1529 +
        /// Repository working tree.
1478 1530
        path: std::path::PathBuf,
1479 1531
    }
1480 1532
1481 1533
    impl TestRepository {
1482 -
        /// Initializes an empty repository on a local `main` branch.
1534 +
        /// Creates a repository with `main` as its initial branch.
1483 1535
        fn new() -> Self {
1484 -
            let sequence = NEXT_REPOSITORY.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1536 +
            let nonce = SystemTime::now()
1537 +
                .duration_since(UNIX_EPOCH)
1538 +
                .unwrap()
1539 +
                .as_nanos();
1485 1540
            let path = std::env::temp_dir().join(format!(
1486 -
                "rustik-brain-test-{}-{sequence}",
1541 +
                "rustik-brain-rebase-{}-{nonce}",
1487 1542
                std::process::id()
1488 1543
            ));
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 }
1544 +
            fs::create_dir(&path).unwrap();
1545 +
            let repository = Self { path };
1546 +
            repository.git(&["init", "-q", "-b", "main"]);
1547 +
            repository.git(&["config", "user.name", "Rustik Test"]);
1548 +
            repository.git(&["config", "user.email", "rustik@example.invalid"]);
1549 +
            repository
1500 1550
        }
1501 1551
1502 -
        /// Runs one Git command with deterministic test identity configuration.
1552 +
        /// Runs a Git command and requires success.
1503 1553
        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 -
                ])
1554 +
            let status = Command::new("git")
1513 1555
                .args(args)
1514 1556
                .current_dir(&self.path)
1515 -
                .output()
1557 +
                .status()
1516 1558
                .unwrap();
1517 -
            assert!(
1518 -
                output.status.success(),
1519 -
                "git {} failed: {}",
1520 -
                args.join(" "),
1521 -
                String::from_utf8_lossy(&output.stderr)
1522 -
            );
1559 +
            assert!(status.success());
1523 1560
        }
1524 1561
    }
1525 1562
1526 1563
    impl Drop for TestRepository {
1527 1564
        fn drop(&mut self) {
1528 -
            let _ = std::fs::remove_dir_all(&self.path);
1565 +
            fs::remove_dir_all(&self.path).unwrap();
1529 1566
        }
1530 1567
    }
1531 1568
1569 +
    #[test]
1570 +
    fn rebase_remaps_acceptance_when_only_target_moves() {
1571 +
        let repository = TestRepository::new();
1572 +
        let file = repository.path.join("reviewed.txt");
1573 +
        fs::write(&file, "base\n").unwrap();
1574 +
        repository.git(&["add", "reviewed.txt"]);
1575 +
        repository.git(&["commit", "-q", "-m", "base"]);
1576 +
        repository.git(&["switch", "-q", "-c", "topic"]);
1577 +
        fs::write(&file, "accepted\n").unwrap();
1578 +
        repository.git(&["commit", "-q", "-am", "T1"]);
1579 +
1580 +
        let base = Rev::try_from("main").unwrap();
1581 +
        let target = Rev::try_from("topic").unwrap();
1582 +
        let backend = GitBackend::new(&repository.path, base, target).unwrap();
1583 +
        let first = backend.commits().unwrap().pop().unwrap();
1584 +
        let first_document = backend.diff_document(first.id).unwrap().split_hunks();
1585 +
        let mut brain = backend.reset_brain().unwrap();
1586 +
        let first_identity = brain
1587 +
            .hunk_identities(&first_document, first.id)
1588 +
            .unwrap()
1589 +
            .into_values()
1590 +
            .next()
1591 +
            .unwrap();
1592 +
        let first_patch =
1593 +
            hunk_identity_patch(&first_document.files[0], &first_document.files[0].hunks[0])
1594 +
                .unwrap();
1595 +
        brain.accept([(first_identity, first_patch)]).unwrap();
1596 +
1597 +
        repository.git(&["commit", "-q", "--amend", "-m", "T2"]);
1598 +
        let second = backend.commits().unwrap().pop().unwrap();
1599 +
        let second_document = backend.diff_document(second.id).unwrap().split_hunks();
1600 +
        let second_identity = brain
1601 +
            .hunk_identities(&second_document, second.id)
1602 +
            .unwrap()
1603 +
            .into_values()
1604 +
            .next()
1605 +
            .unwrap();
1606 +
1607 +
        let rebased = backend.rebase_brain().unwrap();
1608 +
1609 +
        assert_eq!(rebased.state_ref, brain.state_ref);
1610 +
        assert_eq!(rebased.target, second.id);
1611 +
        assert_eq!(rebased.accepted, Accepted::from([second_identity]));
1612 +
    }
1613 +
1532 1614
    #[test]
1533 1615
    fn statuses_match_symbolic_target_to_branch_commit() {
1534 1616
        let fixture = TestRepository::new();
1535 1617
        fixture.git(&["config", "init.defaultBranch", "main"]);
1536 1618
        fixture.git(&["commit", "-q", "--allow-empty", "-m", "base"]);
1539 1621
        let identity = ReviewIdentity::new(
1540 1622
            Rev::try_from("main").unwrap(),
1541 1623
            Rev::try_from("HEAD").unwrap(),
1542 1624
        );
1543 1625
        let base = repository.commit_id(&identity.base).unwrap();
1544 -
        let _brain = Brain::reset(repository.clone(), base, &identity).unwrap();
1626 +
        let target = repository.commit_id(&identity.target).unwrap();
1627 +
        let _brain = Brain::reset(repository.clone(), base, target, &identity).unwrap();
1545 1628
1546 1629
        let statuses = Brain::statuses(&repository).unwrap();
1547 1630
1548 1631
        assert_eq!(statuses.len(), 1);
1549 1632
        assert_eq!(statuses[0].head, "main");
1562 1645
        }
1563 1646
    }
1564 1647
1565 1648
    #[test]
1566 1649
    fn accepted_state_roundtrips_through_commit_message() {
1567 -
        let accepted = Accepted::from([
1568 -
            accepted_hunk("1111111111111111111111111111111111111111", "alpha", 0, 2),
1569 -
            accepted_hunk("1111111111111111111111111111111111111111", "beta", 0, 2),
1570 -
        ]);
1571 -
        let message = encode_state(&accepted);
1650 +
        let state = PersistedState {
1651 +
            target: "2222222222222222222222222222222222222222".parse().unwrap(),
1652 +
            accepted: Accepted::from([
1653 +
                accepted_hunk("1111111111111111111111111111111111111111", "alpha", 0, 2),
1654 +
                accepted_hunk("1111111111111111111111111111111111111111", "beta", 0, 2),
1655 +
            ]),
1656 +
        };
1657 +
        let message = encode_state(&state);
1572 1658
1573 -
        assert_eq!(decode_state(&message), Some(accepted));
1659 +
        assert!(message.starts_with("brain state\n\nbrain-v1\ntarget "));
1660 +
        assert_eq!(decode_state(&message), Some(state));
1574 1661
        assert_eq!(decode_state(SYNTHETIC_BRAIN_MESSAGE), None);
1575 1662
    }
1576 1663
1577 1664
    #[test]
1578 1665
    fn empty_accepted_state_roundtrips_through_commit_message() {
1579 -
        let message = encode_state(&Accepted::new());
1666 +
        let state = PersistedState {
1667 +
            target: "2222222222222222222222222222222222222222".parse().unwrap(),
1668 +
            accepted: Accepted::new(),
1669 +
        };
1670 +
        let message = encode_state(&state);
1580 1671
1581 -
        assert_eq!(decode_state(&message), Some(Accepted::new()));
1672 +
        assert_eq!(decode_state(&message), Some(state.clone()));
1582 1673
        // Git terminates `%B` output with its own newline.
1583 -
        assert_eq!(decode_state(&format!("{message}\n")), Some(Accepted::new()));
1674 +
        assert_eq!(decode_state(&format!("{message}\n")), Some(state));
1584 1675
    }
1585 1676
1586 1677
    #[test]
1587 1678
    fn accepted_state_rejects_inconsistent_line_totals() {
1588 1679
        let commit = "1111111111111111111111111111111111111111";
1680 +
        let target = format!("target {commit}\n");
1589 1681
        let inconsistent = format!(
1590 -
            "{SYNTHETIC_BRAIN_MESSAGE}\n\n{STATE_SECTION}\n{commit} alpha 0 1 2\n{commit} beta 0 1 3\n"
1682 +
            "{SYNTHETIC_BRAIN_MESSAGE}\n\n{STATE_SECTION}\n{target}{commit} alpha 0 1 2\n{commit} beta 0 1 3\n"
1591 1683
        );
1592 -
        let zero = format!("{SYNTHETIC_BRAIN_MESSAGE}\n\n{STATE_SECTION}\n{commit} alpha 0 0 1\n");
1684 +
        let zero =
1685 +
            format!("{SYNTHETIC_BRAIN_MESSAGE}\n\n{STATE_SECTION}\n{target}{commit} alpha 0 0 1\n");
1593 1686
        let duplicate = format!(
1594 -
            "{SYNTHETIC_BRAIN_MESSAGE}\n\n{STATE_SECTION}\n{commit} alpha 0 1 1\n{commit} alpha 0 1 1\n"
1687 +
            "{SYNTHETIC_BRAIN_MESSAGE}\n\n{STATE_SECTION}\n{target}{commit} alpha 0 1 1\n{commit} alpha 0 1 1\n"
1595 1688
        );
1596 1689
1597 1690
        assert_eq!(decode_state(&inconsistent), None);
1598 1691
        assert_eq!(decode_state(&zero), None);
1599 1692
        assert_eq!(decode_state(&duplicate), None);
1600 1693
    }
1601 1694
1602 1695
    #[test]
1603 1696
    fn accepted_state_rejects_malformed_payload() {
1604 -
        let message = format!(
1605 -
            "{SYNTHETIC_BRAIN_MESSAGE}\n\n{STATE_SECTION}\n{} alpha 0 1 1 extra\n",
1606 -
            "1111111111111111111111111111111111111111"
1697 +
        let commit = "1111111111111111111111111111111111111111";
1698 +
        let extra_field = format!(
1699 +
            "{SYNTHETIC_BRAIN_MESSAGE}\n\n{STATE_SECTION}\ntarget {commit}\n{commit} alpha 0 1 1 extra\n"
1607 1700
        );
1701 +
        let missing_target =
1702 +
            format!("{SYNTHETIC_BRAIN_MESSAGE}\n\n{STATE_SECTION}\n{commit} alpha 0 1 1\n");
1608 1703
1609 -
        assert_eq!(decode_state(&message), None);
1704 +
        assert_eq!(decode_state(&extra_field), None);
1705 +
        assert_eq!(decode_state(&missing_target), None);
1610 1706
    }
1611 1707
1612 1708
    #[test]
1613 1709
    fn reconciliation_uses_exact_accepted_identities() {
1614 1710
        let first = accepted_hunk("1111111111111111111111111111111111111111", "change", 0, 1);
f +0 -0
new.rs +0 -0
image.png +0 -0