1use std::path::Path;
10
11use vitrify_core::CoreError;
12use vitrify_core::audit;
13use vitrify_core::config::Overrides;
14use vitrify_core::contract::State;
15use vitrify_core::model::{self, Instance, SddHandle, Shape, is_empty_marker};
16use vitrify_core::{changelog, contract, journal, questions, readset, tdd};
17
18use crate::out::{J, emit};
19
20pub const CHECKS: &str = "L1–L11";
22
23pub struct Finding {
24 pub check: &'static str,
25 pub subject: String,
26 pub cause: String,
27 pub remediation: String,
29}
30
31fn f(
32 check: &'static str,
33 subject: impl Into<String>,
34 cause: impl Into<String>,
35 remediation: impl Into<String>,
36) -> Finding {
37 Finding {
38 check,
39 subject: subject.into(),
40 cause: cause.into(),
41 remediation: remediation.into(),
42 }
43}
44
45impl Finding {
46 pub fn line(&self) -> String {
48 format!(
49 "[{}] {}: {} → {}",
50 self.check, self.subject, self.cause, self.remediation
51 )
52 }
53}
54
55pub struct Flags {
56 pub sdd: Option<String>,
57 pub all: bool,
59 pub built: bool,
61 pub json: bool,
62}
63
64fn findings_json(findings: &[Finding]) -> Vec<(String, J)> {
65 let jf: Vec<J> = findings
66 .iter()
67 .map(|x| {
68 J::Obj(vec![
69 ("check".into(), J::s(x.check)),
70 ("subject".into(), J::s(x.subject.clone())),
71 ("cause".into(), J::s(x.cause.clone())),
72 ("remediation".into(), J::s(x.remediation.clone())),
73 ])
74 })
75 .collect();
76 vec![
77 ("clean".into(), J::Bool(findings.is_empty())),
78 ("findings".into(), J::Arr(jf)),
79 ]
80}
81
82pub fn run(flags: Flags) -> Result<u8, CoreError> {
83 let root = super::repo_root();
84 let sdds = super::targets(&root, flags.sdd.as_deref(), flags.all, &super::cwd())?;
85 let budget = super::load_config(&Overrides::default())?
86 .lint
87 .readset_budget_bytes;
88 let lint = |sdd: &SddHandle| -> Result<Vec<Finding>, CoreError> {
89 let inst = Instance::load(sdd.clone())?;
90 if flags.built {
91 pre_run_findings(&inst, &root, budget)
92 } else {
93 check_all(&inst, &root, budget)
94 }
95 };
96
97 if !flags.all {
98 let findings = lint(&sdds[0])?;
99 if flags.json {
100 emit(&J::Obj(findings_json(&findings)).dumps_indent2());
101 } else {
102 if findings.is_empty() {
103 emit(&format!("lint clean ({CHECKS})"));
104 }
105 for x in &findings {
106 emit(&x.line());
107 }
108 }
109 return Ok(if findings.is_empty() { 0 } else { 2 });
110 }
111
112 let mut reports: Vec<J> = Vec::new();
114 let code = super::each(&root, &sdds, |sdd| {
115 let findings = lint(sdd)?;
116 let name = super::label(sdd, &root);
117 if flags.json {
118 let mut pairs = vec![
119 ("sdd".into(), J::s(name)),
120 ("root".into(), J::s(super::shown(&root, &sdd.root))),
121 ];
122 pairs.extend(findings_json(&findings));
123 reports.push(J::Obj(pairs));
124 } else {
125 if findings.is_empty() {
126 emit(&format!("{name}: lint clean ({CHECKS})"));
127 }
128 for x in &findings {
129 emit(&format!("{name}: {}", x.line()));
130 }
131 }
132 Ok(if findings.is_empty() { 0 } else { 2 })
133 });
134 if flags.json {
135 emit(&J::Arr(reports).dumps_indent2());
136 }
137 Ok(code)
138}
139
140fn listed(ids: &[String]) -> String {
142 match ids {
143 [] => String::new(),
144 [one] => one.clone(),
145 [init @ .., last] => format!("{} and {last}", init.join(", ")),
146 }
147}
148
149pub fn check_all(inst: &Instance, root: &Path, budget: i64) -> Result<Vec<Finding>, CoreError> {
150 let mut findings: Vec<Finding> = Vec::new();
151 let units = &inst.units;
152 let unit_ids: Vec<&str> = units.iter().map(|u| u.unit.as_str()).collect();
153 let at = super::shown(root, &inst.root);
155 let handle = inst.handle();
156
157 for u in units {
159 for d in u.meta.get_list("depends_on") {
160 if !unit_ids.contains(&d.as_str()) {
161 findings.push(f(
162 "L1",
163 u.unit.clone(),
164 format!("depends_on references nonexistent unit {d}"),
165 format!("remove {d} from {}'s depends_on, or add unit {d}", u.unit),
166 ));
167 }
168 }
169 }
170 if let Some(cycle) = find_cycle(units) {
171 findings.push(f(
172 "L1",
173 cycle.join(" → "),
174 "depends_on graph contains a cycle",
175 "remove one of the cycle's depends_on edges",
176 ));
177 }
178
179 let owns: Vec<(String, Vec<String>)> = units
181 .iter()
182 .map(|u| (u.unit.clone(), u.meta.get_list("owns")))
183 .collect();
184 for (i, (ua, gsa)) in owns.iter().enumerate() {
185 for (ub, gsb) in owns.iter().skip(i + 1) {
186 for ga in gsa {
187 for gb in gsb {
188 if globs_overlap(ga, gb) {
189 findings.push(f(
190 "L2",
191 format!("{ua}/{ub}"),
192 format!("owns globs can match a common path: `{ga}` vs `{gb}`"),
193 format!("narrow {ua}'s or {ub}'s owns so no path matches both"),
194 ));
195 }
196 }
197 }
198 }
199 }
200 let core_text = model::read_text(&inst.file)?;
201 let unmanaged = unmanaged_globs(&core_text);
202 let scope_files = super::governed_files(root, inst)
205 .unwrap_or_else(|| audit::walk_scope(root, &inst.meta.get_list("scope_roots")));
206 for file in &scope_files {
207 let owned = owns
208 .iter()
209 .any(|(_, gs)| gs.iter().any(|g| audit::matches(file, g)))
210 || unmanaged.iter().any(|g| audit::matches(file, g));
211 if !owned {
212 findings.push(f(
213 "L2",
214 file.clone(),
215 "file under scope_roots is neither owned nor unmanaged",
216 "add a glob that matches it to one unit's owns, or list it under unmanaged: in System Layout & Ownership",
217 ));
218 }
219 }
220
221 for u in units {
223 let group = u.meta.get_str_or("parallel_group", "");
224 if is_empty_marker(group.trim()) {
225 continue;
226 }
227 for d in u.meta.get_list("depends_on") {
228 if let Some(dep) = units.iter().find(|x| x.unit == d)
229 && dep.meta.get_str_or("parallel_group", "") == group
230 {
231 findings.push(f(
232 "L3",
233 u.unit.clone(),
234 format!("depends on {d} inside its own parallel group {group}"),
235 format!(
236 "move {} or {d} to another parallel_group, or drop the dependency",
237 u.unit
238 ),
239 ));
240 }
241 }
242 }
243
244 for u in units {
246 for cid in u.meta.get_list("consumes") {
247 if model::contract_text(&handle, &cid)?.is_none() {
248 findings.push(f(
249 "L4",
250 u.unit.clone(),
251 format!("consumes unresolvable contract {cid}"),
252 format!(
253 "write contract {cid}, or remove it from {}'s consumes",
254 u.unit
255 ),
256 ));
257 }
258 }
259 }
260 for (cid, cref) in audit::contract_refs(inst)? {
261 let mut refs: Vec<&String> = Vec::new();
262 if let Some(p) = &cref.producer {
263 refs.push(p);
264 }
265 refs.extend(cref.consumers.iter());
266 for uid in refs {
267 if !unit_ids.contains(&uid.as_str()) {
268 findings.push(f(
269 "L4",
270 cid.clone(),
271 format!("references nonexistent unit {uid}"),
272 format!(
273 "make {cid}'s Producer and Consumers lines name only units the SDD has"
274 ),
275 ));
276 }
277 }
278 }
279 let contracts = contract::list(&handle)?;
283 for c in &contracts {
284 if let Some((header_only, consumes_only)) = contract::consumer_mismatch(c, units) {
285 let mut parts: Vec<String> = Vec::new();
286 if !header_only.is_empty() {
287 parts.push(format!(
288 "names {}, which {} not list it in `consumes`",
289 listed(&header_only),
290 if header_only.len() == 1 { "does" } else { "do" }
291 ));
292 }
293 if !consumes_only.is_empty() {
294 parts.push(format!(
295 "omits {}, which {} it",
296 listed(&consumes_only),
297 if consumes_only.len() == 1 {
298 "consumes"
299 } else {
300 "consume"
301 }
302 ));
303 }
304 findings.push(f(
305 "L4",
306 c.id.clone(),
307 format!("its Consumers line {}", parts.join(" and ")),
308 format!(
309 "make {}'s Consumers line name exactly the units that list it in consumes",
310 c.id
311 ),
312 ));
313 }
314 }
315
316 let peers = super::peers(root);
318 for u in units {
319 match readset::resolve(inst, &u.unit, &peers) {
320 Ok(items) => {
321 let total: i64 = items.iter().map(|i| i.bytes as i64).sum();
322 if total > budget {
323 findings.push(f(
324 "L5",
325 u.unit.clone(),
326 format!("reading set totals {total} bytes, over budget {budget}"),
327 format!(
328 "split {} or shrink what it reads (vitrify readset --unit {} --sdd {at} lists it)",
329 u.unit, u.unit
330 ),
331 ));
332 }
333 }
334 Err(e)
338 if e.to_string().lines().all(|l| {
339 l.contains("consumed contract missing") || l.contains(readset::PIN_PROBLEM)
340 }) => {}
341 Err(e) => findings.push(f(
342 "L5",
343 u.unit.clone(),
344 format!(
345 "reading set does not resolve: {}",
346 e.to_string().replace('\n', "; ")
347 ),
348 format!(
349 "make every path {}'s reading set names exist (vitrify readset --unit {} --sdd {at})",
350 u.unit, u.unit
351 ),
352 )),
353 }
354 }
355
356 for u in units {
358 let text = unit_text(inst, u)?;
359 let declared = declared_requirements(&text, &u.unit);
360 let covers = covers_tokens(&text);
361 let covers_all = covers.iter().any(|t| t.eq_ignore_ascii_case("all"));
362 for r in &declared {
363 let short = format!("R{r}");
364 let full = format!("{}.R{r}", u.unit);
365 if !covers_all && !covers.contains(&short) && !covers.contains(&full) {
366 findings.push(f(
367 "L6",
368 u.unit.clone(),
369 format!("requirement {full} not covered by any Verification row"),
370 format!(
371 "add a Verification row whose Covers column names {short}, or remove {full}"
372 ),
373 ));
374 }
375 }
376 }
377
378 let built = journal::read(&handle)?.1;
381 let l7 = |unit: &str, cause: &str, clear: &str| {
382 let remediation = if built {
383 format!("the SDD is being built: vitrify lint --built --sdd {at}")
384 } else {
385 format!("{clear} in {unit}'s entry: the build sets it")
386 };
387 f("L7", unit, cause, remediation)
388 };
389 for u in units {
390 let status = u.meta.get_str_or("status", "Draft");
391 if status != "Draft" && status != "Ready" {
392 findings.push(l7(
393 &u.unit,
394 &format!("status {status} is beyond Ready before the build"),
395 "set status to Draft or Ready",
396 ));
397 }
398 if !is_empty_marker(u.meta.get_str_or("claimed_by", "").trim()) {
399 findings.push(l7(
400 &u.unit,
401 "claimed_by set before the build",
402 "set claimed_by to —",
403 ));
404 }
405 if !is_empty_marker(u.meta.get_str_or("claim_expires", "").trim()) {
406 findings.push(l7(
407 &u.unit,
408 "claim_expires set before the build",
409 "set claim_expires to —",
410 ));
411 }
412 if u.meta.get_map("trace").is_some_and(|m| !m.is_empty()) {
413 findings.push(l7(
414 &u.unit,
415 "trace recorded before the build",
416 "remove the trace map",
417 ));
418 }
419 }
420
421 let asked: Vec<String> = questions::of(&handle)?.into_iter().map(|q| q.id).collect();
424 for u in units {
425 let text = unit_text(inst, u)?;
426 let markers = questions::markers(&text);
427 if u.meta.get_str_or("status", "Draft") == "Ready" && text.contains("OPEN(Q-") {
428 let named = if markers.is_empty() {
429 "the question".to_string()
430 } else {
431 listed(&markers)
432 };
433 findings.push(f(
434 "L8",
435 u.unit.clone(),
436 "OPEN(Q-###) marker inside a Ready unit's region",
437 format!(
438 "resolve {named} in the Decision Log and remove the marker, or set {} back to Draft",
439 u.unit
440 ),
441 ));
442 }
443 for q in markers {
444 if !asked.contains(&q) {
445 findings.push(f(
446 "L8",
447 u.unit.clone(),
448 format!("OPEN({q}) names a question with no entry in the Decision Log"),
449 format!("add {q} to the Decision Log, or correct the marker"),
450 ));
451 }
452 }
453 }
454
455 for (subject, cause, remediation) in pin_findings(inst, &peers, &at)? {
459 findings.push(f("L9", subject, cause, remediation));
460 }
461
462 let entries = changelog::entries(&handle)?;
465 let last = entries.iter().max_by_key(|e| e.number);
466 for (subject, cause) in changelog::findings(
467 &entries,
468 inst.meta.get_str_or("version", ""),
469 inst.meta.get_str_or("updated", ""),
470 ) {
471 let remediation = match (subject.as_str(), last) {
472 ("version" | "updated", Some(last)) => format!(
473 "set version and updated in the front matter to {}'s ({} and {})",
474 last.id,
475 last.to.as_deref().unwrap_or("its target version"),
476 last.date.as_deref().unwrap_or("its date")
477 ),
478 _ => format!(
479 "give {subject} the next unused id: change entries are appended in id order, newest last"
480 ),
481 };
482 findings.push(f("L10", subject, cause, remediation));
483 }
484 for (id, hashes) in changelog::misplaced(&handle)? {
486 let (cause, remediation) = changelog::misplaced_finding(&id, hashes);
487 findings.push(f("L10", id, cause, remediation));
488 }
489
490 for (subject, cause) in
493 tdd::findings(&inst.meta, &inst.file, root, |p| model::read_text(p).ok())
494 {
495 let remediation = match subject.as_str() {
496 "tdd_version" => {
497 "re-pin tdd_version to the TDD's Revision in a change entry (vitrify brief change)"
498 }
499 _ if cause.contains("names no file") => {
500 "set tdd: to the TDD's path, from the SDD's directory or the repository root"
501 }
502 _ => "approve the TDD (Status: Approved), or keep the SDD Draft until it is",
503 };
504 findings.push(f("L11", subject, cause, remediation));
505 }
506
507 Ok(findings)
508}
509
510pub fn pin_findings(
514 inst: &Instance,
515 peers: &contract::Peers,
516 at: &str,
517) -> Result<Vec<(String, String, String)>, CoreError> {
518 Ok(contract::examine(inst, peers)?
519 .into_iter()
520 .filter(|ext| ext.state.is_finding())
521 .map(|ext| {
522 let remediation = match ext.state {
523 State::Stale => format!("vitrify pin sync --sdd {at}"),
524 State::MissingAuthority => format!(
525 "make {}'s Pin: line name an SDD and contract this repository has (vitrify pin list --all)",
526 ext.id
527 ),
528 _ => format!(
529 "correct {}'s header as its cause says (vitrify schema show, Interface Contracts)",
530 ext.id
531 ),
532 };
533 (ext.id, ext.detail, remediation)
534 })
535 .collect())
536}
537
538pub fn pre_run_findings(
541 inst: &Instance,
542 root: &Path,
543 budget: i64,
544) -> Result<Vec<Finding>, CoreError> {
545 Ok(check_all(inst, root, budget)?
546 .into_iter()
547 .filter(|x| x.check != "L7")
548 .collect())
549}
550
551fn find_cycle(units: &[model::Unit]) -> Option<Vec<String>> {
552 fn visit(
554 uid: &str,
555 units: &[model::Unit],
556 path: &mut Vec<String>,
557 done: &mut Vec<String>,
558 ) -> Option<Vec<String>> {
559 if done.iter().any(|d| d == uid) {
560 return None;
561 }
562 if let Some(pos) = path.iter().position(|p| p == uid) {
563 let mut cycle = path[pos..].to_vec();
564 cycle.push(uid.to_string());
565 return Some(cycle);
566 }
567 path.push(uid.to_string());
568 if let Some(u) = units.iter().find(|u| u.unit == uid) {
569 for d in u.meta.get_list("depends_on") {
570 if let Some(c) = visit(&d, units, path, done) {
571 return Some(c);
572 }
573 }
574 }
575 path.pop();
576 done.push(uid.to_string());
577 None
578 }
579 let mut done = Vec::new();
580 for u in units {
581 if let Some(c) = visit(&u.unit, units, &mut Vec::new(), &mut done) {
582 return Some(c);
583 }
584 }
585 None
586}
587
588fn globs_overlap(a: &str, b: &str) -> bool {
590 let lit = |g: &str| -> (String, bool) {
591 match g.find(['*', '?', '[']) {
592 Some(i) => (g[..i].to_string(), true),
593 None => (g.trim_end_matches('/').to_string(), false),
594 }
595 };
596 let (pa, wild_a) = lit(a);
597 let (pb, wild_b) = lit(b);
598 if !wild_a && !wild_b {
599 return pa == pb || pa.starts_with(&format!("{pb}/")) || pb.starts_with(&format!("{pa}/"));
600 }
601 pa.starts_with(&pb) || pb.starts_with(&pa)
602}
603
604fn unmanaged_globs(core_text: &str) -> Vec<String> {
605 let sec = model::section(core_text, "System Layout & Ownership");
606 let mut out = Vec::new();
607 let mut in_block = false;
608 for line in sec.lines() {
609 if !in_block {
610 if line.trim() == "unmanaged:" {
611 in_block = true;
612 }
613 continue;
614 }
615 let trimmed = line.trim_start();
616 if let Some(item) = trimmed.strip_prefix("- ")
617 && line.starts_with(|c: char| c.is_whitespace())
618 {
619 out.push(item.trim().to_string());
620 } else {
621 break;
622 }
623 }
624 out
625}
626
627fn unit_text(inst: &Instance, u: &model::Unit) -> Result<String, CoreError> {
628 match inst.shape {
629 Shape::Bundle => model::read_text(&u.file),
630 Shape::Single => {
631 let text = model::read_text(&inst.file)?;
632 Ok(model::find_unit_span(&text, &u.unit)
633 .map(|(s, e)| text[s..e].to_string())
634 .unwrap_or_default())
635 }
636 }
637}
638
639fn declared_requirements(text: &str, unit_id: &str) -> Vec<u32> {
641 let needle = format!("{unit_id}.R");
642 let mut out: Vec<u32> = Vec::new();
643 let mut search = text;
644 while let Some(i) = search.find(&needle) {
645 let rest = &search[i + needle.len()..];
646 let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
647 if let Ok(n) = digits.parse::<u32>()
648 && !out.contains(&n)
649 {
650 out.push(n);
651 }
652 search = &search[i + needle.len()..];
653 }
654 out
655}
656
657fn covers_tokens(text: &str) -> Vec<String> {
659 let mut tokens = Vec::new();
660 let mut in_section = false;
661 for line in text.lines() {
662 let is_heading = line.starts_with("##");
663 if is_heading {
664 in_section = line
665 .trim_start_matches('#')
666 .trim()
667 .eq_ignore_ascii_case("Verification");
668 continue;
669 }
670 if !in_section || !line.trim_start().starts_with('|') {
671 continue;
672 }
673 let stripped = line.trim().trim_matches('|');
674 let cells: Vec<&str> = stripped.split('|').map(str::trim).collect();
675 if cells.is_empty() {
676 continue;
677 }
678 let first = cells[0];
679 if first.chars().all(|c| c == '-' || c == ' ' || c == ':')
680 || first.eq_ignore_ascii_case("covers")
681 {
682 continue;
683 }
684 for tok in first.split([',', '·']) {
685 let t = tok.trim().trim_matches('*').trim();
686 if t.is_empty() {
687 continue;
688 }
689 if let Some((lo, hi)) = parse_range(t) {
691 for n in lo..=hi {
692 tokens.push(format!("R{n}"));
693 }
694 } else {
695 tokens.push(t.to_string());
696 }
697 }
698 }
699 tokens
700}
701
702fn parse_range(token: &str) -> Option<(u32, u32)> {
704 for sep in ['\u{2013}', '-'] {
705 if let Some((a, b)) = token.split_once(sep) {
706 let lo = a.trim().strip_prefix('R')?.parse().ok()?;
707 let hi = b.trim().strip_prefix('R')?.parse().ok()?;
708 return Some((lo, hi));
709 }
710 }
711 None
712}