Skip to main content

vitrify_cli/cmd/
audit.rs

1//! `vitrify audit` — the seven checks. Report-only by default;
2//! `--fix-leases` / `--apply-stale` edit the current worktree and leave
3//! committing to the caller. Check 4 runs the SDD's own Verification
4//! commands through [`crate::gate`] — the one sanctioned shell use.
5
6use std::path::Path;
7
8use vitrify_core::audit::{self, Finding, Options, StateEdit};
9use vitrify_core::journal::{self, Event};
10use vitrify_core::model::{self, Instance, SddHandle, UtcTime};
11use vitrify_core::{CoreError, ledger, yamlish};
12
13use crate::gate::MemoRunner;
14use crate::out::{J, diag, emit};
15
16pub struct Flags {
17    pub json: bool,
18    pub fix_leases: bool,
19    pub apply_stale: bool,
20    pub skip_rotten: bool,
21    pub journal: bool,
22    pub sdd: Option<String>,
23    /// Every SDD of the repository.
24    pub all: bool,
25}
26
27fn append_event(
28    inst: &Instance,
29    event: &str,
30    unit: Option<&str>,
31    claim_seq: Option<i64>,
32    cause: Option<&str>,
33    findings: Option<i64>,
34) -> Result<(), CoreError> {
35    let handle = inst.handle();
36    let (events, _) = journal::read(&handle)?;
37    let e = Event {
38        seq: events.last().map(|e| e.seq).unwrap_or(0) + 1,
39        at: UtcTime::now().format(),
40        event: event.to_string(),
41        unit: unit.map(str::to_string),
42        actor: Some("audit".to_string()),
43        claim_seq,
44        cause: cause.map(str::to_string),
45        findings,
46        sdd: inst.meta.get_str_or("version", "0.0.0").to_string(),
47        ..Default::default()
48    };
49    journal::append_line(&handle, &journal::render_line(&e))?;
50    Ok(())
51}
52
53/// Apply the audit's state edits to the working tree — lapsed leases first,
54/// then Stale marks — appending one journal event each.
55/// Returns (leases released, units marked Stale). The caller regenerates the
56/// ledger and commits.
57pub fn apply_edits(inst: &Instance, edits: &[StateEdit]) -> Result<(usize, usize), CoreError> {
58    let handle = inst.handle();
59    let mut fixed_leases = 0usize;
60    let mut marked_stale = 0usize;
61    for edit in edits {
62        if let StateEdit::FixLease { unit, claim_seq } = edit {
63            let Some(u) = inst.unit(unit).cloned() else {
64                continue;
65            };
66            model::rewrite_unit_meta(&handle, &u, |inner| {
67                let b = yamlish::set_scalar_in_place(inner, "status", "Ready");
68                let b = yamlish::set_scalar_in_place(&b, "claimed_by", "—");
69                yamlish::set_scalar_in_place(&b, "claim_expires", "—")
70            })?;
71            append_event(inst, "release", Some(unit), Some(*claim_seq), None, None)?;
72            fixed_leases += 1;
73        }
74    }
75    for edit in edits {
76        if let StateEdit::ApplyStale { unit, cause } = edit {
77            let Some(u) = inst.unit(unit).cloned() else {
78                continue;
79            };
80            model::rewrite_unit_meta(&handle, &u, |inner| {
81                yamlish::set_scalar_in_place(inner, "status", "Stale")
82            })?;
83            append_event(inst, "stale", Some(unit), None, Some(cause), None)?;
84            marked_stale += 1;
85        }
86    }
87    Ok((fixed_leases, marked_stale))
88}
89
90/// Run the seven checks over `inst`, writing nothing: the findings, and the
91/// state edits `opts`' fixing flags ask for.
92fn examine(
93    root: &Path,
94    inst: &Instance,
95    opts: Options,
96) -> Result<(Vec<Finding>, Vec<StateEdit>), CoreError> {
97    let skip_rotten = opts.skip_rotten;
98    let opts = super::audit_options(opts, root, inst);
99    // check 4: every Verified unit's rows, each distinct command once,
100    // run.gate_jobs at a time (one per core unless configured)
101    let runner: Box<dyn audit::CommandRunner> = if skip_rotten {
102        Box::new(crate::gate::ShRunner)
103    } else {
104        let cfg = super::load_config(&vitrify_core::config::Overrides::default())?;
105        Box::new(MemoRunner::for_verified(
106            inst,
107            root,
108            cfg.run.rows_at_once(),
109        )?)
110    };
111    audit::run(inst, root, &opts, runner.as_ref(), UtcTime::now())
112}
113
114/// The audit's findings for one SDD, report-only: no fix is applied and
115/// nothing is written. Check 4 runs unless `skip_rotten`.
116pub fn findings(
117    root: &Path,
118    inst: &Instance,
119    skip_rotten: bool,
120) -> Result<Vec<Finding>, CoreError> {
121    let opts = Options {
122        skip_rotten,
123        ..Default::default()
124    };
125    Ok(examine(root, inst, opts)?.0)
126}
127
128/// Audit one SDD: run the checks, apply what the fixing flags ask for,
129/// append the `audit` event. Returns the findings as found, before any fix.
130fn audit_one(root: &Path, sdd: &SddHandle, flags: &Flags) -> Result<Vec<Finding>, CoreError> {
131    let inst = Instance::load(sdd.clone())?;
132    let opts = Options {
133        skip_rotten: flags.skip_rotten,
134        fix_leases: flags.fix_leases,
135        apply_stale: flags.apply_stale,
136        ..Default::default()
137    };
138    let (findings, edits) = examine(root, &inst, opts)?;
139
140    let (fixed_leases, marked_stale) = apply_edits(&inst, &edits)?;
141    if fixed_leases > 0 || marked_stale > 0 {
142        let fresh = Instance::load(inst.handle())?;
143        ledger::regen(&fresh, &UtcTime::now().format_date())?;
144    }
145    if fixed_leases > 0 {
146        diag(&format!(
147            "note: {fixed_leases} lapsed lease(s) returned to Ready — commit this"
148        ));
149    }
150    if marked_stale > 0 {
151        diag(&format!(
152            "note: {marked_stale} unit(s) marked Stale — commit this"
153        ));
154    }
155    if flags.journal {
156        append_event(
157            &inst,
158            "audit",
159            None,
160            None,
161            None,
162            Some(findings.len() as i64),
163        )?;
164    }
165    Ok(findings)
166}
167
168fn report_json(findings: &[Finding]) -> Vec<(String, J)> {
169    vec![
170        ("clean".into(), J::Bool(findings.is_empty())),
171        (
172            "findings".into(),
173            J::Arr(findings.iter().map(finding_json).collect()),
174        ),
175    ]
176}
177
178/// The report's lines: the clean line, or one per finding — each under
179/// `name` when several SDDs are being reported on.
180fn report_text(findings: &[Finding], name: Option<&str>) {
181    let under = name.map(|n| format!("{n}: ")).unwrap_or_default();
182    if findings.is_empty() {
183        emit(&format!("{under}audit clean (7/7 checks)"));
184    }
185    for f in findings {
186        emit(&format!(
187            "{under}[check {}] {}: {} → {}",
188            f.check, f.subject, f.cause, f.remediation
189        ));
190    }
191}
192
193pub fn run(flags: Flags) -> Result<u8, CoreError> {
194    let root = super::repo_root();
195    let sdds = super::targets(&root, flags.sdd.as_deref(), flags.all, &super::cwd())?;
196    if !flags.all {
197        let findings = audit_one(&root, &sdds[0], &flags)?;
198        if flags.json {
199            emit(&J::Obj(report_json(&findings)).dumps_indent2());
200        } else {
201            report_text(&findings, None);
202        }
203        return Ok(if findings.is_empty() { 0 } else { 2 });
204    }
205
206    let mut reports: Vec<J> = Vec::new();
207    let code = super::each(&root, &sdds, |sdd| {
208        let findings = audit_one(&root, sdd, &flags)?;
209        let name = super::label(sdd, &root);
210        if flags.json {
211            let mut pairs = vec![
212                ("sdd".into(), J::s(name)),
213                ("root".into(), J::s(super::shown(&root, &sdd.root))),
214            ];
215            pairs.extend(report_json(&findings));
216            reports.push(J::Obj(pairs));
217        } else {
218            report_text(&findings, Some(&name));
219        }
220        Ok(if findings.is_empty() { 0 } else { 2 })
221    });
222    if flags.json {
223        emit(&J::Arr(reports).dumps_indent2());
224    }
225    Ok(code)
226}
227
228fn finding_json(f: &Finding) -> J {
229    J::Obj(vec![
230        ("check".into(), J::Int(f.check as i64)),
231        ("subject".into(), J::s(f.subject.clone())),
232        ("cause".into(), J::s(f.cause.clone())),
233        ("remediation".into(), J::s(f.remediation.clone())),
234    ])
235}