memstead-base 0.27.1

Engine internals for Memstead — store, parser, validators, mem lifecycle, workspace policy. Published as a dependency of the memstead-cli and memstead-mcp products, not as a supported library — pre-1.0, no API stability promise.
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
//! The author≠checker independence reading, derived from provenance.
//!
//! A check record confirms an acceptance criterion only when the party
//! that did the work did not record it. Until 2026-09-02 the reading
//! compared a check's identity with the identity that CREATED the
//! criterion entity — and the planning session authors criteria while the
//! executing session checks them, so the executor's own checks read
//! `confirmed_independent` (found twice by the evidence-engine bundle,
//! once on a wrong check). The comparator now (decision basket line 9,
//! option a): a check on a criterion reads `confirmed_independent` only
//! when its identity differs from **every identity that mutated the
//! verified plan, its criteria, or its session-log notes since the
//! criterion was written**; a check under one of those identities reads
//! `self_checked`; a check or a record without an identity stays
//! `unconfirmable`. Identities are the only comparator; roles and the
//! transport pair are recorded context. Nothing is stamped: the reading
//! is computed at read time from the append-only provenance record, so
//! every existing ledger keeps parsing and derives under the new rule.
//!
//! The `transition_requires_checks` gate consumes the same reading: a
//! plan cannot complete on the executor's own checks. The gate adds one
//! orthogonal condition the reading never carries (2026-09-27): the
//! confirming record must be declared in a checking capacity, role
//! `checker` or `verifier`. A record in role `author` is the caller
//! saying they act as the author, and a record with no role is
//! cannot-confirm (the 2026-08-09 role decision); neither closes a
//! gate, and each is reported under its own label
//! ([`LABEL_ROLE_AUTHOR`], [`LABEL_ROLE_UNSPECIFIED`]) beside the
//! readings, which stay a closed vocabulary.
//!
//! An archive mount records no history at the engine seam, so nothing
//! on the mount can derive the reading; the export derives it once per
//! sealed record from the source mem's provenance and seals it beside
//! the record (`independence` on [`crate::check::SealedCheck`]), and the
//! mount serves the sealed reading. The archive is immutable, so the
//! reading at export time is the reading, not a stamp that could go
//! stale. A member sealed by an older writer carries none and reads
//! `unconfirmable`, as before.

use std::collections::{BTreeSet, HashMap};

use serde::Serialize;

use super::Engine;
use crate::check::{CheckRecord, CheckState};

/// The independence half of a check's standing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Independence {
    /// The check's identity mutated nothing in the verified plan's set
    /// since the criterion was written.
    ConfirmedIndependent,
    /// The check's identity is one of the executors.
    SelfChecked,
    /// The check, or every relevant provenance record, carries no
    /// identity — absence is never promoted.
    Unconfirmable,
}

impl Independence {
    /// Every reading, in wire order.
    pub const ALL: [Self; 3] = [
        Self::ConfirmedIndependent,
        Self::SelfChecked,
        Self::Unconfirmable,
    ];

    pub fn as_str(self) -> &'static str {
        match self {
            Self::ConfirmedIndependent => "confirmed_independent",
            Self::SelfChecked => "self_checked",
            Self::Unconfirmable => "unconfirmable",
        }
    }

    /// Parse the wire form (the string [`Self::as_str`] renders, as the
    /// sealed member carries it). Closed: anything else is `None`.
    pub fn from_wire(s: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|r| r.as_str() == s)
    }

    /// The vocabulary, for an error message.
    pub fn vocabulary_hint() -> String {
        Self::ALL
            .iter()
            .map(|r| r.as_str())
            .collect::<Vec<_>>()
            .join(", ")
    }
}

/// The gate's label for a confirming record declared in the author's
/// role: the caller said they acted as the author, and an author's
/// record does not close a gate on someone else's check.
pub const LABEL_ROLE_AUTHOR: &str = "role_author";
/// The gate's label for a confirming record that declares no role:
/// absence is cannot-confirm, never a guessed capacity.
pub const LABEL_ROLE_UNSPECIFIED: &str = "role_unspecified";

