Skip to main content

fallow_cli/
explain.rs

1//! Metric and rule definitions for explainable CLI output.
2//!
3//! Provides structured metadata that describes what each metric, threshold,
4//! and rule means — consumed by the `_meta` object in JSON output and by
5//! SARIF `fullDescription` / `helpUri` fields.
6
7use serde_json::{Value, json};
8
9// ── Docs base URL ────────────────────────────────────────────────
10
11const DOCS_BASE: &str = "https://docs.fallow.tools";
12
13/// Docs URL for the dead-code (check) command.
14pub const CHECK_DOCS: &str = "https://docs.fallow.tools/cli/dead-code";
15
16/// Docs URL for the health command.
17pub const HEALTH_DOCS: &str = "https://docs.fallow.tools/cli/health";
18
19/// Docs URL for the dupes command.
20pub const DUPES_DOCS: &str = "https://docs.fallow.tools/cli/dupes";
21
22// ── Check rules ─────────────────────────────────────────────────
23
24/// Rule definition for SARIF `fullDescription` and JSON `_meta`.
25pub struct RuleDef {
26    pub id: &'static str,
27    pub name: &'static str,
28    pub short: &'static str,
29    pub full: &'static str,
30    pub docs_path: &'static str,
31}
32
33pub const CHECK_RULES: &[RuleDef] = &[
34    RuleDef {
35        id: "fallow/unused-file",
36        name: "Unused Files",
37        short: "File is not reachable from any entry point",
38        full: "Source files that are not imported by any other module and are not entry points (scripts, tests, configs). These files can safely be deleted. Detection uses graph reachability from configured entry points.",
39        docs_path: "explanations/dead-code#unused-files",
40    },
41    RuleDef {
42        id: "fallow/unused-export",
43        name: "Unused Exports",
44        short: "Export is never imported",
45        full: "Named exports that are never imported by any other module in the project. Includes both direct exports and re-exports through barrel files. The export may still be used locally within the same file.",
46        docs_path: "explanations/dead-code#unused-exports",
47    },
48    RuleDef {
49        id: "fallow/unused-type",
50        name: "Unused Type Exports",
51        short: "Type export is never imported",
52        full: "Type-only exports (interfaces, type aliases, enums used only as types) that are never imported. These do not generate runtime code but add maintenance burden.",
53        docs_path: "explanations/dead-code#unused-types",
54    },
55    RuleDef {
56        id: "fallow/unused-dependency",
57        name: "Unused Dependencies",
58        short: "Dependency listed but never imported",
59        full: "Packages listed in dependencies that are never imported or required by any source file. Framework plugins and CLI tools may be false positives — use the ignore_dependencies config to suppress.",
60        docs_path: "explanations/dead-code#unused-dependencies",
61    },
62    RuleDef {
63        id: "fallow/unused-dev-dependency",
64        name: "Unused Dev Dependencies",
65        short: "Dev dependency listed but never imported",
66        full: "Packages listed in devDependencies that are never imported by test files, config files, or scripts. Build tools and jest presets that are referenced only in config may appear as false positives.",
67        docs_path: "explanations/dead-code#unused-devdependencies",
68    },
69    RuleDef {
70        id: "fallow/unused-optional-dependency",
71        name: "Unused Optional Dependencies",
72        short: "Optional dependency listed but never imported",
73        full: "Packages listed in optionalDependencies that are never imported. Optional dependencies are typically platform-specific — verify they are not needed on any supported platform before removing.",
74        docs_path: "explanations/dead-code#unused-optionaldependencies",
75    },
76    RuleDef {
77        id: "fallow/type-only-dependency",
78        name: "Type-only Dependencies",
79        short: "Production dependency only used via type-only imports",
80        full: "Production dependencies that are only imported via `import type` statements. These can be moved to devDependencies since they generate no runtime code and are stripped during compilation.",
81        docs_path: "explanations/dead-code#type-only-dependencies",
82    },
83    RuleDef {
84        id: "fallow/unused-enum-member",
85        name: "Unused Enum Members",
86        short: "Enum member is never referenced",
87        full: "Enum members that are never referenced in the codebase. Uses scope-aware binding analysis to track all references including computed access patterns.",
88        docs_path: "explanations/dead-code#unused-enum-members",
89    },
90    RuleDef {
91        id: "fallow/unused-class-member",
92        name: "Unused Class Members",
93        short: "Class member is never referenced",
94        full: "Class methods and properties that are never referenced outside the class. Private members are checked within the class scope; public members are checked project-wide.",
95        docs_path: "explanations/dead-code#unused-class-members",
96    },
97    RuleDef {
98        id: "fallow/unresolved-import",
99        name: "Unresolved Imports",
100        short: "Import could not be resolved",
101        full: "Import specifiers that could not be resolved to a file on disk. Common causes: deleted files, typos in paths, missing path aliases in tsconfig, or uninstalled packages.",
102        docs_path: "explanations/dead-code#unresolved-imports",
103    },
104    RuleDef {
105        id: "fallow/unlisted-dependency",
106        name: "Unlisted Dependencies",
107        short: "Dependency used but not in package.json",
108        full: "Packages that are imported in source code but not listed in package.json. These work by accident (hoisted from another workspace package or transitive dep) and will break in strict package managers.",
109        docs_path: "explanations/dead-code#unlisted-dependencies",
110    },
111    RuleDef {
112        id: "fallow/duplicate-export",
113        name: "Duplicate Exports",
114        short: "Export name appears in multiple modules",
115        full: "The same export name is defined in multiple modules. Consumers may import from the wrong module, leading to subtle bugs. Consider renaming or consolidating.",
116        docs_path: "explanations/dead-code#duplicate-exports",
117    },
118    RuleDef {
119        id: "fallow/circular-dependency",
120        name: "Circular Dependencies",
121        short: "Circular dependency chain detected",
122        full: "A cycle in the module import graph. Circular dependencies cause undefined behavior with CommonJS (partial modules) and initialization ordering issues with ESM. Break cycles by extracting shared code.",
123        docs_path: "explanations/dead-code#circular-dependencies",
124    },
125];
126
127/// Look up a rule definition by its SARIF rule ID across all rule sets.
128#[must_use]
129pub fn rule_by_id(id: &str) -> Option<&'static RuleDef> {
130    CHECK_RULES
131        .iter()
132        .chain(HEALTH_RULES.iter())
133        .chain(DUPES_RULES.iter())
134        .find(|r| r.id == id)
135}
136
137/// Build the docs URL for a rule.
138#[must_use]
139pub fn rule_docs_url(rule: &RuleDef) -> String {
140    format!("{DOCS_BASE}/{}", rule.docs_path)
141}
142
143// ── Health SARIF rules ──────────────────────────────────────────
144
145pub const HEALTH_RULES: &[RuleDef] = &[
146    RuleDef {
147        id: "fallow/high-cyclomatic-complexity",
148        name: "High Cyclomatic Complexity",
149        short: "Function has high cyclomatic complexity",
150        full: "McCabe cyclomatic complexity exceeds the configured threshold. Cyclomatic complexity counts the number of independent paths through a function (1 + decision points: if/else, switch cases, loops, ternary, logical operators). High values indicate functions that are hard to test exhaustively.",
151        docs_path: "explanations/health#cyclomatic-complexity",
152    },
153    RuleDef {
154        id: "fallow/high-cognitive-complexity",
155        name: "High Cognitive Complexity",
156        short: "Function has high cognitive complexity",
157        full: "SonarSource cognitive complexity exceeds the configured threshold. Unlike cyclomatic complexity, cognitive complexity penalizes nesting depth and non-linear control flow (breaks, continues, early returns). It measures how hard a function is to understand when reading sequentially.",
158        docs_path: "explanations/health#cognitive-complexity",
159    },
160    RuleDef {
161        id: "fallow/high-complexity",
162        name: "High Complexity (Both)",
163        short: "Function exceeds both complexity thresholds",
164        full: "Function exceeds both cyclomatic and cognitive complexity thresholds. This is the strongest signal that a function needs refactoring — it has many paths AND is hard to understand.",
165        docs_path: "explanations/health#complexity-metrics",
166    },
167    RuleDef {
168        id: "fallow/refactoring-target",
169        name: "Refactoring Target",
170        short: "File identified as a high-priority refactoring candidate",
171        full: "File identified as a refactoring candidate based on a weighted combination of complexity density, churn velocity, dead code ratio, fan-in (blast radius), and fan-out (coupling). Categories: urgent churn+complexity, break circular dependency, split high-impact file, remove dead code, extract complex functions, reduce coupling.",
172        docs_path: "explanations/health#refactoring-targets",
173    },
174];
175
176pub const DUPES_RULES: &[RuleDef] = &[RuleDef {
177    id: "fallow/code-duplication",
178    name: "Code Duplication",
179    short: "Duplicated code block",
180    full: "A block of code that appears in multiple locations with identical or near-identical token sequences. Clone detection uses normalized token comparison — identifier names and literals are abstracted away in non-strict modes.",
181    docs_path: "explanations/duplication#clone-groups",
182}];
183
184// ── JSON _meta builders ─────────────────────────────────────────
185
186/// Build the `_meta` object for `fallow dead-code --format json --explain`.
187#[must_use]
188pub fn check_meta() -> Value {
189    let rules: Value = CHECK_RULES
190        .iter()
191        .map(|r| {
192            (
193                r.id.replace("fallow/", ""),
194                json!({
195                    "name": r.name,
196                    "description": r.full,
197                    "docs": rule_docs_url(r)
198                }),
199            )
200        })
201        .collect::<serde_json::Map<String, Value>>()
202        .into();
203
204    json!({
205        "docs": CHECK_DOCS,
206        "rules": rules
207    })
208}
209
210/// Build the `_meta` object for `fallow health --format json --explain`.
211#[must_use]
212pub fn health_meta() -> Value {
213    json!({
214        "docs": HEALTH_DOCS,
215        "metrics": {
216            "cyclomatic": {
217                "name": "Cyclomatic Complexity",
218                "description": "McCabe cyclomatic complexity: 1 + number of decision points (if/else, switch cases, loops, ternary, logical operators). Measures the number of independent paths through a function.",
219                "range": "[1, \u{221e})",
220                "interpretation": "lower is better; default threshold: 20"
221            },
222            "cognitive": {
223                "name": "Cognitive Complexity",
224                "description": "SonarSource cognitive complexity: penalizes nesting depth and non-linear control flow (breaks, continues, early returns). Measures how hard a function is to understand when reading top-to-bottom.",
225                "range": "[0, \u{221e})",
226                "interpretation": "lower is better; default threshold: 15"
227            },
228            "line_count": {
229                "name": "Line Count",
230                "description": "Number of lines in the function body.",
231                "range": "[1, \u{221e})",
232                "interpretation": "context-dependent; long functions may need splitting"
233            },
234            "maintainability_index": {
235                "name": "Maintainability Index",
236                "description": "Composite score: 100 - (complexity_density \u{00d7} 30) - (dead_code_ratio \u{00d7} 20) - min(ln(fan_out+1) \u{00d7} 4, 15). Clamped to [0, 100]. Higher is better.",
237                "range": "[0, 100]",
238                "interpretation": "higher is better; <40 poor, 40\u{2013}70 moderate, >70 good"
239            },
240            "complexity_density": {
241                "name": "Complexity Density",
242                "description": "Total cyclomatic complexity divided by lines of code. Measures how densely complex the code is per line.",
243                "range": "[0, \u{221e})",
244                "interpretation": "lower is better; >1.0 indicates very dense complexity"
245            },
246            "dead_code_ratio": {
247                "name": "Dead Code Ratio",
248                "description": "Fraction of value exports (excluding type-only exports like interfaces and type aliases) with zero references across the project.",
249                "range": "[0, 1]",
250                "interpretation": "lower is better; 0 = all exports are used"
251            },
252            "fan_in": {
253                "name": "Fan-in (Importers)",
254                "description": "Number of files that import this file. High fan-in means high blast radius \u{2014} changes to this file affect many dependents.",
255                "range": "[0, \u{221e})",
256                "interpretation": "context-dependent; high fan-in files need careful review before changes"
257            },
258            "fan_out": {
259                "name": "Fan-out (Imports)",
260                "description": "Number of files this file directly imports. High fan-out indicates high coupling and change propagation risk.",
261                "range": "[0, \u{221e})",
262                "interpretation": "lower is better; MI penalty caps at ~40 imports"
263            },
264            "score": {
265                "name": "Hotspot Score",
266                "description": "normalized_churn \u{00d7} normalized_complexity \u{00d7} 100, where normalization is against the project maximum. Identifies files that are both complex AND frequently changing.",
267                "range": "[0, 100]",
268                "interpretation": "higher = riskier; prioritize refactoring high-score files"
269            },
270            "weighted_commits": {
271                "name": "Weighted Commits",
272                "description": "Recency-weighted commit count using exponential decay with 90-day half-life. Recent commits contribute more than older ones.",
273                "range": "[0, \u{221e})",
274                "interpretation": "higher = more recent churn activity"
275            },
276            "trend": {
277                "name": "Churn Trend",
278                "description": "Compares recent vs older commit frequency within the analysis window. accelerating = recent > 1.5\u{00d7} older, cooling = recent < 0.67\u{00d7} older, stable = in between.",
279                "values": ["accelerating", "stable", "cooling"],
280                "interpretation": "accelerating files need attention; cooling files are stabilizing"
281            },
282            "priority": {
283                "name": "Refactoring Priority",
284                "description": "Weighted score: complexity density (30%), hotspot boost (25%), dead code ratio (20%), fan-in (15%), fan-out (10%). Fan-in and fan-out normalization uses adaptive percentile-based thresholds (p95 of the project distribution). Does not use the maintainability index to avoid double-counting.",
285                "range": "[0, 100]",
286                "interpretation": "higher = more urgent to refactor"
287            },
288            "efficiency": {
289                "name": "Efficiency Score",
290                "description": "priority / effort_numeric (Low=1, Medium=2, High=3). Surfaces quick wins: high-priority, low-effort targets rank first. Default sort order.",
291                "range": "[0, 100] \u{2014} effective max depends on effort: Low=100, Medium=50, High\u{2248}33",
292                "interpretation": "higher = better quick-win value; targets are sorted by efficiency descending"
293            },
294            "effort": {
295                "name": "Effort Estimate",
296                "description": "Heuristic effort estimate based on file size, function count, and fan-in. Thresholds adapt to the project\u{2019}s distribution (percentile-based). Low: small file, few functions, low fan-in. High: large file, high fan-in, or many functions with high density. Medium: everything else.",
297                "values": ["low", "medium", "high"],
298                "interpretation": "low = quick win, high = needs planning and coordination"
299            },
300            "confidence": {
301                "name": "Confidence Level",
302                "description": "Reliability of the recommendation based on data source. High: deterministic graph/AST analysis (dead code, circular deps, complexity). Medium: heuristic thresholds (fan-in/fan-out coupling). Low: depends on git history quality (churn-based recommendations).",
303                "values": ["high", "medium", "low"],
304                "interpretation": "high = act on it, medium = verify context, low = treat as a signal, not a directive"
305            },
306            "health_score": {
307                "name": "Health Score",
308                "description": "Project-level aggregate score computed from vital signs: dead code, complexity, maintainability, hotspots, unused deps, and circular deps. Penalties subtracted from 100. Missing metrics (from pipelines that didn't run) don't penalize. Use --score to force full pipeline for maximum accuracy.",
309                "range": "[0, 100]",
310                "interpretation": "higher is better; A (85\u{2013}100), B (70\u{2013}84), C (55\u{2013}69), D (40\u{2013}54), F (0\u{2013}39)"
311            }
312        }
313    })
314}
315
316/// Build the `_meta` object for `fallow dupes --format json --explain`.
317#[must_use]
318pub fn dupes_meta() -> Value {
319    json!({
320        "docs": DUPES_DOCS,
321        "metrics": {
322            "duplication_percentage": {
323                "name": "Duplication Percentage",
324                "description": "Fraction of total source tokens that appear in at least one clone group. Computed over the full analyzed file set.",
325                "range": "[0, 100]",
326                "interpretation": "lower is better"
327            },
328            "token_count": {
329                "name": "Token Count",
330                "description": "Number of normalized source tokens in the clone group. Tokens are language-aware (keywords, identifiers, operators, punctuation). Higher token count = larger duplicate.",
331                "range": "[1, \u{221e})",
332                "interpretation": "larger clones have higher refactoring value"
333            },
334            "line_count": {
335                "name": "Line Count",
336                "description": "Number of source lines spanned by the clone instance. Approximation of clone size for human readability.",
337                "range": "[1, \u{221e})",
338                "interpretation": "larger clones are more impactful to deduplicate"
339            },
340            "clone_groups": {
341                "name": "Clone Groups",
342                "description": "A set of code fragments with identical or near-identical normalized token sequences. Each group has 2+ instances across different locations.",
343                "interpretation": "each group is a single refactoring opportunity"
344            },
345            "clone_families": {
346                "name": "Clone Families",
347                "description": "Groups of clone groups that share the same set of files. Indicates systematic duplication patterns (e.g., mirrored directory structures).",
348                "interpretation": "families suggest extract-module refactoring opportunities"
349            }
350        }
351    })
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357
358    // ── rule_by_id ───────────────────────────────────────────────────
359
360    #[test]
361    fn rule_by_id_finds_check_rule() {
362        let rule = rule_by_id("fallow/unused-file").unwrap();
363        assert_eq!(rule.name, "Unused Files");
364    }
365
366    #[test]
367    fn rule_by_id_finds_health_rule() {
368        let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
369        assert_eq!(rule.name, "High Cyclomatic Complexity");
370    }
371
372    #[test]
373    fn rule_by_id_finds_dupes_rule() {
374        let rule = rule_by_id("fallow/code-duplication").unwrap();
375        assert_eq!(rule.name, "Code Duplication");
376    }
377
378    #[test]
379    fn rule_by_id_returns_none_for_unknown() {
380        assert!(rule_by_id("fallow/nonexistent").is_none());
381        assert!(rule_by_id("").is_none());
382    }
383
384    // ── rule_docs_url ────────────────────────────────────────────────
385
386    #[test]
387    fn rule_docs_url_format() {
388        let rule = rule_by_id("fallow/unused-export").unwrap();
389        let url = rule_docs_url(rule);
390        assert!(url.starts_with("https://docs.fallow.tools/"));
391        assert!(url.contains("unused-exports"));
392    }
393
394    // ── CHECK_RULES completeness ─────────────────────────────────────
395
396    #[test]
397    fn check_rules_all_have_fallow_prefix() {
398        for rule in CHECK_RULES {
399            assert!(
400                rule.id.starts_with("fallow/"),
401                "rule {} should start with fallow/",
402                rule.id
403            );
404        }
405    }
406
407    #[test]
408    fn check_rules_all_have_docs_path() {
409        for rule in CHECK_RULES {
410            assert!(
411                !rule.docs_path.is_empty(),
412                "rule {} should have a docs_path",
413                rule.id
414            );
415        }
416    }
417
418    #[test]
419    fn check_rules_no_duplicate_ids() {
420        let mut seen = rustc_hash::FxHashSet::default();
421        for rule in CHECK_RULES.iter().chain(HEALTH_RULES).chain(DUPES_RULES) {
422            assert!(seen.insert(rule.id), "duplicate rule id: {}", rule.id);
423        }
424    }
425
426    // ── check_meta ───────────────────────────────────────────────────
427
428    #[test]
429    fn check_meta_has_docs_and_rules() {
430        let meta = check_meta();
431        assert!(meta.get("docs").is_some());
432        assert!(meta.get("rules").is_some());
433        let rules = meta["rules"].as_object().unwrap();
434        // Verify all 13 rule categories are present (stripped fallow/ prefix)
435        assert_eq!(rules.len(), CHECK_RULES.len());
436        assert!(rules.contains_key("unused-file"));
437        assert!(rules.contains_key("unused-export"));
438        assert!(rules.contains_key("unused-type"));
439        assert!(rules.contains_key("unused-dependency"));
440        assert!(rules.contains_key("unused-dev-dependency"));
441        assert!(rules.contains_key("unused-optional-dependency"));
442        assert!(rules.contains_key("unused-enum-member"));
443        assert!(rules.contains_key("unused-class-member"));
444        assert!(rules.contains_key("unresolved-import"));
445        assert!(rules.contains_key("unlisted-dependency"));
446        assert!(rules.contains_key("duplicate-export"));
447        assert!(rules.contains_key("type-only-dependency"));
448        assert!(rules.contains_key("circular-dependency"));
449    }
450
451    #[test]
452    fn check_meta_rule_has_required_fields() {
453        let meta = check_meta();
454        let rules = meta["rules"].as_object().unwrap();
455        for (key, value) in rules {
456            assert!(value.get("name").is_some(), "rule {key} missing 'name'");
457            assert!(
458                value.get("description").is_some(),
459                "rule {key} missing 'description'"
460            );
461            assert!(value.get("docs").is_some(), "rule {key} missing 'docs'");
462        }
463    }
464
465    // ── health_meta ──────────────────────────────────────────────────
466
467    #[test]
468    fn health_meta_has_metrics() {
469        let meta = health_meta();
470        assert!(meta.get("docs").is_some());
471        let metrics = meta["metrics"].as_object().unwrap();
472        assert!(metrics.contains_key("cyclomatic"));
473        assert!(metrics.contains_key("cognitive"));
474        assert!(metrics.contains_key("maintainability_index"));
475        assert!(metrics.contains_key("complexity_density"));
476        assert!(metrics.contains_key("fan_in"));
477        assert!(metrics.contains_key("fan_out"));
478    }
479
480    // ── dupes_meta ───────────────────────────────────────────────────
481
482    #[test]
483    fn dupes_meta_has_metrics() {
484        let meta = dupes_meta();
485        assert!(meta.get("docs").is_some());
486        let metrics = meta["metrics"].as_object().unwrap();
487        assert!(metrics.contains_key("duplication_percentage"));
488        assert!(metrics.contains_key("token_count"));
489        assert!(metrics.contains_key("clone_groups"));
490        assert!(metrics.contains_key("clone_families"));
491    }
492
493    // ── HEALTH_RULES completeness ──────────────────────────────────
494
495    #[test]
496    fn health_rules_all_have_fallow_prefix() {
497        for rule in HEALTH_RULES {
498            assert!(
499                rule.id.starts_with("fallow/"),
500                "health rule {} should start with fallow/",
501                rule.id
502            );
503        }
504    }
505
506    #[test]
507    fn health_rules_all_have_docs_path() {
508        for rule in HEALTH_RULES {
509            assert!(
510                !rule.docs_path.is_empty(),
511                "health rule {} should have a docs_path",
512                rule.id
513            );
514        }
515    }
516
517    #[test]
518    fn health_rules_all_have_non_empty_fields() {
519        for rule in HEALTH_RULES {
520            assert!(
521                !rule.name.is_empty(),
522                "health rule {} missing name",
523                rule.id
524            );
525            assert!(
526                !rule.short.is_empty(),
527                "health rule {} missing short description",
528                rule.id
529            );
530            assert!(
531                !rule.full.is_empty(),
532                "health rule {} missing full description",
533                rule.id
534            );
535        }
536    }
537
538    // ── DUPES_RULES completeness ───────────────────────────────────
539
540    #[test]
541    fn dupes_rules_all_have_fallow_prefix() {
542        for rule in DUPES_RULES {
543            assert!(
544                rule.id.starts_with("fallow/"),
545                "dupes rule {} should start with fallow/",
546                rule.id
547            );
548        }
549    }
550
551    #[test]
552    fn dupes_rules_all_have_docs_path() {
553        for rule in DUPES_RULES {
554            assert!(
555                !rule.docs_path.is_empty(),
556                "dupes rule {} should have a docs_path",
557                rule.id
558            );
559        }
560    }
561
562    #[test]
563    fn dupes_rules_all_have_non_empty_fields() {
564        for rule in DUPES_RULES {
565            assert!(!rule.name.is_empty(), "dupes rule {} missing name", rule.id);
566            assert!(
567                !rule.short.is_empty(),
568                "dupes rule {} missing short description",
569                rule.id
570            );
571            assert!(
572                !rule.full.is_empty(),
573                "dupes rule {} missing full description",
574                rule.id
575            );
576        }
577    }
578
579    // ── CHECK_RULES field completeness ─────────────────────────────
580
581    #[test]
582    fn check_rules_all_have_non_empty_fields() {
583        for rule in CHECK_RULES {
584            assert!(!rule.name.is_empty(), "check rule {} missing name", rule.id);
585            assert!(
586                !rule.short.is_empty(),
587                "check rule {} missing short description",
588                rule.id
589            );
590            assert!(
591                !rule.full.is_empty(),
592                "check rule {} missing full description",
593                rule.id
594            );
595        }
596    }
597
598    // ── rule_docs_url with health/dupes rules ──────────────────────
599
600    #[test]
601    fn rule_docs_url_health_rule() {
602        let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
603        let url = rule_docs_url(rule);
604        assert!(url.starts_with("https://docs.fallow.tools/"));
605        assert!(url.contains("health"));
606    }
607
608    #[test]
609    fn rule_docs_url_dupes_rule() {
610        let rule = rule_by_id("fallow/code-duplication").unwrap();
611        let url = rule_docs_url(rule);
612        assert!(url.starts_with("https://docs.fallow.tools/"));
613        assert!(url.contains("duplication"));
614    }
615
616    // ── health_meta metric structure ───────────────────────────────
617
618    #[test]
619    fn health_meta_all_metrics_have_name_and_description() {
620        let meta = health_meta();
621        let metrics = meta["metrics"].as_object().unwrap();
622        for (key, value) in metrics {
623            assert!(
624                value.get("name").is_some(),
625                "health metric {key} missing 'name'"
626            );
627            assert!(
628                value.get("description").is_some(),
629                "health metric {key} missing 'description'"
630            );
631            assert!(
632                value.get("interpretation").is_some(),
633                "health metric {key} missing 'interpretation'"
634            );
635        }
636    }
637
638    #[test]
639    fn health_meta_has_all_expected_metrics() {
640        let meta = health_meta();
641        let metrics = meta["metrics"].as_object().unwrap();
642        let expected = [
643            "cyclomatic",
644            "cognitive",
645            "line_count",
646            "maintainability_index",
647            "complexity_density",
648            "dead_code_ratio",
649            "fan_in",
650            "fan_out",
651            "score",
652            "weighted_commits",
653            "trend",
654            "priority",
655            "efficiency",
656            "effort",
657            "confidence",
658        ];
659        for key in &expected {
660            assert!(
661                metrics.contains_key(*key),
662                "health_meta missing expected metric: {key}"
663            );
664        }
665    }
666
667    // ── dupes_meta metric structure ────────────────────────────────
668
669    #[test]
670    fn dupes_meta_all_metrics_have_name_and_description() {
671        let meta = dupes_meta();
672        let metrics = meta["metrics"].as_object().unwrap();
673        for (key, value) in metrics {
674            assert!(
675                value.get("name").is_some(),
676                "dupes metric {key} missing 'name'"
677            );
678            assert!(
679                value.get("description").is_some(),
680                "dupes metric {key} missing 'description'"
681            );
682        }
683    }
684
685    #[test]
686    fn dupes_meta_has_line_count() {
687        let meta = dupes_meta();
688        let metrics = meta["metrics"].as_object().unwrap();
689        assert!(metrics.contains_key("line_count"));
690    }
691
692    // ── docs URLs ─────────────────────────────────────────────────
693
694    #[test]
695    fn check_docs_url_valid() {
696        assert!(CHECK_DOCS.starts_with("https://"));
697        assert!(CHECK_DOCS.contains("dead-code"));
698    }
699
700    #[test]
701    fn health_docs_url_valid() {
702        assert!(HEALTH_DOCS.starts_with("https://"));
703        assert!(HEALTH_DOCS.contains("health"));
704    }
705
706    #[test]
707    fn dupes_docs_url_valid() {
708        assert!(DUPES_DOCS.starts_with("https://"));
709        assert!(DUPES_DOCS.contains("dupes"));
710    }
711
712    // ── check_meta docs URL matches constant ──────────────────────
713
714    #[test]
715    fn check_meta_docs_url_matches_constant() {
716        let meta = check_meta();
717        assert_eq!(meta["docs"].as_str().unwrap(), CHECK_DOCS);
718    }
719
720    #[test]
721    fn health_meta_docs_url_matches_constant() {
722        let meta = health_meta();
723        assert_eq!(meta["docs"].as_str().unwrap(), HEALTH_DOCS);
724    }
725
726    #[test]
727    fn dupes_meta_docs_url_matches_constant() {
728        let meta = dupes_meta();
729        assert_eq!(meta["docs"].as_str().unwrap(), DUPES_DOCS);
730    }
731
732    // ── rule_by_id finds all check rules ──────────────────────────
733
734    #[test]
735    fn rule_by_id_finds_all_check_rules() {
736        for rule in CHECK_RULES {
737            assert!(
738                rule_by_id(rule.id).is_some(),
739                "rule_by_id should find check rule {}",
740                rule.id
741            );
742        }
743    }
744
745    #[test]
746    fn rule_by_id_finds_all_health_rules() {
747        for rule in HEALTH_RULES {
748            assert!(
749                rule_by_id(rule.id).is_some(),
750                "rule_by_id should find health rule {}",
751                rule.id
752            );
753        }
754    }
755
756    #[test]
757    fn rule_by_id_finds_all_dupes_rules() {
758        for rule in DUPES_RULES {
759            assert!(
760                rule_by_id(rule.id).is_some(),
761                "rule_by_id should find dupes rule {}",
762                rule.id
763            );
764        }
765    }
766
767    // ── Rule count verification ───────────────────────────────────
768
769    #[test]
770    fn check_rules_count() {
771        assert_eq!(CHECK_RULES.len(), 13);
772    }
773
774    #[test]
775    fn health_rules_count() {
776        assert_eq!(HEALTH_RULES.len(), 4);
777    }
778
779    #[test]
780    fn dupes_rules_count() {
781        assert_eq!(DUPES_RULES.len(), 1);
782    }
783}