1use std::collections::BTreeMap;
36use std::io::Write;
37use std::path::{Path, PathBuf};
38
39use serde::{Deserialize, Serialize};
40
41pub const VERDICTS: [&str; 2] = ["ok", "failed"];
44
45pub const CHECK_KINDS: [&str; 2] = ["verification", "conformance"];
55
56pub const FOREIGN_KIND_PREFIX: &str = "x-";
63
64pub const INVALID_CHECK_FINDING_CODE: &str = "INVALID_CHECK_FINDING";
66
67#[derive(Debug, Clone, thiserror::Error)]
71#[error(
72 "batch check refused: {} of {total} entr(ies) failed validation, nothing recorded",
73 failed_entries.len()
74)]
75pub struct CheckBatchRefused {
76 pub failed_entries: Vec<serde_json::Value>,
77 pub total: usize,
78}
79
80impl CheckBatchRefused {
81 pub fn code(&self) -> &'static str {
82 "BATCH_REFUSED"
83 }
84
85 pub fn details(&self) -> serde_json::Value {
86 serde_json::json!({ "failed_entries": self.failed_entries })
87 }
88}
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum CheckKind {
93 Verification,
94 Conformance,
95}
96
97#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum RecordKind {
101 Engine(CheckKind),
102 Foreign(String),
103}
104
105impl RecordKind {
106 pub fn from_wire(s: &str) -> Option<Self> {
111 if let Some(k) = CheckKind::from_wire(s) {
112 return Some(Self::Engine(k));
113 }
114 s.starts_with(FOREIGN_KIND_PREFIX)
118 .then(|| memstead_schema::check_kind_wire_is_well_formed(s))
119 .filter(|ok| *ok)
120 .map(|_| Self::Foreign(s.to_string()))
121 }
122
123 pub fn engine_kind(&self) -> Option<CheckKind> {
125 match self {
126 Self::Engine(k) => Some(*k),
127 Self::Foreign(_) => None,
128 }
129 }
130
131 pub fn as_wire(&self) -> &str {
133 match self {
134 Self::Engine(k) => k.as_str(),
135 Self::Foreign(s) => s.as_str(),
136 }
137 }
138
139 pub fn vocabulary_hint() -> String {
141 format!(
142 "{}, or a caller-declared `{FOREIGN_KIND_PREFIX}<name>` kind (lowercase letters, digits, hyphens) the engine records verbatim and never interprets",
143 CHECK_KINDS.join(", ")
144 )
145 }
146}
147
148#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
156#[serde(deny_unknown_fields)]
157pub struct CheckFinding {
158 pub code: String,
160 #[serde(default, skip_serializing_if = "Option::is_none")]
162 pub section: Option<String>,
163 pub message: String,
165 #[serde(default, skip_serializing_if = "Option::is_none")]
167 pub evidence: Option<String>,
168}
169
170impl CheckFinding {
171 pub const SHAPE: &'static str =
173 "{code: <non-empty>, message: <non-empty>, section?: <key>, evidence?: <text>}";
174
175 pub fn validate(&self) -> Result<(), String> {
178 if self.code.trim().is_empty() {
179 return Err(format!(
180 "finding.code is required and must be non-empty — shape {}",
181 Self::SHAPE
182 ));
183 }
184 if self.message.trim().is_empty() {
185 return Err(format!(
186 "finding.message is required and must be non-empty — shape {}",
187 Self::SHAPE
188 ));
189 }
190 if self.section.as_deref().is_some_and(|s| s.trim().is_empty()) {
191 return Err(format!(
192 "finding.section, when given, must be non-empty — shape {}",
193 Self::SHAPE
194 ));
195 }
196 if self
197 .evidence
198 .as_deref()
199 .is_some_and(|s| s.trim().is_empty())
200 {
201 return Err(format!(
202 "finding.evidence, when given, must be non-empty — shape {}",
203 Self::SHAPE
204 ));
205 }
206 Ok(())
207 }
208
209 pub fn from_json(value: serde_json::Value) -> Result<Self, InvalidCheckFinding> {
213 let finding: CheckFinding =
214 serde_json::from_value(value).map_err(|e| InvalidCheckFinding {
215 reason: format!("finding does not match the shape {} ({e})", Self::SHAPE),
216 })?;
217 finding
218 .validate()
219 .map_err(|reason| InvalidCheckFinding { reason })?;
220 Ok(finding)
221 }
222}
223
224#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
227#[error("{reason}")]
228pub struct InvalidCheckFinding {
229 pub reason: String,
230}
231
232impl InvalidCheckFinding {
233 pub fn code(&self) -> &'static str {
234 INVALID_CHECK_FINDING_CODE
235 }
236
237 pub fn details(&self) -> serde_json::Value {
238 serde_json::json!({ "shape": CheckFinding::SHAPE })
239 }
240}
241
242impl CheckKind {
243 pub fn from_wire(s: &str) -> Option<Self> {
245 match s {
246 "verification" => Some(Self::Verification),
247 "conformance" => Some(Self::Conformance),
248 _ => None,
249 }
250 }
251
252 pub fn as_str(self) -> &'static str {
253 match self {
254 Self::Verification => "verification",
255 Self::Conformance => "conformance",
256 }
257 }
258}
259
260#[derive(Debug, Clone, Copy, PartialEq, Eq)]
262pub enum Verdict {
263 Ok,
264 Failed,
265}
266
267impl Verdict {
268 pub fn from_wire(s: &str) -> Option<Self> {
270 match s {
271 "ok" => Some(Self::Ok),
272 "failed" => Some(Self::Failed),
273 _ => None,
274 }
275 }
276
277 pub fn as_str(self) -> &'static str {
278 match self {
279 Self::Ok => "ok",
280 Self::Failed => "failed",
281 }
282 }
283}
284
285pub const CARRY_REASON_TRANSITION: &str = "transition";
288
289pub const CARRY_REASON_EXPORT: &str = "export";
292
293#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
307pub struct CarriedFrom {
308 pub hash: String,
310 pub reason: String,
312 #[serde(default, skip_serializing_if = "Option::is_none")]
320 pub depth: Option<u32>,
321}
322
323impl CarriedFrom {
324 pub fn transition(hash: &str) -> Self {
325 Self::transition_at(hash, 1)
326 }
327
328 pub fn transition_at(hash: &str, depth: u32) -> Self {
330 Self {
331 hash: hash.to_string(),
332 reason: CARRY_REASON_TRANSITION.to_string(),
333 depth: Some(depth),
334 }
335 }
336
337 pub fn chain_depth(&self) -> u32 {
339 self.depth.unwrap_or(1)
340 }
341
342 pub fn export(hash: &str) -> Self {
343 Self {
344 hash: hash.to_string(),
345 reason: CARRY_REASON_EXPORT.to_string(),
346 depth: None,
347 }
348 }
349}
350
351#[derive(Debug, Clone, Serialize, Deserialize)]
353pub struct CheckRecord {
354 pub ts: u64,
357 #[serde(default, skip_serializing_if = "Option::is_none")]
368 pub observed_at: Option<u64>,
369 pub entity: String,
371 pub verdict: String,
373 #[serde(default, skip_serializing_if = "Option::is_none")]
376 pub method: Option<String>,
377 pub entity_hash: String,
380 pub actor: String,
382 #[serde(default, skip_serializing_if = "Option::is_none")]
384 pub client: Option<String>,
385 pub role: String,
389 #[serde(default, skip_serializing_if = "Option::is_none")]
395 pub identity: Option<String>,
396 #[serde(default, skip_serializing_if = "Option::is_none")]
402 pub kind: Option<String>,
403 #[serde(default, skip_serializing_if = "Option::is_none")]
408 pub schema_ref: Option<String>,
409 #[serde(default, skip_serializing_if = "Option::is_none")]
414 pub finding: Option<CheckFinding>,
415 #[serde(default, skip_serializing_if = "Option::is_none")]
425 pub renamed_from: Option<String>,
426 #[serde(default, skip_serializing_if = "Option::is_none")]
430 pub carried_from: Option<CarriedFrom>,
431 #[serde(default, skip_serializing_if = "Option::is_none")]
442 pub checked_write: Option<String>,
443}
444
445pub const LOCAL_TIE_WINDOW_SECS: u64 = 60;
450
451pub const OBSERVED_AT_SKEW_SECS: u64 = 300;
456
457pub fn parse_observed_at(raw: &str, now: u64) -> Result<u64, String> {
464 let s = raw.trim();
465 let Some(at) = crate::engine::due::parse_iso_utc_seconds(s) else {
466 return Err(format!(
467 "observed_at {raw:?} is not an ISO-8601 UTC instant (`YYYY-MM-DDTHH:MM:SSZ`) \
468 or a civil date (`YYYY-MM-DD`)"
469 ));
470 };
471 if at > now.saturating_add(OBSERVED_AT_SKEW_SECS) {
472 return Err(format!(
473 "observed_at {raw:?} lies in the future (the engine's clock reads {now} epoch \
474 seconds); a check is recorded after it was made, never before"
475 ));
476 }
477 Ok(at)
478}
479
480impl CheckRecord {
481 pub fn act_time(&self) -> u64 {
485 self.observed_at.unwrap_or(self.ts)
486 }
487
488 pub fn resolved_kind(&self) -> Option<CheckKind> {
493 match self.kind.as_deref() {
494 None => Some(CheckKind::Verification),
495 Some(k) if k.starts_with(FOREIGN_KIND_PREFIX) => None,
496 Some(k) => Some(CheckKind::from_wire(k).unwrap_or(CheckKind::Verification)),
497 }
498 }
499
500 pub fn foreign_kind(&self) -> Option<&str> {
502 self.kind
503 .as_deref()
504 .filter(|k| k.starts_with(FOREIGN_KIND_PREFIX))
505 }
506}
507
508#[derive(Debug, Clone, Copy, PartialEq, Eq)]
510pub enum CheckState {
511 NeverChecked,
512 CheckedOk,
513 CheckFailed,
514 CheckStale,
515}
516
517impl CheckState {
518 pub fn as_str(self) -> &'static str {
519 match self {
520 Self::NeverChecked => "never_checked",
521 Self::CheckedOk => "checked_ok",
522 Self::CheckFailed => "check_failed",
523 Self::CheckStale => "check_stale",
524 }
525 }
526}
527
528pub fn derive_state(latest: Option<&CheckRecord>, current_hash: &str) -> CheckState {
533 derive_state_pinned(latest, current_hash, None)
534}
535
536pub fn derive_state_pinned(
544 latest: Option<&CheckRecord>,
545 current_hash: &str,
546 current_schema_ref: Option<&str>,
547) -> CheckState {
548 match latest {
549 None => CheckState::NeverChecked,
550 Some(rec) if rec.entity_hash != current_hash => CheckState::CheckStale,
551 Some(rec)
552 if rec.schema_ref.is_some() && rec.schema_ref.as_deref() != current_schema_ref =>
553 {
554 CheckState::CheckStale
555 }
556 Some(rec) if rec.verdict == "failed" => CheckState::CheckFailed,
557 Some(_) => CheckState::CheckedOk,
558 }
559}
560
561fn checks_dir(workspace_root: &Path) -> PathBuf {
564 workspace_root
565 .join(crate::workspace_store::WORKSPACE_STORE_DIR)
566 .join("state")
567 .join("checks")
568}
569
570fn check_ledger_path(workspace_root: &Path) -> PathBuf {
573 checks_dir(workspace_root).join("checks.jsonl")
574}
575
576#[derive(Debug, Clone)]
578pub struct CheckLedger {
579 path: PathBuf,
580}
581
582impl CheckLedger {
583 pub fn for_workspace(workspace_root: &Path) -> Self {
584 Self {
585 path: check_ledger_path(workspace_root),
586 }
587 }
588
589 pub fn record(&self, rec: &CheckRecord) -> std::io::Result<()> {
594 if let Some(dir) = self.path.parent() {
595 std::fs::create_dir_all(dir)?;
596 }
597 let mut line = serde_json::to_string(rec).map_err(std::io::Error::other)?;
598 line.push('\n');
599 let mut f = std::fs::OpenOptions::new()
600 .create(true)
601 .append(true)
602 .open(&self.path)?;
603 f.write_all(line.as_bytes())
604 }
605
606 pub fn record_local(&self, mut rec: CheckRecord) -> std::io::Result<CheckRecord> {
618 if rec.observed_at.is_none() {
619 let newest = self
620 .raw_lines()
621 .iter()
622 .filter(|r| r.entity == rec.entity)
623 .map(CheckRecord::act_time)
624 .max();
625 if let Some(newest) = newest
626 && newest >= rec.ts
627 && newest <= rec.ts.saturating_add(LOCAL_TIE_WINDOW_SECS)
628 {
629 rec.ts = newest + 1;
630 }
631 }
632 self.record(&rec)?;
633 Ok(rec)
634 }
635
636 pub fn carry_rename(&self, old: &str, new: &str) -> std::io::Result<usize> {
643 let carried: Vec<CheckRecord> = self
644 .raw_lines()
645 .into_iter()
646 .filter(|r| r.entity == old)
647 .map(|mut r| {
648 r.entity = new.to_string();
649 r.renamed_from = Some(old.to_string());
650 r
651 })
652 .collect();
653 if carried.is_empty() {
654 return Ok(0);
655 }
656 let mut lines = String::new();
657 for rec in &carried {
658 lines.push_str(&serde_json::to_string(rec).map_err(std::io::Error::other)?);
659 lines.push('\n');
660 }
661 let mut f = std::fs::OpenOptions::new()
662 .create(true)
663 .append(true)
664 .open(&self.path)?;
665 f.write_all(lines.as_bytes())?;
666 Ok(carried.len())
667 }
668
669 pub fn carry_transition(
679 &self,
680 entity: &str,
681 kind: &str,
682 pre_hash: &str,
683 post_hash: &str,
684 ) -> std::io::Result<bool> {
685 if pre_hash == post_hash {
686 return Ok(false);
687 }
688 let Some(latest) = self.latest_for_wire_kind(entity, kind) else {
689 return Ok(false);
690 };
691 if latest.entity_hash != pre_hash || latest.verdict != Verdict::Ok.as_str() {
692 return Ok(false);
693 }
694 let depth = latest
695 .carried_from
696 .as_ref()
697 .map_or(1, |c| c.chain_depth() + 1);
698 let carried = CheckRecord {
699 entity_hash: post_hash.to_string(),
700 carried_from: Some(CarriedFrom::transition_at(pre_hash, depth)),
701 ..latest
702 };
703 self.record(&carried)?;
704 Ok(true)
705 }
706
707 pub fn rows_for_mem(&self, mem: &str) -> Vec<CheckRecord> {
711 let prefix = format!("{mem}--");
712 standing_order(
713 self.raw_lines()
714 .into_iter()
715 .filter(|r| r.entity.starts_with(&prefix))
716 .collect(),
717 )
718 }
719
720 pub fn transport_lines_for_mem(&self, mem: &str) -> Vec<u8> {
722 Self::transport_lines(&self.rows_for_mem(mem))
723 }
724
725 pub fn transport_lines(records: &[CheckRecord]) -> Vec<u8> {
731 let mut lines: Vec<(u64, String)> = records
732 .iter()
733 .filter_map(|r| serde_json::to_string(r).ok().map(|s| (r.ts, s)))
734 .collect();
735 lines.sort();
736 lines.dedup();
737 let mut out = Vec::new();
738 for (_, line) in lines {
739 out.extend_from_slice(line.as_bytes());
740 out.push(b'\n');
741 }
742 out
743 }
744
745 pub fn merge_transport_lines(&self, lines: &[u8], now: u64) -> std::io::Result<MergedRows> {
759 let present: std::collections::HashSet<String> = self
760 .raw_lines()
761 .iter()
762 .filter_map(|r| serde_json::to_string(r).ok())
763 .collect();
764 let mut out = MergedRows::default();
765 for line in String::from_utf8_lossy(lines).lines() {
766 let Ok(rec) = serde_json::from_str::<CheckRecord>(line) else {
767 continue;
768 };
769 let Ok(canonical) = serde_json::to_string(&rec) else {
770 continue;
771 };
772 if present.contains(&canonical) {
773 continue;
774 }
775 if rec.act_time() > now.saturating_add(OBSERVED_AT_SKEW_SECS) {
776 out.refused.push(RefusedCheckRow {
777 entity: rec.entity.clone(),
778 kind: sealed_kind_of(&rec),
779 act_time: rec.act_time(),
780 identity: rec.identity.clone(),
781 reason: format!(
782 "the row's time of the act ({}) lies more than {OBSERVED_AT_SKEW_SECS} \
783 seconds ahead of this engine's clock ({now}); a check is recorded after \
784 it was made, never before",
785 rec.act_time()
786 ),
787 });
788 continue;
789 }
790 self.record(&rec)?;
791 out.appended += 1;
792 }
793 Ok(out)
794 }
795
796 fn raw_lines(&self) -> Vec<CheckRecord> {
804 let Ok(content) = std::fs::read_to_string(&self.path) else {
805 return Vec::new();
806 };
807 content
808 .lines()
809 .filter_map(|l| serde_json::from_str(l).ok())
810 .collect()
811 }
812
813 pub fn in_standing_order(&self) -> Vec<CheckRecord> {
831 standing_order(self.raw_lines())
832 }
833
834 pub fn latest_for(&self, entity: &str) -> Option<CheckRecord> {
839 self.in_standing_order()
840 .into_iter()
841 .rev()
842 .find(|r| r.entity == entity)
843 }
844
845 pub fn latest_for_kind(&self, entity: &str, kind: CheckKind) -> Option<CheckRecord> {
849 self.in_standing_order()
850 .into_iter()
851 .rev()
852 .find(|r| r.entity == entity && r.resolved_kind() == Some(kind))
853 }
854
855 pub fn latest_for_wire_kind(&self, entity: &str, kind: &str) -> Option<CheckRecord> {
861 match CheckKind::from_wire(kind) {
862 Some(k) => self.latest_for_kind(entity, k),
863 None => self
864 .in_standing_order()
865 .into_iter()
866 .rev()
867 .find(|r| r.entity == entity && r.kind.as_deref() == Some(kind)),
868 }
869 }
870}
871
872#[derive(Debug, Clone, Default, PartialEq, Eq)]
875pub struct MergedRows {
876 pub appended: usize,
878 pub refused: Vec<RefusedCheckRow>,
880}
881
882#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
885pub struct RefusedCheckRow {
886 pub entity: String,
888 pub kind: String,
890 pub act_time: u64,
892 #[serde(default, skip_serializing_if = "Option::is_none")]
894 pub identity: Option<String>,
895 pub reason: String,
897}
898
899fn standing_order(rows: Vec<CheckRecord>) -> Vec<CheckRecord> {
902 let carries: Vec<(String, String, String, u64, Option<u32>)> = rows
905 .iter()
906 .filter_map(|r| {
907 r.carried_from.as_ref().map(|c| {
908 (
909 r.entity.clone(),
910 sealed_kind_of(r),
911 c.hash.clone(),
912 r.act_time(),
913 c.depth,
914 )
915 })
916 })
917 .collect();
918 let depth_of = |r: &CheckRecord| r.carried_from.as_ref().and_then(|c| c.depth).unwrap_or(0);
929 let superseded = |r: &CheckRecord| {
930 let kind = sealed_kind_of(r);
931 let depth = depth_of(r);
932 carries.iter().any(|(entity, k, left, at, d)| {
933 *entity == r.entity
934 && *k == kind
935 && *left == r.entity_hash
936 && r.act_time() <= *at
937 && d.is_none_or(|d| depth < d)
938 })
939 };
940 let mut keyed: Vec<(bool, u64, String, CheckRecord)> = rows
941 .into_iter()
942 .map(|r| {
943 let sup = superseded(&r);
944 let bytes = serde_json::to_string(&r).unwrap_or_default();
945 (!sup, r.act_time(), bytes, r)
946 })
947 .collect();
948 keyed.sort_by(|a, b| (a.0, a.1, &a.2).cmp(&(b.0, b.1, &b.2)));
949 keyed.into_iter().map(|(_, _, _, r)| r).collect()
950}
951
952pub const SEALED_CHECKS_VERSION: u32 = 1;
962
963#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
970pub struct SealedCheck {
971 pub ts: u64,
973 #[serde(default, skip_serializing_if = "Option::is_none")]
976 pub observed_at: Option<u64>,
977 pub verdict: String,
979 #[serde(default, skip_serializing_if = "Option::is_none")]
982 pub method: Option<String>,
983 pub entity_hash: String,
986 pub actor: String,
988 pub role: String,
990 #[serde(default, skip_serializing_if = "Option::is_none")]
992 pub identity: Option<String>,
993 #[serde(default, skip_serializing_if = "Option::is_none")]
995 pub schema_ref: Option<String>,
996 #[serde(default, skip_serializing_if = "Option::is_none")]
998 pub renamed_from: Option<String>,
999 #[serde(default, skip_serializing_if = "Option::is_none")]
1003 pub carried_from: Option<CarriedFrom>,
1004 #[serde(default, skip_serializing_if = "Option::is_none")]
1013 pub independence: Option<String>,
1014 #[serde(default, skip_serializing_if = "Option::is_none")]
1029 pub origin: Option<String>,
1030}
1031
1032impl SealedCheck {
1033 pub fn from_record(rec: &CheckRecord) -> Self {
1037 Self {
1038 ts: rec.ts,
1039 observed_at: rec.observed_at,
1040 verdict: rec.verdict.clone(),
1041 method: rec.method.clone(),
1042 entity_hash: rec.entity_hash.clone(),
1043 actor: rec.actor.clone(),
1044 role: rec.role.clone(),
1045 identity: rec.identity.clone(),
1046 schema_ref: rec.schema_ref.clone(),
1047 renamed_from: rec.renamed_from.clone(),
1048 carried_from: rec.carried_from.clone(),
1049 independence: None,
1050 origin: None,
1051 }
1052 }
1053
1054 pub fn sealed_independence(&self) -> Option<crate::engine::independence::Independence> {
1057 self.independence
1058 .as_deref()
1059 .and_then(crate::engine::independence::Independence::from_wire)
1060 }
1061
1062 pub fn sealed_origin(&self) -> Option<crate::render::OriginClass> {
1074 match self.origin.as_deref()? {
1075 "first-party" => Some(crate::render::OriginClass::FirstParty),
1076 "third-party" => Some(crate::render::OriginClass::ThirdParty),
1077 _ => None,
1078 }
1079 }
1080
1081 pub fn to_record(&self, entity_id: &str, kind: &str) -> CheckRecord {
1087 CheckRecord {
1088 ts: self.ts,
1089 observed_at: self.observed_at,
1090 entity: entity_id.to_string(),
1091 verdict: self.verdict.clone(),
1092 method: self.method.clone(),
1093 entity_hash: self.entity_hash.clone(),
1094 actor: self.actor.clone(),
1095 client: None,
1096 role: self.role.clone(),
1097 identity: self.identity.clone(),
1098 kind: (kind != CheckKind::Verification.as_str()).then(|| kind.to_string()),
1099 schema_ref: self.schema_ref.clone(),
1100 finding: None,
1101 renamed_from: self.renamed_from.clone(),
1102 carried_from: self.carried_from.clone(),
1103 checked_write: None,
1104 }
1105 }
1106}
1107
1108#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1112pub struct SealedChecks {
1113 pub version: u32,
1114 #[serde(default)]
1115 pub entities: BTreeMap<String, BTreeMap<String, SealedCheck>>,
1116}
1117
1118impl SealedChecks {
1119 pub fn new() -> Self {
1121 Self {
1122 version: SEALED_CHECKS_VERSION,
1123 entities: BTreeMap::new(),
1124 }
1125 }
1126
1127 pub fn latest(&self, entity_path: &str, kind: &str) -> Option<&SealedCheck> {
1130 self.entities
1131 .get(entity_path)
1132 .and_then(|kinds| kinds.get(kind))
1133 }
1134
1135 pub fn kinds_of(&self, entity_path: &str) -> impl Iterator<Item = (&str, &SealedCheck)> {
1137 self.entities
1138 .get(entity_path)
1139 .into_iter()
1140 .flat_map(|kinds| kinds.iter().map(|(k, v)| (k.as_str(), v)))
1141 }
1142
1143 pub fn rekey_entity(&mut self, entity_path: &str, pre_hash: &str, post_hash: &str) -> usize {
1154 if pre_hash == post_hash {
1155 return 0;
1156 }
1157 let Some(kinds) = self.entities.get_mut(entity_path) else {
1158 return 0;
1159 };
1160 let mut moved = 0;
1161 for rec in kinds.values_mut() {
1162 if rec.entity_hash == pre_hash {
1163 rec.entity_hash = post_hash.to_string();
1164 rec.carried_from = Some(CarriedFrom::export(pre_hash));
1165 moved += 1;
1166 }
1167 }
1168 moved
1169 }
1170
1171 pub fn to_archive_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
1175 let mut s = serde_json::to_string_pretty(self)?;
1176 s.push('\n');
1177 Ok(s.into_bytes())
1178 }
1179
1180 pub fn from_archive_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
1183 serde_json::from_slice(bytes)
1184 }
1185
1186 pub fn validate(&self, carried: &std::collections::BTreeSet<String>) -> Result<(), String> {
1192 if self.version != SEALED_CHECKS_VERSION {
1193 return Err(format!(
1194 "version {} is not the version this engine reads ({SEALED_CHECKS_VERSION})",
1195 self.version
1196 ));
1197 }
1198 for (path, kinds) in &self.entities {
1199 if !carried.contains(path) {
1200 return Err(format!(
1201 "entity `{path}` names no entity the archive carries"
1202 ));
1203 }
1204 for (kind, rec) in kinds {
1205 let at = format!("entity `{path}`, kind `{kind}`");
1206 if RecordKind::from_wire(kind).is_none() {
1207 return Err(format!(
1208 "{at}: the kind is not one of {}",
1209 RecordKind::vocabulary_hint()
1210 ));
1211 }
1212 if Verdict::from_wire(&rec.verdict).is_none() {
1213 return Err(format!(
1214 "{at}: verdict `{}` is not one of {}",
1215 rec.verdict,
1216 VERDICTS.join(", ")
1217 ));
1218 }
1219 if rec.entity_hash.trim().is_empty() {
1220 return Err(format!("{at}: entity_hash is empty"));
1221 }
1222 if rec.actor.trim().is_empty() {
1223 return Err(format!("{at}: actor is empty"));
1224 }
1225 if rec.role.trim().is_empty() {
1226 return Err(format!("{at}: role is empty"));
1227 }
1228 if let Some(reading) = rec.independence.as_deref()
1229 && crate::engine::independence::Independence::from_wire(reading).is_none()
1230 {
1231 return Err(format!(
1232 "{at}: independence `{reading}` is not one of {}",
1233 crate::engine::independence::Independence::vocabulary_hint()
1234 ));
1235 }
1236 if let Some(origin) = rec.origin.as_deref()
1242 && rec.sealed_origin().is_none()
1243 {
1244 return Err(format!(
1245 "{at}: origin `{origin}` is not one of first-party | third-party"
1246 ));
1247 }
1248 }
1249 }
1250 Ok(())
1251 }
1252}
1253
1254impl Default for SealedChecks {
1255 fn default() -> Self {
1256 Self::new()
1257 }
1258}
1259
1260pub fn sealed_kind_of(rec: &CheckRecord) -> String {
1264 match rec.resolved_kind() {
1265 Some(k) => k.as_str().to_string(),
1266 None => rec.kind.clone().unwrap_or_default(),
1267 }
1268}
1269
1270#[cfg(test)]
1271mod tests {
1272 use super::*;
1273 use tempfile::TempDir;
1274
1275 fn rec(entity: &str, verdict: &str, hash: &str) -> CheckRecord {
1276 CheckRecord {
1277 ts: 1,
1278 observed_at: None,
1279 entity: entity.to_string(),
1280 verdict: verdict.to_string(),
1281 method: None,
1282 entity_hash: hash.to_string(),
1283 actor: "cli".to_string(),
1284 client: None,
1285 role: "checker".to_string(),
1286 identity: None,
1287 kind: None,
1288 schema_ref: None,
1289 finding: None,
1290 renamed_from: None,
1291 carried_from: None,
1292 checked_write: None,
1293 }
1294 }
1295
1296 fn at(entity: &str, verdict: &str, hash: &str, ts: u64) -> CheckRecord {
1297 CheckRecord {
1298 ts,
1299 ..rec(entity, verdict, hash)
1300 }
1301 }
1302
1303 fn line(r: &CheckRecord) -> Vec<u8> {
1304 let mut l = serde_json::to_vec(r).unwrap();
1305 l.push(b'\n');
1306 l
1307 }
1308
1309 #[test]
1313 fn a_merged_row_stands_by_its_time_of_the_act_not_its_arrival() {
1314 let now = 10_000;
1315 let tmp = TempDir::new().unwrap();
1316 let ledger = CheckLedger::for_workspace(tmp.path());
1317 ledger.record(&at("m--e", "ok", "h1", 200)).unwrap();
1318 let merged = ledger
1319 .merge_transport_lines(&line(&at("m--e", "failed", "h1", 100)), now)
1320 .unwrap();
1321 assert_eq!(merged.appended, 1);
1322 let standing = ledger
1323 .latest_for_kind("m--e", CheckKind::Verification)
1324 .unwrap();
1325 assert_eq!((standing.verdict.as_str(), standing.ts), ("ok", 200));
1326
1327 ledger
1328 .merge_transport_lines(&line(&at("m--e", "failed", "h1", 300)), now)
1329 .unwrap();
1330 let standing = ledger
1331 .latest_for_kind("m--e", CheckKind::Verification)
1332 .unwrap();
1333 assert_eq!((standing.verdict.as_str(), standing.ts), ("failed", 300));
1334 }
1335
1336 #[test]
1339 fn checks_recorded_out_of_order_stand_by_observed_at() {
1340 let tmp = TempDir::new().unwrap();
1341 let ledger = CheckLedger::for_workspace(tmp.path());
1342 let mut later = at("m--e", "ok", "h1", 500);
1343 later.observed_at = Some(400);
1344 let mut earlier = at("m--e", "failed", "h1", 501);
1345 earlier.observed_at = Some(100);
1346 ledger.record(&later).unwrap();
1347 ledger.record(&earlier).unwrap();
1348 let standing = ledger.latest_for_wire_kind("m--e", "verification").unwrap();
1349 assert_eq!(standing.verdict, "ok");
1350 }
1351
1352 #[test]
1356 fn a_carried_line_stands_over_its_source() {
1357 for order in [false, true] {
1358 let tmp = TempDir::new().unwrap();
1359 let ledger = CheckLedger::for_workspace(tmp.path());
1360 let mut source = at("m--e", "ok", "h1", 100);
1361 source.kind = Some("x-approval".into());
1362 let carried = CheckRecord {
1363 entity_hash: "h2".into(),
1364 carried_from: Some(CarriedFrom::transition("h1")),
1365 checked_write: None,
1366 ..source.clone()
1367 };
1368 let mut sibling = at("m--e", "ok", "zz-sibling", 100);
1371 sibling.entity_hash = "h1".into();
1372 sibling.kind = Some("x-approval".into());
1373 sibling.method = Some("zzzz".into());
1374 let mut rows = vec![source.clone(), carried.clone(), sibling];
1375 if order {
1376 rows.reverse();
1377 }
1378 for r in &rows {
1379 ledger.record(r).unwrap();
1380 }
1381 let standing = ledger.latest_for_wire_kind("m--e", "x-approval").unwrap();
1382 assert_eq!(standing.entity_hash, "h2", "order reversed: {order}");
1383 assert!(standing.carried_from.is_some());
1384 }
1385 }
1386
1387 #[test]
1391 fn a_check_after_a_return_to_the_carried_from_hash_stands() {
1392 let tmp = TempDir::new().unwrap();
1393 let ledger = CheckLedger::for_workspace(tmp.path());
1394 let source = at("m--e", "ok", "h1", 100);
1395 ledger.record(&source).unwrap();
1396 ledger
1397 .record(&CheckRecord {
1398 entity_hash: "h2".into(),
1399 carried_from: Some(CarriedFrom::transition("h1")),
1400 checked_write: None,
1401 ..source.clone()
1402 })
1403 .unwrap();
1404 ledger.record(&at("m--e", "failed", "h1", 500)).unwrap();
1405 let standing = ledger
1406 .latest_for_kind("m--e", CheckKind::Verification)
1407 .unwrap();
1408 assert_eq!((standing.verdict.as_str(), standing.ts), ("failed", 500));
1409
1410 let a = at("m--e", "ok", "h1", 100);
1411 let carry = |hash: &str, from: &str, depth: u32| CheckRecord {
1412 entity_hash: hash.into(),
1413 carried_from: Some(CarriedFrom::transition_at(from, depth)),
1414 ..a.clone()
1415 };
1416 let read = |rows: &[&CheckRecord]| {
1417 let tmp = TempDir::new().unwrap();
1418 let ledger = CheckLedger::for_workspace(tmp.path());
1419 for r in rows {
1420 ledger.record(r).unwrap();
1421 }
1422 ledger
1423 .latest_for_kind("m--e", CheckKind::Verification)
1424 .unwrap()
1425 };
1426 let (mid, last) = (carry("h2", "h1", 1), carry("h3", "h2", 2));
1428 assert_eq!(read(&[&last, &a, &mid]).entity_hash, "h3");
1429 assert_eq!(read(&[&mid, &last, &a]).entity_hash, "h3");
1430 let (b1, back, b2) = (
1434 carry("h2", "h1", 1),
1435 carry("h1", "h2", 2),
1436 carry("h2", "h1", 3),
1437 );
1438 for rows in [
1439 [&a, &b1, &back, &b2],
1440 [&b2, &back, &b1, &a],
1441 [&back, &a, &b2, &b1],
1442 ] {
1443 let standing = read(&rows);
1444 assert_eq!(standing.entity_hash, "h2");
1445 assert_eq!(standing.carried_from.as_ref().unwrap().depth, Some(3));
1446 }
1447 let old = |hash: &str, from: &str| CheckRecord {
1449 entity_hash: hash.into(),
1450 carried_from: Some(CarriedFrom {
1451 depth: None,
1452 ..CarriedFrom::transition(from)
1453 }),
1454 ..a.clone()
1455 };
1456 assert_eq!(
1457 read(&[&old("h3", "h2"), &a, &old("h2", "h1")]).entity_hash,
1458 "h3"
1459 );
1460 }
1461
1462 #[test]
1465 fn two_ledgers_with_the_same_rows_derive_the_same_newest() {
1466 let mut a = at("m--e", "ok", "h1", 100);
1467 a.identity = Some("grader-a".into());
1468 let mut b = at("m--e", "failed", "h1", 100);
1469 b.identity = Some("grader-b".into());
1470 let c = at("m--e", "ok", "h1", 50);
1471 let rows = [a, b, c];
1472 let mut standings = Vec::new();
1473 for perm in [[0, 1, 2], [1, 0, 2], [2, 1, 0], [1, 2, 0]] {
1474 let tmp = TempDir::new().unwrap();
1475 let ledger = CheckLedger::for_workspace(tmp.path());
1476 for i in perm {
1477 ledger.record(&rows[i]).unwrap();
1478 }
1479 let s = ledger
1480 .latest_for_kind("m--e", CheckKind::Verification)
1481 .unwrap();
1482 standings.push(serde_json::to_string(&s).unwrap());
1483 assert_eq!(
1484 serde_json::to_string(&ledger.in_standing_order()).unwrap(),
1485 serde_json::to_string(&standing_order(rows.to_vec())).unwrap(),
1486 "the whole order is derived from the rows alone"
1487 );
1488 }
1489 standings.dedup();
1490 assert_eq!(standings.len(), 1, "{standings:?}");
1491 }
1492
1493 #[test]
1498 fn a_local_recheck_in_the_same_second_stands_over_the_earlier_check() {
1499 let tmp = TempDir::new().unwrap();
1500 let ledger = CheckLedger::for_workspace(tmp.path());
1501 ledger
1503 .record_local(at("m--e", "ok", "zz-old", 1000))
1504 .unwrap();
1505 let fresh = ledger.record_local(at("m--e", "ok", "h2", 1000)).unwrap();
1506 assert_eq!(fresh.ts, 1001);
1507 let standing = ledger
1508 .latest_for_kind("m--e", CheckKind::Verification)
1509 .unwrap();
1510 assert_eq!(standing.entity_hash, "h2");
1511 let mut stated = at("m--e", "ok", "h3", 1000);
1512 stated.observed_at = Some(900);
1513 assert_eq!(ledger.record_local(stated).unwrap().ts, 1000);
1514 assert_eq!(
1516 ledger.record_local(at("m--f", "ok", "h", 5000)).unwrap().ts,
1517 5000
1518 );
1519 }
1520
1521 #[test]
1525 fn a_merged_row_from_the_future_is_refused_and_named() {
1526 let now = 10_000;
1527 let tmp = TempDir::new().unwrap();
1528 let ledger = CheckLedger::for_workspace(tmp.path());
1529 let mut future = at("m--e", "ok", "h1", now + OBSERVED_AT_SKEW_SECS + 1);
1530 future.identity = Some("clock-wrong".into());
1531 let mut dated_future = at("m--e", "ok", "h1", 100);
1532 dated_future.observed_at = Some(now + 10 * OBSERVED_AT_SKEW_SECS);
1533 let inside = at("m--e", "ok", "h1", now + OBSERVED_AT_SKEW_SECS);
1534 let mut bytes = line(&future);
1535 bytes.extend(line(&dated_future));
1536 bytes.extend(line(&inside));
1537 let merged = ledger.merge_transport_lines(&bytes, now).unwrap();
1538 assert_eq!(merged.appended, 1);
1539 assert_eq!(merged.refused.len(), 2);
1540 assert_eq!(merged.refused[0].entity, "m--e");
1541 assert_eq!(merged.refused[0].identity.as_deref(), Some("clock-wrong"));
1542 assert_eq!(merged.refused[1].act_time, now + 10 * OBSERVED_AT_SKEW_SECS);
1543 assert_eq!(ledger.raw_lines().len(), 1);
1544 }
1545
1546 #[test]
1547 fn state_derivation_covers_all_four_states() {
1548 assert_eq!(derive_state(None, "h1"), CheckState::NeverChecked);
1549 let ok = rec("m--e", "ok", "h1");
1550 assert_eq!(derive_state(Some(&ok), "h1"), CheckState::CheckedOk);
1551 assert_eq!(derive_state(Some(&ok), "h2"), CheckState::CheckStale);
1552 let failed = rec("m--e", "failed", "h1");
1553 assert_eq!(derive_state(Some(&failed), "h1"), CheckState::CheckFailed);
1554 assert_eq!(derive_state(Some(&failed), "h2"), CheckState::CheckStale);
1557 }
1558
1559 #[test]
1560 fn ledger_appends_and_serves_newest_per_entity() {
1561 let tmp = TempDir::new().unwrap();
1562 let ledger = CheckLedger::for_workspace(tmp.path());
1563 assert!(ledger.latest_for("m--a").is_none());
1564 ledger.record(&at("m--a", "failed", "h1", 1)).unwrap();
1565 ledger.record(&at("m--b", "ok", "h9", 2)).unwrap();
1566 ledger.record(&at("m--a", "ok", "h2", 3)).unwrap();
1567 let latest = ledger.latest_for("m--a").unwrap();
1568 assert_eq!(latest.verdict, "ok");
1569 assert_eq!(latest.entity_hash, "h2");
1570 assert_eq!(ledger.raw_lines().len(), 3);
1572 }
1573
1574 #[test]
1586 fn observed_at_parses_refuses_the_future_and_survives_the_carries() {
1587 let now = 1_792_503_930; assert_eq!(parse_observed_at("2026-10-19", now), Ok(1_792_368_000));
1589 assert_eq!(parse_observed_at(" 2026-10-20T13:45:30Z ", now), Ok(now));
1590 assert!(parse_observed_at("2026-10-20T13:50:00Z", now).is_ok());
1592 let err = parse_observed_at("2026-10-20T13:51:00Z", now).unwrap_err();
1593 assert!(err.contains("future"), "{err}");
1594 let err = parse_observed_at("20.10.2026", now).unwrap_err();
1595 assert!(err.contains("ISO-8601"), "{err}");
1596
1597 let tmp = TempDir::new().unwrap();
1598 let ledger = CheckLedger::for_workspace(tmp.path());
1599 let mut dated = rec("m--old", "ok", "h1");
1600 dated.observed_at = Some(1_792_368_000);
1601 ledger.record(&dated).unwrap();
1602 ledger.record(&rec("m--old", "ok", "h2")).unwrap();
1603 assert_eq!(ledger.carry_rename("m--old", "m--new").unwrap(), 2);
1604 let carried: Vec<CheckRecord> = ledger
1605 .raw_lines()
1606 .into_iter()
1607 .filter(|r| r.entity == "m--new")
1608 .collect();
1609 assert_eq!(carried[0].observed_at, Some(1_792_368_000));
1610 assert_eq!(carried[1].observed_at, None);
1611
1612 let sealed = SealedCheck::from_record(&dated);
1613 assert_eq!(sealed.observed_at, Some(1_792_368_000));
1614 assert_eq!(
1615 sealed.to_record("m--old", "verification").observed_at,
1616 Some(1_792_368_000)
1617 );
1618
1619 let raw = std::fs::read_to_string(check_ledger_path(tmp.path())).unwrap();
1620 let lines: Vec<&str> = raw.lines().collect();
1621 assert!(
1622 lines[0].contains("\"observed_at\":1792368000"),
1623 "{}",
1624 lines[0]
1625 );
1626 assert!(!lines[1].contains("observed_at"), "{}", lines[1]);
1627 }
1628
1629 #[test]
1630 fn carry_rename_rekeys_without_erasing() {
1631 let tmp = TempDir::new().unwrap();
1632 let ledger = CheckLedger::for_workspace(tmp.path());
1633 ledger.record(&rec("m--old", "ok", "h1")).unwrap();
1634 ledger.record(&rec("m--other", "ok", "h9")).unwrap();
1635 let mut conf = rec("m--old", "failed", "h1");
1636 conf.kind = Some("conformance".into());
1637 ledger.record(&conf).unwrap();
1638
1639 assert_eq!(ledger.carry_rename("m--old", "m--new").unwrap(), 2);
1640 assert_eq!(ledger.carry_rename("m--absent", "m--new").unwrap(), 0);
1641
1642 let all = ledger.raw_lines();
1643 assert_eq!(all.len(), 5);
1644 assert!(all.iter().filter(|r| r.entity == "m--old").count() == 2);
1645 let carried: Vec<&CheckRecord> = all.iter().filter(|r| r.entity == "m--new").collect();
1646 assert_eq!(carried.len(), 2);
1647 assert!(
1648 carried
1649 .iter()
1650 .all(|r| r.renamed_from.as_deref() == Some("m--old"))
1651 );
1652 let latest = ledger
1653 .latest_for_kind("m--new", CheckKind::Verification)
1654 .unwrap();
1655 assert_eq!(latest.verdict, "ok");
1656 assert_eq!(derive_state(Some(&latest), "h1"), CheckState::CheckedOk);
1657 assert_eq!(
1658 derive_state(Some(&latest), "h2-after-rename"),
1659 CheckState::CheckStale
1660 );
1661 assert_eq!(
1662 ledger
1663 .latest_for_kind("m--new", CheckKind::Conformance)
1664 .unwrap()
1665 .verdict,
1666 "failed"
1667 );
1668 assert!(
1670 ledger
1671 .latest_for("m--other")
1672 .unwrap()
1673 .renamed_from
1674 .is_none()
1675 );
1676 }
1677
1678 #[test]
1684 fn carry_transition_moves_only_the_fresh_confirming_record() {
1685 let tmp = TempDir::new().unwrap();
1686 let ledger = CheckLedger::for_workspace(tmp.path());
1687 let mut ok = rec("m--plan", "ok", "h1");
1688 ok.kind = Some("x-projection".into());
1689 ok.identity = Some("checker-c".into());
1690 ledger.record(&ok).unwrap();
1691
1692 assert!(
1693 !ledger
1694 .carry_transition("m--plan", "x-projection", "h1", "h1")
1695 .unwrap()
1696 );
1697 assert!(
1698 !ledger
1699 .carry_transition("m--plan", "x-projection", "h0", "h2")
1700 .unwrap()
1701 );
1702 assert!(
1703 !ledger
1704 .carry_transition("m--plan", "verification", "h1", "h2")
1705 .unwrap()
1706 );
1707 assert_eq!(ledger.raw_lines().len(), 1, "nothing appended so far");
1708
1709 assert!(
1710 ledger
1711 .carry_transition("m--plan", "x-projection", "h1", "h2")
1712 .unwrap()
1713 );
1714 let all = ledger.raw_lines();
1715 assert_eq!(all.len(), 2, "append-only: the original stays");
1716 let carried = ledger
1717 .latest_for_wire_kind("m--plan", "x-projection")
1718 .unwrap();
1719 assert_eq!(carried.entity_hash, "h2");
1720 assert_eq!(carried.identity.as_deref(), Some("checker-c"));
1721 assert_eq!(carried.verdict, "ok");
1722 assert_eq!(carried.carried_from, Some(CarriedFrom::transition("h1")));
1723 assert_eq!(derive_state(Some(&carried), "h2"), CheckState::CheckedOk);
1724 assert!(
1726 ledger
1727 .carry_transition("m--plan", "x-projection", "h2", "h3")
1728 .unwrap()
1729 );
1730 let again = ledger
1731 .latest_for_wire_kind("m--plan", "x-projection")
1732 .unwrap();
1733 assert_eq!(again.carried_from.as_ref().unwrap().hash, "h2");
1734
1735 let mut failed = rec("m--other", "failed", "h1");
1737 failed.kind = Some("x-projection".into());
1738 ledger.record(&failed).unwrap();
1739 assert!(
1740 !ledger
1741 .carry_transition("m--other", "x-projection", "h1", "h2")
1742 .unwrap()
1743 );
1744 assert!(all[0].carried_from.is_none());
1746 }
1747
1748 #[test]
1751 fn sealed_rekey_moves_fresh_records_and_leaves_stale_ones() {
1752 let mut sealed = SealedChecks::new();
1753 let fresh = SealedCheck::from_record(&rec("m--a", "ok", "h1"));
1754 let mut stale = SealedCheck::from_record(&rec("m--a", "ok", "h0"));
1755 stale.ts = 0;
1756 sealed.entities.insert(
1757 "a".into(),
1758 BTreeMap::from([
1759 ("verification".to_string(), fresh),
1760 ("x-audit".to_string(), stale),
1761 ]),
1762 );
1763 assert_eq!(sealed.rekey_entity("a", "h1", "h1"), 0);
1764 assert_eq!(sealed.rekey_entity("absent", "h1", "h2"), 0);
1765 assert_eq!(sealed.rekey_entity("a", "h1", "h2"), 1);
1766 let v = sealed.latest("a", "verification").unwrap();
1767 assert_eq!(v.entity_hash, "h2");
1768 assert_eq!(v.carried_from.as_ref().unwrap().reason, CARRY_REASON_EXPORT);
1769 assert_eq!(v.carried_from.as_ref().unwrap().hash, "h1");
1770 let x = sealed.latest("a", "x-audit").unwrap();
1771 assert_eq!(x.entity_hash, "h0", "stale stays stale");
1772 assert!(x.carried_from.is_none());
1773 let back = v.to_record("m--a", "verification");
1775 assert_eq!(back.carried_from, v.carried_from);
1776 assert_eq!(SealedCheck::from_record(&back), *v);
1777 let legacy = r#"{"ts":1,"verdict":"ok","entity_hash":"h","actor":"cli","role":"checker"}"#;
1779 let parsed: SealedCheck = serde_json::from_str(legacy).unwrap();
1780 assert!(parsed.carried_from.is_none());
1781 assert!(parsed.independence.is_none());
1782 assert!(parsed.sealed_independence().is_none());
1783 }
1784
1785 #[test]
1792 fn sealed_row_origin_parses_only_from_the_closed_vocabulary() {
1793 let mut sealed = SealedChecks::new();
1794 let mut row = SealedCheck::from_record(&rec("m--a", "ok", "h1"));
1795 row.origin = Some("third-party".to_string());
1796 sealed.entities.insert(
1797 "a".into(),
1798 BTreeMap::from([("verification".to_string(), row)]),
1799 );
1800 assert_eq!(
1801 sealed.latest("a", "verification").unwrap().sealed_origin(),
1802 Some(crate::render::OriginClass::ThirdParty)
1803 );
1804 let carried: std::collections::BTreeSet<String> = ["a".to_string()].into();
1805 assert!(sealed.validate(&carried).is_ok());
1806
1807 let legacy = r#"{"ts":1,"verdict":"ok","entity_hash":"h","actor":"cli","role":"checker"}"#;
1809 let parsed: SealedCheck = serde_json::from_str(legacy).unwrap();
1810 assert!(parsed.origin.is_none());
1811 assert!(parsed.sealed_origin().is_none());
1812
1813 sealed
1816 .entities
1817 .get_mut("a")
1818 .unwrap()
1819 .get_mut("verification")
1820 .unwrap()
1821 .origin = Some("trusted".into());
1822 assert!(
1823 sealed
1824 .latest("a", "verification")
1825 .unwrap()
1826 .sealed_origin()
1827 .is_none()
1828 );
1829 let err = sealed.validate(&carried).unwrap_err();
1830 assert!(err.contains("origin `trusted`"), "{err}");
1831 }
1832
1833 #[test]
1838 fn sealed_independence_is_kept_by_rekey_and_closed_in_vocabulary() {
1839 use crate::engine::independence::Independence;
1840 let mut sealed = SealedChecks::new();
1841 let mut fresh = SealedCheck::from_record(&rec("m--a", "ok", "h1"));
1842 fresh.independence = Some(Independence::ConfirmedIndependent.as_str().to_string());
1843 sealed.entities.insert(
1844 "a".into(),
1845 BTreeMap::from([("verification".to_string(), fresh)]),
1846 );
1847 assert_eq!(sealed.rekey_entity("a", "h1", "h2"), 1);
1848 let v = sealed.latest("a", "verification").unwrap();
1849 assert_eq!(
1850 v.sealed_independence(),
1851 Some(Independence::ConfirmedIndependent)
1852 );
1853 let bytes = sealed.to_archive_bytes().unwrap();
1854 let back = SealedChecks::from_archive_bytes(&bytes).unwrap();
1855 assert_eq!(back, sealed);
1856 assert!(v.to_record("m--a", "verification").carried_from.is_some());
1857 let carried: std::collections::BTreeSet<String> = ["a".to_string()].into();
1858 assert!(back.validate(&carried).is_ok());
1859
1860 let mut foreign = sealed.clone();
1861 foreign
1862 .entities
1863 .get_mut("a")
1864 .unwrap()
1865 .get_mut("verification")
1866 .unwrap()
1867 .independence = Some("trusted".into());
1868 assert!(
1869 foreign
1870 .latest("a", "verification")
1871 .unwrap()
1872 .sealed_independence()
1873 .is_none()
1874 );
1875 let err = foreign.validate(&carried).unwrap_err();
1876 assert!(err.contains("independence `trusted`"), "{err}");
1877 }
1878
1879 #[test]
1880 fn verdict_vocabulary_is_closed() {
1881 assert!(Verdict::from_wire("ok").is_some());
1882 assert!(Verdict::from_wire("failed").is_some());
1883 assert!(Verdict::from_wire("passed").is_none());
1884 assert!(Verdict::from_wire("OK").is_none());
1885 }
1886
1887 fn conf(entity: &str, verdict: &str, hash: &str, pin: &str) -> CheckRecord {
1888 CheckRecord {
1889 kind: Some("conformance".to_string()),
1890 schema_ref: Some(pin.to_string()),
1891 ..rec(entity, verdict, hash)
1892 }
1893 }
1894
1895 #[test]
1896 fn kind_vocabulary_is_closed() {
1897 assert!(CheckKind::from_wire("verification").is_some());
1898 assert!(CheckKind::from_wire("conformance").is_some());
1899 assert!(CheckKind::from_wire("semantic").is_none());
1900 assert!(CheckKind::from_wire("Conformance").is_none());
1901 }
1902
1903 #[test]
1907 fn legacy_lines_read_as_verification() {
1908 let legacy = r#"{"ts":1,"entity":"m--e","verdict":"ok","entity_hash":"h1","actor":"cli","role":"checker"}"#;
1909 let parsed: CheckRecord = serde_json::from_str(legacy).unwrap();
1910 assert_eq!(parsed.resolved_kind(), Some(CheckKind::Verification));
1911 let fresh = rec("m--e", "ok", "h1");
1914 let line = serde_json::to_string(&fresh).unwrap();
1915 assert!(!line.contains("kind"));
1916 assert!(!line.contains("schema_ref"));
1917 assert!(!line.contains("identity"));
1921 }
1922
1923 #[test]
1926 fn latest_is_per_kind() {
1927 let tmp = TempDir::new().unwrap();
1928 let ledger = CheckLedger::for_workspace(tmp.path());
1929 ledger.record(&rec("m--a", "ok", "h1")).unwrap();
1930 ledger
1931 .record(&conf("m--a", "failed", "h1", "planning@1.0.0"))
1932 .unwrap();
1933 let v = ledger
1934 .latest_for_kind("m--a", CheckKind::Verification)
1935 .unwrap();
1936 assert_eq!(v.verdict, "ok");
1937 let c = ledger
1938 .latest_for_kind("m--a", CheckKind::Conformance)
1939 .unwrap();
1940 assert_eq!(c.verdict, "failed");
1941 assert_eq!(c.schema_ref.as_deref(), Some("planning@1.0.0"));
1942 }
1943
1944 #[test]
1947 fn conformance_stales_on_pin_move_verification_does_not() {
1948 let c = conf("m--e", "ok", "h1", "planning@1.0.0");
1949 assert_eq!(
1950 derive_state_pinned(Some(&c), "h1", Some("planning@1.0.0")),
1951 CheckState::CheckedOk
1952 );
1953 assert_eq!(
1954 derive_state_pinned(Some(&c), "h2", Some("planning@1.0.0")),
1955 CheckState::CheckStale
1956 );
1957 assert_eq!(
1958 derive_state_pinned(Some(&c), "h1", Some("planning@2.0.0")),
1959 CheckState::CheckStale
1960 );
1961 assert_eq!(
1963 derive_state_pinned(Some(&c), "h1", None),
1964 CheckState::CheckStale
1965 );
1966 let v = rec("m--e", "ok", "h1");
1968 assert_eq!(
1969 derive_state_pinned(Some(&v), "h1", Some("planning@9.0.0")),
1970 CheckState::CheckedOk
1971 );
1972 assert_eq!(derive_state(Some(&v), "h1"), CheckState::CheckedOk);
1973 }
1974
1975 #[test]
1978 fn finding_shape_is_fixed_and_validated_whole() {
1979 let ok = CheckFinding::from_json(serde_json::json!({
1980 "code": "hidden-premise", "message": "The step assumes X.", "section": "step"
1981 }))
1982 .unwrap();
1983 assert_eq!(ok.code, "hidden-premise");
1984 assert_eq!(ok.section.as_deref(), Some("step"));
1985 for bad in [
1986 serde_json::json!({ "message": "no code" }),
1987 serde_json::json!({ "code": "x" }),
1988 serde_json::json!({ "code": "", "message": "empty code" }),
1989 serde_json::json!({ "code": "x", "message": " " }),
1990 serde_json::json!({ "code": "x", "message": "m", "severity": "high" }),
1991 serde_json::json!({ "code": "x", "message": "m", "section": "" }),
1992 ] {
1993 let err = CheckFinding::from_json(bad.clone())
1994 .unwrap_err()
1995 .to_string();
1996 assert!(err.contains("shape"), "{bad}: {err}");
1997 }
1998 }
1999
2000 #[test]
2001 fn open_kinds_parse_only_with_the_prefix_and_never_resolve_to_an_engine_kind() {
2002 assert_eq!(
2003 RecordKind::from_wire("verification"),
2004 Some(RecordKind::Engine(CheckKind::Verification))
2005 );
2006 assert_eq!(
2007 RecordKind::from_wire("x-step-walk"),
2008 Some(RecordKind::Foreign("x-step-walk".to_string()))
2009 );
2010 for bad in ["step-walk", "x-", "x-Step", "x--a", "x-a-", "X-a"] {
2011 assert!(RecordKind::from_wire(bad).is_none(), "{bad}");
2012 }
2013 assert!(RecordKind::vocabulary_hint().contains("x-<name>"));
2014 let mut r = rec("m--e", "ok", "h");
2015 r.kind = Some("x-step-walk".to_string());
2016 assert_eq!(r.resolved_kind(), None);
2017 assert_eq!(r.foreign_kind(), Some("x-step-walk"));
2018 r.kind = None;
2019 assert_eq!(r.resolved_kind(), Some(CheckKind::Verification));
2020 r.kind = Some("conformance".to_string());
2021 assert_eq!(r.resolved_kind(), Some(CheckKind::Conformance));
2022 r.kind = Some("mystery".to_string());
2024 assert_eq!(r.resolved_kind(), Some(CheckKind::Verification));
2025 }
2026
2027 #[test]
2028 fn pre_finding_ledger_lines_parse_and_derive_unchanged_and_findings_round_trip() {
2029 let tmp = TempDir::new().unwrap();
2030 let ledger = CheckLedger::for_workspace(tmp.path());
2031 let dir = check_ledger_path(tmp.path());
2032 std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
2033 std::fs::write(
2035 &dir,
2036 "{\"ts\":1,\"entity\":\"m--e\",\"verdict\":\"failed\",\"entity_hash\":\"h\",\"actor\":\"cli\",\"role\":\"unspecified\"}\n",
2037 )
2038 .unwrap();
2039 let old = ledger
2040 .latest_for_kind("m--e", CheckKind::Verification)
2041 .unwrap();
2042 assert!(old.finding.is_none());
2043 assert_eq!(derive_state(Some(&old), "h"), CheckState::CheckFailed);
2044
2045 let mut with = rec("m--e", "failed", "h");
2046 with.ts = 2;
2047 with.finding = Some(CheckFinding {
2048 code: "hidden-premise".into(),
2049 section: Some("step".into()),
2050 message: "The step assumes X.".into(),
2051 evidence: None,
2052 });
2053 ledger.record(&with).unwrap();
2054 let mut foreign = rec("m--e", "ok", "h");
2056 foreign.ts = 3;
2057 foreign.kind = Some("x-step-walk".into());
2058 ledger.record(&foreign).unwrap();
2059 let latest = ledger
2060 .latest_for_kind("m--e", CheckKind::Verification)
2061 .unwrap();
2062 assert_eq!(
2063 latest.ts, 2,
2064 "the foreign record is not the latest verification record"
2065 );
2066 assert_eq!(latest.finding.as_ref().unwrap().code, "hidden-premise");
2067 assert_eq!(derive_state(Some(&latest), "h"), CheckState::CheckFailed);
2068 let text = std::fs::read_to_string(&dir).unwrap();
2069 assert!(text.contains("\"finding\":{\"code\":\"hidden-premise\",\"section\":\"step\",\"message\":\"The step assumes X.\"}"), "{text}");
2070 assert!(text.contains("\"kind\":\"x-step-walk\""));
2071 assert_eq!(text.lines().count(), 3, "append-only");
2072 }
2073}