/// One entity's standing before the gate: its derived check state, for
/// an ok-checked entity the independence of that check, and the role
/// the record was declared in.
///
/// Three orthogonal conditions close a gate, and each is reported on
/// its own: the state is `checked_ok` (fresh against the entity's
/// bytes), the reading is `confirmed_independent` (the identity is none
/// of the executors), and the role is a checking capacity, `checker` or
/// `verifier`. A record in role `author` reads [`LABEL_ROLE_AUTHOR`],
/// one with no role [`LABEL_ROLE_UNSPECIFIED`]; neither confirms. The
/// role never enters the independence reading, which compares
/// identities and nothing else.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CheckStanding {
    pub state: CheckState,
    /// `Some` only for `CheckedOk`.
    pub independence: Option<Independence>,
    /// The role the newest record was declared in; `Unspecified` when
    /// it carries none, and for every state but `CheckedOk`.
    pub role: crate::vcs::Role,
}

impl CheckStanding {
    /// A standing that confirms when the state is `checked_ok` — the
    /// form store-only callers (and tests) build when no provenance is
    /// in play: independent, and declared in the checker's role.
    pub fn assumed_independent(state: CheckState) -> Self {
        Self {
            state,
            independence: (state == CheckState::CheckedOk)
                .then_some(Independence::ConfirmedIndependent),
            role: crate::vcs::Role::Checker,
        }
    }

    /// Whether the declared role is a checking capacity.
    pub fn role_confirms(&self) -> bool {
        matches!(
            self.role,
            crate::vcs::Role::Checker | crate::vcs::Role::Verifier
        )
    }

    /// Whether this standing satisfies the transition gate.
    pub fn confirms(&self) -> bool {
        self.state == CheckState::CheckedOk
            && self.independence == Some(Independence::ConfirmedIndependent)
            && self.role_confirms()
    }

    /// The label the gate reports for an entity that does not confirm:
    /// the check state; the independence reading when the state is
    /// `checked_ok` but not independent; the role label when the record
    /// is independent but not declared in a checking capacity.
    pub fn label(&self) -> &'static str {
        match (self.state, self.independence) {
            (CheckState::CheckedOk, Some(Independence::ConfirmedIndependent)) => match self.role {
                crate::vcs::Role::Checker | crate::vcs::Role::Verifier => {
                    Independence::ConfirmedIndependent.as_str()
                }
                crate::vcs::Role::Author => LABEL_ROLE_AUTHOR,
                crate::vcs::Role::Unspecified => LABEL_ROLE_UNSPECIFIED,
            },
            (CheckState::CheckedOk, Some(i)) => i.as_str(),
            (CheckState::CheckedOk, None) => Independence::Unconfirmable.as_str(),
            (s, _) => s.as_str(),
        }
    }
}

/// One recorded write of an entity: when, by whom, the backend-native
/// reference of the write (a commit sha on a git-branch mem, the ledger
/// line's timestamp token on a folder mem), and its place in the mem's
/// write order (`seq`, oldest first), which orders writes inside one
/// second without a clock.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Touch {
    pub ts: i64,
    pub identity: Option<String>,
    pub reference: String,
    pub seq: usize,
}

/// One mem's mutation touches by entity, from the mem's provenance record
/// (the git-branch note trailers, or the folder ledger). Built once per
/// mem and shared by every derivation in one pass.
#[derive(Debug, Default, Clone)]
pub struct MemTouches {
    by_entity: HashMap<String, Vec<Touch>>,
    /// Rename notes seen, as `(seq, old, new)`, for [`Self::follow_renames`].
    renames: Vec<(usize, String, String)>,
}

impl MemTouches {
    /// Record one note's touch. A rename note's entity field reads
    /// `old → new` (the engine's own subject shape, the pair
    /// [`super::history::parse_rename_pair`] splits); the touch lands
    /// under both ids and the pair is kept so [`Self::follow_renames`]
    /// can join the two halves of the story. Anything else is one id.
    fn absorb(&mut self, entity_field: &str, touch: Touch) {
        match super::history::parse_rename_pair(entity_field) {
            Some((old, new)) => {
                self.by_entity
                    .entry(old.clone())
                    .or_default()
                    .push(touch.clone());
                let seq = touch.seq;
                self.by_entity.entry(new.clone()).or_default().push(touch);
                self.renames.push((seq, old, new));
            }
            None => self
                .by_entity
                .entry(entity_field.to_string())
                .or_default()
                .push(touch),
        }
    }

