Skip to main content

vitrify_cli/cmd/
trace.rs

1//! `vitrify trace record|verify` — the trace verbs, wiring
2//! `vitrify-core::trace` (the only hashing/masking implementation) plus the
3//! stamp edits — and the editorial re-stamp `vitrify change apply` does.
4//! These edit the working tree and leave committing to the caller.
5
6use std::path::PathBuf;
7use std::process::Command;
8
9use vitrify_core::model::{self, Instance, UtcTime};
10use vitrify_core::{CoreError, trace, yamlish};
11
12use crate::cli::StampKind;
13use crate::out::{J, emit};
14
15fn short_head() -> String {
16    let out = Command::new("git")
17        .args(["rev-parse", "--short", "HEAD"])
18        .output();
19    if let Ok(o) = out
20        && o.status.success()
21        && let Ok(s) = String::from_utf8(o.stdout)
22    {
23        let t = s.trim().to_string();
24        if !t.is_empty() {
25            return t;
26        }
27    }
28    "0000000".to_string()
29}
30
31fn load(sdd: Option<&str>, unit: &str) -> Result<(Instance, model::Unit), CoreError> {
32    let root = super::repo_root();
33    let inst = Instance::load(super::resolve_sdd(&root, sdd, &super::cwd())?)?;
34    let u = inst
35        .unit(unit)
36        .cloned()
37        .ok_or_else(|| CoreError::refusal(4, format!("error: unit not found: {unit}")))?;
38    Ok((inst, u))
39}
40
41/// The unit's trace as its current inputs give it; a missing input (a
42/// consumed contract that does not exist) refuses, exit 4.
43pub fn current(inst: &Instance, u: &model::Unit) -> Result<trace::TraceMap, CoreError> {
44    let (trace_map, problems) = trace::compute(inst, u)?;
45    if !problems.is_empty() {
46        let msg = problems
47            .iter()
48            .map(|p| format!("error: {}: {p}", u.unit))
49            .collect::<Vec<_>>()
50            .join("\n");
51        return Err(CoreError::refusal(4, msg));
52    }
53    Ok(trace_map)
54}
55
56/// The editorial re-stamp: rewrite the unit's recorded trace to `trace_map`
57/// (its [`current`] trace), keeping its status and stamps. Returns the file
58/// written.
59pub fn restamp(
60    inst: &Instance,
61    u: &model::Unit,
62    trace_map: &trace::TraceMap,
63) -> Result<PathBuf, CoreError> {
64    model::rewrite_unit_meta(&inst.handle(), u, |inner| {
65        yamlish::set_map_in_place(inner, "trace", trace_map)
66    })
67}
68
69pub fn record(
70    unit: &str,
71    stamp: StampKind,
72    commit: Option<&str>,
73    sdd: Option<&str>,
74) -> Result<u8, CoreError> {
75    let (inst, u) = load(sdd, unit)?;
76    let trace_map = current(&inst, &u)?;
77
78    let version = inst.meta.get_str_or("version", "0.0.0").to_string();
79    let commit = commit.map(str::to_string).unwrap_or_else(short_head);
80    let stamp_text = model::render_stamp(&UtcTime::now().format_date(), &version, &commit);
81    let stamp_name = match stamp {
82        StampKind::Built => "built",
83        StampKind::Verified => "verified",
84    };
85
86    let path = model::rewrite_unit_meta(&inst.handle(), &u, |inner| {
87        let block = match stamp {
88            StampKind::Built => {
89                let b = yamlish::set_scalar_in_place(inner, "status", "Built");
90                yamlish::set_scalar_in_place(&b, "built", &stamp_text)
91            }
92            StampKind::Verified => {
93                let b = yamlish::set_scalar_in_place(inner, "status", "Verified");
94                let b = yamlish::set_scalar_in_place(&b, "verified", &stamp_text);
95                let b = yamlish::set_scalar_in_place(&b, "claimed_by", "—");
96                yamlish::set_scalar_in_place(&b, "claim_expires", "—")
97            }
98        };
99        yamlish::set_map_in_place(&block, "trace", &trace_map)
100    })?;
101
102    let recorded = J::Obj(
103        trace_map
104            .iter()
105            .map(|(k, v)| (k.clone(), J::s(v.clone())))
106            .collect(),
107    );
108    let obj = J::Obj(vec![
109        ("unit".into(), J::s(unit)),
110        ("recorded".into(), recorded),
111        ("stamp".into(), J::s(stamp_name)),
112        ("file".into(), J::s(path.display().to_string())),
113    ]);
114    emit(&obj.dumps_default());
115    Ok(0)
116}
117
118pub fn verify(unit: &str, sdd: Option<&str>, json: bool) -> Result<u8, CoreError> {
119    let (inst, u) = load(sdd, unit)?;
120    let Some(recorded) = u.meta.get_map("trace").cloned() else {
121        return Err(CoreError::refusal(
122            4,
123            format!("error: no trace recorded for {unit}"),
124        ));
125    };
126    if recorded.is_empty() {
127        return Err(CoreError::refusal(
128            4,
129            format!("error: no trace recorded for {unit}"),
130        ));
131    }
132    let (current, problems) = trace::compute(&inst, &u)?;
133    for p in &problems {
134        crate::out::diag(&format!("error: {p}"));
135    }
136    let mismatches = trace::verify(&recorded, &current);
137    if json {
138        let jm: Vec<J> = mismatches
139            .iter()
140            .map(|m| {
141                J::Obj(vec![
142                    ("key".into(), J::s(m.key.clone())),
143                    ("recorded".into(), J::opt_str(m.recorded.clone())),
144                    ("current".into(), J::opt_str(m.current.clone())),
145                ])
146            })
147            .collect();
148        let obj = J::Obj(vec![
149            ("unit".into(), J::s(unit)),
150            ("match".into(), J::Bool(mismatches.is_empty())),
151            ("mismatches".into(), J::Arr(jm)),
152        ]);
153        emit(&obj.dumps_indent2());
154    } else if mismatches.is_empty() {
155        emit(&format!("{unit}: trace matches"));
156    } else {
157        let keys: Vec<&str> = mismatches.iter().map(|m| m.key.as_str()).collect();
158        emit(&format!(
159            "{unit}: STALE — mismatched keys: {}",
160            keys.join(", ")
161        ));
162    }
163    Ok(if mismatches.is_empty() { 0 } else { 3 })
164}