1use std::collections::BTreeMap;
37use std::io::Write;
38use std::path::{Path, PathBuf};
39
40use serde::{Deserialize, Serialize};
41
42pub const VERDICTS: [&str; 2] = ["ok", "failed"];
45
46pub const CHECK_KINDS: [&str; 2] = ["verification", "conformance"];
56
57pub const FOREIGN_KIND_PREFIX: &str = "x-";
64
65pub const INVALID_CHECK_FINDING_CODE: &str = "INVALID_CHECK_FINDING";
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum CheckKind {
71 Verification,
72 Conformance,
73}
74
75#[derive(Debug, Clone, PartialEq, Eq)]
78pub enum RecordKind {
79 Engine(CheckKind),
80 Foreign(String),
81}
82
83impl RecordKind {
84 pub fn from_wire(s: &str) -> Option<Self> {
89 if let Some(k) = CheckKind::from_wire(s) {
90 return Some(Self::Engine(k));
91 }
92 s.starts_with(FOREIGN_KIND_PREFIX)
96 .then(|| memstead_schema::check_kind_wire_is_well_formed(s))
97 .filter(|ok| *ok)
98 .map(|_| Self::Foreign(s.to_string()))
99 }
100
101 pub fn engine_kind(&self) -> Option<CheckKind> {
103 match self {
104 Self::Engine(k) => Some(*k),
105 Self::Foreign(_) => None,
106 }
107 }
108
109 pub fn as_wire(&self) -> &str {
111 match self {
112 Self::Engine(k) => k.as_str(),
113 Self::Foreign(s) => s.as_str(),
114 }
115 }
116
117 pub fn vocabulary_hint() -> String {
119 format!(
120 "{}, or a caller-declared `{FOREIGN_KIND_PREFIX}<name>` kind (lowercase letters, digits, hyphens) the engine records verbatim and never interprets",
121 CHECK_KINDS.join(", ")
122 )
123 }
124}
125
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
134#[serde(deny_unknown_fields)]
135pub struct CheckFinding {
136 pub code: String,
138 #[serde(default, skip_serializing_if = "Option::is_none")]
140 pub section: Option<String>,
141 pub message: String,
143 #[serde(default, skip_serializing_if = "Option::is_none")]
145 pub evidence: Option<String>,
146}
147
148impl CheckFinding {
149 pub const SHAPE: &'static str =
151 "{code: <non-empty>, message: <non-empty>, section?: <key>, evidence?: <text>}";
152
153 pub fn validate(&self) -> Result<(), String> {
156 if self.code.trim().is_empty() {
157 return Err(format!(
158 "finding.code is required and must be non-empty — shape {}",
159 Self::SHAPE
160 ));
161 }
162 if self.message.trim().is_empty() {
163 return Err(format!(
164 "finding.message is required and must be non-empty — shape {}",
165 Self::SHAPE
166 ));
167 }
168 if self.section.as_deref().is_some_and(|s| s.trim().is_empty()) {
169 return Err(format!(
170 "finding.section, when given, must be non-empty — shape {}",
171 Self::SHAPE
172 ));
173 }
174 if self
175 .evidence
176 .as_deref()
177 .is_some_and(|s| s.trim().is_empty())
178 {
179 return Err(format!(
180 "finding.evidence, when given, must be non-empty — shape {}",
181 Self::SHAPE
182 ));
183 }
184 Ok(())
185 }
186
187 pub fn from_json(value: serde_json::Value) -> Result<Self, String> {
191 let finding: CheckFinding = serde_json::from_value(value)
192 .map_err(|e| format!("finding does not match the shape {} ({e})", Self::SHAPE))?;
193 finding.validate()?;
194 Ok(finding)
195 }
196}
197
198impl CheckKind {
199 pub fn from_wire(s: &str) -> Option<Self> {
201 match s {
202 "verification" => Some(Self::Verification),
203 "conformance" => Some(Self::Conformance),
204 _ => None,
205 }
206 }
207
208 pub fn as_str(self) -> &'static str {
209 match self {
210 Self::Verification => "verification",
211 Self::Conformance => "conformance",
212 }
213 }
214}
215
216#[derive(Debug, Clone, Copy, PartialEq, Eq)]
218pub enum Verdict {
219 Ok,
220 Failed,
221}
222
223impl Verdict {
224 pub fn from_wire(s: &str) -> Option<Self> {
226 match s {
227 "ok" => Some(Self::Ok),
228 "failed" => Some(Self::Failed),
229 _ => None,
230 }
231 }
232
233 pub fn as_str(self) -> &'static str {
234 match self {
235 Self::Ok => "ok",
236 Self::Failed => "failed",
237 }
238 }
239}
240
241pub const CARRY_REASON_TRANSITION: &str = "transition";
244
245pub const CARRY_REASON_EXPORT: &str = "export";
248
249#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
263pub struct CarriedFrom {
264 pub hash: String,
266 pub reason: String,
268}
269
270impl CarriedFrom {
271 pub fn transition(hash: &str) -> Self {
272 Self {
273 hash: hash.to_string(),
274 reason: CARRY_REASON_TRANSITION.to_string(),
275 }
276 }
277
278 pub fn export(hash: &str) -> Self {
279 Self {
280 hash: hash.to_string(),
281 reason: CARRY_REASON_EXPORT.to_string(),
282 }
283 }
284}
285
286#[derive(Debug, Clone, Serialize, Deserialize)]
288pub struct CheckRecord {
289 pub ts: u64,
291 pub entity: String,
293 pub verdict: String,
295 #[serde(default, skip_serializing_if = "Option::is_none")]
298 pub method: Option<String>,
299 pub entity_hash: String,
302 pub actor: String,
304 #[serde(default, skip_serializing_if = "Option::is_none")]
306 pub client: Option<String>,
307 pub role: String,
311 #[serde(default, skip_serializing_if = "Option::is_none")]
317 pub identity: Option<String>,
318 #[serde(default, skip_serializing_if = "Option::is_none")]
324 pub kind: Option<String>,
325 #[serde(default, skip_serializing_if = "Option::is_none")]
330 pub schema_ref: Option<String>,
331 #[serde(default, skip_serializing_if = "Option::is_none")]
336 pub finding: Option<CheckFinding>,
337 #[serde(default, skip_serializing_if = "Option::is_none")]
347 pub renamed_from: Option<String>,
348 #[serde(default, skip_serializing_if = "Option::is_none")]
352 pub carried_from: Option<CarriedFrom>,
353}
354
355impl CheckRecord {
356 pub fn resolved_kind(&self) -> Option<CheckKind> {
361 match self.kind.as_deref() {
362 None => Some(CheckKind::Verification),
363 Some(k) if k.starts_with(FOREIGN_KIND_PREFIX) => None,
364 Some(k) => Some(CheckKind::from_wire(k).unwrap_or(CheckKind::Verification)),
365 }
366 }
367
368 pub fn foreign_kind(&self) -> Option<&str> {
370 self.kind
371 .as_deref()
372 .filter(|k| k.starts_with(FOREIGN_KIND_PREFIX))
373 }
374}
375
376#[derive(Debug, Clone, Copy, PartialEq, Eq)]
378pub enum CheckState {
379 NeverChecked,
380 CheckedOk,
381 CheckFailed,
382 CheckStale,
383}
384
385impl CheckState {
386 pub fn as_str(self) -> &'static str {
387 match self {
388 Self::NeverChecked => "never_checked",
389 Self::CheckedOk => "checked_ok",
390 Self::CheckFailed => "check_failed",
391 Self::CheckStale => "check_stale",
392 }
393 }
394}
395
396pub fn derive_state(latest: Option<&CheckRecord>, current_hash: &str) -> CheckState {
401 derive_state_pinned(latest, current_hash, None)
402}
403
404pub fn derive_state_pinned(
412 latest: Option<&CheckRecord>,
413 current_hash: &str,
414 current_schema_ref: Option<&str>,
415) -> CheckState {
416 match latest {
417 None => CheckState::NeverChecked,
418 Some(rec) if rec.entity_hash != current_hash => CheckState::CheckStale,
419 Some(rec)
420 if rec.schema_ref.is_some() && rec.schema_ref.as_deref() != current_schema_ref =>
421 {
422 CheckState::CheckStale
423 }
424 Some(rec) if rec.verdict == "failed" => CheckState::CheckFailed,
425 Some(_) => CheckState::CheckedOk,
426 }
427}
428
429fn checks_dir(workspace_root: &Path) -> PathBuf {
432 workspace_root
433 .join(crate::workspace_store::WORKSPACE_STORE_DIR)
434 .join("state")
435 .join("checks")
436}
437
438pub fn check_ledger_path(workspace_root: &Path) -> PathBuf {
440 checks_dir(workspace_root).join("checks.jsonl")
441}
442
443#[derive(Debug, Clone)]
445pub struct CheckLedger {
446 path: PathBuf,
447}
448
449impl CheckLedger {
450 pub fn for_workspace(workspace_root: &Path) -> Self {
451 Self {
452 path: check_ledger_path(workspace_root),
453 }
454 }
455
456 pub fn record(&self, rec: &CheckRecord) -> std::io::Result<()> {
461 if let Some(dir) = self.path.parent() {
462 std::fs::create_dir_all(dir)?;
463 }
464 let mut line = serde_json::to_string(rec).map_err(std::io::Error::other)?;
465 line.push('\n');
466 let mut f = std::fs::OpenOptions::new()
467 .create(true)
468 .append(true)
469 .open(&self.path)?;
470 f.write_all(line.as_bytes())
471 }
472
473 pub fn carry_rename(&self, old: &str, new: &str) -> std::io::Result<usize> {
480 let carried: Vec<CheckRecord> = self
481 .all()
482 .into_iter()
483 .filter(|r| r.entity == old)
484 .map(|mut r| {
485 r.entity = new.to_string();
486 r.renamed_from = Some(old.to_string());
487 r
488 })
489 .collect();
490 if carried.is_empty() {
491 return Ok(0);
492 }
493 let mut lines = String::new();
494 for rec in &carried {
495 lines.push_str(&serde_json::to_string(rec).map_err(std::io::Error::other)?);
496 lines.push('\n');
497 }
498 let mut f = std::fs::OpenOptions::new()
499 .create(true)
500 .append(true)
501 .open(&self.path)?;
502 f.write_all(lines.as_bytes())?;
503 Ok(carried.len())
504 }
505
506 pub fn carry_transition(
516 &self,
517 entity: &str,
518 kind: &str,
519 pre_hash: &str,
520 post_hash: &str,
521 ) -> std::io::Result<bool> {
522 if pre_hash == post_hash {
523 return Ok(false);
524 }
525 let Some(latest) = self.latest_for_wire_kind(entity, kind) else {
526 return Ok(false);
527 };
528 if latest.entity_hash != pre_hash || latest.verdict != Verdict::Ok.as_str() {
529 return Ok(false);
530 }
531 let carried = CheckRecord {
532 entity_hash: post_hash.to_string(),
533 carried_from: Some(CarriedFrom::transition(pre_hash)),
534 ..latest
535 };
536 self.record(&carried)?;
537 Ok(true)
538 }
539
540 pub fn records_for_mem(&self, mem: &str) -> Vec<CheckRecord> {
543 let prefix = format!("{mem}--");
544 self.all()
545 .into_iter()
546 .filter(|r| r.entity.starts_with(&prefix))
547 .collect()
548 }
549
550 pub fn transport_lines(records: &[CheckRecord]) -> Vec<u8> {
556 let mut lines: Vec<(u64, String)> = records
557 .iter()
558 .filter_map(|r| serde_json::to_string(r).ok().map(|s| (r.ts, s)))
559 .collect();
560 lines.sort();
561 lines.dedup();
562 let mut out = Vec::new();
563 for (_, line) in lines {
564 out.extend_from_slice(line.as_bytes());
565 out.push(b'\n');
566 }
567 out
568 }
569
570 pub fn merge_transport_lines(&self, lines: &[u8]) -> std::io::Result<usize> {
578 let present: std::collections::HashSet<String> = self
579 .all()
580 .iter()
581 .filter_map(|r| serde_json::to_string(r).ok())
582 .collect();
583 let mut appended = 0;
584 for line in String::from_utf8_lossy(lines).lines() {
585 let Ok(rec) = serde_json::from_str::<CheckRecord>(line) else {
586 continue;
587 };
588 let Ok(canonical) = serde_json::to_string(&rec) else {
589 continue;
590 };
591 if present.contains(&canonical) {
592 continue;
593 }
594 self.record(&rec)?;
595 appended += 1;
596 }
597 Ok(appended)
598 }
599
600 pub fn all(&self) -> Vec<CheckRecord> {
604 let Ok(content) = std::fs::read_to_string(&self.path) else {
605 return Vec::new();
606 };
607 content
608 .lines()
609 .filter_map(|l| serde_json::from_str(l).ok())
610 .collect()
611 }
612
613 pub fn latest_for(&self, entity: &str) -> Option<CheckRecord> {
617 self.all().into_iter().rev().find(|r| r.entity == entity)
618 }
619
620 pub fn latest_for_kind(&self, entity: &str, kind: CheckKind) -> Option<CheckRecord> {
624 self.all()
625 .into_iter()
626 .rev()
627 .find(|r| r.entity == entity && r.resolved_kind() == Some(kind))
628 }
629
630 pub fn latest_for_wire_kind(&self, entity: &str, kind: &str) -> Option<CheckRecord> {
636 match CheckKind::from_wire(kind) {
637 Some(k) => self.latest_for_kind(entity, k),
638 None => self
639 .all()
640 .into_iter()
641 .rev()
642 .find(|r| r.entity == entity && r.kind.as_deref() == Some(kind)),
643 }
644 }
645}
646
647pub const SEALED_CHECKS_VERSION: u32 = 1;
657
658#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
665pub struct SealedCheck {
666 pub ts: u64,
668 pub verdict: String,
670 #[serde(default, skip_serializing_if = "Option::is_none")]
673 pub method: Option<String>,
674 pub entity_hash: String,
677 pub actor: String,
679 pub role: String,
681 #[serde(default, skip_serializing_if = "Option::is_none")]
683 pub identity: Option<String>,
684 #[serde(default, skip_serializing_if = "Option::is_none")]
686 pub schema_ref: Option<String>,
687 #[serde(default, skip_serializing_if = "Option::is_none")]
689 pub renamed_from: Option<String>,
690 #[serde(default, skip_serializing_if = "Option::is_none")]
694 pub carried_from: Option<CarriedFrom>,
695 #[serde(default, skip_serializing_if = "Option::is_none")]
704 pub independence: Option<String>,
705 #[serde(default, skip_serializing_if = "Option::is_none")]
720 pub origin: Option<String>,
721}
722
723impl SealedCheck {
724 pub fn from_record(rec: &CheckRecord) -> Self {
728 Self {
729 ts: rec.ts,
730 verdict: rec.verdict.clone(),
731 method: rec.method.clone(),
732 entity_hash: rec.entity_hash.clone(),
733 actor: rec.actor.clone(),
734 role: rec.role.clone(),
735 identity: rec.identity.clone(),
736 schema_ref: rec.schema_ref.clone(),
737 renamed_from: rec.renamed_from.clone(),
738 carried_from: rec.carried_from.clone(),
739 independence: None,
740 origin: None,
741 }
742 }
743
744 pub fn sealed_independence(&self) -> Option<crate::engine::independence::Independence> {
747 self.independence
748 .as_deref()
749 .and_then(crate::engine::independence::Independence::from_wire)
750 }
751
752 pub fn sealed_origin(&self) -> Option<crate::render::OriginClass> {
764 match self.origin.as_deref()? {
765 "first-party" => Some(crate::render::OriginClass::FirstParty),
766 "third-party" => Some(crate::render::OriginClass::ThirdParty),
767 _ => None,
768 }
769 }
770
771 pub fn to_record(&self, entity_id: &str, kind: &str) -> CheckRecord {
777 CheckRecord {
778 ts: self.ts,
779 entity: entity_id.to_string(),
780 verdict: self.verdict.clone(),
781 method: self.method.clone(),
782 entity_hash: self.entity_hash.clone(),
783 actor: self.actor.clone(),
784 client: None,
785 role: self.role.clone(),
786 identity: self.identity.clone(),
787 kind: (kind != CheckKind::Verification.as_str()).then(|| kind.to_string()),
788 schema_ref: self.schema_ref.clone(),
789 finding: None,
790 renamed_from: self.renamed_from.clone(),
791 carried_from: self.carried_from.clone(),
792 }
793 }
794}
795
796#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
800pub struct SealedChecks {
801 pub version: u32,
802 #[serde(default)]
803 pub entities: BTreeMap<String, BTreeMap<String, SealedCheck>>,
804}
805
806impl SealedChecks {
807 pub fn new() -> Self {
809 Self {
810 version: SEALED_CHECKS_VERSION,
811 entities: BTreeMap::new(),
812 }
813 }
814
815 pub fn latest(&self, entity_path: &str, kind: &str) -> Option<&SealedCheck> {
818 self.entities
819 .get(entity_path)
820 .and_then(|kinds| kinds.get(kind))
821 }
822
823 pub fn kinds_of(&self, entity_path: &str) -> impl Iterator<Item = (&str, &SealedCheck)> {
825 self.entities
826 .get(entity_path)
827 .into_iter()
828 .flat_map(|kinds| kinds.iter().map(|(k, v)| (k.as_str(), v)))
829 }
830
831 pub fn rekey_entity(&mut self, entity_path: &str, pre_hash: &str, post_hash: &str) -> usize {
842 if pre_hash == post_hash {
843 return 0;
844 }
845 let Some(kinds) = self.entities.get_mut(entity_path) else {
846 return 0;
847 };
848 let mut moved = 0;
849 for rec in kinds.values_mut() {
850 if rec.entity_hash == pre_hash {
851 rec.entity_hash = post_hash.to_string();
852 rec.carried_from = Some(CarriedFrom::export(pre_hash));
853 moved += 1;
854 }
855 }
856 moved
857 }
858
859 pub fn to_archive_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
863 let mut s = serde_json::to_string_pretty(self)?;
864 s.push('\n');
865 Ok(s.into_bytes())
866 }
867
868 pub fn from_archive_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
871 serde_json::from_slice(bytes)
872 }
873
874 pub fn validate(&self, carried: &std::collections::BTreeSet<String>) -> Result<(), String> {
880 if self.version != SEALED_CHECKS_VERSION {
881 return Err(format!(
882 "version {} is not the version this engine reads ({SEALED_CHECKS_VERSION})",
883 self.version
884 ));
885 }
886 for (path, kinds) in &self.entities {
887 if !carried.contains(path) {
888 return Err(format!(
889 "entity `{path}` names no entity the archive carries"
890 ));
891 }
892 for (kind, rec) in kinds {
893 let at = format!("entity `{path}`, kind `{kind}`");
894 if RecordKind::from_wire(kind).is_none() {
895 return Err(format!(
896 "{at}: the kind is not one of {}",
897 RecordKind::vocabulary_hint()
898 ));
899 }
900 if Verdict::from_wire(&rec.verdict).is_none() {
901 return Err(format!(
902 "{at}: verdict `{}` is not one of {}",
903 rec.verdict,
904 VERDICTS.join(", ")
905 ));
906 }
907 if rec.entity_hash.trim().is_empty() {
908 return Err(format!("{at}: entity_hash is empty"));
909 }
910 if rec.actor.trim().is_empty() {
911 return Err(format!("{at}: actor is empty"));
912 }
913 if rec.role.trim().is_empty() {
914 return Err(format!("{at}: role is empty"));
915 }
916 if let Some(reading) = rec.independence.as_deref()
917 && crate::engine::independence::Independence::from_wire(reading).is_none()
918 {
919 return Err(format!(
920 "{at}: independence `{reading}` is not one of {}",
921 crate::engine::independence::Independence::vocabulary_hint()
922 ));
923 }
924 if let Some(origin) = rec.origin.as_deref()
930 && rec.sealed_origin().is_none()
931 {
932 return Err(format!(
933 "{at}: origin `{origin}` is not one of first-party | third-party"
934 ));
935 }
936 }
937 }
938 Ok(())
939 }
940}
941
942impl Default for SealedChecks {
943 fn default() -> Self {
944 Self::new()
945 }
946}
947
948pub fn sealed_kind_of(rec: &CheckRecord) -> String {
952 match rec.resolved_kind() {
953 Some(k) => k.as_str().to_string(),
954 None => rec.kind.clone().unwrap_or_default(),
955 }
956}
957
958#[cfg(test)]
959mod tests {
960 use super::*;
961 use tempfile::TempDir;
962
963 fn rec(entity: &str, verdict: &str, hash: &str) -> CheckRecord {
964 CheckRecord {
965 ts: 1,
966 entity: entity.to_string(),
967 verdict: verdict.to_string(),
968 method: None,
969 entity_hash: hash.to_string(),
970 actor: "cli".to_string(),
971 client: None,
972 role: "checker".to_string(),
973 identity: None,
974 kind: None,
975 schema_ref: None,
976 finding: None,
977 renamed_from: None,
978 carried_from: None,
979 }
980 }
981
982 #[test]
983 fn state_derivation_covers_all_four_states() {
984 assert_eq!(derive_state(None, "h1"), CheckState::NeverChecked);
985 let ok = rec("m--e", "ok", "h1");
986 assert_eq!(derive_state(Some(&ok), "h1"), CheckState::CheckedOk);
987 assert_eq!(derive_state(Some(&ok), "h2"), CheckState::CheckStale);
988 let failed = rec("m--e", "failed", "h1");
989 assert_eq!(derive_state(Some(&failed), "h1"), CheckState::CheckFailed);
990 assert_eq!(derive_state(Some(&failed), "h2"), CheckState::CheckStale);
993 }
994
995 #[test]
996 fn ledger_appends_and_serves_newest_per_entity() {
997 let tmp = TempDir::new().unwrap();
998 let ledger = CheckLedger::for_workspace(tmp.path());
999 assert!(ledger.latest_for("m--a").is_none());
1000 ledger.record(&rec("m--a", "failed", "h1")).unwrap();
1001 ledger.record(&rec("m--b", "ok", "h9")).unwrap();
1002 ledger.record(&rec("m--a", "ok", "h2")).unwrap();
1003 let latest = ledger.latest_for("m--a").unwrap();
1004 assert_eq!(latest.verdict, "ok");
1005 assert_eq!(latest.entity_hash, "h2");
1006 assert_eq!(ledger.all().len(), 3);
1008 }
1009
1010 #[test]
1016 fn carry_rename_rekeys_without_erasing() {
1017 let tmp = TempDir::new().unwrap();
1018 let ledger = CheckLedger::for_workspace(tmp.path());
1019 ledger.record(&rec("m--old", "ok", "h1")).unwrap();
1020 ledger.record(&rec("m--other", "ok", "h9")).unwrap();
1021 let mut conf = rec("m--old", "failed", "h1");
1022 conf.kind = Some("conformance".into());
1023 ledger.record(&conf).unwrap();
1024
1025 assert_eq!(ledger.carry_rename("m--old", "m--new").unwrap(), 2);
1026 assert_eq!(ledger.carry_rename("m--absent", "m--new").unwrap(), 0);
1027
1028 let all = ledger.all();
1029 assert_eq!(all.len(), 5);
1030 assert!(all.iter().filter(|r| r.entity == "m--old").count() == 2);
1031 let carried: Vec<&CheckRecord> = all.iter().filter(|r| r.entity == "m--new").collect();
1032 assert_eq!(carried.len(), 2);
1033 assert!(
1034 carried
1035 .iter()
1036 .all(|r| r.renamed_from.as_deref() == Some("m--old"))
1037 );
1038 let latest = ledger
1039 .latest_for_kind("m--new", CheckKind::Verification)
1040 .unwrap();
1041 assert_eq!(latest.verdict, "ok");
1042 assert_eq!(derive_state(Some(&latest), "h1"), CheckState::CheckedOk);
1043 assert_eq!(
1044 derive_state(Some(&latest), "h2-after-rename"),
1045 CheckState::CheckStale
1046 );
1047 assert_eq!(
1048 ledger
1049 .latest_for_kind("m--new", CheckKind::Conformance)
1050 .unwrap()
1051 .verdict,
1052 "failed"
1053 );
1054 assert!(
1056 ledger
1057 .latest_for("m--other")
1058 .unwrap()
1059 .renamed_from
1060 .is_none()
1061 );
1062 }
1063
1064 #[test]
1070 fn carry_transition_moves_only_the_fresh_confirming_record() {
1071 let tmp = TempDir::new().unwrap();
1072 let ledger = CheckLedger::for_workspace(tmp.path());
1073 let mut ok = rec("m--plan", "ok", "h1");
1074 ok.kind = Some("x-projection".into());
1075 ok.identity = Some("checker-c".into());
1076 ledger.record(&ok).unwrap();
1077
1078 assert!(
1079 !ledger
1080 .carry_transition("m--plan", "x-projection", "h1", "h1")
1081 .unwrap()
1082 );
1083 assert!(
1084 !ledger
1085 .carry_transition("m--plan", "x-projection", "h0", "h2")
1086 .unwrap()
1087 );
1088 assert!(
1089 !ledger
1090 .carry_transition("m--plan", "verification", "h1", "h2")
1091 .unwrap()
1092 );
1093 assert_eq!(ledger.all().len(), 1, "nothing appended so far");
1094
1095 assert!(
1096 ledger
1097 .carry_transition("m--plan", "x-projection", "h1", "h2")
1098 .unwrap()
1099 );
1100 let all = ledger.all();
1101 assert_eq!(all.len(), 2, "append-only: the original stays");
1102 let carried = ledger
1103 .latest_for_wire_kind("m--plan", "x-projection")
1104 .unwrap();
1105 assert_eq!(carried.entity_hash, "h2");
1106 assert_eq!(carried.identity.as_deref(), Some("checker-c"));
1107 assert_eq!(carried.verdict, "ok");
1108 assert_eq!(
1109 carried.carried_from,
1110 Some(CarriedFrom {
1111 hash: "h1".into(),
1112 reason: CARRY_REASON_TRANSITION.into()
1113 })
1114 );
1115 assert_eq!(derive_state(Some(&carried), "h2"), CheckState::CheckedOk);
1116 assert!(
1118 ledger
1119 .carry_transition("m--plan", "x-projection", "h2", "h3")
1120 .unwrap()
1121 );
1122 let again = ledger
1123 .latest_for_wire_kind("m--plan", "x-projection")
1124 .unwrap();
1125 assert_eq!(again.carried_from.as_ref().unwrap().hash, "h2");
1126
1127 let mut failed = rec("m--other", "failed", "h1");
1129 failed.kind = Some("x-projection".into());
1130 ledger.record(&failed).unwrap();
1131 assert!(
1132 !ledger
1133 .carry_transition("m--other", "x-projection", "h1", "h2")
1134 .unwrap()
1135 );
1136 assert!(all[0].carried_from.is_none());
1138 }
1139
1140 #[test]
1143 fn sealed_rekey_moves_fresh_records_and_leaves_stale_ones() {
1144 let mut sealed = SealedChecks::new();
1145 let fresh = SealedCheck::from_record(&rec("m--a", "ok", "h1"));
1146 let mut stale = SealedCheck::from_record(&rec("m--a", "ok", "h0"));
1147 stale.ts = 0;
1148 sealed.entities.insert(
1149 "a".into(),
1150 BTreeMap::from([
1151 ("verification".to_string(), fresh),
1152 ("x-audit".to_string(), stale),
1153 ]),
1154 );
1155 assert_eq!(sealed.rekey_entity("a", "h1", "h1"), 0);
1156 assert_eq!(sealed.rekey_entity("absent", "h1", "h2"), 0);
1157 assert_eq!(sealed.rekey_entity("a", "h1", "h2"), 1);
1158 let v = sealed.latest("a", "verification").unwrap();
1159 assert_eq!(v.entity_hash, "h2");
1160 assert_eq!(v.carried_from.as_ref().unwrap().reason, CARRY_REASON_EXPORT);
1161 assert_eq!(v.carried_from.as_ref().unwrap().hash, "h1");
1162 let x = sealed.latest("a", "x-audit").unwrap();
1163 assert_eq!(x.entity_hash, "h0", "stale stays stale");
1164 assert!(x.carried_from.is_none());
1165 let back = v.to_record("m--a", "verification");
1167 assert_eq!(back.carried_from, v.carried_from);
1168 assert_eq!(SealedCheck::from_record(&back), *v);
1169 let legacy = r#"{"ts":1,"verdict":"ok","entity_hash":"h","actor":"cli","role":"checker"}"#;
1171 let parsed: SealedCheck = serde_json::from_str(legacy).unwrap();
1172 assert!(parsed.carried_from.is_none());
1173 assert!(parsed.independence.is_none());
1174 assert!(parsed.sealed_independence().is_none());
1175 }
1176
1177 #[test]
1184 fn sealed_row_origin_parses_only_from_the_closed_vocabulary() {
1185 let mut sealed = SealedChecks::new();
1186 let mut row = SealedCheck::from_record(&rec("m--a", "ok", "h1"));
1187 row.origin = Some("third-party".to_string());
1188 sealed.entities.insert(
1189 "a".into(),
1190 BTreeMap::from([("verification".to_string(), row)]),
1191 );
1192 assert_eq!(
1193 sealed.latest("a", "verification").unwrap().sealed_origin(),
1194 Some(crate::render::OriginClass::ThirdParty)
1195 );
1196 let carried: std::collections::BTreeSet<String> = ["a".to_string()].into();
1197 assert!(sealed.validate(&carried).is_ok());
1198
1199 let legacy = r#"{"ts":1,"verdict":"ok","entity_hash":"h","actor":"cli","role":"checker"}"#;
1201 let parsed: SealedCheck = serde_json::from_str(legacy).unwrap();
1202 assert!(parsed.origin.is_none());
1203 assert!(parsed.sealed_origin().is_none());
1204
1205 sealed
1208 .entities
1209 .get_mut("a")
1210 .unwrap()
1211 .get_mut("verification")
1212 .unwrap()
1213 .origin = Some("trusted".into());
1214 assert!(
1215 sealed
1216 .latest("a", "verification")
1217 .unwrap()
1218 .sealed_origin()
1219 .is_none()
1220 );
1221 let err = sealed.validate(&carried).unwrap_err();
1222 assert!(err.contains("origin `trusted`"), "{err}");
1223 }
1224
1225 #[test]
1230 fn sealed_independence_is_kept_by_rekey_and_closed_in_vocabulary() {
1231 use crate::engine::independence::Independence;
1232 let mut sealed = SealedChecks::new();
1233 let mut fresh = SealedCheck::from_record(&rec("m--a", "ok", "h1"));
1234 fresh.independence = Some(Independence::ConfirmedIndependent.as_str().to_string());
1235 sealed.entities.insert(
1236 "a".into(),
1237 BTreeMap::from([("verification".to_string(), fresh)]),
1238 );
1239 assert_eq!(sealed.rekey_entity("a", "h1", "h2"), 1);
1240 let v = sealed.latest("a", "verification").unwrap();
1241 assert_eq!(
1242 v.sealed_independence(),
1243 Some(Independence::ConfirmedIndependent)
1244 );
1245 let bytes = sealed.to_archive_bytes().unwrap();
1246 let back = SealedChecks::from_archive_bytes(&bytes).unwrap();
1247 assert_eq!(back, sealed);
1248 assert!(v.to_record("m--a", "verification").carried_from.is_some());
1249 let carried: std::collections::BTreeSet<String> = ["a".to_string()].into();
1250 assert!(back.validate(&carried).is_ok());
1251
1252 let mut foreign = sealed.clone();
1253 foreign
1254 .entities
1255 .get_mut("a")
1256 .unwrap()
1257 .get_mut("verification")
1258 .unwrap()
1259 .independence = Some("trusted".into());
1260 assert!(
1261 foreign
1262 .latest("a", "verification")
1263 .unwrap()
1264 .sealed_independence()
1265 .is_none()
1266 );
1267 let err = foreign.validate(&carried).unwrap_err();
1268 assert!(err.contains("independence `trusted`"), "{err}");
1269 }
1270
1271 #[test]
1272 fn verdict_vocabulary_is_closed() {
1273 assert!(Verdict::from_wire("ok").is_some());
1274 assert!(Verdict::from_wire("failed").is_some());
1275 assert!(Verdict::from_wire("passed").is_none());
1276 assert!(Verdict::from_wire("OK").is_none());
1277 }
1278
1279 fn conf(entity: &str, verdict: &str, hash: &str, pin: &str) -> CheckRecord {
1280 CheckRecord {
1281 kind: Some("conformance".to_string()),
1282 schema_ref: Some(pin.to_string()),
1283 ..rec(entity, verdict, hash)
1284 }
1285 }
1286
1287 #[test]
1288 fn kind_vocabulary_is_closed() {
1289 assert!(CheckKind::from_wire("verification").is_some());
1290 assert!(CheckKind::from_wire("conformance").is_some());
1291 assert!(CheckKind::from_wire("semantic").is_none());
1292 assert!(CheckKind::from_wire("Conformance").is_none());
1293 }
1294
1295 #[test]
1299 fn legacy_lines_read_as_verification() {
1300 let legacy = r#"{"ts":1,"entity":"m--e","verdict":"ok","entity_hash":"h1","actor":"cli","role":"checker"}"#;
1301 let parsed: CheckRecord = serde_json::from_str(legacy).unwrap();
1302 assert_eq!(parsed.resolved_kind(), Some(CheckKind::Verification));
1303 let fresh = rec("m--e", "ok", "h1");
1306 let line = serde_json::to_string(&fresh).unwrap();
1307 assert!(!line.contains("kind"));
1308 assert!(!line.contains("schema_ref"));
1309 assert!(!line.contains("identity"));
1313 }
1314
1315 #[test]
1318 fn latest_is_per_kind() {
1319 let tmp = TempDir::new().unwrap();
1320 let ledger = CheckLedger::for_workspace(tmp.path());
1321 ledger.record(&rec("m--a", "ok", "h1")).unwrap();
1322 ledger
1323 .record(&conf("m--a", "failed", "h1", "planning@1.0.0"))
1324 .unwrap();
1325 let v = ledger
1326 .latest_for_kind("m--a", CheckKind::Verification)
1327 .unwrap();
1328 assert_eq!(v.verdict, "ok");
1329 let c = ledger
1330 .latest_for_kind("m--a", CheckKind::Conformance)
1331 .unwrap();
1332 assert_eq!(c.verdict, "failed");
1333 assert_eq!(c.schema_ref.as_deref(), Some("planning@1.0.0"));
1334 }
1335
1336 #[test]
1339 fn conformance_stales_on_pin_move_verification_does_not() {
1340 let c = conf("m--e", "ok", "h1", "planning@1.0.0");
1341 assert_eq!(
1342 derive_state_pinned(Some(&c), "h1", Some("planning@1.0.0")),
1343 CheckState::CheckedOk
1344 );
1345 assert_eq!(
1346 derive_state_pinned(Some(&c), "h2", Some("planning@1.0.0")),
1347 CheckState::CheckStale
1348 );
1349 assert_eq!(
1350 derive_state_pinned(Some(&c), "h1", Some("planning@2.0.0")),
1351 CheckState::CheckStale
1352 );
1353 assert_eq!(
1355 derive_state_pinned(Some(&c), "h1", None),
1356 CheckState::CheckStale
1357 );
1358 let v = rec("m--e", "ok", "h1");
1360 assert_eq!(
1361 derive_state_pinned(Some(&v), "h1", Some("planning@9.0.0")),
1362 CheckState::CheckedOk
1363 );
1364 assert_eq!(derive_state(Some(&v), "h1"), CheckState::CheckedOk);
1365 }
1366
1367 #[test]
1370 fn finding_shape_is_fixed_and_validated_whole() {
1371 let ok = CheckFinding::from_json(serde_json::json!({
1372 "code": "hidden-premise", "message": "The step assumes X.", "section": "step"
1373 }))
1374 .unwrap();
1375 assert_eq!(ok.code, "hidden-premise");
1376 assert_eq!(ok.section.as_deref(), Some("step"));
1377 for bad in [
1378 serde_json::json!({ "message": "no code" }),
1379 serde_json::json!({ "code": "x" }),
1380 serde_json::json!({ "code": "", "message": "empty code" }),
1381 serde_json::json!({ "code": "x", "message": " " }),
1382 serde_json::json!({ "code": "x", "message": "m", "severity": "high" }),
1383 serde_json::json!({ "code": "x", "message": "m", "section": "" }),
1384 ] {
1385 let err = CheckFinding::from_json(bad.clone()).unwrap_err();
1386 assert!(err.contains("shape"), "{bad}: {err}");
1387 }
1388 }
1389
1390 #[test]
1391 fn open_kinds_parse_only_with_the_prefix_and_never_resolve_to_an_engine_kind() {
1392 assert_eq!(
1393 RecordKind::from_wire("verification"),
1394 Some(RecordKind::Engine(CheckKind::Verification))
1395 );
1396 assert_eq!(
1397 RecordKind::from_wire("x-step-walk"),
1398 Some(RecordKind::Foreign("x-step-walk".to_string()))
1399 );
1400 for bad in ["step-walk", "x-", "x-Step", "x--a", "x-a-", "X-a"] {
1401 assert!(RecordKind::from_wire(bad).is_none(), "{bad}");
1402 }
1403 assert!(RecordKind::vocabulary_hint().contains("x-<name>"));
1404 let mut r = rec("m--e", "ok", "h");
1405 r.kind = Some("x-step-walk".to_string());
1406 assert_eq!(r.resolved_kind(), None);
1407 assert_eq!(r.foreign_kind(), Some("x-step-walk"));
1408 r.kind = None;
1409 assert_eq!(r.resolved_kind(), Some(CheckKind::Verification));
1410 r.kind = Some("conformance".to_string());
1411 assert_eq!(r.resolved_kind(), Some(CheckKind::Conformance));
1412 r.kind = Some("mystery".to_string());
1414 assert_eq!(r.resolved_kind(), Some(CheckKind::Verification));
1415 }
1416
1417 #[test]
1418 fn pre_finding_ledger_lines_parse_and_derive_unchanged_and_findings_round_trip() {
1419 let tmp = TempDir::new().unwrap();
1420 let ledger = CheckLedger::for_workspace(tmp.path());
1421 let dir = check_ledger_path(tmp.path());
1422 std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
1423 std::fs::write(
1425 &dir,
1426 "{\"ts\":1,\"entity\":\"m--e\",\"verdict\":\"failed\",\"entity_hash\":\"h\",\"actor\":\"cli\",\"role\":\"unspecified\"}\n",
1427 )
1428 .unwrap();
1429 let old = ledger
1430 .latest_for_kind("m--e", CheckKind::Verification)
1431 .unwrap();
1432 assert!(old.finding.is_none());
1433 assert_eq!(derive_state(Some(&old), "h"), CheckState::CheckFailed);
1434
1435 let mut with = rec("m--e", "failed", "h");
1436 with.ts = 2;
1437 with.finding = Some(CheckFinding {
1438 code: "hidden-premise".into(),
1439 section: Some("step".into()),
1440 message: "The step assumes X.".into(),
1441 evidence: None,
1442 });
1443 ledger.record(&with).unwrap();
1444 let mut foreign = rec("m--e", "ok", "h");
1446 foreign.ts = 3;
1447 foreign.kind = Some("x-step-walk".into());
1448 ledger.record(&foreign).unwrap();
1449 let latest = ledger
1450 .latest_for_kind("m--e", CheckKind::Verification)
1451 .unwrap();
1452 assert_eq!(
1453 latest.ts, 2,
1454 "the foreign record is not the latest verification record"
1455 );
1456 assert_eq!(latest.finding.as_ref().unwrap().code, "hidden-premise");
1457 assert_eq!(derive_state(Some(&latest), "h"), CheckState::CheckFailed);
1458 let text = std::fs::read_to_string(&dir).unwrap();
1459 assert!(text.contains("\"finding\":{\"code\":\"hidden-premise\",\"section\":\"step\",\"message\":\"The step assumes X.\"}"), "{text}");
1460 assert!(text.contains("\"kind\":\"x-step-walk\""));
1461 assert_eq!(text.lines().count(), 3, "append-only");
1462 }
1463}