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 None,
56 actor,
57 client,
58 )
59 }
60
61 #[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 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 identity: self.current_identity().map(str::to_string),
184 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 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 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 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 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 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 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 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(), ¤t_hash), latest))
408 }
409
410 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 ¤t_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 #[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 fn self_check_gated_engine(tmp: &tempfile::TempDir, check_kind: &str) -> crate::Engine {
491 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 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 #[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 let findings = engine.constraint_findings(Some("bundles"));
765 assert!(findings.is_empty(), "{findings:?}");
766
767 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 let entity = engine.get_entity(&id).unwrap().clone();
780 let standing = (engine.check_standing_provider())(&entity, "x-projection");
781 assert!(standing.confirms(), "{standing:?}");
782 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 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 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 #[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 #[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 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 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 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 #[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 #[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 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 #[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}