Skip to main content

vitrify_cli/cmd/
check.rs

1//! `vitrify check` — every read-only consistency check vitrify has, over one
2//! SDD or all of them: lint, the audit, the journal replay, the ledger check
3//! and the pin states, each finding with its source and its remediation;
4//! open questions as notes. Writes nothing.
5
6use std::path::Path;
7
8use vitrify_core::CoreError;
9use vitrify_core::config::Overrides;
10use vitrify_core::journal as core_journal;
11use vitrify_core::model::{Instance, SddHandle, is_empty_marker};
12
13use crate::out::{J, emit};
14
15pub struct Flags {
16    pub sdd: Option<String>,
17    /// Every SDD of the repository.
18    pub all: bool,
19    /// Skip audit check 4 (re-running Verified units' Verification tables).
20    pub skip_rotten: bool,
21    pub json: bool,
22}
23
24/// One finding, as `check` reports it.
25struct Item {
26    /// `lint`, `audit`, `journal`, `ledger` or `pin`.
27    source: &'static str,
28    /// The check's own name within its source (`L4`, `5`), where it has one.
29    check: Option<String>,
30    subject: String,
31    cause: String,
32    remediation: String,
33}
34
35/// What `check` found in one SDD.
36struct Report {
37    sdd: String,
38    root: String,
39    findings: Vec<Item>,
40    notes: Vec<String>,
41    code: u8,
42}
43
44impl Report {
45    fn add(
46        &mut self,
47        source: &'static str,
48        check: Option<String>,
49        (subject, cause, remediation): (String, String, String),
50    ) {
51        self.code = self.code.max(match source {
52            "journal" | "ledger" => 3,
53            _ => 2,
54        });
55        self.findings.push(Item {
56            source,
57            check,
58            subject,
59            cause,
60            remediation,
61        });
62    }
63
64    fn json(&self) -> J {
65        J::Obj(vec![
66            ("sdd".into(), J::s(self.sdd.clone())),
67            ("root".into(), J::s(self.root.clone())),
68            ("clean".into(), J::Bool(self.findings.is_empty())),
69            (
70                "findings".into(),
71                J::Arr(
72                    self.findings
73                        .iter()
74                        .map(|x| {
75                            J::Obj(vec![
76                                ("source".into(), J::s(x.source)),
77                                ("check".into(), x.check.clone().map_or(J::Null, J::s)),
78                                ("subject".into(), J::s(x.subject.clone())),
79                                ("cause".into(), J::s(x.cause.clone())),
80                                ("remediation".into(), J::s(x.remediation.clone())),
81                            ])
82                        })
83                        .collect(),
84                ),
85            ),
86            (
87                "notes".into(),
88                J::Arr(self.notes.iter().map(|n| J::s(n.clone())).collect()),
89            ),
90        ])
91    }
92
93    fn emit_text(&self) {
94        for x in &self.findings {
95            let source = match &x.check {
96                Some(check) => format!("{} {check}", x.source),
97                None => x.source.to_string(),
98            };
99            emit(&format!(
100                "{}: [{source}] {}: {} → {}",
101                self.sdd, x.subject, x.cause, x.remediation
102            ));
103        }
104        for n in &self.notes {
105            emit(&format!("{}: note: {n}", self.sdd));
106        }
107    }
108}
109
110/// A unit has build state: a status beyond Draft or Ready, a claim, or a
111/// recorded trace.
112fn has_build_state(inst: &Instance) -> bool {
113    inst.units.iter().any(|u| {
114        !matches!(u.meta.get_str_or("status", "Draft"), "Draft" | "Ready")
115            || !is_empty_marker(u.meta.get_str_or("claimed_by", "").trim())
116            || !is_empty_marker(u.meta.get_str_or("claim_expires", "").trim())
117            || u.meta.get_map("trace").is_some_and(|m| !m.is_empty())
118    })
119}
120
121fn check_one(
122    root: &Path,
123    sdd: &SddHandle,
124    budget: i64,
125    skip_rotten: bool,
126) -> Result<Report, CoreError> {
127    let inst = Instance::load(sdd.clone())?;
128    let at = super::shown(root, &inst.root);
129    let mut report = Report {
130        sdd: super::label(sdd, root),
131        root: at.clone(),
132        findings: Vec::new(),
133        notes: Vec::new(),
134        code: 0,
135    };
136    let (events, _) = core_journal::read(&inst.handle())?;
137    let has_journal = !events.is_empty();
138    let replayed = super::journal::replayed(&inst)?;
139
140    // lint: --built once the SDD has build state. L9 is the pin source's.
141    let lint = if has_journal || has_build_state(&inst) {
142        super::lint::pre_run_findings(&inst, root, budget)?
143    } else {
144        super::lint::check_all(&inst, root, budget)?
145    };
146    for x in lint.into_iter().filter(|x| x.check != "L9") {
147        report.add(
148            "lint",
149            Some(x.check.to_string()),
150            (x.subject, x.cause, x.remediation),
151        );
152    }
153
154    // audit: check 6's replay findings are the journal source's
155    for x in super::audit::findings(root, &inst, skip_rotten)? {
156        let replay_finding =
157            x.check == 6 && (x.subject == "journal" || x.cause.starts_with("journal projects "));
158        if replayed.is_some() && replay_finding {
159            continue;
160        }
161        report.add(
162            "audit",
163            Some(x.check.to_string()),
164            (x.subject, x.cause, x.remediation),
165        );
166    }
167
168    if let Some(r) = &replayed {
169        for x in r.findings() {
170            report.add("journal", None, x);
171        }
172    }
173
174    if let Some((subject, cause)) = super::ledger::mismatch(&inst, has_journal)? {
175        report.add(
176            "ledger",
177            None,
178            (subject, cause, format!("vitrify ledger regen --sdd {at}")),
179        );
180    }
181
182    for x in super::lint::pin_findings(&inst, &super::peers(root), &at)? {
183        report.add("pin", None, x);
184    }
185
186    for (q, blocks) in super::questions::open(sdd)? {
187        report.notes.push(if blocks.is_empty() {
188            format!("{q} is open")
189        } else {
190            format!("{q} is open (blocks {})", blocks.join(", "))
191        });
192    }
193    Ok(report)
194}
195
196fn plural(n: usize, one: &str) -> String {
197    if n == 1 {
198        format!("1 {one}")
199    } else {
200        format!("{n} {one}s")
201    }
202}
203
204pub fn run(flags: Flags) -> Result<u8, CoreError> {
205    let root = super::repo_root();
206    let sdds = super::targets(&root, flags.sdd.as_deref(), flags.all, &super::cwd())?;
207    let budget = super::load_config(&Overrides::default())?
208        .lint
209        .readset_budget_bytes;
210
211    let mut reports: Vec<Report> = Vec::new();
212    let code = if flags.all {
213        super::each(&root, &sdds, |sdd| {
214            let report = check_one(&root, sdd, budget, flags.skip_rotten)?;
215            let code = report.code;
216            if !flags.json {
217                report.emit_text();
218            }
219            reports.push(report);
220            Ok(code)
221        })
222    } else {
223        let report = check_one(&root, &sdds[0], budget, flags.skip_rotten)?;
224        if !flags.json {
225            report.emit_text();
226        }
227        let code = report.code;
228        reports.push(report);
229        code
230    };
231
232    if flags.json {
233        let out = if flags.all {
234            J::Arr(reports.iter().map(Report::json).collect())
235        } else {
236            reports[0].json()
237        };
238        emit(&out.dumps_indent2());
239        return Ok(code);
240    }
241
242    let findings: usize = reports.iter().map(|r| r.findings.len()).sum();
243    let unclean = reports.iter().filter(|r| !r.findings.is_empty()).count();
244    let unchecked = sdds.len() - reports.len();
245    if findings == 0 && unchecked == 0 {
246        emit(&format!("check clean: {}", plural(sdds.len(), "SDD")));
247    } else {
248        let mut line = format!(
249            "check: {} in {unclean} of {}",
250            plural(findings, "finding"),
251            plural(sdds.len(), "SDD")
252        );
253        if unchecked > 0 {
254            line.push_str(&format!("; {unchecked} not checked"));
255        }
256        emit(&line);
257    }
258    Ok(code)
259}