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 mem's mutation touches by entity: `(timestamp, identity)` per
172/// touch, from the mem's provenance record (the git-branch note trailers,
173/// or the folder ledger). Built once per mem and shared by every
174/// derivation in one pass.
175#[derive(Debug, Default, Clone)]
176pub struct MemTouches {
177    by_entity: HashMap<String, Vec<(i64, Option<String>)>>,
178    /// Rename notes seen, as `(ts, old, new)`, for [`Self::follow_renames`].
179    renames: Vec<(i64, String, String)>,
180}
181
182impl MemTouches {
183    /// Record one note's touch. A rename note's entity field reads
184    /// `old → new` (the engine's own subject shape, the pair
185    /// [`super::history::parse_rename_pair`] splits); the touch lands
186    /// under both ids and the pair is kept so [`Self::follow_renames`]
187    /// can join the two halves of the story. Anything else is one id.
188    fn absorb(&mut self, entity_field: &str, ts: i64, identity: Option<String>) {
189        match super::history::parse_rename_pair(entity_field) {
190            Some((old, new)) => {
191                self.by_entity
192                    .entry(old.clone())
193                    .or_default()
194                    .push((ts, identity.clone()));
195                self.by_entity
196                    .entry(new.clone())
197                    .or_default()
198                    .push((ts, identity));
199                self.renames.push((ts, old, new));
200            }
201            None => self
202                .by_entity
203                .entry(entity_field.to_string())
204                .or_default()
205                .push((ts, identity)),
206        }
207    }
208
209    /// Join each renamed entity's story: the touches recorded under the
210    /// old id (its creation among them) become touches of the new id,
211    /// oldest rename first so a chain `a → b → c` carries `a`'s story
212    /// through `b` into `c`. Without this the renamed entity's oldest
213    /// touch is the rename itself and the renamer reads as its author.
214    fn follow_renames(&mut self) {
215        let mut renames = std::mem::take(&mut self.renames);
216        renames.sort_by_key(|r| r.0);
217        for (_, old, new) in &renames {
218            let inherited = self.by_entity.get(old).cloned().unwrap_or_default();
219            let target = self.by_entity.entry(new.clone()).or_default();
220            for touch in inherited {
221                if !target.contains(&touch) {
222                    target.push(touch);
223                }
224            }
225        }
226        self.renames = renames;
227    }
228
229    /// The oldest touch timestamp of `entity`, if any is recorded.
230    fn written_at(&self, entity: &str) -> Option<i64> {
231        self.by_entity
232            .get(entity)
233            .and_then(|t| t.iter().map(|(ts, _)| *ts).min())
234    }
235
236    /// Identities that touched `entity` at or after `since`.
237    fn identities_since(&self, entity: &str, since: i64, into: &mut BTreeSet<String>) {
238        if let Some(touches) = self.by_entity.get(entity) {
239            for (ts, id) in touches {
240                if *ts >= since
241                    && let Some(id) = id
242                {
243                    into.insert(id.clone());
244                }
245            }
246        }
247    }
248
249    /// Whether any touch of `entity` carries an identity.
250    fn any_identity(&self, entity: &str) -> bool {
251        self.by_entity
252            .get(entity)
253            .is_some_and(|t| t.iter().any(|(_, id)| id.is_some()))
254    }
255}
256
257/// The executors of one criterion: the identities the reading compares
258/// against, and the plans the set was drawn from.
259#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
260pub struct Executors {
261    pub identities: Vec<String>,
262    pub plans: Vec<String>,
263}
264
265impl Engine {
266    /// Gather one mem's touches from its provenance record. Git-branch
267    /// mems walk the branch's commit notes once; folder and in-memory
268    /// mems read their ledger; an archive records no history at the
269    /// engine seam and yields no touches ([`Self::independence_of`]
270    /// serves the reading the export sealed instead).
271    pub fn mem_touches(&self, mem: &str) -> MemTouches {
272        let mut out = MemTouches::default();
273        let Some(m) = self.mounts.iter().find(|m| m.mount.mem == mem) else {
274            return out;
275        };
276        match &m.mount.storage {
277            crate::workspace::MountStorage::GitBranch { gitdir, branch } => {
278                if let Some(hook) = self.git_branch_ops.as_ref()
279                    && let Ok(changes) = (hook.changes_since)(
280                        gitdir,
281                        branch,
282                        mem,
283                        crate::ops::EMPTY_TREE_SHA,
284                        crate::ops::RENAME_SIMILARITY_DEFAULT,
285                    )
286                {
287                    for n in &changes.notes {
288                        if let Some(entity) = n.entity_id.as_deref() {
289                            out.absorb(entity, n.timestamp, n.identity.clone());
290                        }
291                        // A multi-entity commit (a batch, a proposal merge)
292                        // names its entities in the `Entities:` trailer and
293                        // a count in its subject; the identity touches
294                        // every one of them.
295                        for entity in &n.entity_ids {
296                            out.absorb(entity, n.timestamp, n.identity.clone());
297                        }
298                    }
299                    out.follow_renames();
300                }
301            }
302            crate::workspace::MountStorage::Folder { .. }
303            | crate::workspace::MountStorage::InMemory => {
304                if let Ok(records) = m.backend.read_provenance(None) {
305                    for r in records {
306                        let Some(entity) = r.entity.as_deref() else {
307                            continue;
308                        };
309                        let ts = r
310                            .timestamp
311                            .duration_since(std::time::UNIX_EPOCH)
312                            .map(|d| d.as_secs() as i64)
313                            .unwrap_or(0);
314                        out.by_entity
315                            .entry(entity.to_string())
316                            .or_default()
317                            .push((ts, r.identity.clone()));
318                    }
319                }
320            }
321            crate::workspace::MountStorage::Archive { .. } => {}
322        }
323        out
324    }
325
326    /// The executors of `entity` (a criterion): every identity that
327    /// mutated the plan(s) it VERIFIES, those plans' other criteria, or the
328    /// notes PART_OF those plans, at or after the criterion's first touch.
329    /// `None` when the entity verifies no plan — the reading then falls
330    /// back to the entity's own author.
331    pub fn executors_of(
332        &self,
333        entity: &crate::entity::Entity,
334        touches: &MemTouches,
335    ) -> Option<Executors> {
336        let plans: Vec<crate::entity::EntityId> = entity
337            .relationships
338            .iter()
339            .filter(|r| r.rel_type == "VERIFIES")
340            .map(|r| r.target.clone())
341            .collect();
342        if plans.is_empty() {
343            return None;
344        }
345        let since = touches.written_at(&entity.id.0).unwrap_or(0);
346        let mut set: BTreeSet<String> = BTreeSet::new();
347        let mut members: BTreeSet<String> = BTreeSet::new();
348        for plan in &plans {
349            members.insert(plan.0.clone());
350            for other in self.store.all_entities().filter(|o| o.mem == entity.mem) {
351                if other.relationships.iter().any(|r| {
352                    &r.target == plan && (r.rel_type == "VERIFIES" || r.rel_type == "PART_OF")
353                }) {
354                    members.insert(other.id.0.clone());
355                }
356            }
357        }
358        for member in &members {
359            touches.identities_since(member, since, &mut set);
360        }
361        Some(Executors {
362            identities: set.into_iter().collect(),
363            plans: plans.into_iter().map(|p| p.0).collect(),
364        })
365    }
366
367    /// The independence reading of one ok check on `entity`. On an
368    /// archive mount the reading is the one the export sealed beside the
369    /// record ([`Self::sealed_independence_of`]): the mount has no
370    /// touches to derive from, and a member sealed without the reading
371    /// stays `unconfirmable`.
372    pub fn independence_of(
373        &self,
374        entity: &crate::entity::Entity,
375        check: &CheckRecord,
376        touches: &MemTouches,
377    ) -> (Independence, Option<Executors>) {
378        if self.is_archive_mount(&entity.mem) {
379            return (
380                self.sealed_independence_of(&entity.mem, check)
381                    .unwrap_or(Independence::Unconfirmable),
382                None,
383            );
384        }
385        let Some(checker) = check.identity.as_deref() else {
386            return (Independence::Unconfirmable, None);
387        };
388        match self.executors_of(entity, touches) {
389            Some(executors) => {
390                let reading = if executors.identities.iter().any(|i| i == checker) {
391                    Independence::SelfChecked
392                } else if executors.identities.is_empty()
393                    && !executors.plans.iter().any(|p| touches.any_identity(p))
394                    && !touches.any_identity(&entity.id.0)
395                {
396                    // Nothing in the plan's set carries an identity: no
397                    // comparator exists, the reading cannot be promoted.
398                    Independence::Unconfirmable
399                } else {
400                    Independence::ConfirmedIndependent
401                };
402                (reading, Some(executors))
403            }
404            None => {
405                // Not a criterion: today's rule, the entity's own author.
406                // The author is the oldest touch; touches are absorbed
407                // newest-first, so among touches in one second the last
408                // absorbed is the one committed first.
409                let author = touches
410                    .by_entity
411                    .get(&entity.id.0)
412                    .and_then(|t| t.iter().rev().min_by_key(|(ts, _)| *ts))
413                    .and_then(|(_, id)| id.clone());
414                let reading = match author {
415                    Some(a) if a == checker => Independence::SelfChecked,
416                    Some(_) => Independence::ConfirmedIndependent,
417                    None => Independence::Unconfirmable,
418                };
419                (reading, None)
420            }
421        }
422    }
423
424    /// The reading an archive mount's sealed member carries for `check`
425    /// (the record [`Self::latest_check_record`] served from it): the
426    /// sealed record under the same entity path and wire kind, at the
427    /// same timestamp and hash. `None` off an archive mount, for a record
428    /// the member does not hold, or for one sealed by a writer that
429    /// carried no reading.
430    pub fn sealed_independence_of(&self, mem: &str, check: &CheckRecord) -> Option<Independence> {
431        let sealed = self.archive_checks_for(mem)?;
432        let id = crate::EntityId(check.entity.clone());
433        let kind = crate::check::sealed_kind_of(check);
434        sealed
435            .latest(id.path(), &kind)
436            .filter(|sc| sc.ts == check.ts && sc.entity_hash == check.entity_hash)
437            .and_then(crate::check::SealedCheck::sealed_independence)
438    }
439
440    /// The export's reader of the independence reading to seal beside
441    /// each check record of `mem`: the same derivation
442    /// [`Self::independence_of`] serves live (the entity as loaded, the
443    /// ledger record, the mem's touches gathered once), so the archive
444    /// carries exactly what the source engine would have answered at
445    /// export time. `None` for a record whose entity the engine does
446    /// not hold (the export does not seal those either).
447    pub fn sealed_independence_reader(
448        &self,
449        mem: &str,
450    ) -> impl Fn(&CheckRecord) -> Option<Independence> + '_ {
451        let touches = self.mem_touches(mem);
452        move |rec: &CheckRecord| {
453            let entity = self.store.get(&crate::EntityId(rec.entity.clone()))?;
454            Some(self.independence_of(entity, rec, &touches).0)
455        }
456    }
457
458    /// Everything the export seals beside one ledger record, derived over
459    /// the live mem so the archive carries exactly what the source engine
460    /// would have answered at export time: the independence reading
461    /// ([`Self::sealed_independence_reader`]) and the trust class of the
462    /// row's own prose ([`Self::check_row_origin_class`]) — who wrote the
463    /// `method` note and the finding message, which in a workspace that
464    /// points a foreign model or a transcribed outside finding at its
465    /// ledger is not the workspace itself.
466    ///
467    /// The class is `None` for every record while the deployment declares
468    /// no owner identities, so an export stays byte-identical until it
469    /// does.
470    pub fn sealed_row_reader(
471        &self,
472        mem: &str,
473    ) -> impl Fn(&CheckRecord) -> crate::ops::export::SealedRowFacts + '_ {
474        let independence = self.sealed_independence_reader(mem);
475        let mem = mem.to_string();
476        move |rec: &CheckRecord| crate::ops::export::SealedRowFacts {
477            independence: independence(rec),
478            origin: self
479                .declares_owner_identities()
480                .then(|| self.check_row_origin_class(&mem, rec.identity.as_deref())),
481        }
482    }
483
484    /// The gate's window into the ledger: derived state plus, for an
485    /// ok-checked entity, the independence of that check — with each
486    /// mem's touches gathered once per provider.
487    pub(crate) fn check_standing_provider(
488        &self,
489    ) -> impl Fn(&crate::entity::Entity, &str) -> CheckStanding + '_ {
490        let touches: std::cell::RefCell<HashMap<String, MemTouches>> =
491            std::cell::RefCell::new(HashMap::new());
492        move |entity: &crate::entity::Entity, kind: &str| {
493            // One source per mount (the sealed member on an archive, the
494            // workspace ledger elsewhere), the same the entity read derives from.
495            let latest = self.latest_check_record(&entity.mem, &entity.id.0, kind);
496            // Pin-aware, as the entity read derives: a `conformance`
497            // record carries the schema pin it judged against and is
498            // fresh only under that pin; a record without one (every
499            // `verification` and `x-` record) ignores the argument.
500            // Hash-only derivation read every conformance record as
501            // `check_stale`, so a gate on that kind never closed.
502            let current_pin = self
503                .find_mount(&entity.mem)
504                .ok()
505                .and_then(|m| m.mount.schema.as_ref().map(|s| s.as_display()));
506            let state = crate::check::derive_state_pinned(
507                latest.as_ref(),
508                &entity.content_hash,
509                current_pin.as_deref(),
510            );
511            if state != CheckState::CheckedOk {
512                return CheckStanding {
513                    state,
514                    independence: None,
515                    role: crate::vcs::Role::Unspecified,
516                };
517            }
518            let check = latest.expect("checked_ok implies a record");
519            let mut cache = touches.borrow_mut();
520            let mem_touches = cache
521                .entry(entity.mem.clone())
522                .or_insert_with(|| self.mem_touches(&entity.mem));
523            let (independence, _) = self.independence_of(entity, &check, mem_touches);
524            CheckStanding {
525                state,
526                independence: Some(independence),
527                role: crate::vcs::Role::from_wire(&check.role).unwrap_or_default(),
528            }
529        }
530    }
531}
532
533#[cfg(test)]
534mod tests {
535    use super::MemTouches;
536
537    /// A git-branch rename note carries `old → new` in its entity field.
538    /// Absorbing it lands the touch under both ids, and following the
539    /// renames joins the old id's story to the new one — the creator
540    /// stays the oldest touch, the renamer does not become the author.
541    /// Before this, the field was split on an ASCII `->` the engine never
542    /// writes, so the renamed entity had no story at all and every check
543    /// on it read `unconfirmable`.
544    #[test]
545    fn rename_notes_join_the_story_under_the_new_id() {
546        let mut t = MemTouches::default();
547        t.absorb("m--a", 10, Some("alice".into()));
548        t.absorb("m--a → m--b", 20, Some("renamer".into()));
549        t.absorb("m--b", 30, Some("bob".into()));
550        t.absorb("m--b → m--c", 40, None);
551        t.follow_renames();
552
553        assert_eq!(t.written_at("m--c"), Some(10));
554        let author = t
555            .by_entity
556            .get("m--c")
557            .and_then(|v| v.iter().min_by_key(|(ts, _)| *ts))
558            .and_then(|(_, id)| id.clone());
559        assert_eq!(author.as_deref(), Some("alice"));
560        let mut ids = std::collections::BTreeSet::new();
561        t.identities_since("m--c", 0, &mut ids);
562        assert_eq!(
563            ids.into_iter().collect::<Vec<_>>(),
564            vec!["alice", "bob", "renamer"]
565        );
566        // A cross-mem rewrite qualifier is not a pair and stays one key.
567        let mut u = MemTouches::default();
568        u.absorb("m--x → m--y (cross-mem rewrite in peer)", 1, None);
569        u.follow_renames();
570        assert!(
571            u.by_entity
572                .contains_key("m--x → m--y (cross-mem rewrite in peer)")
573        );
574        assert!(!u.by_entity.contains_key("m--y"));
575    }
576}