1use std::io::Write;
37use std::path::{Path, PathBuf};
38
39use serde::{Deserialize, Serialize};
40
41pub const VERDICTS: [&str; 2] = ["ok", "failed"];
44
45pub const CHECK_KINDS: [&str; 2] = ["verification", "conformance"];
55
56pub const FOREIGN_KIND_PREFIX: &str = "x-";
63
64pub const INVALID_CHECK_FINDING_CODE: &str = "INVALID_CHECK_FINDING";
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum CheckKind {
70 Verification,
71 Conformance,
72}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
77pub enum RecordKind {
78 Engine(CheckKind),
79 Foreign(String),
80}
81
82impl RecordKind {
83 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 pub fn engine_kind(&self) -> Option<CheckKind> {
103 match self {
104 Self::Engine(k) => Some(*k),
105 Self::Foreign(_) => None,
106 }
107 }
108
109 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
134#[serde(deny_unknown_fields)]
135pub struct CheckFinding {
136 pub code: String,
138 #[serde(default, skip_serializing_if = "Option::is_none")]
140 pub section: Option<String>,
141 pub message: String,
143 #[serde(default, skip_serializing_if = "Option::is_none")]
145 pub evidence: Option<String>,
146}
147
148impl CheckFinding {
149 pub const SHAPE: &'static str =
151 "{code: <non-empty>, message: <non-empty>, section?: <key>, evidence?: <text>}";
152
153 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
218pub enum Verdict {
219 Ok,
220 Failed,
221}
222
223impl Verdict {
224 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#[derive(Debug, Clone, Serialize, Deserialize)]
243pub struct CheckRecord {
244 pub ts: u64,
246 pub entity: String,
248 pub verdict: String,
250 #[serde(default, skip_serializing_if = "Option::is_none")]
253 pub method: Option<String>,
254 pub entity_hash: String,
257 pub actor: String,
259 #[serde(default, skip_serializing_if = "Option::is_none")]
261 pub client: Option<String>,
262 pub role: String,
266 #[serde(default, skip_serializing_if = "Option::is_none")]
272 pub identity: Option<String>,
273 #[serde(default, skip_serializing_if = "Option::is_none")]
279 pub kind: Option<String>,
280 #[serde(default, skip_serializing_if = "Option::is_none")]
285 pub schema_ref: Option<String>,
286 #[serde(default, skip_serializing_if = "Option::is_none")]
291 pub finding: Option<CheckFinding>,
292}
293
294impl CheckRecord {
295 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 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#[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
335pub fn derive_state(latest: Option<&CheckRecord>, current_hash: &str) -> CheckState {
340 derive_state_pinned(latest, current_hash, None)
341}
342
343pub 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
368fn 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
377pub fn check_ledger_path(workspace_root: &Path) -> PathBuf {
379 checks_dir(workspace_root).join("checks.jsonl")
380}
381
382#[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 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 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 pub fn latest_for(&self, entity: &str) -> Option<CheckRecord> {
429 self.all().into_iter().rev().find(|r| r.entity == entity)
430 }
431
432 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 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 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 #[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 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 assert!(!line.contains("identity"));
535 }
536
537 #[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 #[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 assert_eq!(
577 derive_state_pinned(Some(&c), "h1", None),
578 CheckState::CheckStale
579 );
580 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 #[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 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 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 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}