use std::collections::BTreeMap;
use std::io::Write;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
pub const VERDICTS: [&str; 2] = ["ok", "failed"];
pub const CHECK_KINDS: [&str; 2] = ["verification", "conformance"];
pub const FOREIGN_KIND_PREFIX: &str = "x-";
pub const INVALID_CHECK_FINDING_CODE: &str = "INVALID_CHECK_FINDING";
#[derive(Debug, Clone, thiserror::Error)]
#[error(
"batch check refused: {} of {total} entr(ies) failed validation, nothing recorded",
failed_entries.len()
)]
pub struct CheckBatchRefused {
pub failed_entries: Vec<serde_json::Value>,
pub total: usize,
}
impl CheckBatchRefused {
pub fn code(&self) -> &'static str {
"BATCH_REFUSED"
}
pub fn details(&self) -> serde_json::Value {
serde_json::json!({ "failed_entries": self.failed_entries })
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CheckKind {
Verification,
Conformance,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RecordKind {
Engine(CheckKind),
Foreign(String),
}
impl RecordKind {
pub fn from_wire(s: &str) -> Option<Self> {
if let Some(k) = CheckKind::from_wire(s) {
return Some(Self::Engine(k));
}
s.starts_with(FOREIGN_KIND_PREFIX)
.then(|| memstead_schema::check_kind_wire_is_well_formed(s))
.filter(|ok| *ok)
.map(|_| Self::Foreign(s.to_string()))
}
pub fn engine_kind(&self) -> Option<CheckKind> {
match self {
Self::Engine(k) => Some(*k),
Self::Foreign(_) => None,
}
}
pub fn as_wire(&self) -> &str {
match self {
Self::Engine(k) => k.as_str(),
Self::Foreign(s) => s.as_str(),
}
}
pub fn vocabulary_hint() -> String {
format!(
"{}, or a caller-declared `{FOREIGN_KIND_PREFIX}<name>` kind (lowercase letters, digits, hyphens) the engine records verbatim and never interprets",
CHECK_KINDS.join(", ")
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CheckFinding {
pub code: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub section: Option<String>,
pub message: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub evidence: Option<String>,
}
impl CheckFinding {
pub const SHAPE: &'static str =
"{code: <non-empty>, message: <non-empty>, section?: <key>, evidence?: <text>}";
pub fn validate(&self) -> Result<(), String> {
if self.code.trim().is_empty() {
return Err(format!(
"finding.code is required and must be non-empty — shape {}",
Self::SHAPE
));
}
if self.message.trim().is_empty() {
return Err(format!(
"finding.message is required and must be non-empty — shape {}",
Self::SHAPE
));
}
if self.section.as_deref().is_some_and(|s| s.trim().is_empty()) {
return Err(format!(
"finding.section, when given, must be non-empty — shape {}",
Self::SHAPE
));
}
if self
.evidence
.as_deref()
.is_some_and(|s| s.trim().is_empty())
{
return Err(format!(
"finding.evidence, when given, must be non-empty — shape {}",
Self::SHAPE
));
}
Ok(())
}
pub fn from_json(value: serde_json::Value) -> Result<Self, InvalidCheckFinding> {
let finding: CheckFinding =
serde_json::from_value(value).map_err(|e| InvalidCheckFinding {
reason: format!("finding does not match the shape {} ({e})", Self::SHAPE),
})?;
finding
.validate()
.map_err(|reason| InvalidCheckFinding { reason })?;
Ok(finding)
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{reason}")]
pub struct InvalidCheckFinding {
pub reason: String,
}
impl InvalidCheckFinding {
pub fn code(&self) -> &'static str {
INVALID_CHECK_FINDING_CODE
}
pub fn details(&self) -> serde_json::Value {
serde_json::json!({ "shape": CheckFinding::SHAPE })
}
}
impl CheckKind {
pub fn from_wire(s: &str) -> Option<Self> {
match s {
"verification" => Some(Self::Verification),
"conformance" => Some(Self::Conformance),
_ => None,
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::Verification => "verification",
Self::Conformance => "conformance",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verdict {
Ok,
Failed,
}
impl Verdict {
pub fn from_wire(s: &str) -> Option<Self> {
match s {
"ok" => Some(Self::Ok),
"failed" => Some(Self::Failed),
_ => None,
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::Ok => "ok",
Self::Failed => "failed",
}
}
}
pub const CARRY_REASON_TRANSITION: &str = "transition";
pub const CARRY_REASON_EXPORT: &str = "export";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CarriedFrom {
pub hash: String,
pub reason: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub depth: Option<u32>,
}
impl CarriedFrom {
pub fn transition(hash: &str) -> Self {
Self::transition_at(hash, 1)
}
pub fn transition_at(hash: &str, depth: u32) -> Self {
Self {
hash: hash.to_string(),
reason: CARRY_REASON_TRANSITION.to_string(),
depth: Some(depth),
}
}
pub fn chain_depth(&self) -> u32 {
self.depth.unwrap_or(1)
}
pub fn export(hash: &str) -> Self {
Self {
hash: hash.to_string(),
reason: CARRY_REASON_EXPORT.to_string(),
depth: None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CheckRecord {
pub ts: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub observed_at: Option<u64>,
pub entity: String,
pub verdict: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub method: Option<String>,
pub entity_hash: String,
pub actor: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client: Option<String>,
pub role: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schema_ref: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub finding: Option<CheckFinding>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub renamed_from: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub carried_from: Option<CarriedFrom>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub checked_write: Option<String>,
}
pub const LOCAL_TIE_WINDOW_SECS: u64 = 60;
pub const OBSERVED_AT_SKEW_SECS: u64 = 300;
pub fn parse_observed_at(raw: &str, now: u64) -> Result<u64, String> {
let s = raw.trim();
let Some(at) = crate::engine::due::parse_iso_utc_seconds(s) else {
return Err(format!(
"observed_at {raw:?} is not an ISO-8601 UTC instant (`YYYY-MM-DDTHH:MM:SSZ`) \
or a civil date (`YYYY-MM-DD`)"
));
};
if at > now.saturating_add(OBSERVED_AT_SKEW_SECS) {
return Err(format!(
"observed_at {raw:?} lies in the future (the engine's clock reads {now} epoch \
seconds); a check is recorded after it was made, never before"
));
}
Ok(at)
}
impl CheckRecord {
pub fn act_time(&self) -> u64 {
self.observed_at.unwrap_or(self.ts)
}
pub fn resolved_kind(&self) -> Option<CheckKind> {
match self.kind.as_deref() {
None => Some(CheckKind::Verification),
Some(k) if k.starts_with(FOREIGN_KIND_PREFIX) => None,
Some(k) => Some(CheckKind::from_wire(k).unwrap_or(CheckKind::Verification)),
}
}
pub fn foreign_kind(&self) -> Option<&str> {
self.kind
.as_deref()
.filter(|k| k.starts_with(FOREIGN_KIND_PREFIX))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CheckState {
NeverChecked,
CheckedOk,
CheckFailed,
CheckStale,
}
impl CheckState {
pub fn as_str(self) -> &'static str {
match self {
Self::NeverChecked => "never_checked",
Self::CheckedOk => "checked_ok",
Self::CheckFailed => "check_failed",
Self::CheckStale => "check_stale",
}
}
}
pub fn derive_state(latest: Option<&CheckRecord>, current_hash: &str) -> CheckState {
derive_state_pinned(latest, current_hash, None)
}
pub fn derive_state_pinned(
latest: Option<&CheckRecord>,
current_hash: &str,
current_schema_ref: Option<&str>,
) -> CheckState {
match latest {
None => CheckState::NeverChecked,
Some(rec) if rec.entity_hash != current_hash => CheckState::CheckStale,
Some(rec)
if rec.schema_ref.is_some() && rec.schema_ref.as_deref() != current_schema_ref =>
{
CheckState::CheckStale
}
Some(rec) if rec.verdict == "failed" => CheckState::CheckFailed,
Some(_) => CheckState::CheckedOk,
}
}
fn checks_dir(workspace_root: &Path) -> PathBuf {
workspace_root
.join(crate::workspace_store::WORKSPACE_STORE_DIR)
.join("state")
.join("checks")
}
fn check_ledger_path(workspace_root: &Path) -> PathBuf {
checks_dir(workspace_root).join("checks.jsonl")
}
#[derive(Debug, Clone)]
pub struct CheckLedger {
path: PathBuf,
}
impl CheckLedger {
pub fn for_workspace(workspace_root: &Path) -> Self {
Self {
path: check_ledger_path(workspace_root),
}
}
pub fn record(&self, rec: &CheckRecord) -> std::io::Result<()> {
if let Some(dir) = self.path.parent() {
std::fs::create_dir_all(dir)?;
}
let mut line = serde_json::to_string(rec).map_err(std::io::Error::other)?;
line.push('\n');
let mut f = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&self.path)?;
f.write_all(line.as_bytes())
}
pub fn record_local(&self, mut rec: CheckRecord) -> std::io::Result<CheckRecord> {
if rec.observed_at.is_none() {
let newest = self
.raw_lines()
.iter()
.filter(|r| r.entity == rec.entity)
.map(CheckRecord::act_time)
.max();
if let Some(newest) = newest
&& newest >= rec.ts
&& newest <= rec.ts.saturating_add(LOCAL_TIE_WINDOW_SECS)
{
rec.ts = newest + 1;
}
}
self.record(&rec)?;
Ok(rec)
}
pub fn carry_rename(&self, old: &str, new: &str) -> std::io::Result<usize> {
let carried: Vec<CheckRecord> = self
.raw_lines()
.into_iter()
.filter(|r| r.entity == old)
.map(|mut r| {
r.entity = new.to_string();
r.renamed_from = Some(old.to_string());
r
})
.collect();
if carried.is_empty() {
return Ok(0);
}
let mut lines = String::new();
for rec in &carried {
lines.push_str(&serde_json::to_string(rec).map_err(std::io::Error::other)?);
lines.push('\n');
}
let mut f = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&self.path)?;
f.write_all(lines.as_bytes())?;
Ok(carried.len())
}
pub fn carry_transition(
&self,
entity: &str,
kind: &str,
pre_hash: &str,
post_hash: &str,
) -> std::io::Result<bool> {
if pre_hash == post_hash {
return Ok(false);
}
let Some(latest) = self.latest_for_wire_kind(entity, kind) else {
return Ok(false);
};
if latest.entity_hash != pre_hash || latest.verdict != Verdict::Ok.as_str() {
return Ok(false);
}
let depth = latest
.carried_from
.as_ref()
.map_or(1, |c| c.chain_depth() + 1);
let carried = CheckRecord {
entity_hash: post_hash.to_string(),
carried_from: Some(CarriedFrom::transition_at(pre_hash, depth)),
..latest
};
self.record(&carried)?;
Ok(true)
}
pub fn rows_for_mem(&self, mem: &str) -> Vec<CheckRecord> {
let prefix = format!("{mem}--");
standing_order(
self.raw_lines()
.into_iter()
.filter(|r| r.entity.starts_with(&prefix))
.collect(),
)
}
pub fn transport_lines_for_mem(&self, mem: &str) -> Vec<u8> {
Self::transport_lines(&self.rows_for_mem(mem))
}
pub fn transport_lines(records: &[CheckRecord]) -> Vec<u8> {
let mut lines: Vec<(u64, String)> = records
.iter()
.filter_map(|r| serde_json::to_string(r).ok().map(|s| (r.ts, s)))
.collect();
lines.sort();
lines.dedup();
let mut out = Vec::new();
for (_, line) in lines {
out.extend_from_slice(line.as_bytes());
out.push(b'\n');
}
out
}
pub fn merge_transport_lines(&self, lines: &[u8], now: u64) -> std::io::Result<MergedRows> {
let present: std::collections::HashSet<String> = self
.raw_lines()
.iter()
.filter_map(|r| serde_json::to_string(r).ok())
.collect();
let mut out = MergedRows::default();
for line in String::from_utf8_lossy(lines).lines() {
let Ok(rec) = serde_json::from_str::<CheckRecord>(line) else {
continue;
};
let Ok(canonical) = serde_json::to_string(&rec) else {
continue;
};
if present.contains(&canonical) {
continue;
}
if rec.act_time() > now.saturating_add(OBSERVED_AT_SKEW_SECS) {
out.refused.push(RefusedCheckRow {
entity: rec.entity.clone(),
kind: sealed_kind_of(&rec),
act_time: rec.act_time(),
identity: rec.identity.clone(),
reason: format!(
"the row's time of the act ({}) lies more than {OBSERVED_AT_SKEW_SECS} \
seconds ahead of this engine's clock ({now}); a check is recorded after \
it was made, never before",
rec.act_time()
),
});
continue;
}
self.record(&rec)?;
out.appended += 1;
}
Ok(out)
}
fn raw_lines(&self) -> Vec<CheckRecord> {
let Ok(content) = std::fs::read_to_string(&self.path) else {
return Vec::new();
};
content
.lines()
.filter_map(|l| serde_json::from_str(l).ok())
.collect()
}
pub fn in_standing_order(&self) -> Vec<CheckRecord> {
standing_order(self.raw_lines())
}
pub fn latest_for(&self, entity: &str) -> Option<CheckRecord> {
self.in_standing_order()
.into_iter()
.rev()
.find(|r| r.entity == entity)
}
pub fn latest_for_kind(&self, entity: &str, kind: CheckKind) -> Option<CheckRecord> {
self.in_standing_order()
.into_iter()
.rev()
.find(|r| r.entity == entity && r.resolved_kind() == Some(kind))
}
pub fn latest_for_wire_kind(&self, entity: &str, kind: &str) -> Option<CheckRecord> {
match CheckKind::from_wire(kind) {
Some(k) => self.latest_for_kind(entity, k),
None => self
.in_standing_order()
.into_iter()
.rev()
.find(|r| r.entity == entity && r.kind.as_deref() == Some(kind)),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MergedRows {
pub appended: usize,
pub refused: Vec<RefusedCheckRow>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RefusedCheckRow {
pub entity: String,
pub kind: String,
pub act_time: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<String>,
pub reason: String,
}
fn standing_order(rows: Vec<CheckRecord>) -> Vec<CheckRecord> {
let carries: Vec<(String, String, String, u64, Option<u32>)> = rows
.iter()
.filter_map(|r| {
r.carried_from.as_ref().map(|c| {
(
r.entity.clone(),
sealed_kind_of(r),
c.hash.clone(),
r.act_time(),
c.depth,
)
})
})
.collect();
let depth_of = |r: &CheckRecord| r.carried_from.as_ref().and_then(|c| c.depth).unwrap_or(0);
let superseded = |r: &CheckRecord| {
let kind = sealed_kind_of(r);
let depth = depth_of(r);
carries.iter().any(|(entity, k, left, at, d)| {
*entity == r.entity
&& *k == kind
&& *left == r.entity_hash
&& r.act_time() <= *at
&& d.is_none_or(|d| depth < d)
})
};
let mut keyed: Vec<(bool, u64, String, CheckRecord)> = rows
.into_iter()
.map(|r| {
let sup = superseded(&r);
let bytes = serde_json::to_string(&r).unwrap_or_default();
(!sup, r.act_time(), bytes, r)
})
.collect();
keyed.sort_by(|a, b| (a.0, a.1, &a.2).cmp(&(b.0, b.1, &b.2)));
keyed.into_iter().map(|(_, _, _, r)| r).collect()
}
pub const SEALED_CHECKS_VERSION: u32 = 1;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SealedCheck {
pub ts: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub observed_at: Option<u64>,
pub verdict: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub method: Option<String>,
pub entity_hash: String,
pub actor: String,
pub role: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schema_ref: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub renamed_from: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub carried_from: Option<CarriedFrom>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub independence: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub origin: Option<String>,
}
impl SealedCheck {
pub fn from_record(rec: &CheckRecord) -> Self {
Self {
ts: rec.ts,
observed_at: rec.observed_at,
verdict: rec.verdict.clone(),
method: rec.method.clone(),
entity_hash: rec.entity_hash.clone(),
actor: rec.actor.clone(),
role: rec.role.clone(),
identity: rec.identity.clone(),
schema_ref: rec.schema_ref.clone(),
renamed_from: rec.renamed_from.clone(),
carried_from: rec.carried_from.clone(),
independence: None,
origin: None,
}
}
pub fn sealed_independence(&self) -> Option<crate::engine::independence::Independence> {
self.independence
.as_deref()
.and_then(crate::engine::independence::Independence::from_wire)
}
pub fn sealed_origin(&self) -> Option<crate::render::OriginClass> {
match self.origin.as_deref()? {
"first-party" => Some(crate::render::OriginClass::FirstParty),
"third-party" => Some(crate::render::OriginClass::ThirdParty),
_ => None,
}
}
pub fn to_record(&self, entity_id: &str, kind: &str) -> CheckRecord {
CheckRecord {
ts: self.ts,
observed_at: self.observed_at,
entity: entity_id.to_string(),
verdict: self.verdict.clone(),
method: self.method.clone(),
entity_hash: self.entity_hash.clone(),
actor: self.actor.clone(),
client: None,
role: self.role.clone(),
identity: self.identity.clone(),
kind: (kind != CheckKind::Verification.as_str()).then(|| kind.to_string()),
schema_ref: self.schema_ref.clone(),
finding: None,
renamed_from: self.renamed_from.clone(),
carried_from: self.carried_from.clone(),
checked_write: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SealedChecks {
pub version: u32,
#[serde(default)]
pub entities: BTreeMap<String, BTreeMap<String, SealedCheck>>,
}
impl SealedChecks {
pub fn new() -> Self {
Self {
version: SEALED_CHECKS_VERSION,
entities: BTreeMap::new(),
}
}
pub fn latest(&self, entity_path: &str, kind: &str) -> Option<&SealedCheck> {
self.entities
.get(entity_path)
.and_then(|kinds| kinds.get(kind))
}
pub fn kinds_of(&self, entity_path: &str) -> impl Iterator<Item = (&str, &SealedCheck)> {
self.entities
.get(entity_path)
.into_iter()
.flat_map(|kinds| kinds.iter().map(|(k, v)| (k.as_str(), v)))
}
pub fn rekey_entity(&mut self, entity_path: &str, pre_hash: &str, post_hash: &str) -> usize {
if pre_hash == post_hash {
return 0;
}
let Some(kinds) = self.entities.get_mut(entity_path) else {
return 0;
};
let mut moved = 0;
for rec in kinds.values_mut() {
if rec.entity_hash == pre_hash {
rec.entity_hash = post_hash.to_string();
rec.carried_from = Some(CarriedFrom::export(pre_hash));
moved += 1;
}
}
moved
}
pub fn to_archive_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
let mut s = serde_json::to_string_pretty(self)?;
s.push('\n');
Ok(s.into_bytes())
}
pub fn from_archive_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
serde_json::from_slice(bytes)
}
pub fn validate(&self, carried: &std::collections::BTreeSet<String>) -> Result<(), String> {
if self.version != SEALED_CHECKS_VERSION {
return Err(format!(
"version {} is not the version this engine reads ({SEALED_CHECKS_VERSION})",
self.version
));
}
for (path, kinds) in &self.entities {
if !carried.contains(path) {
return Err(format!(
"entity `{path}` names no entity the archive carries"
));
}
for (kind, rec) in kinds {
let at = format!("entity `{path}`, kind `{kind}`");
if RecordKind::from_wire(kind).is_none() {
return Err(format!(
"{at}: the kind is not one of {}",
RecordKind::vocabulary_hint()
));
}
if Verdict::from_wire(&rec.verdict).is_none() {
return Err(format!(
"{at}: verdict `{}` is not one of {}",
rec.verdict,
VERDICTS.join(", ")
));
}
if rec.entity_hash.trim().is_empty() {
return Err(format!("{at}: entity_hash is empty"));
}
if rec.actor.trim().is_empty() {
return Err(format!("{at}: actor is empty"));
}
if rec.role.trim().is_empty() {
return Err(format!("{at}: role is empty"));
}
if let Some(reading) = rec.independence.as_deref()
&& crate::engine::independence::Independence::from_wire(reading).is_none()
{
return Err(format!(
"{at}: independence `{reading}` is not one of {}",
crate::engine::independence::Independence::vocabulary_hint()
));
}
if let Some(origin) = rec.origin.as_deref()
&& rec.sealed_origin().is_none()
{
return Err(format!(
"{at}: origin `{origin}` is not one of first-party | third-party"
));
}
}
}
Ok(())
}
}
impl Default for SealedChecks {
fn default() -> Self {
Self::new()
}
}
pub fn sealed_kind_of(rec: &CheckRecord) -> String {
match rec.resolved_kind() {
Some(k) => k.as_str().to_string(),
None => rec.kind.clone().unwrap_or_default(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
fn rec(entity: &str, verdict: &str, hash: &str) -> CheckRecord {
CheckRecord {
ts: 1,
observed_at: None,
entity: entity.to_string(),
verdict: verdict.to_string(),
method: None,
entity_hash: hash.to_string(),
actor: "cli".to_string(),
client: None,
role: "checker".to_string(),
identity: None,
kind: None,
schema_ref: None,
finding: None,
renamed_from: None,
carried_from: None,
checked_write: None,
}
}
fn at(entity: &str, verdict: &str, hash: &str, ts: u64) -> CheckRecord {
CheckRecord {
ts,
..rec(entity, verdict, hash)
}
}
fn line(r: &CheckRecord) -> Vec<u8> {
let mut l = serde_json::to_vec(r).unwrap();
l.push(b'\n');
l
}
#[test]
fn a_merged_row_stands_by_its_time_of_the_act_not_its_arrival() {
let now = 10_000;
let tmp = TempDir::new().unwrap();
let ledger = CheckLedger::for_workspace(tmp.path());
ledger.record(&at("m--e", "ok", "h1", 200)).unwrap();
let merged = ledger
.merge_transport_lines(&line(&at("m--e", "failed", "h1", 100)), now)
.unwrap();
assert_eq!(merged.appended, 1);
let standing = ledger
.latest_for_kind("m--e", CheckKind::Verification)
.unwrap();
assert_eq!((standing.verdict.as_str(), standing.ts), ("ok", 200));
ledger
.merge_transport_lines(&line(&at("m--e", "failed", "h1", 300)), now)
.unwrap();
let standing = ledger
.latest_for_kind("m--e", CheckKind::Verification)
.unwrap();
assert_eq!((standing.verdict.as_str(), standing.ts), ("failed", 300));
}
#[test]
fn checks_recorded_out_of_order_stand_by_observed_at() {
let tmp = TempDir::new().unwrap();
let ledger = CheckLedger::for_workspace(tmp.path());
let mut later = at("m--e", "ok", "h1", 500);
later.observed_at = Some(400);
let mut earlier = at("m--e", "failed", "h1", 501);
earlier.observed_at = Some(100);
ledger.record(&later).unwrap();
ledger.record(&earlier).unwrap();
let standing = ledger.latest_for_wire_kind("m--e", "verification").unwrap();
assert_eq!(standing.verdict, "ok");
}
#[test]
fn a_carried_line_stands_over_its_source() {
for order in [false, true] {
let tmp = TempDir::new().unwrap();
let ledger = CheckLedger::for_workspace(tmp.path());
let mut source = at("m--e", "ok", "h1", 100);
source.kind = Some("x-approval".into());
let carried = CheckRecord {
entity_hash: "h2".into(),
carried_from: Some(CarriedFrom::transition("h1")),
checked_write: None,
..source.clone()
};
let mut sibling = at("m--e", "ok", "zz-sibling", 100);
sibling.entity_hash = "h1".into();
sibling.kind = Some("x-approval".into());
sibling.method = Some("zzzz".into());
let mut rows = vec![source.clone(), carried.clone(), sibling];
if order {
rows.reverse();
}
for r in &rows {
ledger.record(r).unwrap();
}
let standing = ledger.latest_for_wire_kind("m--e", "x-approval").unwrap();
assert_eq!(standing.entity_hash, "h2", "order reversed: {order}");
assert!(standing.carried_from.is_some());
}
}
#[test]
fn a_check_after_a_return_to_the_carried_from_hash_stands() {
let tmp = TempDir::new().unwrap();
let ledger = CheckLedger::for_workspace(tmp.path());
let source = at("m--e", "ok", "h1", 100);
ledger.record(&source).unwrap();
ledger
.record(&CheckRecord {
entity_hash: "h2".into(),
carried_from: Some(CarriedFrom::transition("h1")),
checked_write: None,
..source.clone()
})
.unwrap();
ledger.record(&at("m--e", "failed", "h1", 500)).unwrap();
let standing = ledger
.latest_for_kind("m--e", CheckKind::Verification)
.unwrap();
assert_eq!((standing.verdict.as_str(), standing.ts), ("failed", 500));
let a = at("m--e", "ok", "h1", 100);
let carry = |hash: &str, from: &str, depth: u32| CheckRecord {
entity_hash: hash.into(),
carried_from: Some(CarriedFrom::transition_at(from, depth)),
..a.clone()
};
let read = |rows: &[&CheckRecord]| {
let tmp = TempDir::new().unwrap();
let ledger = CheckLedger::for_workspace(tmp.path());
for r in rows {
ledger.record(r).unwrap();
}
ledger
.latest_for_kind("m--e", CheckKind::Verification)
.unwrap()
};
let (mid, last) = (carry("h2", "h1", 1), carry("h3", "h2", 2));
assert_eq!(read(&[&last, &a, &mid]).entity_hash, "h3");
assert_eq!(read(&[&mid, &last, &a]).entity_hash, "h3");
let (b1, back, b2) = (
carry("h2", "h1", 1),
carry("h1", "h2", 2),
carry("h2", "h1", 3),
);
for rows in [
[&a, &b1, &back, &b2],
[&b2, &back, &b1, &a],
[&back, &a, &b2, &b1],
] {
let standing = read(&rows);
assert_eq!(standing.entity_hash, "h2");
assert_eq!(standing.carried_from.as_ref().unwrap().depth, Some(3));
}
let old = |hash: &str, from: &str| CheckRecord {
entity_hash: hash.into(),
carried_from: Some(CarriedFrom {
depth: None,
..CarriedFrom::transition(from)
}),
..a.clone()
};
assert_eq!(
read(&[&old("h3", "h2"), &a, &old("h2", "h1")]).entity_hash,
"h3"
);
}
#[test]
fn two_ledgers_with_the_same_rows_derive_the_same_newest() {
let mut a = at("m--e", "ok", "h1", 100);
a.identity = Some("grader-a".into());
let mut b = at("m--e", "failed", "h1", 100);
b.identity = Some("grader-b".into());
let c = at("m--e", "ok", "h1", 50);
let rows = [a, b, c];
let mut standings = Vec::new();
for perm in [[0, 1, 2], [1, 0, 2], [2, 1, 0], [1, 2, 0]] {
let tmp = TempDir::new().unwrap();
let ledger = CheckLedger::for_workspace(tmp.path());
for i in perm {
ledger.record(&rows[i]).unwrap();
}
let s = ledger
.latest_for_kind("m--e", CheckKind::Verification)
.unwrap();
standings.push(serde_json::to_string(&s).unwrap());
assert_eq!(
serde_json::to_string(&ledger.in_standing_order()).unwrap(),
serde_json::to_string(&standing_order(rows.to_vec())).unwrap(),
"the whole order is derived from the rows alone"
);
}
standings.dedup();
assert_eq!(standings.len(), 1, "{standings:?}");
}
#[test]
fn a_local_recheck_in_the_same_second_stands_over_the_earlier_check() {
let tmp = TempDir::new().unwrap();
let ledger = CheckLedger::for_workspace(tmp.path());
ledger
.record_local(at("m--e", "ok", "zz-old", 1000))
.unwrap();
let fresh = ledger.record_local(at("m--e", "ok", "h2", 1000)).unwrap();
assert_eq!(fresh.ts, 1001);
let standing = ledger
.latest_for_kind("m--e", CheckKind::Verification)
.unwrap();
assert_eq!(standing.entity_hash, "h2");
let mut stated = at("m--e", "ok", "h3", 1000);
stated.observed_at = Some(900);
assert_eq!(ledger.record_local(stated).unwrap().ts, 1000);
assert_eq!(
ledger.record_local(at("m--f", "ok", "h", 5000)).unwrap().ts,
5000
);
}
#[test]
fn a_merged_row_from_the_future_is_refused_and_named() {
let now = 10_000;
let tmp = TempDir::new().unwrap();
let ledger = CheckLedger::for_workspace(tmp.path());
let mut future = at("m--e", "ok", "h1", now + OBSERVED_AT_SKEW_SECS + 1);
future.identity = Some("clock-wrong".into());
let mut dated_future = at("m--e", "ok", "h1", 100);
dated_future.observed_at = Some(now + 10 * OBSERVED_AT_SKEW_SECS);
let inside = at("m--e", "ok", "h1", now + OBSERVED_AT_SKEW_SECS);
let mut bytes = line(&future);
bytes.extend(line(&dated_future));
bytes.extend(line(&inside));
let merged = ledger.merge_transport_lines(&bytes, now).unwrap();
assert_eq!(merged.appended, 1);
assert_eq!(merged.refused.len(), 2);
assert_eq!(merged.refused[0].entity, "m--e");
assert_eq!(merged.refused[0].identity.as_deref(), Some("clock-wrong"));
assert_eq!(merged.refused[1].act_time, now + 10 * OBSERVED_AT_SKEW_SECS);
assert_eq!(ledger.raw_lines().len(), 1);
}
#[test]
fn state_derivation_covers_all_four_states() {
assert_eq!(derive_state(None, "h1"), CheckState::NeverChecked);
let ok = rec("m--e", "ok", "h1");
assert_eq!(derive_state(Some(&ok), "h1"), CheckState::CheckedOk);
assert_eq!(derive_state(Some(&ok), "h2"), CheckState::CheckStale);
let failed = rec("m--e", "failed", "h1");
assert_eq!(derive_state(Some(&failed), "h1"), CheckState::CheckFailed);
assert_eq!(derive_state(Some(&failed), "h2"), CheckState::CheckStale);
}
#[test]
fn ledger_appends_and_serves_newest_per_entity() {
let tmp = TempDir::new().unwrap();
let ledger = CheckLedger::for_workspace(tmp.path());
assert!(ledger.latest_for("m--a").is_none());
ledger.record(&at("m--a", "failed", "h1", 1)).unwrap();
ledger.record(&at("m--b", "ok", "h9", 2)).unwrap();
ledger.record(&at("m--a", "ok", "h2", 3)).unwrap();
let latest = ledger.latest_for("m--a").unwrap();
assert_eq!(latest.verdict, "ok");
assert_eq!(latest.entity_hash, "h2");
assert_eq!(ledger.raw_lines().len(), 3);
}
#[test]
fn observed_at_parses_refuses_the_future_and_survives_the_carries() {
let now = 1_792_503_930; assert_eq!(parse_observed_at("2026-10-19", now), Ok(1_792_368_000));
assert_eq!(parse_observed_at(" 2026-10-20T13:45:30Z ", now), Ok(now));
assert!(parse_observed_at("2026-10-20T13:50:00Z", now).is_ok());
let err = parse_observed_at("2026-10-20T13:51:00Z", now).unwrap_err();
assert!(err.contains("future"), "{err}");
let err = parse_observed_at("20.10.2026", now).unwrap_err();
assert!(err.contains("ISO-8601"), "{err}");
let tmp = TempDir::new().unwrap();
let ledger = CheckLedger::for_workspace(tmp.path());
let mut dated = rec("m--old", "ok", "h1");
dated.observed_at = Some(1_792_368_000);
ledger.record(&dated).unwrap();
ledger.record(&rec("m--old", "ok", "h2")).unwrap();
assert_eq!(ledger.carry_rename("m--old", "m--new").unwrap(), 2);
let carried: Vec<CheckRecord> = ledger
.raw_lines()
.into_iter()
.filter(|r| r.entity == "m--new")
.collect();
assert_eq!(carried[0].observed_at, Some(1_792_368_000));
assert_eq!(carried[1].observed_at, None);
let sealed = SealedCheck::from_record(&dated);
assert_eq!(sealed.observed_at, Some(1_792_368_000));
assert_eq!(
sealed.to_record("m--old", "verification").observed_at,
Some(1_792_368_000)
);
let raw = std::fs::read_to_string(check_ledger_path(tmp.path())).unwrap();
let lines: Vec<&str> = raw.lines().collect();
assert!(
lines[0].contains("\"observed_at\":1792368000"),
"{}",
lines[0]
);
assert!(!lines[1].contains("observed_at"), "{}", lines[1]);
}
#[test]
fn carry_rename_rekeys_without_erasing() {
let tmp = TempDir::new().unwrap();
let ledger = CheckLedger::for_workspace(tmp.path());
ledger.record(&rec("m--old", "ok", "h1")).unwrap();
ledger.record(&rec("m--other", "ok", "h9")).unwrap();
let mut conf = rec("m--old", "failed", "h1");
conf.kind = Some("conformance".into());
ledger.record(&conf).unwrap();
assert_eq!(ledger.carry_rename("m--old", "m--new").unwrap(), 2);
assert_eq!(ledger.carry_rename("m--absent", "m--new").unwrap(), 0);
let all = ledger.raw_lines();
assert_eq!(all.len(), 5);
assert!(all.iter().filter(|r| r.entity == "m--old").count() == 2);
let carried: Vec<&CheckRecord> = all.iter().filter(|r| r.entity == "m--new").collect();
assert_eq!(carried.len(), 2);
assert!(
carried
.iter()
.all(|r| r.renamed_from.as_deref() == Some("m--old"))
);
let latest = ledger
.latest_for_kind("m--new", CheckKind::Verification)
.unwrap();
assert_eq!(latest.verdict, "ok");
assert_eq!(derive_state(Some(&latest), "h1"), CheckState::CheckedOk);
assert_eq!(
derive_state(Some(&latest), "h2-after-rename"),
CheckState::CheckStale
);
assert_eq!(
ledger
.latest_for_kind("m--new", CheckKind::Conformance)
.unwrap()
.verdict,
"failed"
);
assert!(
ledger
.latest_for("m--other")
.unwrap()
.renamed_from
.is_none()
);
}
#[test]
fn carry_transition_moves_only_the_fresh_confirming_record() {
let tmp = TempDir::new().unwrap();
let ledger = CheckLedger::for_workspace(tmp.path());
let mut ok = rec("m--plan", "ok", "h1");
ok.kind = Some("x-projection".into());
ok.identity = Some("checker-c".into());
ledger.record(&ok).unwrap();
assert!(
!ledger
.carry_transition("m--plan", "x-projection", "h1", "h1")
.unwrap()
);
assert!(
!ledger
.carry_transition("m--plan", "x-projection", "h0", "h2")
.unwrap()
);
assert!(
!ledger
.carry_transition("m--plan", "verification", "h1", "h2")
.unwrap()
);
assert_eq!(ledger.raw_lines().len(), 1, "nothing appended so far");
assert!(
ledger
.carry_transition("m--plan", "x-projection", "h1", "h2")
.unwrap()
);
let all = ledger.raw_lines();
assert_eq!(all.len(), 2, "append-only: the original stays");
let carried = ledger
.latest_for_wire_kind("m--plan", "x-projection")
.unwrap();
assert_eq!(carried.entity_hash, "h2");
assert_eq!(carried.identity.as_deref(), Some("checker-c"));
assert_eq!(carried.verdict, "ok");
assert_eq!(carried.carried_from, Some(CarriedFrom::transition("h1")));
assert_eq!(derive_state(Some(&carried), "h2"), CheckState::CheckedOk);
assert!(
ledger
.carry_transition("m--plan", "x-projection", "h2", "h3")
.unwrap()
);
let again = ledger
.latest_for_wire_kind("m--plan", "x-projection")
.unwrap();
assert_eq!(again.carried_from.as_ref().unwrap().hash, "h2");
let mut failed = rec("m--other", "failed", "h1");
failed.kind = Some("x-projection".into());
ledger.record(&failed).unwrap();
assert!(
!ledger
.carry_transition("m--other", "x-projection", "h1", "h2")
.unwrap()
);
assert!(all[0].carried_from.is_none());
}
#[test]
fn sealed_rekey_moves_fresh_records_and_leaves_stale_ones() {
let mut sealed = SealedChecks::new();
let fresh = SealedCheck::from_record(&rec("m--a", "ok", "h1"));
let mut stale = SealedCheck::from_record(&rec("m--a", "ok", "h0"));
stale.ts = 0;
sealed.entities.insert(
"a".into(),
BTreeMap::from([
("verification".to_string(), fresh),
("x-audit".to_string(), stale),
]),
);
assert_eq!(sealed.rekey_entity("a", "h1", "h1"), 0);
assert_eq!(sealed.rekey_entity("absent", "h1", "h2"), 0);
assert_eq!(sealed.rekey_entity("a", "h1", "h2"), 1);
let v = sealed.latest("a", "verification").unwrap();
assert_eq!(v.entity_hash, "h2");
assert_eq!(v.carried_from.as_ref().unwrap().reason, CARRY_REASON_EXPORT);
assert_eq!(v.carried_from.as_ref().unwrap().hash, "h1");
let x = sealed.latest("a", "x-audit").unwrap();
assert_eq!(x.entity_hash, "h0", "stale stays stale");
assert!(x.carried_from.is_none());
let back = v.to_record("m--a", "verification");
assert_eq!(back.carried_from, v.carried_from);
assert_eq!(SealedCheck::from_record(&back), *v);
let legacy = r#"{"ts":1,"verdict":"ok","entity_hash":"h","actor":"cli","role":"checker"}"#;
let parsed: SealedCheck = serde_json::from_str(legacy).unwrap();
assert!(parsed.carried_from.is_none());
assert!(parsed.independence.is_none());
assert!(parsed.sealed_independence().is_none());
}
#[test]
fn sealed_row_origin_parses_only_from_the_closed_vocabulary() {
let mut sealed = SealedChecks::new();
let mut row = SealedCheck::from_record(&rec("m--a", "ok", "h1"));
row.origin = Some("third-party".to_string());
sealed.entities.insert(
"a".into(),
BTreeMap::from([("verification".to_string(), row)]),
);
assert_eq!(
sealed.latest("a", "verification").unwrap().sealed_origin(),
Some(crate::render::OriginClass::ThirdParty)
);
let carried: std::collections::BTreeSet<String> = ["a".to_string()].into();
assert!(sealed.validate(&carried).is_ok());
let legacy = r#"{"ts":1,"verdict":"ok","entity_hash":"h","actor":"cli","role":"checker"}"#;
let parsed: SealedCheck = serde_json::from_str(legacy).unwrap();
assert!(parsed.origin.is_none());
assert!(parsed.sealed_origin().is_none());
sealed
.entities
.get_mut("a")
.unwrap()
.get_mut("verification")
.unwrap()
.origin = Some("trusted".into());
assert!(
sealed
.latest("a", "verification")
.unwrap()
.sealed_origin()
.is_none()
);
let err = sealed.validate(&carried).unwrap_err();
assert!(err.contains("origin `trusted`"), "{err}");
}
#[test]
fn sealed_independence_is_kept_by_rekey_and_closed_in_vocabulary() {
use crate::engine::independence::Independence;
let mut sealed = SealedChecks::new();
let mut fresh = SealedCheck::from_record(&rec("m--a", "ok", "h1"));
fresh.independence = Some(Independence::ConfirmedIndependent.as_str().to_string());
sealed.entities.insert(
"a".into(),
BTreeMap::from([("verification".to_string(), fresh)]),
);
assert_eq!(sealed.rekey_entity("a", "h1", "h2"), 1);
let v = sealed.latest("a", "verification").unwrap();
assert_eq!(
v.sealed_independence(),
Some(Independence::ConfirmedIndependent)
);
let bytes = sealed.to_archive_bytes().unwrap();
let back = SealedChecks::from_archive_bytes(&bytes).unwrap();
assert_eq!(back, sealed);
assert!(v.to_record("m--a", "verification").carried_from.is_some());
let carried: std::collections::BTreeSet<String> = ["a".to_string()].into();
assert!(back.validate(&carried).is_ok());
let mut foreign = sealed.clone();
foreign
.entities
.get_mut("a")
.unwrap()
.get_mut("verification")
.unwrap()
.independence = Some("trusted".into());
assert!(
foreign
.latest("a", "verification")
.unwrap()
.sealed_independence()
.is_none()
);
let err = foreign.validate(&carried).unwrap_err();
assert!(err.contains("independence `trusted`"), "{err}");
}
#[test]
fn verdict_vocabulary_is_closed() {
assert!(Verdict::from_wire("ok").is_some());
assert!(Verdict::from_wire("failed").is_some());
assert!(Verdict::from_wire("passed").is_none());
assert!(Verdict::from_wire("OK").is_none());
}
fn conf(entity: &str, verdict: &str, hash: &str, pin: &str) -> CheckRecord {
CheckRecord {
kind: Some("conformance".to_string()),
schema_ref: Some(pin.to_string()),
..rec(entity, verdict, hash)
}
}
#[test]
fn kind_vocabulary_is_closed() {
assert!(CheckKind::from_wire("verification").is_some());
assert!(CheckKind::from_wire("conformance").is_some());
assert!(CheckKind::from_wire("semantic").is_none());
assert!(CheckKind::from_wire("Conformance").is_none());
}
#[test]
fn legacy_lines_read_as_verification() {
let legacy = r#"{"ts":1,"entity":"m--e","verdict":"ok","entity_hash":"h1","actor":"cli","role":"checker"}"#;
let parsed: CheckRecord = serde_json::from_str(legacy).unwrap();
assert_eq!(parsed.resolved_kind(), Some(CheckKind::Verification));
let fresh = rec("m--e", "ok", "h1");
let line = serde_json::to_string(&fresh).unwrap();
assert!(!line.contains("kind"));
assert!(!line.contains("schema_ref"));
assert!(!line.contains("identity"));
}
#[test]
fn latest_is_per_kind() {
let tmp = TempDir::new().unwrap();
let ledger = CheckLedger::for_workspace(tmp.path());
ledger.record(&rec("m--a", "ok", "h1")).unwrap();
ledger
.record(&conf("m--a", "failed", "h1", "planning@1.0.0"))
.unwrap();
let v = ledger
.latest_for_kind("m--a", CheckKind::Verification)
.unwrap();
assert_eq!(v.verdict, "ok");
let c = ledger
.latest_for_kind("m--a", CheckKind::Conformance)
.unwrap();
assert_eq!(c.verdict, "failed");
assert_eq!(c.schema_ref.as_deref(), Some("planning@1.0.0"));
}
#[test]
fn conformance_stales_on_pin_move_verification_does_not() {
let c = conf("m--e", "ok", "h1", "planning@1.0.0");
assert_eq!(
derive_state_pinned(Some(&c), "h1", Some("planning@1.0.0")),
CheckState::CheckedOk
);
assert_eq!(
derive_state_pinned(Some(&c), "h2", Some("planning@1.0.0")),
CheckState::CheckStale
);
assert_eq!(
derive_state_pinned(Some(&c), "h1", Some("planning@2.0.0")),
CheckState::CheckStale
);
assert_eq!(
derive_state_pinned(Some(&c), "h1", None),
CheckState::CheckStale
);
let v = rec("m--e", "ok", "h1");
assert_eq!(
derive_state_pinned(Some(&v), "h1", Some("planning@9.0.0")),
CheckState::CheckedOk
);
assert_eq!(derive_state(Some(&v), "h1"), CheckState::CheckedOk);
}
#[test]
fn finding_shape_is_fixed_and_validated_whole() {
let ok = CheckFinding::from_json(serde_json::json!({
"code": "hidden-premise", "message": "The step assumes X.", "section": "step"
}))
.unwrap();
assert_eq!(ok.code, "hidden-premise");
assert_eq!(ok.section.as_deref(), Some("step"));
for bad in [
serde_json::json!({ "message": "no code" }),
serde_json::json!({ "code": "x" }),
serde_json::json!({ "code": "", "message": "empty code" }),
serde_json::json!({ "code": "x", "message": " " }),
serde_json::json!({ "code": "x", "message": "m", "severity": "high" }),
serde_json::json!({ "code": "x", "message": "m", "section": "" }),
] {
let err = CheckFinding::from_json(bad.clone())
.unwrap_err()
.to_string();
assert!(err.contains("shape"), "{bad}: {err}");
}
}
#[test]
fn open_kinds_parse_only_with_the_prefix_and_never_resolve_to_an_engine_kind() {
assert_eq!(
RecordKind::from_wire("verification"),
Some(RecordKind::Engine(CheckKind::Verification))
);
assert_eq!(
RecordKind::from_wire("x-step-walk"),
Some(RecordKind::Foreign("x-step-walk".to_string()))
);
for bad in ["step-walk", "x-", "x-Step", "x--a", "x-a-", "X-a"] {
assert!(RecordKind::from_wire(bad).is_none(), "{bad}");
}
assert!(RecordKind::vocabulary_hint().contains("x-<name>"));
let mut r = rec("m--e", "ok", "h");
r.kind = Some("x-step-walk".to_string());
assert_eq!(r.resolved_kind(), None);
assert_eq!(r.foreign_kind(), Some("x-step-walk"));
r.kind = None;
assert_eq!(r.resolved_kind(), Some(CheckKind::Verification));
r.kind = Some("conformance".to_string());
assert_eq!(r.resolved_kind(), Some(CheckKind::Conformance));
r.kind = Some("mystery".to_string());
assert_eq!(r.resolved_kind(), Some(CheckKind::Verification));
}
#[test]
fn pre_finding_ledger_lines_parse_and_derive_unchanged_and_findings_round_trip() {
let tmp = TempDir::new().unwrap();
let ledger = CheckLedger::for_workspace(tmp.path());
let dir = check_ledger_path(tmp.path());
std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
std::fs::write(
&dir,
"{\"ts\":1,\"entity\":\"m--e\",\"verdict\":\"failed\",\"entity_hash\":\"h\",\"actor\":\"cli\",\"role\":\"unspecified\"}\n",
)
.unwrap();
let old = ledger
.latest_for_kind("m--e", CheckKind::Verification)
.unwrap();
assert!(old.finding.is_none());
assert_eq!(derive_state(Some(&old), "h"), CheckState::CheckFailed);
let mut with = rec("m--e", "failed", "h");
with.ts = 2;
with.finding = Some(CheckFinding {
code: "hidden-premise".into(),
section: Some("step".into()),
message: "The step assumes X.".into(),
evidence: None,
});
ledger.record(&with).unwrap();
let mut foreign = rec("m--e", "ok", "h");
foreign.ts = 3;
foreign.kind = Some("x-step-walk".into());
ledger.record(&foreign).unwrap();
let latest = ledger
.latest_for_kind("m--e", CheckKind::Verification)
.unwrap();
assert_eq!(
latest.ts, 2,
"the foreign record is not the latest verification record"
);
assert_eq!(latest.finding.as_ref().unwrap().code, "hidden-premise");
assert_eq!(derive_state(Some(&latest), "h"), CheckState::CheckFailed);
let text = std::fs::read_to_string(&dir).unwrap();
assert!(text.contains("\"finding\":{\"code\":\"hidden-premise\",\"section\":\"step\",\"message\":\"The step assumes X.\"}"), "{text}");
assert!(text.contains("\"kind\":\"x-step-walk\""));
assert_eq!(text.lines().count(), 3, "append-only");
}
}