Skip to main content

memstead_base/engine/
independence.rs

1//! The author≠checker independence reading, derived from provenance.
2//!
3//! A check record confirms an acceptance criterion only when the party
4//! that did the work did not record it. Until 2026-09-02 the reading
5//! compared a check's identity with the identity that CREATED the
6//! criterion entity — and the planning session authors criteria while the
7//! executing session checks them, so the executor's own checks read
8//! `confirmed_independent` (found twice by the evidence-engine bundle,
9//! once on a wrong check). The comparator now (decision basket line 9,
10//! option a): a check on a criterion reads `confirmed_independent` only
11//! when its identity differs from **every identity that mutated the
12//! verified plan, its criteria, or its session-log notes since the
13//! criterion was written**; a check under one of those identities reads
14//! `self_checked`; a check or a record without an identity stays
15//! `unconfirmable`. Identities are the only comparator; roles and the
16//! transport pair are recorded context. Nothing is stamped: the reading
17//! is computed at read time from the append-only provenance record, so
18//! every existing ledger keeps parsing and derives under the new rule.
19//!
20//! The `transition_requires_checks` gate consumes the same reading: a
21//! plan cannot complete on the executor's own checks. The gate adds one
22//! orthogonal condition the reading never carries (2026-09-27): the
23//! confirming record must be declared in a checking capacity, role
24//! `checker` or `verifier`. A record in role `author` is the caller
25//! saying they act as the author, and a record with no role is
26//! cannot-confirm (the 2026-08-09 role decision); neither closes a
27//! gate, and each is reported under its own label
28//! ([`LABEL_ROLE_AUTHOR`], [`LABEL_ROLE_UNSPECIFIED`]) beside the
29//! readings, which stay a closed vocabulary.
30//!
31//! An archive mount records no history at the engine seam, so nothing
32//! on the mount can derive the reading; the export derives it once per
33//! sealed record from the source mem's provenance and seals it beside
34//! the record (`independence` on [`crate::check::SealedCheck`]), and the
35//! mount serves the sealed reading. The archive is immutable, so the
36//! reading at export time is the reading, not a stamp that could go
37//! stale. A member sealed by an older writer carries none and reads
38//! `unconfirmable`, as before.
39
40use std::collections::{BTreeSet, HashMap};
41
42use serde::Serialize;
43
44use super::Engine;
45use crate::check::{CheckRecord, CheckState};
46
47/// The independence half of a check's standing.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
49#[serde(rename_all = "snake_case")]
50pub enum Independence {
51    /// The check's identity mutated nothing in the verified plan's set
52    /// since the criterion was written.
53    ConfirmedIndependent,
54    /// The check's identity is one of the executors.
55    SelfChecked,
56    /// The check, or every relevant provenance record, carries no
57    /// identity — absence is never promoted.
58    Unconfirmable,
59}
60
61impl Independence {
62    /// Every reading, in wire order.
63    pub const ALL: [Self; 3] = [
64        Self::ConfirmedIndependent,
65        Self::SelfChecked,
66        Self::Unconfirmable,
67    ];
68
69    pub fn as_str(self) -> &'static str {
70        match self {
71            Self::ConfirmedIndependent => "confirmed_independent",
72            Self::SelfChecked => "self_checked",
73            Self::Unconfirmable => "unconfirmable",
74        }
75    }
76
77    /// Parse the wire form (the string [`Self::as_str`] renders, as the
78    /// sealed member carries it). Closed: anything else is `None`.
79    pub fn from_wire(s: &str) -> Option<Self> {
80        Self::ALL.into_iter().find(|r| r.as_str() == s)
81    }
82
83    /// The vocabulary, for an error message.
84    pub fn vocabulary_hint() -> String {
85        Self::ALL
86            .iter()
87            .map(|r| r.as_str())
88            .collect::<Vec<_>>()
89            .join(", ")
90    }
91}
92
93/// The gate's label for a confirming record declared in the author's
94/// role: the caller said they acted as the author, and an author's
95/// record does not close a gate on someone else's check.
96pub const LABEL_ROLE_AUTHOR: &str = "role_author";
97/// The gate's label for a confirming record that declares no role:
98/// absence is cannot-confirm, never a guessed capacity.
99pub const LABEL_ROLE_UNSPECIFIED: &str = "role_unspecified";
100
101/// One entity's standing before the gate: its derived check state, for
102/// an ok-checked entity the independence of that check, and the role
103/// the record was declared in.
104///
105/// Three orthogonal conditions close a gate, and each is reported on
106/// its own: the state is `checked_ok` (fresh against the entity's
107/// bytes), the reading is `confirmed_independent` (the identity is none
108/// of the executors), and the role is a checking capacity, `checker` or
109/// `verifier`. A record in role `author` reads [`LABEL_ROLE_AUTHOR`],
110/// one with no role [`LABEL_ROLE_UNSPECIFIED`]; neither confirms. The
111/// role never enters the independence reading, which compares
112/// identities and nothing else.
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct CheckStanding {
115    pub state: CheckState,
116    /// `Some` only for `CheckedOk`.
117    pub independence: Option<Independence>,
118    /// The role the newest record was declared in; `Unspecified` when
119    /// it carries none, and for every state but `CheckedOk`.
120    pub role: crate::vcs::Role,
121}
122
123impl CheckStanding {
124    /// A standing that confirms when the state is `checked_ok` — the
125    /// form store-only callers (and tests) build when no provenance is
126    /// in play: independent, and declared in the checker's role.
127    pub fn assumed_independent(state: CheckState) -> Self {
128        Self {
129            state,
130            independence: (state == CheckState::CheckedOk)
131                .then_some(Independence::ConfirmedIndependent),
132            role: crate::vcs::Role::Checker,
133        }
134    }
135
136    /// Whether the declared role is a checking capacity.
137    pub fn role_confirms(&self) -> bool {
138        matches!(
139            self.role,
140            crate::vcs::Role::Checker | crate::vcs::Role::Verifier
141        )
142    }
143
144    /// Whether this standing satisfies the transition gate.
145    pub fn confirms(&self) -> bool {
146        self.state == CheckState::CheckedOk
147            && self.independence == Some(Independence::ConfirmedIndependent)
148            && self.role_confirms()
149    }
150
151    /// The label the gate reports for an entity that does not confirm:
152    /// the check state; the independence reading when the state is
153    /// `checked_ok` but not independent; the role label when the record
154    /// is independent but not declared in a checking capacity.
155    pub fn label(&self) -> &'static str {
156        match (self.state, self.independence) {
157            (CheckState::CheckedOk, Some(Independence::ConfirmedIndependent)) => match self.role {
158                crate::vcs::Role::Checker | crate::vcs::Role::Verifier => {
159                    Independence::ConfirmedIndependent.as_str()
160                }
161                crate::vcs::Role::Author => LABEL_ROLE_AUTHOR,
162                crate::vcs::Role::Unspecified => LABEL_ROLE_UNSPECIFIED,
163            },
164            (CheckState::CheckedOk, Some(i)) => i.as_str(),
165            (CheckState::CheckedOk, None) => Independence::Unconfirmable.as_str(),
166            (s, _) => s.as_str(),
167        }
168    }
169}
170
171/// One recorded write of an entity: when, by whom, the backend-native
172/// reference of the write (a commit sha on a git-branch mem, the ledger
173/// line's timestamp token on a folder mem), and its place in the mem's
174/// write order (`seq`, oldest first), which orders writes inside one
175/// second without a clock.
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub struct Touch {
178    pub ts: i64,
179    pub identity: Option<String>,
180    pub reference: String,
181    pub seq: usize,
182}
183
184/// One mem's mutation touches by entity, from the mem's provenance record
185/// (the git-branch note trailers, or the folder ledger). Built once per
186/// mem and shared by every derivation in one pass.
187#[derive(Debug, Default, Clone)]
188pub struct MemTouches {
189    by_entity: HashMap<String, Vec<Touch>>,
190    /// Rename notes seen, as `(seq, old, new)`, for [`Self::follow_renames`].
191    renames: Vec<(usize, String, String)>,
192}
193
194impl MemTouches {
195    /// Record one note's touch. A rename note's entity field reads
196    /// `old → new` (the engine's own subject shape, the pair
197    /// [`super::history::parse_rename_pair`] splits); the touch lands
198    /// under both ids and the pair is kept so [`Self::follow_renames`]
199    /// can join the two halves of the story. Anything else is one id.
200    fn absorb(&mut self, entity_field: &str, touch: Touch) {
201        match super::history::parse_rename_pair(entity_field) {
202            Some((old, new)) => {
203                self.by_entity
204                    .entry(old.clone())
205                    .or_default()
206                    .push(touch.clone());
207                let seq = touch.seq;
208                self.by_entity.entry(new.clone()).or_default().push(touch);
209                self.renames.push((seq, old, new));
210            }
211            None => self
212                .by_entity
213                .entry(entity_field.to_string())
214                .or_default()
215                .push(touch),
216        }
217    }
218
219    /// Join each renamed entity's story: the touches recorded under the
220    /// old id (its creation among them) become touches of the new id,
221    /// oldest rename first so a chain `a → b → c` carries `a`'s story
222    /// through `b` into `c`, and every story is left in write order.
223    /// Without this the renamed entity's oldest touch is the rename itself
224    /// and the renamer reads as its author.
225    fn follow_renames(&mut self) {
226        let mut renames = std::mem::take(&mut self.renames);
227        renames.sort_by_key(|r| r.0);
228        for (_, old, new) in &renames {
229            let inherited = self.by_entity.get(old).cloned().unwrap_or_default();
230            let target = self.by_entity.entry(new.clone()).or_default();
231            for touch in inherited {
232                if !target.contains(&touch) {
233                    target.push(touch);
234                }
235            }
236        }
237        for touches in self.by_entity.values_mut() {
238            touches.sort_by_key(|t| t.seq);
239        }
240        self.renames = renames;
241    }
242
243    /// The touches of `entity` in write order, oldest first.
244    pub fn story(&self, entity: &str) -> &[Touch] {
245        self.by_entity.get(entity).map(Vec::as_slice).unwrap_or(&[])
246    }
247
248    /// The identity of the write that created `entity`: the first touch in
249    /// write order, whatever order the backend fed them in.
250    pub fn first_author(&self, entity: &str) -> Option<&str> {
251        self.story(entity)
252            .first()
253            .and_then(|t| t.identity.as_deref())
254    }
255
256    /// The reference of `entity`'s last write, the one a check recorded
257    /// now sees.
258    pub fn last_write(&self, entity: &str) -> Option<&str> {
259        self.story(entity).last().map(|t| t.reference.as_str())
260    }
261
262    /// The oldest touch timestamp of `entity`, if any is recorded.
263    fn written_at(&self, entity: &str) -> Option<i64> {
264        self.by_entity
265            .get(entity)
266            .and_then(|t| t.iter().map(|t| t.ts).min())
267    }
268
269    /// Identities that touched `entity` at or after `since`.
270    fn identities_since(&self, entity: &str, since: i64, into: &mut BTreeSet<String>) {
271        if let Some(touches) = self.by_entity.get(entity) {
272            for t in touches {
273                if t.ts >= since
274                    && let Some(id) = &t.identity
275                {
276                    into.insert(id.clone());
277                }
278            }
279        }
280    }
281
282    /// Whether any touch of `entity` carries an identity.
283    fn any_identity(&self, entity: &str) -> bool {
284        self.by_entity
285            .get(entity)
286            .is_some_and(|t| t.iter().any(|t| t.identity.is_some()))
287    }
288
289    /// The writes a check saw: every touch of `entity` up to and including
290    /// the write the record names ([`CheckRecord::checked_write`]), in
291    /// write order. A record without the field (every line an earlier
292    /// engine wrote), or one naming a write the story does not hold, is
293    /// read against every touch at or before its `ts`.
294    pub fn writes_seen_by(&self, entity: &str, check: &CheckRecord) -> Vec<&Touch> {
295        let story = self.story(entity);
296        if let Some(r) = check.checked_write.as_deref()
297            && let Some(at) = story.iter().rposition(|t| t.reference == r)
298        {
299            return story[..=at].iter().collect();
300        }
301        story.iter().filter(|t| t.ts <= check.ts as i64).collect()
302    }
303}
304
305/// The executors of one criterion: the identities the reading compares
306/// against, and the plans the set was drawn from.
307#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
308pub struct Executors {
309    pub identities: Vec<String>,
310    pub plans: Vec<String>,
311}
312
313impl Engine {
314    /// Gather one mem's touches from its provenance record. Git-branch
315    /// mems walk the branch's commit notes once; folder and in-memory
316    /// mems read their ledger; an archive records no history at the
317    /// engine seam and yields no touches ([`Self::independence_of`]
318    /// serves the reading the export sealed instead).
319    pub fn mem_touches(&self, mem: &str) -> MemTouches {
320        let mut out = MemTouches::default();
321        let Some(m) = self.mounts.iter().find(|m| m.mount.mem == mem) else {
322            return out;
323        };
324        match &m.mount.storage {
325            crate::workspace::MountStorage::GitBranch { gitdir, branch } => {
326                if let Some(hook) = self.git_branch_ops.as_ref()
327                    && let Ok(changes) = (hook.changes_since)(
328                        gitdir,
329                        branch,
330                        mem,
331                        crate::ops::EMPTY_TREE_SHA,
332                        crate::ops::RENAME_SIMILARITY_DEFAULT,
333                    )
334                {
335                    // The notes arrive newest first: the write order is
336                    // their reverse.
337                    let count = changes.notes.len();
338                    for (i, n) in changes.notes.iter().enumerate() {
339                        let touch = Touch {
340                            ts: n.timestamp,
341                            identity: n.identity.clone(),
342                            reference: n.sha.clone(),
343                            seq: count - i,
344                        };
345                        if let Some(entity) = n.entity_id.as_deref() {
346                            out.absorb(entity, touch.clone());
347                        }
348                        // A multi-entity commit (a batch, a proposal merge)
349                        // names its entities in the `Entities:` trailer and
350                        // a count in its subject; the identity touches
351                        // every one of them.
352                        for entity in &n.entity_ids {
353                            out.absorb(entity, touch.clone());
354                        }
355                        // A proposal merge names every fork identity that
356                        // wrote a landed entity beside its proposer.
357                        for (entity, identity) in &n.co_writers {
358                            out.absorb(
359                                entity,
360                                Touch {
361                                    identity: Some(identity.clone()),
362                                    ..touch.clone()
363                                },
364                            );
365                        }
366                        // A merge that landed a fork rename joins the new
367                        // id's story to the old id's, as a rename does.
368                        for pair in &n.merge_renames {
369                            out.absorb(pair, touch.clone());
370                        }
371                        for entity in &n.unattributed_writes {
372                            out.absorb(
373                                entity,
374                                Touch {
375                                    identity: None,
376                                    ..touch.clone()
377                                },
378                            );
379                        }
380                    }
381                    out.follow_renames();
382                }
383            }
384            crate::workspace::MountStorage::Folder { .. }
385            | crate::workspace::MountStorage::InMemory => {
386                // The ledger is append-only: its line order is the write
387                // order.
388                if let Ok(records) = m.backend.read_provenance(None) {
389                    for (seq, r) in records.into_iter().enumerate() {
390                        let Some(entity) = r.entity.as_deref() else {
391                            continue;
392                        };
393                        let ts = r
394                            .timestamp
395                            .duration_since(std::time::UNIX_EPOCH)
396                            .map(|d| d.as_secs() as i64)
397                            .unwrap_or(0);
398                        // The line's timestamp token plus its ledger position:
399                        // two writes in one millisecond stay two references.
400                        let touch = Touch {
401                            ts,
402                            identity: r.identity.clone(),
403                            reference: format!(
404                                "{}#{seq}",
405                                crate::filesystem::changelog::format_rfc3339_utc(r.timestamp)
406                            ),
407                            seq,
408                        };
409                        // A rename line names the new id and the old one; the
410                        // story is joined as the git-branch notes join it.
411                        match r.renamed_from.as_deref() {
412                            Some(old) => out.absorb(&format!("{old} → {entity}"), touch),
413                            None => out.absorb(entity, touch),
414                        }
415                    }
416                    out.follow_renames();
417                }
418            }
419            crate::workspace::MountStorage::Archive { .. } => {}
420        }
421        out
422    }
423
424    /// The executors of `entity` (a criterion): every identity that
425    /// mutated the plan(s) it VERIFIES, those plans' other criteria, or the
426    /// notes PART_OF those plans, at or after the criterion's first touch.
427    /// `None` when the entity verifies no plan — the reading then compares
428    /// every identity that wrote the entity up to the write the check saw.
429    pub fn executors_of(
430        &self,
431        entity: &crate::entity::Entity,
432        touches: &MemTouches,
433    ) -> Option<Executors> {
434        let plans: Vec<crate::entity::EntityId> = entity
435            .relationships
436            .iter()
437            .filter(|r| r.rel_type == "VERIFIES")
438            .map(|r| r.target.clone())
439            .collect();
440        if plans.is_empty() {
441            return None;
442        }
443        let since = touches.written_at(&entity.id.0).unwrap_or(0);
444        let mut set: BTreeSet<String> = BTreeSet::new();
445        let mut members: BTreeSet<String> = BTreeSet::new();
446        for plan in &plans {
447            members.insert(plan.0.clone());
448            for other in self.store.all_entities().filter(|o| o.mem == entity.mem) {
449                if other.relationships.iter().any(|r| {
450                    &r.target == plan && (r.rel_type == "VERIFIES" || r.rel_type == "PART_OF")
451                }) {
452                    members.insert(other.id.0.clone());
453                }
454            }
455        }
456        for member in &members {
457            touches.identities_since(member, since, &mut set);
458        }
459        Some(Executors {
460            identities: set.into_iter().collect(),
461            plans: plans.into_iter().map(|p| p.0).collect(),
462        })
463    }
464
465    /// The independence reading of one ok check on `entity`. On an
466    /// archive mount the reading is the one the export sealed beside the
467    /// record ([`Self::sealed_independence_of`]): the mount has no
468    /// touches to derive from, and a member sealed without the reading
469    /// stays `unconfirmable`.
470    pub fn independence_of(
471        &self,
472        entity: &crate::entity::Entity,
473        check: &CheckRecord,
474        touches: &MemTouches,
475    ) -> (Independence, Option<Executors>) {
476        if self.is_archive_mount(&entity.mem) {
477            return (
478                self.sealed_independence_of(&entity.mem, check)
479                    .unwrap_or(Independence::Unconfirmable),
480                None,
481            );
482        }
483        let Some(checker) = check.identity.as_deref() else {
484            return (Independence::Unconfirmable, None);
485        };
486        match self.executors_of(entity, touches) {
487            Some(executors) => {
488                let reading = if executors.identities.iter().any(|i| i == checker) {
489                    Independence::SelfChecked
490                } else if executors.identities.is_empty()
491                    && !executors.plans.iter().any(|p| touches.any_identity(p))
492                    && !touches.any_identity(&entity.id.0)
493                {
494                    // Nothing in the plan's set carries an identity: no
495                    // comparator exists, the reading cannot be promoted.
496                    Independence::Unconfirmable
497                } else {
498                    Independence::ConfirmedIndependent
499                };
500                (reading, Some(executors))
501            }
502            None => {
503                // Not a criterion: every identity that wrote the entity up
504                // to the write the check saw. A writer among them is the
505                // checker checking its own content; a write without an
506                // identity leaves nothing to compare.
507                let seen = touches.writes_seen_by(&entity.id.0, check);
508                let reading = if seen.iter().any(|t| t.identity.as_deref() == Some(checker)) {
509                    Independence::SelfChecked
510                } else if seen.is_empty() || seen.iter().any(|t| t.identity.is_none()) {
511                    Independence::Unconfirmable
512                } else {
513                    Independence::ConfirmedIndependent
514                };
515                (reading, None)
516            }
517        }
518    }
519
520    /// The reading an archive mount's sealed member carries for `check`
521    /// (the record [`Self::latest_check_record`] served from it): the
522    /// sealed record under the same entity path and wire kind, at the
523    /// same timestamp and hash. `None` off an archive mount, for a record
524    /// the member does not hold, or for one sealed by a writer that
525    /// carried no reading.
526    pub fn sealed_independence_of(&self, mem: &str, check: &CheckRecord) -> Option<Independence> {
527        let sealed = self.archive_checks_for(mem)?;
528        let id = crate::EntityId(check.entity.clone());
529        let kind = crate::check::sealed_kind_of(check);
530        sealed
531            .latest(id.path(), &kind)
532            .filter(|sc| sc.ts == check.ts && sc.entity_hash == check.entity_hash)
533            .and_then(crate::check::SealedCheck::sealed_independence)
534    }
535
536    /// The export's reader of the independence reading to seal beside
537    /// each check record of `mem`: the same derivation
538    /// [`Self::independence_of`] serves live (the entity as loaded, the
539    /// ledger record, the mem's touches gathered once), so the archive
540    /// carries exactly what the source engine would have answered at
541    /// export time. `None` for a record whose entity the engine does
542    /// not hold (the export does not seal those either).
543    pub fn sealed_independence_reader(
544        &self,
545        mem: &str,
546    ) -> impl Fn(&CheckRecord) -> Option<Independence> + '_ {
547        let touches = self.mem_touches(mem);
548        move |rec: &CheckRecord| {
549            let entity = self.store.get(&crate::EntityId(rec.entity.clone()))?;
550            Some(self.independence_of(entity, rec, &touches).0)
551        }
552    }
553
554    /// Everything the export seals beside one ledger record, derived over
555    /// the live mem so the archive carries exactly what the source engine
556    /// would have answered at export time: the independence reading
557    /// ([`Self::sealed_independence_reader`]) and the trust class of the
558    /// row's own prose ([`Self::check_row_origin_class`]) — who wrote the
559    /// `method` note and the finding message, which in a workspace that
560    /// points a foreign model or a transcribed outside finding at its
561    /// ledger is not the workspace itself.
562    ///
563    /// The class is `None` for every record while the deployment declares
564    /// no owner identities, so an export stays byte-identical until it
565    /// does.
566    pub fn sealed_row_reader(
567        &self,
568        mem: &str,
569    ) -> impl Fn(&CheckRecord) -> crate::ops::export::SealedRowFacts + '_ {
570        let independence = self.sealed_independence_reader(mem);
571        let mem = mem.to_string();
572        move |rec: &CheckRecord| crate::ops::export::SealedRowFacts {
573            independence: independence(rec),
574            origin: self
575                .declares_owner_identities()
576                .then(|| self.check_row_origin_class(&mem, rec.identity.as_deref())),
577        }
578    }
579
580    /// The gate's window into the ledger: derived state plus, for an
581    /// ok-checked entity, the independence of that check — with each
582    /// mem's touches gathered once per provider.
583    pub(crate) fn check_standing_provider(
584        &self,
585    ) -> impl Fn(&crate::entity::Entity, &str) -> CheckStanding + '_ {
586        let touches: std::cell::RefCell<HashMap<String, MemTouches>> =
587            std::cell::RefCell::new(HashMap::new());
588        move |entity: &crate::entity::Entity, kind: &str| {
589            // One source per mount (the sealed member on an archive, the
590            // workspace ledger elsewhere), the same the entity read derives from.
591            let latest = self.latest_check_record(&entity.mem, &entity.id.0, kind);
592            // Pin-aware, as the entity read derives: a `conformance`
593            // record carries the schema pin it judged against and is
594            // fresh only under that pin; a record without one (every
595            // `verification` and `x-` record) ignores the argument.
596            // Hash-only derivation read every conformance record as
597            // `check_stale`, so a gate on that kind never closed.
598            let current_pin = self
599                .find_mount(&entity.mem)
600                .ok()
601                .and_then(|m| m.mount.schema.as_ref().map(|s| s.as_display()));
602            let state = crate::check::derive_state_pinned(
603                latest.as_ref(),
604                &entity.content_hash,
605                current_pin.as_deref(),
606            );
607            if state != CheckState::CheckedOk {
608                return CheckStanding {
609                    state,
610                    independence: None,
611                    role: crate::vcs::Role::Unspecified,
612                };
613            }
614            let check = latest.expect("checked_ok implies a record");
615            let mut cache = touches.borrow_mut();
616            let mem_touches = cache
617                .entry(entity.mem.clone())
618                .or_insert_with(|| self.mem_touches(&entity.mem));
619            let (independence, _) = self.independence_of(entity, &check, mem_touches);
620            CheckStanding {
621                state,
622                independence: Some(independence),
623                role: crate::vcs::Role::from_wire(&check.role).unwrap_or_default(),
624            }
625        }
626    }
627}
628
629#[cfg(test)]
630mod tests {
631    use super::MemTouches;
632
633    /// A git-branch rename note carries `old → new` in its entity field.
634    /// Absorbing it lands the touch under both ids, and following the
635    /// renames joins the old id's story to the new one — the creator
636    /// stays the oldest touch, the renamer does not become the author.
637    /// Before this, the field was split on an ASCII `->` the engine never
638    /// writes, so the renamed entity had no story at all and every check
639    /// on it read `unconfirmable`.
640    #[test]
641    fn rename_notes_join_the_story_under_the_new_id() {
642        let mut t = MemTouches::default();
643        let touch = |ts: i64, id: Option<&str>, seq: usize| super::Touch {
644            ts,
645            identity: id.map(str::to_string),
646            reference: format!("r{seq}"),
647            seq,
648        };
649        t.absorb("m--a", touch(10, Some("alice"), 1));
650        t.absorb("m--a → m--b", touch(20, Some("renamer"), 2));
651        t.absorb("m--b", touch(30, Some("bob"), 3));
652        t.absorb("m--b → m--c", touch(40, None, 4));
653        t.follow_renames();
654
655        assert_eq!(t.written_at("m--c"), Some(10));
656        assert_eq!(t.first_author("m--c"), Some("alice"));
657        let mut ids = std::collections::BTreeSet::new();
658        t.identities_since("m--c", 0, &mut ids);
659        assert_eq!(
660            ids.into_iter().collect::<Vec<_>>(),
661            vec!["alice", "bob", "renamer"]
662        );
663        // A cross-mem rewrite qualifier is not a pair and stays one key.
664        let mut u = MemTouches::default();
665        u.absorb("m--x → m--y (cross-mem rewrite in peer)", touch(1, None, 5));
666        u.follow_renames();
667        assert!(
668            u.by_entity
669                .contains_key("m--x → m--y (cross-mem rewrite in peer)")
670        );
671        assert!(!u.by_entity.contains_key("m--y"));
672    }
673}