Skip to main content

sokf_core/api/
validate.rs

1//! This module implements `sokf validate`. It loads the configuration,
2//! walks the tree, loads and builds the model, compiles the schemas, and
3//! works out the expected content, then checks the documents and the
4//! expected indexes. With `--fix`, it plans the fixes, applies them, and
5//! runs all of that again. Last, it finishes the report and filters it to
6//! the paths that the caller gave.
7
8use std::{
9    collections::{BTreeSet, HashSet},
10    path::{Path, PathBuf},
11};
12
13use super::{
14    admit::{admit_closure, admit_for_check, admit_full, admit_schemas_for, needed_slugs},
15    load::{CachedLoader, Loaded, ensure_not_missed, load_for_check, load_formats},
16    markers::is_checked_unit,
17};
18use crate::{
19    Cache, CacheMode, Config, Error, Expr, Finding, RepoPath, RepoRoot, Report, Result,
20    cache::CitedFact,
21    check,
22    config::{self, RepoFormats},
23    fix,
24    grammar::Grammar,
25    include, index,
26    model::{KeyIndex, Query},
27};
28
29/// The options of `sokf validate`.
30#[derive(Debug, Clone)]
31pub struct ValidateOptions {
32    /// `PATHS`: the paths that the report is filtered to.
33    pub paths: Vec<PathBuf>,
34    /// The current directory, which `PATHS` resolve from.
35    pub cwd: PathBuf,
36    /// `--fix`: fix what the tool can fix, then check again.
37    pub fix: bool,
38    /// The cache mode, which `--no-cache` sets to `Off`.
39    pub cache: CacheMode,
40    /// `--query`: the expression that projects the report.
41    pub query: Option<Expr>,
42    /// `--changed`: the files that the caller knows have changed, each a
43    /// path from the current directory or from the repository root. The
44    /// cache reads the file metadata of only these files (CLI-4_AC-21).
45    pub changed: Vec<PathBuf>,
46    /// The home directory, whose settings a harness installed at the
47    /// project scope can read, so that the check of the installed harnesses
48    /// sees what `sokf harness install` sees (CLI-4_AC-40).
49    pub home: Option<PathBuf>,
50}
51
52/// `changed_paths` resolves the paths of `--changed`, each a path from the
53/// current directory or from the repository root, whether the file still
54/// exists or has been deleted. A path outside the repository is an error.
55// sokf-implements: CLI-4_AC-22
56fn changed_paths(root: &RepoRoot, cwd: &Path, paths: &[PathBuf]) -> Result<Vec<RepoPath>> {
57    paths
58        .iter()
59        .map(|path| {
60            let shown = path.display().to_string();
61            path.to_str()
62                .and_then(|s| crate::PathArg(s).resolve_new(root, cwd))
63                .ok_or(Error::Path(shown))
64        })
65        .collect()
66}
67
68/// `check_repository` loads the knowledge for a check and checks it. It
69/// checks the documents of the dirty set, then the readers of each
70/// citation that changed. It also runs the checks that run every time,
71/// whatever documents are dirty. It stores what the run derived in the
72/// cache, and returns every finding: those of the documents it checked, and
73/// the cache's stored findings for the documents it didn't check.
74// sokf-implements: CACHE-1_AC-14
75// sokf-implements: CACHE-1_AC-11
76// sokf-implements: CLI-4_AC-20
77pub fn check_repository(
78    root: &RepoRoot,
79    config: &Config,
80    grammar: &Grammar,
81    repo_formats: &RepoFormats,
82    cache: &Cache,
83    want_full: bool,
84) -> Result<(Loaded, Vec<Finding>)> {
85    check_and_keep(root, config, grammar, repo_formats, cache, want_full, true)
86}
87
88/// `check_and_keep` runs the check of `check_repository` and commits what
89/// it derived to the cache. With `report`, it returns the findings of the
90/// check and the cache's stored findings for the units it didn't check.
91/// Without `report`, it returns no findings. A lookup, such as `graph` or
92/// `locate`, calls it this way: the lookup first runs a check to bring the
93/// cache up to date, and it reports no finding from that check
94/// (CACHE-1_AC-35).
95pub(crate) fn check_and_keep(
96    root: &RepoRoot,
97    config: &Config,
98    grammar: &Grammar,
99    repo_formats: &RepoFormats,
100    cache: &Cache,
101    want_full: bool,
102    report: bool,
103) -> Result<(Loaded, Vec<Finding>)> {
104    let run = || {
105        check_once(
106            root,
107            config,
108            grammar,
109            repo_formats,
110            cache,
111            want_full,
112            report,
113        )
114    };
115    let result = run();
116    if hint_missed(root, cache, result.as_ref().err()) {
117        return run();
118    }
119    result
120}
121
122/// `hint_missed` returns whether the hint of this run left out a removed
123/// file that the run read: the run took the file from the store and found
124/// it gone. The cache's loader records such a read, and `e`, the error
125/// that ended the run, can show one too. In that case `hint_missed` drops
126/// the hint, so that the run that follows walks the repository. The run
127/// that follows syncs again, which clears the state of this run.
128// sokf-implements: CACHE-1_AC-53
129fn hint_missed(root: &RepoRoot, cache: &Cache, e: Option<&Error>) -> bool {
130    if cache.hint().is_none() || cache.is_fresh() {
131        return false;
132    }
133    let read_removed = e.is_some_and(|e| {
134        super::load::is_not_found(e)
135            && matches!(e, Error::Io { path, .. } if RepoPath::from_fs(root, path).is_some())
136    });
137    let missed = cache.missed() || read_removed;
138    if missed {
139        cache.drop_hint();
140    }
141    missed
142}
143
144/// `check_once` runs one check for `check_and_keep`.
145fn check_once(
146    root: &RepoRoot,
147    config: &Config,
148    grammar: &Grammar,
149    repo_formats: &RepoFormats,
150    cache: &Cache,
151    want_full: bool,
152    report: bool,
153) -> Result<(Loaded, Vec<Finding>)> {
154    let mut loaded = load_for_check(root, config, grammar, repo_formats, cache, want_full)?;
155    // `indexes` holds the expected index of each touched directory, worked
156    // out from the tree as it stands, with no moves applied.
157    let indexes = index::expected_for(&loaded.model, &[], loaded.touched.as_ref());
158    let (units, citations) = if loaded.full {
159        (None, Vec::new())
160    } else {
161        // The units to check are the dirty documents and the indexes of the
162        // touched directories.
163        let mut units = loaded.dirty.clone();
164        units.extend(indexes.expected.keys().cloned());
165        (
166            Some(units),
167            stored_citations(cache, &loaded.dirty, &loaded.dirty),
168        )
169    };
170    settle(
171        cache,
172        config,
173        &loaded.model,
174        &mut loaded.expected,
175        Some(&indexes),
176        units.as_ref(),
177    );
178    let mut out = check::run_units(
179        &loaded.model,
180        &loaded.compiled,
181        &loaded.expected,
182        &loaded.keys,
183        &indexes,
184        units.as_ref(),
185        citations,
186        true,
187    );
188    if !loaded.full {
189        check_readers(root, config, cache, &mut loaded, &indexes, &mut out)?;
190    }
191    let checked: BTreeSet<RepoPath> = out.documents.keys().cloned().collect();
192    record_run(cache, &loaded, &out, &checked);
193    // A file that holds a text that the formatter left unsettled reads the
194    // query that every run checks again, so the run keeps the findings of
195    // every other file, and the next run formats that text again
196    // (CACHE-2_AC-9).
197    // sokf-implements: CACHE-2_AC-9
198    cache.record_unsettled(loaded.expected.layout.unsettled().intersection(&checked));
199    ensure_not_missed(cache)?;
200    cache.commit();
201    if !report {
202        return Ok((loaded, Vec::new()));
203    }
204    let mut findings = out.findings();
205    if !loaded.full {
206        findings.extend(cache.stored_outputs(&checked));
207    }
208    Ok((loaded, findings))
209}
210
211/// `settle` asks same-same to compare each block of the files in
212/// `units`, or of every file, and each index of `indexes`, that differs
213/// from its expected text, and adds the result to `expected`, so that the
214/// check and the fix read the same answer (CLI-4_AC-45).
215fn settle(
216    cache: &Cache,
217    config: &Config,
218    model: &crate::Model,
219    expected: &mut crate::Expected,
220    indexes: Option<&index::Indexes>,
221    units: Option<&BTreeSet<RepoPath>>,
222) {
223    let pairs = include::pairs(model, expected, indexes, units);
224    let pairs: Vec<_> = pairs
225        .into_iter()
226        .filter(|p| !expected.layout.holds(p))
227        .collect();
228    let layout = cache.comparison().settle(&config.format, &pairs);
229    expected.layout.extend(layout);
230}
231
232/// `stored_citations` returns the citations of each of `units` that the
233/// cache holds, each with the unit that it cites, except those from the
234/// sources in `checked`.
235fn stored_citations(
236    cache: &Cache,
237    units: &BTreeSet<RepoPath>,
238    checked: &BTreeSet<RepoPath>,
239) -> Vec<(RepoPath, check::Citation)> {
240    let mut rows = Vec::new();
241    for unit in units {
242        for c in cache.stored_citations_of(unit, checked) {
243            rows.push((unit.clone(), c));
244        }
245    }
246    rows
247}
248
249/// `check_readers` checks the documents that read a citation that changed
250/// in `out`, the output of the first round, unless this run has checked them
251/// already. It adds their findings and citations to `out`, and the documents
252/// to `loaded.dirty`.
253fn check_readers(
254    root: &RepoRoot,
255    config: &Config,
256    cache: &Cache,
257    loaded: &mut Loaded,
258    indexes: &index::Indexes,
259    out: &mut check::RunOutput,
260) -> Result<()> {
261    // A citation to the same target that differs only in its fragment,
262    // relationship, or marker line still counts as a change.
263    let moved = moved_citations(cache, out);
264    let checked: BTreeSet<RepoPath> = out.documents.keys().cloned().collect();
265    let round2: BTreeSet<RepoPath> = cache
266        .readers_of(&moved)
267        .into_iter()
268        .filter(|p| is_checked_unit(&loaded.model, cache, p) && !checked.contains(p))
269        .collect();
270    if round2.is_empty() {
271        return Ok(());
272    }
273    admit_for_check(
274        &mut loaded.model,
275        &mut CachedLoader::new(root, cache),
276        cache,
277        &mut loaded.compiled,
278        &round2,
279    )?;
280    extend_keys(cache, loaded, &round2, &checked);
281    let more = include::expected_for(&loaded.model, &loaded.keys, Some(&round2));
282    loaded.expected.includes.extend(more.includes);
283    loaded.expected.fences.extend(more.fences);
284    loaded.expected.bodies.extend(more.bodies);
285    loaded.expected.definitions.extend(more.definitions);
286    settle(
287        cache,
288        config,
289        &loaded.model,
290        &mut loaded.expected,
291        None,
292        Some(&round2),
293    );
294    // The citations of the documents checked again are the store's
295    // citations, plus the citations that the first round found. The
296    // store's citations leave out those from the documents that this
297    // run checked, because the run found those citations itself.
298    let excluding: BTreeSet<RepoPath> = checked.union(&round2).cloned().collect();
299    let mut citations = stored_citations(cache, &round2, &excluding);
300    for cited in out.citations.values() {
301        citations.extend(
302            cited
303                .iter()
304                .filter(|(target, _)| round2.contains(target))
305                .cloned(),
306        );
307    }
308    let second = check::run_units(
309        &loaded.model,
310        &loaded.compiled,
311        &loaded.expected,
312        &loaded.keys,
313        indexes,
314        Some(&round2),
315        citations,
316        false,
317    );
318    out.documents.extend(second.documents);
319    out.citations.extend(second.citations);
320    loaded.dirty.extend(round2);
321    Ok(())
322}
323
324/// `moved_citations` returns the query key of the citations of each target
325/// whose citations in `out` differ from those that the cache held.
326fn moved_citations(cache: &Cache, out: &check::RunOutput) -> BTreeSet<String> {
327    let mut moved: BTreeSet<String> = BTreeSet::new();
328    for (source, cited) in &out.citations {
329        let old = cache.old_citations(source);
330        let new: BTreeSet<CitedFact> = cited
331            .iter()
332            .map(|(target, c)| CitedFact::of(target, c))
333            .collect();
334        for fact in old.symmetric_difference(&new) {
335            moved.insert(Query::Citations(fact.target.clone()).key());
336        }
337    }
338    moved
339}
340
341/// `extend_keys` adds to `loaded.keys` the keys and the kept anchors of the
342/// documents of `round2`, which the run checks again, and then the store's
343/// keys and kept anchors for the slugs that a reference needs, except those
344/// of the documents of `checked`. It adds no key that `loaded.keys` already
345/// holds. The kept anchors that this run captured for a document of
346/// `round2` replace the store's.
347fn extend_keys(
348    cache: &Cache,
349    loaded: &mut Loaded,
350    round2: &BTreeSet<RepoPath>,
351    checked: &BTreeSet<RepoPath>,
352) {
353    // The coverage check of these documents reads the captured keys, and the
354    // store records each document's keys from `loaded.keys`. A key that the
355    // store already returned for a slug that a reference needs stays, and the
356    // captured key isn't added a second time.
357    let own = check::capture_keys_of(&loaded.model, &loaded.compiled, Some(round2));
358    let held: HashSet<(RepoPath, String)> = own
359        .document
360        .keys()
361        .filter(|k| loaded.keys.document.contains_key(*k))
362        .cloned()
363        .collect();
364    loaded.keys.extend(
365        own.document
366            .into_iter()
367            .filter(|(k, _)| !held.contains(k))
368            .flat_map(|(_, entries)| entries),
369    );
370    let slugs = needed_slugs(&loaded.model, &KeyIndex::default());
371    let stored = cache.stored_keys_for(&slugs, checked);
372    for (path, anchors) in stored.anchors {
373        if !round2.contains(&path) {
374            loaded.keys.anchors.entry(path).or_default().extend(anchors);
375        }
376    }
377    for path in round2 {
378        loaded.keys.anchors.remove(path);
379    }
380    loaded.keys.anchors.extend(own.anchors);
381    for entries in stored.document.into_values() {
382        for e in entries {
383            if !loaded
384                .keys
385                .document
386                .contains_key(&(e.path.clone(), e.id.clone()))
387            {
388                loaded.keys.add(e);
389            }
390        }
391    }
392}
393
394/// `record_run` stores in the cache what the run derived for each unit of
395/// `checked`: its findings, edges, queries, citations, keys and plans, and
396/// the result of each probe that the run made of a path that the walk
397/// didn't list.
398fn record_run(
399    cache: &Cache,
400    loaded: &Loaded,
401    out: &check::RunOutput,
402    checked: &BTreeSet<RepoPath>,
403) {
404    // Store what this run derived, for the next run to use: the findings of
405    // each unit, the unit's edges for `graph`, and the queries that the run
406    // made for the unit. Those queries include the ones made while the run
407    // worked out the unit's edges.
408    for (path, findings) in &out.documents {
409        cache.record_output(path, findings.clone());
410        if loaded.model.holds(path) || loaded.model.is_additional(path) {
411            loaded.model.watch(path);
412            cache.record_edges(path, crate::graph::edges_of(&loaded.model, path));
413            loaded.model.unwatch();
414        }
415        cache.record_deps(path, &loaded.model.reads_of(path));
416    }
417    for (source, cited) in &out.citations {
418        let rows = cited
419            .iter()
420            .map(|(target, c)| crate::cache::CitationRow {
421                target: target.clone(),
422                slug: c.slug.clone(),
423                source: c.source.clone(),
424                source_type: c.source_type.clone(),
425                rel: c.rel.clone(),
426                line: c.line,
427                include: c.include,
428                supersedes: c.supersedes,
429                retired: c.retired,
430                declared: c.declared,
431            })
432            .collect();
433        cache.record_citations(source, rows);
434    }
435    cache.record_keys_of(&loaded.keys, checked);
436    cache.record_plans_of(&loaded.model.plans, checked);
437    for queries in loaded.model.reads().values() {
438        for q in queries {
439            if let Query::Exists(p) = q
440                && !cache.is_walked(p)
441            {
442                cache.record_probe(p, loaded.model.tree.on_disk(p));
443            }
444        }
445    }
446}
447
448/// `prepare_fix` loads in full every document that a fix might rewrite: the
449/// documents with a finding, and the readers of each document that a fix
450/// moves. It loads those readers because their definition blocks contain the
451/// old path. It then loads the documents that these documents read. Last, it
452/// works out the keys and the expected content that the plan reads. `prepare_fix`
453/// returns the documents that the plan covers, or `None` for a full run.
454// sokf-implements: SOKF_VALIDATION_19
455fn prepare_fix(
456    root: &RepoRoot,
457    config: &Config,
458    cache: &Cache,
459    loaded: &mut Loaded,
460    findings: &[Finding],
461) -> Result<Option<BTreeSet<RepoPath>>> {
462    if loaded.full {
463        return Ok(None);
464    }
465    let mut fix_set: BTreeSet<RepoPath> = findings
466        .iter()
467        .filter(|f| loaded.model.is_unit(&f.path))
468        .map(|f| f.path.clone())
469        .collect();
470    // The plan also covers every index that has a finding, because the plan
471    // reads those indexes.
472    let indexes: BTreeSet<RepoPath> = findings
473        .iter()
474        .filter(|f| f.path.file_name() == "index.md" && !loaded.model.is_unit(&f.path))
475        .map(|f| f.path.clone())
476        .collect();
477    // A move changes the path of a document, and the readers of that
478    // document refer to the old path, so the loop collects the queries that
479    // find those readers.
480    let mut moved: BTreeSet<String> = BTreeSet::new();
481    for f in findings {
482        if !f.message.contains("its lifecycle states place it in") || !loaded.model.is_unit(&f.path)
483        {
484            continue;
485        }
486        moved.insert(Query::Path(f.path.clone()).key());
487        moved.insert(Query::Body(f.path.clone()).key());
488        if let Some(old) = cache.old_row(&f.path)
489            && let Some(id) = old.id
490        {
491            moved.insert(
492                Query::Doc {
493                    knowledge: old.knowledge,
494                    id,
495                }
496                .key(),
497            );
498        }
499        if let Some((_, asset)) = loaded.model.asset_of(&f.path) {
500            moved.insert(Query::Path(asset.path.clone()).key());
501        }
502    }
503    fix_set.extend(
504        cache
505            .readers_of(&moved)
506            .into_iter()
507            .filter(|p| loaded.model.is_unit(p)),
508    );
509    let mut loader = CachedLoader::new(root, cache);
510    admit_full(&mut loaded.model, &mut loader, cache, &fix_set)?;
511    // The plan runs over every document and additional file that the model
512    // holds so far. These include each file that the run read again, because
513    // its modification time was too close to the last sync to trust
514    // (`RACY_MARGIN`). The plan also loads the files that each of them
515    // reads, and reads those files without rewriting them.
516    let held: BTreeSet<RepoPath> = loaded
517        .model
518        .documents()
519        .map(|(_, d)| d.path.clone())
520        .chain(loaded.model.additional.iter().map(|a| a.path.clone()))
521        .collect();
522    admit_closure(&mut loaded.model, &mut loader, cache, &held);
523    admit_schemas_for(&mut loaded.model, &mut loader, cache, &held)?;
524    ensure_not_missed(cache)?;
525    loaded.compiled.compile_more(&loaded.model);
526    // The plan captures the keys of every document held in full, and takes
527    // the keys of the rest from the store by slug.
528    let mut keys = check::capture_keys_of(&loaded.model, &loaded.compiled, Some(&held));
529    let slugs = needed_slugs(&loaded.model, &keys);
530    keys.merge(cache.stored_keys_for(&slugs, &held));
531    // The layout of a pair depends only on its texts, so what the check
532    // settled stays true of the new expected content.
533    let layout = std::mem::take(&mut loaded.expected.layout);
534    loaded.expected = include::expected_for(&loaded.model, &keys, Some(&held));
535    loaded.expected.layout = layout;
536    settle(
537        cache,
538        config,
539        &loaded.model,
540        &mut loaded.expected,
541        None,
542        Some(&held),
543    );
544    loaded.keys = keys;
545    let mut over = held;
546    over.extend(indexes);
547    Ok(Some(over))
548}
549
550/// `plan_fix` loads what a fix needs and plans the fix.
551fn plan_fix(
552    root: &RepoRoot,
553    config: &Config,
554    cache: &Cache,
555    loaded: &mut Loaded,
556    findings: &[Finding],
557    scope: &config::Scope,
558) -> Result<fix::FixPlan> {
559    let over = prepare_fix(root, config, cache, loaded, findings)?;
560    fix::plan(
561        &loaded.model,
562        &loaded.compiled,
563        &loaded.expected,
564        &loaded.keys,
565        scope,
566        over.as_ref(),
567    )
568}
569
570/// `plan_is_stale` returns whether a plan would write where the tree of
571/// the run no longer matches the disk: it moves a file that is gone,
572/// rewrites a file that is gone, creates a file that the tree lists, or
573/// writes into a directory that the tree lists and that is gone. Only a run that
574/// took the tree from the store, with a hint, can make such a plan.
575// sokf-implements: CACHE-1_AC-54
576// sokf-implements: CACHE-1_AC-55
577fn plan_is_stale(root: &RepoRoot, model: &crate::Model, plan: &fix::FixPlan) -> bool {
578    let moved_to: BTreeSet<&RepoPath> = plan.moves.iter().map(|m| &m.to).collect();
579    let listed_dir = |d: &RepoPath| model.tree.dirs.binary_search_by(|x| x.path.cmp(d)).is_ok();
580    let gone_dir = |d: &RepoPath| listed_dir(d) && !d.to_fs(root).is_dir();
581    plan.moves
582        .iter()
583        .any(|m| !m.from.to_fs(root).exists() || m.to.parent().is_some_and(|d| gone_dir(&d)))
584        || plan
585            .rewrites
586            .iter()
587            .any(|r| !moved_to.contains(&r.path) && !r.path.to_fs(root).exists())
588        || plan.creates.iter().any(|c| {
589            model.tree.file(&c.path).is_some() || c.path.parent().is_some_and(|d| gone_dir(&d))
590        })
591}
592
593/// `fix_indexes` brings the index of each directory of `dirs` up to date,
594/// as `validate --fix` does, and repairs nothing else. It creates an index
595/// that is absent, leaves an index that isn't in the generated form, and
596/// returns what it wrote. When it writes, it checks again, as `validate`
597/// does after a fix, so that the cache holds the indexes that it wrote.
598pub(crate) fn fix_indexes(
599    root: &RepoRoot,
600    cache: CacheMode,
601    dirs: &[RepoPath],
602) -> Result<Vec<crate::FixOp>> {
603    let config = config::load_config(root)?;
604    let (grammar, repo_formats) = load_formats(root)?;
605    let cache = Cache::open(root, cache);
606    let scope = config::Scope {
607        files: dirs.iter().filter_map(|d| d.join("index.md")).collect(),
608        dirs: BTreeSet::default(),
609    };
610    let (mut loaded, findings) =
611        check_repository(root, &config, &grammar, &repo_formats, &cache, false)?;
612    let plan = plan_fix(root, &config, &cache, &mut loaded, &findings, &scope)?;
613    let (ops, _) = fix::apply(root, plan)?;
614    // The indexes are written whether or not the second check succeeds, and
615    // a full walk brings a cache that it failed to sync up to date.
616    if !ops.is_empty() {
617        let _ = check_repository(root, &config, &grammar, &repo_formats, &cache, false);
618    }
619    Ok(ops)
620}
621
622/// `FIX_PASSES` bounds the passes of one fix, and so the depth of a chain of
623/// includes that one run repairs.
624const FIX_PASSES: usize = 10;
625
626/// `validate` runs `sokf validate` and returns the report, and the
627/// report's projection when `opts.query` is given.
628// sokf-implements: CLI-4_AC-14
629// sokf-implements: SOKF_VALIDATION_39
630// sokf-implements: CLI-4_AC-2
631// sokf-implements: CLI-4_AC-5
632// sokf-implements: CLI-4_AC-1
633// sokf-implements: CLI-4_AC-4
634// sokf-implements: CLI-4_AC-22
635pub fn validate(
636    root: &RepoRoot,
637    opts: &ValidateOptions,
638) -> Result<(Report, Option<serde_json::Value>)> {
639    let config = config::load_config(root)?;
640    let (grammar, repo_formats) = load_formats(root)?;
641    let mut scope = config::resolve_paths(root, &opts.cwd, &opts.paths)?;
642    let cache = Cache::open(root, opts.cache);
643    if !opts.changed.is_empty() {
644        if opts.cache == CacheMode::Off {
645            return Err(Error::Internal(
646                "`--changed` needs the cache, so don't use it with `--no-cache`".into(),
647            ));
648        }
649        cache.set_hint(changed_paths(root, &opts.cwd, &opts.changed)?);
650    }
651    let check = || check_repository(root, &config, &grammar, &repo_formats, &cache, false);
652    let mut report = Report::default();
653    // With `--fix`, the fix plan covers the documents with findings, which
654    // `prepare_fix` loads in full after the first check. After the fix,
655    // `validate` checks again, and that second check syncs the cache with
656    // the files that the fix wrote.
657    let (mut loaded, mut findings) = check()?;
658    // A pass of the fix expands each include from its source as the source
659    // was before the pass, so a source that the pass repairs leaves its
660    // includes stale. The fix runs again while it leaves a stale include, and
661    // each pass expands from what the last one wrote. A chain of includes
662    // takes one pass for each link, up to `FIX_PASSES` (SOKF_VALIDATION_15,
663    // SOKF_VALIDATION_37).
664    let mut passes = 0;
665    while opts.fix && passes < FIX_PASSES {
666        passes += 1;
667        // The plan can rest on a removed file that the hint left out: a
668        // document with a stored finding, or a directory that the store
669        // lists. The run then checks the whole repository again before it
670        // plans the fix, so that the fix never writes into what was removed.
671        let mut plan = plan_fix(root, &config, &cache, &mut loaded, &findings, &scope);
672        let stale = matches!(&plan, Ok(p) if cache.hint().is_some()
673            && !cache.is_fresh()
674            && plan_is_stale(root, &loaded.model, p));
675        if stale {
676            cache.drop_hint();
677        }
678        if stale || hint_missed(root, &cache, plan.as_ref().err()) {
679            (loaded, findings) = check()?;
680            plan = plan_fix(root, &config, &cache, &mut loaded, &findings, &scope);
681        }
682        let plan = plan?;
683        for m in &plan.moves {
684            scope.add(m.to.clone());
685        }
686        let (ops, refused) = fix::apply(root, plan)?;
687        // The loop adds the files that the fix wrote to the hint, so that the
688        // next check reads their file metadata.
689        if let Some(mut hint) = cache.hint() {
690            for op in &ops {
691                match op {
692                    crate::FixOp::Moved { from, to } => {
693                        hint.push(from.clone());
694                        hint.push(to.clone());
695                    }
696                    crate::FixOp::Created { path } | crate::FixOp::Rewrote { path } => {
697                        hint.push(path.clone());
698                    }
699                }
700            }
701            cache.set_hint(hint);
702        }
703        let wrote = !ops.is_empty();
704        report.fixes.extend(ops);
705        report.extend(refused);
706        (loaded, findings) = check()?;
707        if !wrote || !findings.iter().any(|f| f.criterion == "SOKF_FORMAT_85") {
708            break;
709        }
710    }
711    report.extend(findings);
712    // The check of the configuration runs once in each run, outside the
713    // cache, because the configuration is no unit of the cache.
714    report.extend(check::check_config(&config));
715    report.extend(check::leftover_packs(root));
716    // The state of each installed harness lies outside the knowledge and
717    // the cache, so the run reads it afresh, as it reads the configuration.
718    report.extend(super::harness_stale::stale_parts(root, opts.home.clone()));
719    let report = report.finish().filter(&scope);
720    let projection = opts.query.as_ref().map(|q| report.project(q)).transpose()?;
721    Ok((report, projection))
722}