Skip to main content

fallow_output/
report_contract.rs

1use std::collections::BTreeMap;
2
3use fallow_types::envelope::{Meta, MetaMetric, MetaRule};
4use serde_json::{Value, json};
5
6use crate::{ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION, ACTIONS_FIELD_DEFINITION};
7
8/// Docs URL for the duplication command.
9pub const DUPES_DOCS: &str = "https://docs.fallow.tools/cli/dupes";
10
11/// Docs URL for the runtime coverage setup command's agent-readable JSON.
12pub const COVERAGE_SETUP_DOCS: &str = "https://docs.fallow.tools/cli/coverage#agent-readable-json";
13
14/// Docs URL for `fallow coverage analyze --format json --explain`.
15pub const COVERAGE_ANALYZE_DOCS: &str = "https://docs.fallow.tools/cli/coverage#analyze";
16
17/// Docs URL for the health command.
18pub const HEALTH_DOCS: &str = "https://docs.fallow.tools/cli/health";
19
20/// Docs URL for the security command.
21pub const SECURITY_DOCS: &str = "https://docs.fallow.tools/cli/security";
22
23/// Output-facing metadata for one security rule.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub struct SecurityRuleMeta<'a> {
26    pub id: &'a str,
27    pub name: &'a str,
28    pub description: &'a str,
29    pub docs_path: &'a str,
30}
31
32/// Build the `_meta` object for `fallow health --format json --explain`.
33#[must_use]
34pub fn health_meta() -> Meta {
35    Meta {
36        docs: Some(HEALTH_DOCS.to_string()),
37        field_definitions: action_field_definitions(),
38        metrics: health_metrics(),
39        ..Meta::default()
40    }
41}
42
43/// Build the `_meta` object for `fallow security --format json --explain`.
44#[must_use]
45pub fn security_meta<'a>(rules: impl IntoIterator<Item = SecurityRuleMeta<'a>>) -> Meta {
46    Meta {
47        docs: Some(SECURITY_DOCS.to_string()),
48        field_definitions: security_field_definitions(),
49        metrics: BTreeMap::new(),
50        rules: rules
51            .into_iter()
52            .map(|rule| {
53                (
54                    rule.id.to_string(),
55                    MetaRule {
56                        name: Some(rule.name.to_string()),
57                        description: Some(rule.description.to_string()),
58                        docs: Some(report_rule_docs_url(rule.docs_path)),
59                    },
60                )
61            })
62            .collect(),
63        ..Meta::default()
64    }
65}
66
67/// Build the `_meta` object for `fallow dupes --format json --explain`.
68#[must_use]
69pub fn dupes_meta() -> Meta {
70    Meta {
71        docs: Some(DUPES_DOCS.to_string()),
72        field_definitions: action_field_definitions(),
73        metrics: dupes_metrics(),
74        ..Meta::default()
75    }
76}
77
78fn dupes_metrics() -> BTreeMap<String, MetaMetric> {
79    BTreeMap::from([
80        (
81            "duplication_percentage".to_string(),
82            metric(
83                "Duplication Percentage",
84                "Fraction of total source tokens that appear in at least one clone group. Computed over the full analyzed file set.",
85                Some("[0, 100]"),
86                "lower is better",
87            ),
88        ),
89        (
90            "token_count".to_string(),
91            metric(
92                "Token Count",
93                "Number of normalized source tokens in the clone group. Tokens are language-aware (keywords, identifiers, operators, punctuation). Higher token count = larger duplicate.",
94                Some("[1, ∞)"),
95                "larger clones have higher refactoring value",
96            ),
97        ),
98        (
99            "line_count".to_string(),
100            metric(
101                "Line Count",
102                "Number of source lines spanned by the clone instance. Approximation of clone size for human readability.",
103                Some("[1, ∞)"),
104                "larger clones are more impactful to deduplicate",
105            ),
106        ),
107        (
108            "clone_groups".to_string(),
109            metric(
110                "Clone Groups",
111                "A set of code fragments with identical or near-identical normalized token sequences. Each group has 2+ instances across different locations.",
112                None,
113                "each group is a single refactoring opportunity",
114            ),
115        ),
116        (
117            "clone_groups_below_min_occurrences".to_string(),
118            metric(
119                "Clone Groups Below minOccurrences",
120                "Number of clone groups detected but hidden by the `duplicates.minOccurrences` filter. Always 0 (or absent) when the filter is at its default of 2. Pre-filter group count = `clone_groups + clone_groups_below_min_occurrences`.",
121                Some("[0, ∞)"),
122                "high values suggest noisy pair-only duplication; lower `minOccurrences` to inspect",
123            ),
124        ),
125        (
126            "clone_families".to_string(),
127            metric(
128                "Clone Families",
129                "Groups of clone groups that share the same set of files. Indicates systematic duplication patterns (e.g., mirrored directory structures).",
130                None,
131                "families suggest extract-module refactoring opportunities",
132            ),
133        ),
134    ])
135}
136
137/// Build the `_meta` object for `fallow coverage setup --json --explain`.
138#[must_use]
139pub fn coverage_setup_meta() -> Value {
140    json!({
141        "docs_url": COVERAGE_SETUP_DOCS,
142        "field_definitions": {
143            "schema_version": "Coverage setup JSON contract version. Stays at \"1\" for additive opt-in fields such as _meta.",
144            "framework_detected": "Primary detected runtime framework for compatibility with single-app consumers. In workspaces this mirrors the first emitted runtime member; unknown means no runtime member was detected.",
145            "package_manager": "Detected package manager used for install and run commands, or null when no package manager signal was found.",
146            "runtime_targets": "Union of runtime targets across emitted members.",
147            "members[]": "Per-runtime-workspace setup recipes. Pure aggregator roots and build-only libraries are omitted.",
148            "members[].name": "Workspace package name from package.json, or the root directory name when package.json has no name.",
149            "members[].path": "Workspace path relative to the command root. The root package is represented as \".\".",
150            "members[].framework_detected": "Runtime framework detected for that member.",
151            "members[].package_manager": "Package manager detected for that member, or inherited from the workspace root when no member-specific signal exists.",
152            "members[].runtime_targets": "Runtime targets produced by that member.",
153            "members[].files_to_edit": "Files in that member that should receive runtime beacon setup code.",
154            "members[].snippets": "Copy-paste setup snippets for that member, with paths relative to the command root.",
155            "members[].dockerfile_snippet": "Environment snippet for file-system capture in that member's containerized Node runtime, or null when not applicable.",
156            "members[].warnings": "Actionable setup caveats discovered for that member.",
157            "config_written": "Always null for --json because JSON setup is side-effect-free and never writes configuration.",
158            "files_to_edit": "Compatibility copy of the primary member's files, with workspace prefixes when the primary member is not the root.",
159            "snippets": "Compatibility copy of the primary member's snippets, with workspace prefixes when the primary member is not the root.",
160            "dockerfile_snippet": "Environment snippet for file-system capture in containerized Node runtimes, or null when not applicable.",
161            "commands": "Package-manager commands needed to install the runtime beacon and sidecar packages.",
162            "next_steps": "Ordered setup workflow after applying the emitted snippets.",
163            "warnings": "Actionable setup caveats discovered while building the recipe."
164        },
165        "enums": {
166            "framework_detected": ["nextjs", "nestjs", "nuxt", "sveltekit", "astro", "remix", "vite", "plain_node", "unknown"],
167            "runtime_targets": ["node", "browser"],
168            "package_manager": ["npm", "pnpm", "yarn", "bun", null]
169        },
170        "warnings": {
171            "No runtime workspace members were detected": "The root appears to be a workspace, but no runtime-bearing package was found. The payload emits install commands only.",
172            "No local coverage artifact was detected yet": "Run the application with runtime coverage collection enabled, then re-run setup or health with the produced capture path.",
173            "Package manager was not detected": "No packageManager field or known lockfile was found. Commands fall back to npm.",
174            "Framework was not detected": "No known framework dependency or runtime script was found. Treat the recipe as a generic Node setup and adjust the entry path as needed."
175        }
176    })
177}
178
179/// Build the `_meta` object for `fallow coverage analyze --format json --explain`.
180#[must_use]
181pub fn coverage_analyze_meta() -> Value {
182    json!({
183        "docs_url": COVERAGE_ANALYZE_DOCS,
184        "field_definitions": {
185            "schema_version": "Standalone coverage analyze envelope version. \"1\" for the current shape.",
186            "version": "fallow CLI version that produced this output.",
187            "elapsed_ms": "Wall-clock milliseconds spent producing the report.",
188            "runtime_coverage": "Same RuntimeCoverageReport block emitted by `fallow health --runtime-coverage`.",
189            "runtime_coverage.summary.data_source": "Which evidence source produced the report. local = on-disk artifact via --runtime-coverage <path>; cloud = explicit pull via --cloud / --runtime-coverage-cloud / FALLOW_RUNTIME_COVERAGE_SOURCE=cloud.",
190            "runtime_coverage.summary.last_received_at": "ISO-8601 timestamp of the newest runtime payload included in the report. Null for local artifacts that do not carry receipt metadata.",
191            "runtime_coverage.summary.capture_quality": "Capture-window telemetry derived from the runtime evidence. lazy_parse_warning trips when more than 30% of tracked functions are V8-untracked, which usually indicates a short observation window.",
192            "runtime_coverage.findings[].id": "Per-finding SUPPRESSION key (fallow:prod:<hash>). Hashes file + function + the current line, so it changes when the function moves. Use it to suppress one finding at its current location.",
193            "runtime_coverage.findings[].stable_id": "Cross-surface JOIN key (fallow:fn:<hash>) from fallow_cov_protocol::function_identity_id, hashing file + name + start_line. The same function shares ONE value across findings, hot paths, blast-radius, and importance entries (the per-finding id uses a per-surface salt and differs), and across V8/Istanbul/oxc producers (columns are excluded from the hash). Like id, it changes when the function's file, name, or start line changes: it is a cross-surface/cross-producer join key, NOT a line-move-immune one. Omitted from the JSON entirely (not emitted as null) when the producing surface or an un-migrated cloud supplied no FunctionIdentity. New baselines key on this when present to align with the cross-surface join key; the grace-window reader accepts the legacy id too.",
194            "runtime_coverage._matching": "Function-identity fallback order when joining runtime evidence to local static analysis: (1) exact stable_id match (fallow:fn:<hash>) when both sides carry one; (2) exact (path, name, start_line); (3) fuzzy nearest candidate within a line tolerance. Baseline suppression accepts BOTH the stable_id and the legacy fallow:prod: id during the grace window, so baselines written before this version keep suppressing.",
195            "runtime_coverage.findings[].evidence.static_status": "used = the function is reachable in the AST module graph; unused = it is dead by static analysis.",
196            "runtime_coverage.findings[].evidence.test_coverage": "covered = the local test suite hits the function; not_covered otherwise.",
197            "runtime_coverage.findings[].evidence.v8_tracking": "tracked = V8 observed the function during the capture window; untracked otherwise.",
198            "runtime_coverage.findings[].actions[].type": "Suggested follow-up identifier. delete-cold-code is emitted on safe_to_delete; review-runtime on review_required.",
199            "runtime_coverage.blast_radius[]": "First-class blast-radius entries with stable fallow:blast IDs, static caller count, traffic-weighted caller reach, optional cloud deploy touch count, and low/medium/high risk band.",
200            "runtime_coverage.importance[]": "First-class production-importance entries with stable fallow:importance IDs, invocations, cyclomatic complexity, owner count, 0-100 importance score, and templated reason.",
201            "runtime_coverage.warnings[].code": "Stable warning identifier. cloud_functions_unmatched flags entries dropped because no AST/static counterpart was found locally."
202        },
203        "enums": {
204            "data_source": ["local", "cloud"],
205            "report_verdict": ["clean", "hot-path-touched", "cold-code-detected", "license-expired-grace", "unknown"],
206            "finding_verdict": ["safe_to_delete", "review_required", "coverage_unavailable", "low_traffic", "active", "unknown"],
207            "static_status": ["used", "unused"],
208            "test_coverage": ["covered", "not_covered"],
209            "v8_tracking": ["tracked", "untracked"],
210            "action_type": ["delete-cold-code", "review-runtime"]
211        },
212        "warnings": {
213            "no_runtime_data": "Cloud returned an empty runtime window. Either the period is too narrow or no traces have been ingested yet.",
214            "cloud_functions_unmatched": "One or more cloud-side functions could not be matched against the local AST/static index and were dropped from findings. Common causes: stale runtime data after a rename/move, file path mismatch between deploy and repo, or analysis run on the wrong commit."
215        }
216    })
217}
218
219fn action_field_definitions() -> BTreeMap<String, String> {
220    BTreeMap::from([
221        (
222            "actions[]".to_string(),
223            ACTIONS_FIELD_DEFINITION.to_string(),
224        ),
225        (
226            "actions[].auto_fixable".to_string(),
227            ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION.to_string(),
228        ),
229    ])
230}
231
232fn security_field_definitions() -> BTreeMap<String, String> {
233    BTreeMap::from([
234        (
235            "version".to_string(),
236            "fallow CLI version that produced this output.".to_string(),
237        ),
238        (
239            "elapsed_ms".to_string(),
240            "Wall-clock milliseconds spent producing the security report.".to_string(),
241        ),
242        (
243            "config".to_string(),
244            "Privacy-safe config context relevant to security candidate generation.".to_string(),
245        ),
246        (
247            "config.rules.*.configured".to_string(),
248            "Severity from resolved config before the security command forced default-off rules on."
249                .to_string(),
250        ),
251        (
252            "config.rules.*.effective".to_string(),
253            "Severity used for this security command run.".to_string(),
254        ),
255        (
256            "config.categories_include".to_string(),
257            "Configured security category include list. null means unset, [] means explicitly empty."
258                .to_string(),
259        ),
260        (
261            "config.categories_exclude".to_string(),
262            "Configured security category exclude list. null means unset, [] means explicitly empty."
263                .to_string(),
264        ),
265        (
266            "security_findings[]".to_string(),
267            "Unverified security candidates for downstream human or agent verification.".to_string(),
268        ),
269        (
270            "summary.security_findings".to_string(),
271            "Number of security candidates after all filters, gates, and scopes.".to_string(),
272        ),
273        (
274            "summary.by_severity".to_string(),
275            "Fixed high, medium, and low severity counts for summary JSON.".to_string(),
276        ),
277        (
278            "summary.by_category".to_string(),
279            "Candidate counts by catalogue category, or by kind for uncategorized findings."
280                .to_string(),
281        ),
282        (
283            "summary.by_reachability".to_string(),
284            "Fixed reachability and source-backed ranking-signal counts for summary JSON."
285                .to_string(),
286        ),
287        (
288            "summary.by_runtime_state".to_string(),
289            "Fixed production-runtime coverage state counts for summary JSON.".to_string(),
290        ),
291        (
292            "unresolved_edge_files".to_string(),
293            "Number of client files whose import cone contains dynamic edges the graph could not follow."
294                .to_string(),
295        ),
296        (
297            "unresolved_callee_sites".to_string(),
298            "Number of sink-shaped nodes whose callee could not be flattened to a static path."
299                .to_string(),
300        ),
301    ])
302}
303
304fn health_metrics() -> BTreeMap<String, MetaMetric> {
305    let mut metrics = BTreeMap::new();
306    metrics.extend(health_complexity_metrics());
307    metrics.extend(health_churn_and_target_metrics());
308    metrics.extend(health_ownership_metrics());
309    metrics.extend(health_runtime_metrics());
310    metrics.extend(health_styling_metrics());
311    metrics
312}
313
314fn health_complexity_metrics() -> [(String, MetaMetric); 11] {
315    [
316        health_metric(
317            "cyclomatic",
318            "Cyclomatic Complexity",
319            "McCabe cyclomatic complexity: 1 + number of decision points.",
320            Some("[1, infinity)"),
321            "lower is better; default threshold: 20",
322        ),
323        health_metric(
324            "cognitive",
325            "Cognitive Complexity",
326            "Cognitive complexity penalizes nesting depth and non-linear control flow.",
327            Some("[0, infinity)"),
328            "lower is better; default threshold: 15",
329        ),
330        health_metric(
331            "line_count",
332            "Function Line Count",
333            "Number of lines in the function body.",
334            Some("[1, infinity)"),
335            "context-dependent; long functions may need splitting",
336        ),
337        health_metric(
338            "lines",
339            "File Line Count",
340            "Total lines of code in the file.",
341            Some("[1, infinity)"),
342            "context-dependent; large files may benefit from splitting",
343        ),
344        health_metric(
345            "maintainability_index",
346            "Maintainability Index",
347            "Composite file score combining complexity density, dead code ratio, and coupling.",
348            Some("[0, 100]"),
349            "higher is better",
350        ),
351        health_metric(
352            "complexity_density",
353            "Complexity Density",
354            "Total cyclomatic complexity divided by lines of code.",
355            Some("[0, infinity)"),
356            "lower is better; >1.0 indicates very dense complexity",
357        ),
358        health_metric(
359            "dead_code_ratio",
360            "Dead Code Ratio",
361            "Fraction of value exports with zero references across the project.",
362            Some("[0, 1]"),
363            "lower is better; 0 means all exports are used",
364        ),
365        health_metric(
366            "fan_in",
367            "Fan-in (Importers)",
368            "Number of files that import this file.",
369            Some("[0, infinity)"),
370            "context-dependent; high fan-in files need careful review",
371        ),
372        health_metric(
373            "fan_out",
374            "Fan-out (Imports)",
375            "Number of files this file directly imports.",
376            Some("[0, infinity)"),
377            "lower is better; high fan-out indicates coupling",
378        ),
379        health_metric(
380            "max_render_fan_in",
381            "Render Fan-in (Blast Radius)",
382            "Highest distinct-parent render count across React or Preact components.",
383            Some("[0, infinity)"),
384            "descriptive only; high values mean broad edit ripple",
385        ),
386        health_metric(
387            "crap_max",
388            "Untested Complexity Risk (CRAP)",
389            "Highest Change Risk Anti-Patterns score from complexity and coverage evidence.",
390            Some("[1, infinity)"),
391            "lower is better; high values indicate complex untested code",
392        ),
393    ]
394}
395
396fn health_churn_and_target_metrics() -> [(String, MetaMetric); 8] {
397    [
398        health_metric(
399            "score",
400            "Hotspot Score",
401            "Normalized churn multiplied by normalized complexity.",
402            Some("[0, 100]"),
403            "higher means riskier; prioritize refactoring high-score files",
404        ),
405        health_metric(
406            "weighted_commits",
407            "Weighted Commits",
408            "Recency-weighted commit count using exponential decay.",
409            Some("[0, infinity)"),
410            "higher means more recent churn activity",
411        ),
412        health_metric(
413            "trend",
414            "Churn Trend",
415            "Compares recent vs older commit frequency within the analysis window.",
416            None,
417            "accelerating files need attention; cooling files are stabilizing",
418        ),
419        health_metric(
420            "priority",
421            "Refactoring Priority",
422            "Weighted refactoring score using complexity, hotspots, dead code, fan-in, and fan-out.",
423            Some("[0, 100]"),
424            "higher means more urgent to refactor",
425        ),
426        health_metric(
427            "efficiency",
428            "Efficiency Score",
429            "Priority divided by effort estimate.",
430            Some("[0, 100]"),
431            "higher means better quick-win value",
432        ),
433        health_metric(
434            "effort",
435            "Effort Estimate",
436            "Heuristic effort estimate based on file size, function count, and fan-in.",
437            None,
438            "low means quick win, high needs planning and coordination",
439        ),
440        health_metric(
441            "confidence",
442            "Confidence Level",
443            "Reliability of the recommendation based on data source.",
444            None,
445            "high means act on it; medium or low means verify context",
446        ),
447        health_metric(
448            "health_score",
449            "Health Score",
450            "Project-level aggregate score computed from vital signs and issue signals.",
451            Some("[0, 100]"),
452            "higher is better; missing metrics are not penalized",
453        ),
454    ]
455}
456
457fn health_ownership_metrics() -> [(String, MetaMetric); 6] {
458    [
459        health_metric(
460            "bus_factor",
461            "Bus Factor",
462            "Minimum number of contributors who account for most recent weighted commits.",
463            Some("[1, infinity)"),
464            "lower is higher knowledge-loss risk",
465        ),
466        health_metric(
467            "contributor_count",
468            "Contributor Count",
469            "Number of distinct authors who touched this file in the analysis window.",
470            Some("[0, infinity)"),
471            "higher generally indicates broader knowledge spread",
472        ),
473        health_metric(
474            "share",
475            "Contributor Share",
476            "Recency-weighted share of total weighted commits attributed to a contributor.",
477            Some("[0, 1]"),
478            "share close to 1.0 indicates ownership concentration",
479        ),
480        health_metric(
481            "stale_days",
482            "Stale Days",
483            "Days since this contributor last touched the file.",
484            Some("[0, infinity)"),
485            "high stale days can indicate ownership drift",
486        ),
487        health_metric(
488            "drift",
489            "Ownership Drift",
490            "Whether original authorship and current contribution ownership have diverged.",
491            None,
492            "true means current review ownership may differ from original ownership",
493        ),
494        health_metric(
495            "unowned",
496            "Unowned (Tristate)",
497            "Whether CODEOWNERS exists but has no matching owner for this file.",
498            None,
499            "true on a hotspot is a review-bottleneck risk",
500        ),
501    ]
502}
503
504fn health_runtime_metrics() -> [(String, MetaMetric); 5] {
505    [
506        health_metric(
507            "runtime_coverage_verdict",
508            "Runtime Coverage Verdict",
509            "Overall verdict across runtime-coverage findings.",
510            None,
511            "cold-code-detected is the primary standalone cleanup signal",
512        ),
513        health_metric(
514            "runtime_coverage_state",
515            "Runtime Coverage State",
516            "Per-function runtime observation state.",
517            None,
518            "never-called with static unused is the highest-confidence delete signal",
519        ),
520        health_metric(
521            "runtime_coverage_confidence",
522            "Runtime Coverage Confidence",
523            "Confidence in a runtime-coverage finding.",
524            None,
525            "high means act on it; medium or low means verify context",
526        ),
527        health_metric(
528            "production_invocations",
529            "Production Invocations",
530            "Observed invocation count for the function over the collected coverage window.",
531            Some("[0, infinity)"),
532            "0 plus tracked means cold path; high means active path",
533        ),
534        health_metric(
535            "percent_dead_in_production",
536            "Percent Dead in Production",
537            "Fraction of tracked functions with zero observed invocations, multiplied by 100.",
538            Some("[0, 100]"),
539            "lower is better",
540        ),
541    ]
542}
543
544fn health_styling_metrics() -> [(String, MetaMetric); 10] {
545    [
546        health_metric(
547            "styling_health.score",
548            "Styling Health Score",
549            "CSS/styling-axis aggregate score computed from the styling penalty rubric. Present only under --css.",
550            Some("[0, 100]"),
551            "higher is better; missing metrics are not penalized",
552        ),
553        health_metric(
554            "styling_health.formula_version",
555            "Styling Health Formula Version",
556            "Version of the styling-health scoring rubric used to produce the score. Present only under --css.",
557            Some("[1, infinity)"),
558            "bump signals a rubric change; compare scores only within the same version",
559        ),
560        health_metric(
561            "styling_health.penalties.duplication",
562            "Styling Duplication Penalty",
563            "Points deducted for copy-paste declaration blocks, scaled by the share of declarations removable via consolidation. Present only under --css.",
564            Some("[0, 20]"),
565            "lower is better; 0 means no removable duplicate blocks",
566        ),
567        health_metric(
568            "styling_health.penalties.dead_surface",
569            "Styling Dead-Surface Penalty",
570            "Points deducted for unreferenced classes, unused tokens, at-rules, and font-faces, normalized per stylesheet. Present only under --css.",
571            Some("[0, 20]"),
572            "lower is better; 0 means no dead styling surface",
573        ),
574        health_metric(
575            "styling_health.penalties.broken_references",
576            "Styling Broken-References Penalty",
577            "Points deducted for markup classes one edit from a defined class and animations referencing undefined keyframes. Present only under --css.",
578            Some("[0, 15]"),
579            "lower is better; 0 means no broken references",
580        ),
581        health_metric(
582            "styling_health.penalties.token_erosion",
583            "Styling Token-Erosion Penalty",
584            "Points deducted for mixing font-size units past a healthy baseline and Tailwind arbitrary-value bypasses. Present only under --css.",
585            Some("[0, 10]"),
586            "lower is better; 0 means a single source of truth for the scale",
587        ),
588        health_metric(
589            "styling_health.penalties.structural",
590            "Styling Structural Penalty",
591            "Points deducted for !important density above a healthy floor and deep style-rule nesting. Present only under --css.",
592            Some("[0, 10]"),
593            "lower is better; 0 means no structural smells",
594        ),
595        health_metric(
596            "css_analytics.summary.near_duplicate_theme_tokens",
597            "Near-Duplicate Theme Tokens",
598            "Count of Tailwind v4 theme tokens whose comparable values are close to another token in the same theme dictionary. Present only in deep CSS analysis.",
599            Some("[0, infinity)"),
600            "0 means no near-duplicate token candidates were found",
601        ),
602        health_metric(
603            "styling_findings[].blast_radius",
604            "Styling Finding Blast Radius",
605            "Static lower-bound count of known consumers affected by a styling finding. Omitted when the family has no reliable blast-radius model.",
606            Some("[0, infinity)"),
607            "0 means no static consumers were found; omitted means unknown",
608        ),
609        health_metric(
610            "styling_findings[].nearest_token.distance",
611            "Nearest Styling Token Distance",
612            "Distance between a token-drift finding and its nearest comparable token. Units depend on the token namespace.",
613            Some("(0, infinity)"),
614            "lower means closer; compare only within the same token namespace",
615        ),
616    ]
617}
618
619fn health_metric(
620    key: impl Into<String>,
621    name: impl Into<String>,
622    description: impl Into<String>,
623    range: Option<&str>,
624    interpretation: impl Into<String>,
625) -> (String, MetaMetric) {
626    (key.into(), metric(name, description, range, interpretation))
627}
628
629fn metric(
630    name: impl Into<String>,
631    description: impl Into<String>,
632    range: Option<&str>,
633    interpretation: impl Into<String>,
634) -> MetaMetric {
635    MetaMetric {
636        name: Some(name.into()),
637        description: Some(description.into()),
638        range: range.map(str::to_string),
639        interpretation: Some(interpretation.into()),
640    }
641}
642
643fn report_rule_docs_url(docs_path: &str) -> String {
644    format!("https://docs.fallow.tools/{docs_path}")
645}
646
647#[cfg(test)]
648mod tests {
649    use super::*;
650
651    #[test]
652    fn dupes_meta_uses_output_contract_shape() {
653        let meta = dupes_meta();
654        assert_eq!(meta.docs.as_deref(), Some(DUPES_DOCS));
655        assert!(meta.field_definitions.contains_key("actions[]"));
656        assert!(meta.metrics.contains_key("duplication_percentage"));
657        assert!(
658            meta.metrics
659                .contains_key("clone_groups_below_min_occurrences")
660        );
661    }
662
663    #[test]
664    fn health_meta_uses_output_contract_shape() {
665        let meta = health_meta();
666        assert_eq!(meta.docs.as_deref(), Some(HEALTH_DOCS));
667        assert!(meta.field_definitions.contains_key("actions[]"));
668        assert!(meta.metrics.contains_key("cyclomatic"));
669        assert!(meta.metrics.contains_key("health_score"));
670        assert!(meta.metrics.contains_key("max_render_fan_in"));
671        assert!(meta.metrics.contains_key("percent_dead_in_production"));
672        assert!(meta.metrics.contains_key("styling_health.score"));
673        assert!(
674            meta.metrics
675                .contains_key("styling_health.penalties.duplication")
676        );
677        assert!(
678            meta.metrics
679                .contains_key("styling_health.penalties.structural")
680        );
681    }
682
683    #[test]
684    fn security_meta_uses_output_contract_shape() {
685        let meta = security_meta([SecurityRuleMeta {
686            id: "security/example",
687            name: "Example",
688            description: "Example security candidate.",
689            docs_path: "cli/security",
690        }]);
691        assert_eq!(meta.docs.as_deref(), Some(SECURITY_DOCS));
692        assert!(meta.field_definitions.contains_key("security_findings[]"));
693        assert!(meta.metrics.is_empty());
694        assert_eq!(
695            meta.rules["security/example"].docs.as_deref(),
696            Some("https://docs.fallow.tools/cli/security")
697        );
698    }
699
700    #[test]
701    fn coverage_setup_meta_uses_output_contract_shape() {
702        let meta = coverage_setup_meta();
703        assert_eq!(meta["docs_url"], COVERAGE_SETUP_DOCS);
704        assert!(meta["field_definitions"]["members[]"].is_string());
705        assert!(meta["enums"]["runtime_targets"].is_array());
706        assert!(meta["warnings"]["Package manager was not detected"].is_string());
707    }
708
709    #[test]
710    fn coverage_analyze_meta_uses_output_contract_shape() {
711        let meta = coverage_analyze_meta();
712        assert_eq!(meta["docs_url"], COVERAGE_ANALYZE_DOCS);
713        assert!(meta["field_definitions"]["runtime_coverage.findings[].stable_id"].is_string());
714        assert!(meta["enums"]["action_type"].is_array());
715        assert!(meta["warnings"]["cloud_functions_unmatched"].is_string());
716    }
717}