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