Skip to main content

vitrify_cli/cmd/
pin.rs

1//! `vitrify pin list|sync` — external contracts: one SDD's pins on
2//! contracts another SDD owns, and its transcriptions of sources no SDD owns
3//! ([`vitrify_core::contract`]).
4//!
5//! `list` reads: every external contract, the authority it names, and
6//! whether it still matches — never calling one clean that it could not
7//! check. `sync` writes, in the working tree only: a stale pin takes its
8//! authority's hash, and the units whose recorded trace that moved are
9//! printed as the `Staleness applied` line of the change entry the author
10//! still writes.
11
12use std::path::{Path, PathBuf};
13
14use vitrify_core::contract::{self, External, Kind, Peers, State};
15use vitrify_core::model::{self, Instance, SddHandle};
16use vitrify_core::{CoreError, trace};
17
18use crate::out::{J, diag, emit};
19
20/// The states, in the order a summary counts them.
21const STATES: [State; 5] = [
22    State::Ok,
23    State::Stale,
24    State::MissingAuthority,
25    State::Invalid,
26    State::Unchecked,
27];
28
29/// One SDD's external contracts, examined.
30struct Examined {
31    name: String,
32    inst: Instance,
33    contracts: Vec<External>,
34}
35
36fn examine(root: &Path, sdd: &SddHandle, peers: &Peers) -> Result<Examined, CoreError> {
37    let inst = Instance::load(sdd.clone())?;
38    let contracts = contract::examine(&inst, peers)?;
39    Ok(Examined {
40        name: super::label(sdd, root),
41        inst,
42        contracts,
43    })
44}
45
46/// Examine each of `sdds`; one that cannot be read is reported under its
47/// name and counted in the returned exit code.
48fn examine_each(root: &Path, sdds: &[SddHandle], peers: &Peers) -> (Vec<Examined>, u8) {
49    let mut out = Vec::new();
50    let code = super::each(root, sdds, |sdd| {
51        out.push(examine(root, sdd, peers)?);
52        Ok(0)
53    });
54    (out, code)
55}
56
57fn consumers(inst: &Instance, id: &str) -> Vec<String> {
58    inst.units
59        .iter()
60        .filter(|u| u.meta.get_list("consumes").iter().any(|c| c == id))
61        .map(|u| u.unit.clone())
62        .collect()
63}
64
65/// `pin of alpha C-001`, or what it is instead.
66fn names(ext: &External) -> String {
67    match (&ext.authority, ext.kind) {
68        (Some(a), _) => format!("pin of {} {}", a.slug, a.contract),
69        (None, Kind::Pin) => "pin".to_string(),
70        (None, Kind::Transcription) => "transcription".to_string(),
71    }
72}
73
74fn authority_json(root: &Path, ext: &External) -> J {
75    match &ext.authority {
76        Some(a) => J::Obj(vec![
77            ("sdd".into(), J::s(a.slug.clone())),
78            ("contract".into(), J::s(a.contract.clone())),
79            (
80                "file".into(),
81                J::opt_str(a.file.as_ref().map(|f| super::shown(root, f))),
82            ),
83            (
84                "bytes".into(),
85                a.body_bytes.map(|b| J::Int(b as i64)).unwrap_or(J::Null),
86            ),
87        ]),
88        None => J::Null,
89    }
90}
91
92fn counts(all: &[Examined]) -> Vec<(State, usize)> {
93    STATES
94        .iter()
95        .map(|s| {
96            (
97                *s,
98                all.iter()
99                    .flat_map(|e| &e.contracts)
100                    .filter(|c| c.state == *s)
101                    .count(),
102            )
103        })
104        .collect()
105}
106
107pub fn list(sdd: Option<&str>, all: bool, json: bool) -> Result<u8, CoreError> {
108    let root = super::repo_root();
109    let sdds = super::targets(&root, sdd, all, &super::cwd())?;
110    let peers = super::peers(&root);
111    let (examined, read_code) = examine_each(&root, &sdds, &peers);
112    let counts = counts(&examined);
113    let total: usize = counts.iter().map(|(_, n)| n).sum();
114    let findings = examined
115        .iter()
116        .flat_map(|e| &e.contracts)
117        .any(|c| c.state.is_finding());
118
119    if json {
120        let rows: Vec<J> = examined
121            .iter()
122            .flat_map(|e| e.contracts.iter().map(move |c| (e, c)))
123            .map(|(e, c)| {
124                J::Obj(vec![
125                    ("sdd".into(), J::s(e.name.clone())),
126                    ("contract".into(), J::s(c.id.clone())),
127                    ("file".into(), J::s(super::shown(&root, &c.file))),
128                    ("kind".into(), J::s(c.kind.as_str())),
129                    ("state".into(), J::s(c.state.as_str())),
130                    ("authority".into(), authority_json(&root, c)),
131                    ("bytes".into(), J::Int(c.bytes as i64)),
132                    (
133                        "consumers".into(),
134                        J::Arr(consumers(&e.inst, &c.id).into_iter().map(J::Str).collect()),
135                    ),
136                    (
137                        "detail".into(),
138                        J::opt_str((c.state != State::Ok).then(|| c.detail.clone())),
139                    ),
140                ])
141            })
142            .collect();
143        let obj = J::Obj(vec![
144            ("clean".into(), J::Bool(!findings)),
145            ("contracts".into(), J::Arr(rows)),
146            (
147                "counts".into(),
148                J::Obj(
149                    counts
150                        .iter()
151                        .map(|(s, n)| (s.as_str().to_string(), J::Int(*n as i64)))
152                        .collect(),
153                ),
154            ),
155        ]);
156        emit(&obj.dumps_indent2());
157    } else {
158        let rows: Vec<(String, &External)> = examined
159            .iter()
160            .flat_map(|e| {
161                e.contracts
162                    .iter()
163                    .map(move |c| (format!("{} {}", e.name, c.id), c))
164            })
165            .collect();
166        let width =
167            |f: &dyn Fn(&(String, &External)) -> usize| rows.iter().map(f).max().unwrap_or(0);
168        let (w_id, w_names) = (
169            width(&|r| r.0.chars().count()),
170            width(&|r| names(r.1).chars().count()),
171        );
172        for (id, c) in &rows {
173            let mut line = format!(
174                "{id:<w_id$}  {:<17}  {:<w_names$}  {}",
175                c.state.as_str(),
176                names(c),
177                super::shown(&root, &c.file)
178            );
179            if c.state.is_finding() {
180                line.push_str(&format!(" — {}", c.detail));
181            }
182            emit(&line);
183        }
184        if total == 0 {
185            emit("no external contracts");
186        } else {
187            let parts: Vec<String> = counts
188                .iter()
189                .filter(|(_, n)| *n > 0)
190                .map(|(s, n)| format!("{n} {}", s.as_str()))
191                .collect();
192            emit(&format!(
193                "{total} external contract{}: {}",
194                if total == 1 { "" } else { "s" },
195                parts.join(" · ")
196            ));
197        }
198    }
199    Ok(match (read_code, findings) {
200        (0, false) => 0,
201        (0, true) => 2,
202        (code, _) => code,
203    })
204}
205
206/// One pin a sync rewrote.
207struct Synced {
208    sdd: String,
209    id: String,
210    file: String,
211    authority: Option<(String, String)>,
212    hash: Option<String>,
213}
214
215/// Per contract a sync rewrote, the units it staled.
216type Moved = Vec<(String, Vec<String>)>;
217
218/// The files a dry run would have written, with what it would have written.
219type Overlay = Vec<(PathBuf, String)>;
220
221/// The stamped units of `inst` whose recorded trace no longer matches one
222/// of `ids` — per contract, in `ids` order. A dry run's contracts are read
223/// as `overlay` has them, as the sync would have left them.
224fn moved(inst: &Instance, ids: &[String], overlay: &Overlay) -> Result<Moved, CoreError> {
225    let mut out: Moved = ids.iter().map(|c| (c.clone(), Vec::new())).collect();
226    let mut would: Vec<(String, String)> = Vec::new();
227    if !overlay.is_empty() {
228        let read = |p: &Path| match overlay.iter().find(|(f, _)| f == p) {
229            Some((_, text)) => Ok(text.clone()),
230            None => model::read_text(p),
231        };
232        for cid in ids {
233            if let Some(text) = model::contract_text_with(&inst.handle(), cid, &read)? {
234                would.push((cid.clone(), trace::hash12(&text)));
235            }
236        }
237    }
238    for u in &inst.units {
239        if !matches!(u.meta.get_str_or("status", "Draft"), "Built" | "Verified") {
240            continue;
241        }
242        let Some(recorded) = u.meta.get_map("trace").filter(|m| !m.is_empty()) else {
243            continue;
244        };
245        let (mut current, _) = trace::compute(inst, u)?;
246        for (key, hash) in current.iter_mut() {
247            if let Some((_, h)) = would.iter().find(|(c, _)| c == key) {
248                *hash = h.clone();
249            }
250        }
251        for mismatch in trace::verify(recorded, &current) {
252            if let Some(slot) = out.iter_mut().find(|(c, _)| *c == mismatch.key) {
253                slot.1.push(u.unit.clone());
254            }
255        }
256    }
257    out.retain(|(_, units)| !units.is_empty());
258    Ok(out)
259}
260
261/// The change entry's line for what a sync staled (schema §12).
262fn staleness_line(moved: &Moved) -> String {
263    if moved.is_empty() {
264        return "- Staleness applied: —".to_string();
265    }
266    let parts: Vec<String> = moved
267        .iter()
268        .map(|(c, units)| format!("{} → Stale (consume {c})", units.join(", ")))
269        .collect();
270    format!("- Staleness applied: {}", parts.join("; "))
271}
272
273pub fn sync(sdd: Option<&str>, all: bool, dry_run: bool, json: bool) -> Result<u8, CoreError> {
274    let root = super::repo_root();
275    let sdds = super::targets(&root, sdd, all, &super::cwd())?;
276    let peers = super::peers(&root);
277
278    // a pin's authority is never itself a pin, so one pass puts every
279    // stale pin in step
280    let mut synced: Vec<Synced> = Vec::new();
281    let mut overlay: Overlay = Vec::new();
282    for sdd in &sdds {
283        let Ok(examined) = examine(&root, sdd, &peers) else {
284            continue; // reported below, when everything is examined again
285        };
286        let stale: Vec<&External> = examined
287            .contracts
288            .iter()
289            .filter(|c| c.state == State::Stale && c.fix.is_some())
290            .collect();
291        let fixes: Vec<contract::Fix> = stale.iter().filter_map(|c| c.fix.clone()).collect();
292        if fixes.is_empty() {
293            continue;
294        }
295        if dry_run {
296            overlay.extend(contract::rendered(&fixes)?);
297        } else {
298            contract::apply(&fixes)?;
299        }
300        for c in stale {
301            synced.push(Synced {
302                sdd: examined.name.clone(),
303                id: c.id.clone(),
304                file: super::shown(&root, &c.file),
305                authority: c
306                    .authority
307                    .as_ref()
308                    .map(|a| (a.slug.clone(), a.contract.clone())),
309                hash: c.hash.clone(),
310            });
311        }
312    }
313
314    // what is left: nothing a sync can write, or it would have (a dry run
315    // finds on disk the stale pins it did not write)
316    let (examined, read_code) = examine_each(&root, &sdds, &peers);
317    let would_sync = |e: &Examined, c: &External| {
318        dry_run && synced.iter().any(|s| s.sdd == e.name && s.id == c.id)
319    };
320    let unresolved: Vec<(&Examined, &External)> = examined
321        .iter()
322        .flat_map(|e| e.contracts.iter().map(move |c| (e, c)))
323        .filter(|(e, c)| c.state.is_finding() && !would_sync(e, c))
324        .collect();
325    // per consumer SDD: the stamped units the rewritten pins staled, and
326    // the SDD's root as `--sdd` names it
327    let mut staleness: Vec<(String, Moved, String)> = Vec::new();
328    for e in &examined {
329        let ids: Vec<String> = synced
330            .iter()
331            .filter(|s| s.sdd == e.name)
332            .map(|s| s.id.clone())
333            .collect();
334        if !ids.is_empty() {
335            staleness.push((
336                e.name.clone(),
337                moved(&e.inst, &ids, &overlay)?,
338                super::shown(&root, &e.inst.root),
339            ));
340        }
341    }
342
343    if json {
344        let obj = J::Obj(vec![
345            (
346                "synced".into(),
347                J::Arr(
348                    synced
349                        .iter()
350                        .map(|s| {
351                            J::Obj(vec![
352                                ("sdd".into(), J::s(s.sdd.clone())),
353                                ("contract".into(), J::s(s.id.clone())),
354                                ("file".into(), J::s(s.file.clone())),
355                                (
356                                    "authority".into(),
357                                    match &s.authority {
358                                        Some((slug, id)) => J::Obj(vec![
359                                            ("sdd".into(), J::s(slug.clone())),
360                                            ("contract".into(), J::s(id.clone())),
361                                        ]),
362                                        None => J::Null,
363                                    },
364                                ),
365                                ("hash".into(), J::opt_str(s.hash.clone())),
366                            ])
367                        })
368                        .collect(),
369                ),
370            ),
371            (
372                "staleness".into(),
373                J::Arr(
374                    staleness
375                        .iter()
376                        .map(|(name, moved, _)| {
377                            J::Obj(vec![
378                                ("sdd".into(), J::s(name.clone())),
379                                (
380                                    "stale".into(),
381                                    J::Arr(
382                                        moved
383                                            .iter()
384                                            .map(|(c, units)| {
385                                                J::Obj(vec![
386                                                    ("contract".into(), J::s(c.clone())),
387                                                    (
388                                                        "units".into(),
389                                                        J::Arr(
390                                                            units
391                                                                .iter()
392                                                                .map(|u| J::s(u.clone()))
393                                                                .collect(),
394                                                        ),
395                                                    ),
396                                                ])
397                                            })
398                                            .collect(),
399                                    ),
400                                ),
401                                ("line".into(), J::s(staleness_line(moved))),
402                            ])
403                        })
404                        .collect(),
405                ),
406            ),
407            (
408                "unresolved".into(),
409                J::Arr(
410                    unresolved
411                        .iter()
412                        .map(|(e, c)| {
413                            J::Obj(vec![
414                                ("sdd".into(), J::s(e.name.clone())),
415                                ("contract".into(), J::s(c.id.clone())),
416                                ("state".into(), J::s(c.state.as_str())),
417                                ("detail".into(), J::s(c.detail.clone())),
418                            ])
419                        })
420                        .collect(),
421                ),
422            ),
423            ("dry_run".into(), J::Bool(dry_run)),
424        ]);
425        emit(&obj.dumps_indent2());
426    } else {
427        for s in &synced {
428            let from = s
429                .authority
430                .as_ref()
431                .map(|(slug, id)| format!("{slug} {id}"))
432                .unwrap_or_default();
433            emit(&format!("synced {} {} ← {from}  {}", s.sdd, s.id, s.file));
434        }
435        for (name, moved, _) in &staleness {
436            emit(&format!("{name}: {}", staleness_line(moved)));
437        }
438        for (e, c) in &unresolved {
439            diag(&format!("not synced: {} {}: {}", e.name, c.id, c.detail));
440        }
441        let in_step = examined
442            .iter()
443            .flat_map(|e| &e.contracts)
444            .filter(|c| c.state == State::Ok)
445            .count();
446        emit(&match (synced.len(), unresolved.len()) {
447            (0, 0) => format!("nothing to sync ({in_step} in step)"),
448            (n, 0) => format!("{n} synced"),
449            (n, m) => format!("{n} synced · {m} not synced"),
450        });
451    }
452    if dry_run {
453        diag("dry run: nothing written");
454    } else {
455        // the next step, once per consumer SDD whose pins moved
456        for (name, _, at) in &staleness {
457            diag(&format!(
458                "next: write {name}'s change entry around its line, then run vitrify change apply --sdd {at}"
459            ));
460        }
461    }
462    Ok(match (read_code, unresolved.is_empty()) {
463        (0, true) => 0,
464        (0, false) => 2,
465        (code, _) => code,
466    })
467}