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 renamed_from: None,
182 carried_from: None,
183 };
184 ledger
185 .record(&record)
186 .map_err(|e| EngineError::CheckNotRecorded {
187 reason: format!("ledger append failed: {e}"),
188 })?;
189 Ok(record)
190 }
191
192 pub(crate) fn carry_checks_across_rename(
204 &self,
205 old: &crate::entity::EntityId,
206 new: &crate::entity::EntityId,
207 ) -> Result<usize, EngineError> {
208 let Some(root) = self.workspace_root() else {
209 return Ok(0);
210 };
211 CheckLedger::for_workspace(root)
212 .carry_rename(old.as_ref(), new.as_ref())
213 .map_err(|e| EngineError::CheckNotRecorded {
214 reason: format!("ledger carry across rename {old} → {new} failed: {e}"),
215 })
216 }
217
218 pub(crate) fn licensed_self_check_kinds(
227 &self,
228 next: &crate::entity::Entity,
229 type_def: &memstead_schema::TypeDefinition,
230 ) -> Vec<String> {
231 let provider = self.check_standing_provider();
232 let mut kinds: Vec<String> = Vec::new();
233 for c in &type_def.constraints {
234 let memstead_schema::ConstraintDef::TransitionRequiresSelfCheck {
235 field,
236 to_value,
237 check_kind,
238 ..
239 } = c
240 else {
241 continue;
242 };
243 let triggered = next
244 .metadata
245 .get(field.as_str())
246 .is_some_and(|v| v.to_frontmatter_string() == *to_value);
247 if triggered && !kinds.contains(check_kind) && provider(next, check_kind).confirms() {
248 kinds.push(check_kind.clone());
249 }
250 }
251 kinds
252 }
253
254 pub(crate) fn carry_checks_across_transition(
270 &self,
271 id: &crate::entity::EntityId,
272 kinds: &[String],
273 pre_hash: &str,
274 post_hash: &str,
275 ) -> Result<usize, EngineError> {
276 if kinds.is_empty() || pre_hash == post_hash {
277 return Ok(0);
278 }
279 let Some(root) = self.workspace_root() else {
280 return Ok(0);
281 };
282 let ledger = CheckLedger::for_workspace(root);
283 let mut carried = 0;
284 for kind in kinds {
285 let moved = ledger
286 .carry_transition(id.as_ref(), kind, pre_hash, post_hash)
287 .map_err(|e| EngineError::CheckNotRecorded {
288 reason: format!(
289 "ledger carry of the `{kind}` record across the transition of {id} failed: {e}"
290 ),
291 })?;
292 carried += usize::from(moved);
293 }
294 Ok(carried)
295 }
296
297 pub fn latest_check_record(
306 &self,
307 mem_name: &str,
308 entity_id: &str,
309 kind: &str,
310 ) -> Option<CheckRecord> {
311 if self.is_archive_mount(mem_name) {
312 let path = crate::EntityId(entity_id.to_string());
313 return self
314 .archive_checks_for(mem_name)
315 .and_then(|sealed| sealed.latest(path.path(), kind))
316 .map(|sc| sc.to_record(entity_id, kind));
317 }
318 self.workspace_root()
319 .map(CheckLedger::for_workspace)
320 .and_then(|l| l.latest_for_wire_kind(entity_id, kind))
321 }
322
323 pub fn latest_foreign_checks(&self, mem_name: &str, entity_id: &str) -> Vec<CheckRecord> {
327 if self.is_archive_mount(mem_name) {
328 let path = crate::EntityId(entity_id.to_string());
329 return self
330 .archive_checks_for(mem_name)
331 .map(|sealed| {
332 sealed
333 .kinds_of(path.path())
334 .filter(|(k, _)| k.starts_with(crate::check::FOREIGN_KIND_PREFIX))
335 .map(|(k, sc)| sc.to_record(entity_id, k))
336 .collect()
337 })
338 .unwrap_or_default();
339 }
340 let Some(ledger) = self.workspace_root().map(CheckLedger::for_workspace) else {
341 return Vec::new();
342 };
343 let mut latest: std::collections::BTreeMap<String, CheckRecord> =
344 std::collections::BTreeMap::new();
345 for rec in ledger.all() {
346 if rec.entity != entity_id {
347 continue;
348 }
349 if let Some(k) = rec.foreign_kind() {
350 latest.insert(k.to_string(), rec.clone());
351 }
352 }
353 latest.into_values().collect()
354 }
355
356 pub fn entity_check_state(
362 &self,
363 mem_name: &str,
364 entity_id: &str,
365 ) -> Result<(CheckState, Option<CheckRecord>), EngineError> {
366 self.find_mount(mem_name)?;
367 let current_hash = self
368 .store
369 .all_entities()
370 .find(|e| e.mem == mem_name && e.id.0 == entity_id)
371 .map(|e| e.content_hash.clone())
372 .ok_or_else(|| EngineError::NotFound {
373 id: entity_id.to_string(),
374 })?;
375 let latest =
376 self.latest_check_record(mem_name, entity_id, CheckKind::Verification.as_str());
377 Ok((derive_state(latest.as_ref(), ¤t_hash), latest))
378 }
379
380 pub fn entity_conformance_state(
386 &self,
387 mem_name: &str,
388 entity_id: &str,
389 ) -> Result<(CheckState, Option<CheckRecord>), EngineError> {
390 let mount = self.find_mount(mem_name)?;
391 let current_pin = mount.mount.schema.as_ref().map(|s| s.as_display());
392 let current_hash = self
393 .store
394 .all_entities()
395 .find(|e| e.mem == mem_name && e.id.0 == entity_id)
396 .map(|e| e.content_hash.clone())
397 .ok_or_else(|| EngineError::NotFound {
398 id: entity_id.to_string(),
399 })?;
400 let latest = self.latest_check_record(mem_name, entity_id, CheckKind::Conformance.as_str());
401 Ok((
402 crate::check::derive_state_pinned(
403 latest.as_ref(),
404 ¤t_hash,
405 current_pin.as_deref(),
406 ),
407 latest,
408 ))
409 }
410}
411
412#[cfg(test)]
413mod tests {
414 use crate::check::{CheckKind, CheckLedger, CheckRecord, CheckState, Verdict};
415 use crate::vcs::Actor;
416 use crate::workspace::MountCapability;
417
418 #[test]
425 fn conformance_refuses_without_a_schema_pin() {
426 let tmp = tempfile::TempDir::new().unwrap();
427 std::fs::write(
428 tmp.path().join("anything.md"),
429 "---\nid: anything\ntitle: Anything\ntype: note\n---\n\nBody.\n",
430 )
431 .unwrap();
432 let mut mount = crate::engine::test_helpers::folder_mount("m", tmp.path().to_path_buf());
433 mount.schema = None;
434 let mut engine = crate::Engine::from_mounts(vec![(
435 mount,
436 Box::new(crate::storage::FilesystemBackend::new(
437 tmp.path().to_path_buf(),
438 )) as Box<dyn crate::backend::MemBackend>,
439 )])
440 .unwrap();
441 let err = engine
442 .record_check(
443 "m",
444 "m--anything",
445 Verdict::Ok,
446 CheckKind::Conformance,
447 None,
448 Actor::Cli,
449 None,
450 )
451 .unwrap_err();
452 assert_eq!(err.code(), "MEM_QUARANTINED");
453 }
454
455 fn self_check_gated_engine(tmp: &tempfile::TempDir, check_kind: &str) -> crate::Engine {
461 let schemas_dir = tmp.path().join(".memstead").join("schemas");
464 let pkg = schemas_dir.join("selfgate");
465 std::fs::create_dir_all(pkg.join("types")).unwrap();
466 std::fs::write(
467 pkg.join("schema.yaml"),
468 r#"name: selfgate
469version: 0.1.0
470description: self-check gate fixture
471when_to_use: tests
472types:
473 - plan
474relationships:
475 mode: strict
476 definitions:
477 - name: PART_OF
478 description: hier
479 default_weight: 3.0
480 - name: _default
481 description: fallback
482 default_weight: 1.0
483community:
484 resolution: 1.0
485 seed: 42
486"#,
487 )
488 .unwrap();
489 std::fs::write(
490 pkg.join("types").join("plan.yaml"),
491 format!(
492 r#"name: plan
493description: p
494when_to_use: tests
495sections:
496 - key: body
497 heading: Body
498 required: true
499 search_weight: 10.0
500 catch_all: true
501 write_rules: []
502metadata_fields:
503 - key: status
504 description: s
505 field_type: string
506 default_value: draft
507 enum_values: [draft, complete]
508title_weight: 100.0
509text_fields:
510 - body
511hierarchy_relationship: PART_OF
512updatable_fields:
513 - title
514 - body
515 - status
516health_required_fields: []
517staleness_threshold_days: 90
518constraints:
519 - kind: transition_requires_self_check
520 field: status
521 to_value: complete
522 check_kind: {check_kind}
523 severity: block
524write_rules: []
525"#
526 ),
527 )
528 .unwrap();
529 let mem_dir = tmp.path().join("bundles");
530 std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
531 std::fs::write(
532 mem_dir.join(".memstead").join("config.json"),
533 r#"{"format": 1, "schema": "selfgate@0.1.0", "version": "1.0.0"}"#,
534 )
535 .unwrap();
536 let writer = crate::storage::FilesystemBackend::new(mem_dir.clone());
537 let mount = crate::workspace::Mount {
538 mem: "bundles".to_string(),
539 schema: Some(memstead_schema::SchemaRef::new(
540 "selfgate",
541 semver::Version::new(0, 1, 0),
542 )),
543 storage: crate::workspace::MountStorage::Folder { path: mem_dir },
544 capability: crate::workspace::MountCapability::Write,
545 lifecycle: crate::workspace::MountLifecycle::Eager,
546 cross_linkable: true,
547 migration_target: None,
548 };
549 let mut engine = crate::Engine::from_mounts_with_schemas_dir(
550 vec![(
551 mount,
552 Box::new(writer) as Box<dyn crate::backend::MemBackend>,
553 )],
554 Some(&schemas_dir),
555 )
556 .unwrap();
557 engine.set_workspace_root(tmp.path().to_path_buf());
558 engine
559 }
560
561 fn create_plan(engine: &mut crate::Engine, title: &str) -> crate::entity::EntityId {
562 let (actor, client) = crate::engine::test_helpers::cli_actor();
563 let mut sections = indexmap::IndexMap::new();
564 sections.insert("body".to_string(), "the plan body.".to_string());
565 engine
566 .create_entity(
567 crate::engine::CreateEntityArgs {
568 anchors: Vec::new(),
569 mem: "bundles".to_string(),
570 title: title.to_string(),
571 entity_type: "plan".to_string(),
572 sections,
573 metadata: indexmap::IndexMap::new(),
574 relations: Vec::new(),
575 dry_run: false,
576 },
577 actor,
578 Some(&client),
579 None,
580 )
581 .unwrap()
582 .id
583 }
584
585 fn set_status(
586 engine: &mut crate::Engine,
587 id: &crate::entity::EntityId,
588 value: &str,
589 ) -> Result<crate::engine::UpdateEntityOutcome, crate::engine::error::EngineError> {
590 let (actor, client) = crate::engine::test_helpers::cli_actor();
591 let current = engine.get_entity(id).unwrap().content_hash.clone();
592 let mut metadata = indexmap::IndexMap::new();
593 metadata.insert("status".to_string(), value.to_string());
594 engine.update_entity(
595 crate::engine::UpdateEntityArgs {
596 anchors: Vec::new(),
597 id: id.clone(),
598 expected_hash: Some(current),
599 sections: indexmap::IndexMap::new(),
600 append_sections: indexmap::IndexMap::new(),
601 patch_sections: indexmap::IndexMap::new(),
602 sections_unset: Vec::new(),
603 metadata,
604 metadata_unset: Vec::new(),
605 declare_relations: vec![],
606 dry_run: false,
607 relations_unset: Vec::new(),
608 anchors_unset: Vec::new(),
609 },
610 actor,
611 Some(&client),
612 None,
613 )
614 }
615
616 fn append_body(engine: &mut crate::Engine, id: &crate::entity::EntityId) {
617 let (actor, client) = crate::engine::test_helpers::cli_actor();
618 let current = engine.get_entity(id).unwrap().content_hash.clone();
619 let mut append = indexmap::IndexMap::new();
620 append.insert("body".to_string(), "more.".to_string());
621 engine
622 .update_entity(
623 crate::engine::UpdateEntityArgs {
624 anchors: Vec::new(),
625 id: id.clone(),
626 expected_hash: Some(current),
627 sections: indexmap::IndexMap::new(),
628 append_sections: append,
629 patch_sections: indexmap::IndexMap::new(),
630 sections_unset: Vec::new(),
631 metadata: indexmap::IndexMap::new(),
632 metadata_unset: Vec::new(),
633 declare_relations: vec![],
634 dry_run: false,
635 relations_unset: Vec::new(),
636 anchors_unset: Vec::new(),
637 },
638 actor,
639 Some(&client),
640 None,
641 )
642 .unwrap();
643 }
644
645 fn check_plan(
646 engine: &mut crate::Engine,
647 identity: &str,
648 id: &crate::entity::EntityId,
649 kind: &str,
650 ) {
651 check_plan_as(engine, identity, crate::vcs::Role::Checker, id, kind);
652 }
653
654 fn check_plan_as(
658 engine: &mut crate::Engine,
659 identity: &str,
660 role: crate::vcs::Role,
661 id: &crate::entity::EntityId,
662 kind: &str,
663 ) {
664 let (actor, client) = crate::engine::test_helpers::cli_actor();
665 engine.set_identity(Some(identity.to_string()));
666 engine.set_role(role);
667 engine
668 .record_check_with(
669 "bundles",
670 id.as_ref(),
671 Verdict::Ok,
672 &crate::check::RecordKind::from_wire(kind).unwrap(),
673 Some("projection walked"),
674 None,
675 actor,
676 Some(&client),
677 )
678 .unwrap();
679 engine.set_role(crate::vcs::Role::Unspecified);
680 }
681
682 #[test]
691 fn licensing_self_check_carries_across_the_transition_it_admitted() {
692 let tmp = tempfile::TempDir::new().unwrap();
693 let mut engine = self_check_gated_engine(&tmp, "x-projection");
694 engine.set_identity(Some("author-a".to_string()));
695 let id = create_plan(&mut engine, "The Bundle");
696 let hash_at_check = engine.get_entity(&id).unwrap().content_hash.clone();
697 check_plan(&mut engine, "checker-c", &id, "x-projection");
698
699 engine.set_identity(Some("author-a".to_string()));
700 let outcome = set_status(&mut engine, &id, "complete").expect("the gate admits the write");
701 assert_ne!(
702 outcome.content_hash, hash_at_check,
703 "the write moved the hash"
704 );
705
706 let findings = engine.constraint_findings(Some("bundles"));
708 assert!(findings.is_empty(), "{findings:?}");
709
710 let foreign = engine.latest_foreign_checks("bundles", id.as_ref());
712 assert_eq!(foreign.len(), 1);
713 let carried = &foreign[0];
714 assert_eq!(carried.entity_hash, outcome.content_hash);
715 assert_eq!(carried.identity.as_deref(), Some("checker-c"));
716 assert_eq!(carried.method.as_deref(), Some("projection walked"));
717 assert_eq!(
718 carried.carried_from,
719 Some(crate::check::CarriedFrom::transition(&hash_at_check))
720 );
721 let entity = engine.get_entity(&id).unwrap().clone();
723 let standing = (engine.check_standing_provider())(&entity, "x-projection");
724 assert!(standing.confirms(), "{standing:?}");
725 let ledger = CheckLedger::for_workspace(tmp.path());
727 let lines: Vec<CheckRecord> = ledger
728 .all()
729 .into_iter()
730 .filter(|r| r.entity == id.as_ref())
731 .collect();
732 assert_eq!(lines.len(), 2);
733 assert!(lines[0].carried_from.is_none());
734 assert_eq!(lines[0].entity_hash, hash_at_check);
735
736 engine.set_identity(Some("author-a".to_string()));
739 append_body(&mut engine, &id);
740 assert!(engine.constraint_findings(Some("bundles")).is_empty());
741 let onward = &engine.latest_foreign_checks("bundles", id.as_ref())[0];
742 assert_eq!(
743 onward.entity_hash,
744 engine.get_entity(&id).unwrap().content_hash
745 );
746 assert_eq!(
747 onward.carried_from.as_ref().unwrap().hash,
748 outcome.content_hash
749 );
750 set_status(&mut engine, &id, "draft").unwrap();
753 let before = ledger.all().len();
754 append_body(&mut engine, &id);
755 assert_eq!(
756 ledger.all().len(),
757 before,
758 "no gate passed, nothing carried"
759 );
760 }
761
762 #[test]
767 fn carried_verification_record_reads_checked_ok_and_independent() {
768 let tmp = tempfile::TempDir::new().unwrap();
769 let mut engine = self_check_gated_engine(&tmp, "verification");
770 engine.set_identity(Some("author-a".to_string()));
771 let id = create_plan(&mut engine, "The Bundle");
772 check_plan(&mut engine, "checker-c", &id, "verification");
773 engine.set_identity(Some("author-a".to_string()));
774 set_status(&mut engine, &id, "complete").expect("the gate admits the write");
775
776 let (state, latest) = engine.entity_check_state("bundles", id.as_ref()).unwrap();
777 assert_eq!(state, CheckState::CheckedOk);
778 let latest = latest.unwrap();
779 assert_eq!(latest.identity.as_deref(), Some("checker-c"));
780 assert!(latest.carried_from.is_some());
781 let axis = crate::ops::health::health_checks_axis(&engine, Some("bundles"));
782 let independence = &axis["bundles"]["independence"];
783 assert_eq!(
784 independence["confirmed_independent"]["items"],
785 serde_json::json!([id.as_ref()]),
786 "{axis}"
787 );
788 assert_eq!(
789 axis["bundles"]["checked_ok"],
790 serde_json::json!(1),
791 "{axis}"
792 );
793 assert!(engine.constraint_findings(Some("bundles")).is_empty());
794 }
795
796 #[test]
805 fn a_record_in_role_author_or_without_a_role_does_not_close_the_gate() {
806 let tmp = tempfile::TempDir::new().unwrap();
807 let mut engine = self_check_gated_engine(&tmp, "verification");
808 engine.set_identity(Some("author-a".to_string()));
809 let id = create_plan(&mut engine, "The Bundle");
810
811 check_plan_as(
813 &mut engine,
814 "checker-c",
815 crate::vcs::Role::Author,
816 &id,
817 "verification",
818 );
819 let standing =
820 (engine.check_standing_provider())(engine.get_entity(&id).unwrap(), "verification");
821 assert_eq!(standing.state, CheckState::CheckedOk);
822 assert_eq!(
823 standing.independence,
824 Some(crate::engine::independence::Independence::ConfirmedIndependent)
825 );
826 assert!(!standing.confirms(), "{standing:?}");
827 assert_eq!(standing.label(), "role_author");
828 engine.set_identity(Some("author-a".to_string()));
829 let err = set_status(&mut engine, &id, "complete").unwrap_err();
830 assert_eq!(err.code(), "CONSTRAINT_UNSATISFIED", "{err}");
831 assert!(err.to_string().contains("role_author"), "{err}");
832 let axis = crate::ops::health::health_checks_axis(&engine, Some("bundles"));
833 let row = axis["bundles"]["independence"]["readings"][id.as_ref()]
834 .as_array()
835 .unwrap()
836 .last()
837 .unwrap();
838 assert_eq!(row["reading"], "confirmed_independent", "{axis}");
839 assert_eq!(row["role"], "author", "{axis}");
840 assert_eq!(row["role_confirms"], false, "{axis}");
841
842 check_plan_as(
844 &mut engine,
845 "checker-c",
846 crate::vcs::Role::Unspecified,
847 &id,
848 "verification",
849 );
850 let standing =
851 (engine.check_standing_provider())(engine.get_entity(&id).unwrap(), "verification");
852 assert!(!standing.confirms(), "{standing:?}");
853 assert_eq!(standing.label(), "role_unspecified");
854 engine.set_identity(Some("author-a".to_string()));
855 let err = set_status(&mut engine, &id, "complete").unwrap_err();
856 assert!(err.to_string().contains("role_unspecified"), "{err}");
857
858 check_plan_as(
860 &mut engine,
861 "verifier-v",
862 crate::vcs::Role::Verifier,
863 &id,
864 "verification",
865 );
866 let standing =
867 (engine.check_standing_provider())(engine.get_entity(&id).unwrap(), "verification");
868 assert!(standing.confirms(), "{standing:?}");
869 engine.set_identity(Some("author-a".to_string()));
870 set_status(&mut engine, &id, "complete").expect("a verifier's record closes the gate");
871 let axis = crate::ops::health::health_checks_axis(&engine, Some("bundles"));
872 let row = axis["bundles"]["independence"]["readings"][id.as_ref()]
873 .as_array()
874 .unwrap()
875 .last()
876 .unwrap();
877 assert_eq!(row["role"], "verifier", "{axis}");
878 assert_eq!(row["role_confirms"], true, "{axis}");
879 }
880
881 #[test]
889 fn sealed_independence_holds_the_transition_gate_on_the_archive_mount() {
890 let tmp = tempfile::TempDir::new().unwrap();
891 let mut engine = self_check_gated_engine(&tmp, "verification");
892 engine.set_identity(Some("author-a".to_string()));
893 let id = create_plan(&mut engine, "The Bundle");
894 check_plan(&mut engine, "checker-c", &id, "verification");
895 engine.set_identity(Some("author-a".to_string()));
896 set_status(&mut engine, &id, "complete").expect("the gate admits the write");
897 assert!(engine.constraint_findings(Some("bundles")).is_empty());
898
899 let bytes = engine.export_mem_to_bytes("bundles").unwrap();
900 let mounted = crate::Engine::from_archive_bytes(bytes).unwrap();
901 assert!(mounted.is_archive_mount("bundles"));
902 let findings = mounted.constraint_findings(Some("bundles"));
903 assert!(findings.is_empty(), "{findings:?}");
904 let entity = mounted.get_entity(&id).unwrap();
905 let standing = (mounted.check_standing_provider())(entity, "verification");
906 assert!(standing.confirms(), "{standing:?}");
907 let axis = crate::ops::health::health_checks_axis(&mounted, Some("bundles"));
908 assert_eq!(
909 axis["bundles"]["independence"]["confirmed_independent"]["items"],
910 serde_json::json!([id.as_ref()]),
911 "{axis}"
912 );
913 assert_eq!(
914 axis["bundles"]["checked_ok"],
915 serde_json::json!(1),
916 "{axis}"
917 );
918 }
919
920 #[test]
923 fn stale_self_check_is_not_carried_and_the_write_refuses() {
924 let tmp = tempfile::TempDir::new().unwrap();
925 let mut engine = self_check_gated_engine(&tmp, "x-projection");
926 engine.set_identity(Some("author-a".to_string()));
927 let id = create_plan(&mut engine, "The Bundle");
928 check_plan(&mut engine, "checker-c", &id, "x-projection");
929 engine.set_identity(Some("author-a".to_string()));
931 append_body(&mut engine, &id);
932 let before = CheckLedger::for_workspace(tmp.path()).all().len();
933 let err = set_status(&mut engine, &id, "complete").unwrap_err();
934 assert_eq!(err.code(), "CONSTRAINT_UNSATISFIED");
935 assert!(err.to_string().contains("check_stale"), "{err}");
936 assert_eq!(CheckLedger::for_workspace(tmp.path()).all().len(), before);
937 assert_ne!(
938 engine
939 .get_entity(&id)
940 .unwrap()
941 .metadata
942 .get("status")
943 .map(|v| v.to_frontmatter_string())
944 .as_deref(),
945 Some("complete"),
946 "the refused write left the entity as it was"
947 );
948 }
949
950 #[test]
954 fn check_refuses_read_only_mounts_typed() {
955 let tmp = tempfile::TempDir::new().unwrap();
956 let mut mount = crate::engine::test_helpers::folder_mount("ro", tmp.path().to_path_buf());
957 mount.capability = MountCapability::ReadOnly;
958 let mut engine = crate::Engine::from_mounts(vec![(
959 mount,
960 Box::new(crate::storage::FilesystemBackend::new(
961 tmp.path().to_path_buf(),
962 )) as Box<dyn crate::backend::MemBackend>,
963 )])
964 .unwrap();
965 let err = engine
966 .record_check(
967 "ro",
968 "ro--anything",
969 Verdict::Ok,
970 crate::check::CheckKind::Verification,
971 None,
972 Actor::Cli,
973 None,
974 )
975 .unwrap_err();
976 assert_eq!(err.code(), "READ_ONLY_MOUNT");
977 }
978}