Skip to main content

memstead_base/
check.rs

1//! Check records — the engine-recorded act of verification
2//!.
3//!
4//! A check is an agent recording "entity E checked, verdict ok |
5//! failed, via method M". It is engine state, never entity content:
6//! absent from markdown and `content_hash`, and it produces no mem
7//! commit — checking-touches-nothing is what makes check-staleness
8//! computable. Records are append-only JSONL under the workspace
9//! store (`.memstead/state/checks/checks.jsonl`); a newer check of
10//! the same kind supersedes older ones for state derivation but
11//! never erases them (kinds derive independently, see [`CheckKind`]).
12//!
13//! Unlike the friction ledger next door, recording here is NOT
14//! best-effort: a check the ledger failed to persist must refuse —
15//! the caller believes the act was recorded, and a silently dropped
16//! check is exactly the self-report dishonesty this tier exists to
17//! end. For the same reason there is no rotation cap: check history
18//! is the substrate process state derives from, not disposable
19//! telemetry.
20//!
21//! Each record carries plan-13 provenance (actor, client, declared
22//! role) plus the entity's `content_hash` at check time. State
23//! derivation compares that hash against the current one:
24//!
25//! - no record            → `never_checked`
26//! - hash matches, ok     → `checked_ok`
27//! - hash matches, failed → `check_failed`
28//! - hash differs         → `check_stale` (whatever the verdict was,
29//!   it no longer speaks to the current content — stated, never
30//!   silently carried forward)
31//!
32//! A `conformance` record additionally carries the mem's schema pin
33//! and goes stale when the pin moves ([`derive_state_pinned`]): the
34//! prose it judged against is no longer the prose in force.
35
36use std::collections::BTreeMap;
37use std::io::Write;
38use std::path::{Path, PathBuf};
39
40use serde::{Deserialize, Serialize};
41
42/// The closed verdict vocabulary. Nuance goes in the method note or
43/// in process-mem entities — never in new verdict values.
44pub const VERDICTS: [&str; 2] = ["ok", "failed"];
45
46/// The closed kind vocabulary. `verification` is the default and
47/// today's behaviour: "I checked this entity's content". `conformance`
48/// is the semantic judgment "this entity satisfies its type's
49/// schema prose (`write_rules` / `writing_guidance`)" — recorded with
50/// the mem's schema pin, stamped by the engine at record time, so the
51/// verdict's freshness against both the content AND the prose version
52/// stays computable. A third kind is a separate decision; closed
53/// kinds keep health aggregation well-defined, matching the closed
54/// verdict vocabulary.
55pub const CHECK_KINDS: [&str; 2] = ["verification", "conformance"];
56
57/// Prefix of a caller-declared check kind the engine records verbatim
58/// and never interprets: `x-<name>`, `name` lowercase letters, digits
59/// and hyphens. The prefix makes the declaration deliberate — a typo of
60/// an engine kind cannot silently become a new kind — mirroring the
61/// rule that a third ENGINE kind is a separate decision. Foreign kinds
62/// never influence `check_state`; health lists them by count.
63pub const FOREIGN_KIND_PREFIX: &str = "x-";
64
65/// The typed code for a malformed finding.
66pub const INVALID_CHECK_FINDING_CODE: &str = "INVALID_CHECK_FINDING";
67
68/// A check kind from the closed vocabulary.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum CheckKind {
71    Verification,
72    Conformance,
73}
74
75/// What a caller may declare as a check's kind: one of the engine's
76/// two kinds, or a foreign `x-<name>` kind recorded verbatim.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub enum RecordKind {
79    Engine(CheckKind),
80    Foreign(String),
81}
82
83impl RecordKind {
84    /// Parse a wire kind: an engine kind, an `x-` kind (name non-empty,
85    /// lowercase letters, digits and hyphens), or `None` for anything
86    /// else — the vocabulary the refusal names is [`CHECK_KINDS`] plus
87    /// the `x-<name>` form.
88    pub fn from_wire(s: &str) -> Option<Self> {
89        if let Some(k) = CheckKind::from_wire(s) {
90            return Some(Self::Engine(k));
91        }
92        // ONE grammar, declared beside the schema's constraint
93        // vocabulary so a `transition_requires_self_check` declaration
94        // and a recorded check agree on what a kind may look like.
95        s.starts_with(FOREIGN_KIND_PREFIX)
96            .then(|| memstead_schema::check_kind_wire_is_well_formed(s))
97            .filter(|ok| *ok)
98            .map(|_| Self::Foreign(s.to_string()))
99    }
100
101    /// The engine kind, when this is one.
102    pub fn engine_kind(&self) -> Option<CheckKind> {
103        match self {
104            Self::Engine(k) => Some(*k),
105            Self::Foreign(_) => None,
106        }
107    }
108
109    /// Stable wire form.
110    pub fn as_wire(&self) -> &str {
111        match self {
112            Self::Engine(k) => k.as_str(),
113            Self::Foreign(s) => s.as_str(),
114        }
115    }
116
117    /// The vocabulary sentence a refusal carries.
118    pub fn vocabulary_hint() -> String {
119        format!(
120            "{}, or a caller-declared `{FOREIGN_KIND_PREFIX}<name>` kind (lowercase letters, digits, hyphens) the engine records verbatim and never interprets",
121            CHECK_KINDS.join(", ")
122        )
123    }
124}
125
126/// A structured finding riding a check record: WHAT failed (or what was
127/// observed) in a locatable form, so a `failed` verdict never forces
128/// the author to re-derive the failure from a free-text method note.
129/// `code` in `UPPER_SNAKE` is the engine's namespace and must name a
130/// health condition ([`crate::ops::strict::HEALTH_CONDITIONS`]); any
131/// other spelling is the checker's own vocabulary. The wrapper shape is
132/// fixed and refuses unknown keys.
133#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
134#[serde(deny_unknown_fields)]
135pub struct CheckFinding {
136    /// The checker's finding code (`hidden-premise`, `stale-source`, …).
137    pub code: String,
138    /// The section key the finding concerns, when it concerns one.
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub section: Option<String>,
141    /// One or two sentences a reader can act on.
142    pub message: String,
143    /// What the finding rests on: a quote, a coordinate, a reference.
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub evidence: Option<String>,
146}
147
148impl CheckFinding {
149    /// The shape sentence every refusal names.
150    pub const SHAPE: &'static str =
151        "{code: <non-empty>, message: <non-empty>, section?: <key>, evidence?: <text>}";
152
153    /// `code` and `message` are required and non-empty; `section` and
154    /// `evidence`, when present, are non-empty too.
155    pub fn validate(&self) -> Result<(), String> {
156        if self.code.trim().is_empty() {
157            return Err(format!(
158                "finding.code is required and must be non-empty — shape {}",
159                Self::SHAPE
160            ));
161        }
162        if self.message.trim().is_empty() {
163            return Err(format!(
164                "finding.message is required and must be non-empty — shape {}",
165                Self::SHAPE
166            ));
167        }
168        if self.section.as_deref().is_some_and(|s| s.trim().is_empty()) {
169            return Err(format!(
170                "finding.section, when given, must be non-empty — shape {}",
171                Self::SHAPE
172            ));
173        }
174        if self
175            .evidence
176            .as_deref()
177            .is_some_and(|s| s.trim().is_empty())
178        {
179            return Err(format!(
180                "finding.evidence, when given, must be non-empty — shape {}",
181                Self::SHAPE
182            ));
183        }
184        Ok(())
185    }
186
187    /// Parse and validate a finding from JSON (the CLI's `--finding` and
188    /// batch entries, the MCP param). An unknown key, a missing required
189    /// key, or an empty value is one typed refusal naming the shape.
190    pub fn from_json(value: serde_json::Value) -> Result<Self, String> {
191        let finding: CheckFinding = serde_json::from_value(value)
192            .map_err(|e| format!("finding does not match the shape {} ({e})", Self::SHAPE))?;
193        finding.validate()?;
194        Ok(finding)
195    }
196}
197
198impl CheckKind {
199    /// Parse a wire value; `None` for anything outside the vocabulary.
200    pub fn from_wire(s: &str) -> Option<Self> {
201        match s {
202            "verification" => Some(Self::Verification),
203            "conformance" => Some(Self::Conformance),
204            _ => None,
205        }
206    }
207
208    pub fn as_str(self) -> &'static str {
209        match self {
210            Self::Verification => "verification",
211            Self::Conformance => "conformance",
212        }
213    }
214}
215
216/// A check verdict from the closed vocabulary.
217#[derive(Debug, Clone, Copy, PartialEq, Eq)]
218pub enum Verdict {
219    Ok,
220    Failed,
221}
222
223impl Verdict {
224    /// Parse a wire value; `None` for anything outside the vocabulary.
225    pub fn from_wire(s: &str) -> Option<Self> {
226        match s {
227            "ok" => Some(Self::Ok),
228            "failed" => Some(Self::Failed),
229            _ => None,
230        }
231    }
232
233    pub fn as_str(self) -> &'static str {
234        match self {
235            Self::Ok => "ok",
236            Self::Failed => "failed",
237        }
238    }
239}
240
241/// The reason a record was carried to a new `entity_hash` by the engine
242/// across a status transition it licensed ([`CheckLedger::carry_transition`]).
243pub const CARRY_REASON_TRANSITION: &str = "transition";
244
245/// The reason a sealed record was re-keyed to the archived entity bytes
246/// at export ([`SealedChecks::rekey_entity`]).
247pub const CARRY_REASON_EXPORT: &str = "export";
248
249/// Set on a record the engine carried to a new `entity_hash`: the hash
250/// the record was keyed to before, and why it moved. Two reasons exist.
251/// `transition`: a status write passed a `transition_requires_self_check`
252/// gate on the strength of this record, and the write itself moved the
253/// entity's hash, so the record that licensed the write is re-keyed to
254/// the content the write produced. `export`: a sealed export rewrote the
255/// entity's bytes (a hierarchical mem's self-qualified links follow the
256/// archive name, and the canonical re-pack re-renders every entity), so
257/// a record fresh at export is re-keyed to the archived bytes. In both
258/// cases only a record whose hash matched the pre-rewrite content moves;
259/// a stale record keeps its old hash and stays stale. Every other field
260/// is the original act's, identity included, so independence still reads
261/// the record as the checker's.
262#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
263pub struct CarriedFrom {
264    /// The `entity_hash` the record carried before it was moved.
265    pub hash: String,
266    /// [`CARRY_REASON_TRANSITION`] or [`CARRY_REASON_EXPORT`].
267    pub reason: String,
268}
269
270impl CarriedFrom {
271    pub fn transition(hash: &str) -> Self {
272        Self {
273            hash: hash.to_string(),
274            reason: CARRY_REASON_TRANSITION.to_string(),
275        }
276    }
277
278    pub fn export(hash: &str) -> Self {
279        Self {
280            hash: hash.to_string(),
281            reason: CARRY_REASON_EXPORT.to_string(),
282        }
283    }
284}
285
286/// One recorded check — the full ledger line.
287#[derive(Debug, Clone, Serialize, Deserialize)]
288pub struct CheckRecord {
289    /// Unix epoch seconds at record time: the engine's clock when the
290    /// line was written, never caller-supplied.
291    pub ts: u64,
292    /// Unix epoch seconds at which the check was MADE, when the caller
293    /// said so (`observed_at` on `memstead check`, a `--from` row and
294    /// `memstead_check`): a recorder transcribing checks that were made
295    /// earlier, or out of order, states the time of each act here and
296    /// `ts` keeps the time of the transcription. Informational: a reader
297    /// ordering checks by time takes `observed_at` where present and `ts`
298    /// otherwise; the engine's own state derivation ("the newest record
299    /// of a kind") reads ledger order and ignores both. Absent on every
300    /// line written without it, so existing ledgers parse unchanged.
301    #[serde(default, skip_serializing_if = "Option::is_none")]
302    pub observed_at: Option<u64>,
303    /// Full entity id (`mem--slug`).
304    pub entity: String,
305    /// `ok` | `failed`.
306    pub verdict: String,
307    /// Optional free-text method note ("diffed against source spec",
308    /// "re-ran the derivation").
309    #[serde(default, skip_serializing_if = "Option::is_none")]
310    pub method: Option<String>,
311    /// The entity's `content_hash` at check time — the staleness
312    /// baseline.
313    pub entity_hash: String,
314    /// Recorded actor identity (plan-13 provenance).
315    pub actor: String,
316    /// Recorded client identity (`name@version`), when known.
317    #[serde(default, skip_serializing_if = "Option::is_none")]
318    pub client: Option<String>,
319    /// The caller-declared role, or `"unspecified"` — recorded
320    /// honestly; downstream gates treat unspecified as
321    /// cannot-confirm, never as any real role.
322    pub role: String,
323    /// The caller-declared identity: an opaque
324    /// caller-chosen string, the ONLY comparator the independence
325    /// gate uses. Absent on ledger lines written before identities
326    /// existed and on identity-less callers — both downgrade every
327    /// comparison to `unconfirmable`, never to a guessed category.
328    #[serde(default, skip_serializing_if = "Option::is_none")]
329    pub identity: Option<String>,
330    /// The check kind, from [`CHECK_KINDS`]. Absent on ledger lines
331    /// written before kinds existed AND on freshly recorded
332    /// `verification` checks — both read as `verification`, so an
333    /// existing ledger upgrades with no migration and a kind-omitted
334    /// caller's lines stay byte-identical to before.
335    #[serde(default, skip_serializing_if = "Option::is_none")]
336    pub kind: Option<String>,
337    /// For `conformance` records: the mem's schema pin
338    /// (`name@x.y.z`) as stamped by the engine at record time — never
339    /// caller-supplied, so a verdict cannot claim a prose version the
340    /// caller never read. Absent on `verification` records.
341    #[serde(default, skip_serializing_if = "Option::is_none")]
342    pub schema_ref: Option<String>,
343    /// The structured finding the checker attached, when one was.
344    /// Absent on every line written before findings existed and on
345    /// finding-less checks — serde-default, so every existing line
346    /// still parses and finding-less lines stay byte-identical.
347    #[serde(default, skip_serializing_if = "Option::is_none")]
348    pub finding: Option<CheckFinding>,
349    /// Set on a line the engine carried across a rename: the id the
350    /// check was recorded under before the entity took its current id.
351    /// Every other field is the original act's, hash included, so the
352    /// state derived under the new id stays honest — a rename rewrites
353    /// the file (title, self-links, timestamps), so the carried record
354    /// reads `check_stale` until someone checks the renamed entity; what
355    /// the carry prevents is the ledger losing the entity (`never_checked`
356    /// under the new id, an unreachable row under the old). Absent on
357    /// every line a checker wrote.
358    #[serde(default, skip_serializing_if = "Option::is_none")]
359    pub renamed_from: Option<String>,
360    /// Set on a line the engine carried to a new `entity_hash` (a
361    /// licensed transition, a sealed export): the hash it was keyed to
362    /// before and the reason. Absent on every line a checker wrote.
363    #[serde(default, skip_serializing_if = "Option::is_none")]
364    pub carried_from: Option<CarriedFrom>,
365}
366
367/// The largest lead an `observed_at` may have over the engine's clock
368/// before it refuses as "in the future": two machines' clocks disagree by
369/// seconds, a transcription of a check that has not happened yet is a
370/// mistake.
371pub const OBSERVED_AT_SKEW_SECS: u64 = 300;
372
373/// Parse a caller-supplied `observed_at` (`YYYY-MM-DDTHH:MM:SSZ` or a
374/// bare `YYYY-MM-DD`) against the engine's clock `now` (epoch seconds):
375/// epoch seconds on success, the refusal reason otherwise (a shape the
376/// parser does not read, or an instant more than
377/// [`OBSERVED_AT_SKEW_SECS`] ahead of `now`). One parser for the CLI, the
378/// batch file and the MCP tool, so the three cannot drift.
379pub fn parse_observed_at(raw: &str, now: u64) -> Result<u64, String> {
380    let s = raw.trim();
381    let Some(at) = crate::engine::due::parse_iso_utc_seconds(s) else {
382        return Err(format!(
383            "observed_at {raw:?} is not an ISO-8601 UTC instant (`YYYY-MM-DDTHH:MM:SSZ`) \
384             or a civil date (`YYYY-MM-DD`)"
385        ));
386    };
387    if at > now.saturating_add(OBSERVED_AT_SKEW_SECS) {
388        return Err(format!(
389            "observed_at {raw:?} lies in the future (the engine's clock reads {now} epoch \
390             seconds); a check is recorded after it was made, never before"
391        ));
392    }
393    Ok(at)
394}
395
396impl CheckRecord {
397    /// The record's ENGINE kind, legacy lines included: an absent or
398    /// unrecognised kind reads as `verification`, which is exactly what
399    /// every pre-kind line was; a foreign `x-<name>` kind is `None` —
400    /// recorded, listed, never aggregated into a state.
401    pub fn resolved_kind(&self) -> Option<CheckKind> {
402        match self.kind.as_deref() {
403            None => Some(CheckKind::Verification),
404            Some(k) if k.starts_with(FOREIGN_KIND_PREFIX) => None,
405            Some(k) => Some(CheckKind::from_wire(k).unwrap_or(CheckKind::Verification)),
406        }
407    }
408
409    /// The foreign kind, when the record carries one.
410    pub fn foreign_kind(&self) -> Option<&str> {
411        self.kind
412            .as_deref()
413            .filter(|k| k.starts_with(FOREIGN_KIND_PREFIX))
414    }
415}
416
417/// Derived per-entity check state.
418#[derive(Debug, Clone, Copy, PartialEq, Eq)]
419pub enum CheckState {
420    NeverChecked,
421    CheckedOk,
422    CheckFailed,
423    CheckStale,
424}
425
426impl CheckState {
427    pub fn as_str(self) -> &'static str {
428        match self {
429            Self::NeverChecked => "never_checked",
430            Self::CheckedOk => "checked_ok",
431            Self::CheckFailed => "check_failed",
432            Self::CheckStale => "check_stale",
433        }
434    }
435}
436
437/// Derive the state from the newest record (if any) and the entity's
438/// current `content_hash`. Hash-only: this is the `verification`
439/// derivation, and stays the whole story for that kind — a schema
440/// re-pin never stales a verification verdict.
441pub fn derive_state(latest: Option<&CheckRecord>, current_hash: &str) -> CheckState {
442    derive_state_pinned(latest, current_hash, None)
443}
444
445/// Derive the state with schema-pin awareness: beyond the hash
446/// comparison, a record that carries a `schema_ref` (a `conformance`
447/// record) is stale when the mem's current pin differs from the
448/// recorded one — the prose the verdict judged against is no longer
449/// the prose in force. A mem that has since lost its pin entirely
450/// stales the verdict the same way. Records without a `schema_ref`
451/// (every `verification` record) are unaffected by the pin argument.
452pub fn derive_state_pinned(
453    latest: Option<&CheckRecord>,
454    current_hash: &str,
455    current_schema_ref: Option<&str>,
456) -> CheckState {
457    match latest {
458        None => CheckState::NeverChecked,
459        Some(rec) if rec.entity_hash != current_hash => CheckState::CheckStale,
460        Some(rec)
461            if rec.schema_ref.is_some() && rec.schema_ref.as_deref() != current_schema_ref =>
462        {
463            CheckState::CheckStale
464        }
465        Some(rec) if rec.verdict == "failed" => CheckState::CheckFailed,
466        Some(_) => CheckState::CheckedOk,
467    }
468}
469
470/// The ledger's directory under the workspace store:
471/// `<root>/.memstead/state/checks/`.
472fn checks_dir(workspace_root: &Path) -> PathBuf {
473    workspace_root
474        .join(crate::workspace_store::WORKSPACE_STORE_DIR)
475        .join("state")
476        .join("checks")
477}
478
479/// The ledger file path for a workspace.
480pub fn check_ledger_path(workspace_root: &Path) -> PathBuf {
481    checks_dir(workspace_root).join("checks.jsonl")
482}
483
484/// Append/read handle for a workspace's check ledger.
485#[derive(Debug, Clone)]
486pub struct CheckLedger {
487    path: PathBuf,
488}
489
490impl CheckLedger {
491    pub fn for_workspace(workspace_root: &Path) -> Self {
492        Self {
493            path: check_ledger_path(workspace_root),
494        }
495    }
496
497    /// Append one record. One `write` syscall of one complete line on
498    /// an `O_APPEND` handle — concurrent writers interleave whole
499    /// lines, never tear them. Errors propagate: a check that did not
500    /// persist must refuse at the surface.
501    pub fn record(&self, rec: &CheckRecord) -> std::io::Result<()> {
502        if let Some(dir) = self.path.parent() {
503            std::fs::create_dir_all(dir)?;
504        }
505        let mut line = serde_json::to_string(rec).map_err(std::io::Error::other)?;
506        line.push('\n');
507        let mut f = std::fs::OpenOptions::new()
508            .create(true)
509            .append(true)
510            .open(&self.path)?;
511        f.write_all(line.as_bytes())
512    }
513
514    /// Carry every record of `old` across a rename to `new`: each line
515    /// keyed by the old id is appended again under the new id with
516    /// `renamed_from` set, in ledger order, as one write of whole lines.
517    /// The originals stay — the ledger is append-only and they remain the
518    /// record of what was checked under that id. Returns the number of
519    /// lines carried; zero (and no write) when the old id has none.
520    pub fn carry_rename(&self, old: &str, new: &str) -> std::io::Result<usize> {
521        let carried: Vec<CheckRecord> = self
522            .all()
523            .into_iter()
524            .filter(|r| r.entity == old)
525            .map(|mut r| {
526                r.entity = new.to_string();
527                r.renamed_from = Some(old.to_string());
528                r
529            })
530            .collect();
531        if carried.is_empty() {
532            return Ok(0);
533        }
534        let mut lines = String::new();
535        for rec in &carried {
536            lines.push_str(&serde_json::to_string(rec).map_err(std::io::Error::other)?);
537            lines.push('\n');
538        }
539        let mut f = std::fs::OpenOptions::new()
540            .create(true)
541            .append(true)
542            .open(&self.path)?;
543        f.write_all(lines.as_bytes())?;
544        Ok(carried.len())
545    }
546
547    /// Carry the record that licensed a status transition across the
548    /// write it licensed: the newest record of `entity` under the wire
549    /// `kind` is appended again with `post_hash` as its `entity_hash` and
550    /// `carried_from: {hash: pre_hash, reason: "transition"}`, if and
551    /// only if it is fresh at `pre_hash` and confirming (`ok`). A stale
552    /// or failed record is not carried (it did not license anything),
553    /// and equal hashes carry nothing. Every other field stays the
554    /// original act's, identity included. Returns whether a line was
555    /// appended.
556    pub fn carry_transition(
557        &self,
558        entity: &str,
559        kind: &str,
560        pre_hash: &str,
561        post_hash: &str,
562    ) -> std::io::Result<bool> {
563        if pre_hash == post_hash {
564            return Ok(false);
565        }
566        let Some(latest) = self.latest_for_wire_kind(entity, kind) else {
567            return Ok(false);
568        };
569        if latest.entity_hash != pre_hash || latest.verdict != Verdict::Ok.as_str() {
570            return Ok(false);
571        }
572        let carried = CheckRecord {
573            entity_hash: post_hash.to_string(),
574            carried_from: Some(CarriedFrom::transition(pre_hash)),
575            ..latest
576        };
577        self.record(&carried)?;
578        Ok(true)
579    }
580
581    /// The records of one mem's entities, oldest first: every record
582    /// whose entity id is qualified by `mem`.
583    pub fn records_for_mem(&self, mem: &str) -> Vec<CheckRecord> {
584        let prefix = format!("{mem}--");
585        self.all()
586            .into_iter()
587            .filter(|r| r.entity.starts_with(&prefix))
588            .collect()
589    }
590
591    /// The transport form of a set of records: one JSON line per
592    /// record, ordered by timestamp then by the line's bytes, exact
593    /// duplicates dropped, a trailing newline. The same records give
594    /// the same bytes on every machine, so a publish that changed
595    /// nothing writes nothing.
596    pub fn transport_lines(records: &[CheckRecord]) -> Vec<u8> {
597        let mut lines: Vec<(u64, String)> = records
598            .iter()
599            .filter_map(|r| serde_json::to_string(r).ok().map(|s| (r.ts, s)))
600            .collect();
601        lines.sort();
602        lines.dedup();
603        let mut out = Vec::new();
604        for (_, line) in lines {
605            out.extend_from_slice(line.as_bytes());
606            out.push(b'\n');
607        }
608        out
609    }
610
611    /// Union `lines` (the transport form, from another machine) into
612    /// this ledger: every record not already present is appended, in
613    /// the order the lines carry; a record already present (the same
614    /// bytes) is skipped, so a round trip adds nothing. Unparseable
615    /// lines are skipped. Returns the number of records appended.
616    /// Rows keep every field they arrived with: identity, role, hash,
617    /// timestamp; nothing is rewritten on import.
618    pub fn merge_transport_lines(&self, lines: &[u8]) -> std::io::Result<usize> {
619        let present: std::collections::HashSet<String> = self
620            .all()
621            .iter()
622            .filter_map(|r| serde_json::to_string(r).ok())
623            .collect();
624        let mut appended = 0;
625        for line in String::from_utf8_lossy(lines).lines() {
626            let Ok(rec) = serde_json::from_str::<CheckRecord>(line) else {
627                continue;
628            };
629            let Ok(canonical) = serde_json::to_string(&rec) else {
630                continue;
631            };
632            if present.contains(&canonical) {
633                continue;
634            }
635            self.record(&rec)?;
636            appended += 1;
637        }
638        Ok(appended)
639    }
640
641    /// All records, oldest first. A missing ledger is an empty one;
642    /// unparseable lines are skipped (a torn tail must not poison the
643    /// readable history).
644    pub fn all(&self) -> Vec<CheckRecord> {
645        let Ok(content) = std::fs::read_to_string(&self.path) else {
646            return Vec::new();
647        };
648        content
649            .lines()
650            .filter_map(|l| serde_json::from_str(l).ok())
651            .collect()
652    }
653
654    /// The newest record for one entity, of any kind. State
655    /// derivation is per (entity, kind) — use [`Self::latest_for_kind`]
656    /// there; this remains the "what happened last" accessor.
657    pub fn latest_for(&self, entity: &str) -> Option<CheckRecord> {
658        self.all().into_iter().rev().find(|r| r.entity == entity)
659    }
660
661    /// The newest record for one entity of one kind. A later check of
662    /// the OTHER kind never supersedes it: the two derivations answer
663    /// different questions.
664    pub fn latest_for_kind(&self, entity: &str, kind: CheckKind) -> Option<CheckRecord> {
665        self.all()
666            .into_iter()
667            .rev()
668            .find(|r| r.entity == entity && r.resolved_kind() == Some(kind))
669    }
670
671    /// The newest record for one entity of one WIRE kind: an engine
672    /// kind resolves as [`Self::latest_for_kind`] (legacy kind-less
673    /// lines read as `verification`); a foreign `x-<name>` kind matches
674    /// the recorded kind verbatim. The lookup a `transition_requires_self_check`
675    /// gate declares its kind against.
676    pub fn latest_for_wire_kind(&self, entity: &str, kind: &str) -> Option<CheckRecord> {
677        match CheckKind::from_wire(kind) {
678            Some(k) => self.latest_for_kind(entity, k),
679            None => self
680                .all()
681                .into_iter()
682                .rev()
683                .find(|r| r.entity == entity && r.kind.as_deref() == Some(kind)),
684        }
685    }
686}
687
688// ---------------------------------------------------------------------------
689// Sealed check records: the archive member
690// ---------------------------------------------------------------------------
691
692/// Version of the sealed check-records member
693/// (`.memstead/checks.json`, [`memstead_schema::ARCHIVE_CHECKS_PATH`]).
694/// Read back by the archive mount; a reader tells "absent" from
695/// "not carried" by this line inside the member, so the published
696/// archive format number never moves for it.
697pub const SEALED_CHECKS_VERSION: u32 = 1;
698
699/// One sealed check record: the fields of the ledger line the archive
700/// carries, nothing invented. `kind` is the map key it sits under, the
701/// entity is the map key above that (its mem-relative path, so the
702/// member survives a remount under another mem name). The transport
703/// client and the structured finding stay in the workspace ledger: the
704/// archive answers state, and state derives from these fields alone.
705#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
706pub struct SealedCheck {
707    /// Unix epoch seconds at record time.
708    pub ts: u64,
709    /// When the check was made, as the caller stated it (see
710    /// [`CheckRecord::observed_at`]); absent when nobody did.
711    #[serde(default, skip_serializing_if = "Option::is_none")]
712    pub observed_at: Option<u64>,
713    /// `ok` | `failed`.
714    pub verdict: String,
715    /// The free-text method note, after the export's private-pattern
716    /// redaction (the same classes the provenance member applies).
717    #[serde(default, skip_serializing_if = "Option::is_none")]
718    pub method: Option<String>,
719    /// The entity's `content_hash` at check time: the freshness
720    /// baseline the mount compares against the sealed entity.
721    pub entity_hash: String,
722    /// Recorded actor category (`cli`, `agent`, ...).
723    pub actor: String,
724    /// The declared role, or `unspecified`.
725    pub role: String,
726    /// The declared identity, verbatim: a handle, never a person.
727    #[serde(default, skip_serializing_if = "Option::is_none")]
728    pub identity: Option<String>,
729    /// The schema pin a `conformance` record was judged against.
730    #[serde(default, skip_serializing_if = "Option::is_none")]
731    pub schema_ref: Option<String>,
732    /// The id the check was recorded under before a rename carried it.
733    #[serde(default, skip_serializing_if = "Option::is_none")]
734    pub renamed_from: Option<String>,
735    /// The hash the record was keyed to before the engine carried it,
736    /// and why (a licensed transition on the source mem, or the export's
737    /// own rewrite of the entity bytes).
738    #[serde(default, skip_serializing_if = "Option::is_none")]
739    pub carried_from: Option<CarriedFrom>,
740    /// The author≠checker independence reading
741    /// ([`crate::engine::independence::Independence`], wire form:
742    /// `confirmed_independent`, `self_checked`, `unconfirmable`) the
743    /// export derived for this record from the mem's provenance at
744    /// export time. The archive records no history at the engine seam,
745    /// so the reading cannot be re-derived on the mount; sealed here it
746    /// is the fact an immutable archive carries. Absent from a member an
747    /// older writer sealed: the mount then reads `unconfirmable`.
748    #[serde(default, skip_serializing_if = "Option::is_none")]
749    pub independence: Option<String>,
750    /// The trust class of the TEXT this row carries — its `method` note and
751    /// its finding message ([`crate::render::OriginClass`], wire form
752    /// `first-party` / `third-party`), as the exporting workspace
753    /// classified it ([`crate::Engine::check_row_origin_class`]).
754    ///
755    /// A check row's prose is written by whatever agent recorded the check,
756    /// which in a workspace that points a foreign model or a transcribed
757    /// outside finding at its ledger is not the workspace itself. Sealed
758    /// here for the same reason `independence` is: the mount records no
759    /// identity roster, so the reading cannot be re-derived on it.
760    ///
761    /// Absent when the exporting deployment declared no owner identities
762    /// (the row then inherits its mem's class, which is what every reader
763    /// did before this field) and on every member an older writer sealed.
764    #[serde(default, skip_serializing_if = "Option::is_none")]
765    pub origin: Option<String>,
766}
767
768impl SealedCheck {
769    /// The archive form of a ledger line, with no independence reading
770    /// yet (the export derives and sets it; see
771    /// [`crate::ops::export::build_redacted_sealed_checks`]).
772    pub fn from_record(rec: &CheckRecord) -> Self {
773        Self {
774            ts: rec.ts,
775            observed_at: rec.observed_at,
776            verdict: rec.verdict.clone(),
777            method: rec.method.clone(),
778            entity_hash: rec.entity_hash.clone(),
779            actor: rec.actor.clone(),
780            role: rec.role.clone(),
781            identity: rec.identity.clone(),
782            schema_ref: rec.schema_ref.clone(),
783            renamed_from: rec.renamed_from.clone(),
784            carried_from: rec.carried_from.clone(),
785            independence: None,
786            origin: None,
787        }
788    }
789
790    /// The sealed independence reading, parsed; `None` when the member
791    /// carries none (an older writer) or a value outside the vocabulary.
792    pub fn sealed_independence(&self) -> Option<crate::engine::independence::Independence> {
793        self.independence
794            .as_deref()
795            .and_then(crate::engine::independence::Independence::from_wire)
796    }
797
798    /// The sealed trust class of the row's prose, parsed; `None` when the
799    /// member seals none, which is every member an older writer sealed and
800    /// every export from a deployment that declared no owner identities.
801    /// The reader falls back to the mem's class then, as it did before the
802    /// field existed.
803    ///
804    /// This is the one reader that makes the sealed field load-bearing, and
805    /// it matters exactly where the mem grain cannot answer: a deployment
806    /// that vouches for an installed archive as first-party
807    /// ([`crate::Engine::declare_mem_origin`]) still must not serve a row
808    /// the publisher's own foreign checker wrote as its own prose.
809    pub fn sealed_origin(&self) -> Option<crate::render::OriginClass> {
810        match self.origin.as_deref()? {
811            "first-party" => Some(crate::render::OriginClass::FirstParty),
812            "third-party" => Some(crate::render::OriginClass::ThirdParty),
813            _ => None,
814        }
815    }
816
817    /// The ledger form under `entity_id` and the wire `kind` the record
818    /// sits under, so every derivation ([`derive_state`],
819    /// [`derive_state_pinned`]) and every surface that renders a
820    /// [`CheckRecord`] reads a sealed record the way it reads a ledger
821    /// line. A `verification` kind stays omitted, as the ledger writes it.
822    pub fn to_record(&self, entity_id: &str, kind: &str) -> CheckRecord {
823        CheckRecord {
824            ts: self.ts,
825            observed_at: self.observed_at,
826            entity: entity_id.to_string(),
827            verdict: self.verdict.clone(),
828            method: self.method.clone(),
829            entity_hash: self.entity_hash.clone(),
830            actor: self.actor.clone(),
831            client: None,
832            role: self.role.clone(),
833            identity: self.identity.clone(),
834            kind: (kind != CheckKind::Verification.as_str()).then(|| kind.to_string()),
835            schema_ref: self.schema_ref.clone(),
836            finding: None,
837            renamed_from: self.renamed_from.clone(),
838            carried_from: self.carried_from.clone(),
839        }
840    }
841}
842
843/// The sealed check-records member: per entity (keyed by mem-relative
844/// path) the latest record per kind (keyed by wire kind:
845/// `verification`, `conformance`, or a foreign `x-<name>`).
846#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
847pub struct SealedChecks {
848    pub version: u32,
849    #[serde(default)]
850    pub entities: BTreeMap<String, BTreeMap<String, SealedCheck>>,
851}
852
853impl SealedChecks {
854    /// An empty member of the current version.
855    pub fn new() -> Self {
856        Self {
857            version: SEALED_CHECKS_VERSION,
858            entities: BTreeMap::new(),
859        }
860    }
861
862    /// The latest sealed record of one entity (by mem-relative path)
863    /// under one wire kind.
864    pub fn latest(&self, entity_path: &str, kind: &str) -> Option<&SealedCheck> {
865        self.entities
866            .get(entity_path)
867            .and_then(|kinds| kinds.get(kind))
868    }
869
870    /// Every sealed kind of one entity, in key order.
871    pub fn kinds_of(&self, entity_path: &str) -> impl Iterator<Item = (&str, &SealedCheck)> {
872        self.entities
873            .get(entity_path)
874            .into_iter()
875            .flat_map(|kinds| kinds.iter().map(|(k, v)| (k.as_str(), v)))
876    }
877
878    /// Re-key every record of one entity that is fresh at `pre_hash` to
879    /// `post_hash`, marking it `carried_from: {hash: pre_hash, reason:
880    /// "export"}`: the export rewrote the entity's bytes (links retargeted
881    /// to the archive name, the canonical re-render), and a record that
882    /// was fresh against the source content stays fresh against the
883    /// archived content. A record keyed to any other hash was stale
884    /// before the export and keeps its hash, so it still reads stale on
885    /// the mount. Equal hashes change nothing; every other field, the
886    /// sealed independence reading included, stays as sealed. Returns the
887    /// number of records moved.
888    pub fn rekey_entity(&mut self, entity_path: &str, pre_hash: &str, post_hash: &str) -> usize {
889        if pre_hash == post_hash {
890            return 0;
891        }
892        let Some(kinds) = self.entities.get_mut(entity_path) else {
893            return 0;
894        };
895        let mut moved = 0;
896        for rec in kinds.values_mut() {
897            if rec.entity_hash == pre_hash {
898                rec.entity_hash = post_hash.to_string();
899                rec.carried_from = Some(CarriedFrom::export(pre_hash));
900                moved += 1;
901            }
902        }
903        moved
904    }
905
906    /// Serialise to the canonical member bytes (pretty JSON, trailing
907    /// newline), deterministic for a given content: both maps are
908    /// ordered.
909    pub fn to_archive_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
910        let mut s = serde_json::to_string_pretty(self)?;
911        s.push('\n');
912        Ok(s.into_bytes())
913    }
914
915    /// Parse the member bytes. Shape only; [`Self::validate`] checks the
916    /// vocabulary and the entity roster.
917    pub fn from_archive_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
918        serde_json::from_slice(bytes)
919    }
920
921    /// The validator's shape check: the version this engine reads, every
922    /// kind in the vocabulary, every verdict in the vocabulary, a
923    /// non-empty hash, actor and role, and every entity path one the
924    /// archive carries (`carried` is the set of mem-relative entity
925    /// paths). The error names the first offending record.
926    pub fn validate(&self, carried: &std::collections::BTreeSet<String>) -> Result<(), String> {
927        if self.version != SEALED_CHECKS_VERSION {
928            return Err(format!(
929                "version {} is not the version this engine reads ({SEALED_CHECKS_VERSION})",
930                self.version
931            ));
932        }
933        for (path, kinds) in &self.entities {
934            if !carried.contains(path) {
935                return Err(format!(
936                    "entity `{path}` names no entity the archive carries"
937                ));
938            }
939            for (kind, rec) in kinds {
940                let at = format!("entity `{path}`, kind `{kind}`");
941                if RecordKind::from_wire(kind).is_none() {
942                    return Err(format!(
943                        "{at}: the kind is not one of {}",
944                        RecordKind::vocabulary_hint()
945                    ));
946                }
947                if Verdict::from_wire(&rec.verdict).is_none() {
948                    return Err(format!(
949                        "{at}: verdict `{}` is not one of {}",
950                        rec.verdict,
951                        VERDICTS.join(", ")
952                    ));
953                }
954                if rec.entity_hash.trim().is_empty() {
955                    return Err(format!("{at}: entity_hash is empty"));
956                }
957                if rec.actor.trim().is_empty() {
958                    return Err(format!("{at}: actor is empty"));
959                }
960                if rec.role.trim().is_empty() {
961                    return Err(format!("{at}: role is empty"));
962                }
963                if let Some(reading) = rec.independence.as_deref()
964                    && crate::engine::independence::Independence::from_wire(reading).is_none()
965                {
966                    return Err(format!(
967                        "{at}: independence `{reading}` is not one of {}",
968                        crate::engine::independence::Independence::vocabulary_hint()
969                    ));
970                }
971                // The trust class is publisher-supplied bytes on an
972                // installed archive, so the vocabulary is closed here as
973                // the independence reading's is: an unknown token is
974                // refused with a typed error rather than parsed into
975                // something a reader would treat as a class.
976                if let Some(origin) = rec.origin.as_deref()
977                    && rec.sealed_origin().is_none()
978                {
979                    return Err(format!(
980                        "{at}: origin `{origin}` is not one of first-party | third-party"
981                    ));
982                }
983            }
984        }
985        Ok(())
986    }
987}
988
989impl Default for SealedChecks {
990    fn default() -> Self {
991        Self::new()
992    }
993}
994
995/// The wire kind a ledger line sits under in the sealed member: an
996/// engine kind by its resolved name (a legacy kind-less line is
997/// `verification`), a foreign kind verbatim.
998pub fn sealed_kind_of(rec: &CheckRecord) -> String {
999    match rec.resolved_kind() {
1000        Some(k) => k.as_str().to_string(),
1001        None => rec.kind.clone().unwrap_or_default(),
1002    }
1003}
1004
1005#[cfg(test)]
1006mod tests {
1007    use super::*;
1008    use tempfile::TempDir;
1009
1010    fn rec(entity: &str, verdict: &str, hash: &str) -> CheckRecord {
1011        CheckRecord {
1012            ts: 1,
1013            observed_at: None,
1014            entity: entity.to_string(),
1015            verdict: verdict.to_string(),
1016            method: None,
1017            entity_hash: hash.to_string(),
1018            actor: "cli".to_string(),
1019            client: None,
1020            role: "checker".to_string(),
1021            identity: None,
1022            kind: None,
1023            schema_ref: None,
1024            finding: None,
1025            renamed_from: None,
1026            carried_from: None,
1027        }
1028    }
1029
1030    #[test]
1031    fn state_derivation_covers_all_four_states() {
1032        assert_eq!(derive_state(None, "h1"), CheckState::NeverChecked);
1033        let ok = rec("m--e", "ok", "h1");
1034        assert_eq!(derive_state(Some(&ok), "h1"), CheckState::CheckedOk);
1035        assert_eq!(derive_state(Some(&ok), "h2"), CheckState::CheckStale);
1036        let failed = rec("m--e", "failed", "h1");
1037        assert_eq!(derive_state(Some(&failed), "h1"), CheckState::CheckFailed);
1038        // A failed check on changed content is stale too — the verdict
1039        // no longer speaks to current content either way.
1040        assert_eq!(derive_state(Some(&failed), "h2"), CheckState::CheckStale);
1041    }
1042
1043    #[test]
1044    fn ledger_appends_and_serves_newest_per_entity() {
1045        let tmp = TempDir::new().unwrap();
1046        let ledger = CheckLedger::for_workspace(tmp.path());
1047        assert!(ledger.latest_for("m--a").is_none());
1048        ledger.record(&rec("m--a", "failed", "h1")).unwrap();
1049        ledger.record(&rec("m--b", "ok", "h9")).unwrap();
1050        ledger.record(&rec("m--a", "ok", "h2")).unwrap();
1051        let latest = ledger.latest_for("m--a").unwrap();
1052        assert_eq!(latest.verdict, "ok");
1053        assert_eq!(latest.entity_hash, "h2");
1054        // Supersession never erases: all three records remain.
1055        assert_eq!(ledger.all().len(), 3);
1056    }
1057
1058    /// A rename carries the old id's lines under the new id, marked
1059    /// with their origin, and leaves the originals in place. The carried
1060    /// line keeps the hash the check was made against, so it derives
1061    /// `check_stale` against the renamed file's new hash — never a
1062    /// silently fresh `checked_ok`, never `never_checked`.
1063    /// `observed_at` is the caller's statement of when the check was
1064    /// made: parsed from the two ISO shapes, refused when unreadable or
1065    /// ahead of the clock beyond the skew allowance, kept verbatim by
1066    /// the rename carry (every carried field is the original act's) and
1067    /// by the sealed form's round trip, and absent from a line that
1068    /// never carried it, byte for byte.
1069    #[test]
1070    fn observed_at_parses_refuses_the_future_and_survives_the_carries() {
1071        let now = 1_792_503_930; // 2026-10-20T13:45:30Z
1072        assert_eq!(parse_observed_at("2026-10-19", now), Ok(1_792_368_000));
1073        assert_eq!(parse_observed_at(" 2026-10-20T13:45:30Z ", now), Ok(now));
1074        // Inside the skew allowance: accepted. Beyond it: refused.
1075        assert!(parse_observed_at("2026-10-20T13:50:00Z", now).is_ok());
1076        let err = parse_observed_at("2026-10-20T13:51:00Z", now).unwrap_err();
1077        assert!(err.contains("future"), "{err}");
1078        let err = parse_observed_at("20.10.2026", now).unwrap_err();
1079        assert!(err.contains("ISO-8601"), "{err}");
1080
1081        let tmp = TempDir::new().unwrap();
1082        let ledger = CheckLedger::for_workspace(tmp.path());
1083        let mut dated = rec("m--old", "ok", "h1");
1084        dated.observed_at = Some(1_792_368_000);
1085        ledger.record(&dated).unwrap();
1086        ledger.record(&rec("m--old", "ok", "h2")).unwrap();
1087        assert_eq!(ledger.carry_rename("m--old", "m--new").unwrap(), 2);
1088        let carried: Vec<CheckRecord> = ledger
1089            .all()
1090            .into_iter()
1091            .filter(|r| r.entity == "m--new")
1092            .collect();
1093        assert_eq!(carried[0].observed_at, Some(1_792_368_000));
1094        assert_eq!(carried[1].observed_at, None);
1095
1096        let sealed = SealedCheck::from_record(&dated);
1097        assert_eq!(sealed.observed_at, Some(1_792_368_000));
1098        assert_eq!(
1099            sealed.to_record("m--old", "verification").observed_at,
1100            Some(1_792_368_000)
1101        );
1102
1103        let raw = std::fs::read_to_string(check_ledger_path(tmp.path())).unwrap();
1104        let lines: Vec<&str> = raw.lines().collect();
1105        assert!(
1106            lines[0].contains("\"observed_at\":1792368000"),
1107            "{}",
1108            lines[0]
1109        );
1110        assert!(!lines[1].contains("observed_at"), "{}", lines[1]);
1111    }
1112
1113    #[test]
1114    fn carry_rename_rekeys_without_erasing() {
1115        let tmp = TempDir::new().unwrap();
1116        let ledger = CheckLedger::for_workspace(tmp.path());
1117        ledger.record(&rec("m--old", "ok", "h1")).unwrap();
1118        ledger.record(&rec("m--other", "ok", "h9")).unwrap();
1119        let mut conf = rec("m--old", "failed", "h1");
1120        conf.kind = Some("conformance".into());
1121        ledger.record(&conf).unwrap();
1122
1123        assert_eq!(ledger.carry_rename("m--old", "m--new").unwrap(), 2);
1124        assert_eq!(ledger.carry_rename("m--absent", "m--new").unwrap(), 0);
1125
1126        let all = ledger.all();
1127        assert_eq!(all.len(), 5);
1128        assert!(all.iter().filter(|r| r.entity == "m--old").count() == 2);
1129        let carried: Vec<&CheckRecord> = all.iter().filter(|r| r.entity == "m--new").collect();
1130        assert_eq!(carried.len(), 2);
1131        assert!(
1132            carried
1133                .iter()
1134                .all(|r| r.renamed_from.as_deref() == Some("m--old"))
1135        );
1136        let latest = ledger
1137            .latest_for_kind("m--new", CheckKind::Verification)
1138            .unwrap();
1139        assert_eq!(latest.verdict, "ok");
1140        assert_eq!(derive_state(Some(&latest), "h1"), CheckState::CheckedOk);
1141        assert_eq!(
1142            derive_state(Some(&latest), "h2-after-rename"),
1143            CheckState::CheckStale
1144        );
1145        assert_eq!(
1146            ledger
1147                .latest_for_kind("m--new", CheckKind::Conformance)
1148                .unwrap()
1149                .verdict,
1150            "failed"
1151        );
1152        // A checker's own line never carries the marker.
1153        assert!(
1154            ledger
1155                .latest_for("m--other")
1156                .unwrap()
1157                .renamed_from
1158                .is_none()
1159        );
1160    }
1161
1162    /// A transition carry re-keys the licensing record to the post-write
1163    /// hash and marks its origin; a record that is stale at the pre-write
1164    /// hash, a failed one, or an unchanged hash carries nothing. The
1165    /// carried line keeps the checker's identity, so independence still
1166    /// reads it as the checker's, not the writer's.
1167    #[test]
1168    fn carry_transition_moves_only_the_fresh_confirming_record() {
1169        let tmp = TempDir::new().unwrap();
1170        let ledger = CheckLedger::for_workspace(tmp.path());
1171        let mut ok = rec("m--plan", "ok", "h1");
1172        ok.kind = Some("x-projection".into());
1173        ok.identity = Some("checker-c".into());
1174        ledger.record(&ok).unwrap();
1175
1176        assert!(
1177            !ledger
1178                .carry_transition("m--plan", "x-projection", "h1", "h1")
1179                .unwrap()
1180        );
1181        assert!(
1182            !ledger
1183                .carry_transition("m--plan", "x-projection", "h0", "h2")
1184                .unwrap()
1185        );
1186        assert!(
1187            !ledger
1188                .carry_transition("m--plan", "verification", "h1", "h2")
1189                .unwrap()
1190        );
1191        assert_eq!(ledger.all().len(), 1, "nothing appended so far");
1192
1193        assert!(
1194            ledger
1195                .carry_transition("m--plan", "x-projection", "h1", "h2")
1196                .unwrap()
1197        );
1198        let all = ledger.all();
1199        assert_eq!(all.len(), 2, "append-only: the original stays");
1200        let carried = ledger
1201            .latest_for_wire_kind("m--plan", "x-projection")
1202            .unwrap();
1203        assert_eq!(carried.entity_hash, "h2");
1204        assert_eq!(carried.identity.as_deref(), Some("checker-c"));
1205        assert_eq!(carried.verdict, "ok");
1206        assert_eq!(
1207            carried.carried_from,
1208            Some(CarriedFrom {
1209                hash: "h1".into(),
1210                reason: CARRY_REASON_TRANSITION.into()
1211            })
1212        );
1213        assert_eq!(derive_state(Some(&carried), "h2"), CheckState::CheckedOk);
1214        // A second transition carries the carried line onward, one step.
1215        assert!(
1216            ledger
1217                .carry_transition("m--plan", "x-projection", "h2", "h3")
1218                .unwrap()
1219        );
1220        let again = ledger
1221            .latest_for_wire_kind("m--plan", "x-projection")
1222            .unwrap();
1223        assert_eq!(again.carried_from.as_ref().unwrap().hash, "h2");
1224
1225        // A failed record licenses nothing and is never carried.
1226        let mut failed = rec("m--other", "failed", "h1");
1227        failed.kind = Some("x-projection".into());
1228        ledger.record(&failed).unwrap();
1229        assert!(
1230            !ledger
1231                .carry_transition("m--other", "x-projection", "h1", "h2")
1232                .unwrap()
1233        );
1234        // A checker's own line never carries the marker.
1235        assert!(all[0].carried_from.is_none());
1236    }
1237
1238    /// The sealed member re-keys a record fresh at the pre-rewrite hash
1239    /// to the archived hash and marks it; a stale record keeps its hash.
1240    #[test]
1241    fn sealed_rekey_moves_fresh_records_and_leaves_stale_ones() {
1242        let mut sealed = SealedChecks::new();
1243        let fresh = SealedCheck::from_record(&rec("m--a", "ok", "h1"));
1244        let mut stale = SealedCheck::from_record(&rec("m--a", "ok", "h0"));
1245        stale.ts = 0;
1246        sealed.entities.insert(
1247            "a".into(),
1248            BTreeMap::from([
1249                ("verification".to_string(), fresh),
1250                ("x-audit".to_string(), stale),
1251            ]),
1252        );
1253        assert_eq!(sealed.rekey_entity("a", "h1", "h1"), 0);
1254        assert_eq!(sealed.rekey_entity("absent", "h1", "h2"), 0);
1255        assert_eq!(sealed.rekey_entity("a", "h1", "h2"), 1);
1256        let v = sealed.latest("a", "verification").unwrap();
1257        assert_eq!(v.entity_hash, "h2");
1258        assert_eq!(v.carried_from.as_ref().unwrap().reason, CARRY_REASON_EXPORT);
1259        assert_eq!(v.carried_from.as_ref().unwrap().hash, "h1");
1260        let x = sealed.latest("a", "x-audit").unwrap();
1261        assert_eq!(x.entity_hash, "h0", "stale stays stale");
1262        assert!(x.carried_from.is_none());
1263        // The round trip through the ledger form keeps the marker.
1264        let back = v.to_record("m--a", "verification");
1265        assert_eq!(back.carried_from, v.carried_from);
1266        assert_eq!(SealedCheck::from_record(&back), *v);
1267        // A pre-marker member line still parses, and reads no independence.
1268        let legacy = r#"{"ts":1,"verdict":"ok","entity_hash":"h","actor":"cli","role":"checker"}"#;
1269        let parsed: SealedCheck = serde_json::from_str(legacy).unwrap();
1270        assert!(parsed.carried_from.is_none());
1271        assert!(parsed.independence.is_none());
1272        assert!(parsed.sealed_independence().is_none());
1273    }
1274
1275    /// The sealed trust class of a row's prose parses only from the two
1276    /// origin tokens and fails the validator outside them. The bytes come
1277    /// from a publisher's archive, so the vocabulary is closed here exactly
1278    /// as the independence reading's is: a member claiming `first-party` in
1279    /// a spelling no reader recognises must be refused with a typed error,
1280    /// not parsed into something a reader treats as a class.
1281    #[test]
1282    fn sealed_row_origin_parses_only_from_the_closed_vocabulary() {
1283        let mut sealed = SealedChecks::new();
1284        let mut row = SealedCheck::from_record(&rec("m--a", "ok", "h1"));
1285        row.origin = Some("third-party".to_string());
1286        sealed.entities.insert(
1287            "a".into(),
1288            BTreeMap::from([("verification".to_string(), row)]),
1289        );
1290        assert_eq!(
1291            sealed.latest("a", "verification").unwrap().sealed_origin(),
1292            Some(crate::render::OriginClass::ThirdParty)
1293        );
1294        let carried: std::collections::BTreeSet<String> = ["a".to_string()].into();
1295        assert!(sealed.validate(&carried).is_ok());
1296
1297        // A member an older writer sealed carries none and reads none.
1298        let legacy = r#"{"ts":1,"verdict":"ok","entity_hash":"h","actor":"cli","role":"checker"}"#;
1299        let parsed: SealedCheck = serde_json::from_str(legacy).unwrap();
1300        assert!(parsed.origin.is_none());
1301        assert!(parsed.sealed_origin().is_none());
1302
1303        // A token outside the vocabulary is refused, and reads as no class
1304        // rather than as a guess.
1305        sealed
1306            .entities
1307            .get_mut("a")
1308            .unwrap()
1309            .get_mut("verification")
1310            .unwrap()
1311            .origin = Some("trusted".into());
1312        assert!(
1313            sealed
1314                .latest("a", "verification")
1315                .unwrap()
1316                .sealed_origin()
1317                .is_none()
1318        );
1319        let err = sealed.validate(&carried).unwrap_err();
1320        assert!(err.contains("origin `trusted`"), "{err}");
1321    }
1322
1323    /// The sealed independence reading survives the export re-key, is
1324    /// dropped from the ledger form (the ledger derives, never stores
1325    /// it), parses only from the vocabulary, and fails the validator
1326    /// outside it.
1327    #[test]
1328    fn sealed_independence_is_kept_by_rekey_and_closed_in_vocabulary() {
1329        use crate::engine::independence::Independence;
1330        let mut sealed = SealedChecks::new();
1331        let mut fresh = SealedCheck::from_record(&rec("m--a", "ok", "h1"));
1332        fresh.independence = Some(Independence::ConfirmedIndependent.as_str().to_string());
1333        sealed.entities.insert(
1334            "a".into(),
1335            BTreeMap::from([("verification".to_string(), fresh)]),
1336        );
1337        assert_eq!(sealed.rekey_entity("a", "h1", "h2"), 1);
1338        let v = sealed.latest("a", "verification").unwrap();
1339        assert_eq!(
1340            v.sealed_independence(),
1341            Some(Independence::ConfirmedIndependent)
1342        );
1343        let bytes = sealed.to_archive_bytes().unwrap();
1344        let back = SealedChecks::from_archive_bytes(&bytes).unwrap();
1345        assert_eq!(back, sealed);
1346        assert!(v.to_record("m--a", "verification").carried_from.is_some());
1347        let carried: std::collections::BTreeSet<String> = ["a".to_string()].into();
1348        assert!(back.validate(&carried).is_ok());
1349
1350        let mut foreign = sealed.clone();
1351        foreign
1352            .entities
1353            .get_mut("a")
1354            .unwrap()
1355            .get_mut("verification")
1356            .unwrap()
1357            .independence = Some("trusted".into());
1358        assert!(
1359            foreign
1360                .latest("a", "verification")
1361                .unwrap()
1362                .sealed_independence()
1363                .is_none()
1364        );
1365        let err = foreign.validate(&carried).unwrap_err();
1366        assert!(err.contains("independence `trusted`"), "{err}");
1367    }
1368
1369    #[test]
1370    fn verdict_vocabulary_is_closed() {
1371        assert!(Verdict::from_wire("ok").is_some());
1372        assert!(Verdict::from_wire("failed").is_some());
1373        assert!(Verdict::from_wire("passed").is_none());
1374        assert!(Verdict::from_wire("OK").is_none());
1375    }
1376
1377    fn conf(entity: &str, verdict: &str, hash: &str, pin: &str) -> CheckRecord {
1378        CheckRecord {
1379            kind: Some("conformance".to_string()),
1380            schema_ref: Some(pin.to_string()),
1381            ..rec(entity, verdict, hash)
1382        }
1383    }
1384
1385    #[test]
1386    fn kind_vocabulary_is_closed() {
1387        assert!(CheckKind::from_wire("verification").is_some());
1388        assert!(CheckKind::from_wire("conformance").is_some());
1389        assert!(CheckKind::from_wire("semantic").is_none());
1390        assert!(CheckKind::from_wire("Conformance").is_none());
1391    }
1392
1393    /// Criterion 5: a pre-kind ledger line (no `kind` field) parses
1394    /// and derives as a `verification` record, byte-for-byte the old
1395    /// shape on the write side too.
1396    #[test]
1397    fn legacy_lines_read_as_verification() {
1398        let legacy = r#"{"ts":1,"entity":"m--e","verdict":"ok","entity_hash":"h1","actor":"cli","role":"checker"}"#;
1399        let parsed: CheckRecord = serde_json::from_str(legacy).unwrap();
1400        assert_eq!(parsed.resolved_kind(), Some(CheckKind::Verification));
1401        // A freshly built verification record serialises with no kind
1402        // and no schema_ref key at all.
1403        let fresh = rec("m--e", "ok", "h1");
1404        let line = serde_json::to_string(&fresh).unwrap();
1405        assert!(!line.contains("kind"));
1406        assert!(!line.contains("schema_ref"));
1407        // An identity-less record carries no identity key either —
1408        // pre-plan-15 lines and identity-less callers stay
1409        // byte-identical.
1410        assert!(!line.contains("identity"));
1411    }
1412
1413    /// Criterion 3: state derives per (entity, kind) — a later check
1414    /// of the other kind does not supersede.
1415    #[test]
1416    fn latest_is_per_kind() {
1417        let tmp = TempDir::new().unwrap();
1418        let ledger = CheckLedger::for_workspace(tmp.path());
1419        ledger.record(&rec("m--a", "ok", "h1")).unwrap();
1420        ledger
1421            .record(&conf("m--a", "failed", "h1", "planning@1.0.0"))
1422            .unwrap();
1423        let v = ledger
1424            .latest_for_kind("m--a", CheckKind::Verification)
1425            .unwrap();
1426        assert_eq!(v.verdict, "ok");
1427        let c = ledger
1428            .latest_for_kind("m--a", CheckKind::Conformance)
1429            .unwrap();
1430        assert_eq!(c.verdict, "failed");
1431        assert_eq!(c.schema_ref.as_deref(), Some("planning@1.0.0"));
1432    }
1433
1434    /// Criterion 4: a conformance verdict is stale on a content move
1435    /// AND on a pin move; a verification verdict ignores pin moves.
1436    #[test]
1437    fn conformance_stales_on_pin_move_verification_does_not() {
1438        let c = conf("m--e", "ok", "h1", "planning@1.0.0");
1439        assert_eq!(
1440            derive_state_pinned(Some(&c), "h1", Some("planning@1.0.0")),
1441            CheckState::CheckedOk
1442        );
1443        assert_eq!(
1444            derive_state_pinned(Some(&c), "h2", Some("planning@1.0.0")),
1445            CheckState::CheckStale
1446        );
1447        assert_eq!(
1448            derive_state_pinned(Some(&c), "h1", Some("planning@2.0.0")),
1449            CheckState::CheckStale
1450        );
1451        // The mem losing its pin stales the verdict too.
1452        assert_eq!(
1453            derive_state_pinned(Some(&c), "h1", None),
1454            CheckState::CheckStale
1455        );
1456        // Verification: unaffected by any pin argument.
1457        let v = rec("m--e", "ok", "h1");
1458        assert_eq!(
1459            derive_state_pinned(Some(&v), "h1", Some("planning@9.0.0")),
1460            CheckState::CheckedOk
1461        );
1462        assert_eq!(derive_state(Some(&v), "h1"), CheckState::CheckedOk);
1463    }
1464
1465    // --- findings and open kinds ---
1466
1467    #[test]
1468    fn finding_shape_is_fixed_and_validated_whole() {
1469        let ok = CheckFinding::from_json(serde_json::json!({
1470            "code": "hidden-premise", "message": "The step assumes X.", "section": "step"
1471        }))
1472        .unwrap();
1473        assert_eq!(ok.code, "hidden-premise");
1474        assert_eq!(ok.section.as_deref(), Some("step"));
1475        for bad in [
1476            serde_json::json!({ "message": "no code" }),
1477            serde_json::json!({ "code": "x" }),
1478            serde_json::json!({ "code": "", "message": "empty code" }),
1479            serde_json::json!({ "code": "x", "message": "   " }),
1480            serde_json::json!({ "code": "x", "message": "m", "severity": "high" }),
1481            serde_json::json!({ "code": "x", "message": "m", "section": "" }),
1482        ] {
1483            let err = CheckFinding::from_json(bad.clone()).unwrap_err();
1484            assert!(err.contains("shape"), "{bad}: {err}");
1485        }
1486    }
1487
1488    #[test]
1489    fn open_kinds_parse_only_with_the_prefix_and_never_resolve_to_an_engine_kind() {
1490        assert_eq!(
1491            RecordKind::from_wire("verification"),
1492            Some(RecordKind::Engine(CheckKind::Verification))
1493        );
1494        assert_eq!(
1495            RecordKind::from_wire("x-step-walk"),
1496            Some(RecordKind::Foreign("x-step-walk".to_string()))
1497        );
1498        for bad in ["step-walk", "x-", "x-Step", "x--a", "x-a-", "X-a"] {
1499            assert!(RecordKind::from_wire(bad).is_none(), "{bad}");
1500        }
1501        assert!(RecordKind::vocabulary_hint().contains("x-<name>"));
1502        let mut r = rec("m--e", "ok", "h");
1503        r.kind = Some("x-step-walk".to_string());
1504        assert_eq!(r.resolved_kind(), None);
1505        assert_eq!(r.foreign_kind(), Some("x-step-walk"));
1506        r.kind = None;
1507        assert_eq!(r.resolved_kind(), Some(CheckKind::Verification));
1508        r.kind = Some("conformance".to_string());
1509        assert_eq!(r.resolved_kind(), Some(CheckKind::Conformance));
1510        // A pre-`x-` unrecognised kind keeps its legacy reading.
1511        r.kind = Some("mystery".to_string());
1512        assert_eq!(r.resolved_kind(), Some(CheckKind::Verification));
1513    }
1514
1515    #[test]
1516    fn pre_finding_ledger_lines_parse_and_derive_unchanged_and_findings_round_trip() {
1517        let tmp = TempDir::new().unwrap();
1518        let ledger = CheckLedger::for_workspace(tmp.path());
1519        let dir = check_ledger_path(tmp.path());
1520        std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
1521        // A line written before findings existed: no `finding`, no `kind`.
1522        std::fs::write(
1523            &dir,
1524            "{\"ts\":1,\"entity\":\"m--e\",\"verdict\":\"failed\",\"entity_hash\":\"h\",\"actor\":\"cli\",\"role\":\"unspecified\"}\n",
1525        )
1526        .unwrap();
1527        let old = ledger
1528            .latest_for_kind("m--e", CheckKind::Verification)
1529            .unwrap();
1530        assert!(old.finding.is_none());
1531        assert_eq!(derive_state(Some(&old), "h"), CheckState::CheckFailed);
1532
1533        let mut with = rec("m--e", "failed", "h");
1534        with.ts = 2;
1535        with.finding = Some(CheckFinding {
1536            code: "hidden-premise".into(),
1537            section: Some("step".into()),
1538            message: "The step assumes X.".into(),
1539            evidence: None,
1540        });
1541        ledger.record(&with).unwrap();
1542        // A foreign-kind line beside it moves no verification state.
1543        let mut foreign = rec("m--e", "ok", "h");
1544        foreign.ts = 3;
1545        foreign.kind = Some("x-step-walk".into());
1546        ledger.record(&foreign).unwrap();
1547        let latest = ledger
1548            .latest_for_kind("m--e", CheckKind::Verification)
1549            .unwrap();
1550        assert_eq!(
1551            latest.ts, 2,
1552            "the foreign record is not the latest verification record"
1553        );
1554        assert_eq!(latest.finding.as_ref().unwrap().code, "hidden-premise");
1555        assert_eq!(derive_state(Some(&latest), "h"), CheckState::CheckFailed);
1556        let text = std::fs::read_to_string(&dir).unwrap();
1557        assert!(text.contains("\"finding\":{\"code\":\"hidden-premise\",\"section\":\"step\",\"message\":\"The step assumes X.\"}"), "{text}");
1558        assert!(text.contains("\"kind\":\"x-step-walk\""));
1559        assert_eq!(text.lines().count(), 3, "append-only");
1560    }
1561}