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(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 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 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 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 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 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(), ¤t_hash), latest))
390 }
391
392 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 ¤t_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 #[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 fn self_check_gated_engine(tmp: &tempfile::TempDir, check_kind: &str) -> crate::Engine {
473 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 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 #[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 let findings = engine.constraint_findings(Some("bundles"));
721 assert!(findings.is_empty(), "{findings:?}");
722
723 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 let entity = engine.get_entity(&id).unwrap().clone();
736 let standing = (engine.check_standing_provider())(&entity, "x-projection");
737 assert!(standing.confirms(), "{standing:?}");
738 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 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 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 #[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 #[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 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 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 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 #[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 #[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 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 #[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}