perishables_core/lib.rs
1//! Trust-layer checks for Open Knowledge Format bundles.
2//!
3//! This crate recomputes trust tiers from current verifications
4//! only, checks verification currency, and walks `superseded_by`
5//! chains. It performs no writes. Every instant comes from a pinned
6//! [`AuditClock`], so the same bundle and the same clock always give
7//! the same findings.
8//!
9//! The public surface includes the four locked calls consumed by
10//! downstream upkeep engines: [`recompute_tier`], [`check_currency`],
11//! [`walk_supersession`], and [`check_supersession`]. Finding codes
12//! live in the closed [`FindingCode`] enum and never change meaning
13//! once published.
14//!
15//! # Example
16//!
17//! ```
18//! use perishables_core::{
19//! AuditClock, Bundle, Concept, Tier, VerifiedEvent, check_currency, recompute_tier,
20//! };
21//!
22//! let clock = AuditClock::parse("2026-11-20").expect("valid date");
23//! let concept = Concept {
24//! id: "metrics/revenue".to_string(),
25//! concept_type: "Metric".to_string(),
26//! status: "stable".to_string(),
27//! superseded_by: None,
28//! generated_at: AuditClock::parse("2026-06-20T14:00:00Z").map(|c| c.epoch_seconds),
29//! generated_text: Some("2026-06-20T14:00:00Z".to_string()),
30//! stale_after_text: Some("2026-12-31T00:00:00Z".to_string()),
31//! stale_after: AuditClock::parse("2026-12-31T00:00:00Z").map(|c| c.epoch_seconds),
32//! verified: vec![VerifiedEvent {
33//! by: Some("human:reviewer".to_string()),
34//! at_text: Some("2026-06-25T09:00:00Z".to_string()),
35//! at: AuditClock::parse("2026-06-25T09:00:00Z").map(|c| c.epoch_seconds),
36//! }],
37//! sources: Vec::new(),
38//! citations: Vec::new(),
39//! runtime: None,
40//! parameters: Vec::new(),
41//! code_blocks: Vec::new(),
42//! file_code: None,
43//! claimed_result: None,
44//! };
45//!
46//! let report = recompute_tier(&concept, &clock);
47//! assert_eq!(report.recomputed_tier, Tier::HumanReviewed);
48//!
49//! let bundle = Bundle::from_concepts(vec![concept]);
50//! assert!(check_currency(&bundle, &clock).is_empty());
51//! ```
52
53mod bundle;
54mod checks;
55mod frontmatter;
56mod hash;
57mod time;
58
59pub use bundle::{Bundle, Concept, Parameter, SourceRef, VerifiedEvent};
60pub use hash::sha256_hex;
61
62/// A pinned instant. The library never reads the system clock.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
64pub struct AuditClock {
65 /// Seconds since the Unix epoch, in UTC.
66 pub epoch_seconds: i64,
67}
68
69impl AuditClock {
70 /// Build a clock from an OKF RFC 3339 timestamp or bare `YYYY-MM-DD` date.
71 /// Returns `None` when the text is not a valid calendar date or timestamp.
72 ///
73 /// ```
74 /// use perishables_core::AuditClock;
75 ///
76 /// let clock = AuditClock::parse("2026-11-20").unwrap();
77 /// assert_eq!(clock.to_rfc3339(), "2026-11-20T00:00:00Z");
78 /// assert!(AuditClock::parse("2026-02-29").is_none());
79 /// ```
80 pub fn parse(text: &str) -> Option<AuditClock> {
81 time::parse_timestamp(text).map(|epoch_seconds| AuditClock { epoch_seconds })
82 }
83
84 /// Format this instant as a canonical UTC RFC 3339 timestamp (`YYYY-MM-DDTHH:MM:SSZ`).
85 pub fn to_rfc3339(&self) -> String {
86 time::format_rfc3339(self.epoch_seconds)
87 }
88}
89
90impl std::fmt::Display for AuditClock {
91 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92 f.write_str(&self.to_rfc3339())
93 }
94}
95
96/// A trust tier, derived and never stored.
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum Tier {
99 /// No current verification event.
100 Unverified,
101 /// Current events exist and none is from a human actor.
102 MachineConfirmed,
103 /// At least one current event is from a human actor.
104 HumanReviewed,
105}
106
107impl Tier {
108 /// The tier name as the OKF specification writes it.
109 pub fn name(&self) -> &'static str {
110 match self {
111 Tier::Unverified => "unverified",
112 Tier::MachineConfirmed => "machine-confirmed",
113 Tier::HumanReviewed => "human-reviewed",
114 }
115 }
116}
117
118/// A closed set of finding codes, shared with the corpus labels.
119///
120/// A code once published never changes meaning, and a retired code
121/// is never reused.
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub enum FindingCode {
124 /// A verification predates the last meaningful change, so the
125 /// raw tier overstates the recomputed tier.
126 LapsedVerification,
127 /// A verification event cannot be judged, because it lacks an
128 /// actor or a parseable timestamp. It counts for nothing.
129 MalformedVerification,
130 /// A supersession chain reaches a concept that does not exist.
131 DanglingSupersededBy,
132 /// A supersession chain revisits a concept.
133 SupersessionCycle,
134 /// `superseded_by` appears on a concept that is not deprecated.
135 SupersededWithoutDeprecated,
136 /// The pinned instant is at or past `stale_after` and the
137 /// concept still presents as stable. Stale means check again,
138 /// it does not mean false.
139 StaleButStable,
140 /// A `stale_after` value does not parse as a timestamp. The
141 /// spec says such a value is never treated as fresh.
142 UnparseableStaleAfter,
143 /// The body cites a footnote label that no `sources` entry
144 /// carries as its id, so the attribution resolves to nothing.
145 UnresolvedCitation,
146 /// A `sources` entry points at an in-bundle resource that is
147 /// not in the bundle.
148 MissingSource,
149 /// An Attested Computation ran cleanly under re-execution and
150 /// its result differs from the attested result the bundle
151 /// claims.
152 AttestedResultMismatch,
153 /// A source carries a recorded content hash and the bytes in
154 /// the bundle no longer hash to it.
155 SourceDrift,
156 /// A concept presents a value as attested, while the computation
157 /// behind it is missing, non-deterministic, failed, or outside
158 /// the executable profile.
159 UnattestedClaim,
160}
161
162impl FindingCode {
163 /// The code as the corpus labels write it.
164 pub fn label(&self) -> &'static str {
165 match self {
166 FindingCode::LapsedVerification => "LAPSED_VERIFICATION",
167 FindingCode::MalformedVerification => "MALFORMED_VERIFICATION",
168 FindingCode::DanglingSupersededBy => "DANGLING_SUPERSEDED_BY",
169 FindingCode::SupersessionCycle => "SUPERSESSION_CYCLE",
170 FindingCode::SupersededWithoutDeprecated => "SUPERSEDED_WITHOUT_DEPRECATED",
171 FindingCode::StaleButStable => "STALE_BUT_STABLE",
172 FindingCode::UnparseableStaleAfter => "UNPARSEABLE_STALE_AFTER",
173 FindingCode::UnresolvedCitation => "UNRESOLVED_CITATION",
174 FindingCode::MissingSource => "MISSING_SOURCE",
175 FindingCode::AttestedResultMismatch => "ATTESTED_RESULT_MISMATCH",
176 FindingCode::SourceDrift => "SOURCE_DRIFT",
177 FindingCode::UnattestedClaim => "UNATTESTED_CLAIM",
178 }
179 }
180}
181
182/// One finding, tied to one concept and one rule.
183#[derive(Debug, Clone, PartialEq, Eq)]
184pub struct Finding {
185 /// The concept id, which is the bundle-relative path without
186 /// the `.md` suffix.
187 pub concept_id: String,
188 /// The rule that produced this finding.
189 pub code: FindingCode,
190 /// A plain statement of the fact behind the finding.
191 pub detail: String,
192}
193
194/// How one verification event classifies against its concept.
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub enum EventClass {
197 /// Well-formed and at or after the last generation. It counts.
198 Current,
199 /// Well-formed and earlier than the last generation. It does
200 /// not count.
201 Lapsed,
202 /// Missing its actor or a parseable timestamp. It counts for
203 /// nothing and is reported, never silently dropped.
204 Malformed,
205}
206
207/// The classification of one verification event, with its reason.
208#[derive(Debug, Clone, PartialEq, Eq)]
209pub struct EventReport {
210 /// The actor string, when the event carries one.
211 pub by: Option<String>,
212 /// The raw timestamp text, when the event carries one.
213 pub at_text: Option<String>,
214 /// The class this event falls in.
215 pub class: EventClass,
216 /// A plain statement of why the event falls in that class.
217 pub reason: String,
218}
219
220/// The result of recomputing one concept tier.
221#[derive(Debug, Clone, PartialEq, Eq)]
222pub struct TierReport {
223 /// The concept id.
224 pub concept_id: String,
225 /// The tier the raw verification list implies.
226 pub raw_tier: Tier,
227 /// The tier from current verifications only.
228 pub recomputed_tier: Tier,
229 /// The classification of every recorded event, in order, so a
230 /// reader can see which events were excluded and why.
231 pub events: Vec<EventReport>,
232}
233
234/// How a supersession chain ends.
235#[derive(Debug, Clone, Copy, PartialEq, Eq)]
236pub enum ChainTerminal {
237 /// The chain ends at a concept with no `superseded_by`.
238 Terminated,
239 /// The chain points at a target that is not in the bundle.
240 Dangling,
241 /// The chain revisits a concept or exceeds the hop cap.
242 Cycle,
243 /// The chain carries a `superseded_by` value that is not a
244 /// usable path at all.
245 Malformed,
246}
247
248/// The result of walking one supersession chain.
249#[derive(Debug, Clone, PartialEq, Eq)]
250pub struct ChainReport {
251 /// The concept the walk started from.
252 pub start: String,
253 /// The concepts visited, in walk order.
254 pub hops: Vec<String>,
255 /// How the chain ends.
256 pub terminal: ChainTerminal,
257 /// Targets reached only through the SPEC 12.1 fallback, marked
258 /// as the spec requires. Empty for current-version bundles.
259 pub fallback_targets: Vec<String>,
260 /// The finding when the chain is defective.
261 pub finding: Option<Finding>,
262}
263
264/// Recompute the trust tier of one concept from its current
265/// verifications only. Call one of the locked interface.
266pub fn recompute_tier(concept: &Concept, clock: &AuditClock) -> TierReport {
267 checks::recompute_tier(concept, clock)
268}
269
270/// Check verification currency across a whole bundle. Call two of
271/// the locked interface.
272pub fn check_currency(bundle: &Bundle, clock: &AuditClock) -> Vec<Finding> {
273 checks::check_currency(bundle, clock)
274}
275
276/// Walk one supersession chain to its end. Call three of the
277/// locked interface.
278pub fn walk_supersession(bundle: &Bundle, start: &str) -> ChainReport {
279 checks::walk_supersession(bundle, start)
280}
281
282/// Check every supersession chain in a bundle. Call four of the
283/// locked interface.
284pub fn check_supersession(bundle: &Bundle) -> Vec<Finding> {
285 checks::check_supersession(bundle)
286}
287
288/// Check freshness against the pinned clock.
289pub fn check_freshness(bundle: &Bundle, clock: &AuditClock) -> Vec<Finding> {
290 checks::check_freshness(bundle, clock)
291}
292
293/// Check provenance completeness.
294pub fn check_provenance(bundle: &Bundle) -> Vec<Finding> {
295 checks::check_provenance(bundle)
296}
297
298/// Check source drift against recorded SHA-256 content hashes.
299pub fn check_drift(bundle: &Bundle) -> Vec<Finding> {
300 checks::check_drift(bundle)
301}
302
303/// One piece of information reported without tripping the audit gate.
304#[derive(Debug, Clone, PartialEq, Eq)]
305pub struct InfoNote {
306 /// The concept the note concerns.
307 pub concept_id: String,
308 /// The note, in plain words.
309 pub text: String,
310}
311
312/// Information notes for a bundle, covering stale deprecated concepts,
313/// concepts with no recorded provenance, SPEC 12.1 fallback targets,
314/// and explicit source modification ordering facts.
315pub fn info_notes(bundle: &Bundle, clock: &AuditClock) -> Vec<InfoNote> {
316 checks::info_notes(bundle, clock)
317}
318
319/// Sort findings into deterministic report order by concept id, then
320/// rule id, then detail.
321pub fn sort_findings(findings: &mut [Finding]) {
322 checks::sort_findings(findings)
323}