pointbreak 0.5.0

Durable terminal code review for changes humans and coding agents collaborate on together
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
//! Git-free projection of a Revision's commit-range lifecycle.
//!
//! Folds `WorkObjectProposed` plus the four association/withdrawal events into a
//! per-unit view of which commits and refs the unit currently claims. Every
//! status is derived: `current = capture_target_seed ∪ (associated − withdrawn)`.
//! A commit-range capture seeds one anchored commit that is never withdrawable;
//! only association-backed edges are subtracted by their association id.
//!
//! This fold touches only `event_type` and `payload` — no git, no clock, no
//! store reads. Reachability (merged/live/orphaned) is a separate read-time
//! enrichment and never enters this view.

use std::collections::BTreeMap;

use serde::Serialize;

use crate::error::Result;
use crate::model::{
    CommitAssociationId, CommitWithdrawalId, RefAssociationId, RefWithdrawalId, ReviewEndpoint,
    ReviewTargetRef, RevisionId,
};
use crate::session::event::{
    EventType, GitProvenance, RevisionCommitAssociatedPayload, RevisionCommitWithdrawnPayload,
    RevisionRefAssociatedPayload, RevisionRefWithdrawnPayload, ShoreEvent, WorkObjectProposal,
    WorkObjectProposedPayload,
};
use crate::session::state::ProjectionDiagnostic;

