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(|| self.not_found(entity_id))?;
155 let Some(root) = self.workspace_root() else {
156 return Err(EngineError::CheckNotRecorded {
157 reason: "engine has no workspace root — no durable check store".to_string(),
158 });
159 };
160 let ledger = CheckLedger::for_workspace(root);
161 let record = CheckRecord {
162 ts: now,
163 observed_at,
164 entity: entity_id.to_string(),
165 verdict: verdict.as_str().to_string(),
166 method: method
167 .map(str::trim)
168 .filter(|m| !m.is_empty())
169 .map(str::to_string),
170 entity_hash,
171 actor: actor.as_trailer().to_string(),
172 client: client.map(|c| format!("{}@{}", c.name, c.version)),
173 role: self
174 .current_role()
175 .as_trailer()
176 .unwrap_or("unspecified")
177 .to_string(),
178 identity: self.current_identity().map(str::to_string),
182 kind: match kind {
186 crate::check::RecordKind::Engine(CheckKind::Verification) => None,
187 other => Some(other.as_wire().to_string()),
188 },
189 schema_ref,
190 finding,
191 renamed_from: None,
192 carried_from: None,
193 checked_write: self
196 .mem_touches(mem_name)
197 .last_write(entity_id)
198 .map(str::to_string),
199 };
200 ledger
201 .record_local(record)
202 .map_err(|e| EngineError::CheckNotRecorded {
203 reason: format!("ledger append failed: {e}"),
204 })
205 }
206
207 pub fn check_records(&self, mem_name: &str) -> (Vec<CheckRecord>, bool) {
222 let mounted = self.mounts.iter().any(|m| m.mount.mem == mem_name);
223 let rows = self
224 .workspace_root()
225 .map(|root| CheckLedger::for_workspace(root).rows_for_mem(mem_name))
226 .unwrap_or_default();
227 (rows, mounted)
228 }
229
230 pub fn check_records_all(&self) -> Vec<CheckRecord> {
233 self.workspace_root()
234 .map(|root| CheckLedger::for_workspace(root).in_standing_order())
235 .unwrap_or_default()
236 }
237
238 pub(crate) fn carry_checks_across_rename(
250 &self,
251 old: &crate::entity::EntityId,
252 new: &crate::entity::EntityId,
253 ) -> Result<usize, EngineError> {
254 let Some(root) = self.workspace_root() else {
255 return Ok(0);
256 };
257 CheckLedger::for_workspace(root)
258 .carry_rename(old.as_ref(), new.as_ref())
259 .map_err(|e| EngineError::CheckNotRecorded {
260 reason: format!("ledger carry across rename {old} → {new} failed: {e}"),
261 })
262 }
263
264 pub(crate) fn gate_transition_forms(
282 &self,
283 before: Option<(&crate::entity::Entity, &memstead_schema::TypeDefinition)>,
284 next: &crate::entity::Entity,
285 result_hash: &str,
286 type_def: &memstead_schema::TypeDefinition,
287 violated: Vec<crate::ops::health::UnsatisfiedConstraint>,
288 ) -> (Vec<crate::ops::health::UnsatisfiedConstraint>, Vec<String>) {
289 use crate::ops::health::UnsatisfiedConstraint as U;
290 use memstead_schema::ConstraintDef as C;
291 if self.defer_transition_gates {
292 let kept = violated
293 .into_iter()
294 .filter(|v| {
295 !matches!(
296 v,
297 U::TransitionRequiresChecks { .. } | U::TransitionRequiresSelfCheck { .. }
298 )
299 })
300 .collect();
301 return (kept, Vec::new());
302 }
303 let holds = |e: &crate::entity::Entity, field: &str, value: &str| {
304 e.metadata
305 .get(field)
306 .is_some_and(|v| v.to_frontmatter_string() == value)
307 };
308 let stood = |self_check: bool, field: &str, value: &str| {
311 before.is_some_and(|(b, def)| {
312 holds(b, field, value)
313 && def.constraints.iter().any(|c| match c {
314 C::TransitionRequiresSelfCheck {
315 field: f,
316 to_value: v,
317 ..
318 } => self_check && f == field && v == value,
319 C::TransitionRequiresChecks {
320 field: f,
321 to_value: v,
322 ..
323 } => !self_check && f == field && v == value,
324 _ => false,
325 })
326 })
327 };
328 let mut out: Vec<U> = violated
329 .into_iter()
330 .filter(|v| match v {
331 U::TransitionRequiresChecks {
332 field, to_value, ..
333 } => !stood(false, field, to_value),
334 U::TransitionRequiresSelfCheck { .. } => false,
335 _ => true,
336 })
337 .collect();
338 let provider = self.check_standing_provider();
339 let mut result_entity = next.clone();
340 result_entity.content_hash = result_hash.to_string();
341 let mut carry: Vec<String> = Vec::new();
342 for c in &type_def.constraints {
343 let C::TransitionRequiresSelfCheck {
344 field,
345 to_value,
346 check_kind,
347 severity,
348 } = c
349 else {
350 continue;
351 };
352 if !holds(next, field, to_value) || stood(true, field, to_value) {
353 continue;
354 }
355 let at_result = provider(&result_entity, check_kind);
356 if !result_hash.is_empty() && at_result.confirms() {
359 continue;
360 }
361 let mut state = at_result.label().to_string();
362 let mut changed = Vec::new();
363 if let Some((b, _)) = before {
364 let at_stored = provider(b, check_kind);
365 if at_stored.confirms() {
366 changed = content_changed_beside(b, next, field);
367 if changed.is_empty() {
368 if !carry.contains(check_kind) {
369 carry.push(check_kind.clone());
370 }
371 continue;
372 }
373 }
374 state = at_stored.label().to_string();
375 }
376 out.push(U::TransitionRequiresSelfCheck {
377 field: field.clone(),
378 to_value: to_value.clone(),
379 check_kind: check_kind.clone(),
380 state,
381 changed,
382 severity: *severity,
383 });
384 }
385 (out, carry)
386 }
387
388 pub(crate) fn checks_form_after(
397 &self,
398 post: &crate::store::Store,
399 before: &crate::store::Store,
400 writes: &[(
401 crate::entity::Entity,
402 std::sync::Arc<memstead_schema::TypeDefinition>,
403 )],
404 ) -> Vec<(
405 crate::entity::Entity,
406 Vec<crate::ops::health::UnsatisfiedConstraint>,
407 )> {
408 use crate::ops::health::UnsatisfiedConstraint as U;
409 let provider = self.check_standing_provider();
410 let mut out = Vec::new();
411 for (next, td) in writes {
412 let violated: Vec<U> = crate::ops::health::unsatisfied_constraints(
413 post,
414 next,
415 td.as_ref(),
416 Some(&next.id),
417 Some(&provider),
418 )
419 .into_iter()
420 .filter(|v| matches!(v, U::TransitionRequiresChecks { .. }))
421 .collect();
422 if violated.is_empty() {
423 continue;
424 }
425 let stored = before.get(&next.id).filter(|e| !e.stub).cloned();
426 let stored_def = stored.as_ref().and_then(|b| {
427 self.schemas
428 .get(&b.mem)
429 .and_then(|schema| schema.get_type(&b.entity_type))
430 });
431 let pre = match (&stored, &stored_def) {
432 (Some(b), Some(d)) => Some((b, d.as_ref())),
433 _ => None,
434 };
435 let (kept, _) =
436 self.gate_transition_forms(pre, next, &next.content_hash, td.as_ref(), violated);
437 let blocked: Vec<U> = kept
438 .into_iter()
439 .filter(|v| {
440 matches!(v, U::TransitionRequiresChecks { .. })
441 && v.severity() == memstead_schema::ConstraintSeverity::Block
442 })
443 .collect();
444 if !blocked.is_empty() {
445 out.push((next.clone(), blocked));
446 }
447 }
448 out
449 }
450
451 pub(crate) fn carry_checks_across_transition(
467 &self,
468 id: &crate::entity::EntityId,
469 kinds: &[String],
470 pre_hash: &str,
471 post_hash: &str,
472 ) -> Result<usize, EngineError> {
473 if kinds.is_empty() || pre_hash == post_hash {
474 return Ok(0);
475 }
476 let Some(root) = self.workspace_root() else {
477 return Ok(0);
478 };
479 let ledger = CheckLedger::for_workspace(root);
480 let mut carried = 0;
481 for kind in kinds {
482 let moved = ledger
483 .carry_transition(id.as_ref(), kind, pre_hash, post_hash)
484 .map_err(|e| EngineError::CheckNotRecorded {
485 reason: format!(
486 "ledger carry of the `{kind}` record across the transition of {id} failed: {e}"
487 ),
488 })?;
489 carried += usize::from(moved);
490 }
491 Ok(carried)
492 }
493
494 pub fn latest_check_record(
503 &self,
504 mem_name: &str,
505 entity_id: &str,
506 kind: &str,
507 ) -> Option<CheckRecord> {
508 if self.is_archive_mount(mem_name) {
509 let path = crate::EntityId(entity_id.to_string());
510 return self
511 .archive_checks_for(mem_name)
512 .and_then(|sealed| sealed.latest(path.path(), kind))
513 .map(|sc| sc.to_record(entity_id, kind));
514 }
515 self.workspace_root()
516 .map(CheckLedger::for_workspace)
517 .and_then(|l| l.latest_for_wire_kind(entity_id, kind))
518 }
519
520 pub fn latest_foreign_checks(&self, mem_name: &str, entity_id: &str) -> Vec<CheckRecord> {
524 if self.is_archive_mount(mem_name) {
525 let path = crate::EntityId(entity_id.to_string());
526 return self
527 .archive_checks_for(mem_name)
528 .map(|sealed| {
529 sealed
530 .kinds_of(path.path())
531 .filter(|(k, _)| k.starts_with(crate::check::FOREIGN_KIND_PREFIX))
532 .map(|(k, sc)| sc.to_record(entity_id, k))
533 .collect()
534 })
535 .unwrap_or_default();
536 }
537 let Some(ledger) = self.workspace_root().map(CheckLedger::for_workspace) else {
538 return Vec::new();
539 };
540 let mut latest: std::collections::BTreeMap<String, CheckRecord> =
541 std::collections::BTreeMap::new();
542 for rec in ledger.in_standing_order() {
543 if rec.entity != entity_id {
544 continue;
545 }
546 if let Some(k) = rec.foreign_kind() {
547 latest.insert(k.to_string(), rec.clone());
548 }
549 }
550 latest.into_values().collect()
551 }
552
553 pub fn entity_check_state(
559 &self,
560 mem_name: &str,
561 entity_id: &str,
562 ) -> Result<(CheckState, Option<CheckRecord>), EngineError> {
563 self.find_mount(mem_name)?;
564 let current_hash = self
565 .store
566 .all_entities()
567 .find(|e| e.mem == mem_name && e.id.0 == entity_id)
568 .map(|e| e.content_hash.clone())
569 .ok_or_else(|| self.not_found(entity_id))?;
570 let latest =
571 self.latest_check_record(mem_name, entity_id, CheckKind::Verification.as_str());
572 Ok((derive_state(latest.as_ref(), ¤t_hash), latest))
573 }
574
575 pub fn entity_conformance_state(
581 &self,
582 mem_name: &str,
583 entity_id: &str,
584 ) -> Result<(CheckState, Option<CheckRecord>), EngineError> {
585 let mount = self.find_mount(mem_name)?;
586 let current_pin = mount.mount.schema.as_ref().map(|s| s.as_display());
587 let current_hash = self
588 .store
589 .all_entities()
590 .find(|e| e.mem == mem_name && e.id.0 == entity_id)
591 .map(|e| e.content_hash.clone())
592 .ok_or_else(|| self.not_found(entity_id))?;
593 let latest = self.latest_check_record(mem_name, entity_id, CheckKind::Conformance.as_str());
594 Ok((
595 crate::check::derive_state_pinned(
596 latest.as_ref(),
597 ¤t_hash,
598 current_pin.as_deref(),
599 ),
600 latest,
601 ))
602 }
603}
604
605const STAMPED_TIMESTAMPS: &[&str] = &["created_date", "last_modified"];
608
609pub(crate) fn content_changed_beside(
614 before: &crate::entity::Entity,
615 next: &crate::entity::Entity,
616 field: &str,
617) -> Vec<String> {
618 let mut changed = Vec::new();
619 if before.entity_type != next.entity_type {
620 changed.push("type".to_string());
621 }
622 if before.title != next.title {
623 changed.push("title".to_string());
624 }
625 let mut keys: Vec<&String> = before.sections.keys().chain(next.sections.keys()).collect();
626 keys.sort();
627 keys.dedup();
628 for k in keys {
629 let norm = |s: Option<&String>| {
633 s.map(|b| b.trim_end_matches(['\n', '\r']).to_string())
634 .filter(|b| !b.is_empty())
635 };
636 if norm(before.sections.get(k)) != norm(next.sections.get(k)) {
637 changed.push(format!("section:{k}"));
638 }
639 }
640 let mut keys: Vec<&String> = before.metadata.keys().chain(next.metadata.keys()).collect();
641 keys.sort();
642 keys.dedup();
643 for k in keys {
644 if k == field || STAMPED_TIMESTAMPS.contains(&k.as_str()) {
645 continue;
646 }
647 let v = |m: &indexmap::IndexMap<String, crate::entity::MetadataValue>| {
648 m.get(k.as_str()).map(|v| v.to_frontmatter_string())
649 };
650 if v(&before.metadata) != v(&next.metadata) {
651 changed.push(format!("metadata:{k}"));
652 }
653 }
654 let edges = |e: &crate::entity::Entity| {
655 let mut r: Vec<(String, String)> = e
656 .relationships
657 .iter()
658 .map(|r| (r.rel_type.clone(), r.target.0.clone()))
659 .collect();
660 r.sort();
661 r.dedup();
662 r
663 };
664 if edges(before) != edges(next) {
665 changed.push("relationships".to_string());
666 }
667 changed
668}
669
670#[cfg(test)]
671mod tests {
672 use crate::check::{CheckKind, CheckLedger, CheckRecord, CheckState, Verdict};
673 use crate::vcs::Actor;
674 use crate::workspace::MountCapability;
675
676 #[test]
683 fn conformance_refuses_without_a_schema_pin() {
684 let tmp = tempfile::TempDir::new().unwrap();
685 std::fs::write(
686 tmp.path().join("anything.md"),
687 "---\nid: anything\ntitle: Anything\ntype: note\n---\n\nBody.\n",
688 )
689 .unwrap();
690 let mut mount = crate::engine::test_helpers::folder_mount("m", tmp.path().to_path_buf());
691 mount.schema = None;
692 let mut engine = crate::Engine::from_mounts(vec![(
693 mount,
694 Box::new(crate::storage::FilesystemBackend::new(
695 tmp.path().to_path_buf(),
696 )) as Box<dyn crate::backend::MemBackend>,
697 )])
698 .unwrap();
699 let err = engine
700 .record_check(
701 "m",
702 "m--anything",
703 Verdict::Ok,
704 CheckKind::Conformance,
705 None,
706 Actor::Cli,
707 None,
708 )
709 .unwrap_err();
710 assert_eq!(err.code(), "MEM_QUARANTINED");
711 }
712
713 fn self_check_gated_engine(tmp: &tempfile::TempDir, check_kind: &str) -> crate::Engine {
719 let schemas_dir = tmp.path().join(".memstead").join("schemas");
722 let pkg = schemas_dir.join("selfgate");
723 std::fs::create_dir_all(pkg.join("types")).unwrap();
724 std::fs::write(
725 pkg.join("schema.yaml"),
726 r#"name: selfgate
727version: 0.1.0
728description: self-check gate fixture
729when_to_use: tests
730types:
731 - plan
732 - memo
733relationships:
734 mode: strict
735 definitions:
736 - name: PART_OF
737 description: hier
738 default_weight: 3.0
739 - name: _default
740 description: fallback
741 default_weight: 1.0
742community:
743 resolution: 1.0
744 seed: 42
745"#,
746 )
747 .unwrap();
748 std::fs::write(
749 pkg.join("types").join("plan.yaml"),
750 format!(
751 r#"name: plan
752description: p
753when_to_use: tests
754sections:
755 - key: body
756 heading: Body
757 required: true
758 search_weight: 10.0
759 catch_all: true
760 write_rules: []
761metadata_fields:
762 - key: status
763 description: s
764 field_type: string
765 default_value: draft
766 enum_values: [draft, complete]
767 - key: remark
768 description: r
769 field_type: string
770 required: false
771title_weight: 100.0
772text_fields:
773 - body
774hierarchy_relationship: PART_OF
775updatable_fields:
776 - title
777 - body
778 - status
779 - remark
780health_required_fields: []
781staleness_threshold_days: 90
782constraints:
783 - kind: transition_requires_self_check
784 field: status
785 to_value: complete
786 check_kind: {check_kind}
787 severity: block
788write_rules: []
789"#
790 ),
791 )
792 .unwrap();
793 let plan_yaml = std::fs::read_to_string(pkg.join("types").join("plan.yaml")).unwrap();
795 let cut = plan_yaml.find("constraints:").unwrap();
796 let memo_yaml =
797 plan_yaml[..cut].replacen("name: plan", "name: memo", 1) + "write_rules: []\n";
798 std::fs::write(pkg.join("types").join("memo.yaml"), memo_yaml).unwrap();
799 let mem_dir = tmp.path().join("bundles");
800 std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
801 std::fs::write(
802 mem_dir.join(".memstead").join("config.json"),
803 r#"{"format": 1, "schema": "selfgate@0.1.0", "version": "1.0.0"}"#,
804 )
805 .unwrap();
806 let writer = crate::storage::FilesystemBackend::new(mem_dir.clone());
807 let mount = crate::workspace::Mount {
808 mem: "bundles".to_string(),
809 schema: Some(memstead_schema::SchemaRef::new(
810 "selfgate",
811 semver::Version::new(0, 1, 0),
812 )),
813 storage: crate::workspace::MountStorage::Folder { path: mem_dir },
814 capability: crate::workspace::MountCapability::Write,
815 lifecycle: crate::workspace::MountLifecycle::Eager,
816 cross_linkable: true,
817 migration_target: None,
818 };
819 let mut engine = crate::Engine::from_mounts_with_schemas_dir(
820 vec![(
821 mount,
822 Box::new(writer) as Box<dyn crate::backend::MemBackend>,
823 )],
824 Some(&schemas_dir),
825 )
826 .unwrap();
827 engine.set_workspace_root(tmp.path().to_path_buf());
828 engine
829 }
830
831 fn create_plan(engine: &mut crate::Engine, title: &str) -> crate::entity::EntityId {
832 let (actor, client) = crate::engine::test_helpers::cli_actor();
833 let mut sections = indexmap::IndexMap::new();
834 sections.insert("body".to_string(), "the plan body.".to_string());
835 engine
836 .create_entity(
837 crate::engine::CreateEntityArgs {
838 anchors: Vec::new(),
839 mem: "bundles".to_string(),
840 title: title.to_string(),
841 entity_type: "plan".to_string(),
842 sections,
843 metadata: indexmap::IndexMap::new(),
844 relations: Vec::new(),
845 dry_run: false,
846 },
847 actor,
848 Some(&client),
849 None,
850 )
851 .unwrap()
852 .id
853 }
854
855 fn set_status(
856 engine: &mut crate::Engine,
857 id: &crate::entity::EntityId,
858 value: &str,
859 ) -> Result<crate::engine::UpdateEntityOutcome, crate::engine::error::EngineError> {
860 let (actor, client) = crate::engine::test_helpers::cli_actor();
861 let current = engine.get_entity(id).unwrap().content_hash.clone();
862 let mut metadata = indexmap::IndexMap::new();
863 metadata.insert("status".to_string(), value.to_string());
864 engine.update_entity(
865 crate::engine::UpdateEntityArgs {
866 anchors: Vec::new(),
867 id: id.clone(),
868 expected_hash: crate::ExpectedHash::Current(current),
869 sections: indexmap::IndexMap::new(),
870 append_sections: indexmap::IndexMap::new(),
871 patch_sections: indexmap::IndexMap::new(),
872 sections_unset: Vec::new(),
873 metadata,
874 metadata_unset: Vec::new(),
875 declare_relations: vec![],
876 dry_run: false,
877 relations_unset: Vec::new(),
878 anchors_unset: Vec::new(),
879 },
880 actor,
881 Some(&client),
882 None,
883 )
884 }
885
886 fn update(
888 engine: &mut crate::Engine,
889 id: &crate::entity::EntityId,
890 meta: Option<(&str, &str)>,
891 body: Option<&str>,
892 ) -> Result<crate::engine::UpdateEntityOutcome, crate::engine::error::EngineError> {
893 let (actor, client) = crate::engine::test_helpers::cli_actor();
894 let current = engine.get_entity(id).unwrap().content_hash.clone();
895 let mut metadata = indexmap::IndexMap::new();
896 if let Some((k, v)) = meta {
897 metadata.insert(k.to_string(), v.to_string());
898 }
899 let mut sections = indexmap::IndexMap::new();
900 if let Some(b) = body {
901 sections.insert("body".to_string(), b.to_string());
902 }
903 engine.update_entity(
904 crate::engine::UpdateEntityArgs {
905 anchors: Vec::new(),
906 id: id.clone(),
907 expected_hash: crate::ExpectedHash::Current(current),
908 sections,
909 append_sections: indexmap::IndexMap::new(),
910 patch_sections: indexmap::IndexMap::new(),
911 sections_unset: Vec::new(),
912 metadata,
913 metadata_unset: Vec::new(),
914 declare_relations: vec![],
915 dry_run: false,
916 relations_unset: Vec::new(),
917 anchors_unset: Vec::new(),
918 },
919 actor,
920 Some(&client),
921 None,
922 )
923 }
924
925 fn append_body(engine: &mut crate::Engine, id: &crate::entity::EntityId) {
926 let (actor, client) = crate::engine::test_helpers::cli_actor();
927 let current = engine.get_entity(id).unwrap().content_hash.clone();
928 let mut append = indexmap::IndexMap::new();
929 append.insert("body".to_string(), "more.".to_string());
930 engine
931 .update_entity(
932 crate::engine::UpdateEntityArgs {
933 anchors: Vec::new(),
934 id: id.clone(),
935 expected_hash: crate::ExpectedHash::Current(current),
936 sections: indexmap::IndexMap::new(),
937 append_sections: append,
938 patch_sections: indexmap::IndexMap::new(),
939 sections_unset: Vec::new(),
940 metadata: indexmap::IndexMap::new(),
941 metadata_unset: Vec::new(),
942 declare_relations: vec![],
943 dry_run: false,
944 relations_unset: Vec::new(),
945 anchors_unset: Vec::new(),
946 },
947 actor,
948 Some(&client),
949 None,
950 )
951 .unwrap();
952 }
953
954 fn check_plan(
955 engine: &mut crate::Engine,
956 identity: &str,
957 id: &crate::entity::EntityId,
958 kind: &str,
959 ) {
960 check_plan_as(engine, identity, crate::vcs::Role::Checker, id, kind);
961 }
962
963 fn check_plan_as(
967 engine: &mut crate::Engine,
968 identity: &str,
969 role: crate::vcs::Role,
970 id: &crate::entity::EntityId,
971 kind: &str,
972 ) {
973 let (actor, client) = crate::engine::test_helpers::cli_actor();
974 engine.set_identity(Some(identity.to_string()));
975 engine.set_role(role);
976 engine
977 .record_check_with(
978 "bundles",
979 id.as_ref(),
980 Verdict::Ok,
981 &crate::check::RecordKind::from_wire(kind).unwrap(),
982 Some("projection walked"),
983 None,
984 None,
985 actor,
986 Some(&client),
987 )
988 .unwrap();
989 engine.set_role(crate::vcs::Role::Unspecified);
990 }
991
992 #[test]
1006 fn a_conformance_self_check_gate_closes_on_a_fresh_record() {
1007 let tmp = tempfile::TempDir::new().unwrap();
1008 let mut engine = self_check_gated_engine(&tmp, "conformance");
1009 engine.set_identity(Some("author-a".to_string()));
1010 let id = create_plan(&mut engine, "The Bundle");
1011 let entity = engine.get_entity(&id).unwrap().clone();
1012 let standing = (engine.check_standing_provider())(&entity, "conformance");
1013 assert_eq!(standing.state, CheckState::NeverChecked);
1014
1015 check_plan(&mut engine, "checker-c", &id, "conformance");
1016 let entity = engine.get_entity(&id).unwrap().clone();
1017 let standing = (engine.check_standing_provider())(&entity, "conformance");
1018 assert_eq!(standing.state, CheckState::CheckedOk, "{standing:?}");
1019 assert!(standing.confirms(), "{standing:?}");
1020
1021 engine.set_identity(Some("author-a".to_string()));
1022 set_status(&mut engine, &id, "complete").expect("the gate admits the write");
1023 assert!(engine.constraint_findings(Some("bundles")).is_empty());
1024 }
1025
1026 #[test]
1027 fn licensing_self_check_carries_across_the_transition_it_admitted() {
1028 let tmp = tempfile::TempDir::new().unwrap();
1029 let mut engine = self_check_gated_engine(&tmp, "x-projection");
1030 engine.set_identity(Some("author-a".to_string()));
1031 let id = create_plan(&mut engine, "The Bundle");
1032 let hash_at_check = engine.get_entity(&id).unwrap().content_hash.clone();
1033 check_plan(&mut engine, "checker-c", &id, "x-projection");
1034
1035 engine.set_identity(Some("author-a".to_string()));
1036 let outcome = set_status(&mut engine, &id, "complete").expect("the gate admits the write");
1037 assert_ne!(
1038 outcome.content_hash, hash_at_check,
1039 "the write moved the hash"
1040 );
1041
1042 let findings = engine.constraint_findings(Some("bundles"));
1044 assert!(findings.is_empty(), "{findings:?}");
1045
1046 let foreign = engine.latest_foreign_checks("bundles", id.as_ref());
1048 assert_eq!(foreign.len(), 1);
1049 let carried = &foreign[0];
1050 assert_eq!(carried.entity_hash, outcome.content_hash);
1051 assert_eq!(carried.identity.as_deref(), Some("checker-c"));
1052 assert_eq!(carried.method.as_deref(), Some("projection walked"));
1053 assert_eq!(
1054 carried.carried_from,
1055 Some(crate::check::CarriedFrom::transition(&hash_at_check))
1056 );
1057 let entity = engine.get_entity(&id).unwrap().clone();
1059 let standing = (engine.check_standing_provider())(&entity, "x-projection");
1060 assert!(standing.confirms(), "{standing:?}");
1061 let ledger = CheckLedger::for_workspace(tmp.path());
1063 let lines: Vec<CheckRecord> = ledger
1064 .in_standing_order()
1065 .into_iter()
1066 .filter(|r| r.entity == id.as_ref())
1067 .collect();
1068 assert_eq!(lines.len(), 2);
1069 assert!(lines[0].carried_from.is_none());
1070 assert_eq!(lines[0].entity_hash, hash_at_check);
1071
1072 engine.set_identity(Some("author-a".to_string()));
1077 let lines_before = ledger.in_standing_order().len();
1078 append_body(&mut engine, &id);
1079 assert_eq!(
1080 ledger.in_standing_order().len(),
1081 lines_before,
1082 "nothing carried"
1083 );
1084 let stale = &engine.latest_foreign_checks("bundles", id.as_ref())[0];
1085 assert_ne!(
1086 stale.entity_hash,
1087 engine.get_entity(&id).unwrap().content_hash,
1088 "the approval stays keyed to the content it approved"
1089 );
1090 let findings = engine.constraint_findings(Some("bundles"));
1091 assert_eq!(findings.len(), 1, "{findings:?}");
1092 check_plan(&mut engine, "checker-c", &id, "x-projection");
1093 assert!(engine.constraint_findings(Some("bundles")).is_empty());
1094 set_status(&mut engine, &id, "draft").unwrap();
1097 let before = ledger.in_standing_order().len();
1098 append_body(&mut engine, &id);
1099 assert_eq!(
1100 ledger.in_standing_order().len(),
1101 before,
1102 "no gate passed, nothing carried"
1103 );
1104 }
1105
1106 #[test]
1115 fn an_approval_does_not_outlive_an_edit_of_what_it_approved() {
1116 for kind in ["x-projection", "verification"] {
1117 let tmp = tempfile::TempDir::new().unwrap();
1118 let mut engine = self_check_gated_engine(&tmp, kind);
1119 engine.set_identity(Some("author-a".to_string()));
1120 let id = create_plan(&mut engine, "The Bundle");
1121 let ledger = CheckLedger::for_workspace(tmp.path());
1122
1123 check_plan(&mut engine, "checker-c", &id, kind);
1125 engine.set_identity(Some("author-a".to_string()));
1126 let stored = engine.get_entity(&id).unwrap().content_hash.clone();
1127 let lines = ledger.in_standing_order().len();
1128 let err = update(
1129 &mut engine,
1130 &id,
1131 Some(("status", "complete")),
1132 Some("rewritten."),
1133 )
1134 .expect_err("a self-check transition write may change nothing else");
1135 assert_eq!(err.code(), "CONSTRAINT_UNSATISFIED", "{kind}");
1136 let msg = err.to_string();
1137 assert!(msg.contains("transition_requires_self_check"), "{msg}");
1138 assert!(msg.contains("section:body"), "{msg}");
1139 assert_eq!(engine.get_entity(&id).unwrap().content_hash, stored);
1140 assert_eq!(ledger.in_standing_order().len(), lines);
1141
1142 set_status(&mut engine, &id, "complete").expect("the gate admits the write");
1144 let entity = engine.get_entity(&id).unwrap().clone();
1145 assert!((engine.check_standing_provider())(&entity, kind).confirms());
1146 assert!(engine.constraint_findings(Some("bundles")).is_empty());
1147
1148 for edit in [
1149 (None, Some("a section edit.")),
1150 (Some(("remark", "noted")), None),
1151 ] {
1152 let lines = ledger.in_standing_order().len();
1153 update(&mut engine, &id, edit.0, edit.1).expect("an edit is not a transition");
1154 assert_eq!(
1155 ledger.in_standing_order().len(),
1156 lines,
1157 "{kind}: nothing carried"
1158 );
1159 let entity = engine.get_entity(&id).unwrap().clone();
1160 let standing = (engine.check_standing_provider())(&entity, kind);
1161 assert_eq!(standing.label(), "check_stale", "{kind}");
1162 let findings = engine.constraint_findings(Some("bundles"));
1163 assert_eq!(findings.len(), 1, "{kind}: {findings:?}");
1164 check_plan(&mut engine, "checker-c", &id, kind);
1165 engine.set_identity(Some("author-a".to_string()));
1166 assert!(
1167 engine.constraint_findings(Some("bundles")).is_empty(),
1168 "{kind}"
1169 );
1170 }
1171 }
1172 }
1173
1174 #[test]
1179 fn carried_verification_record_reads_checked_ok_and_independent() {
1180 let tmp = tempfile::TempDir::new().unwrap();
1181 let mut engine = self_check_gated_engine(&tmp, "verification");
1182 engine.set_identity(Some("author-a".to_string()));
1183 let id = create_plan(&mut engine, "The Bundle");
1184 check_plan(&mut engine, "checker-c", &id, "verification");
1185 engine.set_identity(Some("author-a".to_string()));
1186 set_status(&mut engine, &id, "complete").expect("the gate admits the write");
1187
1188 let (state, latest) = engine.entity_check_state("bundles", id.as_ref()).unwrap();
1189 assert_eq!(state, CheckState::CheckedOk);
1190 let latest = latest.unwrap();
1191 assert_eq!(latest.identity.as_deref(), Some("checker-c"));
1192 assert!(latest.carried_from.is_some());
1193 let axis = crate::ops::health::health_checks_axis(&engine, Some("bundles"));
1194 let independence = &axis["bundles"]["independence"];
1195 assert_eq!(
1196 independence["confirmed_independent"]["items"],
1197 serde_json::json!([id.as_ref()]),
1198 "{axis}"
1199 );
1200 assert_eq!(
1201 axis["bundles"]["checked_ok"],
1202 serde_json::json!(1),
1203 "{axis}"
1204 );
1205 assert!(engine.constraint_findings(Some("bundles")).is_empty());
1206 }
1207
1208 #[test]
1217 fn a_record_in_role_author_or_without_a_role_does_not_close_the_gate() {
1218 let tmp = tempfile::TempDir::new().unwrap();
1219 let mut engine = self_check_gated_engine(&tmp, "verification");
1220 engine.set_identity(Some("author-a".to_string()));
1221 let id = create_plan(&mut engine, "The Bundle");
1222
1223 check_plan_as(
1225 &mut engine,
1226 "checker-c",
1227 crate::vcs::Role::Author,
1228 &id,
1229 "verification",
1230 );
1231 let standing =
1232 (engine.check_standing_provider())(engine.get_entity(&id).unwrap(), "verification");
1233 assert_eq!(standing.state, CheckState::CheckedOk);
1234 assert_eq!(
1235 standing.independence,
1236 Some(crate::engine::independence::Independence::ConfirmedIndependent)
1237 );
1238 assert!(!standing.confirms(), "{standing:?}");
1239 assert_eq!(standing.label(), "role_author");
1240 engine.set_identity(Some("author-a".to_string()));
1241 let err = set_status(&mut engine, &id, "complete").unwrap_err();
1242 assert_eq!(err.code(), "CONSTRAINT_UNSATISFIED", "{err}");
1243 assert!(err.to_string().contains("role_author"), "{err}");
1244 let axis = crate::ops::health::health_checks_axis(&engine, Some("bundles"));
1245 let row = axis["bundles"]["independence"]["readings"][id.as_ref()]
1246 .as_array()
1247 .unwrap()
1248 .last()
1249 .unwrap();
1250 assert_eq!(row["reading"], "confirmed_independent", "{axis}");
1251 assert_eq!(row["role"], "author", "{axis}");
1252 assert_eq!(row["role_confirms"], false, "{axis}");
1253
1254 check_plan_as(
1256 &mut engine,
1257 "checker-c",
1258 crate::vcs::Role::Unspecified,
1259 &id,
1260 "verification",
1261 );
1262 let standing =
1263 (engine.check_standing_provider())(engine.get_entity(&id).unwrap(), "verification");
1264 assert!(!standing.confirms(), "{standing:?}");
1265 assert_eq!(standing.label(), "role_unspecified");
1266 engine.set_identity(Some("author-a".to_string()));
1267 let err = set_status(&mut engine, &id, "complete").unwrap_err();
1268 assert!(err.to_string().contains("role_unspecified"), "{err}");
1269
1270 check_plan_as(
1272 &mut engine,
1273 "verifier-v",
1274 crate::vcs::Role::Verifier,
1275 &id,
1276 "verification",
1277 );
1278 let standing =
1279 (engine.check_standing_provider())(engine.get_entity(&id).unwrap(), "verification");
1280 assert!(standing.confirms(), "{standing:?}");
1281 engine.set_identity(Some("author-a".to_string()));
1282 set_status(&mut engine, &id, "complete").expect("a verifier's record closes the gate");
1283 let axis = crate::ops::health::health_checks_axis(&engine, Some("bundles"));
1284 let row = axis["bundles"]["independence"]["readings"][id.as_ref()]
1285 .as_array()
1286 .unwrap()
1287 .last()
1288 .unwrap();
1289 assert_eq!(row["role"], "verifier", "{axis}");
1290 assert_eq!(row["role_confirms"], true, "{axis}");
1291 }
1292
1293 #[test]
1301 fn sealed_independence_holds_the_transition_gate_on_the_archive_mount() {
1302 let tmp = tempfile::TempDir::new().unwrap();
1303 let mut engine = self_check_gated_engine(&tmp, "verification");
1304 engine.set_identity(Some("author-a".to_string()));
1305 let id = create_plan(&mut engine, "The Bundle");
1306 check_plan(&mut engine, "checker-c", &id, "verification");
1307 engine.set_identity(Some("author-a".to_string()));
1308 set_status(&mut engine, &id, "complete").expect("the gate admits the write");
1309 assert!(engine.constraint_findings(Some("bundles")).is_empty());
1310
1311 let bytes = engine.export_mem_to_bytes("bundles").unwrap();
1312 let mounted = crate::Engine::from_archive_bytes(bytes).unwrap();
1313 assert!(mounted.is_archive_mount("bundles"));
1314 let findings = mounted.constraint_findings(Some("bundles"));
1315 assert!(findings.is_empty(), "{findings:?}");
1316 let entity = mounted.get_entity(&id).unwrap();
1317 let standing = (mounted.check_standing_provider())(entity, "verification");
1318 assert!(standing.confirms(), "{standing:?}");
1319 let axis = crate::ops::health::health_checks_axis(&mounted, Some("bundles"));
1320 assert_eq!(
1321 axis["bundles"]["independence"]["confirmed_independent"]["items"],
1322 serde_json::json!([id.as_ref()]),
1323 "{axis}"
1324 );
1325 assert_eq!(
1326 axis["bundles"]["checked_ok"],
1327 serde_json::json!(1),
1328 "{axis}"
1329 );
1330 }
1331
1332 #[test]
1335 fn stale_self_check_is_not_carried_and_the_write_refuses() {
1336 let tmp = tempfile::TempDir::new().unwrap();
1337 let mut engine = self_check_gated_engine(&tmp, "x-projection");
1338 engine.set_identity(Some("author-a".to_string()));
1339 let id = create_plan(&mut engine, "The Bundle");
1340 check_plan(&mut engine, "checker-c", &id, "x-projection");
1341 engine.set_identity(Some("author-a".to_string()));
1343 append_body(&mut engine, &id);
1344 let before = CheckLedger::for_workspace(tmp.path())
1345 .in_standing_order()
1346 .len();
1347 let err = set_status(&mut engine, &id, "complete").unwrap_err();
1348 assert_eq!(err.code(), "CONSTRAINT_UNSATISFIED");
1349 assert!(err.to_string().contains("check_stale"), "{err}");
1350 assert_eq!(
1351 CheckLedger::for_workspace(tmp.path())
1352 .in_standing_order()
1353 .len(),
1354 before
1355 );
1356 assert_ne!(
1357 engine
1358 .get_entity(&id)
1359 .unwrap()
1360 .metadata
1361 .get("status")
1362 .map(|v| v.to_frontmatter_string())
1363 .as_deref(),
1364 Some("complete"),
1365 "the refused write left the entity as it was"
1366 );
1367 }
1368
1369 #[test]
1379 fn every_reader_stands_on_the_newest_act_not_the_last_line() {
1380 let tmp = tempfile::TempDir::new().unwrap();
1381 let mut engine = self_check_gated_engine(&tmp, "x-projection");
1382 engine.set_identity(Some("author-a".to_string()));
1383 let id = create_plan(&mut engine, "The Bundle");
1384 let hash = engine.get_entity(&id).unwrap().content_hash.clone();
1385 let ledger = CheckLedger::for_workspace(tmp.path());
1386 let base = std::time::SystemTime::now()
1389 .duration_since(std::time::UNIX_EPOCH)
1390 .unwrap()
1391 .as_secs()
1392 + 2;
1393 let row = |verdict: &str, kind: Option<&str>, ts: u64| CheckRecord {
1394 ts,
1395 observed_at: None,
1396 entity: id.as_ref().to_string(),
1397 verdict: verdict.to_string(),
1398 method: None,
1399 entity_hash: hash.clone(),
1400 actor: "cli".to_string(),
1401 client: None,
1402 role: "checker".to_string(),
1403 identity: Some("checker-c".to_string()),
1404 kind: kind.map(str::to_string),
1405 schema_ref: None,
1406 finding: None,
1407 renamed_from: None,
1408 carried_from: None,
1409 checked_write: None,
1410 };
1411 ledger.record(&row("ok", None, base + 20)).unwrap();
1413 ledger
1414 .record(&row("ok", Some("x-projection"), base + 20))
1415 .unwrap();
1416 ledger.record(&row("failed", None, base + 10)).unwrap();
1417 ledger
1418 .record(&row("failed", Some("x-projection"), base + 10))
1419 .unwrap();
1420
1421 let (state, latest) = engine.entity_check_state("bundles", id.as_ref()).unwrap();
1422 assert_eq!(state, crate::check::CheckState::CheckedOk);
1423 assert_eq!(latest.unwrap().ts, base + 20);
1424 let foreign = engine.latest_foreign_checks("bundles", id.as_ref());
1425 assert_eq!(foreign[0].verdict, "ok");
1426 let entity = engine.get_entity(&id).unwrap().clone();
1427 assert!((engine.check_standing_provider())(&entity, "x-projection").confirms());
1428 let axis = crate::ops::health::health_checks_axis(&engine, Some("bundles"));
1429 assert_eq!(axis["bundles"]["checked_ok"], 1, "{axis}");
1430 assert_eq!(axis["bundles"]["check_failed"], 0, "{axis}");
1431 let (sealed, _) = crate::ops::export::sealed_checks_bytes_for(
1432 Some(tmp.path()),
1433 "bundles",
1434 &[id.path().to_string()],
1435 None,
1436 );
1437 let sealed = crate::check::SealedChecks::from_archive_bytes(&sealed.unwrap()).unwrap();
1438 assert_eq!(
1439 sealed.latest(id.path(), "verification").unwrap().verdict,
1440 "ok"
1441 );
1442 assert_eq!(
1443 sealed.latest(id.path(), "x-projection").unwrap().verdict,
1444 "ok"
1445 );
1446 set_status(&mut engine, &id, "complete").expect("the newest act confirms");
1449 assert!(engine.constraint_findings(Some("bundles")).is_empty());
1450
1451 let post = engine.get_entity(&id).unwrap().content_hash.clone();
1453 ledger
1454 .record(&CheckRecord {
1455 entity_hash: post,
1456 ..row("failed", Some("x-projection"), base + 30)
1457 })
1458 .unwrap();
1459 let entity = engine.get_entity(&id).unwrap().clone();
1460 assert!(!(engine.check_standing_provider())(&entity, "x-projection").confirms());
1461 assert!(!engine.constraint_findings(Some("bundles")).is_empty());
1462 }
1463
1464 #[test]
1470 fn conflict_resolution_lands_a_self_check_gated_value_only_on_a_record_of_its_bytes() {
1471 let tmp = tempfile::TempDir::new().unwrap();
1472 let mut engine = self_check_gated_engine(&tmp, "x-projection");
1473 engine.set_identity(Some("author-a".to_string()));
1474 let id = create_plan(&mut engine, "The Bundle");
1475 check_plan(&mut engine, "checker-c", &id, "x-projection");
1476 engine.set_identity(Some("author-a".to_string()));
1477 set_status(&mut engine, &id, "complete").unwrap();
1478 let path = tmp.path().join("bundles").join("the-bundle.md");
1479 let checked = std::fs::read_to_string(&path).unwrap();
1480 let edited = checked.replace("the plan body.", "an edit nobody checked.");
1481 assert_ne!(edited, checked);
1482 let conflicted = format!(
1483 "<<<<<<< ours\n{}=======\n{}>>>>>>> theirs\n",
1484 edited, checked
1485 );
1486 let ledger = CheckLedger::for_workspace(tmp.path());
1487 let (actor, client) = crate::engine::test_helpers::cli_actor();
1488
1489 std::fs::write(&path, &conflicted).unwrap();
1490 let lines = ledger.in_standing_order().len();
1491 let err = engine
1492 .resolve_merge_conflict(
1493 &id,
1494 crate::engine::conflicts::ConflictSide::Ours,
1495 actor,
1496 Some(&client),
1497 None,
1498 )
1499 .expect_err("the edited side was never checked");
1500 assert_eq!(err.code(), "CONSTRAINT_UNSATISFIED", "{err}");
1501 assert_eq!(std::fs::read_to_string(&path).unwrap(), conflicted);
1502 assert_eq!(ledger.in_standing_order().len(), lines);
1503
1504 engine
1505 .resolve_merge_conflict(
1506 &id,
1507 crate::engine::conflicts::ConflictSide::Theirs,
1508 actor,
1509 Some(&client),
1510 None,
1511 )
1512 .expect("the checked side lands");
1513 assert_eq!(std::fs::read_to_string(&path).unwrap(), checked);
1514 }
1515
1516 #[test]
1521 fn a_rename_keeps_every_writer_in_the_story_on_folder() {
1522 let tmp = tempfile::TempDir::new().unwrap();
1523 let mut engine = self_check_gated_engine(&tmp, "x-projection");
1524 engine.set_identity(Some("identity-a".to_string()));
1525 let id = create_plan(&mut engine, "The Bundle");
1526 engine.set_identity(Some("identity-b".to_string()));
1527 update(&mut engine, &id, None, Some("rewritten by b.")).unwrap();
1528 engine.set_identity(Some("identity-c".to_string()));
1529 let (actor, client) = crate::engine::test_helpers::cli_actor();
1530 let current = engine.get_entity(&id).unwrap().content_hash.clone();
1531 let out = engine
1532 .rename_entity(
1533 crate::engine::RenameEntityArgs {
1534 id: id.clone(),
1535 expected_hash: crate::ExpectedHash::Current(current),
1536 new_title: "The Renamed".to_string(),
1537 },
1538 actor,
1539 Some(&client),
1540 None,
1541 )
1542 .unwrap();
1543 let new_id = out.new_id.clone();
1544 eprintln!(
1545 "story {:?}",
1546 engine.mem_touches("bundles").story(new_id.as_ref())
1547 );
1548 check_plan(&mut engine, "identity-b", &new_id, "x-projection");
1549 let touches = engine.mem_touches("bundles");
1550 let entity = engine.get_entity(&new_id).unwrap().clone();
1551 let standing = (engine.check_standing_provider())(&entity, "x-projection");
1552 let first = touches.first_author(new_id.as_ref()).map(str::to_string);
1553 engine.set_identity(Some("identity-e".to_string()));
1554 let gate = set_status(&mut engine, &new_id, "complete");
1555 assert_eq!(
1556 (standing.label(), first.as_deref(), gate.is_err()),
1557 ("self_checked", Some("identity-a"), true)
1558 );
1559 }
1560
1561 #[test]
1573 fn independence_counts_every_identity_that_wrote_what_was_checked_on_folder() {
1574 for pause in [true, false] {
1575 let tmp = tempfile::TempDir::new().unwrap();
1576 let mut engine = self_check_gated_engine(&tmp, "x-projection");
1577 engine.set_identity(Some("identity-a".to_string()));
1578 let id = create_plan(&mut engine, "The Bundle");
1579 if pause {
1580 std::thread::sleep(std::time::Duration::from_millis(1100));
1581 }
1582 engine.set_identity(Some("identity-b".to_string()));
1583 update(&mut engine, &id, None, Some("rewritten by b.")).unwrap();
1584 check_plan(&mut engine, "identity-b", &id, "x-projection");
1585 let touches = engine.mem_touches("bundles");
1586 assert_eq!(
1587 touches.first_author(id.as_ref()),
1588 Some("identity-a"),
1589 "pause {pause}"
1590 );
1591 let entity = engine.get_entity(&id).unwrap().clone();
1592 let standing = (engine.check_standing_provider())(&entity, "x-projection");
1593 assert_eq!(standing.label(), "self_checked", "pause {pause}");
1594 engine.set_identity(Some("identity-c".to_string()));
1595 let err =
1596 set_status(&mut engine, &id, "complete").expect_err("b checked its own writing");
1597 assert_eq!(err.code(), "CONSTRAINT_UNSATISFIED");
1598
1599 check_plan(&mut engine, "identity-d", &id, "x-projection");
1600 engine.set_identity(Some("identity-d".to_string()));
1601 set_status(&mut engine, &id, "complete").expect("d wrote nothing it checked");
1602 let entity = engine.get_entity(&id).unwrap().clone();
1603 let standing = (engine.check_standing_provider())(&entity, "x-projection");
1604 assert_eq!(standing.label(), "confirmed_independent", "pause {pause}");
1605 let carried = &engine.latest_foreign_checks("bundles", id.as_ref())[0];
1606 assert!(carried.carried_from.is_some());
1607 assert_eq!(carried.identity.as_deref(), Some("identity-d"));
1608 }
1609
1610 let tmp = tempfile::TempDir::new().unwrap();
1612 let mut engine = self_check_gated_engine(&tmp, "x-projection");
1613 engine.set_identity(Some("identity-a".to_string()));
1614 let id = create_plan(&mut engine, "The Bundle");
1615 engine.set_identity(Some("identity-d".to_string()));
1616 update(&mut engine, &id, None, Some("rewritten by d.")).unwrap();
1617 check_plan(&mut engine, "identity-d", &id, "x-projection");
1618 let entity = engine.get_entity(&id).unwrap().clone();
1619 assert_eq!(
1620 (engine.check_standing_provider())(&entity, "x-projection").label(),
1621 "self_checked"
1622 );
1623
1624 let tmp = tempfile::TempDir::new().unwrap();
1626 let mut engine = self_check_gated_engine(&tmp, "x-projection");
1627 engine.set_identity(Some("identity-a".to_string()));
1628 let id = create_plan(&mut engine, "The Bundle");
1629 engine.set_identity(None);
1630 update(&mut engine, &id, None, Some("anonymous edit.")).unwrap();
1631 check_plan(&mut engine, "identity-d", &id, "x-projection");
1632 let entity = engine.get_entity(&id).unwrap().clone();
1633 assert_eq!(
1634 (engine.check_standing_provider())(&entity, "x-projection").label(),
1635 "unconfirmable"
1636 );
1637
1638 let tmp = tempfile::TempDir::new().unwrap();
1641 let mut engine = self_check_gated_engine(&tmp, "x-projection");
1642 engine.set_identity(Some("identity-a".to_string()));
1643 let id = create_plan(&mut engine, "The Bundle");
1644 let entity = engine.get_entity(&id).unwrap().clone();
1645 let touches = engine.mem_touches("bundles");
1646 let legacy = |identity: &str, ts: u64| CheckRecord {
1647 ts,
1648 observed_at: None,
1649 entity: id.as_ref().to_string(),
1650 verdict: "ok".to_string(),
1651 method: None,
1652 entity_hash: entity.content_hash.clone(),
1653 actor: "cli".to_string(),
1654 client: None,
1655 role: "checker".to_string(),
1656 identity: Some(identity.to_string()),
1657 kind: Some("x-projection".to_string()),
1658 schema_ref: None,
1659 finding: None,
1660 renamed_from: None,
1661 carried_from: None,
1662 checked_write: None,
1663 };
1664 let now = std::time::SystemTime::now()
1665 .duration_since(std::time::UNIX_EPOCH)
1666 .unwrap()
1667 .as_secs();
1668 let (r, _) = engine.independence_of(&entity, &legacy("identity-a", now + 5), &touches);
1669 assert_eq!(r, crate::engine::independence::Independence::SelfChecked);
1670 let (r, _) = engine.independence_of(&entity, &legacy("identity-d", now + 5), &touches);
1671 assert_eq!(
1672 r,
1673 crate::engine::independence::Independence::ConfirmedIndependent
1674 );
1675 let (r, _) = engine.independence_of(&entity, &legacy("identity-d", 1), &touches);
1676 assert_eq!(
1677 r,
1678 crate::engine::independence::Independence::Unconfirmable,
1679 "no write at or before the line's ts"
1680 );
1681 }
1682
1683 fn create_args(title: &str, ty: &str, status: Option<&str>) -> crate::engine::CreateEntityArgs {
1684 let mut sections = indexmap::IndexMap::new();
1685 sections.insert("body".to_string(), "the plan body.".to_string());
1686 let mut metadata = indexmap::IndexMap::new();
1687 if let Some(v) = status {
1688 metadata.insert("status".to_string(), v.to_string());
1689 }
1690 crate::engine::CreateEntityArgs {
1691 anchors: Vec::new(),
1692 mem: "bundles".to_string(),
1693 title: title.to_string(),
1694 entity_type: ty.to_string(),
1695 sections,
1696 metadata,
1697 relations: Vec::new(),
1698 dry_run: false,
1699 }
1700 }
1701
1702 fn update_args(
1703 engine: &crate::Engine,
1704 id: &crate::entity::EntityId,
1705 status: Option<&str>,
1706 body: Option<&str>,
1707 ) -> crate::engine::UpdateEntityArgs {
1708 let mut metadata = indexmap::IndexMap::new();
1709 if let Some(v) = status {
1710 metadata.insert("status".to_string(), v.to_string());
1711 }
1712 let mut sections = indexmap::IndexMap::new();
1713 if let Some(b) = body {
1714 sections.insert("body".to_string(), b.to_string());
1715 }
1716 crate::engine::UpdateEntityArgs {
1717 anchors: Vec::new(),
1718 id: id.clone(),
1719 expected_hash: crate::ExpectedHash::Current(
1720 engine.get_entity(id).unwrap().content_hash.clone(),
1721 ),
1722 sections,
1723 append_sections: indexmap::IndexMap::new(),
1724 patch_sections: indexmap::IndexMap::new(),
1725 sections_unset: Vec::new(),
1726 metadata,
1727 metadata_unset: Vec::new(),
1728 declare_relations: vec![],
1729 dry_run: false,
1730 relations_unset: Vec::new(),
1731 anchors_unset: Vec::new(),
1732 }
1733 }
1734
1735 #[test]
1743 fn the_self_check_column_of_the_verb_table() {
1744 let tmp = tempfile::TempDir::new().unwrap();
1745 let mut engine = self_check_gated_engine(&tmp, "x-projection");
1746 engine.set_identity(Some("author-a".to_string()));
1747 let ledger = CheckLedger::for_workspace(tmp.path());
1748 let (actor, client) = crate::engine::test_helpers::cli_actor();
1749 let files = |tmp: &tempfile::TempDir| {
1750 let mut v: Vec<_> = std::fs::read_dir(tmp.path().join("bundles"))
1751 .unwrap()
1752 .map(|e| e.unwrap().file_name())
1753 .collect();
1754 v.sort();
1755 v
1756 };
1757 let before = files(&tmp);
1758
1759 let err = engine
1760 .create_entity(
1761 create_args("Born Done", "plan", Some("complete")),
1762 actor,
1763 Some(&client),
1764 None,
1765 )
1766 .expect_err("create");
1767 assert_eq!(err.code(), "CONSTRAINT_UNSATISFIED");
1768 let batch = engine.batch_create(
1769 vec![(create_args("Born Done Too", "plan", Some("complete")), None)],
1770 actor,
1771 Some(&client),
1772 false,
1773 );
1774 assert!(
1775 batch.as_ref().is_err() || !batch.as_ref().unwrap().applied,
1776 "batch create must not land the gated value: {batch:?}"
1777 );
1778 assert_eq!(files(&tmp), before);
1779 assert!(ledger.in_standing_order().is_empty());
1780
1781 let id = create_plan(&mut engine, "The Bundle");
1782 check_plan(&mut engine, "checker-c", &id, "x-projection");
1783 engine.set_identity(Some("author-a".to_string()));
1784 let stored = engine.get_entity(&id).unwrap().content_hash.clone();
1785 let lines = ledger.in_standing_order().len();
1786 let refused = engine.batch_update(
1787 vec![(
1788 update_args(&engine, &id, Some("complete"), Some("rewritten.")),
1789 None,
1790 )],
1791 actor,
1792 Some(&client),
1793 false,
1794 );
1795 assert!(
1796 refused.as_ref().is_err() || !refused.as_ref().unwrap().applied,
1797 "{refused:?}"
1798 );
1799 assert_eq!(engine.get_entity(&id).unwrap().content_hash, stored);
1800 assert_eq!(ledger.in_standing_order().len(), lines);
1801 engine
1802 .batch_update(
1803 vec![(update_args(&engine, &id, Some("complete"), None), None)],
1804 actor,
1805 Some(&client),
1806 false,
1807 )
1808 .unwrap();
1809 assert_eq!(
1810 engine.get_entity(&id).unwrap().metadata["status"].to_frontmatter_string(),
1811 "complete"
1812 );
1813 assert_eq!(
1814 ledger.in_standing_order().len(),
1815 lines + 1,
1816 "the record is carried"
1817 );
1818
1819 let memo = engine
1821 .create_entity(
1822 create_args("The Memo", "memo", Some("complete")),
1823 actor,
1824 Some(&client),
1825 None,
1826 )
1827 .unwrap()
1828 .id;
1829 check_plan(&mut engine, "checker-c", &memo, "x-projection");
1830 engine.set_identity(Some("author-a".to_string()));
1831 let stored = engine.get_entity(&memo).unwrap().content_hash.clone();
1832 let err = engine
1833 .retype_entity(
1834 crate::engine::RetypeEntityArgs {
1835 id: memo.clone(),
1836 expected_hash: crate::ExpectedHash::Current(stored.clone()),
1837 target_type: "plan".to_string(),
1838 section_map: indexmap::IndexMap::new(),
1839 drop_metadata: Vec::new(),
1840 dry_run: false,
1841 },
1842 actor,
1843 Some(&client),
1844 None,
1845 )
1846 .expect_err("a retype onto the gate changes the type");
1847 assert!(err.to_string().contains("block-tier constraint"), "{err}");
1848 assert_eq!(engine.get_entity(&memo).unwrap().content_hash, stored);
1849 let problem = &err.details()["problems"][0];
1851 assert_eq!(problem["code"], "CONSTRAINT_UNSATISFIED", "{problem}");
1852 assert_eq!(
1853 problem["violations"][0]["kind"], "transition_requires_self_check",
1854 "{problem}"
1855 );
1856 }
1857
1858 #[test]
1861 fn a_rename_counts_its_identity_on_every_referrer_it_rewrites_on_folder() {
1862 let tmp = tempfile::TempDir::new().unwrap();
1863 let mut engine = self_check_gated_engine(&tmp, "x-projection");
1864 engine.set_identity(Some("identity-a".to_string()));
1865 let target = create_plan(&mut engine, "The Target");
1866 let (actor, client) = crate::engine::test_helpers::cli_actor();
1867 let mut sections = indexmap::IndexMap::new();
1868 sections.insert("body".to_string(), format!("see [[{}]].", target.0));
1869 let referrer = engine
1870 .create_entity(
1871 crate::engine::CreateEntityArgs {
1872 anchors: Vec::new(),
1873 mem: "bundles".to_string(),
1874 title: "The Referrer".to_string(),
1875 entity_type: "plan".to_string(),
1876 sections,
1877 metadata: indexmap::IndexMap::new(),
1878 relations: vec![crate::ops::RelateArg {
1879 target: target.clone(),
1880 rel_type: "PART_OF".to_string(),
1881 description: None,
1882 }],
1883 dry_run: false,
1884 },
1885 actor,
1886 Some(&client),
1887 None,
1888 )
1889 .unwrap()
1890 .id;
1891 let before = engine.get_entity(&referrer).unwrap().content_hash.clone();
1892 engine.set_identity(Some("identity-c".to_string()));
1893 let current = engine.get_entity(&target).unwrap().content_hash.clone();
1894 engine
1895 .rename_entity(
1896 crate::engine::RenameEntityArgs {
1897 id: target.clone(),
1898 expected_hash: crate::ExpectedHash::Current(current),
1899 new_title: "The Moved".to_string(),
1900 },
1901 actor,
1902 Some(&client),
1903 None,
1904 )
1905 .unwrap();
1906 let after = engine.get_entity(&referrer).unwrap().content_hash.clone();
1907 assert_ne!(before, after, "the rename rewrote the referrer");
1908 check_plan(&mut engine, "identity-c", &referrer, "x-projection");
1909 let entity = engine.get_entity(&referrer).unwrap().clone();
1910 let standing = (engine.check_standing_provider())(&entity, "x-projection");
1911 assert_eq!(standing.label(), "self_checked");
1912 let touches = engine.mem_touches("bundles");
1913 assert_eq!(touches.first_author(referrer.as_ref()), Some("identity-a"));
1914 }
1915
1916 #[test]
1917 fn check_refuses_read_only_mounts_typed() {
1918 let tmp = tempfile::TempDir::new().unwrap();
1919 let mut mount = crate::engine::test_helpers::folder_mount("ro", tmp.path().to_path_buf());
1920 mount.capability = MountCapability::ReadOnly;
1921 let mut engine = crate::Engine::from_mounts(vec![(
1922 mount,
1923 Box::new(crate::storage::FilesystemBackend::new(
1924 tmp.path().to_path_buf(),
1925 )) as Box<dyn crate::backend::MemBackend>,
1926 )])
1927 .unwrap();
1928 let err = engine
1929 .record_check(
1930 "ro",
1931 "ro--anything",
1932 Verdict::Ok,
1933 crate::check::CheckKind::Verification,
1934 None,
1935 Actor::Cli,
1936 None,
1937 )
1938 .unwrap_err();
1939 assert_eq!(err.code(), "READ_ONLY_MOUNT");
1940 }
1941}