    /// Join each renamed entity's story: the touches recorded under the
    /// old id (its creation among them) become touches of the new id,
    /// oldest rename first so a chain `a → b → c` carries `a`'s story
    /// through `b` into `c`, and every story is left in write order.
    /// Without this the renamed entity's oldest touch is the rename itself
    /// and the renamer reads as its author.
    fn follow_renames(&mut self) {
        let mut renames = std::mem::take(&mut self.renames);
        renames.sort_by_key(|r| r.0);
        for (_, old, new) in &renames {
            let inherited = self.by_entity.get(old).cloned().unwrap_or_default();
            let target = self.by_entity.entry(new.clone()).or_default();
            for touch in inherited {
                if !target.contains(&touch) {
                    target.push(touch);
                }
            }
        }
        for touches in self.by_entity.values_mut() {
            touches.sort_by_key(|t| t.seq);
        }
        self.renames = renames;
    }

    /// The touches of `entity` in write order, oldest first.
    pub fn story(&self, entity: &str) -> &[Touch] {
        self.by_entity.get(entity).map(Vec::as_slice).unwrap_or(&[])
    }

    /// The identity of the write that created `entity`: the first touch in
    /// write order, whatever order the backend fed them in.
    pub fn first_author(&self, entity: &str) -> Option<&str> {
        self.story(entity)
            .first()
            .and_then(|t| t.identity.as_deref())
    }

    /// The reference of `entity`'s last write, the one a check recorded
    /// now sees.
    pub fn last_write(&self, entity: &str) -> Option<&str> {
        self.story(entity).last().map(|t| t.reference.as_str())
    }

    /// The oldest touch timestamp of `entity`, if any is recorded.
    fn written_at(&self, entity: &str) -> Option<i64> {
        self.by_entity
            .get(entity)
            .and_then(|t| t.iter().map(|t| t.ts).min())
    }

    /// Identities that touched `entity` at or after `since`.
    fn identities_since(&self, entity: &str, since: i64, into: &mut BTreeSet<String>) {
        if let Some(touches) = self.by_entity.get(entity) {
            for t in touches {
                if t.ts >= since
                    && let Some(id) = &t.identity
                {
                    into.insert(id.clone());
                }
            }
        }
    }

    /// Whether any touch of `entity` carries an identity.
    fn any_identity(&self, entity: &str) -> bool {
        self.by_entity
            .get(entity)
            .is_some_and(|t| t.iter().any(|t| t.identity.is_some()))
    }

    /// The writes a check saw: every touch of `entity` up to and including
    /// the write the record names ([`CheckRecord::checked_write`]), in
    /// write order. A record without the field (every line an earlier
    /// engine wrote), or one naming a write the story does not hold, is
    /// read against every touch at or before its `ts`.
    pub fn writes_seen_by(&self, entity: &str, check: &CheckRecord) -> Vec<&Touch> {
        let story = self.story(entity);
        if let Some(r) = check.checked_write.as_deref()
            && let Some(at) = story.iter().rposition(|t| t.reference == r)
        {
            return story[..=at].iter().collect();
        }
        story.iter().filter(|t| t.ts <= check.ts as i64).collect()
    }
}

/// The executors of one criterion: the identities the reading compares
/// against, and the plans the set was drawn from.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct Executors {
    pub identities: Vec<String>,
    pub plans: Vec<String>,
}

