1use std::collections::{BTreeMap, BTreeSet};
34use std::path::Path;
35use std::time::Instant;
36
37use crate::ontology::sigma::{Sigma, SigmaError};
38
39use super::finding::LintFinding;
40use super::rules::RuleSeverity;
41use super::{GateDetail, GateExtra, GateResult, Verdict};
42
43#[derive(Debug)]
45pub enum RelationsOutcome {
46 NoSigma,
48 Malformed(SigmaError),
50 NoRelations {
52 contracts_checked: usize,
53 legacy_depends_on: usize,
54 },
55 Ran {
57 result: Box<GateResult>,
58 findings: Vec<LintFinding>,
59 },
60}
61
62use crate::ontology::witness::TypedEdge as Edge;
64
65#[must_use]
67pub fn run_relations_gate(contract_dir: &Path) -> RelationsOutcome {
68 let start = Instant::now();
69 let sigma_path = contract_dir.join("ontology.yaml");
70 let Ok(text) = std::fs::read_to_string(&sigma_path) else {
71 return RelationsOutcome::NoSigma;
72 };
73 let sigma = match Sigma::from_yaml(&text) {
74 Ok(s) => s,
75 Err(e) => return RelationsOutcome::Malformed(e),
76 };
77 if let Err(e) = sigma.check_integrity() {
78 return RelationsOutcome::Malformed(e);
79 }
80
81 let (docs, stems) = read_corpus(contract_dir, &sigma_path);
82
83 let mut findings = Vec::new();
85 let mut edges: BTreeSet<Edge> = BTreeSet::new();
86 let mut contracts_with_relations = 0usize;
87 let mut legacy_depends_on = 0usize;
88 let mut legacy_unresolved = 0usize;
89 for (stem, file, doc) in &docs {
90 let (n_legacy, n_unresolved) = legacy_depends_on_edges(doc, &stems);
91 legacy_depends_on += n_legacy;
92 legacy_unresolved += n_unresolved;
93 let Some(map) = doc.get("relations").and_then(serde_yaml::Value::as_mapping) else {
94 continue;
95 };
96 contracts_with_relations += 1;
97 findings.extend(check_block(&sigma, stem, file, map, &stems, &mut edges));
98 }
99
100 let relations_n = edges.len();
101 if relations_n == 0 && findings.is_empty() {
102 return RelationsOutcome::NoRelations {
103 contracts_checked: docs.len(),
104 legacy_depends_on,
105 };
106 }
107
108 let (cycle_findings, cycles) = cycle_sweep(&sigma, &edges);
109 findings.extend(cycle_findings);
110
111 if let Some(baseline) = baseline_legacy_unresolved(contract_dir) {
113 if legacy_unresolved > baseline {
114 findings.push(LintFinding::new(
115 "PV-ONT-010",
116 RuleSeverity::Error,
117 format!(
118 "legacy_unresolved_depends_on rose {baseline} -> {legacy_unresolved}: a `metadata.depends_on` naming no contract was added. The baseline in contracts/lint-baseline.json is shrink-only"
119 ),
120 "contracts/lint-baseline.json".to_string(),
121 ));
122 }
123 }
124 let mut roles_used: BTreeMap<String, usize> = BTreeMap::new();
125 for e in &edges {
126 *roles_used.entry(e.role.clone()).or_default() += 1;
127 }
128 let violations = findings.len();
129 let passed = violations == 0;
130 let duration = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
131 let result = GateResult {
132 name: "relations".into(),
133 passed,
134 skipped: false,
135 verdict: Verdict::from_gate(passed, false),
136 duration_ms: duration,
137 detail: GateDetail::Validate {
138 contracts: docs.len(),
139 errors: violations,
140 warnings: 0,
141 error_messages: findings.iter().map(|f| f.message.clone()).collect(),
142 },
143 extra: Some(GateExtra::Relations {
144 relations_n,
145 contracts_with_relations,
146 roles_used: roles_used.iter().map(|(r, n)| format!("{r}={n}")).collect(),
147 cycles,
148 legacy_depends_on,
149 legacy_unresolved_depends_on: legacy_unresolved,
150 violations,
151 }),
152 };
153 RelationsOutcome::Ran {
154 result: Box::new(result),
155 findings,
156 }
157}
158
159#[derive(Debug)]
162pub enum TypedGraph {
163 NoSigma,
165 Malformed(SigmaError),
167 Read {
169 ids: BTreeSet<String>,
170 edges: BTreeSet<Edge>,
171 },
172}
173
174#[must_use]
177pub fn typed_graph(contract_dir: &Path) -> TypedGraph {
178 let sigma_path = contract_dir.join("ontology.yaml");
179 let Ok(text) = std::fs::read_to_string(&sigma_path) else {
180 return TypedGraph::NoSigma;
181 };
182 let sigma = match Sigma::from_yaml(&text) {
183 Ok(s) => s,
184 Err(e) => return TypedGraph::Malformed(e),
185 };
186 if let Err(e) = sigma.check_integrity() {
187 return TypedGraph::Malformed(e);
188 }
189 let (docs, stems) = read_corpus(contract_dir, &sigma_path);
190 let mut edges = BTreeSet::new();
191 for (stem, file, doc) in &docs {
192 if let Some(map) = doc.get("relations").and_then(serde_yaml::Value::as_mapping) {
193 let _ = check_block(&sigma, stem, file, map, &stems, &mut edges);
194 }
195 }
196 TypedGraph::Read { ids: stems, edges }
197}
198
199type Doc = (String, std::path::PathBuf, serde_yaml::Value);
200
201#[must_use]
205pub fn corpus_documents(
206 contract_dir: &Path,
207) -> BTreeMap<String, (std::path::PathBuf, serde_yaml::Value)> {
208 let (docs, _) = read_corpus(contract_dir, &contract_dir.join("ontology.yaml"));
209 docs.into_iter()
210 .map(|(stem, file, doc)| (stem, (file, doc)))
211 .collect()
212}
213
214fn read_corpus(contract_dir: &Path, sigma_path: &Path) -> (Vec<Doc>, BTreeSet<String>) {
216 let mut files = Vec::new();
217 super::collect_yaml_files(contract_dir, &mut files);
218 let mut docs: Vec<Doc> = Vec::new();
219 let mut stems: BTreeSet<String> = BTreeSet::new();
220 for file in &files {
221 if file == sigma_path {
222 continue;
223 }
224 let Ok(raw) = std::fs::read_to_string(file) else {
225 continue;
226 };
227 let Ok(doc) = serde_yaml::from_str::<serde_yaml::Value>(&raw) else {
228 continue; };
230 let stem = file
231 .file_stem()
232 .and_then(|s| s.to_str())
233 .unwrap_or_default()
234 .to_string();
235 stems.insert(stem.clone());
236 docs.push((stem, file.clone(), doc));
237 }
238 (docs, stems)
239}
240
241fn check_block(
243 sigma: &Sigma,
244 stem: &str,
245 file: &Path,
246 map: &serde_yaml::Mapping,
247 stems: &BTreeSet<String>,
248 edges: &mut BTreeSet<Edge>,
249) -> Vec<LintFinding> {
250 let mut out = Vec::new();
251 for (key, value) in map {
252 let Some(role) = key.as_str() else { continue };
253 let Some(decl) = sigma.roles.get(role) else {
254 out.push(finding(
255 "PV-ONT-005",
256 format!("relation `{role}` is not a role Σ declares (contracts/ontology.yaml)"),
257 file,
258 stem,
259 ));
260 continue;
261 };
262 if decl.domain != "Contract" || decl.range != "Contract" {
263 out.push(finding(
264 "PV-ONT-006",
265 format!(
266 "relation `{role}` relates {} to {} in Σ, not Contract to Contract — it does not belong in a `relations:` block",
267 decl.domain, decl.range
268 ),
269 file,
270 stem,
271 ));
272 continue;
273 }
274 let Some(targets) = value.as_sequence() else {
275 out.push(finding(
276 "PV-ONT-007",
277 format!("relation `{role}` must be a list of contract ids"),
278 file,
279 stem,
280 ));
281 continue;
282 };
283 out.extend(check_targets(
284 stem,
285 file,
286 role,
287 decl.symmetric,
288 targets,
289 stems,
290 edges,
291 ));
292 }
293 out
294}
295
296fn cycle_sweep(sigma: &Sigma, edges: &BTreeSet<Edge>) -> (Vec<LintFinding>, Vec<String>) {
298 let mut findings = Vec::new();
299 let mut cycles = Vec::new();
300 for (role, decl) in &sigma.roles {
301 if !decl.acyclic {
302 continue;
303 }
304 let adj: BTreeMap<&str, Vec<&str>> =
305 edges
306 .iter()
307 .filter(|e| e.role == *role)
308 .fold(BTreeMap::new(), |mut m, e| {
309 m.entry(e.from.as_str()).or_default().push(e.to.as_str());
310 m
311 });
312 if let Some(path) = first_cycle(&adj) {
313 let shown = path.join(" -> ");
314 findings.push(LintFinding::new(
315 "PV-ONT-009",
316 RuleSeverity::Error,
317 format!("`{role}` is acyclic in Σ, and the corpus closes a cycle: {shown}"),
318 format!("contracts/{}.yaml", path[0]),
319 ));
320 cycles.push(format!("{role}: {shown}"));
321 }
322 }
323 let union_roles = ["depends_on", "supersedes"];
327 let per_role_hit = cycles
328 .iter()
329 .any(|c| union_roles.iter().any(|r| c.starts_with(&format!("{r}:"))));
330 if !per_role_hit {
331 let adj: BTreeMap<&str, Vec<&str>> = edges
332 .iter()
333 .filter(|e| union_roles.contains(&e.role.as_str()))
334 .fold(BTreeMap::new(), |mut m, e| {
335 m.entry(e.from.as_str()).or_default().push(e.to.as_str());
336 m
337 });
338 if let Some(path) = first_cycle(&adj) {
339 let shown = path.join(" -> ");
340 findings.push(LintFinding::new(
341 "PV-ONT-009",
342 RuleSeverity::Error,
343 format!("`depends_on ∪ supersedes` is acyclic (ont-self-v1 INV-2), and the corpus closes a cycle through the two roles together: {shown}"),
344 format!("contracts/{}.yaml", path[0]),
345 ));
346 cycles.push(format!("depends_on ∪ supersedes: {shown}"));
347 }
348 }
349 (findings, cycles)
350}
351
352fn check_targets(
354 stem: &str,
355 file: &Path,
356 role: &str,
357 symmetric: bool,
358 targets: &[serde_yaml::Value],
359 stems: &BTreeSet<String>,
360 edges: &mut BTreeSet<Edge>,
361) -> Vec<LintFinding> {
362 let mut out = Vec::new();
363 for t in targets {
364 let Some(to) = t.as_str() else {
365 out.push(finding(
366 "PV-ONT-007",
367 format!("relation `{role}` carries a non-string target"),
368 file,
369 stem,
370 ));
371 continue;
372 };
373 let to = normalize_id(to);
374 if !stems.contains(&to) {
375 out.push(finding(
376 "PV-ONT-008",
377 format!("`{stem}` {role} `{to}`, and no contracts/{to}.yaml exists — a dangling relation"),
378 file,
379 stem,
380 ));
381 continue;
382 }
383 edges.insert(Edge {
384 from: stem.to_string(),
385 role: role.to_string(),
386 to: to.clone(),
387 });
388 if symmetric {
389 edges.insert(Edge {
390 from: to,
391 role: role.to_string(),
392 to: stem.to_string(),
393 });
394 }
395 }
396 out
397}
398
399fn finding(rule: &str, message: String, file: &Path, stem: &str) -> LintFinding {
400 let mut f = LintFinding::new(
401 rule,
402 RuleSeverity::Error,
403 message,
404 file.display().to_string(),
405 );
406 f.contract_stem = Some(stem.to_string());
407 f
408}
409
410fn normalize_id(raw: &str) -> String {
412 let s = raw.trim();
413 let s = s.strip_prefix("contracts/").unwrap_or(s);
414 let s = s.strip_suffix(".yaml").unwrap_or(s);
415 s.to_string()
416}
417
418fn legacy_depends_on_edges(doc: &serde_yaml::Value, stems: &BTreeSet<String>) -> (usize, usize) {
420 let Some(list) = doc
421 .get("metadata")
422 .and_then(|m| m.get("depends_on"))
423 .and_then(serde_yaml::Value::as_sequence)
424 else {
425 return (0, 0);
426 };
427 let mut n = 0usize;
428 let mut unresolved = 0usize;
429 for item in list {
430 let Some(s) = item.as_str() else { continue };
431 n += 1;
432 if !stems.contains(&normalize_id(s)) {
433 unresolved += 1;
434 }
435 }
436 (n, unresolved)
437}
438
439fn baseline_legacy_unresolved(contract_dir: &Path) -> Option<usize> {
441 let raw = std::fs::read_to_string(contract_dir.join("lint-baseline.json")).ok()?;
442 let doc: serde_json::Value = serde_json::from_str(&raw).ok()?;
443 doc.get("ont")?
444 .get("legacy_unresolved_depends_on")?
445 .as_u64()
446 .and_then(|n| usize::try_from(n).ok())
447}
448
449#[derive(Clone, Copy, PartialEq)]
451enum Mark {
452 White,
453 Grey,
454 Black,
455}
456
457fn first_cycle<'a>(adj: &BTreeMap<&'a str, Vec<&'a str>>) -> Option<Vec<String>> {
460 let mut mark: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
461 for k in adj.values().flatten() {
462 mark.entry(k).or_insert(Mark::White);
463 }
464 let mut stack: Vec<&str> = Vec::new();
465 let nodes: Vec<&str> = mark.keys().copied().collect();
466 for n in nodes {
467 if mark.get(n).copied() != Some(Mark::White) {
468 continue;
469 }
470 if let Some(c) = visit(n, adj, &mut mark, &mut stack) {
471 return Some(c);
472 }
473 }
474 None
475}
476
477fn visit<'a>(
479 node: &'a str,
480 adj: &BTreeMap<&'a str, Vec<&'a str>>,
481 mark: &mut BTreeMap<&'a str, Mark>,
482 stack: &mut Vec<&'a str>,
483) -> Option<Vec<String>> {
484 mark.insert(node, Mark::Grey);
485 stack.push(node);
486 for &n in adj.get(node).map(Vec::as_slice).unwrap_or_default() {
487 match mark.get(n).copied().unwrap_or(Mark::White) {
488 Mark::Grey => {
489 let at = stack.iter().position(|s| *s == n).unwrap_or(0);
490 let mut path: Vec<String> = stack[at..].iter().map(|s| (*s).to_string()).collect();
491 path.push(n.to_string());
492 return Some(path);
493 }
494 Mark::White => {
495 if let Some(c) = visit(n, adj, mark, stack) {
496 return Some(c);
497 }
498 }
499 Mark::Black => {}
500 }
501 }
502 stack.pop();
503 mark.insert(node, Mark::Black);
504 None
505}
506
507#[cfg(test)]
508mod tests {
509 use super::*;
510
511 fn fixture(name: &str) -> std::path::PathBuf {
512 std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
513 .join("../../tests/fixtures/ont")
514 .join(name)
515 }
516
517 fn ran(name: &str) -> (Box<GateResult>, Vec<LintFinding>) {
518 match run_relations_gate(&fixture(name)) {
519 RelationsOutcome::Ran { result, findings } => (result, findings),
520 other => panic!("expected Ran for {name}, got {other:?}"),
521 }
522 }
523
524 fn rules(findings: &[LintFinding]) -> Vec<&str> {
525 findings.iter().map(|f| f.rule_id.as_str()).collect()
526 }
527
528 #[test]
529 fn four_relations_are_accepted_and_contradicts_is_symmetric() {
530 let (result, findings) = ran("relations-ok");
531 assert!(result.passed, "{findings:?}");
532 assert_eq!(result.verdict, Verdict::Pass);
533 match result.extra {
534 Some(GateExtra::Relations {
535 relations_n,
536 contracts_with_relations,
537 ref roles_used,
538 ..
539 }) => {
540 assert_eq!(relations_n, 5, "{roles_used:?}");
542 assert_eq!(contracts_with_relations, 2);
543 assert!(
544 roles_used.contains(&"contradicts=2".to_string()),
545 "{roles_used:?}"
546 );
547 }
548 other => panic!("expected Relations extra, got {other:?}"),
549 }
550 }
551
552 #[test]
553 fn a_dangling_id_is_rejected_naming_contract_role_and_target() {
554 let (result, findings) = ran("relations-dangling");
555 assert!(!result.passed);
556 assert_eq!(rules(&findings), vec!["PV-ONT-008"]);
557 assert!(
558 findings[0].message.contains("`a` depends_on `ghost`"),
559 "{}",
560 findings[0].message
561 );
562 }
563
564 #[test]
565 fn a_cycle_through_an_acyclic_role_is_rejected_naming_the_path() {
566 let (result, findings) = ran("relations-cycle");
567 assert!(!result.passed);
568 assert_eq!(rules(&findings), vec!["PV-ONT-009"]);
569 assert!(
570 findings[0].message.contains("a -> b -> c -> a"),
571 "{}",
572 findings[0].message
573 );
574 }
575
576 #[test]
580 fn a_cycle_through_depends_on_and_supersedes_together_is_rejected() {
581 let (result, findings) = ran("relations-mixed-cycle");
582 assert!(!result.passed, "{findings:?}");
583 assert_eq!(rules(&findings), vec!["PV-ONT-009"]);
584 assert!(
585 findings[0].message.contains("depends_on ∪ supersedes")
586 && findings[0].message.contains("a -> b -> a"),
587 "{}",
588 findings[0].message
589 );
590 }
591
592 #[test]
593 fn a_role_outside_contract_to_contract_is_rejected() {
594 let (result, findings) = ran("relations-domain");
595 assert!(!result.passed);
596 assert_eq!(rules(&findings), vec!["PV-ONT-006"]);
597 assert!(
598 findings[0].message.contains("`binds`"),
599 "{}",
600 findings[0].message
601 );
602 }
603
604 #[test]
605 fn an_undeclared_role_and_a_non_list_are_rejected() {
606 let (result, findings) = ran("relations-malformed");
607 assert!(!result.passed);
608 let mut got = rules(&findings);
609 got.sort_unstable();
610 assert_eq!(got, vec!["PV-ONT-005", "PV-ONT-007"]);
611 }
612
613 #[test]
614 fn zero_typed_relations_is_a_decline_not_a_pass() {
615 match run_relations_gate(&fixture("sigma-ok")) {
616 RelationsOutcome::NoRelations {
617 contracts_checked, ..
618 } => assert!(contracts_checked > 0),
619 other => panic!("expected NoRelations (R-2), got {other:?}"),
620 }
621 }
622
623 #[test]
624 fn legacy_depends_on_is_counted_never_rejected_and_ratcheted() {
625 let (result, findings) = ran("relations-legacy");
627 assert!(result.passed, "{findings:?}");
628 match result.extra {
629 Some(GateExtra::Relations {
630 legacy_depends_on,
631 legacy_unresolved_depends_on,
632 ..
633 }) => {
634 assert_eq!(legacy_depends_on, 2);
635 assert_eq!(legacy_unresolved_depends_on, 1);
636 }
637 other => panic!("expected Relations extra, got {other:?}"),
638 }
639 let (result, findings) = ran("relations-legacy-rise");
641 assert!(!result.passed);
642 assert_eq!(rules(&findings), vec!["PV-ONT-010"]);
643 }
644
645 #[test]
646 fn no_sigma_is_not_a_corpus_verdict() {
647 assert!(matches!(
648 run_relations_gate(&fixture("sigma-absent")),
649 RelationsOutcome::NoSigma
650 ));
651 }
652
653 #[test]
654 fn first_cycle_is_deterministic_and_names_the_closing_path() {
655 let mut adj: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
656 adj.insert("x", vec!["y"]);
657 adj.insert("y", vec!["z"]);
658 adj.insert("z", vec!["y"]);
659 assert_eq!(
660 first_cycle(&adj),
661 Some(vec!["y".into(), "z".into(), "y".into()])
662 );
663 let mut dag: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
664 dag.insert("x", vec!["y", "z"]);
665 dag.insert("y", vec!["z"]);
666 assert_eq!(first_cycle(&dag), None);
667 }
668}