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        };
182        ledger
183            .record(&record)
184            .map_err(|e| EngineError::CheckNotRecorded {
185                reason: format!("ledger append failed: {e}"),
186            })?;
187        Ok(record)
188    }
189
190    /// Derive one entity's check state and newest check record.
191    /// Refuses typed on unknown mem/entity; an engine with no
192    /// workspace root has no check store and honestly derives
193    /// `never_checked` (no recorded checks exist).
194    pub fn entity_check_state(
195        &self,
196        mem_name: &str,
197        entity_id: &str,
198    ) -> Result<(CheckState, Option<CheckRecord>), EngineError> {
199        self.find_mount(mem_name)?;
200        let current_hash = self
201            .store
202            .all_entities()
203            .find(|e| e.mem == mem_name && e.id.0 == entity_id)
204            .map(|e| e.content_hash.clone())
205            .ok_or_else(|| EngineError::NotFound {
206                id: entity_id.to_string(),
207            })?;
208        let latest = self
209            .workspace_root()
210            .map(CheckLedger::for_workspace)
211            .and_then(|l| l.latest_for_kind(entity_id, CheckKind::Verification));
212        Ok((derive_state(latest.as_ref(), &current_hash), latest))
213    }
214
215    /// Derive one entity's `conformance` state and newest conformance
216    /// record: hash staleness plus pin staleness (a re-pinned or
217    /// unpinned mem stales the verdict — the prose it judged against
218    /// is no longer the prose in force). Same refusals as
219    /// [`Self::entity_check_state`].
220    pub fn entity_conformance_state(
221        &self,
222        mem_name: &str,
223        entity_id: &str,
224    ) -> Result<(CheckState, Option<CheckRecord>), EngineError> {
225        let mount = self.find_mount(mem_name)?;
226        let current_pin = mount.mount.schema.as_ref().map(|s| s.as_display());
227        let current_hash = self
228            .store
229            .all_entities()
230            .find(|e| e.mem == mem_name && e.id.0 == entity_id)
231            .map(|e| e.content_hash.clone())
232            .ok_or_else(|| EngineError::NotFound {
233                id: entity_id.to_string(),
234            })?;
235        let latest = self
236            .workspace_root()
237            .map(CheckLedger::for_workspace)
238            .and_then(|l| l.latest_for_kind(entity_id, CheckKind::Conformance));
239        Ok((
240            crate::check::derive_state_pinned(
241                latest.as_ref(),
242                &current_hash,
243                current_pin.as_deref(),
244            ),
245            latest,
246        ))
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use crate::check::{CheckKind, Verdict};
253    use crate::vcs::Actor;
254    use crate::workspace::MountCapability;
255
256    /// A conformance check binds to the mem's schema pin; a mem that
257    /// declares none cannot accept one. Today that refusal arrives as
258    /// the quarantine gate (an unpinned mem quarantines at boot and
259    /// serves nothing), which fires before the pin guard inside
260    /// `record_check`; the guard's own `INVALID_INPUT` remains as
261    /// defense in depth for any future backend that serves unpinned.
262    #[test]
263    fn conformance_refuses_without_a_schema_pin() {
264        let tmp = tempfile::TempDir::new().unwrap();
265        std::fs::write(
266            tmp.path().join("anything.md"),
267            "---\nid: anything\ntitle: Anything\ntype: note\n---\n\nBody.\n",
268        )
269        .unwrap();
270        let mut mount = crate::engine::test_helpers::folder_mount("m", tmp.path().to_path_buf());
271        mount.schema = None;
272        let mut engine = crate::Engine::from_mounts(vec![(
273            mount,
274            Box::new(crate::storage::FilesystemMemWriter::new(
275                tmp.path().to_path_buf(),
276            )) as Box<dyn crate::backend::MemBackend>,
277        )])
278        .unwrap();
279        let err = engine
280            .record_check(
281                "m",
282                "m--anything",
283                Verdict::Ok,
284                CheckKind::Conformance,
285                None,
286                Actor::Cli,
287                None,
288            )
289            .unwrap_err();
290        assert_eq!(err.code(), "MEM_QUARANTINED");
291    }
292
293    /// Criterion 5 complement: a read-only mount refuses a check
294    /// typed (`READ_ONLY_MOUNT`) — capability gating runs before the
295    /// entity lookup, same as every mutation-shaped guard.
296    #[test]
297    fn check_refuses_read_only_mounts_typed() {
298        let tmp = tempfile::TempDir::new().unwrap();
299        let mut mount = crate::engine::test_helpers::folder_mount("ro", tmp.path().to_path_buf());
300        mount.capability = MountCapability::ReadOnly;
301        let mut engine = crate::Engine::from_mounts(vec![(
302            mount,
303            Box::new(crate::storage::FilesystemMemWriter::new(
304                tmp.path().to_path_buf(),
305            )) as Box<dyn crate::backend::MemBackend>,
306        )])
307        .unwrap();
308        let err = engine
309            .record_check(
310                "ro",
311                "ro--anything",
312                Verdict::Ok,
313                crate::check::CheckKind::Verification,
314                None,
315                Actor::Cli,
316                None,
317            )
318            .unwrap_err();
319        assert_eq!(err.code(), "READ_ONLY_MOUNT");
320    }
321}