Skip to main content

vitrify_cli/cmd/
lint.rs

1//! `vitrify lint` — the mechanical authoring checks L1–L12.
2//! Named findings `{check, subject, cause, remediation}`; exit 0 clean / 2 on
3//! any finding. The remediation is the edit or the command that resolves it.
4//!
5//! L1–L8 hold one SDD to itself. L9–L12 hold it to what lies outside it and
6//! that it names: the contracts of other SDDs it pins (L9), its
7//! own changelog (L10), the TDD it is derived from (L11), and the units of
8//! other SDDs it waits on through pins (L12).
9
10use std::path::Path;
11
12use vitrify_core::CoreError;
13use vitrify_core::audit;
14use vitrify_core::config::Overrides;
15use vitrify_core::contract::State;
16use vitrify_core::graph::{self, Entry, Node, UnitGraph, render_path};
17use vitrify_core::model::{self, Instance, SddHandle, Shape, is_empty_marker};
18use vitrify_core::{changelog, contract, journal, questions, readset, tdd};
19
20use crate::out::{J, emit};
21
22/// The checks, as the clean line names them.
23pub const CHECKS: &str = "L1–L12";
24
25pub struct Finding {
26    pub check: &'static str,
27    pub subject: String,
28    pub cause: String,
29    /// The edit or the command that resolves it.
30    pub remediation: String,
31}
32
33fn f(
34    check: &'static str,
35    subject: impl Into<String>,
36    cause: impl Into<String>,
37    remediation: impl Into<String>,
38) -> Finding {
39    Finding {
40        check,
41        subject: subject.into(),
42        cause: cause.into(),
43        remediation: remediation.into(),
44    }
45}
46
47impl Finding {
48    /// `[L4] C-001: <cause> → <remediation>`
49    pub fn line(&self) -> String {
50        format!(
51            "[{}] {}: {} → {}",
52            self.check, self.subject, self.cause, self.remediation
53        )
54    }
55}
56
57pub struct Flags {
58    pub sdd: Option<String>,
59    /// Every SDD of the repository.
60    pub all: bool,
61    /// Lint an SDD that is being built or has been: every check but L7.
62    pub built: bool,
63    pub json: bool,
64}
65
66fn findings_json(findings: &[Finding]) -> Vec<(String, J)> {
67    let jf: Vec<J> = findings
68        .iter()
69        .map(|x| {
70            J::Obj(vec![
71                ("check".into(), J::s(x.check)),
72                ("subject".into(), J::s(x.subject.clone())),
73                ("cause".into(), J::s(x.cause.clone())),
74                ("remediation".into(), J::s(x.remediation.clone())),
75            ])
76        })
77        .collect();
78    vec![
79        ("clean".into(), J::Bool(findings.is_empty())),
80        ("findings".into(), J::Arr(jf)),
81    ]
82}
83
84pub fn run(flags: Flags) -> Result<u8, CoreError> {
85    let root = super::repo_root();
86    let sdds = super::targets(&root, flags.sdd.as_deref(), flags.all, &super::cwd())?;
87    let budget = super::load_config(&Overrides::default())?
88        .lint
89        .readset_budget_bytes;
90    let lint = |sdd: &SddHandle| -> Result<Vec<Finding>, CoreError> {
91        let inst = Instance::load(sdd.clone())?;
92        if flags.built {
93            pre_run_findings(&inst, &root, budget)
94        } else {
95            check_all(&inst, &root, budget)
96        }
97    };
98
99    if !flags.all {
100        let findings = lint(&sdds[0])?;
101        if flags.json {
102            emit(&J::Obj(findings_json(&findings)).dumps_indent2());
103        } else {
104            if findings.is_empty() {
105                emit(&format!("lint clean ({CHECKS})"));
106            }
107            for x in &findings {
108                emit(&x.line());
109            }
110        }
111        return Ok(if findings.is_empty() { 0 } else { 2 });
112    }
113
114    // every SDD: one line per finding, each under its SDD's name
115    let mut reports: Vec<J> = Vec::new();
116    let code = super::each(&root, &sdds, |sdd| {
117        let findings = lint(sdd)?;
118        let name = super::label(sdd, &root);
119        if flags.json {
120            let mut pairs = vec![
121                ("sdd".into(), J::s(name)),
122                ("root".into(), J::s(super::shown(&root, &sdd.root))),
123            ];
124            pairs.extend(findings_json(&findings));
125            reports.push(J::Obj(pairs));
126        } else {
127            if findings.is_empty() {
128                emit(&format!("{name}: lint clean ({CHECKS})"));
129            }
130            for x in &findings {
131                emit(&format!("{name}: {}", x.line()));
132            }
133        }
134        Ok(if findings.is_empty() { 0 } else { 2 })
135    });
136    if flags.json {
137        emit(&J::Arr(reports).dumps_indent2());
138    }
139    Ok(code)
140}
141
142/// `U-001`; `U-001 and U-002`; `U-001, U-002 and U-003`.
143fn listed(ids: &[String]) -> String {
144    match ids {
145        [] => String::new(),
146        [one] => one.clone(),
147        [init @ .., last] => format!("{} and {last}", init.join(", ")),
148    }
149}
150
151pub fn check_all(inst: &Instance, root: &Path, budget: i64) -> Result<Vec<Finding>, CoreError> {
152    let mut findings: Vec<Finding> = Vec::new();
153    let units = &inst.units;
154    let unit_ids: Vec<&str> = units.iter().map(|u| u.unit.as_str()).collect();
155    // the SDD as a `--sdd` value
156    let at = super::shown(root, &inst.root);
157    let handle = inst.handle();
158
159    // L1 — DAG acyclic; every depends_on entry is a unit of this SDD or —
160    // from schema 2.1 — a pin of it the unit also consumes
161    for ue in graph::classify(inst)? {
162        for (d, entry) in &ue.entries {
163            if let Entry::Invalid(p) = entry {
164                findings.push(f(
165                    "L1",
166                    ue.unit.clone(),
167                    p.cause(&ue.unit, d),
168                    p.remediation(&ue.unit, d),
169                ));
170            }
171        }
172    }
173    if let Some(cycle) = find_cycle(units) {
174        findings.push(f(
175            "L1",
176            cycle.join(" → "),
177            "depends_on graph contains a cycle",
178            "remove one of the cycle's depends_on edges",
179        ));
180    }
181
182    // L2 — ownership exclusive + exhaustive over scope_roots
183    let owns: Vec<(String, Vec<String>)> = units
184        .iter()
185        .map(|u| (u.unit.clone(), u.meta.get_list("owns")))
186        .collect();
187    for (i, (ua, gsa)) in owns.iter().enumerate() {
188        for (ub, gsb) in owns.iter().skip(i + 1) {
189            for ga in gsa {
190                for gb in gsb {
191                    if globs_overlap(ga, gb) {
192                        findings.push(f(
193                            "L2",
194                            format!("{ua}/{ub}"),
195                            format!("owns globs can match a common path: `{ga}` vs `{gb}`"),
196                            format!("narrow {ua}'s or {ub}'s owns so no path matches both"),
197                        ));
198                    }
199                }
200            }
201        }
202    }
203    let core_text = model::read_text(&inst.file)?;
204    let unmanaged = unmanaged_globs(&core_text);
205    let tests = audit::tests_globs(&core_text);
206    let tests_counted = inst.schema().tests_list();
207    if tests_counted {
208        let scope_roots = inst.meta.get_list("scope_roots");
209        for t in &tests {
210            if !audit::tests_entry_in_scope(t, &scope_roots) {
211                findings.push(f(
212                    "L2",
213                    t.clone(),
214                    format!("tests: entry `{t}` lies outside scope_roots"),
215                    format!("narrow `{t}` to a path under scope_roots, or remove it from tests:"),
216                ));
217            }
218        }
219        for t in &tests {
220            for u in &unmanaged {
221                if globs_overlap(t, u) {
222                    findings.push(f(
223                        "L2",
224                        t.clone(),
225                        format!(
226                            "tests: entry `{t}` and unmanaged: entry `{u}` can match a common path"
227                        ),
228                        "narrow one of them so no path is both a test and unmanaged",
229                    ));
230                }
231            }
232        }
233    } else if !tests.is_empty() {
234        let version = inst.schema().as_str();
235        findings.push(f(
236            "L2",
237            "tests:",
238            format!(
239                "§6 lists tests:, and this SDD declares schema_version {version} — a tests: list is schema 2.2"
240            ),
241            "set schema_version: 2.2 in the SDD's core front matter (a PATCH change entry), or remove the tests: list",
242        ));
243    }
244    // the governed tree: what git would commit (its ignore rules decide,
245    // whatever the ecosystem); outside a repository, every file on disk
246    let scope_files = super::governed_files(root, inst)
247        .unwrap_or_else(|| audit::walk_scope(root, &inst.meta.get_list("scope_roots")));
248    for file in &scope_files {
249        let owned = owns
250            .iter()
251            .any(|(_, gs)| gs.iter().any(|g| audit::matches(file, g)))
252            || unmanaged.iter().any(|g| audit::matches(file, g))
253            || (tests_counted && tests.iter().any(|g| audit::matches(file, g)));
254        if !owned {
255            findings.push(f(
256                "L2",
257                file.clone(),
258                "file under scope_roots is neither owned nor unmanaged",
259                "add a glob that matches it to one unit's owns, or list it under unmanaged: in System Layout & Ownership",
260            ));
261        }
262    }
263
264    // L3 — parallel groups mutually independent (no intra-group deps)
265    for u in units {
266        let group = u.meta.get_str_or("parallel_group", "");
267        if is_empty_marker(group.trim()) {
268            continue;
269        }
270        for d in u.meta.get_list("depends_on") {
271            if let Some(dep) = units.iter().find(|x| x.unit == d)
272                && dep.meta.get_str_or("parallel_group", "") == group
273            {
274                findings.push(f(
275                    "L3",
276                    u.unit.clone(),
277                    format!("depends on {d} inside its own parallel group {group}"),
278                    format!(
279                        "move {} or {d} to another parallel_group, or drop the dependency",
280                        u.unit
281                    ),
282                ));
283            }
284        }
285    }
286
287    // L4 — contract reference integrity
288    for u in units {
289        for cid in u.meta.get_list("consumes") {
290            if model::contract_text(&handle, &cid)?.is_none() {
291                findings.push(f(
292                    "L4",
293                    u.unit.clone(),
294                    format!("consumes unresolvable contract {cid}"),
295                    format!(
296                        "write contract {cid}, or remove it from {}'s consumes",
297                        u.unit
298                    ),
299                ));
300            }
301        }
302    }
303    for (cid, cref) in audit::contract_refs(inst)? {
304        let mut refs: Vec<&String> = Vec::new();
305        if let Some(p) = &cref.producer {
306            refs.push(p);
307        }
308        refs.extend(cref.consumers.iter());
309        for uid in refs {
310            if !unit_ids.contains(&uid.as_str()) {
311                findings.push(f(
312                    "L4",
313                    cid.clone(),
314                    format!("references nonexistent unit {uid}"),
315                    format!(
316                        "make {cid}'s Producer and Consumers lines name only units the SDD has"
317                    ),
318                ));
319            }
320        }
321    }
322    // … and both ways round: a contract's Consumers line names exactly the
323    // units that list it in `consumes` (its producer apart, which may
324    // consume its own contract)
325    let contracts = contract::list(&handle)?;
326    for c in &contracts {
327        if let Some((header_only, consumes_only)) = contract::consumer_mismatch(c, units) {
328            let mut parts: Vec<String> = Vec::new();
329            if !header_only.is_empty() {
330                parts.push(format!(
331                    "names {}, which {} not list it in `consumes`",
332                    listed(&header_only),
333                    if header_only.len() == 1 { "does" } else { "do" }
334                ));
335            }
336            if !consumes_only.is_empty() {
337                parts.push(format!(
338                    "omits {}, which {} it",
339                    listed(&consumes_only),
340                    if consumes_only.len() == 1 {
341                        "consumes"
342                    } else {
343                        "consume"
344                    }
345                ));
346            }
347            findings.push(f(
348                "L4",
349                c.id.clone(),
350                format!("its Consumers line {}", parts.join(" and ")),
351                format!(
352                    "make {}'s Consumers line name exactly the units that list it in consumes",
353                    c.id
354                ),
355            ));
356        }
357    }
358
359    // L5 — reading-set budget
360    let peers = super::peers(root);
361    for u in units {
362        match readset::resolve(inst, &u.unit, &peers) {
363            Ok(items) => {
364                let total: i64 = items.iter().map(|i| i.bytes as i64).sum();
365                if total > budget {
366                    findings.push(f(
367                        "L5",
368                        u.unit.clone(),
369                        format!("reading set totals {total} bytes, over budget {budget}"),
370                        format!(
371                            "split {} or shrink what it reads (vitrify readset --unit {} --sdd {at} lists it)",
372                            u.unit, u.unit
373                        ),
374                    ));
375                }
376            }
377            // a missing consumed contract is L4's finding, not L5's — and a
378            // pin that does not resolve, L9's — unless something else is
379            // wrong with the set as well
380            Err(e)
381                if e.to_string().lines().all(|l| {
382                    l.contains("consumed contract missing") || l.contains(readset::PIN_PROBLEM)
383                }) => {}
384            Err(e) => findings.push(f(
385                "L5",
386                u.unit.clone(),
387                format!(
388                    "reading set does not resolve: {}",
389                    e.to_string().replace('\n', "; ")
390                ),
391                format!(
392                    "make every path {}'s reading set names exist (vitrify readset --unit {} --sdd {at})",
393                    u.unit, u.unit
394                ),
395            )),
396        }
397    }
398
399    // L6 — requirement coverage in the Verification Covers column
400    for u in units {
401        let text = unit_text(inst, u)?;
402        let declared = declared_requirements(&text, &u.unit);
403        let covers = covers_tokens(&text);
404        let covers_all = covers.iter().any(|t| t.eq_ignore_ascii_case("all"));
405        for r in &declared {
406            let short = format!("R{r}");
407            let full = format!("{}.R{r}", u.unit);
408            if !covers_all && !covers.contains(&short) && !covers.contains(&full) {
409                findings.push(f(
410                    "L6",
411                    u.unit.clone(),
412                    format!("requirement {full} not covered by any Verification row"),
413                    format!(
414                        "add a Verification row whose Covers column names {short}, or remove {full}"
415                    ),
416                ));
417            }
418        }
419    }
420
421    // L7 — pre-build state sanity. An SDD with a journal is being built, or
422    // has been: its build state is lint --built's to judge.
423    let built = journal::read(&handle)?.1;
424    let l7 = |unit: &str, cause: &str, clear: &str| {
425        let remediation = if built {
426            format!("the SDD is being built: vitrify lint --built --sdd {at}")
427        } else {
428            format!("{clear} in {unit}'s entry: the build sets it")
429        };
430        f("L7", unit, cause, remediation)
431    };
432    for u in units {
433        let status = u.meta.get_str_or("status", "Draft");
434        if status != "Draft" && status != "Ready" {
435            findings.push(l7(
436                &u.unit,
437                &format!("status {status} is beyond Ready before the build"),
438                "set status to Draft or Ready",
439            ));
440        }
441        if !is_empty_marker(u.meta.get_str_or("claimed_by", "").trim()) {
442            findings.push(l7(
443                &u.unit,
444                "claimed_by set before the build",
445                "set claimed_by to —",
446            ));
447        }
448        if !is_empty_marker(u.meta.get_str_or("claim_expires", "").trim()) {
449            findings.push(l7(
450                &u.unit,
451                "claim_expires set before the build",
452                "set claim_expires to —",
453            ));
454        }
455        if u.meta.get_map("trace").is_some_and(|m| !m.is_empty()) {
456            findings.push(l7(
457                &u.unit,
458                "trace recorded before the build",
459                "remove the trace map",
460            ));
461        }
462    }
463
464    // L8 — no OPEN(Q-###) inside any Ready unit's region; and whatever its
465    // status, a marker names a question the Decision Log holds
466    let asked: Vec<String> = questions::of(&handle)?.into_iter().map(|q| q.id).collect();
467    for u in units {
468        let text = unit_text(inst, u)?;
469        let markers = questions::markers(&text);
470        if u.meta.get_str_or("status", "Draft") == "Ready" && text.contains("OPEN(Q-") {
471            let named = if markers.is_empty() {
472                "the question".to_string()
473            } else {
474                listed(&markers)
475            };
476            findings.push(f(
477                "L8",
478                u.unit.clone(),
479                "OPEN(Q-###) marker inside a Ready unit's region",
480                format!(
481                    "resolve {named} in the Decision Log and remove the marker, or set {} back to Draft",
482                    u.unit
483                ),
484            ));
485        }
486        for q in markers {
487            if !asked.contains(&q) {
488                findings.push(f(
489                    "L8",
490                    u.unit.clone(),
491                    format!("OPEN({q}) names a question with no entry in the Decision Log"),
492                    format!("add {q} to the Decision Log, or correct the marker"),
493                ));
494            }
495        }
496    }
497
498    // L9 — an external contract is its authority's: a pin's hash is the
499    // hash of the body it stands for, and the authority it names is there
500    // to be found
501    for (subject, cause, remediation) in pin_findings(inst, &peers, &at)? {
502        findings.push(f("L9", subject, cause, remediation));
503    }
504
505    // L10 — the front matter's version and date are the last change
506    // entry's, and change entries are in id order
507    let entries = changelog::entries(&handle)?;
508    let last = entries.iter().max_by_key(|e| e.number);
509    for (subject, cause) in changelog::findings(
510        &entries,
511        inst.meta.get_str_or("version", ""),
512        inst.meta.get_str_or("updated", ""),
513    ) {
514        let remediation = match (subject.as_str(), last) {
515            ("version" | "updated", Some(last)) => format!(
516                "set version and updated in the front matter to {}'s ({} and {})",
517                last.id,
518                last.to.as_deref().unwrap_or("its target version"),
519                last.date.as_deref().unwrap_or("its date")
520            ),
521            _ => format!(
522                "give {subject} the next unused id: change entries are appended in id order, newest last"
523            ),
524        };
525        findings.push(f("L10", subject, cause, remediation));
526    }
527    // … and a single file's entries are where they are read
528    for (id, hashes) in changelog::misplaced(&handle)? {
529        let (cause, remediation) = changelog::misplaced_finding(&id, hashes);
530        findings.push(f("L10", id, cause, remediation));
531    }
532
533    // L11 — the TDD pin: `tdd:` names a file, and an Active SDD pins the
534    // current revision of an Approved TDD
535    for (subject, cause) in
536        tdd::findings(&inst.meta, &inst.file, root, |p| model::read_text(p).ok())
537    {
538        let remediation = match subject.as_str() {
539            "tdd_version" => {
540                "re-pin tdd_version to the TDD's Revision in a change entry (vitrify brief change)"
541            }
542            _ if cause.contains("names no file") => {
543                "set tdd: to the TDD's path, from the SDD's directory or the repository root"
544            }
545            _ => "approve the TDD (Status: Approved), or keep the SDD Draft until it is",
546        };
547        findings.push(f("L11", subject, cause, remediation));
548    }
549
550    // L12 — across SDDs: every pin in depends_on leads to the units that
551    // produce its authority, and no cycle runs through pins. Every SDD on
552    // such a cycle, or behind one, has a pin in depends_on of its own.
553    if graph::classify(inst)?
554        .iter()
555        .any(|ue| ue.entries.iter().any(|(_, e)| matches!(e, Entry::Pin(_))))
556    {
557        let unit_graph = super::repo_graph(root, Some(inst))?;
558        findings.extend(graph_findings(inst, &unit_graph));
559    }
560
561    Ok(findings)
562}
563
564/// L12's findings for `inst` in the repository's unit graph: its pins in
565/// `depends_on` whose authority names no units of its SDD; every cycle
566/// through pins that runs through one of its units, as the path that closes
567/// it; and its units that only wait behind such a cycle. A cycle through
568/// pins crosses SDDs, or takes an edge that only a pin makes — a pin of the
569/// SDD's own contract, too. A cycle of the SDD's units alone is L1's.
570pub fn graph_findings(inst: &Instance, unit_graph: &UnitGraph) -> Vec<Finding> {
571    let slug = graph::slug_of(inst);
572    let mut findings: Vec<Finding> = unit_graph
573        .problems()
574        .iter()
575        .filter(|p| p.slug == slug && p.check() == "L12")
576        .map(|p| f("L12", p.unit.clone(), p.cause(), p.remediation()))
577        .collect();
578    let Err(cycles) = unit_graph.resolve() else {
579        return findings;
580    };
581    let crosses = |path: &[Node]| path.iter().any(|n| n.slug != path[0].slug);
582    let through_pins: Vec<&Vec<Node>> = cycles
583        .cycles
584        .iter()
585        .filter(|path| crosses(path) || path.windows(2).any(|w| pin_only(unit_graph, &w[0], &w[1])))
586        .collect();
587    for path in &through_pins {
588        if path.iter().any(|n| n.slug == slug) {
589            let cause = if crosses(path) {
590                "depends_on graph across SDDs contains a cycle through pins"
591            } else {
592                "depends_on graph contains a cycle through a pin of this SDD's own contract"
593            };
594            findings.push(f(
595                "L12",
596                render_path(path),
597                cause,
598                "remove one of the cycle's depends_on edges — a pin a unit only reads stays in consumes alone",
599            ));
600        }
601    }
602    for n in cycles.waiting.iter().filter(|n| n.slug == slug) {
603        if let Some(path) = through_pins
604            .iter()
605            .find(|path| waits_on(unit_graph, n, path))
606        {
607            findings.push(f(
608                "L12",
609                n.unit.clone(),
610                format!("waits behind the cycle {}", render_path(path)),
611                "break the cycle its own L12 finding names",
612            ));
613        }
614    }
615    findings
616}
617
618/// Whether `from` depends on `to` only through a pin: no `depends_on` entry
619/// names `to` directly.
620fn pin_only(unit_graph: &UnitGraph, from: &Node, to: &Node) -> bool {
621    let edges: Vec<_> = unit_graph
622        .edges()
623        .iter()
624        .filter(|e| &e.from == from && &e.to == to)
625        .collect();
626    !edges.is_empty() && edges.iter().all(|e| e.via.is_some())
627}
628
629/// Whether `n` depends, transitively, on a unit of `path`.
630fn waits_on(unit_graph: &UnitGraph, n: &Node, path: &[Node]) -> bool {
631    let mut seen: Vec<&Node> = Vec::new();
632    let mut stack: Vec<&Node> = vec![n];
633    while let Some(x) = stack.pop() {
634        for d in unit_graph.dependencies(x) {
635            if path.contains(d) {
636                return true;
637            }
638            if !seen.contains(&d) {
639                seen.push(d);
640                stack.push(d);
641            }
642        }
643    }
644    false
645}
646
647/// The external contracts of `inst` that are not `ok`, as
648/// `(contract, cause, remediation)`; `at` is the SDD as a `--sdd` value.
649/// Lint reports them as L9, and `vitrify check` as its pin source.
650pub fn pin_findings(
651    inst: &Instance,
652    peers: &contract::Peers,
653    at: &str,
654) -> Result<Vec<(String, String, String)>, CoreError> {
655    Ok(contract::examine(inst, peers)?
656        .into_iter()
657        .filter(|ext| ext.state.is_finding())
658        .map(|ext| {
659            let remediation = match ext.state {
660                State::Stale => format!("vitrify pin sync --sdd {at}"),
661                State::MissingAuthority => format!(
662                    "make {}'s Pin: line name an SDD and contract this repository has (vitrify pin list --all)",
663                    ext.id
664                ),
665                _ => format!(
666                    "correct {}'s header as its cause says (vitrify schema show, Interface Contracts)",
667                    ext.id
668                ),
669            };
670            (ext.id, ext.detail, remediation)
671        })
672        .collect())
673}
674
675/// Findings of every check except L7 — the resume-tolerant subset the
676/// orchestrator preflights with on an Active, partially-built SDD.
677pub fn pre_run_findings(
678    inst: &Instance,
679    root: &Path,
680    budget: i64,
681) -> Result<Vec<Finding>, CoreError> {
682    Ok(check_all(inst, root, budget)?
683        .into_iter()
684        .filter(|x| x.check != "L7")
685        .collect())
686}
687
688fn find_cycle(units: &[model::Unit]) -> Option<Vec<String>> {
689    // DFS with a path stack; returns the first cycle found.
690    fn visit(
691        uid: &str,
692        units: &[model::Unit],
693        path: &mut Vec<String>,
694        done: &mut Vec<String>,
695    ) -> Option<Vec<String>> {
696        if done.iter().any(|d| d == uid) {
697            return None;
698        }
699        if let Some(pos) = path.iter().position(|p| p == uid) {
700            let mut cycle = path[pos..].to_vec();
701            cycle.push(uid.to_string());
702            return Some(cycle);
703        }
704        path.push(uid.to_string());
705        if let Some(u) = units.iter().find(|u| u.unit == uid) {
706            for d in u.meta.get_list("depends_on") {
707                if let Some(c) = visit(&d, units, path, done) {
708                    return Some(c);
709                }
710            }
711        }
712        path.pop();
713        done.push(uid.to_string());
714        None
715    }
716    let mut done = Vec::new();
717    for u in units {
718        if let Some(c) = visit(&u.unit, units, &mut Vec::new(), &mut done) {
719            return Some(c);
720        }
721    }
722    None
723}
724
725/// Conservative literal/prefix overlap between two owns globs.
726fn globs_overlap(a: &str, b: &str) -> bool {
727    let lit = |g: &str| -> (String, bool) {
728        match g.find(['*', '?', '[']) {
729            Some(i) => (g[..i].to_string(), true),
730            None => (g.trim_end_matches('/').to_string(), false),
731        }
732    };
733    let (pa, wild_a) = lit(a);
734    let (pb, wild_b) = lit(b);
735    if !wild_a && !wild_b {
736        return pa == pb || pa.starts_with(&format!("{pb}/")) || pb.starts_with(&format!("{pa}/"));
737    }
738    pa.starts_with(&pb) || pb.starts_with(&pa)
739}
740
741fn unmanaged_globs(core_text: &str) -> Vec<String> {
742    let sec = model::section(core_text, "System Layout & Ownership");
743    let mut out = Vec::new();
744    let mut in_block = false;
745    for line in sec.lines() {
746        if !in_block {
747            if line.trim() == "unmanaged:" {
748                in_block = true;
749            }
750            continue;
751        }
752        let trimmed = line.trim_start();
753        if let Some(item) = trimmed.strip_prefix("- ")
754            && line.starts_with(|c: char| c.is_whitespace())
755        {
756            out.push(item.trim().to_string());
757        } else {
758            break;
759        }
760    }
761    out
762}
763
764fn unit_text(inst: &Instance, u: &model::Unit) -> Result<String, CoreError> {
765    match inst.shape {
766        Shape::Bundle => model::read_text(&u.file),
767        Shape::Single => {
768            let text = model::read_text(&inst.file)?;
769            Ok(model::find_unit_span(&text, &u.unit)
770                .map(|(s, e)| text[s..e].to_string())
771                .unwrap_or_default())
772        }
773    }
774}
775
776/// Requirement numbers declared as `U-###.R<n>` in the unit's text.
777fn declared_requirements(text: &str, unit_id: &str) -> Vec<u32> {
778    let needle = format!("{unit_id}.R");
779    let mut out: Vec<u32> = Vec::new();
780    let mut search = text;
781    while let Some(i) = search.find(&needle) {
782        let rest = &search[i + needle.len()..];
783        let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
784        if let Ok(n) = digits.parse::<u32>()
785            && !out.contains(&n)
786        {
787            out.push(n);
788        }
789        search = &search[i + needle.len()..];
790    }
791    out
792}
793
794/// First-column tokens of every Verification table row.
795fn covers_tokens(text: &str) -> Vec<String> {
796    let mut tokens = Vec::new();
797    let mut in_section = false;
798    for line in text.lines() {
799        let is_heading = line.starts_with("##");
800        if is_heading {
801            in_section = line
802                .trim_start_matches('#')
803                .trim()
804                .eq_ignore_ascii_case("Verification");
805            continue;
806        }
807        if !in_section || !line.trim_start().starts_with('|') {
808            continue;
809        }
810        let stripped = line.trim().trim_matches('|');
811        let cells: Vec<&str> = stripped.split('|').map(str::trim).collect();
812        if cells.is_empty() {
813            continue;
814        }
815        let first = cells[0];
816        if first.chars().all(|c| c == '-' || c == ' ' || c == ':')
817            || first.eq_ignore_ascii_case("covers")
818        {
819            continue;
820        }
821        for tok in first.split([',', '·']) {
822            let t = tok.trim().trim_matches('*').trim();
823            if t.is_empty() {
824                continue;
825            }
826            // expand ranges like R1–R4 / R1-R4
827            if let Some((lo, hi)) = parse_range(t) {
828                for n in lo..=hi {
829                    tokens.push(format!("R{n}"));
830                }
831            } else {
832                tokens.push(t.to_string());
833            }
834        }
835    }
836    tokens
837}
838
839/// Parse `R<a>–R<b>` / `R<a>-R<b>` range tokens.
840fn parse_range(token: &str) -> Option<(u32, u32)> {
841    for sep in ['\u{2013}', '-'] {
842        if let Some((a, b)) = token.split_once(sep) {
843            let lo = a.trim().strip_prefix('R')?.parse().ok()?;
844            let hi = b.trim().strip_prefix('R')?.parse().ok()?;
845            return Some((lo, hi));
846        }
847    }
848    None
849}