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