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.
290    pub ts: u64,
291    /// Full entity id (`mem--slug`).
292    pub entity: String,
293    /// `ok` | `failed`.
294    pub verdict: String,
295    /// Optional free-text method note ("diffed against source spec",
296    /// "re-ran the derivation").
297    #[serde(default, skip_serializing_if = "Option::is_none")]
298    pub method: Option<String>,
299    /// The entity's `content_hash` at check time — the staleness
300    /// baseline.
301    pub entity_hash: String,
302    /// Recorded actor identity (plan-13 provenance).
303    pub actor: String,
304    /// Recorded client identity (`name@version`), when known.
305    #[serde(default, skip_serializing_if = "Option::is_none")]
306    pub client: Option<String>,
307    /// The caller-declared role, or `"unspecified"` — recorded
308    /// honestly; downstream gates treat unspecified as
309    /// cannot-confirm, never as any real role.
310    pub role: String,
311    /// The caller-declared identity: an opaque
312    /// caller-chosen string, the ONLY comparator the independence
313    /// gate uses. Absent on ledger lines written before identities
314    /// existed and on identity-less callers — both downgrade every
315    /// comparison to `unconfirmable`, never to a guessed category.
316    #[serde(default, skip_serializing_if = "Option::is_none")]
317    pub identity: Option<String>,
318    /// The check kind, from [`CHECK_KINDS`]. Absent on ledger lines
319    /// written before kinds existed AND on freshly recorded
320    /// `verification` checks — both read as `verification`, so an
321    /// existing ledger upgrades with no migration and a kind-omitted
322    /// caller's lines stay byte-identical to before.
323    #[serde(default, skip_serializing_if = "Option::is_none")]
324    pub kind: Option<String>,
325    /// For `conformance` records: the mem's schema pin
326    /// (`name@x.y.z`) as stamped by the engine at record time — never
327    /// caller-supplied, so a verdict cannot claim a prose version the
328    /// caller never read. Absent on `verification` records.
329    #[serde(default, skip_serializing_if = "Option::is_none")]
330    pub schema_ref: Option<String>,
331    /// The structured finding the checker attached, when one was.
332    /// Absent on every line written before findings existed and on
333    /// finding-less checks — serde-default, so every existing line
334    /// still parses and finding-less lines stay byte-identical.
335    #[serde(default, skip_serializing_if = "Option::is_none")]
336    pub finding: Option<CheckFinding>,
337    /// Set on a line the engine carried across a rename: the id the
338    /// check was recorded under before the entity took its current id.
339    /// Every other field is the original act's, hash included, so the
340    /// state derived under the new id stays honest — a rename rewrites
341    /// the file (title, self-links, timestamps), so the carried record
342    /// reads `check_stale` until someone checks the renamed entity; what
343    /// the carry prevents is the ledger losing the entity (`never_checked`
344    /// under the new id, an unreachable row under the old). Absent on
345    /// every line a checker wrote.
346    #[serde(default, skip_serializing_if = "Option::is_none")]
347    pub renamed_from: Option<String>,
348    /// Set on a line the engine carried to a new `entity_hash` (a
349    /// licensed transition, a sealed export): the hash it was keyed to
350    /// before and the reason. Absent on every line a checker wrote.
351    #[serde(default, skip_serializing_if = "Option::is_none")]
352    pub carried_from: Option<CarriedFrom>,
353}
354
355impl CheckRecord {
356    /// The record's ENGINE kind, legacy lines included: an absent or
357    /// unrecognised kind reads as `verification`, which is exactly what
358    /// every pre-kind line was; a foreign `x-<name>` kind is `None` —
359    /// recorded, listed, never aggregated into a state.
360    pub fn resolved_kind(&self) -> Option<CheckKind> {
361        match self.kind.as_deref() {
362            None => Some(CheckKind::Verification),
363            Some(k) if k.starts_with(FOREIGN_KIND_PREFIX) => None,
364            Some(k) => Some(CheckKind::from_wire(k).unwrap_or(CheckKind::Verification)),
365        }
366    }
367
368    /// The foreign kind, when the record carries one.
369    pub fn foreign_kind(&self) -> Option<&str> {
370        self.kind
371            .as_deref()
372            .filter(|k| k.starts_with(FOREIGN_KIND_PREFIX))
373    }
374}
375
376/// Derived per-entity check state.
377#[derive(Debug, Clone, Copy, PartialEq, Eq)]
378pub enum CheckState {
379    NeverChecked,
380    CheckedOk,
381    CheckFailed,
382    CheckStale,
383}
384
385impl CheckState {
386    pub fn as_str(self) -> &'static str {
387        match self {
388            Self::NeverChecked => "never_checked",
389            Self::CheckedOk => "checked_ok",
390            Self::CheckFailed => "check_failed",
391            Self::CheckStale => "check_stale",
392        }
393    }
394}
395
396/// Derive the state from the newest record (if any) and the entity's
397/// current `content_hash`. Hash-only: this is the `verification`
398/// derivation, and stays the whole story for that kind — a schema
399/// re-pin never stales a verification verdict.
400pub fn derive_state(latest: Option<&CheckRecord>, current_hash: &str) -> CheckState {
401    derive_state_pinned(latest, current_hash, None)
402}
403
404/// Derive the state with schema-pin awareness: beyond the hash
405/// comparison, a record that carries a `schema_ref` (a `conformance`
406/// record) is stale when the mem's current pin differs from the
407/// recorded one — the prose the verdict judged against is no longer
408/// the prose in force. A mem that has since lost its pin entirely
409/// stales the verdict the same way. Records without a `schema_ref`
410/// (every `verification` record) are unaffected by the pin argument.
411pub fn derive_state_pinned(
412    latest: Option<&CheckRecord>,
413    current_hash: &str,
414    current_schema_ref: Option<&str>,
415) -> CheckState {
416    match latest {
417        None => CheckState::NeverChecked,
418        Some(rec) if rec.entity_hash != current_hash => CheckState::CheckStale,
419        Some(rec)
420            if rec.schema_ref.is_some() && rec.schema_ref.as_deref() != current_schema_ref =>
421        {
422            CheckState::CheckStale
423        }
424        Some(rec) if rec.verdict == "failed" => CheckState::CheckFailed,
425        Some(_) => CheckState::CheckedOk,
426    }
427}
428
429/// The ledger's directory under the workspace store:
430/// `<root>/.memstead/state/checks/`.
431fn checks_dir(workspace_root: &Path) -> PathBuf {
432    workspace_root
433        .join(crate::workspace_store::WORKSPACE_STORE_DIR)
434        .join("state")
435        .join("checks")
436}
437
438/// The ledger file path for a workspace.
439pub fn check_ledger_path(workspace_root: &Path) -> PathBuf {
440    checks_dir(workspace_root).join("checks.jsonl")
441}
442
443/// Append/read handle for a workspace's check ledger.
444#[derive(Debug, Clone)]
445pub struct CheckLedger {
446    path: PathBuf,
447}
448
449impl CheckLedger {
450    pub fn for_workspace(workspace_root: &Path) -> Self {
451        Self {
452            path: check_ledger_path(workspace_root),
453        }
454    }
455
456    /// Append one record. One `write` syscall of one complete line on
457    /// an `O_APPEND` handle — concurrent writers interleave whole
458    /// lines, never tear them. Errors propagate: a check that did not
459    /// persist must refuse at the surface.
460    pub fn record(&self, rec: &CheckRecord) -> std::io::Result<()> {
461        if let Some(dir) = self.path.parent() {
462            std::fs::create_dir_all(dir)?;
463        }
464        let mut line = serde_json::to_string(rec).map_err(std::io::Error::other)?;
465        line.push('\n');
466        let mut f = std::fs::OpenOptions::new()
467            .create(true)
468            .append(true)
469            .open(&self.path)?;
470        f.write_all(line.as_bytes())
471    }
472
473    /// Carry every record of `old` across a rename to `new`: each line
474    /// keyed by the old id is appended again under the new id with
475    /// `renamed_from` set, in ledger order, as one write of whole lines.
476    /// The originals stay — the ledger is append-only and they remain the
477    /// record of what was checked under that id. Returns the number of
478    /// lines carried; zero (and no write) when the old id has none.
479    pub fn carry_rename(&self, old: &str, new: &str) -> std::io::Result<usize> {
480        let carried: Vec<CheckRecord> = self
481            .all()
482            .into_iter()
483            .filter(|r| r.entity == old)
484            .map(|mut r| {
485                r.entity = new.to_string();
486                r.renamed_from = Some(old.to_string());
487                r
488            })
489            .collect();
490        if carried.is_empty() {
491            return Ok(0);
492        }
493        let mut lines = String::new();
494        for rec in &carried {
495            lines.push_str(&serde_json::to_string(rec).map_err(std::io::Error::other)?);
496            lines.push('\n');
497        }
498        let mut f = std::fs::OpenOptions::new()
499            .create(true)
500            .append(true)
501            .open(&self.path)?;
502        f.write_all(lines.as_bytes())?;
503        Ok(carried.len())
504    }
505
506    /// Carry the record that licensed a status transition across the
507    /// write it licensed: the newest record of `entity` under the wire
508    /// `kind` is appended again with `post_hash` as its `entity_hash` and
509    /// `carried_from: {hash: pre_hash, reason: "transition"}`, if and
510    /// only if it is fresh at `pre_hash` and confirming (`ok`). A stale
511    /// or failed record is not carried (it did not license anything),
512    /// and equal hashes carry nothing. Every other field stays the
513    /// original act's, identity included. Returns whether a line was
514    /// appended.
515    pub fn carry_transition(
516        &self,
517        entity: &str,
518        kind: &str,
519        pre_hash: &str,
520        post_hash: &str,
521    ) -> std::io::Result<bool> {
522        if pre_hash == post_hash {
523            return Ok(false);
524        }
525        let Some(latest) = self.latest_for_wire_kind(entity, kind) else {
526            return Ok(false);
527        };
528        if latest.entity_hash != pre_hash || latest.verdict != Verdict::Ok.as_str() {
529            return Ok(false);
530        }
531        let carried = CheckRecord {
532            entity_hash: post_hash.to_string(),
533            carried_from: Some(CarriedFrom::transition(pre_hash)),
534            ..latest
535        };
536        self.record(&carried)?;
537        Ok(true)
538    }
539
540    /// The records of one mem's entities, oldest first: every record
541    /// whose entity id is qualified by `mem`.
542    pub fn records_for_mem(&self, mem: &str) -> Vec<CheckRecord> {
543        let prefix = format!("{mem}--");
544        self.all()
545            .into_iter()
546            .filter(|r| r.entity.starts_with(&prefix))
547            .collect()
548    }
549
550    /// The transport form of a set of records: one JSON line per
551    /// record, ordered by timestamp then by the line's bytes, exact
552    /// duplicates dropped, a trailing newline. The same records give
553    /// the same bytes on every machine, so a publish that changed
554    /// nothing writes nothing.
555    pub fn transport_lines(records: &[CheckRecord]) -> Vec<u8> {
556        let mut lines: Vec<(u64, String)> = records
557            .iter()
558            .filter_map(|r| serde_json::to_string(r).ok().map(|s| (r.ts, s)))
559            .collect();
560        lines.sort();
561        lines.dedup();
562        let mut out = Vec::new();
563        for (_, line) in lines {
564            out.extend_from_slice(line.as_bytes());
565            out.push(b'\n');
566        }
567        out
568    }
569
570    /// Union `lines` (the transport form, from another machine) into
571    /// this ledger: every record not already present is appended, in
572    /// the order the lines carry; a record already present (the same
573    /// bytes) is skipped, so a round trip adds nothing. Unparseable
574    /// lines are skipped. Returns the number of records appended.
575    /// Rows keep every field they arrived with: identity, role, hash,
576    /// timestamp; nothing is rewritten on import.
577    pub fn merge_transport_lines(&self, lines: &[u8]) -> std::io::Result<usize> {
578        let present: std::collections::HashSet<String> = self
579            .all()
580            .iter()
581            .filter_map(|r| serde_json::to_string(r).ok())
582            .collect();
583        let mut appended = 0;
584        for line in String::from_utf8_lossy(lines).lines() {
585            let Ok(rec) = serde_json::from_str::<CheckRecord>(line) else {
586                continue;
587            };
588            let Ok(canonical) = serde_json::to_string(&rec) else {
589                continue;
590            };
591            if present.contains(&canonical) {
592                continue;
593            }
594            self.record(&rec)?;
595            appended += 1;
596        }
597        Ok(appended)
598    }
599
600    /// All records, oldest first. A missing ledger is an empty one;
601    /// unparseable lines are skipped (a torn tail must not poison the
602    /// readable history).
603    pub fn all(&self) -> Vec<CheckRecord> {
604        let Ok(content) = std::fs::read_to_string(&self.path) else {
605            return Vec::new();
606        };
607        content
608            .lines()
609            .filter_map(|l| serde_json::from_str(l).ok())
610            .collect()
611    }
612
613    /// The newest record for one entity, of any kind. State
614    /// derivation is per (entity, kind) — use [`Self::latest_for_kind`]
615    /// there; this remains the "what happened last" accessor.
616    pub fn latest_for(&self, entity: &str) -> Option<CheckRecord> {
617        self.all().into_iter().rev().find(|r| r.entity == entity)
618    }
619
620    /// The newest record for one entity of one kind. A later check of
621    /// the OTHER kind never supersedes it: the two derivations answer
622    /// different questions.
623    pub fn latest_for_kind(&self, entity: &str, kind: CheckKind) -> Option<CheckRecord> {
624        self.all()
625            .into_iter()
626            .rev()
627            .find(|r| r.entity == entity && r.resolved_kind() == Some(kind))
628    }
629
630    /// The newest record for one entity of one WIRE kind: an engine
631    /// kind resolves as [`Self::latest_for_kind`] (legacy kind-less
632    /// lines read as `verification`); a foreign `x-<name>` kind matches
633    /// the recorded kind verbatim. The lookup a `transition_requires_self_check`
634    /// gate declares its kind against.
635    pub fn latest_for_wire_kind(&self, entity: &str, kind: &str) -> Option<CheckRecord> {
636        match CheckKind::from_wire(kind) {
637            Some(k) => self.latest_for_kind(entity, k),
638            None => self
639                .all()
640                .into_iter()
641                .rev()
642                .find(|r| r.entity == entity && r.kind.as_deref() == Some(kind)),
643        }
644    }
645}
646
647// ---------------------------------------------------------------------------
648// Sealed check records: the archive member
649// ---------------------------------------------------------------------------
650
651/// Version of the sealed check-records member
652/// (`.memstead/checks.json`, [`memstead_schema::ARCHIVE_CHECKS_PATH`]).
653/// Read back by the archive mount; a reader tells "absent" from
654/// "not carried" by this line inside the member, so the published
655/// archive format number never moves for it.
656pub const SEALED_CHECKS_VERSION: u32 = 1;
657
658/// One sealed check record: the fields of the ledger line the archive
659/// carries, nothing invented. `kind` is the map key it sits under, the
660/// entity is the map key above that (its mem-relative path, so the
661/// member survives a remount under another mem name). The transport
662/// client and the structured finding stay in the workspace ledger: the
663/// archive answers state, and state derives from these fields alone.
664#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
665pub struct SealedCheck {
666    /// Unix epoch seconds at record time.
667    pub ts: u64,
668    /// `ok` | `failed`.
669    pub verdict: String,
670    /// The free-text method note, after the export's private-pattern
671    /// redaction (the same classes the provenance member applies).
672    #[serde(default, skip_serializing_if = "Option::is_none")]
673    pub method: Option<String>,
674    /// The entity's `content_hash` at check time: the freshness
675    /// baseline the mount compares against the sealed entity.
676    pub entity_hash: String,
677    /// Recorded actor category (`cli`, `agent`, ...).
678    pub actor: String,
679    /// The declared role, or `unspecified`.
680    pub role: String,
681    /// The declared identity, verbatim: a handle, never a person.
682    #[serde(default, skip_serializing_if = "Option::is_none")]
683    pub identity: Option<String>,
684    /// The schema pin a `conformance` record was judged against.
685    #[serde(default, skip_serializing_if = "Option::is_none")]
686    pub schema_ref: Option<String>,
687    /// The id the check was recorded under before a rename carried it.
688    #[serde(default, skip_serializing_if = "Option::is_none")]
689    pub renamed_from: Option<String>,
690    /// The hash the record was keyed to before the engine carried it,
691    /// and why (a licensed transition on the source mem, or the export's
692    /// own rewrite of the entity bytes).
693    #[serde(default, skip_serializing_if = "Option::is_none")]
694    pub carried_from: Option<CarriedFrom>,
695    /// The author≠checker independence reading
696    /// ([`crate::engine::independence::Independence`], wire form:
697    /// `confirmed_independent`, `self_checked`, `unconfirmable`) the
698    /// export derived for this record from the mem's provenance at
699    /// export time. The archive records no history at the engine seam,
700    /// so the reading cannot be re-derived on the mount; sealed here it
701    /// is the fact an immutable archive carries. Absent from a member an
702    /// older writer sealed: the mount then reads `unconfirmable`.
703    #[serde(default, skip_serializing_if = "Option::is_none")]
704    pub independence: Option<String>,
705    /// The trust class of the TEXT this row carries — its `method` note and
706    /// its finding message ([`crate::render::OriginClass`], wire form
707    /// `first-party` / `third-party`), as the exporting workspace
708    /// classified it ([`crate::Engine::check_row_origin_class`]).
709    ///
710    /// A check row's prose is written by whatever agent recorded the check,
711    /// which in a workspace that points a foreign model or a transcribed
712    /// outside finding at its ledger is not the workspace itself. Sealed
713    /// here for the same reason `independence` is: the mount records no
714    /// identity roster, so the reading cannot be re-derived on it.
715    ///
716    /// Absent when the exporting deployment declared no owner identities
717    /// (the row then inherits its mem's class, which is what every reader
718    /// did before this field) and on every member an older writer sealed.
719    #[serde(default, skip_serializing_if = "Option::is_none")]
720    pub origin: Option<String>,
721}
722
723impl SealedCheck {
724    /// The archive form of a ledger line, with no independence reading
725    /// yet (the export derives and sets it; see
726    /// [`crate::ops::export::build_redacted_sealed_checks`]).
727    pub fn from_record(rec: &CheckRecord) -> Self {
728        Self {
729            ts: rec.ts,
730            verdict: rec.verdict.clone(),
731            method: rec.method.clone(),
732            entity_hash: rec.entity_hash.clone(),
733            actor: rec.actor.clone(),
734            role: rec.role.clone(),
735            identity: rec.identity.clone(),
736            schema_ref: rec.schema_ref.clone(),
737            renamed_from: rec.renamed_from.clone(),
738            carried_from: rec.carried_from.clone(),
739            independence: None,
740            origin: None,
741        }
742    }
743
744    /// The sealed independence reading, parsed; `None` when the member
745    /// carries none (an older writer) or a value outside the vocabulary.
746    pub fn sealed_independence(&self) -> Option<crate::engine::independence::Independence> {
747        self.independence
748            .as_deref()
749            .and_then(crate::engine::independence::Independence::from_wire)
750    }
751
752    /// The sealed trust class of the row's prose, parsed; `None` when the
753    /// member seals none, which is every member an older writer sealed and
754    /// every export from a deployment that declared no owner identities.
755    /// The reader falls back to the mem's class then, as it did before the
756    /// field existed.
757    ///
758    /// This is the one reader that makes the sealed field load-bearing, and
759    /// it matters exactly where the mem grain cannot answer: a deployment
760    /// that vouches for an installed archive as first-party
761    /// ([`crate::Engine::declare_mem_origin`]) still must not serve a row
762    /// the publisher's own foreign checker wrote as its own prose.
763    pub fn sealed_origin(&self) -> Option<crate::render::OriginClass> {
764        match self.origin.as_deref()? {
765            "first-party" => Some(crate::render::OriginClass::FirstParty),
766            "third-party" => Some(crate::render::OriginClass::ThirdParty),
767            _ => None,
768        }
769    }
770
771    /// The ledger form under `entity_id` and the wire `kind` the record
772    /// sits under, so every derivation ([`derive_state`],
773    /// [`derive_state_pinned`]) and every surface that renders a
774    /// [`CheckRecord`] reads a sealed record the way it reads a ledger
775    /// line. A `verification` kind stays omitted, as the ledger writes it.
776    pub fn to_record(&self, entity_id: &str, kind: &str) -> CheckRecord {
777        CheckRecord {
778            ts: self.ts,
779            entity: entity_id.to_string(),
780            verdict: self.verdict.clone(),
781            method: self.method.clone(),
782            entity_hash: self.entity_hash.clone(),
783            actor: self.actor.clone(),
784            client: None,
785            role: self.role.clone(),
786            identity: self.identity.clone(),
787            kind: (kind != CheckKind::Verification.as_str()).then(|| kind.to_string()),
788            schema_ref: self.schema_ref.clone(),
789            finding: None,
790            renamed_from: self.renamed_from.clone(),
791            carried_from: self.carried_from.clone(),
792        }
793    }
794}
795
796/// The sealed check-records member: per entity (keyed by mem-relative
797/// path) the latest record per kind (keyed by wire kind:
798/// `verification`, `conformance`, or a foreign `x-<name>`).
799#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
800pub struct SealedChecks {
801    pub version: u32,
802    #[serde(default)]
803    pub entities: BTreeMap<String, BTreeMap<String, SealedCheck>>,
804}
805
806impl SealedChecks {
807    /// An empty member of the current version.
808    pub fn new() -> Self {
809        Self {
810            version: SEALED_CHECKS_VERSION,
811            entities: BTreeMap::new(),
812        }
813    }
814
815    /// The latest sealed record of one entity (by mem-relative path)
816    /// under one wire kind.
817    pub fn latest(&self, entity_path: &str, kind: &str) -> Option<&SealedCheck> {
818        self.entities
819            .get(entity_path)
820            .and_then(|kinds| kinds.get(kind))
821    }
822
823    /// Every sealed kind of one entity, in key order.
824    pub fn kinds_of(&self, entity_path: &str) -> impl Iterator<Item = (&str, &SealedCheck)> {
825        self.entities
826            .get(entity_path)
827            .into_iter()
828            .flat_map(|kinds| kinds.iter().map(|(k, v)| (k.as_str(), v)))
829    }
830
831    /// Re-key every record of one entity that is fresh at `pre_hash` to
832    /// `post_hash`, marking it `carried_from: {hash: pre_hash, reason:
833    /// "export"}`: the export rewrote the entity's bytes (links retargeted
834    /// to the archive name, the canonical re-render), and a record that
835    /// was fresh against the source content stays fresh against the
836    /// archived content. A record keyed to any other hash was stale
837    /// before the export and keeps its hash, so it still reads stale on
838    /// the mount. Equal hashes change nothing; every other field, the
839    /// sealed independence reading included, stays as sealed. Returns the
840    /// number of records moved.
841    pub fn rekey_entity(&mut self, entity_path: &str, pre_hash: &str, post_hash: &str) -> usize {
842        if pre_hash == post_hash {
843            return 0;
844        }
845        let Some(kinds) = self.entities.get_mut(entity_path) else {
846            return 0;
847        };
848        let mut moved = 0;
849        for rec in kinds.values_mut() {
850            if rec.entity_hash == pre_hash {
851                rec.entity_hash = post_hash.to_string();
852                rec.carried_from = Some(CarriedFrom::export(pre_hash));
853                moved += 1;
854            }
855        }
856        moved
857    }
858
859    /// Serialise to the canonical member bytes (pretty JSON, trailing
860    /// newline), deterministic for a given content: both maps are
861    /// ordered.
862    pub fn to_archive_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
863        let mut s = serde_json::to_string_pretty(self)?;
864        s.push('\n');
865        Ok(s.into_bytes())
866    }
867
868    /// Parse the member bytes. Shape only; [`Self::validate`] checks the
869    /// vocabulary and the entity roster.
870    pub fn from_archive_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
871        serde_json::from_slice(bytes)
872    }
873
874    /// The validator's shape check: the version this engine reads, every
875    /// kind in the vocabulary, every verdict in the vocabulary, a
876    /// non-empty hash, actor and role, and every entity path one the
877    /// archive carries (`carried` is the set of mem-relative entity
878    /// paths). The error names the first offending record.
879    pub fn validate(&self, carried: &std::collections::BTreeSet<String>) -> Result<(), String> {
880        if self.version != SEALED_CHECKS_VERSION {
881            return Err(format!(
882                "version {} is not the version this engine reads ({SEALED_CHECKS_VERSION})",
883                self.version
884            ));
885        }
886        for (path, kinds) in &self.entities {
887            if !carried.contains(path) {
888                return Err(format!(
889                    "entity `{path}` names no entity the archive carries"
890                ));
891            }
892            for (kind, rec) in kinds {
893                let at = format!("entity `{path}`, kind `{kind}`");
894                if RecordKind::from_wire(kind).is_none() {
895                    return Err(format!(
896                        "{at}: the kind is not one of {}",
897                        RecordKind::vocabulary_hint()
898                    ));
899                }
900                if Verdict::from_wire(&rec.verdict).is_none() {
901                    return Err(format!(
902                        "{at}: verdict `{}` is not one of {}",
903                        rec.verdict,
904                        VERDICTS.join(", ")
905                    ));
906                }
907                if rec.entity_hash.trim().is_empty() {
908                    return Err(format!("{at}: entity_hash is empty"));
909                }
910                if rec.actor.trim().is_empty() {
911                    return Err(format!("{at}: actor is empty"));
912                }
913                if rec.role.trim().is_empty() {
914                    return Err(format!("{at}: role is empty"));
915                }
916                if let Some(reading) = rec.independence.as_deref()
917                    && crate::engine::independence::Independence::from_wire(reading).is_none()
918                {
919                    return Err(format!(
920                        "{at}: independence `{reading}` is not one of {}",
921                        crate::engine::independence::Independence::vocabulary_hint()
922                    ));
923                }
924                // The trust class is publisher-supplied bytes on an
925                // installed archive, so the vocabulary is closed here as
926                // the independence reading's is: an unknown token is
927                // refused with a typed error rather than parsed into
928                // something a reader would treat as a class.
929                if let Some(origin) = rec.origin.as_deref()
930                    && rec.sealed_origin().is_none()
931                {
932                    return Err(format!(
933                        "{at}: origin `{origin}` is not one of first-party | third-party"
934                    ));
935                }
936            }
937        }
938        Ok(())
939    }
940}
941
942impl Default for SealedChecks {
943    fn default() -> Self {
944        Self::new()
945    }
946}
947
948/// The wire kind a ledger line sits under in the sealed member: an
949/// engine kind by its resolved name (a legacy kind-less line is
950/// `verification`), a foreign kind verbatim.
951pub fn sealed_kind_of(rec: &CheckRecord) -> String {
952    match rec.resolved_kind() {
953        Some(k) => k.as_str().to_string(),
954        None => rec.kind.clone().unwrap_or_default(),
955    }
956}
957
958#[cfg(test)]
959mod tests {
960    use super::*;
961    use tempfile::TempDir;
962
963    fn rec(entity: &str, verdict: &str, hash: &str) -> CheckRecord {
964        CheckRecord {
965            ts: 1,
966            entity: entity.to_string(),
967            verdict: verdict.to_string(),
968            method: None,
969            entity_hash: hash.to_string(),
970            actor: "cli".to_string(),
971            client: None,
972            role: "checker".to_string(),
973            identity: None,
974            kind: None,
975            schema_ref: None,
976            finding: None,
977            renamed_from: None,
978            carried_from: None,
979        }
980    }
981
982    #[test]
983    fn state_derivation_covers_all_four_states() {
984        assert_eq!(derive_state(None, "h1"), CheckState::NeverChecked);
985        let ok = rec("m--e", "ok", "h1");
986        assert_eq!(derive_state(Some(&ok), "h1"), CheckState::CheckedOk);
987        assert_eq!(derive_state(Some(&ok), "h2"), CheckState::CheckStale);
988        let failed = rec("m--e", "failed", "h1");
989        assert_eq!(derive_state(Some(&failed), "h1"), CheckState::CheckFailed);
990        // A failed check on changed content is stale too — the verdict
991        // no longer speaks to current content either way.
992        assert_eq!(derive_state(Some(&failed), "h2"), CheckState::CheckStale);
993    }
994
995    #[test]
996    fn ledger_appends_and_serves_newest_per_entity() {
997        let tmp = TempDir::new().unwrap();
998        let ledger = CheckLedger::for_workspace(tmp.path());
999        assert!(ledger.latest_for("m--a").is_none());
1000        ledger.record(&rec("m--a", "failed", "h1")).unwrap();
1001        ledger.record(&rec("m--b", "ok", "h9")).unwrap();
1002        ledger.record(&rec("m--a", "ok", "h2")).unwrap();
1003        let latest = ledger.latest_for("m--a").unwrap();
1004        assert_eq!(latest.verdict, "ok");
1005        assert_eq!(latest.entity_hash, "h2");
1006        // Supersession never erases: all three records remain.
1007        assert_eq!(ledger.all().len(), 3);
1008    }
1009
1010    /// A rename carries the old id's lines under the new id, marked
1011    /// with their origin, and leaves the originals in place. The carried
1012    /// line keeps the hash the check was made against, so it derives
1013    /// `check_stale` against the renamed file's new hash — never a
1014    /// silently fresh `checked_ok`, never `never_checked`.
1015    #[test]
1016    fn carry_rename_rekeys_without_erasing() {
1017        let tmp = TempDir::new().unwrap();
1018        let ledger = CheckLedger::for_workspace(tmp.path());
1019        ledger.record(&rec("m--old", "ok", "h1")).unwrap();
1020        ledger.record(&rec("m--other", "ok", "h9")).unwrap();
1021        let mut conf = rec("m--old", "failed", "h1");
1022        conf.kind = Some("conformance".into());
1023        ledger.record(&conf).unwrap();
1024
1025        assert_eq!(ledger.carry_rename("m--old", "m--new").unwrap(), 2);
1026        assert_eq!(ledger.carry_rename("m--absent", "m--new").unwrap(), 0);
1027
1028        let all = ledger.all();
1029        assert_eq!(all.len(), 5);
1030        assert!(all.iter().filter(|r| r.entity == "m--old").count() == 2);
1031        let carried: Vec<&CheckRecord> = all.iter().filter(|r| r.entity == "m--new").collect();
1032        assert_eq!(carried.len(), 2);
1033        assert!(
1034            carried
1035                .iter()
1036                .all(|r| r.renamed_from.as_deref() == Some("m--old"))
1037        );
1038        let latest = ledger
1039            .latest_for_kind("m--new", CheckKind::Verification)
1040            .unwrap();
1041        assert_eq!(latest.verdict, "ok");
1042        assert_eq!(derive_state(Some(&latest), "h1"), CheckState::CheckedOk);
1043        assert_eq!(
1044            derive_state(Some(&latest), "h2-after-rename"),
1045            CheckState::CheckStale
1046        );
1047        assert_eq!(
1048            ledger
1049                .latest_for_kind("m--new", CheckKind::Conformance)
1050                .unwrap()
1051                .verdict,
1052            "failed"
1053        );
1054        // A checker's own line never carries the marker.
1055        assert!(
1056            ledger
1057                .latest_for("m--other")
1058                .unwrap()
1059                .renamed_from
1060                .is_none()
1061        );
1062    }
1063
1064    /// A transition carry re-keys the licensing record to the post-write
1065    /// hash and marks its origin; a record that is stale at the pre-write
1066    /// hash, a failed one, or an unchanged hash carries nothing. The
1067    /// carried line keeps the checker's identity, so independence still
1068    /// reads it as the checker's, not the writer's.
1069    #[test]
1070    fn carry_transition_moves_only_the_fresh_confirming_record() {
1071        let tmp = TempDir::new().unwrap();
1072        let ledger = CheckLedger::for_workspace(tmp.path());
1073        let mut ok = rec("m--plan", "ok", "h1");
1074        ok.kind = Some("x-projection".into());
1075        ok.identity = Some("checker-c".into());
1076        ledger.record(&ok).unwrap();
1077
1078        assert!(
1079            !ledger
1080                .carry_transition("m--plan", "x-projection", "h1", "h1")
1081                .unwrap()
1082        );
1083        assert!(
1084            !ledger
1085                .carry_transition("m--plan", "x-projection", "h0", "h2")
1086                .unwrap()
1087        );
1088        assert!(
1089            !ledger
1090                .carry_transition("m--plan", "verification", "h1", "h2")
1091                .unwrap()
1092        );
1093        assert_eq!(ledger.all().len(), 1, "nothing appended so far");
1094
1095        assert!(
1096            ledger
1097                .carry_transition("m--plan", "x-projection", "h1", "h2")
1098                .unwrap()
1099        );
1100        let all = ledger.all();
1101        assert_eq!(all.len(), 2, "append-only: the original stays");
1102        let carried = ledger
1103            .latest_for_wire_kind("m--plan", "x-projection")
1104            .unwrap();
1105        assert_eq!(carried.entity_hash, "h2");
1106        assert_eq!(carried.identity.as_deref(), Some("checker-c"));
1107        assert_eq!(carried.verdict, "ok");
1108        assert_eq!(
1109            carried.carried_from,
1110            Some(CarriedFrom {
1111                hash: "h1".into(),
1112                reason: CARRY_REASON_TRANSITION.into()
1113            })
1114        );
1115        assert_eq!(derive_state(Some(&carried), "h2"), CheckState::CheckedOk);
1116        // A second transition carries the carried line onward, one step.
1117        assert!(
1118            ledger
1119                .carry_transition("m--plan", "x-projection", "h2", "h3")
1120                .unwrap()
1121        );
1122        let again = ledger
1123            .latest_for_wire_kind("m--plan", "x-projection")
1124            .unwrap();
1125        assert_eq!(again.carried_from.as_ref().unwrap().hash, "h2");
1126
1127        // A failed record licenses nothing and is never carried.
1128        let mut failed = rec("m--other", "failed", "h1");
1129        failed.kind = Some("x-projection".into());
1130        ledger.record(&failed).unwrap();
1131        assert!(
1132            !ledger
1133                .carry_transition("m--other", "x-projection", "h1", "h2")
1134                .unwrap()
1135        );
1136        // A checker's own line never carries the marker.
1137        assert!(all[0].carried_from.is_none());
1138    }
1139
1140    /// The sealed member re-keys a record fresh at the pre-rewrite hash
1141    /// to the archived hash and marks it; a stale record keeps its hash.
1142    #[test]
1143    fn sealed_rekey_moves_fresh_records_and_leaves_stale_ones() {
1144        let mut sealed = SealedChecks::new();
1145        let fresh = SealedCheck::from_record(&rec("m--a", "ok", "h1"));
1146        let mut stale = SealedCheck::from_record(&rec("m--a", "ok", "h0"));
1147        stale.ts = 0;
1148        sealed.entities.insert(
1149            "a".into(),
1150            BTreeMap::from([
1151                ("verification".to_string(), fresh),
1152                ("x-audit".to_string(), stale),
1153            ]),
1154        );
1155        assert_eq!(sealed.rekey_entity("a", "h1", "h1"), 0);
1156        assert_eq!(sealed.rekey_entity("absent", "h1", "h2"), 0);
1157        assert_eq!(sealed.rekey_entity("a", "h1", "h2"), 1);
1158        let v = sealed.latest("a", "verification").unwrap();
1159        assert_eq!(v.entity_hash, "h2");
1160        assert_eq!(v.carried_from.as_ref().unwrap().reason, CARRY_REASON_EXPORT);
1161        assert_eq!(v.carried_from.as_ref().unwrap().hash, "h1");
1162        let x = sealed.latest("a", "x-audit").unwrap();
1163        assert_eq!(x.entity_hash, "h0", "stale stays stale");
1164        assert!(x.carried_from.is_none());
1165        // The round trip through the ledger form keeps the marker.
1166        let back = v.to_record("m--a", "verification");
1167        assert_eq!(back.carried_from, v.carried_from);
1168        assert_eq!(SealedCheck::from_record(&back), *v);
1169        // A pre-marker member line still parses, and reads no independence.
1170        let legacy = r#"{"ts":1,"verdict":"ok","entity_hash":"h","actor":"cli","role":"checker"}"#;
1171        let parsed: SealedCheck = serde_json::from_str(legacy).unwrap();
1172        assert!(parsed.carried_from.is_none());
1173        assert!(parsed.independence.is_none());
1174        assert!(parsed.sealed_independence().is_none());
1175    }
1176
1177    /// The sealed trust class of a row's prose parses only from the two
1178    /// origin tokens and fails the validator outside them. The bytes come
1179    /// from a publisher's archive, so the vocabulary is closed here exactly
1180    /// as the independence reading's is: a member claiming `first-party` in
1181    /// a spelling no reader recognises must be refused with a typed error,
1182    /// not parsed into something a reader treats as a class.
1183    #[test]
1184    fn sealed_row_origin_parses_only_from_the_closed_vocabulary() {
1185        let mut sealed = SealedChecks::new();
1186        let mut row = SealedCheck::from_record(&rec("m--a", "ok", "h1"));
1187        row.origin = Some("third-party".to_string());
1188        sealed.entities.insert(
1189            "a".into(),
1190            BTreeMap::from([("verification".to_string(), row)]),
1191        );
1192        assert_eq!(
1193            sealed.latest("a", "verification").unwrap().sealed_origin(),
1194            Some(crate::render::OriginClass::ThirdParty)
1195        );
1196        let carried: std::collections::BTreeSet<String> = ["a".to_string()].into();
1197        assert!(sealed.validate(&carried).is_ok());
1198
1199        // A member an older writer sealed carries none and reads none.
1200        let legacy = r#"{"ts":1,"verdict":"ok","entity_hash":"h","actor":"cli","role":"checker"}"#;
1201        let parsed: SealedCheck = serde_json::from_str(legacy).unwrap();
1202        assert!(parsed.origin.is_none());
1203        assert!(parsed.sealed_origin().is_none());
1204
1205        // A token outside the vocabulary is refused, and reads as no class
1206        // rather than as a guess.
1207        sealed
1208            .entities
1209            .get_mut("a")
1210            .unwrap()
1211            .get_mut("verification")
1212            .unwrap()
1213            .origin = Some("trusted".into());
1214        assert!(
1215            sealed
1216                .latest("a", "verification")
1217                .unwrap()
1218                .sealed_origin()
1219                .is_none()
1220        );
1221        let err = sealed.validate(&carried).unwrap_err();
1222        assert!(err.contains("origin `trusted`"), "{err}");
1223    }
1224
1225    /// The sealed independence reading survives the export re-key, is
1226    /// dropped from the ledger form (the ledger derives, never stores
1227    /// it), parses only from the vocabulary, and fails the validator
1228    /// outside it.
1229    #[test]
1230    fn sealed_independence_is_kept_by_rekey_and_closed_in_vocabulary() {
1231        use crate::engine::independence::Independence;
1232        let mut sealed = SealedChecks::new();
1233        let mut fresh = SealedCheck::from_record(&rec("m--a", "ok", "h1"));
1234        fresh.independence = Some(Independence::ConfirmedIndependent.as_str().to_string());
1235        sealed.entities.insert(
1236            "a".into(),
1237            BTreeMap::from([("verification".to_string(), fresh)]),
1238        );
1239        assert_eq!(sealed.rekey_entity("a", "h1", "h2"), 1);
1240        let v = sealed.latest("a", "verification").unwrap();
1241        assert_eq!(
1242            v.sealed_independence(),
1243            Some(Independence::ConfirmedIndependent)
1244        );
1245        let bytes = sealed.to_archive_bytes().unwrap();
1246        let back = SealedChecks::from_archive_bytes(&bytes).unwrap();
1247        assert_eq!(back, sealed);
1248        assert!(v.to_record("m--a", "verification").carried_from.is_some());
1249        let carried: std::collections::BTreeSet<String> = ["a".to_string()].into();
1250        assert!(back.validate(&carried).is_ok());
1251
1252        let mut foreign = sealed.clone();
1253        foreign
1254            .entities
1255            .get_mut("a")
1256            .unwrap()
1257            .get_mut("verification")
1258            .unwrap()
1259            .independence = Some("trusted".into());
1260        assert!(
1261            foreign
1262                .latest("a", "verification")
1263                .unwrap()
1264                .sealed_independence()
1265                .is_none()
1266        );
1267        let err = foreign.validate(&carried).unwrap_err();
1268        assert!(err.contains("independence `trusted`"), "{err}");
1269    }
1270
1271    #[test]
1272    fn verdict_vocabulary_is_closed() {
1273        assert!(Verdict::from_wire("ok").is_some());
1274        assert!(Verdict::from_wire("failed").is_some());
1275        assert!(Verdict::from_wire("passed").is_none());
1276        assert!(Verdict::from_wire("OK").is_none());
1277    }
1278
1279    fn conf(entity: &str, verdict: &str, hash: &str, pin: &str) -> CheckRecord {
1280        CheckRecord {
1281            kind: Some("conformance".to_string()),
1282            schema_ref: Some(pin.to_string()),
1283            ..rec(entity, verdict, hash)
1284        }
1285    }
1286
1287    #[test]
1288    fn kind_vocabulary_is_closed() {
1289        assert!(CheckKind::from_wire("verification").is_some());
1290        assert!(CheckKind::from_wire("conformance").is_some());
1291        assert!(CheckKind::from_wire("semantic").is_none());
1292        assert!(CheckKind::from_wire("Conformance").is_none());
1293    }
1294
1295    /// Criterion 5: a pre-kind ledger line (no `kind` field) parses
1296    /// and derives as a `verification` record, byte-for-byte the old
1297    /// shape on the write side too.
1298    #[test]
1299    fn legacy_lines_read_as_verification() {
1300        let legacy = r#"{"ts":1,"entity":"m--e","verdict":"ok","entity_hash":"h1","actor":"cli","role":"checker"}"#;
1301        let parsed: CheckRecord = serde_json::from_str(legacy).unwrap();
1302        assert_eq!(parsed.resolved_kind(), Some(CheckKind::Verification));
1303        // A freshly built verification record serialises with no kind
1304        // and no schema_ref key at all.
1305        let fresh = rec("m--e", "ok", "h1");
1306        let line = serde_json::to_string(&fresh).unwrap();
1307        assert!(!line.contains("kind"));
1308        assert!(!line.contains("schema_ref"));
1309        // An identity-less record carries no identity key either —
1310        // pre-plan-15 lines and identity-less callers stay
1311        // byte-identical.
1312        assert!(!line.contains("identity"));
1313    }
1314
1315    /// Criterion 3: state derives per (entity, kind) — a later check
1316    /// of the other kind does not supersede.
1317    #[test]
1318    fn latest_is_per_kind() {
1319        let tmp = TempDir::new().unwrap();
1320        let ledger = CheckLedger::for_workspace(tmp.path());
1321        ledger.record(&rec("m--a", "ok", "h1")).unwrap();
1322        ledger
1323            .record(&conf("m--a", "failed", "h1", "planning@1.0.0"))
1324            .unwrap();
1325        let v = ledger
1326            .latest_for_kind("m--a", CheckKind::Verification)
1327            .unwrap();
1328        assert_eq!(v.verdict, "ok");
1329        let c = ledger
1330            .latest_for_kind("m--a", CheckKind::Conformance)
1331            .unwrap();
1332        assert_eq!(c.verdict, "failed");
1333        assert_eq!(c.schema_ref.as_deref(), Some("planning@1.0.0"));
1334    }
1335
1336    /// Criterion 4: a conformance verdict is stale on a content move
1337    /// AND on a pin move; a verification verdict ignores pin moves.
1338    #[test]
1339    fn conformance_stales_on_pin_move_verification_does_not() {
1340        let c = conf("m--e", "ok", "h1", "planning@1.0.0");
1341        assert_eq!(
1342            derive_state_pinned(Some(&c), "h1", Some("planning@1.0.0")),
1343            CheckState::CheckedOk
1344        );
1345        assert_eq!(
1346            derive_state_pinned(Some(&c), "h2", Some("planning@1.0.0")),
1347            CheckState::CheckStale
1348        );
1349        assert_eq!(
1350            derive_state_pinned(Some(&c), "h1", Some("planning@2.0.0")),
1351            CheckState::CheckStale
1352        );
1353        // The mem losing its pin stales the verdict too.
1354        assert_eq!(
1355            derive_state_pinned(Some(&c), "h1", None),
1356            CheckState::CheckStale
1357        );
1358        // Verification: unaffected by any pin argument.
1359        let v = rec("m--e", "ok", "h1");
1360        assert_eq!(
1361            derive_state_pinned(Some(&v), "h1", Some("planning@9.0.0")),
1362            CheckState::CheckedOk
1363        );
1364        assert_eq!(derive_state(Some(&v), "h1"), CheckState::CheckedOk);
1365    }
1366
1367    // --- findings and open kinds ---
1368
1369    #[test]
1370    fn finding_shape_is_fixed_and_validated_whole() {
1371        let ok = CheckFinding::from_json(serde_json::json!({
1372            "code": "hidden-premise", "message": "The step assumes X.", "section": "step"
1373        }))
1374        .unwrap();
1375        assert_eq!(ok.code, "hidden-premise");
1376        assert_eq!(ok.section.as_deref(), Some("step"));
1377        for bad in [
1378            serde_json::json!({ "message": "no code" }),
1379            serde_json::json!({ "code": "x" }),
1380            serde_json::json!({ "code": "", "message": "empty code" }),
1381            serde_json::json!({ "code": "x", "message": "   " }),
1382            serde_json::json!({ "code": "x", "message": "m", "severity": "high" }),
1383            serde_json::json!({ "code": "x", "message": "m", "section": "" }),
1384        ] {
1385            let err = CheckFinding::from_json(bad.clone()).unwrap_err();
1386            assert!(err.contains("shape"), "{bad}: {err}");
1387        }
1388    }
1389
1390    #[test]
1391    fn open_kinds_parse_only_with_the_prefix_and_never_resolve_to_an_engine_kind() {
1392        assert_eq!(
1393            RecordKind::from_wire("verification"),
1394            Some(RecordKind::Engine(CheckKind::Verification))
1395        );
1396        assert_eq!(
1397            RecordKind::from_wire("x-step-walk"),
1398            Some(RecordKind::Foreign("x-step-walk".to_string()))
1399        );
1400        for bad in ["step-walk", "x-", "x-Step", "x--a", "x-a-", "X-a"] {
1401            assert!(RecordKind::from_wire(bad).is_none(), "{bad}");
1402        }
1403        assert!(RecordKind::vocabulary_hint().contains("x-<name>"));
1404        let mut r = rec("m--e", "ok", "h");
1405        r.kind = Some("x-step-walk".to_string());
1406        assert_eq!(r.resolved_kind(), None);
1407        assert_eq!(r.foreign_kind(), Some("x-step-walk"));
1408        r.kind = None;
1409        assert_eq!(r.resolved_kind(), Some(CheckKind::Verification));
1410        r.kind = Some("conformance".to_string());
1411        assert_eq!(r.resolved_kind(), Some(CheckKind::Conformance));
1412        // A pre-`x-` unrecognised kind keeps its legacy reading.
1413        r.kind = Some("mystery".to_string());
1414        assert_eq!(r.resolved_kind(), Some(CheckKind::Verification));
1415    }
1416
1417    #[test]
1418    fn pre_finding_ledger_lines_parse_and_derive_unchanged_and_findings_round_trip() {
1419        let tmp = TempDir::new().unwrap();
1420        let ledger = CheckLedger::for_workspace(tmp.path());
1421        let dir = check_ledger_path(tmp.path());
1422        std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
1423        // A line written before findings existed: no `finding`, no `kind`.
1424        std::fs::write(
1425            &dir,
1426            "{\"ts\":1,\"entity\":\"m--e\",\"verdict\":\"failed\",\"entity_hash\":\"h\",\"actor\":\"cli\",\"role\":\"unspecified\"}\n",
1427        )
1428        .unwrap();
1429        let old = ledger
1430            .latest_for_kind("m--e", CheckKind::Verification)
1431            .unwrap();
1432        assert!(old.finding.is_none());
1433        assert_eq!(derive_state(Some(&old), "h"), CheckState::CheckFailed);
1434
1435        let mut with = rec("m--e", "failed", "h");
1436        with.ts = 2;
1437        with.finding = Some(CheckFinding {
1438            code: "hidden-premise".into(),
1439            section: Some("step".into()),
1440            message: "The step assumes X.".into(),
1441            evidence: None,
1442        });
1443        ledger.record(&with).unwrap();
1444        // A foreign-kind line beside it moves no verification state.
1445        let mut foreign = rec("m--e", "ok", "h");
1446        foreign.ts = 3;
1447        foreign.kind = Some("x-step-walk".into());
1448        ledger.record(&foreign).unwrap();
1449        let latest = ledger
1450            .latest_for_kind("m--e", CheckKind::Verification)
1451            .unwrap();
1452        assert_eq!(
1453            latest.ts, 2,
1454            "the foreign record is not the latest verification record"
1455        );
1456        assert_eq!(latest.finding.as_ref().unwrap().code, "hidden-premise");
1457        assert_eq!(derive_state(Some(&latest), "h"), CheckState::CheckFailed);
1458        let text = std::fs::read_to_string(&dir).unwrap();
1459        assert!(text.contains("\"finding\":{\"code\":\"hidden-premise\",\"section\":\"step\",\"message\":\"The step assumes X.\"}"), "{text}");
1460        assert!(text.contains("\"kind\":\"x-step-walk\""));
1461        assert_eq!(text.lines().count(), 3, "append-only");
1462    }
1463}