impl Engine {
    /// Gather one mem's touches from its provenance record. Git-branch
    /// mems walk the branch's commit notes once; folder and in-memory
    /// mems read their ledger; an archive records no history at the
    /// engine seam and yields no touches ([`Self::independence_of`]
    /// serves the reading the export sealed instead).
    pub fn mem_touches(&self, mem: &str) -> MemTouches {
        let mut out = MemTouches::default();
        let Some(m) = self.mounts.iter().find(|m| m.mount.mem == mem) else {
            return out;
        };
        match &m.mount.storage {
            crate::workspace::MountStorage::GitBranch { gitdir, branch } => {
                if let Some(hook) = self.git_branch_ops.as_ref()
                    && let Ok(changes) = (hook.changes_since)(
                        gitdir,
                        branch,
                        mem,
                        crate::ops::EMPTY_TREE_SHA,
                        crate::ops::RENAME_SIMILARITY_DEFAULT,
                    )
                {
                    // The notes arrive newest first: the write order is
                    // their reverse.
                    let count = changes.notes.len();
                    for (i, n) in changes.notes.iter().enumerate() {
                        let touch = Touch {
                            ts: n.timestamp,
                            identity: n.identity.clone(),
                            reference: n.sha.clone(),
                            seq: count - i,
                        };
                        if let Some(entity) = n.entity_id.as_deref() {
                            out.absorb(entity, touch.clone());
                        }
                        // A multi-entity commit (a batch, a proposal merge)
                        // names its entities in the `Entities:` trailer and
                        // a count in its subject; the identity touches
                        // every one of them.
                        for entity in &n.entity_ids {
                            out.absorb(entity, touch.clone());
                        }
                        // A proposal merge names every fork identity that
                        // wrote a landed entity beside its proposer.
                        for (entity, identity) in &n.co_writers {
                            out.absorb(
                                entity,
                                Touch {
                                    identity: Some(identity.clone()),
                                    ..touch.clone()
                                },
                            );
                        }
                        // A merge that landed a fork rename joins the new
                        // id's story to the old id's, as a rename does.
                        for pair in &n.merge_renames {
                            out.absorb(pair, touch.clone());
                        }
                        for entity in &n.unattributed_writes {
                            out.absorb(
                                entity,
                                Touch {
                                    identity: None,
                                    ..touch.clone()
                                },
                            );
                        }
                    }
                    out.follow_renames();
                }
            }
            crate::workspace::MountStorage::Folder { .. }
            | crate::workspace::MountStorage::InMemory => {
                // The ledger is append-only: its line order is the write
                // order.
                if let Ok(records) = m.backend.read_provenance(None) {
                    for (seq, r) in records.into_iter().enumerate() {
                        let Some(entity) = r.entity.as_deref() else {
                            continue;
                        };
                        let ts = r
                            .timestamp
                            .duration_since(std::time::UNIX_EPOCH)
                            .map(|d| d.as_secs() as i64)
                            .unwrap_or(0);
                        // The line's timestamp token plus its ledger position:
                        // two writes in one millisecond stay two references.
                        let touch = Touch {
                            ts,
                            identity: r.identity.clone(),
                            reference: format!(
                                "{}#{seq}",
                                crate::filesystem::changelog::format_rfc3339_utc(r.timestamp)
                            ),
                            seq,
                        };
                        // A rename line names the new id and the old one; the
                        // story is joined as the git-branch notes join it.
                        match r.renamed_from.as_deref() {
                            Some(old) => out.absorb(&format!("{old} → {entity}"), touch),
                            None => out.absorb(entity, touch),
                        }
                    }
                    out.follow_renames();
                }
            }
            crate::workspace::MountStorage::Archive { .. } => {}
        }
        out
    }

    /// The executors of `entity` (a criterion): every identity that
    /// mutated the plan(s) it VERIFIES, those plans' other criteria, or the
    /// notes PART_OF those plans, at or after the criterion's first touch.
    /// `None` when the entity verifies no plan — the reading then compares
    /// every identity that wrote the entity up to the write the check saw.
    pub fn executors_of(
        &self,
        entity: &crate::entity::Entity,
        touches: &MemTouches,
    ) -> Option<Executors> {
        let plans: Vec<crate::entity::EntityId> = entity
            .relationships
            .iter()
            .filter(|r| r.rel_type == "VERIFIES")
            .map(|r| r.target.clone())
            .collect();
        if plans.is_empty() {
            return None;
        }
        let since = touches.written_at(&entity.id.0).unwrap_or(0);
        let mut set: BTreeSet<String> = BTreeSet::new();
        let mut members: BTreeSet<String> = BTreeSet::new();
        for plan in &plans {
            members.insert(plan.0.clone());
            for other in self.store.all_entities().filter(|o| o.mem == entity.mem) {
                if other.relationships.iter().any(|r| {
                    &r.target == plan && (r.rel_type == "VERIFIES" || r.rel_type == "PART_OF")
                }) {
                    members.insert(other.id.0.clone());
                }
            }
        }
        for member in &members {
            touches.identities_since(member, since, &mut set);
        }
        Some(Executors {
            identities: set.into_iter().collect(),
            plans: plans.into_iter().map(|p| p.0).collect(),
        })
    }