/// Two un-withdrawn commit edges with different OIDs claim one unit at once. The
/// projection surfaces both and withholds any headline. Realizes the condition
/// ADR-0008 reserved as `ambiguous_supersession` for the commit axis.
pub const DIVERGENT_COMMIT_ASSOCIATION_CODE: &str = "divergent_commit_association";
/// A withdrawal names an association id absent from the unit's associated set.
/// The withdrawal has no effect yet; the diagnostic clears when the association
/// backfills. Recorded, never rejected.
pub const RETRACTION_TARGET_MISSING_CODE: &str = "retraction_target_missing";

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RevisionCommitRangeProjection {
    pub units: BTreeMap<RevisionId, RevisionCommitRangeView>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RevisionCommitRangeView {
    pub revision_id: RevisionId,
    pub anchored: bool,
    pub current_commits: Vec<CurrentCommitAssociation>,
    pub current_refs: Vec<CurrentRefAssociation>,
    pub withdrawn_commits: Vec<WithdrawnCommitAssociation>,
    pub withdrawn_refs: Vec<WithdrawnRefAssociation>,
    pub diagnostics: Vec<ProjectionDiagnostic>,
}

/// How a current commit edge entered the view.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CommitEdgeSource {
    /// A commit-range capture's seed target: born anchored, not withdrawable.
    CaptureTarget,
    /// An association event: subtractable by its association id.
    Association,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CurrentCommitAssociation {
    pub commit_oid: String,
    pub tree_oid: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub commit_association_id: Option<CommitAssociationId>,
    pub source: CommitEdgeSource,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CurrentRefAssociation {
    pub ref_association_id: RefAssociationId,
    pub ref_name: String,
    pub head_oid: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WithdrawnCommitAssociation {
    pub commit_oid: String,
    pub tree_oid: String,
    pub commit_association_id: CommitAssociationId,
    pub commit_withdrawal_id: CommitWithdrawalId,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WithdrawnRefAssociation {
    pub ref_association_id: RefAssociationId,
    pub ref_name: String,
    pub head_oid: String,
    pub ref_withdrawal_id: RefWithdrawalId,
}

impl RevisionCommitRangeProjection {
    pub fn from_events(events: &[ShoreEvent]) -> Result<Self> {
        let mut builders = BTreeMap::<RevisionId, CommitRangeBuilder>::new();

        for event in events {
            match event.event_type {
                EventType::WorkObjectProposed => {
                    let payload: WorkObjectProposedPayload =
                        serde_json::from_value(event.payload.clone())?;
                    if let WorkObjectProposal::Revision { revision, .. } = payload.work_object {
                        let builder = builders.entry(revision.id.clone()).or_default();
                        if let Some(GitProvenance {
                            target:
                                ReviewEndpoint::GitCommit {
                                    commit_oid,
                                    tree_oid,
                                },
                            ..
                        }) = revision.git_provenance
                        {
                            builder.capture_target = Some((commit_oid, tree_oid));
                        }
                    }
                }
                EventType::RevisionCommitAssociated => {
                    let payload: RevisionCommitAssociatedPayload =
                        serde_json::from_value(event.payload.clone())?;
                    if let (
                        Some(revision_id),
                        ReviewEndpoint::GitCommit {
                            commit_oid,
                            tree_oid,
                        },
                    ) = (revision_of(&payload.target), payload.commit)
                    {
                        builders
                            .entry(revision_id)
                            .or_default()
                            .associated_commits
                            .insert(payload.commit_association_id, (commit_oid, tree_oid));
                    }
                }
                EventType::RevisionCommitWithdrawn => {
                    let payload: RevisionCommitWithdrawnPayload =
                        serde_json::from_value(event.payload.clone())?;
                    if let Some(revision_id) = revision_of(&payload.target) {
                        builders
                            .entry(revision_id)
                            .or_default()
                            .withdrawn_commits
                            .insert(payload.commit_association_id, payload.commit_withdrawal_id);
                    }
                }
                EventType::RevisionRefAssociated => {
                    let payload: RevisionRefAssociatedPayload =
                        serde_json::from_value(event.payload.clone())?;
                    if let Some(revision_id) = revision_of(&payload.target) {
                        builders
                            .entry(revision_id)
                            .or_default()
                            .associated_refs
                            .insert(
                                payload.ref_association_id,
                                (payload.ref_name, payload.head_oid),
                            );
                    }
                }
                EventType::RevisionRefWithdrawn => {
                    let payload: RevisionRefWithdrawnPayload =
                        serde_json::from_value(event.payload.clone())?;
                    if let Some(revision_id) = revision_of(&payload.target) {
                        builders
                            .entry(revision_id)
                            .or_default()
                            .withdrawn_refs
                            .insert(payload.ref_association_id, payload.ref_withdrawal_id);
                    }
                }
                _ => {}
            }
        }

        let units = builders
            .into_iter()
            .map(|(revision_id, builder)| {
                let view = builder.finish(revision_id.clone());
                (revision_id, view)
            })
            .collect();

        Ok(Self { units })
    }

    pub fn unit(&self, revision_id: &RevisionId) -> Option<&RevisionCommitRangeView> {
        self.units.get(revision_id)
    }

    /// Units whose current refs include an exact `ref_name` label match. Used by
    /// the offline `--ref` (Label) read filter.
    pub fn units_for_ref(&self, ref_name: &str) -> Vec<&RevisionCommitRangeView> {
        self.units
            .values()
            .filter(|view| {
                view.current_refs
                    .iter()
                    .any(|current| current.ref_name == ref_name)
            })
            .collect()
    }
}

/// The review-unit subject of an association payload, if it is the expected
/// `Revision` target shape.
pub(crate) fn revision_of(target: &ReviewTargetRef) -> Option<RevisionId> {
    match target {
        ReviewTargetRef::Revision { revision_id } => Some(revision_id.clone()),
        _ => None,
    }
}

#[derive(Debug, Default)]
struct CommitRangeBuilder {
    capture_target: Option<(String, String)>,
    associated_commits: BTreeMap<CommitAssociationId, (String, String)>,
    withdrawn_commits: BTreeMap<CommitAssociationId, CommitWithdrawalId>,
    associated_refs: BTreeMap<RefAssociationId, (String, String)>,
    withdrawn_refs: BTreeMap<RefAssociationId, RefWithdrawalId>,
}

impl CommitRangeBuilder {
    fn finish(self, revision_id: RevisionId) -> RevisionCommitRangeView {
        let mut diagnostics = Vec::new();

        let commit_axis = partition_axis(self.associated_commits, self.withdrawn_commits);
        let ref_axis = partition_axis(self.associated_refs, self.withdrawn_refs);

        // current_commits: capture-target seed (never withdrawable) ∪ association-backed survivors.
        let mut current_commits = Vec::new();
        if let Some((commit_oid, tree_oid)) = self.capture_target {
            current_commits.push(CurrentCommitAssociation {
                commit_oid,
                tree_oid,
                commit_association_id: None,
                source: CommitEdgeSource::CaptureTarget,
            });
        }
        for (commit_association_id, (commit_oid, tree_oid)) in commit_axis.current {
            current_commits.push(CurrentCommitAssociation {
                commit_oid,
                tree_oid,
                commit_association_id: Some(commit_association_id),
                source: CommitEdgeSource::Association,
            });
        }
        current_commits.sort_by(|left, right| left.commit_oid.cmp(&right.commit_oid));

        let mut withdrawn_commits = commit_axis
            .withdrawn
            .into_iter()
            .map(
                |(commit_association_id, (commit_oid, tree_oid), commit_withdrawal_id)| {
                    WithdrawnCommitAssociation {
                        commit_oid,
                        tree_oid,
                        commit_association_id,
                        commit_withdrawal_id,
                    }
                },
            )
            .collect::<Vec<_>>();
        withdrawn_commits.sort_by(|left, right| left.commit_oid.cmp(&right.commit_oid));

        let mut current_refs = ref_axis
            .current
            .into_iter()
            .map(
                |(ref_association_id, (ref_name, head_oid))| CurrentRefAssociation {
                    ref_association_id,
                    ref_name,
                    head_oid,
                },
            )
            .collect::<Vec<_>>();
        current_refs.sort_by(|left, right| {
            left.ref_name
                .cmp(&right.ref_name)
                .then_with(|| left.head_oid.cmp(&right.head_oid))
        });

        let mut withdrawn_refs = ref_axis
            .withdrawn
            .into_iter()
            .map(
                |(ref_association_id, (ref_name, head_oid), ref_withdrawal_id)| {
                    WithdrawnRefAssociation {
                        ref_association_id,
                        ref_name,
                        head_oid,
                        ref_withdrawal_id,
                    }
                },
            )
            .collect::<Vec<_>>();
        withdrawn_refs.sort_by(|left, right| left.ref_name.cmp(&right.ref_name));

        // retraction_target_missing: a withdrawal whose association id never appeared.
        for missing in commit_axis
            .missing_targets
            .into_iter()
            .map(|id| id.as_str().to_owned())
            .chain(
                ref_axis
                    .missing_targets
                    .into_iter()
                    .map(|id| id.as_str().to_owned()),
            )
        {
            diagnostics.push(diagnostic(
                RETRACTION_TARGET_MISSING_CODE,
                format!(
                    "revision {} withdraws association {missing}, which has no matching association",
                    revision_id.as_str()
                ),
            ));
        }

        // divergent_commit_association: two or more distinct current OIDs claim the revision.
        let distinct_oids = current_commits
            .iter()
            .map(|commit| commit.commit_oid.as_str())
            .collect::<std::collections::BTreeSet<_>>();
        if distinct_oids.len() > 1 {
            diagnostics.push(diagnostic(
                DIVERGENT_COMMIT_ASSOCIATION_CODE,
                format!(
                    "revision {} has {} distinct current commit associations",
                    revision_id.as_str(),
                    distinct_oids.len()
                ),
            ));
        }

        RevisionCommitRangeView {
            revision_id,
            anchored: !current_commits.is_empty(),
            current_commits,
            current_refs,
            withdrawn_commits,
            withdrawn_refs,
            diagnostics,
        }
    }
}

struct AxisPartition<I, V, W> {
    current: Vec<(I, V)>,
    withdrawn: Vec<(I, V, W)>,
    missing_targets: Vec<I>,
}

/// Splits an associated map against a withdrawn map by id: survivors are
/// `associated − withdrawn`, withdrawn-history pairs an association with its
/// withdrawal, and a withdrawal with no matching association is a missing
/// target (the `retraction_target_missing` signal). Shared by both axes.
fn partition_axis<I, V, W>(
    associated: BTreeMap<I, V>,
    mut withdrawn: BTreeMap<I, W>,
) -> AxisPartition<I, V, W>
where
    I: Ord + Clone,
{
    let mut current = Vec::new();
    let mut withdrawn_history = Vec::new();
    for (id, value) in associated {
        match withdrawn.remove(&id) {
            Some(withdrawal) => withdrawn_history.push((id, value, withdrawal)),
            None => current.push((id, value)),
        }
    }
    let missing_targets = withdrawn.into_keys().collect();
    AxisPartition {
        current,
        withdrawn: withdrawn_history,
        missing_targets,
    }
}

fn diagnostic(code: &str, message: String) -> ProjectionDiagnostic {
    ProjectionDiagnostic {
        code: code.to_owned(),
        message,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{
        EngagementId, JournalId, ObjectId, ReviewEndpoint, ReviewTargetRef, RevisionId,
        RevisionSource, WorktreeCaptureMode,
    };
    use crate::session::event::{
        EventTarget, EventType, GitProvenance, Revision, RevisionCommitAssociatedPayload,
        RevisionCommitWithdrawnPayload, RevisionRefAssociatedPayload, ShoreEvent,
        WorkObjectProposal, WorkObjectProposedPayload, Writer, build_commit_association_id,
        build_commit_withdrawal_id, build_ref_association_id,
    };

    fn revision_id() -> RevisionId {
        RevisionId::new("rev:git:sha256:def")
    }

    fn target() -> ReviewTargetRef {
        ReviewTargetRef::Revision {
            revision_id: revision_id(),
        }
    }

    fn envelope() -> EventTarget {
        EventTarget::for_revision(JournalId::new("journal:default"), revision_id(), None).unwrap()
    }

    fn capture(target_endpoint: ReviewEndpoint) -> ShoreEvent {
        ShoreEvent::new(
            EventType::WorkObjectProposed,
            format!("work_object_proposed:{}", revision_id().as_str()),
            envelope(),
            Writer::shore_local("test"),
            WorkObjectProposedPayload {
                engagement_id: EngagementId::new(format!(
                    "engagement:sha256:{}",
                    crate::canonical_hash::sha256_bytes_hex(
                        (RevisionId::new("rev:git:sha256:def")).as_str().as_bytes()
                    )
                )),
                work_object: WorkObjectProposal::Revision {
                    revision: Revision {
                        id: revision_id(),
                        object_id: ObjectId::new("snap:git:sha256:ghi"),
                        git_provenance: Some(GitProvenance {
                            source: RevisionSource::GitWorktree {
                                mode: WorktreeCaptureMode::CombinedHeadToWorkingTree,
                                include_untracked: true,
                                pathspecs: Vec::new(),
                            },
                            base: ReviewEndpoint::GitCommit {
                                commit_oid: "base".to_owned(),
                                tree_oid: "base-tree".to_owned(),
                            },
                            target: target_endpoint,
                        }),
                    },
                    object_artifact_content_hash: "sha256:artifact".to_owned(),
                    supersedes: vec![],
                },
            },
            "2026-06-19T00:00:00Z",
        )
        .unwrap()
    }

    fn worktree_capture() -> ShoreEvent {
        capture(ReviewEndpoint::GitWorkingTree {
            worktree_root: "/repo".to_owned(),
        })
    }

    fn commit_associated(commit_oid: &str) -> ShoreEvent {
        let ru = revision_id();
        let cid = build_commit_association_id(&ru, commit_oid).unwrap();
        ShoreEvent::new(
            EventType::RevisionCommitAssociated,
            RevisionCommitAssociatedPayload::idempotency_key(&ru, commit_oid),
            envelope(),
            Writer::shore_local("test"),
            RevisionCommitAssociatedPayload {
                commit_association_id: cid,
                target: target(),
                commit: ReviewEndpoint::GitCommit {
                    commit_oid: commit_oid.to_owned(),
                    tree_oid: format!("{commit_oid}-tree"),
                },
            },
            "2026-06-19T00:00:01Z",
        )
        .unwrap()
    }

    fn commit_withdrawn(commit_oid: &str) -> ShoreEvent {
        let ru = revision_id();
        let cid = build_commit_association_id(&ru, commit_oid).unwrap();
        let wid = build_commit_withdrawal_id(&ru, &cid).unwrap();
        ShoreEvent::new(
            EventType::RevisionCommitWithdrawn,
            RevisionCommitWithdrawnPayload::idempotency_key(&cid),
            envelope(),
            Writer::shore_local("test"),
            RevisionCommitWithdrawnPayload {
                commit_withdrawal_id: wid,
                target: target(),
                commit_association_id: cid,
            },
            "2026-06-19T00:00:02Z",
        )
        .unwrap()
    }

    fn ref_associated(ref_name: &str, head_oid: &str) -> ShoreEvent {
        let ru = revision_id();
        let rid = build_ref_association_id(&ru, ref_name, head_oid).unwrap();
        ShoreEvent::new(
            EventType::RevisionRefAssociated,
            RevisionRefAssociatedPayload::idempotency_key(&ru, ref_name, head_oid),
            envelope(),
            Writer::shore_local("test"),
            RevisionRefAssociatedPayload {
                ref_association_id: rid,
                target: target(),
                ref_name: ref_name.to_owned(),
                head_oid: head_oid.to_owned(),
            },
            "2026-06-19T00:00:03Z",
        )
        .unwrap()
    }

    fn view_of(events: &[ShoreEvent]) -> RevisionCommitRangeView {
        RevisionCommitRangeProjection::from_events(events)
            .unwrap()
            .unit(&revision_id())
            .unwrap()
            .clone()
    }

    #[test]
    fn commit_range_capture_is_born_anchored() {
        let view = view_of(&[capture(ReviewEndpoint::GitCommit {
            commit_oid: "target".to_owned(),
            tree_oid: "target-tree".to_owned(),
        })]);

        assert!(view.anchored);
        assert_eq!(view.current_commits.len(), 1);
        assert_eq!(view.current_commits[0].commit_oid, "target");
        assert_eq!(
            view.current_commits[0].source,
            CommitEdgeSource::CaptureTarget
        );
        assert!(view.current_commits[0].commit_association_id.is_none());
    }

    #[test]
    fn worktree_capture_is_born_floating() {
        let view = view_of(&[worktree_capture()]);

        assert!(!view.anchored);
        assert!(view.current_commits.is_empty());
    }

    #[test]
    fn current_set_is_associated_minus_withdrawn() {
        let anchored = view_of(&[worktree_capture(), commit_associated("oidA")]);
        assert!(anchored.anchored);
        assert_eq!(anchored.current_commits.len(), 1);
        assert_eq!(anchored.current_commits[0].commit_oid, "oidA");
        assert_eq!(
            anchored.current_commits[0].source,
            CommitEdgeSource::Association
        );

        let floating = view_of(&[
            worktree_capture(),
            commit_associated("oidA"),
            commit_withdrawn("oidA"),
        ]);
        assert!(!floating.anchored);
        assert!(floating.current_commits.is_empty());
        assert_eq!(floating.withdrawn_commits.len(), 1);
        assert_eq!(floating.withdrawn_commits[0].commit_oid, "oidA");
    }

    #[test]
    fn capture_target_seed_is_not_withdrawable() {
        // A withdrawal cannot name the capture-target seed (it has no association id),
        // so an anchored commit-range capture stays anchored.
        let view = view_of(&[
            capture(ReviewEndpoint::GitCommit {
                commit_oid: "target".to_owned(),
                tree_oid: "target-tree".to_owned(),
            }),
            commit_associated("oidA"),
            commit_withdrawn("oidA"),
        ]);

        assert!(view.anchored);
        assert_eq!(view.current_commits.len(), 1);
        assert_eq!(
            view.current_commits[0].source,
            CommitEdgeSource::CaptureTarget
        );
    }

    #[test]
    fn withdrawal_is_terminal_no_revival() {
        let view = view_of(&[
            worktree_capture(),
            commit_associated("oidA"),
            commit_withdrawn("oidA"),
            commit_associated("oidA"),
        ]);

        assert!(!view.anchored);
        assert!(view.current_commits.is_empty());
        assert_eq!(view.withdrawn_commits.len(), 1);
    }

    #[test]
    fn divergent_commit_association_withholds_and_surfaces_both() {
        let view = view_of(&[
            worktree_capture(),
            commit_associated("oidA"),
            commit_associated("oidB"),
        ]);

        assert_eq!(view.current_commits.len(), 2);
        let oids: Vec<&str> = view
            .current_commits
            .iter()
            .map(|commit| commit.commit_oid.as_str())
            .collect();
        assert_eq!(oids, vec!["oidA", "oidB"]);
        let divergent = view
            .diagnostics
            .iter()
            .find(|d| d.code == DIVERGENT_COMMIT_ASSOCIATION_CODE)
            .expect("divergent diagnostic present");
        assert!(
            divergent.message.contains("revision"),
            "message names the revision work object: {}",
            divergent.message
        );
        assert!(
            !divergent.message.contains("review unit"),
            "retired vocabulary swept: {}",
            divergent.message
        );
    }

    #[test]
    fn retraction_target_missing_self_heals() {
        let missing = view_of(&[worktree_capture(), commit_withdrawn("oidA")]);
        let retraction = missing
            .diagnostics
            .iter()
            .find(|d| d.code == RETRACTION_TARGET_MISSING_CODE)
            .expect("retraction diagnostic present");
        assert!(
            retraction.message.contains("revision"),
            "message names the revision work object: {}",
            retraction.message
        );
        assert!(
            !retraction.message.contains("review unit"),
            "retired vocabulary swept: {}",
            retraction.message
        );
        assert!(!missing.anchored);

        // When the association backfills, the diagnostic clears and the edge is subtracted.
        let healed = view_of(&[
            worktree_capture(),
            commit_withdrawn("oidA"),
            commit_associated("oidA"),
        ]);
        assert!(
            !healed
                .diagnostics
                .iter()
                .any(|d| d.code == RETRACTION_TARGET_MISSING_CODE)
        );
        assert!(!healed.anchored);
        assert_eq!(healed.withdrawn_commits.len(), 1);
    }

    #[test]
    fn ref_axis_tracks_current_and_units_for_ref() {
        let view = view_of(&[
            worktree_capture(),
            ref_associated("refs/heads/feat/x", "oidH"),
        ]);
        assert_eq!(view.current_refs.len(), 1);
        assert_eq!(view.current_refs[0].ref_name, "refs/heads/feat/x");

        let projection = RevisionCommitRangeProjection::from_events(&[
            worktree_capture(),
            ref_associated("refs/heads/feat/x", "oidH"),
        ])
        .unwrap();
        assert_eq!(projection.units_for_ref("refs/heads/feat/x").len(), 1);
        assert_eq!(projection.units_for_ref("refs/heads/other").len(), 0);
    }
}