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::io::Write;
37use std::path::{Path, PathBuf};
38
39use serde::{Deserialize, Serialize};
40
41/// The closed verdict vocabulary. Nuance goes in the method note or
42/// in process-mem entities — never in new verdict values.
43pub const VERDICTS: [&str; 2] = ["ok", "failed"];
44
45/// The closed kind vocabulary. `verification` is the default and
46/// today's behaviour: "I checked this entity's content". `conformance`
47/// is the semantic judgment "this entity satisfies its type's
48/// schema prose (`write_rules` / `writing_guidance`)" — recorded with
49/// the mem's schema pin, stamped by the engine at record time, so the
50/// verdict's freshness against both the content AND the prose version
51/// stays computable. A third kind is a separate decision; closed
52/// kinds keep health aggregation well-defined, matching the closed
53/// verdict vocabulary.
54pub const CHECK_KINDS: [&str; 2] = ["verification", "conformance"];
55
56/// Prefix of a caller-declared check kind the engine records verbatim
57/// and never interprets: `x-<name>`, `name` lowercase letters, digits
58/// and hyphens. The prefix makes the declaration deliberate — a typo of
59/// an engine kind cannot silently become a new kind — mirroring the
60/// rule that a third ENGINE kind is a separate decision. Foreign kinds
61/// never influence `check_state`; health lists them by count.
62pub const FOREIGN_KIND_PREFIX: &str = "x-";
63
64/// The typed code for a malformed finding.
65pub const INVALID_CHECK_FINDING_CODE: &str = "INVALID_CHECK_FINDING";
66
67/// A check kind from the closed vocabulary.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum CheckKind {
70    Verification,
71    Conformance,
72}
73
74/// What a caller may declare as a check's kind: one of the engine's
75/// two kinds, or a foreign `x-<name>` kind recorded verbatim.
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub enum RecordKind {
78    Engine(CheckKind),
79    Foreign(String),
80}
81
82impl RecordKind {
83    /// Parse a wire kind: an engine kind, an `x-` kind (name non-empty,
84    /// lowercase letters, digits and hyphens), or `None` for anything
85    /// else — the vocabulary the refusal names is [`CHECK_KINDS`] plus
86    /// the `x-<name>` form.
87    pub fn from_wire(s: &str) -> Option<Self> {
88        if let Some(k) = CheckKind::from_wire(s) {
89            return Some(Self::Engine(k));
90        }
91        let name = s.strip_prefix(FOREIGN_KIND_PREFIX)?;
92        let well_formed = !name.is_empty()
93            && name
94                .chars()
95                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
96            && !name.starts_with('-')
97            && !name.ends_with('-');
98        well_formed.then(|| 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/// One recorded check — the full ledger line.
242#[derive(Debug, Clone, Serialize, Deserialize)]
243pub struct CheckRecord {
244    /// Unix epoch seconds at record time.
245    pub ts: u64,
246    /// Full entity id (`mem--slug`).
247    pub entity: String,
248    /// `ok` | `failed`.
249    pub verdict: String,
250    /// Optional free-text method note ("diffed against source spec",
251    /// "re-ran the derivation").
252    #[serde(default, skip_serializing_if = "Option::is_none")]
253    pub method: Option<String>,
254    /// The entity's `content_hash` at check time — the staleness
255    /// baseline.
256    pub entity_hash: String,
257    /// Recorded actor identity (plan-13 provenance).
258    pub actor: String,
259    /// Recorded client identity (`name@version`), when known.
260    #[serde(default, skip_serializing_if = "Option::is_none")]
261    pub client: Option<String>,
262    /// The caller-declared role, or `"unspecified"` — recorded
263    /// honestly; downstream gates treat unspecified as
264    /// cannot-confirm, never as any real role.
265    pub role: String,
266    /// The caller-declared identity: an opaque
267    /// caller-chosen string, the ONLY comparator the independence
268    /// gate uses. Absent on ledger lines written before identities
269    /// existed and on identity-less callers — both downgrade every
270    /// comparison to `unconfirmable`, never to a guessed category.
271    #[serde(default, skip_serializing_if = "Option::is_none")]
272    pub identity: Option<String>,
273    /// The check kind, from [`CHECK_KINDS`]. Absent on ledger lines
274    /// written before kinds existed AND on freshly recorded
275    /// `verification` checks — both read as `verification`, so an
276    /// existing ledger upgrades with no migration and a kind-omitted
277    /// caller's lines stay byte-identical to before.
278    #[serde(default, skip_serializing_if = "Option::is_none")]
279    pub kind: Option<String>,
280    /// For `conformance` records: the mem's schema pin
281    /// (`name@x.y.z`) as stamped by the engine at record time — never
282    /// caller-supplied, so a verdict cannot claim a prose version the
283    /// caller never read. Absent on `verification` records.
284    #[serde(default, skip_serializing_if = "Option::is_none")]
285    pub schema_ref: Option<String>,
286    /// The structured finding the checker attached, when one was.
287    /// Absent on every line written before findings existed and on
288    /// finding-less checks — serde-default, so every existing line
289    /// still parses and finding-less lines stay byte-identical.
290    #[serde(default, skip_serializing_if = "Option::is_none")]
291    pub finding: Option<CheckFinding>,
292}
293
294impl CheckRecord {
295    /// The record's ENGINE kind, legacy lines included: an absent or
296    /// unrecognised kind reads as `verification`, which is exactly what
297    /// every pre-kind line was; a foreign `x-<name>` kind is `None` —
298    /// recorded, listed, never aggregated into a state.
299    pub fn resolved_kind(&self) -> Option<CheckKind> {
300        match self.kind.as_deref() {
301            None => Some(CheckKind::Verification),
302            Some(k) if k.starts_with(FOREIGN_KIND_PREFIX) => None,
303            Some(k) => Some(CheckKind::from_wire(k).unwrap_or(CheckKind::Verification)),
304        }
305    }
306
307    /// The foreign kind, when the record carries one.
308    pub fn foreign_kind(&self) -> Option<&str> {
309        self.kind
310            .as_deref()
311            .filter(|k| k.starts_with(FOREIGN_KIND_PREFIX))
312    }
313}
314
315/// Derived per-entity check state.
316#[derive(Debug, Clone, Copy, PartialEq, Eq)]
317pub enum CheckState {
318    NeverChecked,
319    CheckedOk,
320    CheckFailed,
321    CheckStale,
322}
323
324impl CheckState {
325    pub fn as_str(self) -> &'static str {
326        match self {
327            Self::NeverChecked => "never_checked",
328            Self::CheckedOk => "checked_ok",
329            Self::CheckFailed => "check_failed",
330            Self::CheckStale => "check_stale",
331        }
332    }
333}
334
335/// Derive the state from the newest record (if any) and the entity's
336/// current `content_hash`. Hash-only: this is the `verification`
337/// derivation, and stays the whole story for that kind — a schema
338/// re-pin never stales a verification verdict.
339pub fn derive_state(latest: Option<&CheckRecord>, current_hash: &str) -> CheckState {
340    derive_state_pinned(latest, current_hash, None)
341}
342
343/// Derive the state with schema-pin awareness: beyond the hash
344/// comparison, a record that carries a `schema_ref` (a `conformance`
345/// record) is stale when the mem's current pin differs from the
346/// recorded one — the prose the verdict judged against is no longer
347/// the prose in force. A mem that has since lost its pin entirely
348/// stales the verdict the same way. Records without a `schema_ref`
349/// (every `verification` record) are unaffected by the pin argument.
350pub fn derive_state_pinned(
351    latest: Option<&CheckRecord>,
352    current_hash: &str,
353    current_schema_ref: Option<&str>,
354) -> CheckState {
355    match latest {
356        None => CheckState::NeverChecked,
357        Some(rec) if rec.entity_hash != current_hash => CheckState::CheckStale,
358        Some(rec)
359            if rec.schema_ref.is_some() && rec.schema_ref.as_deref() != current_schema_ref =>
360        {
361            CheckState::CheckStale
362        }
363        Some(rec) if rec.verdict == "failed" => CheckState::CheckFailed,
364        Some(_) => CheckState::CheckedOk,
365    }
366}
367
368/// The ledger's directory under the workspace store:
369/// `<root>/.memstead/state/checks/`.
370fn checks_dir(workspace_root: &Path) -> PathBuf {
371    workspace_root
372        .join(crate::workspace_store::WORKSPACE_STORE_DIR)
373        .join("state")
374        .join("checks")
375}
376
377/// The ledger file path for a workspace.
378pub fn check_ledger_path(workspace_root: &Path) -> PathBuf {
379    checks_dir(workspace_root).join("checks.jsonl")
380}
381
382/// Append/read handle for a workspace's check ledger.
383#[derive(Debug, Clone)]
384pub struct CheckLedger {
385    path: PathBuf,
386}
387
388impl CheckLedger {
389    pub fn for_workspace(workspace_root: &Path) -> Self {
390        Self {
391            path: check_ledger_path(workspace_root),
392        }
393    }
394
395    /// Append one record. One `write` syscall of one complete line on
396    /// an `O_APPEND` handle — concurrent writers interleave whole
397    /// lines, never tear them. Errors propagate: a check that did not
398    /// persist must refuse at the surface.
399    pub fn record(&self, rec: &CheckRecord) -> std::io::Result<()> {
400        if let Some(dir) = self.path.parent() {
401            std::fs::create_dir_all(dir)?;
402        }
403        let mut line = serde_json::to_string(rec).map_err(std::io::Error::other)?;
404        line.push('\n');
405        let mut f = std::fs::OpenOptions::new()
406            .create(true)
407            .append(true)
408            .open(&self.path)?;
409        f.write_all(line.as_bytes())
410    }
411
412    /// All records, oldest first. A missing ledger is an empty one;
413    /// unparseable lines are skipped (a torn tail must not poison the
414    /// readable history).
415    pub fn all(&self) -> Vec<CheckRecord> {
416        let Ok(content) = std::fs::read_to_string(&self.path) else {
417            return Vec::new();
418        };
419        content
420            .lines()
421            .filter_map(|l| serde_json::from_str(l).ok())
422            .collect()
423    }
424
425    /// The newest record for one entity, of any kind. State
426    /// derivation is per (entity, kind) — use [`Self::latest_for_kind`]
427    /// there; this remains the "what happened last" accessor.
428    pub fn latest_for(&self, entity: &str) -> Option<CheckRecord> {
429        self.all().into_iter().rev().find(|r| r.entity == entity)
430    }
431
432    /// The newest record for one entity of one kind. A later check of
433    /// the OTHER kind never supersedes it: the two derivations answer
434    /// different questions.
435    pub fn latest_for_kind(&self, entity: &str, kind: CheckKind) -> Option<CheckRecord> {
436        self.all()
437            .into_iter()
438            .rev()
439            .find(|r| r.entity == entity && r.resolved_kind() == Some(kind))
440    }
441}
442
443#[cfg(test)]
444mod tests {
445    use super::*;
446    use tempfile::TempDir;
447
448    fn rec(entity: &str, verdict: &str, hash: &str) -> CheckRecord {
449        CheckRecord {
450            ts: 1,
451            entity: entity.to_string(),
452            verdict: verdict.to_string(),
453            method: None,
454            entity_hash: hash.to_string(),
455            actor: "cli".to_string(),
456            client: None,
457            role: "checker".to_string(),
458            identity: None,
459            kind: None,
460            schema_ref: None,
461            finding: None,
462        }
463    }
464
465    #[test]
466    fn state_derivation_covers_all_four_states() {
467        assert_eq!(derive_state(None, "h1"), CheckState::NeverChecked);
468        let ok = rec("m--e", "ok", "h1");
469        assert_eq!(derive_state(Some(&ok), "h1"), CheckState::CheckedOk);
470        assert_eq!(derive_state(Some(&ok), "h2"), CheckState::CheckStale);
471        let failed = rec("m--e", "failed", "h1");
472        assert_eq!(derive_state(Some(&failed), "h1"), CheckState::CheckFailed);
473        // A failed check on changed content is stale too — the verdict
474        // no longer speaks to current content either way.
475        assert_eq!(derive_state(Some(&failed), "h2"), CheckState::CheckStale);
476    }
477
478    #[test]
479    fn ledger_appends_and_serves_newest_per_entity() {
480        let tmp = TempDir::new().unwrap();
481        let ledger = CheckLedger::for_workspace(tmp.path());
482        assert!(ledger.latest_for("m--a").is_none());
483        ledger.record(&rec("m--a", "failed", "h1")).unwrap();
484        ledger.record(&rec("m--b", "ok", "h9")).unwrap();
485        ledger.record(&rec("m--a", "ok", "h2")).unwrap();
486        let latest = ledger.latest_for("m--a").unwrap();
487        assert_eq!(latest.verdict, "ok");
488        assert_eq!(latest.entity_hash, "h2");
489        // Supersession never erases: all three records remain.
490        assert_eq!(ledger.all().len(), 3);
491    }
492
493    #[test]
494    fn verdict_vocabulary_is_closed() {
495        assert!(Verdict::from_wire("ok").is_some());
496        assert!(Verdict::from_wire("failed").is_some());
497        assert!(Verdict::from_wire("passed").is_none());
498        assert!(Verdict::from_wire("OK").is_none());
499    }
500
501    fn conf(entity: &str, verdict: &str, hash: &str, pin: &str) -> CheckRecord {
502        CheckRecord {
503            kind: Some("conformance".to_string()),
504            schema_ref: Some(pin.to_string()),
505            ..rec(entity, verdict, hash)
506        }
507    }
508
509    #[test]
510    fn kind_vocabulary_is_closed() {
511        assert!(CheckKind::from_wire("verification").is_some());
512        assert!(CheckKind::from_wire("conformance").is_some());
513        assert!(CheckKind::from_wire("semantic").is_none());
514        assert!(CheckKind::from_wire("Conformance").is_none());
515    }
516
517    /// Criterion 5: a pre-kind ledger line (no `kind` field) parses
518    /// and derives as a `verification` record, byte-for-byte the old
519    /// shape on the write side too.
520    #[test]
521    fn legacy_lines_read_as_verification() {
522        let legacy = r#"{"ts":1,"entity":"m--e","verdict":"ok","entity_hash":"h1","actor":"cli","role":"checker"}"#;
523        let parsed: CheckRecord = serde_json::from_str(legacy).unwrap();
524        assert_eq!(parsed.resolved_kind(), Some(CheckKind::Verification));
525        // A freshly built verification record serialises with no kind
526        // and no schema_ref key at all.
527        let fresh = rec("m--e", "ok", "h1");
528        let line = serde_json::to_string(&fresh).unwrap();
529        assert!(!line.contains("kind"));
530        assert!(!line.contains("schema_ref"));
531        // An identity-less record carries no identity key either —
532        // pre-plan-15 lines and identity-less callers stay
533        // byte-identical.
534        assert!(!line.contains("identity"));
535    }
536
537    /// Criterion 3: state derives per (entity, kind) — a later check
538    /// of the other kind does not supersede.
539    #[test]
540    fn latest_is_per_kind() {
541        let tmp = TempDir::new().unwrap();
542        let ledger = CheckLedger::for_workspace(tmp.path());
543        ledger.record(&rec("m--a", "ok", "h1")).unwrap();
544        ledger
545            .record(&conf("m--a", "failed", "h1", "planning@1.0.0"))
546            .unwrap();
547        let v = ledger
548            .latest_for_kind("m--a", CheckKind::Verification)
549            .unwrap();
550        assert_eq!(v.verdict, "ok");
551        let c = ledger
552            .latest_for_kind("m--a", CheckKind::Conformance)
553            .unwrap();
554        assert_eq!(c.verdict, "failed");
555        assert_eq!(c.schema_ref.as_deref(), Some("planning@1.0.0"));
556    }
557
558    /// Criterion 4: a conformance verdict is stale on a content move
559    /// AND on a pin move; a verification verdict ignores pin moves.
560    #[test]
561    fn conformance_stales_on_pin_move_verification_does_not() {
562        let c = conf("m--e", "ok", "h1", "planning@1.0.0");
563        assert_eq!(
564            derive_state_pinned(Some(&c), "h1", Some("planning@1.0.0")),
565            CheckState::CheckedOk
566        );
567        assert_eq!(
568            derive_state_pinned(Some(&c), "h2", Some("planning@1.0.0")),
569            CheckState::CheckStale
570        );
571        assert_eq!(
572            derive_state_pinned(Some(&c), "h1", Some("planning@2.0.0")),
573            CheckState::CheckStale
574        );
575        // The mem losing its pin stales the verdict too.
576        assert_eq!(
577            derive_state_pinned(Some(&c), "h1", None),
578            CheckState::CheckStale
579        );
580        // Verification: unaffected by any pin argument.
581        let v = rec("m--e", "ok", "h1");
582        assert_eq!(
583            derive_state_pinned(Some(&v), "h1", Some("planning@9.0.0")),
584            CheckState::CheckedOk
585        );
586        assert_eq!(derive_state(Some(&v), "h1"), CheckState::CheckedOk);
587    }
588
589    // --- findings and open kinds ---
590
591    #[test]
592    fn finding_shape_is_fixed_and_validated_whole() {
593        let ok = CheckFinding::from_json(serde_json::json!({
594            "code": "hidden-premise", "message": "The step assumes X.", "section": "step"
595        }))
596        .unwrap();
597        assert_eq!(ok.code, "hidden-premise");
598        assert_eq!(ok.section.as_deref(), Some("step"));
599        for bad in [
600            serde_json::json!({ "message": "no code" }),
601            serde_json::json!({ "code": "x" }),
602            serde_json::json!({ "code": "", "message": "empty code" }),
603            serde_json::json!({ "code": "x", "message": "   " }),
604            serde_json::json!({ "code": "x", "message": "m", "severity": "high" }),
605            serde_json::json!({ "code": "x", "message": "m", "section": "" }),
606        ] {
607            let err = CheckFinding::from_json(bad.clone()).unwrap_err();
608            assert!(err.contains("shape"), "{bad}: {err}");
609        }
610    }
611
612    #[test]
613    fn open_kinds_parse_only_with_the_prefix_and_never_resolve_to_an_engine_kind() {
614        assert_eq!(
615            RecordKind::from_wire("verification"),
616            Some(RecordKind::Engine(CheckKind::Verification))
617        );
618        assert_eq!(
619            RecordKind::from_wire("x-step-walk"),
620            Some(RecordKind::Foreign("x-step-walk".to_string()))
621        );
622        for bad in ["step-walk", "x-", "x-Step", "x--a", "x-a-", "X-a"] {
623            assert!(RecordKind::from_wire(bad).is_none(), "{bad}");
624        }
625        assert!(RecordKind::vocabulary_hint().contains("x-<name>"));
626        let mut r = rec("m--e", "ok", "h");
627        r.kind = Some("x-step-walk".to_string());
628        assert_eq!(r.resolved_kind(), None);
629        assert_eq!(r.foreign_kind(), Some("x-step-walk"));
630        r.kind = None;
631        assert_eq!(r.resolved_kind(), Some(CheckKind::Verification));
632        r.kind = Some("conformance".to_string());
633        assert_eq!(r.resolved_kind(), Some(CheckKind::Conformance));
634        // A pre-`x-` unrecognised kind keeps its legacy reading.
635        r.kind = Some("mystery".to_string());
636        assert_eq!(r.resolved_kind(), Some(CheckKind::Verification));
637    }
638
639    #[test]
640    fn pre_finding_ledger_lines_parse_and_derive_unchanged_and_findings_round_trip() {
641        let tmp = TempDir::new().unwrap();
642        let ledger = CheckLedger::for_workspace(tmp.path());
643        let dir = check_ledger_path(tmp.path());
644        std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
645        // A line written before findings existed: no `finding`, no `kind`.
646        std::fs::write(
647            &dir,
648            "{\"ts\":1,\"entity\":\"m--e\",\"verdict\":\"failed\",\"entity_hash\":\"h\",\"actor\":\"cli\",\"role\":\"unspecified\"}\n",
649        )
650        .unwrap();
651        let old = ledger
652            .latest_for_kind("m--e", CheckKind::Verification)
653            .unwrap();
654        assert!(old.finding.is_none());
655        assert_eq!(derive_state(Some(&old), "h"), CheckState::CheckFailed);
656
657        let mut with = rec("m--e", "failed", "h");
658        with.ts = 2;
659        with.finding = Some(CheckFinding {
660            code: "hidden-premise".into(),
661            section: Some("step".into()),
662            message: "The step assumes X.".into(),
663            evidence: None,
664        });
665        ledger.record(&with).unwrap();
666        // A foreign-kind line beside it moves no verification state.
667        let mut foreign = rec("m--e", "ok", "h");
668        foreign.ts = 3;
669        foreign.kind = Some("x-step-walk".into());
670        ledger.record(&foreign).unwrap();
671        let latest = ledger
672            .latest_for_kind("m--e", CheckKind::Verification)
673            .unwrap();
674        assert_eq!(
675            latest.ts, 2,
676            "the foreign record is not the latest verification record"
677        );
678        assert_eq!(latest.finding.as_ref().unwrap().code, "hidden-premise");
679        assert_eq!(derive_state(Some(&latest), "h"), CheckState::CheckFailed);
680        let text = std::fs::read_to_string(&dir).unwrap();
681        assert!(text.contains("\"finding\":{\"code\":\"hidden-premise\",\"section\":\"step\",\"message\":\"The step assumes X.\"}"), "{text}");
682        assert!(text.contains("\"kind\":\"x-step-walk\""));
683        assert_eq!(text.lines().count(), 3, "append-only");
684    }
685}