    /// The independence reading of one ok check on `entity`. On an
    /// archive mount the reading is the one the export sealed beside the
    /// record ([`Self::sealed_independence_of`]): the mount has no
    /// touches to derive from, and a member sealed without the reading
    /// stays `unconfirmable`.
    pub fn independence_of(
        &self,
        entity: &crate::entity::Entity,
        check: &CheckRecord,
        touches: &MemTouches,
    ) -> (Independence, Option<Executors>) {
        if self.is_archive_mount(&entity.mem) {
            return (
                self.sealed_independence_of(&entity.mem, check)
                    .unwrap_or(Independence::Unconfirmable),
                None,
            );
        }
        let Some(checker) = check.identity.as_deref() else {
            return (Independence::Unconfirmable, None);
        };
        match self.executors_of(entity, touches) {
            Some(executors) => {
                let reading = if executors.identities.iter().any(|i| i == checker) {
                    Independence::SelfChecked
                } else if executors.identities.is_empty()
                    && !executors.plans.iter().any(|p| touches.any_identity(p))
                    && !touches.any_identity(&entity.id.0)
                {
                    // Nothing in the plan's set carries an identity: no
                    // comparator exists, the reading cannot be promoted.
                    Independence::Unconfirmable
                } else {
                    Independence::ConfirmedIndependent
                };
                (reading, Some(executors))
            }
            None => {
                // Not a criterion: every identity that wrote the entity up
                // to the write the check saw. A writer among them is the
                // checker checking its own content; a write without an
                // identity leaves nothing to compare.
                let seen = touches.writes_seen_by(&entity.id.0, check);
                let reading = if seen.iter().any(|t| t.identity.as_deref() == Some(checker)) {
                    Independence::SelfChecked
                } else if seen.is_empty() || seen.iter().any(|t| t.identity.is_none()) {
                    Independence::Unconfirmable
                } else {
                    Independence::ConfirmedIndependent
                };
                (reading, None)
            }
        }
    }

    /// The reading an archive mount's sealed member carries for `check`
    /// (the record [`Self::latest_check_record`] served from it): the
    /// sealed record under the same entity path and wire kind, at the
    /// same timestamp and hash. `None` off an archive mount, for a record
    /// the member does not hold, or for one sealed by a writer that
    /// carried no reading.
    pub fn sealed_independence_of(&self, mem: &str, check: &CheckRecord) -> Option<Independence> {
        let sealed = self.archive_checks_for(mem)?;
        let id = crate::EntityId(check.entity.clone());
        let kind = crate::check::sealed_kind_of(check);
        sealed
            .latest(id.path(), &kind)
            .filter(|sc| sc.ts == check.ts && sc.entity_hash == check.entity_hash)
            .and_then(crate::check::SealedCheck::sealed_independence)
    }

