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. Then the dirty units: Verified units a committed
5//! change reached since their last recorded check, each with the changed
6//! paths that made it so — listed, never re-checked; that is a run's job.
7//! Writes nothing.
8
9use std::path::Path;
10
11use vitrify_core::CoreError;
12use vitrify_core::cascade::{Anchors, Dirty, Why};
13use vitrify_core::config::Overrides;
14use vitrify_core::graph::{self, render_path};
15use vitrify_core::journal as core_journal;
16use vitrify_core::model::{Instance, SddHandle, is_empty_marker};
17
18use crate::git::Git;
19use crate::incremental::dirty::{self, Cascade, DirtySet, Mode, Snapshot};
20use crate::out::{J, diag, emit};
21
22pub struct Flags {
23    pub sdd: Option<String>,
24    /// Every SDD of the repository.
25    pub all: bool,
26    /// Skip audit check 4 (re-running Verified units' Verification tables).
27    pub skip_rotten: bool,
28    pub json: bool,
29}
30
31/// One finding, as `check` reports it.
32struct Item {
33    /// `lint`, `audit`, `journal`, `ledger` or `pin`.
34    source: &'static str,
35    /// The check's own name within its source (`L4`, `5`), where it has one.
36    check: Option<String>,
37    subject: String,
38    cause: String,
39    remediation: String,
40}
41
42/// What `check` found in one SDD.
43struct Report {
44    sdd: String,
45    root: String,
46    findings: Vec<Item>,
47    notes: Vec<String>,
48    /// Its dirty units, sorted by unit id.
49    dirty: Vec<Dirty>,
50    /// Its recorded checks.
51    anchors: Anchors,
52    code: u8,
53}
54
55/// `changed`, `no-anchor`, `unresolved-anchor` or `everything`: why a unit
56/// is dirty, as `--json` names it.
57fn why_code(why: &Why) -> &'static str {
58    match why {
59        Why::Paths(_) => "changed",
60        Why::NoAnchor => "no-anchor",
61        Why::NoDiff(_) => "unresolved-anchor",
62        Why::Everything => "everything",
63    }
64}
65
66fn dirty_json(d: &Dirty, anchor: Option<String>) -> J {
67    let paths = match &d.why {
68        Why::Paths(reasons) => reasons
69            .iter()
70            .map(|r| {
71                J::Obj(vec![
72                    ("path".into(), J::s(r.path.clone())),
73                    ("owner".into(), J::s(r.owner.describe())),
74                ])
75            })
76            .collect(),
77        _ => Vec::new(),
78    };
79    J::Obj(vec![
80        ("unit".into(), J::s(d.node.unit.clone())),
81        ("anchor".into(), J::opt_str(anchor)),
82        ("why".into(), J::s(why_code(&d.why))),
83        ("paths".into(), J::Arr(paths)),
84    ])
85}
86
87impl Report {
88    fn add(
89        &mut self,
90        source: &'static str,
91        check: Option<String>,
92        (subject, cause, remediation): (String, String, String),
93    ) {
94        self.code = self.code.max(match source {
95            "journal" | "ledger" => 3,
96            _ => 2,
97        });
98        self.findings.push(Item {
99            source,
100            check,
101            subject,
102            cause,
103            remediation,
104        });
105    }
106
107    fn json(&self) -> J {
108        J::Obj(vec![
109            ("sdd".into(), J::s(self.sdd.clone())),
110            ("root".into(), J::s(self.root.clone())),
111            ("clean".into(), J::Bool(self.findings.is_empty())),
112            (
113                "findings".into(),
114                J::Arr(
115                    self.findings
116                        .iter()
117                        .map(|x| {
118                            J::Obj(vec![
119                                ("source".into(), J::s(x.source)),
120                                ("check".into(), x.check.clone().map_or(J::Null, J::s)),
121                                ("subject".into(), J::s(x.subject.clone())),
122                                ("cause".into(), J::s(x.cause.clone())),
123                                ("remediation".into(), J::s(x.remediation.clone())),
124                            ])
125                        })
126                        .collect(),
127                ),
128            ),
129            (
130                "notes".into(),
131                J::Arr(self.notes.iter().map(|n| J::s(n.clone())).collect()),
132            ),
133            (
134                "dirty".into(),
135                J::Arr(
136                    self.dirty
137                        .iter()
138                        .map(|d| dirty_json(d, self.anchor_of(d)))
139                        .collect(),
140                ),
141            ),
142        ])
143    }
144
145    /// The anchor a dirty unit's reason names, when it has one.
146    fn anchor_of(&self, d: &Dirty) -> Option<String> {
147        match &d.why {
148            Why::NoDiff(anchor) => Some(anchor.clone()),
149            Why::NoAnchor | Why::Everything => None,
150            Why::Paths(_) => self.anchors.unit(&d.node.unit).map(str::to_string),
151        }
152    }
153
154    fn emit_text(&self) {
155        for x in &self.findings {
156            let source = match &x.check {
157                Some(check) => format!("{} {check}", x.source),
158                None => x.source.to_string(),
159            };
160            emit(&format!(
161                "{}: [{source}] {}: {} → {}",
162                self.sdd, x.subject, x.cause, x.remediation
163            ));
164        }
165        for n in &self.notes {
166            emit(&format!("{}: note: {n}", self.sdd));
167        }
168        for d in &self.dirty {
169            emit(&format!(
170                "{}: dirty {}: {}",
171                self.sdd,
172                d.node.unit,
173                dirty::describe(&d.why)
174            ));
175        }
176    }
177}
178
179/// A unit has build state: a status beyond Draft or Ready, a claim, or a
180/// recorded trace.
181fn has_build_state(inst: &Instance) -> bool {
182    inst.units.iter().any(|u| {
183        !matches!(u.meta.get_str_or("status", "Draft"), "Draft" | "Ready")
184            || !is_empty_marker(u.meta.get_str_or("claimed_by", "").trim())
185            || !is_empty_marker(u.meta.get_str_or("claim_expires", "").trim())
186            || u.meta.get_map("trace").is_some_and(|m| !m.is_empty())
187    })
188}
189
190fn check_one(
191    root: &Path,
192    sdd: &SddHandle,
193    budget: i64,
194    skip_rotten: bool,
195    dirty: Option<&DirtySet>,
196) -> Result<Report, CoreError> {
197    let inst = Instance::load(sdd.clone())?;
198    let at = super::shown(root, &inst.root);
199    let (events, _) = core_journal::read(&inst.handle())?;
200    let slug = graph::slug_of(&inst);
201    let mut report = Report {
202        sdd: super::label(sdd, root),
203        root: at.clone(),
204        findings: Vec::new(),
205        notes: Vec::new(),
206        dirty: dirty
207            .map(|set| set.of_sdd(slug).cloned().collect())
208            .unwrap_or_default(),
209        anchors: Anchors::from_events(&events),
210        code: 0,
211    };
212    let has_journal = !events.is_empty();
213    let replayed = super::journal::replayed(&inst)?;
214
215    // lint: --built once the SDD has build state. L9 is the pin source's.
216    let lint = if has_journal || has_build_state(&inst) {
217        super::lint::pre_run_findings(&inst, root, budget)?
218    } else {
219        super::lint::check_all(&inst, root, budget)?
220    };
221    for x in lint.into_iter().filter(|x| x.check != "L9") {
222        report.add(
223            "lint",
224            Some(x.check.to_string()),
225            (x.subject, x.cause, x.remediation),
226        );
227    }
228
229    // audit: check 6's replay findings are the journal source's
230    for x in super::audit::findings(root, &inst, skip_rotten)? {
231        let replay_finding =
232            x.check == 6 && (x.subject == "journal" || x.cause.starts_with("journal projects "));
233        if replayed.is_some() && replay_finding {
234            continue;
235        }
236        report.add(
237            "audit",
238            Some(x.check.to_string()),
239            (x.subject, x.cause, x.remediation),
240        );
241    }
242
243    if let Some(r) = &replayed {
244        for x in r.findings() {
245            report.add("journal", None, x);
246        }
247    }
248
249    if let Some((subject, cause)) = super::ledger::mismatch(&inst, has_journal)? {
250        report.add(
251            "ledger",
252            None,
253            (subject, cause, format!("vitrify ledger regen --sdd {at}")),
254        );
255    }
256
257    for x in super::lint::pin_findings(&inst, &super::peers(root), &at)? {
258        report.add("pin", None, x);
259    }
260
261    for (q, blocks) in super::questions::open(sdd)? {
262        report.notes.push(if blocks.is_empty() {
263            format!("{q} is open")
264        } else {
265            format!("{q} is open (blocks {})", blocks.join(", "))
266        });
267    }
268    Ok(report)
269}
270
271/// The repository's dirty units at `HEAD`, from the checkout at `root`.
272/// `None` outside a git repository, before its first commit, and — with a
273/// note on stderr — when the SDDs cannot all be read or the unit graph has
274/// a cycle: there is nothing to cascade along then.
275fn dirty_units(root: &Path) -> Option<DirtySet> {
276    let git = Git::new(root);
277    let head = git.resolve_commit("HEAD").ok().flatten()?;
278    let not_computed = |why: &str| diag(&format!("note: dirty units not computed: {why}"));
279    let snapshot = match Snapshot::load(&git, root, &head) {
280        Ok(s) => s,
281        Err(e) => {
282            let text = e.to_string();
283            not_computed(text.strip_prefix("error: ").unwrap_or(&text));
284            return None;
285        }
286    };
287    match snapshot.dirty(&git, Mode::Changes) {
288        Ok(Cascade::Resolved(set)) => Some(set),
289        Ok(Cascade::Cycles(cycles)) => {
290            let paths: Vec<String> = cycles.cycles.iter().map(|c| render_path(c)).collect();
291            not_computed(&format!("the unit graph has a cycle: {}", paths.join("; ")));
292            None
293        }
294        Err(e) => {
295            let text = e.to_string();
296            not_computed(text.strip_prefix("error: ").unwrap_or(&text));
297            None
298        }
299    }
300}
301
302fn plural(n: usize, one: &str) -> String {
303    if n == 1 {
304        format!("1 {one}")
305    } else {
306        format!("{n} {one}s")
307    }
308}
309
310pub fn run(flags: Flags) -> Result<u8, CoreError> {
311    let root = super::repo_root();
312    let sdds = super::targets(&root, flags.sdd.as_deref(), flags.all, &super::cwd())?;
313    let budget = super::load_config(&Overrides::default())?
314        .lint
315        .readset_budget_bytes;
316
317    let dirty = dirty_units(&root);
318    let mut reports: Vec<Report> = Vec::new();
319    let code = if flags.all {
320        super::each(&root, &sdds, |sdd| {
321            let report = check_one(&root, sdd, budget, flags.skip_rotten, dirty.as_ref())?;
322            let code = report.code;
323            if !flags.json {
324                report.emit_text();
325            }
326            reports.push(report);
327            Ok(code)
328        })
329    } else {
330        let report = check_one(&root, &sdds[0], budget, flags.skip_rotten, dirty.as_ref())?;
331        if !flags.json {
332            report.emit_text();
333        }
334        let code = report.code;
335        reports.push(report);
336        code
337    };
338
339    if flags.json {
340        let out = if flags.all {
341            J::Arr(reports.iter().map(Report::json).collect())
342        } else {
343            reports[0].json()
344        };
345        emit(&out.dumps_indent2());
346        return Ok(code);
347    }
348
349    let findings: usize = reports.iter().map(|r| r.findings.len()).sum();
350    let unclean = reports.iter().filter(|r| !r.findings.is_empty()).count();
351    let unchecked = sdds.len() - reports.len();
352    let dirty: usize = reports.iter().map(|r| r.dirty.len()).sum();
353    let mut line = if findings == 0 && unchecked == 0 {
354        format!("check clean: {}", plural(sdds.len(), "SDD"))
355    } else {
356        let mut line = format!(
357            "check: {} in {unclean} of {}",
358            plural(findings, "finding"),
359            plural(sdds.len(), "SDD")
360        );
361        if unchecked > 0 {
362            line.push_str(&format!("; {unchecked} not checked"));
363        }
364        line
365    };
366    if dirty > 0 {
367        line.push_str(&format!("; {} dirty", plural(dirty, "unit")));
368    }
369    emit(&line);
370    Ok(code)
371}