Skip to main content

memstead_base/engine/
check_ops.rs

1//! The check operation and derived check state.
2//!
3//! `record_check` is the engine-recorded act of verification: it
4//! appends one [`crate::check::CheckRecord`] — verdict, method note,
5//! the entity's `content_hash` at check time, and plan-13 provenance
6//! (actor, client, declared role) — to the workspace check ledger.
7//! Checking mutates nothing: no entity write, no mem commit, no
8//! `content_hash` change. That non-mutation is load-bearing — it is
9//! what makes check-staleness derivable by hash comparison.
10//!
11//! `entity_check_state` derives never-checked | checked-ok |
12//! check-failed | check-stale from the newest record against the
13//! entity's current hash; the derivation lives in
14//! [`crate::check::derive_state`] so surfaces and health share one
15//! implementation.
16
17use crate::check::{CheckKind, CheckLedger, CheckRecord, CheckState, Verdict, derive_state};
18use crate::vcs::{Actor, ClientId};
19
20use super::{Engine, error::EngineError};
21
22impl Engine {
23    /// Record a check of one entity. Refuses typed on unknown mem
24    /// (quarantine included), unknown entity, read-only mounts, and
25    /// on any persistence failure (`CHECK_NOT_RECORDED`) — recording
26    /// is never best-effort, because a caller who believes an
27    /// unrecorded check landed is the exact dishonesty this tier
28    /// removes. The declared role rides engine session state
29    /// ([`Engine::set_role`]), same as every mutation.
30    ///
31    /// `kind` selects the closed check-kind vocabulary. A
32    /// `conformance` record is bound to the mem's schema pin, stamped
33    /// HERE from the mount — never caller-supplied, so a verdict
34    /// cannot claim a prose version the caller never read; a mem with
35    /// no pin refuses (`INVALID_INPUT`), because a semantic judgment
36    /// against no schema binds to nothing.
37    #[allow(clippy::too_many_arguments)] // the record's own fields, no natural grouping
38    pub fn record_check(
39        &mut self,
40        mem_name: &str,
41        entity_id: &str,
42        verdict: Verdict,
43        kind: CheckKind,
44        method: Option<&str>,
45        actor: Actor,
46        client: Option<&ClientId>,
47    ) -> Result<CheckRecord, EngineError> {
48        self.record_check_with(
49            mem_name,
50            entity_id,
51            verdict,
52            &crate::check::RecordKind::Engine(kind),
53            method,
54            None,
55            actor,
56            client,
57        )
58    }
59
60    /// [`Self::record_check`] with the full record shape: a kind that may
61    /// be a caller-declared foreign `x-<name>` kind (recorded verbatim,
62    /// never interpreted — it stamps no schema pin and moves no state),
63    /// and an optional structured finding (validated before anything is
64    /// appended; a malformed one refuses `INVALID_CHECK_FINDING`).
65    #[allow(clippy::too_many_arguments)]
66    pub fn record_check_with(
67        &mut self,
68        mem_name: &str,
69        entity_id: &str,
70        verdict: Verdict,
71        kind: &crate::check::RecordKind,
72        method: Option<&str>,
73        finding: Option<crate::check::CheckFinding>,
74        actor: Actor,
75        client: Option<&ClientId>,
76    ) -> Result<CheckRecord, EngineError> {
77        if let Some(f) = &finding {
78            f.validate()
79                .map_err(|reason| EngineError::InvalidCheckFinding { reason })?;
80            // The code namespace: `UPPER_SNAKE` claims an engine health
81            // condition (the acknowledgement `health --strict` honours),
82            // so it must name one; a checker's own vocabulary keeps any
83            // other spelling. An acknowledgement (a `failed` verdict on a
84            // condition) names its owner and the closing plan in `method`.
85            if crate::ops::strict::is_engine_code_shape(&f.code)
86                && !crate::ops::strict::is_health_condition(&f.code)
87            {
88                return Err(EngineError::InvalidCheckFinding {
89                    reason: format!(
90                        "finding.code `{}` is spelled in the engine's UPPER_SNAKE namespace but \
91                         names no health condition — an acknowledgement names one of: {}; a \
92                         checker's own code takes another spelling (`hidden-premise`)",
93                        f.code,
94                        crate::ops::strict::HEALTH_CONDITIONS.join(", ")
95                    ),
96                });
97            }
98            if crate::ops::strict::is_health_condition(&f.code)
99                && verdict == Verdict::Failed
100                && method.is_none_or(|m| m.trim().is_empty())
101            {
102                return Err(EngineError::InvalidCheckFinding {
103                    reason: format!(
104                        "an acknowledgement of `{}` names its owner and the plan that closes it \
105                         in `method`, and none was given",
106                        f.code
107                    ),
108                });
109            }
110        }
111        let mount_idx = self
112            .mounts
113            .iter()
114            .position(|m| m.mount.mem == mem_name)
115            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
116        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
117            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
118        }
119        let schema_ref = match kind.engine_kind() {
120            None | Some(CheckKind::Verification) => None,
121            Some(CheckKind::Conformance) => Some(
122                self.mounts[mount_idx]
123                    .mount
124                    .schema
125                    .as_ref()
126                    .map(|s| s.as_display())
127                    .ok_or_else(|| {
128                        EngineError::InvalidInput(format!(
129                            "a conformance check binds to the mem's schema pin, and mem \
130                             `{mem_name}` declares none"
131                        ))
132                    })?,
133            ),
134        };
135        let entity_hash = self
136            .store
137            .all_entities()
138            .find(|e| e.mem == mem_name && e.id.0 == entity_id)
139            .map(|e| e.content_hash.clone())
140            .ok_or_else(|| EngineError::NotFound {
141                id: entity_id.to_string(),
142            })?;
143        let Some(root) = self.workspace_root() else {
144            return Err(EngineError::CheckNotRecorded {
145                reason: "engine has no workspace root — no durable check store".to_string(),
146            });
147        };
148        let ledger = CheckLedger::for_workspace(root);
149        let record = CheckRecord {
150            ts: std::time::SystemTime::now()
151                .duration_since(std::time::UNIX_EPOCH)
152                .map(|d| d.as_secs())
153                .unwrap_or(0),
154            entity: entity_id.to_string(),
155            verdict: verdict.as_str().to_string(),
156            method: method
157                .map(str::trim)
158                .filter(|m| !m.is_empty())
159                .map(str::to_string),
160            entity_hash,
161            actor: actor.as_trailer().to_string(),
162            client: client.map(|c| format!("{}@{}", c.name, c.version)),
163            role: self
164                .current_role()
165                .as_trailer()
166                .unwrap_or("unspecified")
167                .to_string(),
168            // The caller-declared identity rides engine session state
169            // ([`Engine::set_identity`]), same as the role — absence
170            // records as absence (plan 15).
171            identity: self.current_identity().map(str::to_string),
172            // Verification records omit the kind entirely, so a
173            // kind-omitted caller's ledger lines stay byte-identical
174            // to the pre-kind shape.
175            kind: match kind {
176                crate::check::RecordKind::Engine(CheckKind::Verification) => None,
177                other => Some(other.as_wire().to_string()),
178            },
179            schema_ref,
180            finding,
181            renamed_from: None,
182            carried_from: None,
183        };
184        ledger
185            .record(&record)
186            .map_err(|e| EngineError::CheckNotRecorded {
187                reason: format!("ledger append failed: {e}"),
188            })?;
189        Ok(record)
190    }
191
192    /// Carry the check ledger across a rename: every line recorded under
193    /// `old` is appended again under `new`, marked `renamed_from`, so the
194    /// renamed entity keeps its check history instead of reading
195    /// `never_checked` while its record sits unreachable under an id
196    /// nothing resolves any more. The carried lines keep their hash, so
197    /// they derive `check_stale` against the renamed file — a rename is
198    /// a content change (title, self-links), and the verdict is not
199    /// re-asserted on content the checker never saw. An engine with no
200    /// workspace root has no ledger and carries nothing. A failed
201    /// append refuses, as recording does: the caller runs this before
202    /// the rename commits.
203    pub(crate) fn carry_checks_across_rename(
204        &self,
205        old: &crate::entity::EntityId,
206        new: &crate::entity::EntityId,
207    ) -> Result<usize, EngineError> {
208        let Some(root) = self.workspace_root() else {
209            return Ok(0);
210        };
211        CheckLedger::for_workspace(root)
212            .carry_rename(old.as_ref(), new.as_ref())
213            .map_err(|e| EngineError::CheckNotRecorded {
214                reason: format!("ledger carry across rename {old} → {new} failed: {e}"),
215            })
216    }
217
218    /// The `transition_requires_self_check` kinds a prepared write passes
219    /// on the strength of a fresh, independent record: every such
220    /// constraint of `type_def` whose gated value `next` holds and whose
221    /// declared kind the provider confirms against `next.content_hash`
222    /// (the PRE-write hash: the caller hands the composed entity before
223    /// the store or disk moved). These are the records the write is
224    /// about to stale; [`Self::carry_checks_across_transition`] carries
225    /// them. Empty when the type declares no such gate or none passes.
226    pub(crate) fn licensed_self_check_kinds(
227        &self,
228        next: &crate::entity::Entity,
229        type_def: &memstead_schema::TypeDefinition,
230    ) -> Vec<String> {
231        let provider = self.check_standing_provider();
232        let mut kinds: Vec<String> = Vec::new();
233        for c in &type_def.constraints {
234            let memstead_schema::ConstraintDef::TransitionRequiresSelfCheck {
235                field,
236                to_value,
237                check_kind,
238                ..
239            } = c
240            else {
241                continue;
242            };
243            let triggered = next
244                .metadata
245                .get(field.as_str())
246                .is_some_and(|v| v.to_frontmatter_string() == *to_value);
247            if triggered && !kinds.contains(check_kind) && provider(next, check_kind).confirms() {
248                kinds.push(check_kind.clone());
249            }
250        }
251        kinds
252    }
253
254    /// Carry the records that licensed a gated transition across the
255    /// write they licensed: for each wire kind in `kinds`, the newest
256    /// record of `id` that is fresh at `pre_hash` and confirming is
257    /// appended again keyed to `post_hash`, marked
258    /// `carried_from: {hash, reason: "transition"}`
259    /// ([`CheckLedger::carry_transition`]). Without this the write that
260    /// a `transition_requires_self_check` gate admitted moves the
261    /// entity's hash and stales the very record that admitted it, so the
262    /// constraint reads unsatisfied the moment after it was satisfied.
263    /// The carried line keeps the checker's identity: the writer is not
264    /// the checker, and independence must go on reading it that way. A
265    /// stale or failed record is not carried, it licensed nothing. An
266    /// engine with no workspace root has no ledger and carries nothing.
267    /// A failed append refuses, as recording does: the caller runs this
268    /// before the write is staged. Returns the number of lines carried.
269    pub(crate) fn carry_checks_across_transition(
270        &self,
271        id: &crate::entity::EntityId,
272        kinds: &[String],
273        pre_hash: &str,
274        post_hash: &str,
275    ) -> Result<usize, EngineError> {
276        if kinds.is_empty() || pre_hash == post_hash {
277            return Ok(0);
278        }
279        let Some(root) = self.workspace_root() else {
280            return Ok(0);
281        };
282        let ledger = CheckLedger::for_workspace(root);
283        let mut carried = 0;
284        for kind in kinds {
285            let moved = ledger
286                .carry_transition(id.as_ref(), kind, pre_hash, post_hash)
287                .map_err(|e| EngineError::CheckNotRecorded {
288                    reason: format!(
289                        "ledger carry of the `{kind}` record across the transition of {id} failed: {e}"
290                    ),
291                })?;
292            carried += usize::from(moved);
293        }
294        Ok(carried)
295    }
296
297    /// The newest check record of one entity under one wire kind, from
298    /// the one source the mount has: the sealed member for an archive
299    /// mount (a workspace ledger beside it is never consulted, and an
300    /// archive sealed without records has none), the workspace ledger
301    /// for every other mount (a writable mem never reads a sealed
302    /// member; an engine with no workspace root has no ledger). Every
303    /// check-state read goes through here, so the derivation is the same
304    /// whatever the mount.
305    pub fn latest_check_record(
306        &self,
307        mem_name: &str,
308        entity_id: &str,
309        kind: &str,
310    ) -> Option<CheckRecord> {
311        if self.is_archive_mount(mem_name) {
312            let path = crate::EntityId(entity_id.to_string());
313            return self
314                .archive_checks_for(mem_name)
315                .and_then(|sealed| sealed.latest(path.path(), kind))
316                .map(|sc| sc.to_record(entity_id, kind));
317        }
318        self.workspace_root()
319            .map(CheckLedger::for_workspace)
320            .and_then(|l| l.latest_for_wire_kind(entity_id, kind))
321    }
322
323    /// The newest record per foreign `x-<name>` kind of one entity, in
324    /// kind order, from the same source as [`Self::latest_check_record`].
325    /// Recorded, listed, never aggregated into a state.
326    pub fn latest_foreign_checks(&self, mem_name: &str, entity_id: &str) -> Vec<CheckRecord> {
327        if self.is_archive_mount(mem_name) {
328            let path = crate::EntityId(entity_id.to_string());
329            return self
330                .archive_checks_for(mem_name)
331                .map(|sealed| {
332                    sealed
333                        .kinds_of(path.path())
334                        .filter(|(k, _)| k.starts_with(crate::check::FOREIGN_KIND_PREFIX))
335                        .map(|(k, sc)| sc.to_record(entity_id, k))
336                        .collect()
337                })
338                .unwrap_or_default();
339        }
340        let Some(ledger) = self.workspace_root().map(CheckLedger::for_workspace) else {
341            return Vec::new();
342        };
343        let mut latest: std::collections::BTreeMap<String, CheckRecord> =
344            std::collections::BTreeMap::new();
345        for rec in ledger.all() {
346            if rec.entity != entity_id {
347                continue;
348            }
349            if let Some(k) = rec.foreign_kind() {
350                latest.insert(k.to_string(), rec.clone());
351            }
352        }
353        latest.into_values().collect()
354    }
355
356    /// Derive one entity's check state and newest check record.
357    /// Refuses typed on unknown mem/entity; an engine with no
358    /// workspace root has no check store and honestly derives
359    /// `never_checked` (no recorded checks exist); an archive mount
360    /// derives from its sealed member the same way.
361    pub fn entity_check_state(
362        &self,
363        mem_name: &str,
364        entity_id: &str,
365    ) -> Result<(CheckState, Option<CheckRecord>), EngineError> {
366        self.find_mount(mem_name)?;
367        let current_hash = self
368            .store
369            .all_entities()
370            .find(|e| e.mem == mem_name && e.id.0 == entity_id)
371            .map(|e| e.content_hash.clone())
372            .ok_or_else(|| EngineError::NotFound {
373                id: entity_id.to_string(),
374            })?;
375        let latest =
376            self.latest_check_record(mem_name, entity_id, CheckKind::Verification.as_str());
377        Ok((derive_state(latest.as_ref(), &current_hash), latest))
378    }
379
380    /// Derive one entity's `conformance` state and newest conformance
381    /// record: hash staleness plus pin staleness (a re-pinned or
382    /// unpinned mem stales the verdict — the prose it judged against
383    /// is no longer the prose in force). Same refusals as
384    /// [`Self::entity_check_state`].
385    pub fn entity_conformance_state(
386        &self,
387        mem_name: &str,
388        entity_id: &str,
389    ) -> Result<(CheckState, Option<CheckRecord>), EngineError> {
390        let mount = self.find_mount(mem_name)?;
391        let current_pin = mount.mount.schema.as_ref().map(|s| s.as_display());
392        let current_hash = self
393            .store
394            .all_entities()
395            .find(|e| e.mem == mem_name && e.id.0 == entity_id)
396            .map(|e| e.content_hash.clone())
397            .ok_or_else(|| EngineError::NotFound {
398                id: entity_id.to_string(),
399            })?;
400        let latest = self.latest_check_record(mem_name, entity_id, CheckKind::Conformance.as_str());
401        Ok((
402            crate::check::derive_state_pinned(
403                latest.as_ref(),
404                &current_hash,
405                current_pin.as_deref(),
406            ),
407            latest,
408        ))
409    }
410}
411
412#[cfg(test)]
413mod tests {
414    use crate::check::{CheckKind, CheckLedger, CheckRecord, CheckState, Verdict};
415    use crate::vcs::Actor;
416    use crate::workspace::MountCapability;
417
418    /// A conformance check binds to the mem's schema pin; a mem that
419    /// declares none cannot accept one. Today that refusal arrives as
420    /// the quarantine gate (an unpinned mem quarantines at boot and
421    /// serves nothing), which fires before the pin guard inside
422    /// `record_check`; the guard's own `INVALID_INPUT` remains as
423    /// defense in depth for any future backend that serves unpinned.
424    #[test]
425    fn conformance_refuses_without_a_schema_pin() {
426        let tmp = tempfile::TempDir::new().unwrap();
427        std::fs::write(
428            tmp.path().join("anything.md"),
429            "---\nid: anything\ntitle: Anything\ntype: note\n---\n\nBody.\n",
430        )
431        .unwrap();
432        let mut mount = crate::engine::test_helpers::folder_mount("m", tmp.path().to_path_buf());
433        mount.schema = None;
434        let mut engine = crate::Engine::from_mounts(vec![(
435            mount,
436            Box::new(crate::storage::FilesystemBackend::new(
437                tmp.path().to_path_buf(),
438            )) as Box<dyn crate::backend::MemBackend>,
439        )])
440        .unwrap();
441        let err = engine
442            .record_check(
443                "m",
444                "m--anything",
445                Verdict::Ok,
446                CheckKind::Conformance,
447                None,
448                Actor::Cli,
449                None,
450            )
451            .unwrap_err();
452        assert_eq!(err.code(), "MEM_QUARANTINED");
453    }
454
455    // --- the licensing record carries across the transition it licensed ---
456
457    /// A workspace-rooted folder mem `bundles` whose `plan` type gates
458    /// `status: complete` on a fresh independent record of `check_kind`
459    /// on the plan itself (`transition_requires_self_check`).
460    fn self_check_gated_engine(tmp: &tempfile::TempDir, check_kind: &str) -> crate::Engine {
461        // The workspace's fixed authored-schema location, so an export
462        // of the mem finds the schema source to embed.
463        let schemas_dir = tmp.path().join(".memstead").join("schemas");
464        let pkg = schemas_dir.join("selfgate");
465        std::fs::create_dir_all(pkg.join("types")).unwrap();
466        std::fs::write(
467            pkg.join("schema.yaml"),
468            r#"name: selfgate
469version: 0.1.0
470description: self-check gate fixture
471when_to_use: tests
472types:
473  - plan
474relationships:
475  mode: strict
476  definitions:
477    - name: PART_OF
478      description: hier
479      default_weight: 3.0
480    - name: _default
481      description: fallback
482      default_weight: 1.0
483community:
484  resolution: 1.0
485  seed: 42
486"#,
487        )
488        .unwrap();
489        std::fs::write(
490            pkg.join("types").join("plan.yaml"),
491            format!(
492                r#"name: plan
493description: p
494when_to_use: tests
495sections:
496  - key: body
497    heading: Body
498    required: true
499    search_weight: 10.0
500    catch_all: true
501    write_rules: []
502metadata_fields:
503  - key: status
504    description: s
505    field_type: string
506    default_value: draft
507    enum_values: [draft, complete]
508title_weight: 100.0
509text_fields:
510  - body
511hierarchy_relationship: PART_OF
512updatable_fields:
513  - title
514  - body
515  - status
516health_required_fields: []
517staleness_threshold_days: 90
518constraints:
519  - kind: transition_requires_self_check
520    field: status
521    to_value: complete
522    check_kind: {check_kind}
523    severity: block
524write_rules: []
525"#
526            ),
527        )
528        .unwrap();
529        let mem_dir = tmp.path().join("bundles");
530        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
531        std::fs::write(
532            mem_dir.join(".memstead").join("config.json"),
533            r#"{"format": 1, "schema": "selfgate@0.1.0", "version": "1.0.0"}"#,
534        )
535        .unwrap();
536        let writer = crate::storage::FilesystemBackend::new(mem_dir.clone());
537        let mount = crate::workspace::Mount {
538            mem: "bundles".to_string(),
539            schema: Some(memstead_schema::SchemaRef::new(
540                "selfgate",
541                semver::Version::new(0, 1, 0),
542            )),
543            storage: crate::workspace::MountStorage::Folder { path: mem_dir },
544            capability: crate::workspace::MountCapability::Write,
545            lifecycle: crate::workspace::MountLifecycle::Eager,
546            cross_linkable: true,
547            migration_target: None,
548        };
549        let mut engine = crate::Engine::from_mounts_with_schemas_dir(
550            vec![(
551                mount,
552                Box::new(writer) as Box<dyn crate::backend::MemBackend>,
553            )],
554            Some(&schemas_dir),
555        )
556        .unwrap();
557        engine.set_workspace_root(tmp.path().to_path_buf());
558        engine
559    }
560
561    fn create_plan(engine: &mut crate::Engine, title: &str) -> crate::entity::EntityId {
562        let (actor, client) = crate::engine::test_helpers::cli_actor();
563        let mut sections = indexmap::IndexMap::new();
564        sections.insert("body".to_string(), "the plan body.".to_string());
565        engine
566            .create_entity(
567                crate::engine::CreateEntityArgs {
568                    anchors: Vec::new(),
569                    mem: "bundles".to_string(),
570                    title: title.to_string(),
571                    entity_type: "plan".to_string(),
572                    sections,
573                    metadata: indexmap::IndexMap::new(),
574                    relations: Vec::new(),
575                    dry_run: false,
576                },
577                actor,
578                Some(&client),
579                None,
580            )
581            .unwrap()
582            .id
583    }
584
585    fn set_status(
586        engine: &mut crate::Engine,
587        id: &crate::entity::EntityId,
588        value: &str,
589    ) -> Result<crate::engine::UpdateEntityOutcome, crate::engine::error::EngineError> {
590        let (actor, client) = crate::engine::test_helpers::cli_actor();
591        let current = engine.get_entity(id).unwrap().content_hash.clone();
592        let mut metadata = indexmap::IndexMap::new();
593        metadata.insert("status".to_string(), value.to_string());
594        engine.update_entity(
595            crate::engine::UpdateEntityArgs {
596                anchors: Vec::new(),
597                id: id.clone(),
598                expected_hash: Some(current),
599                sections: indexmap::IndexMap::new(),
600                append_sections: indexmap::IndexMap::new(),
601                patch_sections: indexmap::IndexMap::new(),
602                sections_unset: Vec::new(),
603                metadata,
604                metadata_unset: Vec::new(),
605                declare_relations: vec![],
606                dry_run: false,
607                relations_unset: Vec::new(),
608                anchors_unset: Vec::new(),
609            },
610            actor,
611            Some(&client),
612            None,
613        )
614    }
615
616    fn append_body(engine: &mut crate::Engine, id: &crate::entity::EntityId) {
617        let (actor, client) = crate::engine::test_helpers::cli_actor();
618        let current = engine.get_entity(id).unwrap().content_hash.clone();
619        let mut append = indexmap::IndexMap::new();
620        append.insert("body".to_string(), "more.".to_string());
621        engine
622            .update_entity(
623                crate::engine::UpdateEntityArgs {
624                    anchors: Vec::new(),
625                    id: id.clone(),
626                    expected_hash: Some(current),
627                    sections: indexmap::IndexMap::new(),
628                    append_sections: append,
629                    patch_sections: indexmap::IndexMap::new(),
630                    sections_unset: Vec::new(),
631                    metadata: indexmap::IndexMap::new(),
632                    metadata_unset: Vec::new(),
633                    declare_relations: vec![],
634                    dry_run: false,
635                    relations_unset: Vec::new(),
636                    anchors_unset: Vec::new(),
637                },
638                actor,
639                Some(&client),
640                None,
641            )
642            .unwrap();
643    }
644
645    fn check_plan(
646        engine: &mut crate::Engine,
647        identity: &str,
648        id: &crate::entity::EntityId,
649        kind: &str,
650    ) {
651        check_plan_as(engine, identity, crate::vcs::Role::Checker, id, kind);
652    }
653
654    /// A check under `identity` declared in `role`: the walker's shape
655    /// is `checker`; `author` and `unspecified` are the roles a gate
656    /// refuses.
657    fn check_plan_as(
658        engine: &mut crate::Engine,
659        identity: &str,
660        role: crate::vcs::Role,
661        id: &crate::entity::EntityId,
662        kind: &str,
663    ) {
664        let (actor, client) = crate::engine::test_helpers::cli_actor();
665        engine.set_identity(Some(identity.to_string()));
666        engine.set_role(role);
667        engine
668            .record_check_with(
669                "bundles",
670                id.as_ref(),
671                Verdict::Ok,
672                &crate::check::RecordKind::from_wire(kind).unwrap(),
673                Some("projection walked"),
674                None,
675                actor,
676                Some(&client),
677            )
678            .unwrap();
679        engine.set_role(crate::vcs::Role::Unspecified);
680    }
681
682    /// The defect: a bundle carries a fresh `x-projection` ok record under
683    /// an independent identity, the author's `status: complete` passes
684    /// the gate, and the write moves the hash; before the carry, the
685    /// constraints axis reported the gate unsatisfied (`check_stale`) the
686    /// moment after it admitted the write. Now the licensing record is
687    /// carried to the post-write hash, marked, still the checker's; the
688    /// constraints axis stays clean and the gate keeps holding across a
689    /// later write to the complete plan.
690    #[test]
691    fn licensing_self_check_carries_across_the_transition_it_admitted() {
692        let tmp = tempfile::TempDir::new().unwrap();
693        let mut engine = self_check_gated_engine(&tmp, "x-projection");
694        engine.set_identity(Some("author-a".to_string()));
695        let id = create_plan(&mut engine, "The Bundle");
696        let hash_at_check = engine.get_entity(&id).unwrap().content_hash.clone();
697        check_plan(&mut engine, "checker-c", &id, "x-projection");
698
699        engine.set_identity(Some("author-a".to_string()));
700        let outcome = set_status(&mut engine, &id, "complete").expect("the gate admits the write");
701        assert_ne!(
702            outcome.content_hash, hash_at_check,
703            "the write moved the hash"
704        );
705
706        // The constraints axis reads no violation after the write.
707        let findings = engine.constraint_findings(Some("bundles"));
708        assert!(findings.is_empty(), "{findings:?}");
709
710        // The carried line: post-write hash, marked, the checker's identity.
711        let foreign = engine.latest_foreign_checks("bundles", id.as_ref());
712        assert_eq!(foreign.len(), 1);
713        let carried = &foreign[0];
714        assert_eq!(carried.entity_hash, outcome.content_hash);
715        assert_eq!(carried.identity.as_deref(), Some("checker-c"));
716        assert_eq!(carried.method.as_deref(), Some("projection walked"));
717        assert_eq!(
718            carried.carried_from,
719            Some(crate::check::CarriedFrom::transition(&hash_at_check))
720        );
721        // The gate's own reading of the carried record: fresh and independent.
722        let entity = engine.get_entity(&id).unwrap().clone();
723        let standing = (engine.check_standing_provider())(&entity, "x-projection");
724        assert!(standing.confirms(), "{standing:?}");
725        // Append-only: the checker's original line stays, unmarked.
726        let ledger = CheckLedger::for_workspace(tmp.path());
727        let lines: Vec<CheckRecord> = ledger
728            .all()
729            .into_iter()
730            .filter(|r| r.entity == id.as_ref())
731            .collect();
732        assert_eq!(lines.len(), 2);
733        assert!(lines[0].carried_from.is_none());
734        assert_eq!(lines[0].entity_hash, hash_at_check);
735
736        // A later write to the complete plan passes on the carried record
737        // and carries it onward, so the gate keeps holding.
738        engine.set_identity(Some("author-a".to_string()));
739        append_body(&mut engine, &id);
740        assert!(engine.constraint_findings(Some("bundles")).is_empty());
741        let onward = &engine.latest_foreign_checks("bundles", id.as_ref())[0];
742        assert_eq!(
743            onward.entity_hash,
744            engine.get_entity(&id).unwrap().content_hash
745        );
746        assert_eq!(
747            onward.carried_from.as_ref().unwrap().hash,
748            outcome.content_hash
749        );
750        // A write that leaves the gate unentered carries nothing: back to
751        // draft, then an append, and the record is not moved again.
752        set_status(&mut engine, &id, "draft").unwrap();
753        let before = ledger.all().len();
754        append_body(&mut engine, &id);
755        assert_eq!(
756            ledger.all().len(),
757            before,
758            "no gate passed, nothing carried"
759        );
760    }
761
762    /// The `verification` kind through the same gate: after the write the
763    /// entity's check state reads `checked_ok` and the health checks axis
764    /// lists it `confirmed_independent`: the carried record stays the
765    /// checker's, never the writer's.
766    #[test]
767    fn carried_verification_record_reads_checked_ok_and_independent() {
768        let tmp = tempfile::TempDir::new().unwrap();
769        let mut engine = self_check_gated_engine(&tmp, "verification");
770        engine.set_identity(Some("author-a".to_string()));
771        let id = create_plan(&mut engine, "The Bundle");
772        check_plan(&mut engine, "checker-c", &id, "verification");
773        engine.set_identity(Some("author-a".to_string()));
774        set_status(&mut engine, &id, "complete").expect("the gate admits the write");
775
776        let (state, latest) = engine.entity_check_state("bundles", id.as_ref()).unwrap();
777        assert_eq!(state, CheckState::CheckedOk);
778        let latest = latest.unwrap();
779        assert_eq!(latest.identity.as_deref(), Some("checker-c"));
780        assert!(latest.carried_from.is_some());
781        let axis = crate::ops::health::health_checks_axis(&engine, Some("bundles"));
782        let independence = &axis["bundles"]["independence"];
783        assert_eq!(
784            independence["confirmed_independent"]["items"],
785            serde_json::json!([id.as_ref()]),
786            "{axis}"
787        );
788        assert_eq!(
789            axis["bundles"]["checked_ok"],
790            serde_json::json!(1),
791            "{axis}"
792        );
793        assert!(engine.constraint_findings(Some("bundles")).is_empty());
794    }
795
796    /// The role is the gate's third condition, orthogonal to the reading.
797    /// An independent identity's ok record declared in role `author`
798    /// reads `confirmed_independent` on the checks axis (the identities
799    /// differ, and the axis says so) and still refuses the gate under
800    /// the label `role_author`; a record with no role refuses under
801    /// `role_unspecified`; a `verifier` record confirms like a
802    /// `checker`'s. The axis row carries the role and whether it
803    /// confirms.
804    #[test]
805    fn a_record_in_role_author_or_without_a_role_does_not_close_the_gate() {
806        let tmp = tempfile::TempDir::new().unwrap();
807        let mut engine = self_check_gated_engine(&tmp, "verification");
808        engine.set_identity(Some("author-a".to_string()));
809        let id = create_plan(&mut engine, "The Bundle");
810
811        // An independent identity, declared as the author.
812        check_plan_as(
813            &mut engine,
814            "checker-c",
815            crate::vcs::Role::Author,
816            &id,
817            "verification",
818        );
819        let standing =
820            (engine.check_standing_provider())(engine.get_entity(&id).unwrap(), "verification");
821        assert_eq!(standing.state, CheckState::CheckedOk);
822        assert_eq!(
823            standing.independence,
824            Some(crate::engine::independence::Independence::ConfirmedIndependent)
825        );
826        assert!(!standing.confirms(), "{standing:?}");
827        assert_eq!(standing.label(), "role_author");
828        engine.set_identity(Some("author-a".to_string()));
829        let err = set_status(&mut engine, &id, "complete").unwrap_err();
830        assert_eq!(err.code(), "CONSTRAINT_UNSATISFIED", "{err}");
831        assert!(err.to_string().contains("role_author"), "{err}");
832        let axis = crate::ops::health::health_checks_axis(&engine, Some("bundles"));
833        let row = axis["bundles"]["independence"]["readings"][id.as_ref()]
834            .as_array()
835            .unwrap()
836            .last()
837            .unwrap();
838        assert_eq!(row["reading"], "confirmed_independent", "{axis}");
839        assert_eq!(row["role"], "author", "{axis}");
840        assert_eq!(row["role_confirms"], false, "{axis}");
841
842        // The same identity, no role declared.
843        check_plan_as(
844            &mut engine,
845            "checker-c",
846            crate::vcs::Role::Unspecified,
847            &id,
848            "verification",
849        );
850        let standing =
851            (engine.check_standing_provider())(engine.get_entity(&id).unwrap(), "verification");
852        assert!(!standing.confirms(), "{standing:?}");
853        assert_eq!(standing.label(), "role_unspecified");
854        engine.set_identity(Some("author-a".to_string()));
855        let err = set_status(&mut engine, &id, "complete").unwrap_err();
856        assert!(err.to_string().contains("role_unspecified"), "{err}");
857
858        // A verifier's record confirms like a checker's.
859        check_plan_as(
860            &mut engine,
861            "verifier-v",
862            crate::vcs::Role::Verifier,
863            &id,
864            "verification",
865        );
866        let standing =
867            (engine.check_standing_provider())(engine.get_entity(&id).unwrap(), "verification");
868        assert!(standing.confirms(), "{standing:?}");
869        engine.set_identity(Some("author-a".to_string()));
870        set_status(&mut engine, &id, "complete").expect("a verifier's record closes the gate");
871        let axis = crate::ops::health::health_checks_axis(&engine, Some("bundles"));
872        let row = axis["bundles"]["independence"]["readings"][id.as_ref()]
873            .as_array()
874            .unwrap()
875            .last()
876            .unwrap();
877        assert_eq!(row["role"], "verifier", "{axis}");
878        assert_eq!(row["role_confirms"], true, "{axis}");
879    }
880
881    /// The gate on the archive mount. A complete plan exported to a
882    /// `.mem` and mounted from bytes used to report
883    /// `transition_requires_self_check` unsatisfied (`unconfirmable`):
884    /// the mount has no provenance to derive independence from. The
885    /// export seals the reading beside the record, so the mount's
886    /// constraints axis is clean and its checks axis lists the plan
887    /// `confirmed_independent`, exactly as the source engine did.
888    #[test]
889    fn sealed_independence_holds_the_transition_gate_on_the_archive_mount() {
890        let tmp = tempfile::TempDir::new().unwrap();
891        let mut engine = self_check_gated_engine(&tmp, "verification");
892        engine.set_identity(Some("author-a".to_string()));
893        let id = create_plan(&mut engine, "The Bundle");
894        check_plan(&mut engine, "checker-c", &id, "verification");
895        engine.set_identity(Some("author-a".to_string()));
896        set_status(&mut engine, &id, "complete").expect("the gate admits the write");
897        assert!(engine.constraint_findings(Some("bundles")).is_empty());
898
899        let bytes = engine.export_mem_to_bytes("bundles").unwrap();
900        let mounted = crate::Engine::from_archive_bytes(bytes).unwrap();
901        assert!(mounted.is_archive_mount("bundles"));
902        let findings = mounted.constraint_findings(Some("bundles"));
903        assert!(findings.is_empty(), "{findings:?}");
904        let entity = mounted.get_entity(&id).unwrap();
905        let standing = (mounted.check_standing_provider())(entity, "verification");
906        assert!(standing.confirms(), "{standing:?}");
907        let axis = crate::ops::health::health_checks_axis(&mounted, Some("bundles"));
908        assert_eq!(
909            axis["bundles"]["independence"]["confirmed_independent"]["items"],
910            serde_json::json!([id.as_ref()]),
911            "{axis}"
912        );
913        assert_eq!(
914            axis["bundles"]["checked_ok"],
915            serde_json::json!(1),
916            "{axis}"
917        );
918    }
919
920    /// A record already stale before the write licenses nothing: the
921    /// write refuses as before, and the ledger gains no carried line.
922    #[test]
923    fn stale_self_check_is_not_carried_and_the_write_refuses() {
924        let tmp = tempfile::TempDir::new().unwrap();
925        let mut engine = self_check_gated_engine(&tmp, "x-projection");
926        engine.set_identity(Some("author-a".to_string()));
927        let id = create_plan(&mut engine, "The Bundle");
928        check_plan(&mut engine, "checker-c", &id, "x-projection");
929        // The author edits after the check: the record goes stale.
930        engine.set_identity(Some("author-a".to_string()));
931        append_body(&mut engine, &id);
932        let before = CheckLedger::for_workspace(tmp.path()).all().len();
933        let err = set_status(&mut engine, &id, "complete").unwrap_err();
934        assert_eq!(err.code(), "CONSTRAINT_UNSATISFIED");
935        assert!(err.to_string().contains("check_stale"), "{err}");
936        assert_eq!(CheckLedger::for_workspace(tmp.path()).all().len(), before);
937        assert_ne!(
938            engine
939                .get_entity(&id)
940                .unwrap()
941                .metadata
942                .get("status")
943                .map(|v| v.to_frontmatter_string())
944                .as_deref(),
945            Some("complete"),
946            "the refused write left the entity as it was"
947        );
948    }
949
950    /// Criterion 5 complement: a read-only mount refuses a check
951    /// typed (`READ_ONLY_MOUNT`) — capability gating runs before the
952    /// entity lookup, same as every mutation-shaped guard.
953    #[test]
954    fn check_refuses_read_only_mounts_typed() {
955        let tmp = tempfile::TempDir::new().unwrap();
956        let mut mount = crate::engine::test_helpers::folder_mount("ro", tmp.path().to_path_buf());
957        mount.capability = MountCapability::ReadOnly;
958        let mut engine = crate::Engine::from_mounts(vec![(
959            mount,
960            Box::new(crate::storage::FilesystemBackend::new(
961                tmp.path().to_path_buf(),
962            )) as Box<dyn crate::backend::MemBackend>,
963        )])
964        .unwrap();
965        let err = engine
966            .record_check(
967                "ro",
968                "ro--anything",
969                Verdict::Ok,
970                crate::check::CheckKind::Verification,
971                None,
972                Actor::Cli,
973                None,
974            )
975            .unwrap_err();
976        assert_eq!(err.code(), "READ_ONLY_MOUNT");
977    }
978}