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,
292 #[serde(default, skip_serializing_if = "Option::is_none")]
302 pub observed_at: Option<u64>,
303 pub entity: String,
305 pub verdict: String,
307 #[serde(default, skip_serializing_if = "Option::is_none")]
310 pub method: Option<String>,
311 pub entity_hash: String,
314 pub actor: String,
316 #[serde(default, skip_serializing_if = "Option::is_none")]
318 pub client: Option<String>,
319 pub role: String,
323 #[serde(default, skip_serializing_if = "Option::is_none")]
329 pub identity: Option<String>,
330 #[serde(default, skip_serializing_if = "Option::is_none")]
336 pub kind: Option<String>,
337 #[serde(default, skip_serializing_if = "Option::is_none")]
342 pub schema_ref: Option<String>,
343 #[serde(default, skip_serializing_if = "Option::is_none")]
348 pub finding: Option<CheckFinding>,
349 #[serde(default, skip_serializing_if = "Option::is_none")]
359 pub renamed_from: Option<String>,
360 #[serde(default, skip_serializing_if = "Option::is_none")]
364 pub carried_from: Option<CarriedFrom>,
365}
366
367pub const OBSERVED_AT_SKEW_SECS: u64 = 300;
372
373pub fn parse_observed_at(raw: &str, now: u64) -> Result<u64, String> {
380 let s = raw.trim();
381 let Some(at) = crate::engine::due::parse_iso_utc_seconds(s) else {
382 return Err(format!(
383 "observed_at {raw:?} is not an ISO-8601 UTC instant (`YYYY-MM-DDTHH:MM:SSZ`) \
384 or a civil date (`YYYY-MM-DD`)"
385 ));
386 };
387 if at > now.saturating_add(OBSERVED_AT_SKEW_SECS) {
388 return Err(format!(
389 "observed_at {raw:?} lies in the future (the engine's clock reads {now} epoch \
390 seconds); a check is recorded after it was made, never before"
391 ));
392 }
393 Ok(at)
394}
395
396impl CheckRecord {
397 pub fn resolved_kind(&self) -> Option<CheckKind> {
402 match self.kind.as_deref() {
403 None => Some(CheckKind::Verification),
404 Some(k) if k.starts_with(FOREIGN_KIND_PREFIX) => None,
405 Some(k) => Some(CheckKind::from_wire(k).unwrap_or(CheckKind::Verification)),
406 }
407 }
408
409 pub fn foreign_kind(&self) -> Option<&str> {
411 self.kind
412 .as_deref()
413 .filter(|k| k.starts_with(FOREIGN_KIND_PREFIX))
414 }
415}
416
417#[derive(Debug, Clone, Copy, PartialEq, Eq)]
419pub enum CheckState {
420 NeverChecked,
421 CheckedOk,
422 CheckFailed,
423 CheckStale,
424}
425
426impl CheckState {
427 pub fn as_str(self) -> &'static str {
428 match self {
429 Self::NeverChecked => "never_checked",
430 Self::CheckedOk => "checked_ok",
431 Self::CheckFailed => "check_failed",
432 Self::CheckStale => "check_stale",
433 }
434 }
435}
436
437pub fn derive_state(latest: Option<&CheckRecord>, current_hash: &str) -> CheckState {
442 derive_state_pinned(latest, current_hash, None)
443}
444
445pub fn derive_state_pinned(
453 latest: Option<&CheckRecord>,
454 current_hash: &str,
455 current_schema_ref: Option<&str>,
456) -> CheckState {
457 match latest {
458 None => CheckState::NeverChecked,
459 Some(rec) if rec.entity_hash != current_hash => CheckState::CheckStale,
460 Some(rec)
461 if rec.schema_ref.is_some() && rec.schema_ref.as_deref() != current_schema_ref =>
462 {
463 CheckState::CheckStale
464 }
465 Some(rec) if rec.verdict == "failed" => CheckState::CheckFailed,
466 Some(_) => CheckState::CheckedOk,
467 }
468}
469
470fn checks_dir(workspace_root: &Path) -> PathBuf {
473 workspace_root
474 .join(crate::workspace_store::WORKSPACE_STORE_DIR)
475 .join("state")
476 .join("checks")
477}
478
479pub fn check_ledger_path(workspace_root: &Path) -> PathBuf {
481 checks_dir(workspace_root).join("checks.jsonl")
482}
483
484#[derive(Debug, Clone)]
486pub struct CheckLedger {
487 path: PathBuf,
488}
489
490impl CheckLedger {
491 pub fn for_workspace(workspace_root: &Path) -> Self {
492 Self {
493 path: check_ledger_path(workspace_root),
494 }
495 }
496
497 pub fn record(&self, rec: &CheckRecord) -> std::io::Result<()> {
502 if let Some(dir) = self.path.parent() {
503 std::fs::create_dir_all(dir)?;
504 }
505 let mut line = serde_json::to_string(rec).map_err(std::io::Error::other)?;
506 line.push('\n');
507 let mut f = std::fs::OpenOptions::new()
508 .create(true)
509 .append(true)
510 .open(&self.path)?;
511 f.write_all(line.as_bytes())
512 }
513
514 pub fn carry_rename(&self, old: &str, new: &str) -> std::io::Result<usize> {
521 let carried: Vec<CheckRecord> = self
522 .all()
523 .into_iter()
524 .filter(|r| r.entity == old)
525 .map(|mut r| {
526 r.entity = new.to_string();
527 r.renamed_from = Some(old.to_string());
528 r
529 })
530 .collect();
531 if carried.is_empty() {
532 return Ok(0);
533 }
534 let mut lines = String::new();
535 for rec in &carried {
536 lines.push_str(&serde_json::to_string(rec).map_err(std::io::Error::other)?);
537 lines.push('\n');
538 }
539 let mut f = std::fs::OpenOptions::new()
540 .create(true)
541 .append(true)
542 .open(&self.path)?;
543 f.write_all(lines.as_bytes())?;
544 Ok(carried.len())
545 }
546
547 pub fn carry_transition(
557 &self,
558 entity: &str,
559 kind: &str,
560 pre_hash: &str,
561 post_hash: &str,
562 ) -> std::io::Result<bool> {
563 if pre_hash == post_hash {
564 return Ok(false);
565 }
566 let Some(latest) = self.latest_for_wire_kind(entity, kind) else {
567 return Ok(false);
568 };
569 if latest.entity_hash != pre_hash || latest.verdict != Verdict::Ok.as_str() {
570 return Ok(false);
571 }
572 let carried = CheckRecord {
573 entity_hash: post_hash.to_string(),
574 carried_from: Some(CarriedFrom::transition(pre_hash)),
575 ..latest
576 };
577 self.record(&carried)?;
578 Ok(true)
579 }
580
581 pub fn records_for_mem(&self, mem: &str) -> Vec<CheckRecord> {
584 let prefix = format!("{mem}--");
585 self.all()
586 .into_iter()
587 .filter(|r| r.entity.starts_with(&prefix))
588 .collect()
589 }
590
591 pub fn transport_lines(records: &[CheckRecord]) -> Vec<u8> {
597 let mut lines: Vec<(u64, String)> = records
598 .iter()
599 .filter_map(|r| serde_json::to_string(r).ok().map(|s| (r.ts, s)))
600 .collect();
601 lines.sort();
602 lines.dedup();
603 let mut out = Vec::new();
604 for (_, line) in lines {
605 out.extend_from_slice(line.as_bytes());
606 out.push(b'\n');
607 }
608 out
609 }
610
611 pub fn merge_transport_lines(&self, lines: &[u8]) -> std::io::Result<usize> {
619 let present: std::collections::HashSet<String> = self
620 .all()
621 .iter()
622 .filter_map(|r| serde_json::to_string(r).ok())
623 .collect();
624 let mut appended = 0;
625 for line in String::from_utf8_lossy(lines).lines() {
626 let Ok(rec) = serde_json::from_str::<CheckRecord>(line) else {
627 continue;
628 };
629 let Ok(canonical) = serde_json::to_string(&rec) else {
630 continue;
631 };
632 if present.contains(&canonical) {
633 continue;
634 }
635 self.record(&rec)?;
636 appended += 1;
637 }
638 Ok(appended)
639 }
640
641 pub fn all(&self) -> Vec<CheckRecord> {
645 let Ok(content) = std::fs::read_to_string(&self.path) else {
646 return Vec::new();
647 };
648 content
649 .lines()
650 .filter_map(|l| serde_json::from_str(l).ok())
651 .collect()
652 }
653
654 pub fn latest_for(&self, entity: &str) -> Option<CheckRecord> {
658 self.all().into_iter().rev().find(|r| r.entity == entity)
659 }
660
661 pub fn latest_for_kind(&self, entity: &str, kind: CheckKind) -> Option<CheckRecord> {
665 self.all()
666 .into_iter()
667 .rev()
668 .find(|r| r.entity == entity && r.resolved_kind() == Some(kind))
669 }
670
671 pub fn latest_for_wire_kind(&self, entity: &str, kind: &str) -> Option<CheckRecord> {
677 match CheckKind::from_wire(kind) {
678 Some(k) => self.latest_for_kind(entity, k),
679 None => self
680 .all()
681 .into_iter()
682 .rev()
683 .find(|r| r.entity == entity && r.kind.as_deref() == Some(kind)),
684 }
685 }
686}
687
688pub const SEALED_CHECKS_VERSION: u32 = 1;
698
699#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
706pub struct SealedCheck {
707 pub ts: u64,
709 #[serde(default, skip_serializing_if = "Option::is_none")]
712 pub observed_at: Option<u64>,
713 pub verdict: String,
715 #[serde(default, skip_serializing_if = "Option::is_none")]
718 pub method: Option<String>,
719 pub entity_hash: String,
722 pub actor: String,
724 pub role: String,
726 #[serde(default, skip_serializing_if = "Option::is_none")]
728 pub identity: Option<String>,
729 #[serde(default, skip_serializing_if = "Option::is_none")]
731 pub schema_ref: Option<String>,
732 #[serde(default, skip_serializing_if = "Option::is_none")]
734 pub renamed_from: Option<String>,
735 #[serde(default, skip_serializing_if = "Option::is_none")]
739 pub carried_from: Option<CarriedFrom>,
740 #[serde(default, skip_serializing_if = "Option::is_none")]
749 pub independence: Option<String>,
750 #[serde(default, skip_serializing_if = "Option::is_none")]
765 pub origin: Option<String>,
766}
767
768impl SealedCheck {
769 pub fn from_record(rec: &CheckRecord) -> Self {
773 Self {
774 ts: rec.ts,
775 observed_at: rec.observed_at,
776 verdict: rec.verdict.clone(),
777 method: rec.method.clone(),
778 entity_hash: rec.entity_hash.clone(),
779 actor: rec.actor.clone(),
780 role: rec.role.clone(),
781 identity: rec.identity.clone(),
782 schema_ref: rec.schema_ref.clone(),
783 renamed_from: rec.renamed_from.clone(),
784 carried_from: rec.carried_from.clone(),
785 independence: None,
786 origin: None,
787 }
788 }
789
790 pub fn sealed_independence(&self) -> Option<crate::engine::independence::Independence> {
793 self.independence
794 .as_deref()
795 .and_then(crate::engine::independence::Independence::from_wire)
796 }
797
798 pub fn sealed_origin(&self) -> Option<crate::render::OriginClass> {
810 match self.origin.as_deref()? {
811 "first-party" => Some(crate::render::OriginClass::FirstParty),
812 "third-party" => Some(crate::render::OriginClass::ThirdParty),
813 _ => None,
814 }
815 }
816
817 pub fn to_record(&self, entity_id: &str, kind: &str) -> CheckRecord {
823 CheckRecord {
824 ts: self.ts,
825 observed_at: self.observed_at,
826 entity: entity_id.to_string(),
827 verdict: self.verdict.clone(),
828 method: self.method.clone(),
829 entity_hash: self.entity_hash.clone(),
830 actor: self.actor.clone(),
831 client: None,
832 role: self.role.clone(),
833 identity: self.identity.clone(),
834 kind: (kind != CheckKind::Verification.as_str()).then(|| kind.to_string()),
835 schema_ref: self.schema_ref.clone(),
836 finding: None,
837 renamed_from: self.renamed_from.clone(),
838 carried_from: self.carried_from.clone(),
839 }
840 }
841}
842
843#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
847pub struct SealedChecks {
848 pub version: u32,
849 #[serde(default)]
850 pub entities: BTreeMap<String, BTreeMap<String, SealedCheck>>,
851}
852
853impl SealedChecks {
854 pub fn new() -> Self {
856 Self {
857 version: SEALED_CHECKS_VERSION,
858 entities: BTreeMap::new(),
859 }
860 }
861
862 pub fn latest(&self, entity_path: &str, kind: &str) -> Option<&SealedCheck> {
865 self.entities
866 .get(entity_path)
867 .and_then(|kinds| kinds.get(kind))
868 }
869
870 pub fn kinds_of(&self, entity_path: &str) -> impl Iterator<Item = (&str, &SealedCheck)> {
872 self.entities
873 .get(entity_path)
874 .into_iter()
875 .flat_map(|kinds| kinds.iter().map(|(k, v)| (k.as_str(), v)))
876 }
877
878 pub fn rekey_entity(&mut self, entity_path: &str, pre_hash: &str, post_hash: &str) -> usize {
889 if pre_hash == post_hash {
890 return 0;
891 }
892 let Some(kinds) = self.entities.get_mut(entity_path) else {
893 return 0;
894 };
895 let mut moved = 0;
896 for rec in kinds.values_mut() {
897 if rec.entity_hash == pre_hash {
898 rec.entity_hash = post_hash.to_string();
899 rec.carried_from = Some(CarriedFrom::export(pre_hash));
900 moved += 1;
901 }
902 }
903 moved
904 }
905
906 pub fn to_archive_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
910 let mut s = serde_json::to_string_pretty(self)?;
911 s.push('\n');
912 Ok(s.into_bytes())
913 }
914
915 pub fn from_archive_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
918 serde_json::from_slice(bytes)
919 }
920
921 pub fn validate(&self, carried: &std::collections::BTreeSet<String>) -> Result<(), String> {
927 if self.version != SEALED_CHECKS_VERSION {
928 return Err(format!(
929 "version {} is not the version this engine reads ({SEALED_CHECKS_VERSION})",
930 self.version
931 ));
932 }
933 for (path, kinds) in &self.entities {
934 if !carried.contains(path) {
935 return Err(format!(
936 "entity `{path}` names no entity the archive carries"
937 ));
938 }
939 for (kind, rec) in kinds {
940 let at = format!("entity `{path}`, kind `{kind}`");
941 if RecordKind::from_wire(kind).is_none() {
942 return Err(format!(
943 "{at}: the kind is not one of {}",
944 RecordKind::vocabulary_hint()
945 ));
946 }
947 if Verdict::from_wire(&rec.verdict).is_none() {
948 return Err(format!(
949 "{at}: verdict `{}` is not one of {}",
950 rec.verdict,
951 VERDICTS.join(", ")
952 ));
953 }
954 if rec.entity_hash.trim().is_empty() {
955 return Err(format!("{at}: entity_hash is empty"));
956 }
957 if rec.actor.trim().is_empty() {
958 return Err(format!("{at}: actor is empty"));
959 }
960 if rec.role.trim().is_empty() {
961 return Err(format!("{at}: role is empty"));
962 }
963 if let Some(reading) = rec.independence.as_deref()
964 && crate::engine::independence::Independence::from_wire(reading).is_none()
965 {
966 return Err(format!(
967 "{at}: independence `{reading}` is not one of {}",
968 crate::engine::independence::Independence::vocabulary_hint()
969 ));
970 }
971 if let Some(origin) = rec.origin.as_deref()
977 && rec.sealed_origin().is_none()
978 {
979 return Err(format!(
980 "{at}: origin `{origin}` is not one of first-party | third-party"
981 ));
982 }
983 }
984 }
985 Ok(())
986 }
987}
988
989impl Default for SealedChecks {
990 fn default() -> Self {
991 Self::new()
992 }
993}
994
995pub fn sealed_kind_of(rec: &CheckRecord) -> String {
999 match rec.resolved_kind() {
1000 Some(k) => k.as_str().to_string(),
1001 None => rec.kind.clone().unwrap_or_default(),
1002 }
1003}
1004
1005#[cfg(test)]
1006mod tests {
1007 use super::*;
1008 use tempfile::TempDir;
1009
1010 fn rec(entity: &str, verdict: &str, hash: &str) -> CheckRecord {
1011 CheckRecord {
1012 ts: 1,
1013 observed_at: None,
1014 entity: entity.to_string(),
1015 verdict: verdict.to_string(),
1016 method: None,
1017 entity_hash: hash.to_string(),
1018 actor: "cli".to_string(),
1019 client: None,
1020 role: "checker".to_string(),
1021 identity: None,
1022 kind: None,
1023 schema_ref: None,
1024 finding: None,
1025 renamed_from: None,
1026 carried_from: None,
1027 }
1028 }
1029
1030 #[test]
1031 fn state_derivation_covers_all_four_states() {
1032 assert_eq!(derive_state(None, "h1"), CheckState::NeverChecked);
1033 let ok = rec("m--e", "ok", "h1");
1034 assert_eq!(derive_state(Some(&ok), "h1"), CheckState::CheckedOk);
1035 assert_eq!(derive_state(Some(&ok), "h2"), CheckState::CheckStale);
1036 let failed = rec("m--e", "failed", "h1");
1037 assert_eq!(derive_state(Some(&failed), "h1"), CheckState::CheckFailed);
1038 assert_eq!(derive_state(Some(&failed), "h2"), CheckState::CheckStale);
1041 }
1042
1043 #[test]
1044 fn ledger_appends_and_serves_newest_per_entity() {
1045 let tmp = TempDir::new().unwrap();
1046 let ledger = CheckLedger::for_workspace(tmp.path());
1047 assert!(ledger.latest_for("m--a").is_none());
1048 ledger.record(&rec("m--a", "failed", "h1")).unwrap();
1049 ledger.record(&rec("m--b", "ok", "h9")).unwrap();
1050 ledger.record(&rec("m--a", "ok", "h2")).unwrap();
1051 let latest = ledger.latest_for("m--a").unwrap();
1052 assert_eq!(latest.verdict, "ok");
1053 assert_eq!(latest.entity_hash, "h2");
1054 assert_eq!(ledger.all().len(), 3);
1056 }
1057
1058 #[test]
1070 fn observed_at_parses_refuses_the_future_and_survives_the_carries() {
1071 let now = 1_792_503_930; assert_eq!(parse_observed_at("2026-10-19", now), Ok(1_792_368_000));
1073 assert_eq!(parse_observed_at(" 2026-10-20T13:45:30Z ", now), Ok(now));
1074 assert!(parse_observed_at("2026-10-20T13:50:00Z", now).is_ok());
1076 let err = parse_observed_at("2026-10-20T13:51:00Z", now).unwrap_err();
1077 assert!(err.contains("future"), "{err}");
1078 let err = parse_observed_at("20.10.2026", now).unwrap_err();
1079 assert!(err.contains("ISO-8601"), "{err}");
1080
1081 let tmp = TempDir::new().unwrap();
1082 let ledger = CheckLedger::for_workspace(tmp.path());
1083 let mut dated = rec("m--old", "ok", "h1");
1084 dated.observed_at = Some(1_792_368_000);
1085 ledger.record(&dated).unwrap();
1086 ledger.record(&rec("m--old", "ok", "h2")).unwrap();
1087 assert_eq!(ledger.carry_rename("m--old", "m--new").unwrap(), 2);
1088 let carried: Vec<CheckRecord> = ledger
1089 .all()
1090 .into_iter()
1091 .filter(|r| r.entity == "m--new")
1092 .collect();
1093 assert_eq!(carried[0].observed_at, Some(1_792_368_000));
1094 assert_eq!(carried[1].observed_at, None);
1095
1096 let sealed = SealedCheck::from_record(&dated);
1097 assert_eq!(sealed.observed_at, Some(1_792_368_000));
1098 assert_eq!(
1099 sealed.to_record("m--old", "verification").observed_at,
1100 Some(1_792_368_000)
1101 );
1102
1103 let raw = std::fs::read_to_string(check_ledger_path(tmp.path())).unwrap();
1104 let lines: Vec<&str> = raw.lines().collect();
1105 assert!(
1106 lines[0].contains("\"observed_at\":1792368000"),
1107 "{}",
1108 lines[0]
1109 );
1110 assert!(!lines[1].contains("observed_at"), "{}", lines[1]);
1111 }
1112
1113 #[test]
1114 fn carry_rename_rekeys_without_erasing() {
1115 let tmp = TempDir::new().unwrap();
1116 let ledger = CheckLedger::for_workspace(tmp.path());
1117 ledger.record(&rec("m--old", "ok", "h1")).unwrap();
1118 ledger.record(&rec("m--other", "ok", "h9")).unwrap();
1119 let mut conf = rec("m--old", "failed", "h1");
1120 conf.kind = Some("conformance".into());
1121 ledger.record(&conf).unwrap();
1122
1123 assert_eq!(ledger.carry_rename("m--old", "m--new").unwrap(), 2);
1124 assert_eq!(ledger.carry_rename("m--absent", "m--new").unwrap(), 0);
1125
1126 let all = ledger.all();
1127 assert_eq!(all.len(), 5);
1128 assert!(all.iter().filter(|r| r.entity == "m--old").count() == 2);
1129 let carried: Vec<&CheckRecord> = all.iter().filter(|r| r.entity == "m--new").collect();
1130 assert_eq!(carried.len(), 2);
1131 assert!(
1132 carried
1133 .iter()
1134 .all(|r| r.renamed_from.as_deref() == Some("m--old"))
1135 );
1136 let latest = ledger
1137 .latest_for_kind("m--new", CheckKind::Verification)
1138 .unwrap();
1139 assert_eq!(latest.verdict, "ok");
1140 assert_eq!(derive_state(Some(&latest), "h1"), CheckState::CheckedOk);
1141 assert_eq!(
1142 derive_state(Some(&latest), "h2-after-rename"),
1143 CheckState::CheckStale
1144 );
1145 assert_eq!(
1146 ledger
1147 .latest_for_kind("m--new", CheckKind::Conformance)
1148 .unwrap()
1149 .verdict,
1150 "failed"
1151 );
1152 assert!(
1154 ledger
1155 .latest_for("m--other")
1156 .unwrap()
1157 .renamed_from
1158 .is_none()
1159 );
1160 }
1161
1162 #[test]
1168 fn carry_transition_moves_only_the_fresh_confirming_record() {
1169 let tmp = TempDir::new().unwrap();
1170 let ledger = CheckLedger::for_workspace(tmp.path());
1171 let mut ok = rec("m--plan", "ok", "h1");
1172 ok.kind = Some("x-projection".into());
1173 ok.identity = Some("checker-c".into());
1174 ledger.record(&ok).unwrap();
1175
1176 assert!(
1177 !ledger
1178 .carry_transition("m--plan", "x-projection", "h1", "h1")
1179 .unwrap()
1180 );
1181 assert!(
1182 !ledger
1183 .carry_transition("m--plan", "x-projection", "h0", "h2")
1184 .unwrap()
1185 );
1186 assert!(
1187 !ledger
1188 .carry_transition("m--plan", "verification", "h1", "h2")
1189 .unwrap()
1190 );
1191 assert_eq!(ledger.all().len(), 1, "nothing appended so far");
1192
1193 assert!(
1194 ledger
1195 .carry_transition("m--plan", "x-projection", "h1", "h2")
1196 .unwrap()
1197 );
1198 let all = ledger.all();
1199 assert_eq!(all.len(), 2, "append-only: the original stays");
1200 let carried = ledger
1201 .latest_for_wire_kind("m--plan", "x-projection")
1202 .unwrap();
1203 assert_eq!(carried.entity_hash, "h2");
1204 assert_eq!(carried.identity.as_deref(), Some("checker-c"));
1205 assert_eq!(carried.verdict, "ok");
1206 assert_eq!(
1207 carried.carried_from,
1208 Some(CarriedFrom {
1209 hash: "h1".into(),
1210 reason: CARRY_REASON_TRANSITION.into()
1211 })
1212 );
1213 assert_eq!(derive_state(Some(&carried), "h2"), CheckState::CheckedOk);
1214 assert!(
1216 ledger
1217 .carry_transition("m--plan", "x-projection", "h2", "h3")
1218 .unwrap()
1219 );
1220 let again = ledger
1221 .latest_for_wire_kind("m--plan", "x-projection")
1222 .unwrap();
1223 assert_eq!(again.carried_from.as_ref().unwrap().hash, "h2");
1224
1225 let mut failed = rec("m--other", "failed", "h1");
1227 failed.kind = Some("x-projection".into());
1228 ledger.record(&failed).unwrap();
1229 assert!(
1230 !ledger
1231 .carry_transition("m--other", "x-projection", "h1", "h2")
1232 .unwrap()
1233 );
1234 assert!(all[0].carried_from.is_none());
1236 }
1237
1238 #[test]
1241 fn sealed_rekey_moves_fresh_records_and_leaves_stale_ones() {
1242 let mut sealed = SealedChecks::new();
1243 let fresh = SealedCheck::from_record(&rec("m--a", "ok", "h1"));
1244 let mut stale = SealedCheck::from_record(&rec("m--a", "ok", "h0"));
1245 stale.ts = 0;
1246 sealed.entities.insert(
1247 "a".into(),
1248 BTreeMap::from([
1249 ("verification".to_string(), fresh),
1250 ("x-audit".to_string(), stale),
1251 ]),
1252 );
1253 assert_eq!(sealed.rekey_entity("a", "h1", "h1"), 0);
1254 assert_eq!(sealed.rekey_entity("absent", "h1", "h2"), 0);
1255 assert_eq!(sealed.rekey_entity("a", "h1", "h2"), 1);
1256 let v = sealed.latest("a", "verification").unwrap();
1257 assert_eq!(v.entity_hash, "h2");
1258 assert_eq!(v.carried_from.as_ref().unwrap().reason, CARRY_REASON_EXPORT);
1259 assert_eq!(v.carried_from.as_ref().unwrap().hash, "h1");
1260 let x = sealed.latest("a", "x-audit").unwrap();
1261 assert_eq!(x.entity_hash, "h0", "stale stays stale");
1262 assert!(x.carried_from.is_none());
1263 let back = v.to_record("m--a", "verification");
1265 assert_eq!(back.carried_from, v.carried_from);
1266 assert_eq!(SealedCheck::from_record(&back), *v);
1267 let legacy = r#"{"ts":1,"verdict":"ok","entity_hash":"h","actor":"cli","role":"checker"}"#;
1269 let parsed: SealedCheck = serde_json::from_str(legacy).unwrap();
1270 assert!(parsed.carried_from.is_none());
1271 assert!(parsed.independence.is_none());
1272 assert!(parsed.sealed_independence().is_none());
1273 }
1274
1275 #[test]
1282 fn sealed_row_origin_parses_only_from_the_closed_vocabulary() {
1283 let mut sealed = SealedChecks::new();
1284 let mut row = SealedCheck::from_record(&rec("m--a", "ok", "h1"));
1285 row.origin = Some("third-party".to_string());
1286 sealed.entities.insert(
1287 "a".into(),
1288 BTreeMap::from([("verification".to_string(), row)]),
1289 );
1290 assert_eq!(
1291 sealed.latest("a", "verification").unwrap().sealed_origin(),
1292 Some(crate::render::OriginClass::ThirdParty)
1293 );
1294 let carried: std::collections::BTreeSet<String> = ["a".to_string()].into();
1295 assert!(sealed.validate(&carried).is_ok());
1296
1297 let legacy = r#"{"ts":1,"verdict":"ok","entity_hash":"h","actor":"cli","role":"checker"}"#;
1299 let parsed: SealedCheck = serde_json::from_str(legacy).unwrap();
1300 assert!(parsed.origin.is_none());
1301 assert!(parsed.sealed_origin().is_none());
1302
1303 sealed
1306 .entities
1307 .get_mut("a")
1308 .unwrap()
1309 .get_mut("verification")
1310 .unwrap()
1311 .origin = Some("trusted".into());
1312 assert!(
1313 sealed
1314 .latest("a", "verification")
1315 .unwrap()
1316 .sealed_origin()
1317 .is_none()
1318 );
1319 let err = sealed.validate(&carried).unwrap_err();
1320 assert!(err.contains("origin `trusted`"), "{err}");
1321 }
1322
1323 #[test]
1328 fn sealed_independence_is_kept_by_rekey_and_closed_in_vocabulary() {
1329 use crate::engine::independence::Independence;
1330 let mut sealed = SealedChecks::new();
1331 let mut fresh = SealedCheck::from_record(&rec("m--a", "ok", "h1"));
1332 fresh.independence = Some(Independence::ConfirmedIndependent.as_str().to_string());
1333 sealed.entities.insert(
1334 "a".into(),
1335 BTreeMap::from([("verification".to_string(), fresh)]),
1336 );
1337 assert_eq!(sealed.rekey_entity("a", "h1", "h2"), 1);
1338 let v = sealed.latest("a", "verification").unwrap();
1339 assert_eq!(
1340 v.sealed_independence(),
1341 Some(Independence::ConfirmedIndependent)
1342 );
1343 let bytes = sealed.to_archive_bytes().unwrap();
1344 let back = SealedChecks::from_archive_bytes(&bytes).unwrap();
1345 assert_eq!(back, sealed);
1346 assert!(v.to_record("m--a", "verification").carried_from.is_some());
1347 let carried: std::collections::BTreeSet<String> = ["a".to_string()].into();
1348 assert!(back.validate(&carried).is_ok());
1349
1350 let mut foreign = sealed.clone();
1351 foreign
1352 .entities
1353 .get_mut("a")
1354 .unwrap()
1355 .get_mut("verification")
1356 .unwrap()
1357 .independence = Some("trusted".into());
1358 assert!(
1359 foreign
1360 .latest("a", "verification")
1361 .unwrap()
1362 .sealed_independence()
1363 .is_none()
1364 );
1365 let err = foreign.validate(&carried).unwrap_err();
1366 assert!(err.contains("independence `trusted`"), "{err}");
1367 }
1368
1369 #[test]
1370 fn verdict_vocabulary_is_closed() {
1371 assert!(Verdict::from_wire("ok").is_some());
1372 assert!(Verdict::from_wire("failed").is_some());
1373 assert!(Verdict::from_wire("passed").is_none());
1374 assert!(Verdict::from_wire("OK").is_none());
1375 }
1376
1377 fn conf(entity: &str, verdict: &str, hash: &str, pin: &str) -> CheckRecord {
1378 CheckRecord {
1379 kind: Some("conformance".to_string()),
1380 schema_ref: Some(pin.to_string()),
1381 ..rec(entity, verdict, hash)
1382 }
1383 }
1384
1385 #[test]
1386 fn kind_vocabulary_is_closed() {
1387 assert!(CheckKind::from_wire("verification").is_some());
1388 assert!(CheckKind::from_wire("conformance").is_some());
1389 assert!(CheckKind::from_wire("semantic").is_none());
1390 assert!(CheckKind::from_wire("Conformance").is_none());
1391 }
1392
1393 #[test]
1397 fn legacy_lines_read_as_verification() {
1398 let legacy = r#"{"ts":1,"entity":"m--e","verdict":"ok","entity_hash":"h1","actor":"cli","role":"checker"}"#;
1399 let parsed: CheckRecord = serde_json::from_str(legacy).unwrap();
1400 assert_eq!(parsed.resolved_kind(), Some(CheckKind::Verification));
1401 let fresh = rec("m--e", "ok", "h1");
1404 let line = serde_json::to_string(&fresh).unwrap();
1405 assert!(!line.contains("kind"));
1406 assert!(!line.contains("schema_ref"));
1407 assert!(!line.contains("identity"));
1411 }
1412
1413 #[test]
1416 fn latest_is_per_kind() {
1417 let tmp = TempDir::new().unwrap();
1418 let ledger = CheckLedger::for_workspace(tmp.path());
1419 ledger.record(&rec("m--a", "ok", "h1")).unwrap();
1420 ledger
1421 .record(&conf("m--a", "failed", "h1", "planning@1.0.0"))
1422 .unwrap();
1423 let v = ledger
1424 .latest_for_kind("m--a", CheckKind::Verification)
1425 .unwrap();
1426 assert_eq!(v.verdict, "ok");
1427 let c = ledger
1428 .latest_for_kind("m--a", CheckKind::Conformance)
1429 .unwrap();
1430 assert_eq!(c.verdict, "failed");
1431 assert_eq!(c.schema_ref.as_deref(), Some("planning@1.0.0"));
1432 }
1433
1434 #[test]
1437 fn conformance_stales_on_pin_move_verification_does_not() {
1438 let c = conf("m--e", "ok", "h1", "planning@1.0.0");
1439 assert_eq!(
1440 derive_state_pinned(Some(&c), "h1", Some("planning@1.0.0")),
1441 CheckState::CheckedOk
1442 );
1443 assert_eq!(
1444 derive_state_pinned(Some(&c), "h2", Some("planning@1.0.0")),
1445 CheckState::CheckStale
1446 );
1447 assert_eq!(
1448 derive_state_pinned(Some(&c), "h1", Some("planning@2.0.0")),
1449 CheckState::CheckStale
1450 );
1451 assert_eq!(
1453 derive_state_pinned(Some(&c), "h1", None),
1454 CheckState::CheckStale
1455 );
1456 let v = rec("m--e", "ok", "h1");
1458 assert_eq!(
1459 derive_state_pinned(Some(&v), "h1", Some("planning@9.0.0")),
1460 CheckState::CheckedOk
1461 );
1462 assert_eq!(derive_state(Some(&v), "h1"), CheckState::CheckedOk);
1463 }
1464
1465 #[test]
1468 fn finding_shape_is_fixed_and_validated_whole() {
1469 let ok = CheckFinding::from_json(serde_json::json!({
1470 "code": "hidden-premise", "message": "The step assumes X.", "section": "step"
1471 }))
1472 .unwrap();
1473 assert_eq!(ok.code, "hidden-premise");
1474 assert_eq!(ok.section.as_deref(), Some("step"));
1475 for bad in [
1476 serde_json::json!({ "message": "no code" }),
1477 serde_json::json!({ "code": "x" }),
1478 serde_json::json!({ "code": "", "message": "empty code" }),
1479 serde_json::json!({ "code": "x", "message": " " }),
1480 serde_json::json!({ "code": "x", "message": "m", "severity": "high" }),
1481 serde_json::json!({ "code": "x", "message": "m", "section": "" }),
1482 ] {
1483 let err = CheckFinding::from_json(bad.clone()).unwrap_err();
1484 assert!(err.contains("shape"), "{bad}: {err}");
1485 }
1486 }
1487
1488 #[test]
1489 fn open_kinds_parse_only_with_the_prefix_and_never_resolve_to_an_engine_kind() {
1490 assert_eq!(
1491 RecordKind::from_wire("verification"),
1492 Some(RecordKind::Engine(CheckKind::Verification))
1493 );
1494 assert_eq!(
1495 RecordKind::from_wire("x-step-walk"),
1496 Some(RecordKind::Foreign("x-step-walk".to_string()))
1497 );
1498 for bad in ["step-walk", "x-", "x-Step", "x--a", "x-a-", "X-a"] {
1499 assert!(RecordKind::from_wire(bad).is_none(), "{bad}");
1500 }
1501 assert!(RecordKind::vocabulary_hint().contains("x-<name>"));
1502 let mut r = rec("m--e", "ok", "h");
1503 r.kind = Some("x-step-walk".to_string());
1504 assert_eq!(r.resolved_kind(), None);
1505 assert_eq!(r.foreign_kind(), Some("x-step-walk"));
1506 r.kind = None;
1507 assert_eq!(r.resolved_kind(), Some(CheckKind::Verification));
1508 r.kind = Some("conformance".to_string());
1509 assert_eq!(r.resolved_kind(), Some(CheckKind::Conformance));
1510 r.kind = Some("mystery".to_string());
1512 assert_eq!(r.resolved_kind(), Some(CheckKind::Verification));
1513 }
1514
1515 #[test]
1516 fn pre_finding_ledger_lines_parse_and_derive_unchanged_and_findings_round_trip() {
1517 let tmp = TempDir::new().unwrap();
1518 let ledger = CheckLedger::for_workspace(tmp.path());
1519 let dir = check_ledger_path(tmp.path());
1520 std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
1521 std::fs::write(
1523 &dir,
1524 "{\"ts\":1,\"entity\":\"m--e\",\"verdict\":\"failed\",\"entity_hash\":\"h\",\"actor\":\"cli\",\"role\":\"unspecified\"}\n",
1525 )
1526 .unwrap();
1527 let old = ledger
1528 .latest_for_kind("m--e", CheckKind::Verification)
1529 .unwrap();
1530 assert!(old.finding.is_none());
1531 assert_eq!(derive_state(Some(&old), "h"), CheckState::CheckFailed);
1532
1533 let mut with = rec("m--e", "failed", "h");
1534 with.ts = 2;
1535 with.finding = Some(CheckFinding {
1536 code: "hidden-premise".into(),
1537 section: Some("step".into()),
1538 message: "The step assumes X.".into(),
1539 evidence: None,
1540 });
1541 ledger.record(&with).unwrap();
1542 let mut foreign = rec("m--e", "ok", "h");
1544 foreign.ts = 3;
1545 foreign.kind = Some("x-step-walk".into());
1546 ledger.record(&foreign).unwrap();
1547 let latest = ledger
1548 .latest_for_kind("m--e", CheckKind::Verification)
1549 .unwrap();
1550 assert_eq!(
1551 latest.ts, 2,
1552 "the foreign record is not the latest verification record"
1553 );
1554 assert_eq!(latest.finding.as_ref().unwrap().code, "hidden-premise");
1555 assert_eq!(derive_state(Some(&latest), "h"), CheckState::CheckFailed);
1556 let text = std::fs::read_to_string(&dir).unwrap();
1557 assert!(text.contains("\"finding\":{\"code\":\"hidden-premise\",\"section\":\"step\",\"message\":\"The step assumes X.\"}"), "{text}");
1558 assert!(text.contains("\"kind\":\"x-step-walk\""));
1559 assert_eq!(text.lines().count(), 3, "append-only");
1560 }
1561}