    /// The export's reader of the independence reading to seal beside
    /// each check record of `mem`: the same derivation
    /// [`Self::independence_of`] serves live (the entity as loaded, the
    /// ledger record, the mem's touches gathered once), so the archive
    /// carries exactly what the source engine would have answered at
    /// export time. `None` for a record whose entity the engine does
    /// not hold (the export does not seal those either).
    pub fn sealed_independence_reader(
        &self,
        mem: &str,
    ) -> impl Fn(&CheckRecord) -> Option<Independence> + '_ {
        let touches = self.mem_touches(mem);
        move |rec: &CheckRecord| {
            let entity = self.store.get(&crate::EntityId(rec.entity.clone()))?;
            Some(self.independence_of(entity, rec, &touches).0)
        }
    }

    /// Everything the export seals beside one ledger record, derived over
    /// the live mem so the archive carries exactly what the source engine
    /// would have answered at export time: the independence reading
    /// ([`Self::sealed_independence_reader`]) and the trust class of the
    /// row's own prose ([`Self::check_row_origin_class`]) — who wrote the
    /// `method` note and the finding message, which in a workspace that
    /// points a foreign model or a transcribed outside finding at its
    /// ledger is not the workspace itself.
    ///
    /// The class is `None` for every record while the deployment declares
    /// no owner identities, so an export stays byte-identical until it
    /// does.
    pub fn sealed_row_reader(
        &self,
        mem: &str,
    ) -> impl Fn(&CheckRecord) -> crate::ops::export::SealedRowFacts + '_ {
        let independence = self.sealed_independence_reader(mem);
        let mem = mem.to_string();
        move |rec: &CheckRecord| crate::ops::export::SealedRowFacts {
            independence: independence(rec),
            origin: self
                .declares_owner_identities()
                .then(|| self.check_row_origin_class(&mem, rec.identity.as_deref())),
        }
    }

    /// The gate's window into the ledger: derived state plus, for an
    /// ok-checked entity, the independence of that check — with each
    /// mem's touches gathered once per provider.
    pub(crate) fn check_standing_provider(
        &self,
    ) -> impl Fn(&crate::entity::Entity, &str) -> CheckStanding + '_ {
        let touches: std::cell::RefCell<HashMap<String, MemTouches>> =
            std::cell::RefCell::new(HashMap::new());
        move |entity: &crate::entity::Entity, kind: &str| {
            // One source per mount (the sealed member on an archive, the
            // workspace ledger elsewhere), the same the entity read derives from.
            let latest = self.latest_check_record(&entity.mem, &entity.id.0, kind);
            // Pin-aware, as the entity read derives: a `conformance`
            // record carries the schema pin it judged against and is
            // fresh only under that pin; a record without one (every
            // `verification` and `x-` record) ignores the argument.
            // Hash-only derivation read every conformance record as
            // `check_stale`, so a gate on that kind never closed.
            let current_pin = self
                .find_mount(&entity.mem)
                .ok()
                .and_then(|m| m.mount.schema.as_ref().map(|s| s.as_display()));
            let state = crate::check::derive_state_pinned(
                latest.as_ref(),
                &entity.content_hash,
                current_pin.as_deref(),
            );
            if state != CheckState::CheckedOk {
                return CheckStanding {
                    state,
                    independence: None,
                    role: crate::vcs::Role::Unspecified,
                };
            }
            let check = latest.expect("checked_ok implies a record");
            let mut cache = touches.borrow_mut();
            let mem_touches = cache
                .entry(entity.mem.clone())
                .or_insert_with(|| self.mem_touches(&entity.mem));
            let (independence, _) = self.independence_of(entity, &check, mem_touches);
            CheckStanding {
                state,
                independence: Some(independence),
                role: crate::vcs::Role::from_wire(&check.role).unwrap_or_default(),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::MemTouches;

    /// A git-branch rename note carries `old → new` in its entity field.
    /// Absorbing it lands the touch under both ids, and following the
    /// renames joins the old id's story to the new one — the creator
    /// stays the oldest touch, the renamer does not become the author.
    /// Before this, the field was split on an ASCII `->` the engine never
    /// writes, so the renamed entity had no story at all and every check
    /// on it read `unconfirmable`.
    #[test]
    fn rename_notes_join_the_story_under_the_new_id() {
        let mut t = MemTouches::default();
        let touch = |ts: i64, id: Option<&str>, seq: usize| super::Touch {
            ts,
            identity: id.map(str::to_string),
            reference: format!("r{seq}"),
            seq,
        };
        t.absorb("m--a", touch(10, Some("alice"), 1));
        t.absorb("m--a → m--b", touch(20, Some("renamer"), 2));
        t.absorb("m--b", touch(30, Some("bob"), 3));
        t.absorb("m--b → m--c", touch(40, None, 4));
        t.follow_renames();

        assert_eq!(t.written_at("m--c"), Some(10));
        assert_eq!(t.first_author("m--c"), Some("alice"));
        let mut ids = std::collections::BTreeSet::new();
        t.identities_since("m--c", 0, &mut ids);
        assert_eq!(
            ids.into_iter().collect::<Vec<_>>(),
            vec!["alice", "bob", "renamer"]
        );
        // A cross-mem rewrite qualifier is not a pair and stays one key.
        let mut u = MemTouches::default();
        u.absorb("m--x → m--y (cross-mem rewrite in peer)", touch(1, None, 5));
        u.follow_renames();
        assert!(
            u.by_entity
                .contains_key("m--x → m--y (cross-mem rewrite in peer)")
        );
        assert!(!u.by_entity.contains_key("m--y"));
    }
}