Skip to main content

vitrify_cli/incremental/
dirty.rs

1//! Dirty units from git: anchors, one diff per anchor, the core cascade.
2//!
3//! A [`Snapshot`] is the repository at one commit: every SDD loaded from a
4//! checkout of it, the unit graph over them, each SDD's anchors from its
5//! journal, and the declared ownership of every path. Asked which Verified
6//! units a change reaches ([`Snapshot::dirty`]), it resolves each recorded
7//! anchor — a short sha — to a commit, runs `git diff --name-only <anchor>
8//! <head>` once per distinct commit (units integrated in one commit share
9//! one), drops the paths whose change is protocol state only
10//! ([`classify_changes`]), and hands the rest to
11//! [`cascade::dirty_set`]. An anchor git cannot resolve — history
12//! rewritten, a shallow clone — gets no diff, so its units are dirty with
13//! that reason: the cascade never trusts what it cannot compare. Each SDD's
14//! §5 Test command is judged the same way against its suite anchor.
15//!
16//! A graph with a cycle has no closures to cascade along: the cycles are
17//! returned instead of a guess. Output is sorted by unit (slug, then id) and
18//! SDDs by slug, so the same repository state gives the same answer.
19
20use std::collections::{BTreeMap, BTreeSet};
21use std::path::{Path, PathBuf};
22
23use vitrify_core::CoreError;
24use vitrify_core::cascade::{self, Anchors, Candidate, Changes, Closures, Dirty, Ownership, Why};
25use vitrify_core::graph::{self, Cycles, Node, Resolution, UnitGraph};
26use vitrify_core::journal;
27use vitrify_core::model::{self, Instance, Shape};
28use vitrify_core::trace;
29
30use crate::cmd;
31use crate::git::Git;
32
33// ------------------------------------------------------ protocol state
34
35/// Where the SDDs of a repository keep their files, repository-relative:
36/// what tells protocol state from everything else.
37#[derive(Debug, Clone, Default, PartialEq, Eq)]
38pub struct SpecFiles {
39    /// Each bundle's directory (`""` for a bundle at the repository root),
40    /// sorted.
41    pub bundles: Vec<String>,
42    /// Each single-file SDD's file, sorted.
43    pub singles: Vec<String>,
44}
45
46impl SpecFiles {
47    /// The spec files of `sdds`, loaded from the checkout at `root`.
48    pub fn of(root: &Path, sdds: &[Instance]) -> SpecFiles {
49        let mut out = SpecFiles::default();
50        for inst in sdds {
51            match inst.shape {
52                Shape::Bundle => {
53                    let dir = cmd::shown(root, &inst.root);
54                    out.bundles
55                        .push(if dir == "." { String::new() } else { dir });
56                }
57                Shape::Single => out.singles.push(cmd::shown(root, &inst.file)),
58            }
59        }
60        out.bundles.sort();
61        out.bundles.dedup();
62        out.singles.sort();
63        out.singles.dedup();
64        out
65    }
66
67    fn is_bundle(&self, dir: &str) -> bool {
68        self.bundles
69            .binary_search_by(|b| b.as_str().cmp(dir))
70            .is_ok()
71    }
72
73    fn is_single(&self, path: &str) -> bool {
74        self.singles
75            .binary_search_by(|s| s.as_str().cmp(path))
76            .is_ok()
77    }
78}
79
80/// The paths that differ between `old` and `new`, sorted, each with whether
81/// its change is protocol state only: a bundle's journal, ledger, decision
82/// or change log; a bundle's unit file, or a single-file SDD, that differs
83/// in nothing but vitrify-managed fields (and, in a single file, those
84/// sections). Such changes — claims, renewals, stamps, recorded questions —
85/// change nothing a build, a test or a lint reads.
86pub fn classify_changes(
87    git: &Git,
88    old: &str,
89    new: &str,
90    spec: &SpecFiles,
91) -> Result<Vec<(String, bool)>, CoreError> {
92    let both = |path: &str| -> Option<(String, String)> {
93        Some((
94            git.show_text(old, path).ok().flatten()?,
95            git.show_text(new, path).ok().flatten()?,
96        ))
97    };
98    let mut paths = git.changed_paths(old, new).map_err(CoreError::from)?;
99    paths.sort();
100    paths.dedup();
101    let mut out = Vec::with_capacity(paths.len());
102    for path in paths {
103        let (dir, name) = path.rsplit_once('/').unwrap_or(("", path.as_str()));
104        let state_only = if matches!(
105            name,
106            "journal.ndjson" | "ledger.md" | "decisions.md" | "changelog.md"
107        ) {
108            spec.is_bundle(dir)
109        } else if spec.is_single(&path) {
110            both(&path).is_some_and(|(a, b)| single_state_masked(&a) == single_state_masked(&b))
111        } else if (dir == "units" || dir.ends_with("/units"))
112            && name.starts_with("U-")
113            && name.ends_with(".md")
114            && spec.is_bundle(dir.trim_end_matches("units").trim_end_matches('/'))
115        {
116            both(&path).is_some_and(|(a, b)| {
117                trace::mask_unit_fields(Shape::Bundle, &a, "", &trace::VOLATILE)
118                    == trace::mask_unit_fields(Shape::Bundle, &b, "", &trace::VOLATILE)
119            })
120        } else {
121            false
122        };
123        out.push((path, state_only));
124    }
125    Ok(out)
126}
127
128/// What a run's dirty sets found at one head, kept for the next: each
129/// anchor's commit, and the paths that differ between it and the head.
130/// Moving to a new head diffs only the commits in between; a path they
131/// touched is compared, anchor by anchor, in one batch.
132#[derive(Debug, Default)]
133pub struct DiffCache {
134    head: String,
135    /// Anchor as recorded → its commit (`None`: it names none).
136    full_of: BTreeMap<String, Option<String>>,
137    /// Anchor commit → the paths that differ between it and `head`, sorted.
138    paths: BTreeMap<String, Vec<String>>,
139}
140
141impl DiffCache {
142    /// Bring every kept diff from the old head to `head`. Anything that
143    /// cannot be carried over is dropped, and diffed afresh when asked.
144    fn advance(&mut self, git: &Git, head: &str) -> Result<(), CoreError> {
145        if self.head == head {
146            return Ok(());
147        }
148        let old = std::mem::replace(&mut self.head, head.to_string());
149        if old.is_empty()
150            || self.paths.is_empty()
151            || !git.is_ancestor(&old, head).map_err(CoreError::from)?
152        {
153            self.paths.clear();
154            return Ok(());
155        }
156        let moved = git.changed_paths(&old, head).map_err(CoreError::from)?;
157        if moved.is_empty() {
158            return Ok(());
159        }
160        if moved.iter().any(|p| p.contains('\n')) {
161            self.paths.clear();
162            return Ok(());
163        }
164        // a path the new commits touched differs from an anchor when its
165        // object there is not its object at the head
166        let mut names: Vec<String> = moved.iter().map(|p| format!("{head}:{p}")).collect();
167        let anchors: Vec<String> = self.paths.keys().cloned().collect();
168        for a in &anchors {
169            names.extend(moved.iter().map(|p| format!("{a}:{p}")));
170        }
171        let ids = git.object_ids(&names).map_err(CoreError::from)?;
172        let at_head = &ids[..moved.len()];
173        for (k, a) in anchors.iter().enumerate() {
174            let at_anchor = &ids[(k + 1) * moved.len()..(k + 2) * moved.len()];
175            let Some(paths) = self.paths.get_mut(a) else {
176                continue;
177            };
178            let mut set: BTreeSet<String> = std::mem::take(paths).into_iter().collect();
179            for (i, p) in moved.iter().enumerate() {
180                if at_anchor[i] == at_head[i] {
181                    set.remove(p);
182                } else {
183                    set.insert(p.clone());
184                }
185            }
186            *paths = set.into_iter().collect();
187        }
188        Ok(())
189    }
190}
191
192/// The paths that differ between `old` and `new` beyond protocol state,
193/// sorted.
194pub fn substantive_changes(
195    git: &Git,
196    old: &str,
197    new: &str,
198    spec: &SpecFiles,
199) -> Result<Vec<String>, CoreError> {
200    Ok(classify_changes(git, old, new, spec)?
201        .into_iter()
202        .filter(|(_, state_only)| !state_only)
203        .map(|(path, _)| path)
204        .collect())
205}
206
207/// Whether `old..new` moved nothing but protocol state: `new` descends
208/// from `old`, and no path changed beyond it. What was established at
209/// `old` then holds at `new`.
210pub fn benign(git: &Git, old: &str, new: &str, spec: &SpecFiles) -> Result<bool, CoreError> {
211    if old == new {
212        return Ok(true);
213    }
214    if !git.is_ancestor(old, new).map_err(CoreError::from)? {
215        return Ok(false);
216    }
217    Ok(substantive_changes(git, old, new, spec)?.is_empty())
218}
219
220/// A single-file SDD's text with everything vitrify itself writes removed:
221/// each unit's managed fields, the journal, the ledger, the decision and
222/// change logs.
223fn single_state_masked(text: &str) -> String {
224    let mut t = text.to_string();
225    let ids: Vec<String> = model::split_h3_regions(&t, "Work Units")
226        .into_iter()
227        .map(|(id, _)| id)
228        .collect();
229    for id in ids {
230        if let Some(masked) = trace::mask_unit_fields(Shape::Single, &t, &id, &trace::VOLATILE) {
231            t = masked;
232        }
233    }
234    for heading in [
235        "Journal",
236        "State Ledger",
237        "Decisions & Open Questions",
238        "Changelog",
239    ] {
240        if let Some((s, e)) = model::section_span(&t, heading) {
241            t = format!("{}{}", &t[..s], &t[e..]);
242        }
243    }
244    t
245}
246
247// ------------------------------------------------------------ snapshot
248
249/// One SDD of a [`Snapshot`].
250#[derive(Debug, Clone)]
251pub struct SddAt {
252    /// Its `sdd:` slug.
253    pub slug: String,
254    /// Its root as output names it: repository-relative (`specs/calc`,
255    /// `specs/x.sdd.md`).
256    pub root: String,
257    pub inst: Instance,
258    /// Its recorded checks, from its journal.
259    pub anchors: Anchors,
260}
261
262/// The repository at one commit, as the re-check cascade reads it.
263#[derive(Debug, Clone)]
264pub struct Snapshot {
265    /// The checkout the SDDs were loaded from.
266    pub checkout: PathBuf,
267    /// The commit, in full.
268    pub head: String,
269    /// Every SDD of the repository, sorted by slug, then root.
270    pub sdds: Vec<SddAt>,
271    pub graph: UnitGraph,
272    /// The graph's order and closures, or its cycles.
273    pub resolved: Result<Resolution, Cycles>,
274    pub ownership: Ownership,
275    pub spec: SpecFiles,
276}
277
278/// How far recorded checks are trusted.
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280pub enum Mode {
281    /// Each until a path it is checked against changes.
282    Changes,
283    /// Not at all: every Verified unit and every suite is dirty
284    /// (`vitrify run --recheck`).
285    Everything,
286}
287
288/// One SDD's §5 Test command, against its suite anchor.
289#[derive(Debug, Clone, PartialEq, Eq)]
290pub struct SuiteState {
291    pub slug: String,
292    /// The anchor its journal records: the commit of its latest `audit`
293    /// event with `suite: "pass"`.
294    pub anchor: Option<String>,
295    /// Why it must run again; `None` when the recorded pass holds.
296    pub dirty: Option<Why>,
297}
298
299/// Which Verified units — and which suites — a change reaches.
300#[derive(Debug, Clone, PartialEq, Eq)]
301pub struct DirtySet {
302    /// The commit judged, in full.
303    pub head: String,
304    /// The dirty units, sorted by node, each with its reason.
305    pub units: Vec<Dirty>,
306    /// Every SDD's suite state, sorted by slug.
307    pub suites: Vec<SuiteState>,
308    /// The recorded anchors git could not resolve, sorted.
309    pub unresolved: Vec<String>,
310}
311
312impl DirtySet {
313    /// The dirty units of the SDD `slug`, sorted by unit id.
314    pub fn of_sdd<'a>(&'a self, slug: &'a str) -> impl Iterator<Item = &'a Dirty> + 'a {
315        self.units.iter().filter(move |d| d.node.slug == slug)
316    }
317
318    /// Whether `node` is dirty.
319    pub fn is_dirty(&self, node: &Node) -> bool {
320        self.units.binary_search_by(|d| d.node.cmp(node)).is_ok()
321    }
322
323    /// The suite state of `slug`'s SDD.
324    pub fn suite(&self, slug: &str) -> Option<&SuiteState> {
325        self.suites.iter().find(|s| s.slug == slug)
326    }
327}
328
329/// What the cascade made of a [`Snapshot`].
330#[derive(Debug, Clone, PartialEq, Eq)]
331pub enum Cascade {
332    Resolved(DirtySet),
333    /// The unit graph has a cycle: there is no closure to cascade along,
334    /// so nothing is computed.
335    Cycles(Cycles),
336}
337
338/// One human line for why a unit or a suite is dirty: the changed paths
339/// with their owners, `no recorded check`, `every recorded check is
340/// distrusted`, or `anchor <c> cannot be resolved …`.
341pub fn describe(why: &Why) -> String {
342    match why {
343        Why::NoDiff(anchor) => {
344            format!("anchor {anchor} cannot be resolved (rewritten history, or a shallow clone)")
345        }
346        other => other.describe(),
347    }
348}
349
350impl Snapshot {
351    /// Load every SDD of the repository from `checkout`, which holds the
352    /// tree of the commit `head` names (a lane checkout reset to it, or the
353    /// primary checkout at `HEAD`). An SDD that cannot be read is an error:
354    /// without it the graph, and every closure through it, is incomplete.
355    pub fn load(git: &Git, checkout: &Path, head: &str) -> Result<Snapshot, CoreError> {
356        let head = git
357            .resolve_commit(head)
358            .map_err(CoreError::from)?
359            .ok_or_else(|| CoreError::refusal(1, format!("error: {head} names no commit")))?;
360        let mut sdds: Vec<SddAt> = Vec::new();
361        for handle in cmd::discover(checkout) {
362            let inst = Instance::load(handle)?;
363            let (events, _) = journal::read(&inst.handle())?;
364            sdds.push(SddAt {
365                slug: graph::slug_of(&inst).to_string(),
366                root: cmd::shown(checkout, &inst.root),
367                anchors: Anchors::from_events(&events),
368                inst,
369            });
370        }
371        sdds.sort_by(|a, b| (&a.slug, &a.root).cmp(&(&b.slug, &b.root)));
372        let instances: Vec<Instance> = sdds.iter().map(|s| s.inst.clone()).collect();
373        let graph = UnitGraph::build(&instances)?;
374        let resolved = graph.resolve();
375        let ownership =
376            Ownership::build(checkout, sdds.iter().map(|s| (s.slug.as_str(), &s.inst)))?;
377        let spec = SpecFiles::of(checkout, &instances);
378        Ok(Snapshot {
379            checkout: checkout.to_path_buf(),
380            head,
381            sdds,
382            graph,
383            resolved,
384            ownership,
385            spec,
386        })
387    }
388
389    /// [`Snapshot::load`] for a run that must go on whatever one SDD holds:
390    /// an SDD that cannot be read is left out, and when the unit graph has
391    /// a cycle the SDDs with a unit on one are left out of the graph — so
392    /// the rest still get their closures, dirty sets and priorities — and
393    /// the cycles are returned. Ownership and spec files still count every
394    /// SDD read, so a change to a left-out SDD's files is still its own.
395    pub fn load_resolvable(
396        git: &Git,
397        checkout: &Path,
398        head: &str,
399    ) -> Result<(Snapshot, Option<Cycles>), CoreError> {
400        let full = git
401            .resolve_commit(head)
402            .map_err(CoreError::from)?
403            .ok_or_else(|| CoreError::refusal(1, format!("error: {head} names no commit")))?;
404        let mut all: Vec<SddAt> = Vec::new();
405        for handle in cmd::discover(checkout) {
406            let Ok(inst) = Instance::load(handle) else {
407                continue;
408            };
409            let (events, _) = journal::read(&inst.handle()).unwrap_or_default();
410            all.push(SddAt {
411                slug: graph::slug_of(&inst).to_string(),
412                root: cmd::shown(checkout, &inst.root),
413                anchors: Anchors::from_events(&events),
414                inst,
415            });
416        }
417        all.sort_by(|a, b| (&a.slug, &a.root).cmp(&(&b.slug, &b.root)));
418        let every: Vec<Instance> = all.iter().map(|s| s.inst.clone()).collect();
419        let ownership = Ownership::build(checkout, all.iter().map(|s| (s.slug.as_str(), &s.inst)))?;
420        let spec = SpecFiles::of(checkout, &every);
421        let mut graph = UnitGraph::build(&every)?;
422        let mut resolved = graph.resolve();
423        let mut cycles = None;
424        if let Err(c) = &resolved {
425            let on_cycle: BTreeSet<&str> =
426                c.cycles.iter().flatten().map(|n| n.slug.as_str()).collect();
427            let kept: Vec<SddAt> = all
428                .iter()
429                .filter(|s| !on_cycle.contains(s.slug.as_str()))
430                .cloned()
431                .collect();
432            cycles = Some(c.clone());
433            let instances: Vec<Instance> = kept.iter().map(|s| s.inst.clone()).collect();
434            graph = UnitGraph::build(&instances)?;
435            resolved = graph.resolve();
436            all = kept;
437        }
438        Ok((
439            Snapshot {
440                checkout: checkout.to_path_buf(),
441                head: full,
442                sdds: all,
443                graph,
444                resolved,
445                ownership,
446                spec,
447            },
448            cycles,
449        ))
450    }
451
452    /// The SDD with `slug`.
453    pub fn sdd(&self, slug: &str) -> Option<&SddAt> {
454        self.sdds.iter().find(|s| s.slug == slug)
455    }
456
457    /// Every unit Verified at the head, with its anchor; sorted by node.
458    pub fn candidates(&self) -> Vec<Candidate> {
459        let mut out: Vec<Candidate> = self
460            .sdds
461            .iter()
462            .flat_map(|s| {
463                s.inst
464                    .units
465                    .iter()
466                    .filter(|u| u.meta.get_str_or("status", "Draft") == "Verified")
467                    .map(|u| Candidate {
468                        node: Node::new(&s.slug, &u.unit),
469                        anchor: s.anchors.unit(&u.unit).map(str::to_string),
470                    })
471            })
472            .collect();
473        out.sort_by(|a, b| a.node.cmp(&b.node));
474        out
475    }
476
477    /// Which Verified units, and which suites, must be checked again at the
478    /// head. In [`Mode::Changes`] git is asked for one diff per distinct
479    /// anchor; in [`Mode::Everything`] nothing is asked and everything is
480    /// dirty.
481    pub fn dirty(&self, git: &Git, mode: Mode) -> Result<Cascade, CoreError> {
482        self.dirty_with(git, mode, &mut DiffCache::default())
483    }
484
485    /// [`Snapshot::dirty`], with what an earlier head's diffs found kept in
486    /// `cache`: a run reads every head, and most of what changed since an
487    /// anchor had changed by the head before.
488    pub fn dirty_with(
489        &self,
490        git: &Git,
491        mode: Mode,
492        cache: &mut DiffCache,
493    ) -> Result<Cascade, CoreError> {
494        let resolution = match &self.resolved {
495            Ok(r) => r,
496            Err(cycles) => return Ok(Cascade::Cycles(cycles.clone())),
497        };
498        let candidates = self.candidates();
499        if mode == Mode::Everything {
500            return Ok(Cascade::Resolved(DirtySet {
501                head: self.head.clone(),
502                units: cascade::dirty_everything(&candidates),
503                suites: self
504                    .sdds
505                    .iter()
506                    .map(|s| SuiteState {
507                        slug: s.slug.clone(),
508                        anchor: s.anchors.suite.clone(),
509                        dirty: Some(Why::Everything),
510                    })
511                    .collect(),
512                unresolved: Vec::new(),
513            }));
514        }
515        let closures: Closures = self
516            .graph
517            .nodes()
518            .iter()
519            .map(|n| {
520                let deps: BTreeSet<Node> = resolution.closure(n).into_iter().cloned().collect();
521                (n.clone(), deps)
522            })
523            .collect();
524
525        // every recorded anchor, once: units and suites
526        let mut recorded: BTreeSet<&str> = candidates
527            .iter()
528            .filter_map(|c| c.anchor.as_deref())
529            .collect();
530        recorded.extend(self.sdds.iter().filter_map(|s| s.anchors.suite.as_deref()));
531        let mut full_of: BTreeMap<&str, String> = BTreeMap::new();
532        let mut unresolved: Vec<String> = Vec::new();
533        let unknown: Vec<&str> = recorded
534            .iter()
535            .copied()
536            .filter(|a| !cache.full_of.contains_key(*a))
537            .collect();
538        let names: Vec<String> = unknown.iter().map(|a| format!("{a}^{{commit}}")).collect();
539        for (anchor, full) in unknown
540            .iter()
541            .zip(git.object_ids(&names).map_err(CoreError::from)?)
542        {
543            cache.full_of.insert(anchor.to_string(), full);
544        }
545        for anchor in recorded {
546            match cache.full_of.get(anchor).cloned().flatten() {
547                Some(full) => {
548                    full_of.insert(anchor, full);
549                }
550                None => unresolved.push(anchor.to_string()),
551            }
552        }
553        cache.advance(git, &self.head)?;
554        // one diff per distinct commit, whatever names it. Protocol state
555        // lives under the SDDs' own roots, and the cascade never takes a
556        // spec path as an input (`Owner::Spec`): a plain diff gives the
557        // same answer as one with protocol state filtered out, without
558        // reading every changed spec file at both ends for every anchor.
559        let mut diffs: BTreeMap<&str, Vec<String>> = BTreeMap::new();
560        for full in full_of.values() {
561            if !diffs.contains_key(full.as_str()) {
562                let paths = match cache.paths.get(full.as_str()) {
563                    Some(paths) => paths.clone(),
564                    None => {
565                        let mut paths = git
566                            .changed_paths(full, &self.head)
567                            .map_err(CoreError::from)?;
568                        paths.sort();
569                        paths.dedup();
570                        cache.paths.insert(full.clone(), paths.clone());
571                        paths
572                    }
573                };
574                diffs.insert(full.as_str(), paths);
575            }
576        }
577        // what no anchor names any more is let go
578        let named: BTreeSet<&String> = full_of.values().collect();
579        cache.paths.retain(|full, _| named.contains(full));
580        let changes: Changes = full_of
581            .iter()
582            .map(|(anchor, full)| {
583                let paths = diffs.get(full.as_str()).cloned().unwrap_or_default();
584                (anchor.to_string(), paths)
585            })
586            .collect();
587
588        let units = cascade::dirty_set(&candidates, &changes, &closures, &self.ownership);
589        let suites = self
590            .sdds
591            .iter()
592            .map(|s| {
593                let nodes: Vec<Node> = s
594                    .inst
595                    .units
596                    .iter()
597                    .map(|u| Node::new(&s.slug, &u.unit))
598                    .collect();
599                let anchor = s.anchors.suite.as_deref();
600                let changed = anchor.and_then(|a| changes.get(a)).map(Vec::as_slice);
601                SuiteState {
602                    slug: s.slug.clone(),
603                    anchor: s.anchors.suite.clone(),
604                    dirty: cascade::suite_dirty(
605                        &s.slug,
606                        &nodes,
607                        anchor,
608                        changed,
609                        &closures,
610                        &self.ownership,
611                    ),
612                }
613            })
614            .collect();
615        Ok(Cascade::Resolved(DirtySet {
616            head: self.head.clone(),
617            units,
618            suites,
619            unresolved,
620        }))
621    }
622}