1use crate::check::{CheckKind, CheckLedger, CheckRecord, CheckState, Verdict, derive_state};
18use crate::vcs::{Actor, ClientId};
19
20use super::{Engine, error::EngineError};
21
22impl Engine {
23 #[allow(clippy::too_many_arguments)] 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 #[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 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 identity: self.current_identity().map(str::to_string),
172 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 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(), ¤t_hash), latest))
213 }
214
215 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 ¤t_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 #[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 #[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}