Skip to main content

memstead_base/
check.rs

1//! Check records — the engine-recorded act of verification.
2//!
3//! A check is an agent recording "entity E checked, verdict ok |
4//! failed, via method M". It is engine state, never entity content:
5//! absent from markdown and `content_hash`, and it produces no mem
6//! commit — checking-touches-nothing is what makes check-staleness
7//! computable. Records are append-only JSONL under the workspace
8//! store (`.memstead/state/checks/checks.jsonl`); a newer check of
9//! the same kind supersedes older ones for state derivation but
10//! never erases them (kinds derive independently, see [`CheckKind`]).
11//!
12//! Unlike the friction ledger next door, recording here is NOT
13//! best-effort: a check the ledger failed to persist must refuse —
14//! the caller believes the act was recorded, and a silently dropped
15//! check is exactly the self-report dishonesty this tier exists to
16//! end. For the same reason there is no rotation cap: check history
17//! is the substrate process state derives from, not disposable
18//! telemetry.
19//!
20//! Each record carries provenance (actor, client, declared
21//! role) plus the entity's `content_hash` at check time. State
22//! derivation compares that hash against the current one:
23//!
24//! - no record            → `never_checked`
25//! - hash matches, ok     → `checked_ok`
26//! - hash matches, failed → `check_failed`
27//! - hash differs         → `check_stale` (whatever the verdict was,
28//!   it no longer speaks to the current content — stated, never
29//!   silently carried forward)
30//!
31//! A `conformance` record additionally carries the mem's schema pin
32//! and goes stale when the pin moves ([`derive_state_pinned`]): the
33//! prose it judged against is no longer the prose in force.
34
35use std::collections::BTreeMap;
36use std::io::Write;
37use std::path::{Path, PathBuf};
38
39use serde::{Deserialize, Serialize};
40
41/// The closed verdict vocabulary. Nuance goes in the method note or
42/// in process-mem entities — never in new verdict values.
43pub const VERDICTS: [&str; 2] = ["ok", "failed"];
44
45/// The closed kind vocabulary. `verification` is the default and
46/// today's behaviour: "I checked this entity's content". `conformance`
47/// is the semantic judgment "this entity satisfies its type's
48/// schema prose (`write_rules` / `writing_guidance`)" — recorded with
49/// the mem's schema pin, stamped by the engine at record time, so the
50/// verdict's freshness against both the content AND the prose version
51/// stays computable. A third kind is a separate decision; closed
52/// kinds keep health aggregation well-defined, matching the closed
53/// verdict vocabulary.
54pub const CHECK_KINDS: [&str; 2] = ["verification", "conformance"];
55
56/// Prefix of a caller-declared check kind the engine records verbatim
57/// and never interprets: `x-<name>`, `name` lowercase letters, digits
58/// and hyphens. The prefix makes the declaration deliberate — a typo of
59/// an engine kind cannot silently become a new kind — mirroring the
60/// rule that a third ENGINE kind is a separate decision. Foreign kinds
61/// never influence `check_state`; health lists them by count.
62pub const FOREIGN_KIND_PREFIX: &str = "x-";
63
64/// The typed code for a malformed finding.
65pub const INVALID_CHECK_FINDING_CODE: &str = "INVALID_CHECK_FINDING";
66
67/// A batch of checks refused whole because entries failed validation;
68/// nothing is recorded. Each failed entry carries its index, its id and
69/// the typed errors it met.
70#[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/// A check kind from the closed vocabulary.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum CheckKind {
93    Verification,
94    Conformance,
95}
96
97/// What a caller may declare as a check's kind: one of the engine's
98/// two kinds, or a foreign `x-<name>` kind recorded verbatim.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum RecordKind {
101    Engine(CheckKind),
102    Foreign(String),
103}
104
105impl RecordKind {
106    /// Parse a wire kind: an engine kind, an `x-` kind (name non-empty,
107    /// lowercase letters, digits and hyphens), or `None` for anything
108    /// else — the vocabulary the refusal names is [`CHECK_KINDS`] plus
109    /// the `x-<name>` form.
110    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        // ONE grammar, declared beside the schema's constraint
115        // vocabulary so a `transition_requires_self_check` declaration
116        // and a recorded check agree on what a kind may look like.
117        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    /// The engine kind, when this is one.
124    pub fn engine_kind(&self) -> Option<CheckKind> {
125        match self {
126            Self::Engine(k) => Some(*k),
127            Self::Foreign(_) => None,
128        }
129    }
130
131    /// Stable wire form.
132    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    /// The vocabulary sentence a refusal carries.
140    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/// A structured finding riding a check record: WHAT failed (or what was
149/// observed) in a locatable form, so a `failed` verdict never forces
150/// the author to re-derive the failure from a free-text method note.
151/// `code` in `UPPER_SNAKE` is the engine's namespace and must name a
152/// health condition ([`crate::ops::strict::HEALTH_CONDITIONS`]); any
153/// other spelling is the checker's own vocabulary. The wrapper shape is
154/// fixed and refuses unknown keys.
155#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
156#[serde(deny_unknown_fields)]
157pub struct CheckFinding {
158    /// The checker's finding code (`hidden-premise`, `stale-source`, …).
159    pub code: String,
160    /// The section key the finding concerns, when it concerns one.
161    #[serde(default, skip_serializing_if = "Option::is_none")]
162    pub section: Option<String>,
163    /// One or two sentences a reader can act on.
164    pub message: String,
165    /// What the finding rests on: a quote, a coordinate, a reference.
166    #[serde(default, skip_serializing_if = "Option::is_none")]
167    pub evidence: Option<String>,
168}
169
170impl CheckFinding {
171    /// The shape sentence every refusal names.
172    pub const SHAPE: &'static str =
173        "{code: <non-empty>, message: <non-empty>, section?: <key>, evidence?: <text>}";
174
175    /// `code` and `message` are required and non-empty; `section` and
176    /// `evidence`, when present, are non-empty too.
177    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    /// Parse and validate a finding from JSON (the CLI's `--finding` and
210    /// batch entries, the MCP param). An unknown key, a missing required
211    /// key, or an empty value is one typed refusal naming the shape.
212    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/// A check finding that does not match its shape: one refusal, the same
225/// on every surface, naming the shape it must match.
226#[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    /// Parse a wire value; `None` for anything outside the vocabulary.
244    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/// A check verdict from the closed vocabulary.
261#[derive(Debug, Clone, Copy, PartialEq, Eq)]
262pub enum Verdict {
263    Ok,
264    Failed,
265}
266
267impl Verdict {
268    /// Parse a wire value; `None` for anything outside the vocabulary.
269    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
285/// The reason a record was carried to a new `entity_hash` by the engine
286/// across a status transition it licensed ([`CheckLedger::carry_transition`]).
287pub const CARRY_REASON_TRANSITION: &str = "transition";
288
289/// The reason a sealed record was re-keyed to the archived entity bytes
290/// at export ([`SealedChecks::rekey_entity`]).
291pub const CARRY_REASON_EXPORT: &str = "export";
292
293/// Set on a record the engine carried to a new `entity_hash`: the hash
294/// the record was keyed to before, and why it moved. Two reasons exist.
295/// `transition`: a status write passed a `transition_requires_self_check`
296/// gate on the strength of this record, and the write itself moved the
297/// entity's hash, so the record that licensed the write is re-keyed to
298/// the content the write produced. `export`: a sealed export rewrote the
299/// entity's bytes (a hierarchical mem's self-qualified links follow the
300/// archive name, and the canonical re-pack re-renders every entity), so
301/// a record fresh at export is re-keyed to the archived bytes. In both
302/// cases only a record whose hash matched the pre-rewrite content moves;
303/// a stale record keeps its old hash and stays stale. Every other field
304/// is the original act's, identity included, so independence still reads
305/// the record as the checker's.
306#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
307pub struct CarriedFrom {
308    /// The `entity_hash` the record carried before it was moved.
309    pub hash: String,
310    /// [`CARRY_REASON_TRANSITION`] or [`CARRY_REASON_EXPORT`].
311    pub reason: String,
312    /// On a transition carry: the line's place in its carry chain (1 for a
313    /// line carried from a checker's own record, one more for each carry
314    /// onward). A carried line supersedes only records of a lower depth,
315    /// which orders a chain that returns to an earlier hash (two gated
316    /// values on one field, written in one second) without a clock.
317    /// Absent on export carries and on lines earlier engines wrote, which
318    /// read as depth 1.
319    #[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    /// A transition carry at `depth` in its chain.
329    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    /// The line's depth in its carry chain (see [`Self::depth`]).
338    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/// One recorded check — the full ledger line.
352#[derive(Debug, Clone, Serialize, Deserialize)]
353pub struct CheckRecord {
354    /// Unix epoch seconds at record time: the engine's clock when the
355    /// line was written, never caller-supplied.
356    pub ts: u64,
357    /// Unix epoch seconds at which the check was MADE, when the caller
358    /// said so (`observed_at` on `memstead check`, a `--from` row and
359    /// `memstead_check`): a recorder transcribing checks that were made
360    /// earlier, or out of order, states the time of each act here and
361    /// `ts` keeps the time of the transcription. It is the record's time
362    /// of the act ([`CheckRecord::act_time`]: `observed_at` where present,
363    /// `ts` otherwise), and the newest record of a kind is the one whose
364    /// act is latest ([`CheckLedger::in_standing_order`]), never the one
365    /// the ledger happens to hold last. Absent on every line written
366    /// without it, so existing ledgers parse unchanged.
367    #[serde(default, skip_serializing_if = "Option::is_none")]
368    pub observed_at: Option<u64>,
369    /// Full entity id (`mem--slug`).
370    pub entity: String,
371    /// `ok` | `failed`.
372    pub verdict: String,
373    /// Optional free-text method note ("diffed against source spec",
374    /// "re-ran the derivation").
375    #[serde(default, skip_serializing_if = "Option::is_none")]
376    pub method: Option<String>,
377    /// The entity's `content_hash` at check time — the staleness
378    /// baseline.
379    pub entity_hash: String,
380    /// Recorded actor identity (provenance).
381    pub actor: String,
382    /// Recorded client identity (`name@version`), when known.
383    #[serde(default, skip_serializing_if = "Option::is_none")]
384    pub client: Option<String>,
385    /// The caller-declared role, or `"unspecified"` — recorded
386    /// honestly; downstream gates treat unspecified as
387    /// cannot-confirm, never as any real role.
388    pub role: String,
389    /// The caller-declared identity: an opaque
390    /// caller-chosen string, the ONLY comparator the independence
391    /// gate uses. Absent on ledger lines written before identities
392    /// existed and on identity-less callers — both downgrade every
393    /// comparison to `unconfirmable`, never to a guessed category.
394    #[serde(default, skip_serializing_if = "Option::is_none")]
395    pub identity: Option<String>,
396    /// The check kind, from [`CHECK_KINDS`]. Absent on ledger lines
397    /// written before kinds existed AND on freshly recorded
398    /// `verification` checks — both read as `verification`, so an
399    /// existing ledger upgrades with no migration and a kind-omitted
400    /// caller's lines stay byte-identical to before.
401    #[serde(default, skip_serializing_if = "Option::is_none")]
402    pub kind: Option<String>,
403    /// For `conformance` records: the mem's schema pin
404    /// (`name@x.y.z`) as stamped by the engine at record time — never
405    /// caller-supplied, so a verdict cannot claim a prose version the
406    /// caller never read. Absent on `verification` records.
407    #[serde(default, skip_serializing_if = "Option::is_none")]
408    pub schema_ref: Option<String>,
409    /// The structured finding the checker attached, when one was.
410    /// Absent on every line written before findings existed and on
411    /// finding-less checks — serde-default, so every existing line
412    /// still parses and finding-less lines stay byte-identical.
413    #[serde(default, skip_serializing_if = "Option::is_none")]
414    pub finding: Option<CheckFinding>,
415    /// Set on a line the engine carried across a rename: the id the
416    /// check was recorded under before the entity took its current id.
417    /// Every other field is the original act's, hash included, so the
418    /// state derived under the new id stays honest — a rename rewrites
419    /// the file (title, self-links, timestamps), so the carried record
420    /// reads `check_stale` until someone checks the renamed entity; what
421    /// the carry prevents is the ledger losing the entity (`never_checked`
422    /// under the new id, an unreachable row under the old). Absent on
423    /// every line a checker wrote.
424    #[serde(default, skip_serializing_if = "Option::is_none")]
425    pub renamed_from: Option<String>,
426    /// Set on a line the engine carried to a new `entity_hash` (a
427    /// licensed transition, a sealed export): the hash it was keyed to
428    /// before and the reason. Absent on every line a checker wrote.
429    #[serde(default, skip_serializing_if = "Option::is_none")]
430    pub carried_from: Option<CarriedFrom>,
431    /// The write whose result the check saw: the backend-native reference
432    /// of the entity's last write when the record was made (a commit sha
433    /// on a git-branch mem, the ledger line's timestamp token on a folder
434    /// mem), stamped by the engine. Independence on an entity that is not a
435    /// plan criterion compares the checker with every identity that wrote
436    /// the entity up to and including this write, in write order, so a
437    /// write in the same second before or after the check is told apart
438    /// without a clock. A carried line keeps its source's. Absent on every
439    /// line an earlier engine wrote: those are read against every write at
440    /// or before their `ts`.
441    #[serde(default, skip_serializing_if = "Option::is_none")]
442    pub checked_write: Option<String>,
443}
444
445/// How far past the engine's clock an entity's newest act may lie for a
446/// new local check to be stamped one second after it
447/// ([`CheckLedger::record_local`]). Well inside [`OBSERVED_AT_SKEW_SECS`],
448/// so a stamped row never reads as dated in the future on another machine.
449pub const LOCAL_TIE_WINDOW_SECS: u64 = 60;
450
451/// The largest lead an `observed_at` may have over the engine's clock
452/// before it refuses as "in the future": two machines' clocks disagree by
453/// seconds, a transcription of a check that has not happened yet is a
454/// mistake.
455pub const OBSERVED_AT_SKEW_SECS: u64 = 300;
456
457/// Parse a caller-supplied `observed_at` (`YYYY-MM-DDTHH:MM:SSZ` or a
458/// bare `YYYY-MM-DD`) against the engine's clock `now` (epoch seconds):
459/// epoch seconds on success, the refusal reason otherwise (a shape the
460/// parser does not read, or an instant more than
461/// [`OBSERVED_AT_SKEW_SECS`] ahead of `now`). One parser for the CLI, the
462/// batch file and the MCP tool, so the three cannot drift.
463pub 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    /// The time of the act: `observed_at` where the recorder stated one,
482    /// `ts` otherwise. The newest record of a kind is the one with the
483    /// latest act ([`CheckLedger::in_standing_order`]).
484    pub fn act_time(&self) -> u64 {
485        self.observed_at.unwrap_or(self.ts)
486    }
487
488    /// The record's ENGINE kind, legacy lines included: an absent or
489    /// unrecognised kind reads as `verification`, which is exactly what
490    /// every pre-kind line was; a foreign `x-<name>` kind is `None` —
491    /// recorded, listed, never aggregated into a state.
492    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    /// The foreign kind, when the record carries one.
501    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/// Derived per-entity check state.
509#[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
528/// Derive the state from the newest record (if any) and the entity's
529/// current `content_hash`. Hash-only: this is the `verification`
530/// derivation, and stays the whole story for that kind — a schema
531/// re-pin never stales a verification verdict.
532pub fn derive_state(latest: Option<&CheckRecord>, current_hash: &str) -> CheckState {
533    derive_state_pinned(latest, current_hash, None)
534}
535
536/// Derive the state with schema-pin awareness: beyond the hash
537/// comparison, a record that carries a `schema_ref` (a `conformance`
538/// record) is stale when the mem's current pin differs from the
539/// recorded one — the prose the verdict judged against is no longer
540/// the prose in force. A mem that has since lost its pin entirely
541/// stales the verdict the same way. Records without a `schema_ref`
542/// (every `verification` record) are unaffected by the pin argument.
543pub 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
561/// The ledger's directory under the workspace store:
562/// `<root>/.memstead/state/checks/`.
563fn 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
570/// The ledger file path for a workspace. Private to this module with the
571/// raw read: every reader elsewhere gets rows only in standing order.
572fn check_ledger_path(workspace_root: &Path) -> PathBuf {
573    checks_dir(workspace_root).join("checks.jsonl")
574}
575
576/// Append/read handle for a workspace's check ledger.
577#[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    /// Append one record. One `write` syscall of one complete line on
590    /// an `O_APPEND` handle — concurrent writers interleave whole
591    /// lines, never tear them. Errors propagate: a check that did not
592    /// persist must refuse at the surface.
593    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    /// Append one check this engine just made, stamped so it never ties
607    /// with an earlier act on the same entity: `ts` is the engine's clock,
608    /// and when the entity's newest act already sits at or up to
609    /// [`LOCAL_TIE_WINDOW_SECS`] past it (a re-check within the same
610    /// second as the last one, say after an edit), `ts` moves to one
611    /// second past that act. Whole-second clocks would otherwise tie the
612    /// two, and the tie would go to the rows' bytes, which could stand
613    /// the check of the replaced content over the check just made. A
614    /// record whose caller stated `observed_at` is appended as stated:
615    /// the caller named the time of the act. Returns the record as
616    /// appended.
617    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    /// Carry every record of `old` across a rename to `new`: each line
637    /// keyed by the old id is appended again under the new id with
638    /// `renamed_from` set, in ledger order, as one write of whole lines.
639    /// The originals stay — the ledger is append-only and they remain the
640    /// record of what was checked under that id. Returns the number of
641    /// lines carried; zero (and no write) when the old id has none.
642    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    /// Carry the record that licensed a status transition across the
670    /// write it licensed: the newest record of `entity` under the wire
671    /// `kind` is appended again with `post_hash` as its `entity_hash` and
672    /// `carried_from: {hash: pre_hash, reason: "transition"}`, if and
673    /// only if it is fresh at `pre_hash` and confirming (`ok`). A stale
674    /// or failed record is not carried (it did not license anything),
675    /// and equal hashes carry nothing. Every other field stays the
676    /// original act's, identity included. Returns whether a line was
677    /// appended.
678    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    /// The records of one mem's entities, in standing order
708    /// ([`Self::in_standing_order`]): every record whose entity id is
709    /// qualified by `mem`.
710    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    /// The transport form of one mem's rows ([`Self::transport_lines`]).
721    pub fn transport_lines_for_mem(&self, mem: &str) -> Vec<u8> {
722        Self::transport_lines(&self.rows_for_mem(mem))
723    }
724
725    /// The transport form of a set of records: one JSON line per
726    /// record, ordered by timestamp then by the line's bytes, exact
727    /// duplicates dropped, a trailing newline. The same records give
728    /// the same bytes on every machine, so a publish that changed
729    /// nothing writes nothing.
730    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    /// Union `lines` (the transport form, from another machine) into
746    /// this ledger: every record not already present is appended; a
747    /// record already present (the same bytes) is skipped, so a round
748    /// trip adds nothing. Unparseable lines are skipped. Rows keep every
749    /// field they arrived with: identity, role, hash, timestamps; nothing
750    /// is rewritten on import, and a merged row counts by its own fields
751    /// (its time of the act places it, never its arrival).
752    ///
753    /// A row whose time of the act lies more than
754    /// [`OBSERVED_AT_SKEW_SECS`] ahead of `now` (the receiving engine's
755    /// clock) is refused as a local record with such a time is, and named
756    /// in the outcome: ordered by time, a row from a machine with a wrong
757    /// clock would otherwise stand for good.
758    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    /// The ledger's lines in arrival order. Private by construction:
797    /// arrival order is not an order any reading may rest on (two machines
798    /// holding the same rows hold them in different orders), so every
799    /// reader outside this module gets rows only through
800    /// [`Self::in_standing_order`] and the lookups built on it. A missing
801    /// ledger is an empty one; unparseable lines are skipped (a torn tail
802    /// must not poison the readable history).
803    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    /// Every record, in standing order: the one order every reader of a
814    /// standing folds, so the last row of any (entity, kind) group, and of
815    /// any narrower group of one entity's rows, is that group's newest
816    /// record. The order is derived from the rows alone, so two machines
817    /// holding the same rows derive the same newest whatever order their
818    /// ledgers hold them in:
819    ///
820    /// 1. a carried line supersedes every record of the same entity and
821    ///    kind whose `entity_hash` is its `carried_from.hash` and whose act
822    ///    is no later than the carried line's (they are keyed to content
823    ///    the carry replaced; a check made later, after the content came
824    ///    back to that hash, is a new act) and that stand lower in the carry
825    ///    chain ([`CarriedFrom::depth`]); superseded rows come first;
826    /// 2. among the rest, the earlier time of the act comes first
827    ///    ([`CheckRecord::act_time`]);
828    /// 3. remaining ties are ordered by the rows' canonical bytes, never
829    ///    by ledger position.
830    pub fn in_standing_order(&self) -> Vec<CheckRecord> {
831        standing_order(self.raw_lines())
832    }
833
834    /// The newest record for one entity, of any kind
835    /// ([`Self::in_standing_order`]). State derivation is per (entity,
836    /// kind) — use [`Self::latest_for_kind`] there; this remains the
837    /// "what happened last" accessor.
838    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    /// The newest record for one entity of one kind. A later check of
846    /// the OTHER kind never supersedes it: the two derivations answer
847    /// different questions.
848    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    /// The newest record for one entity of one WIRE kind: an engine
856    /// kind resolves as [`Self::latest_for_kind`] (legacy kind-less
857    /// lines read as `verification`); a foreign `x-<name>` kind matches
858    /// the recorded kind verbatim. The lookup a `transition_requires_self_check`
859    /// gate declares its kind against.
860    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/// What [`CheckLedger::merge_transport_lines`] did with a set of rows
873/// from another machine.
874#[derive(Debug, Clone, Default, PartialEq, Eq)]
875pub struct MergedRows {
876    /// Rows appended to the local ledger.
877    pub appended: usize,
878    /// Rows refused, each named.
879    pub refused: Vec<RefusedCheckRow>,
880}
881
882/// A merged row the receiving engine refused: its time of the act lies
883/// beyond the clock skew allowance ahead of the receiving clock.
884#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
885pub struct RefusedCheckRow {
886    /// Full entity id (`mem--slug`).
887    pub entity: String,
888    /// Wire kind.
889    pub kind: String,
890    /// The row's time of the act, epoch seconds.
891    pub act_time: u64,
892    /// The row's declared identity, when it carries one.
893    #[serde(default, skip_serializing_if = "Option::is_none")]
894    pub identity: Option<String>,
895    /// Why it was refused.
896    pub reason: String,
897}
898
899/// Sort rows into standing order (see [`CheckLedger::in_standing_order`]).
900/// The one place the order is decided.
901fn standing_order(rows: Vec<CheckRecord>) -> Vec<CheckRecord> {
902    // Each carried line: (entity, kind, hash it left, its time of the act,
903    // its depth in the carry chain).
904    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    // A row is superseded by a carried line of its entity and kind that
919    // left the row's hash, when the row's act is no later than the
920    // carried line's (a check made later at that hash, after the content
921    // came back to it, is a new act and competes by its time), and when the
922    // row stands lower in the carry chain (a checker's own record is depth
923    // 0). The depth orders a chain that returns to an earlier hash, which
924    // two gated values on one field written in one second produce: every
925    // line of it shares the source's times, and only the last carry stands.
926    // A line an earlier engine carried has no depth and supersedes as it
927    // always did; a row without a depth stands below every depth.
928    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
952// ---------------------------------------------------------------------------
953// Sealed check records: the archive member
954// ---------------------------------------------------------------------------
955
956/// Version of the sealed check-records member
957/// (`.memstead/checks.json`, [`memstead_schema::ARCHIVE_CHECKS_PATH`]).
958/// Read back by the archive mount; a reader tells "absent" from
959/// "not carried" by this line inside the member, so the published
960/// archive format number never moves for it.
961pub const SEALED_CHECKS_VERSION: u32 = 1;
962
963/// One sealed check record: the fields of the ledger line the archive
964/// carries, nothing invented. `kind` is the map key it sits under, the
965/// entity is the map key above that (its mem-relative path, so the
966/// member survives a remount under another mem name). The transport
967/// client and the structured finding stay in the workspace ledger: the
968/// archive answers state, and state derives from these fields alone.
969#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
970pub struct SealedCheck {
971    /// Unix epoch seconds at record time.
972    pub ts: u64,
973    /// When the check was made, as the caller stated it (see
974    /// [`CheckRecord::observed_at`]); absent when nobody did.
975    #[serde(default, skip_serializing_if = "Option::is_none")]
976    pub observed_at: Option<u64>,
977    /// `ok` | `failed`.
978    pub verdict: String,
979    /// The free-text method note, after the export's private-pattern
980    /// redaction (the same classes the provenance member applies).
981    #[serde(default, skip_serializing_if = "Option::is_none")]
982    pub method: Option<String>,
983    /// The entity's `content_hash` at check time: the freshness
984    /// baseline the mount compares against the sealed entity.
985    pub entity_hash: String,
986    /// Recorded actor category (`cli`, `agent`, ...).
987    pub actor: String,
988    /// The declared role, or `unspecified`.
989    pub role: String,
990    /// The declared identity, verbatim: a handle, never a person.
991    #[serde(default, skip_serializing_if = "Option::is_none")]
992    pub identity: Option<String>,
993    /// The schema pin a `conformance` record was judged against.
994    #[serde(default, skip_serializing_if = "Option::is_none")]
995    pub schema_ref: Option<String>,
996    /// The id the check was recorded under before a rename carried it.
997    #[serde(default, skip_serializing_if = "Option::is_none")]
998    pub renamed_from: Option<String>,
999    /// The hash the record was keyed to before the engine carried it,
1000    /// and why (a licensed transition on the source mem, or the export's
1001    /// own rewrite of the entity bytes).
1002    #[serde(default, skip_serializing_if = "Option::is_none")]
1003    pub carried_from: Option<CarriedFrom>,
1004    /// The author≠checker independence reading
1005    /// ([`crate::engine::independence::Independence`], wire form:
1006    /// `confirmed_independent`, `self_checked`, `unconfirmable`) the
1007    /// export derived for this record from the mem's provenance at
1008    /// export time. The archive records no history at the engine seam,
1009    /// so the reading cannot be re-derived on the mount; sealed here it
1010    /// is the fact an immutable archive carries. Absent from a member an
1011    /// older writer sealed: the mount then reads `unconfirmable`.
1012    #[serde(default, skip_serializing_if = "Option::is_none")]
1013    pub independence: Option<String>,
1014    /// The trust class of the TEXT this row carries — its `method` note and
1015    /// its finding message ([`crate::render::OriginClass`], wire form
1016    /// `first-party` / `third-party`), as the exporting workspace
1017    /// classified it ([`crate::Engine::check_row_origin_class`]).
1018    ///
1019    /// A check row's prose is written by whatever agent recorded the check,
1020    /// which in a workspace that points a foreign model or a transcribed
1021    /// outside finding at its ledger is not the workspace itself. Sealed
1022    /// here for the same reason `independence` is: the mount records no
1023    /// identity roster, so the reading cannot be re-derived on it.
1024    ///
1025    /// Absent when the exporting deployment declared no owner identities
1026    /// (the row then inherits its mem's class, which is what every reader
1027    /// did before this field) and on every member an older writer sealed.
1028    #[serde(default, skip_serializing_if = "Option::is_none")]
1029    pub origin: Option<String>,
1030}
1031
1032impl SealedCheck {
1033    /// The archive form of a ledger line, with no independence reading
1034    /// yet (the export derives and sets it; see
1035    /// [`crate::ops::export::build_redacted_sealed_checks`]).
1036    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    /// The sealed independence reading, parsed; `None` when the member
1055    /// carries none (an older writer) or a value outside the vocabulary.
1056    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    /// The sealed trust class of the row's prose, parsed; `None` when the
1063    /// member seals none, which is every member an older writer sealed and
1064    /// every export from a deployment that declared no owner identities.
1065    /// The reader falls back to the mem's class then, as it did before the
1066    /// field existed.
1067    ///
1068    /// This is the one reader that makes the sealed field load-bearing, and
1069    /// it matters exactly where the mem grain cannot answer: a deployment
1070    /// that vouches for an installed archive as first-party
1071    /// ([`crate::Engine::declare_mem_origin`]) still must not serve a row
1072    /// the publisher's own foreign checker wrote as its own prose.
1073    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    /// The ledger form under `entity_id` and the wire `kind` the record
1082    /// sits under, so every derivation ([`derive_state`],
1083    /// [`derive_state_pinned`]) and every surface that renders a
1084    /// [`CheckRecord`] reads a sealed record the way it reads a ledger
1085    /// line. A `verification` kind stays omitted, as the ledger writes it.
1086    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/// The sealed check-records member: per entity (keyed by mem-relative
1109/// path) the latest record per kind (keyed by wire kind:
1110/// `verification`, `conformance`, or a foreign `x-<name>`).
1111#[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    /// An empty member of the current version.
1120    pub fn new() -> Self {
1121        Self {
1122            version: SEALED_CHECKS_VERSION,
1123            entities: BTreeMap::new(),
1124        }
1125    }
1126
1127    /// The latest sealed record of one entity (by mem-relative path)
1128    /// under one wire kind.
1129    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    /// Every sealed kind of one entity, in key order.
1136    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    /// Re-key every record of one entity that is fresh at `pre_hash` to
1144    /// `post_hash`, marking it `carried_from: {hash: pre_hash, reason:
1145    /// "export"}`: the export rewrote the entity's bytes (links retargeted
1146    /// to the archive name, the canonical re-render), and a record that
1147    /// was fresh against the source content stays fresh against the
1148    /// archived content. A record keyed to any other hash was stale
1149    /// before the export and keeps its hash, so it still reads stale on
1150    /// the mount. Equal hashes change nothing; every other field, the
1151    /// sealed independence reading included, stays as sealed. Returns the
1152    /// number of records moved.
1153    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    /// Serialise to the canonical member bytes (pretty JSON, trailing
1172    /// newline), deterministic for a given content: both maps are
1173    /// ordered.
1174    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    /// Parse the member bytes. Shape only; [`Self::validate`] checks the
1181    /// vocabulary and the entity roster.
1182    pub fn from_archive_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
1183        serde_json::from_slice(bytes)
1184    }
1185
1186    /// The validator's shape check: the version this engine reads, every
1187    /// kind in the vocabulary, every verdict in the vocabulary, a
1188    /// non-empty hash, actor and role, and every entity path one the
1189    /// archive carries (`carried` is the set of mem-relative entity
1190    /// paths). The error names the first offending record.
1191    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                // The trust class is publisher-supplied bytes on an
1237                // installed archive, so the vocabulary is closed here as
1238                // the independence reading's is: an unknown token is
1239                // refused with a typed error rather than parsed into
1240                // something a reader would treat as a class.
1241                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
1260/// The wire kind a ledger line sits under in the sealed member: an
1261/// engine kind by its resolved name (a legacy kind-less line is
1262/// `verification`), a foreign kind verbatim.
1263pub 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    /// The newest record of a kind is the one made last, whatever order
1310    /// the ledger holds the lines in: a merged row older than the local
1311    /// one does not displace it, a merged row made later does.
1312    #[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    /// `observed_at` is the time of the act: checks transcribed out of
1337    /// order stand by it, not by the transcription time `ts`.
1338    #[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    /// A carried line shares its source's times by construction; it
1353    /// supersedes every record of the entity and kind keyed to the hash
1354    /// it was carried from, whatever the bytes would say.
1355    #[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            // A second record at the source's hash, same second: also
1369            // keyed to the replaced content, also superseded.
1370            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    /// A check made at the hash a carry left, after the content came back
1388    /// to it, is a new act and stands by its time. A carry chain stands on
1389    /// its last line, and so does a carry cycle, in every ledger order.
1390    #[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        // A chain h1 to h2 to h3 stands on its last line.
1427        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        // A cycle h1 to h2, back to h1, on to h2 again (two gated values
1431        // on one field, written in one second) stands on its last carry
1432        // in every ledger order.
1433        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        // Lines an earlier engine carried (no depth) keep their old reading.
1448        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    /// Two workspaces holding the same rows in different ledger orders,
1463    /// two of them with equal times of the act, derive the same standing.
1464    #[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    /// A check this engine makes right after another on the same entity,
1494    /// in the same second, stands over it: the local stamp moves past the
1495    /// earlier act instead of tying with it. A stated `observed_at` is
1496    /// kept as stated.
1497    #[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        // "zz" sorts after "h2": by bytes alone the old check would win.
1502        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        // Far behind the clock: nothing moves.
1515        assert_eq!(
1516            ledger.record_local(at("m--f", "ok", "h", 5000)).unwrap().ts,
1517            5000
1518        );
1519    }
1520
1521    /// A merged row dated beyond the clock skew ahead of the receiving
1522    /// clock is refused as a local record with such a time is, and named;
1523    /// the rows beside it still land.
1524    #[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        // A failed check on changed content is stale too — the verdict
1555        // no longer speaks to current content either way.
1556        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        // Supersession never erases: all three records remain.
1571        assert_eq!(ledger.raw_lines().len(), 3);
1572    }
1573
1574    /// A rename carries the old id's lines under the new id, marked
1575    /// with their origin, and leaves the originals in place. The carried
1576    /// line keeps the hash the check was made against, so it derives
1577    /// `check_stale` against the renamed file's new hash — never a
1578    /// silently fresh `checked_ok`, never `never_checked`.
1579    /// `observed_at` is the caller's statement of when the check was
1580    /// made: parsed from the two ISO shapes, refused when unreadable or
1581    /// ahead of the clock beyond the skew allowance, kept verbatim by
1582    /// the rename carry (every carried field is the original act's) and
1583    /// by the sealed form's round trip, and absent from a line that
1584    /// never carried it, byte for byte.
1585    #[test]
1586    fn observed_at_parses_refuses_the_future_and_survives_the_carries() {
1587        let now = 1_792_503_930; // 2026-10-20T13:45:30Z
1588        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        // Inside the skew allowance: accepted. Beyond it: refused.
1591        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        // A checker's own line never carries the marker.
1669        assert!(
1670            ledger
1671                .latest_for("m--other")
1672                .unwrap()
1673                .renamed_from
1674                .is_none()
1675        );
1676    }
1677
1678    /// A transition carry re-keys the licensing record to the post-write
1679    /// hash and marks its origin; a record that is stale at the pre-write
1680    /// hash, a failed one, or an unchanged hash carries nothing. The
1681    /// carried line keeps the checker's identity, so independence still
1682    /// reads it as the checker's, not the writer's.
1683    #[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        // A second transition carries the carried line onward, one step.
1725        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        // A failed record licenses nothing and is never carried.
1736        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        // A checker's own line never carries the marker.
1745        assert!(all[0].carried_from.is_none());
1746    }
1747
1748    /// The sealed member re-keys a record fresh at the pre-rewrite hash
1749    /// to the archived hash and marks it; a stale record keeps its hash.
1750    #[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        // The round trip through the ledger form keeps the marker.
1774        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        // A pre-marker member line still parses, and reads no independence.
1778        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    /// The sealed trust class of a row's prose parses only from the two
1786    /// origin tokens and fails the validator outside them. The bytes come
1787    /// from a publisher's archive, so the vocabulary is closed here exactly
1788    /// as the independence reading's is: a member claiming `first-party` in
1789    /// a spelling no reader recognises must be refused with a typed error,
1790    /// not parsed into something a reader treats as a class.
1791    #[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        // A member an older writer sealed carries none and reads none.
1808        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        // A token outside the vocabulary is refused, and reads as no class
1814        // rather than as a guess.
1815        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    /// The sealed independence reading survives the export re-key, is
1834    /// dropped from the ledger form (the ledger derives, never stores
1835    /// it), parses only from the vocabulary, and fails the validator
1836    /// outside it.
1837    #[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    /// A pre-kind ledger line (no `kind` field) parses
1904    /// and derives as a `verification` record, byte-for-byte the old
1905    /// shape on the write side too.
1906    #[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        // A freshly built verification record serialises with no kind
1912        // and no schema_ref key at all.
1913        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        // An identity-less record carries no identity key either —
1918        // pre-identity lines and identity-less callers stay
1919        // byte-identical.
1920        assert!(!line.contains("identity"));
1921    }
1922
1923    /// State derives per (entity, kind) — a later check
1924    /// of the other kind does not supersede.
1925    #[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    /// A conformance verdict is stale on a content move
1945    /// AND on a pin move; a verification verdict ignores pin moves.
1946    #[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        // The mem losing its pin stales the verdict too.
1962        assert_eq!(
1963            derive_state_pinned(Some(&c), "h1", None),
1964            CheckState::CheckStale
1965        );
1966        // Verification: unaffected by any pin argument.
1967        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    // --- findings and open kinds ---
1976
1977    #[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        // A pre-`x-` unrecognised kind keeps its legacy reading.
2023        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        // A line written before findings existed: no `finding`, no `kind`.
2034        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        // A foreign-kind line beside it moves no verification state.
2055        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}