1use 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
22pub const CHECKS: &str = "L1–L12";
24
25pub struct Finding {
26 pub check: &'static str,
27 pub subject: String,
28 pub cause: String,
29 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 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 pub all: bool,
61 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 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
142fn 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 let at = super::shown(root, &inst.root);
157 let handle = inst.handle();
158
159 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 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 scope_files = super::governed_files(root, inst)
208 .unwrap_or_else(|| audit::walk_scope(root, &inst.meta.get_list("scope_roots")));
209 for file in &scope_files {
210 let owned = owns
211 .iter()
212 .any(|(_, gs)| gs.iter().any(|g| audit::matches(file, g)))
213 || unmanaged.iter().any(|g| audit::matches(file, g));
214 if !owned {
215 findings.push(f(
216 "L2",
217 file.clone(),
218 "file under scope_roots is neither owned nor unmanaged",
219 "add a glob that matches it to one unit's owns, or list it under unmanaged: in System Layout & Ownership",
220 ));
221 }
222 }
223
224 for u in units {
226 let group = u.meta.get_str_or("parallel_group", "");
227 if is_empty_marker(group.trim()) {
228 continue;
229 }
230 for d in u.meta.get_list("depends_on") {
231 if let Some(dep) = units.iter().find(|x| x.unit == d)
232 && dep.meta.get_str_or("parallel_group", "") == group
233 {
234 findings.push(f(
235 "L3",
236 u.unit.clone(),
237 format!("depends on {d} inside its own parallel group {group}"),
238 format!(
239 "move {} or {d} to another parallel_group, or drop the dependency",
240 u.unit
241 ),
242 ));
243 }
244 }
245 }
246
247 for u in units {
249 for cid in u.meta.get_list("consumes") {
250 if model::contract_text(&handle, &cid)?.is_none() {
251 findings.push(f(
252 "L4",
253 u.unit.clone(),
254 format!("consumes unresolvable contract {cid}"),
255 format!(
256 "write contract {cid}, or remove it from {}'s consumes",
257 u.unit
258 ),
259 ));
260 }
261 }
262 }
263 for (cid, cref) in audit::contract_refs(inst)? {
264 let mut refs: Vec<&String> = Vec::new();
265 if let Some(p) = &cref.producer {
266 refs.push(p);
267 }
268 refs.extend(cref.consumers.iter());
269 for uid in refs {
270 if !unit_ids.contains(&uid.as_str()) {
271 findings.push(f(
272 "L4",
273 cid.clone(),
274 format!("references nonexistent unit {uid}"),
275 format!(
276 "make {cid}'s Producer and Consumers lines name only units the SDD has"
277 ),
278 ));
279 }
280 }
281 }
282 let contracts = contract::list(&handle)?;
286 for c in &contracts {
287 if let Some((header_only, consumes_only)) = contract::consumer_mismatch(c, units) {
288 let mut parts: Vec<String> = Vec::new();
289 if !header_only.is_empty() {
290 parts.push(format!(
291 "names {}, which {} not list it in `consumes`",
292 listed(&header_only),
293 if header_only.len() == 1 { "does" } else { "do" }
294 ));
295 }
296 if !consumes_only.is_empty() {
297 parts.push(format!(
298 "omits {}, which {} it",
299 listed(&consumes_only),
300 if consumes_only.len() == 1 {
301 "consumes"
302 } else {
303 "consume"
304 }
305 ));
306 }
307 findings.push(f(
308 "L4",
309 c.id.clone(),
310 format!("its Consumers line {}", parts.join(" and ")),
311 format!(
312 "make {}'s Consumers line name exactly the units that list it in consumes",
313 c.id
314 ),
315 ));
316 }
317 }
318
319 let peers = super::peers(root);
321 for u in units {
322 match readset::resolve(inst, &u.unit, &peers) {
323 Ok(items) => {
324 let total: i64 = items.iter().map(|i| i.bytes as i64).sum();
325 if total > budget {
326 findings.push(f(
327 "L5",
328 u.unit.clone(),
329 format!("reading set totals {total} bytes, over budget {budget}"),
330 format!(
331 "split {} or shrink what it reads (vitrify readset --unit {} --sdd {at} lists it)",
332 u.unit, u.unit
333 ),
334 ));
335 }
336 }
337 Err(e)
341 if e.to_string().lines().all(|l| {
342 l.contains("consumed contract missing") || l.contains(readset::PIN_PROBLEM)
343 }) => {}
344 Err(e) => findings.push(f(
345 "L5",
346 u.unit.clone(),
347 format!(
348 "reading set does not resolve: {}",
349 e.to_string().replace('\n', "; ")
350 ),
351 format!(
352 "make every path {}'s reading set names exist (vitrify readset --unit {} --sdd {at})",
353 u.unit, u.unit
354 ),
355 )),
356 }
357 }
358
359 for u in units {
361 let text = unit_text(inst, u)?;
362 let declared = declared_requirements(&text, &u.unit);
363 let covers = covers_tokens(&text);
364 let covers_all = covers.iter().any(|t| t.eq_ignore_ascii_case("all"));
365 for r in &declared {
366 let short = format!("R{r}");
367 let full = format!("{}.R{r}", u.unit);
368 if !covers_all && !covers.contains(&short) && !covers.contains(&full) {
369 findings.push(f(
370 "L6",
371 u.unit.clone(),
372 format!("requirement {full} not covered by any Verification row"),
373 format!(
374 "add a Verification row whose Covers column names {short}, or remove {full}"
375 ),
376 ));
377 }
378 }
379 }
380
381 let built = journal::read(&handle)?.1;
384 let l7 = |unit: &str, cause: &str, clear: &str| {
385 let remediation = if built {
386 format!("the SDD is being built: vitrify lint --built --sdd {at}")
387 } else {
388 format!("{clear} in {unit}'s entry: the build sets it")
389 };
390 f("L7", unit, cause, remediation)
391 };
392 for u in units {
393 let status = u.meta.get_str_or("status", "Draft");
394 if status != "Draft" && status != "Ready" {
395 findings.push(l7(
396 &u.unit,
397 &format!("status {status} is beyond Ready before the build"),
398 "set status to Draft or Ready",
399 ));
400 }
401 if !is_empty_marker(u.meta.get_str_or("claimed_by", "").trim()) {
402 findings.push(l7(
403 &u.unit,
404 "claimed_by set before the build",
405 "set claimed_by to —",
406 ));
407 }
408 if !is_empty_marker(u.meta.get_str_or("claim_expires", "").trim()) {
409 findings.push(l7(
410 &u.unit,
411 "claim_expires set before the build",
412 "set claim_expires to —",
413 ));
414 }
415 if u.meta.get_map("trace").is_some_and(|m| !m.is_empty()) {
416 findings.push(l7(
417 &u.unit,
418 "trace recorded before the build",
419 "remove the trace map",
420 ));
421 }
422 }
423
424 let asked: Vec<String> = questions::of(&handle)?.into_iter().map(|q| q.id).collect();
427 for u in units {
428 let text = unit_text(inst, u)?;
429 let markers = questions::markers(&text);
430 if u.meta.get_str_or("status", "Draft") == "Ready" && text.contains("OPEN(Q-") {
431 let named = if markers.is_empty() {
432 "the question".to_string()
433 } else {
434 listed(&markers)
435 };
436 findings.push(f(
437 "L8",
438 u.unit.clone(),
439 "OPEN(Q-###) marker inside a Ready unit's region",
440 format!(
441 "resolve {named} in the Decision Log and remove the marker, or set {} back to Draft",
442 u.unit
443 ),
444 ));
445 }
446 for q in markers {
447 if !asked.contains(&q) {
448 findings.push(f(
449 "L8",
450 u.unit.clone(),
451 format!("OPEN({q}) names a question with no entry in the Decision Log"),
452 format!("add {q} to the Decision Log, or correct the marker"),
453 ));
454 }
455 }
456 }
457
458 for (subject, cause, remediation) in pin_findings(inst, &peers, &at)? {
462 findings.push(f("L9", subject, cause, remediation));
463 }
464
465 let entries = changelog::entries(&handle)?;
468 let last = entries.iter().max_by_key(|e| e.number);
469 for (subject, cause) in changelog::findings(
470 &entries,
471 inst.meta.get_str_or("version", ""),
472 inst.meta.get_str_or("updated", ""),
473 ) {
474 let remediation = match (subject.as_str(), last) {
475 ("version" | "updated", Some(last)) => format!(
476 "set version and updated in the front matter to {}'s ({} and {})",
477 last.id,
478 last.to.as_deref().unwrap_or("its target version"),
479 last.date.as_deref().unwrap_or("its date")
480 ),
481 _ => format!(
482 "give {subject} the next unused id: change entries are appended in id order, newest last"
483 ),
484 };
485 findings.push(f("L10", subject, cause, remediation));
486 }
487 for (id, hashes) in changelog::misplaced(&handle)? {
489 let (cause, remediation) = changelog::misplaced_finding(&id, hashes);
490 findings.push(f("L10", id, cause, remediation));
491 }
492
493 for (subject, cause) in
496 tdd::findings(&inst.meta, &inst.file, root, |p| model::read_text(p).ok())
497 {
498 let remediation = match subject.as_str() {
499 "tdd_version" => {
500 "re-pin tdd_version to the TDD's Revision in a change entry (vitrify brief change)"
501 }
502 _ if cause.contains("names no file") => {
503 "set tdd: to the TDD's path, from the SDD's directory or the repository root"
504 }
505 _ => "approve the TDD (Status: Approved), or keep the SDD Draft until it is",
506 };
507 findings.push(f("L11", subject, cause, remediation));
508 }
509
510 if graph::classify(inst)?
514 .iter()
515 .any(|ue| ue.entries.iter().any(|(_, e)| matches!(e, Entry::Pin(_))))
516 {
517 let unit_graph = super::repo_graph(root, Some(inst))?;
518 findings.extend(graph_findings(inst, &unit_graph));
519 }
520
521 Ok(findings)
522}
523
524pub fn graph_findings(inst: &Instance, unit_graph: &UnitGraph) -> Vec<Finding> {
531 let slug = graph::slug_of(inst);
532 let mut findings: Vec<Finding> = unit_graph
533 .problems()
534 .iter()
535 .filter(|p| p.slug == slug && p.check() == "L12")
536 .map(|p| f("L12", p.unit.clone(), p.cause(), p.remediation()))
537 .collect();
538 let Err(cycles) = unit_graph.resolve() else {
539 return findings;
540 };
541 let crosses = |path: &[Node]| path.iter().any(|n| n.slug != path[0].slug);
542 let through_pins: Vec<&Vec<Node>> = cycles
543 .cycles
544 .iter()
545 .filter(|path| crosses(path) || path.windows(2).any(|w| pin_only(unit_graph, &w[0], &w[1])))
546 .collect();
547 for path in &through_pins {
548 if path.iter().any(|n| n.slug == slug) {
549 let cause = if crosses(path) {
550 "depends_on graph across SDDs contains a cycle through pins"
551 } else {
552 "depends_on graph contains a cycle through a pin of this SDD's own contract"
553 };
554 findings.push(f(
555 "L12",
556 render_path(path),
557 cause,
558 "remove one of the cycle's depends_on edges — a pin a unit only reads stays in consumes alone",
559 ));
560 }
561 }
562 for n in cycles.waiting.iter().filter(|n| n.slug == slug) {
563 if let Some(path) = through_pins
564 .iter()
565 .find(|path| waits_on(unit_graph, n, path))
566 {
567 findings.push(f(
568 "L12",
569 n.unit.clone(),
570 format!("waits behind the cycle {}", render_path(path)),
571 "break the cycle its own L12 finding names",
572 ));
573 }
574 }
575 findings
576}
577
578fn pin_only(unit_graph: &UnitGraph, from: &Node, to: &Node) -> bool {
581 let edges: Vec<_> = unit_graph
582 .edges()
583 .iter()
584 .filter(|e| &e.from == from && &e.to == to)
585 .collect();
586 !edges.is_empty() && edges.iter().all(|e| e.via.is_some())
587}
588
589fn waits_on(unit_graph: &UnitGraph, n: &Node, path: &[Node]) -> bool {
591 let mut seen: Vec<&Node> = Vec::new();
592 let mut stack: Vec<&Node> = vec![n];
593 while let Some(x) = stack.pop() {
594 for d in unit_graph.dependencies(x) {
595 if path.contains(d) {
596 return true;
597 }
598 if !seen.contains(&d) {
599 seen.push(d);
600 stack.push(d);
601 }
602 }
603 }
604 false
605}
606
607pub fn pin_findings(
611 inst: &Instance,
612 peers: &contract::Peers,
613 at: &str,
614) -> Result<Vec<(String, String, String)>, CoreError> {
615 Ok(contract::examine(inst, peers)?
616 .into_iter()
617 .filter(|ext| ext.state.is_finding())
618 .map(|ext| {
619 let remediation = match ext.state {
620 State::Stale => format!("vitrify pin sync --sdd {at}"),
621 State::MissingAuthority => format!(
622 "make {}'s Pin: line name an SDD and contract this repository has (vitrify pin list --all)",
623 ext.id
624 ),
625 _ => format!(
626 "correct {}'s header as its cause says (vitrify schema show, Interface Contracts)",
627 ext.id
628 ),
629 };
630 (ext.id, ext.detail, remediation)
631 })
632 .collect())
633}
634
635pub fn pre_run_findings(
638 inst: &Instance,
639 root: &Path,
640 budget: i64,
641) -> Result<Vec<Finding>, CoreError> {
642 Ok(check_all(inst, root, budget)?
643 .into_iter()
644 .filter(|x| x.check != "L7")
645 .collect())
646}
647
648fn find_cycle(units: &[model::Unit]) -> Option<Vec<String>> {
649 fn visit(
651 uid: &str,
652 units: &[model::Unit],
653 path: &mut Vec<String>,
654 done: &mut Vec<String>,
655 ) -> Option<Vec<String>> {
656 if done.iter().any(|d| d == uid) {
657 return None;
658 }
659 if let Some(pos) = path.iter().position(|p| p == uid) {
660 let mut cycle = path[pos..].to_vec();
661 cycle.push(uid.to_string());
662 return Some(cycle);
663 }
664 path.push(uid.to_string());
665 if let Some(u) = units.iter().find(|u| u.unit == uid) {
666 for d in u.meta.get_list("depends_on") {
667 if let Some(c) = visit(&d, units, path, done) {
668 return Some(c);
669 }
670 }
671 }
672 path.pop();
673 done.push(uid.to_string());
674 None
675 }
676 let mut done = Vec::new();
677 for u in units {
678 if let Some(c) = visit(&u.unit, units, &mut Vec::new(), &mut done) {
679 return Some(c);
680 }
681 }
682 None
683}
684
685fn globs_overlap(a: &str, b: &str) -> bool {
687 let lit = |g: &str| -> (String, bool) {
688 match g.find(['*', '?', '[']) {
689 Some(i) => (g[..i].to_string(), true),
690 None => (g.trim_end_matches('/').to_string(), false),
691 }
692 };
693 let (pa, wild_a) = lit(a);
694 let (pb, wild_b) = lit(b);
695 if !wild_a && !wild_b {
696 return pa == pb || pa.starts_with(&format!("{pb}/")) || pb.starts_with(&format!("{pa}/"));
697 }
698 pa.starts_with(&pb) || pb.starts_with(&pa)
699}
700
701fn unmanaged_globs(core_text: &str) -> Vec<String> {
702 let sec = model::section(core_text, "System Layout & Ownership");
703 let mut out = Vec::new();
704 let mut in_block = false;
705 for line in sec.lines() {
706 if !in_block {
707 if line.trim() == "unmanaged:" {
708 in_block = true;
709 }
710 continue;
711 }
712 let trimmed = line.trim_start();
713 if let Some(item) = trimmed.strip_prefix("- ")
714 && line.starts_with(|c: char| c.is_whitespace())
715 {
716 out.push(item.trim().to_string());
717 } else {
718 break;
719 }
720 }
721 out
722}
723
724fn unit_text(inst: &Instance, u: &model::Unit) -> Result<String, CoreError> {
725 match inst.shape {
726 Shape::Bundle => model::read_text(&u.file),
727 Shape::Single => {
728 let text = model::read_text(&inst.file)?;
729 Ok(model::find_unit_span(&text, &u.unit)
730 .map(|(s, e)| text[s..e].to_string())
731 .unwrap_or_default())
732 }
733 }
734}
735
736fn declared_requirements(text: &str, unit_id: &str) -> Vec<u32> {
738 let needle = format!("{unit_id}.R");
739 let mut out: Vec<u32> = Vec::new();
740 let mut search = text;
741 while let Some(i) = search.find(&needle) {
742 let rest = &search[i + needle.len()..];
743 let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
744 if let Ok(n) = digits.parse::<u32>()
745 && !out.contains(&n)
746 {
747 out.push(n);
748 }
749 search = &search[i + needle.len()..];
750 }
751 out
752}
753
754fn covers_tokens(text: &str) -> Vec<String> {
756 let mut tokens = Vec::new();
757 let mut in_section = false;
758 for line in text.lines() {
759 let is_heading = line.starts_with("##");
760 if is_heading {
761 in_section = line
762 .trim_start_matches('#')
763 .trim()
764 .eq_ignore_ascii_case("Verification");
765 continue;
766 }
767 if !in_section || !line.trim_start().starts_with('|') {
768 continue;
769 }
770 let stripped = line.trim().trim_matches('|');
771 let cells: Vec<&str> = stripped.split('|').map(str::trim).collect();
772 if cells.is_empty() {
773 continue;
774 }
775 let first = cells[0];
776 if first.chars().all(|c| c == '-' || c == ' ' || c == ':')
777 || first.eq_ignore_ascii_case("covers")
778 {
779 continue;
780 }
781 for tok in first.split([',', '·']) {
782 let t = tok.trim().trim_matches('*').trim();
783 if t.is_empty() {
784 continue;
785 }
786 if let Some((lo, hi)) = parse_range(t) {
788 for n in lo..=hi {
789 tokens.push(format!("R{n}"));
790 }
791 } else {
792 tokens.push(t.to_string());
793 }
794 }
795 }
796 tokens
797}
798
799fn parse_range(token: &str) -> Option<(u32, u32)> {
801 for sep in ['\u{2013}', '-'] {
802 if let Some((a, b)) = token.split_once(sep) {
803 let lo = a.trim().strip_prefix('R')?.parse().ok()?;
804 let hi = b.trim().strip_prefix('R')?.parse().ok()?;
805 return Some((lo, hi));
806 }
807 }
808 None
809}