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://fallow.tools/docs/cli/dupes/";
10
11/// Docs URL for the runtime coverage setup command's agent-readable JSON.
12pub const COVERAGE_SETUP_DOCS: &str = "https://fallow.tools/docs/cli/coverage/#agent-readable-json";
13
14/// Docs URL for `fallow coverage analyze --format json --explain`.
15pub const COVERAGE_ANALYZE_DOCS: &str = "https://fallow.tools/docs/cli/coverage/#analyze";
16
17/// Docs URL for the health command.
18pub const HEALTH_DOCS: &str = "https://fallow.tools/docs/cli/health/";
19
20/// Docs URL for the security command.
21pub const SECURITY_DOCS: &str = "https://fallow.tools/docs/cli/security/";
22
23/// Output-facing metadata for one security rule.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub struct SecurityRuleMeta<'a> {
26    /// Stable rule identifier used as the `_meta.rules` key.
27    pub id: &'a str,
28    /// Human-readable rule name.
29    pub name: &'a str,
30    /// One-line rule description.
31    pub description: &'a str,
32    /// Docs path relative to the docs site root, joined onto the base URL.
33    pub docs_path: &'a str,
34}
35
36/// Build the `_meta` object for `fallow health --format json --explain`.
37#[must_use]
38pub fn health_meta() -> Meta {
39    Meta {
40        docs: Some(HEALTH_DOCS.to_string()),
41        field_definitions: action_field_definitions(),
42        metrics: health_metrics(),
43        ..Meta::default()
44    }
45}
46
47/// Build the `_meta` object for `fallow security --format json --explain`.
48#[must_use]
49pub fn security_meta<'a>(rules: impl IntoIterator<Item = SecurityRuleMeta<'a>>) -> Meta {
50    Meta {
51        docs: Some(SECURITY_DOCS.to_string()),
52        field_definitions: security_field_definitions(),
53        metrics: BTreeMap::new(),
54        rules: rules
55            .into_iter()
56            .map(|rule| {
57                (
58                    rule.id.to_string(),
59                    MetaRule {
60                        name: Some(rule.name.to_string()),
61                        description: Some(rule.description.to_string()),
62                        docs: Some(crate::issue_contract::rule_docs_url(rule.docs_path)),
63                    },
64                )
65            })
66            .collect(),
67        ..Meta::default()
68    }
69}
70
71/// Build the `_meta` object for `fallow dupes --format json --explain`.
72#[must_use]
73pub fn dupes_meta() -> Meta {
74    Meta {
75        docs: Some(DUPES_DOCS.to_string()),
76        field_definitions: action_field_definitions(),
77        metrics: dupes_metrics(),
78        ..Meta::default()
79    }
80}
81
82fn dupes_metrics() -> BTreeMap<String, MetaMetric> {
83    dupes_size_metrics()
84        .into_iter()
85        .chain(dupes_triage_metrics())
86        .collect()
87}
88
89fn dupes_size_metrics() -> [(String, MetaMetric); 6] {
90    [
91        (
92            "duplication_percentage".to_string(),
93            metric(
94                "Duplication Percentage",
95                "Percentage of source lines that overlap at least one reported clone instance. Computed over the full analyzed file set.",
96                Some("[0, 100]"),
97                "lower is better",
98            ),
99        ),
100        (
101            "duplicated_tokens".to_string(),
102            metric(
103                "Duplicated Tokens",
104                "Number of tokens in redundant clone copies, excluding one retained copy per clone group.",
105                Some("[0, ∞)"),
106                "higher values indicate more code that can be removed by consolidating clones",
107            ),
108        ),
109        (
110            "token_count".to_string(),
111            metric(
112                "Token Count",
113                "Number of normalized source tokens in the clone group. Tokens are language-aware (keywords, identifiers, operators, punctuation). Higher token count = larger duplicate.",
114                Some("[1, ∞)"),
115                "larger clones have higher refactoring value",
116            ),
117        ),
118        (
119            "line_count".to_string(),
120            metric(
121                "Line Count",
122                "Number of source lines spanned by the clone instance. Approximation of clone size for human readability.",
123                Some("[1, ∞)"),
124                "larger clones are more impactful to deduplicate",
125            ),
126        ),
127        (
128            "spread".to_string(),
129            metric(
130                "Clone Spread",
131                "Maximum directory-tree distance between files in a clone group, or the same-file line gap measured in 250-line steps.",
132                Some("[0, ∞)"),
133                "higher values indicate clones that are harder to discover and coordinate",
134            ),
135        ),
136        (
137            "similarity".to_string(),
138            metric(
139                "Clone Similarity",
140                "Lowest all-pairs Jaccard similarity in a near-miss clone group. Omitted for exact clone groups.",
141                Some("[0, 1]"),
142                "values closer to 1 are more structurally alike",
143            ),
144        ),
145    ]
146}
147
148fn dupes_triage_metrics() -> [(String, MetaMetric); 5] {
149    [
150        (
151            "clone_groups".to_string(),
152            metric(
153                "Clone Groups",
154                "A set of code fragments with identical or near-identical normalized token sequences. Each group has 2+ instances across different locations.",
155                None,
156                "each group is a single refactoring opportunity",
157            ),
158        ),
159        (
160            "clone_groups_below_min_occurrences".to_string(),
161            metric(
162                "Clone Groups Below minOccurrences",
163                "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`.",
164                Some("[0, ∞)"),
165                "high values suggest noisy pair-only duplication; lower `minOccurrences` to inspect",
166            ),
167        ),
168        (
169            "clone_groups_ignored".to_string(),
170            metric(
171                "Ignored Clone Groups",
172                "Number of clone groups hidden by `duplicates.ignoredClones` in this run.",
173                Some("[0, ∞)"),
174                "nonzero values show reviewed clone groups omitted from the report",
175            ),
176        ),
177        (
178            "near_candidates_skipped".to_string(),
179            metric(
180                "Skipped Near Candidates",
181                "Number of near-miss candidate comparisons skipped by bounded-work limits.",
182                Some("[0, ∞)"),
183                "nonzero values mean near-miss detection intentionally limited candidate work",
184            ),
185        ),
186        (
187            "clone_families".to_string(),
188            metric(
189                "Clone Families",
190                "Groups of clone groups that share the same set of files. Indicates systematic duplication patterns (e.g., mirrored directory structures).",
191                None,
192                "families suggest extract-module refactoring opportunities",
193            ),
194        ),
195    ]
196}
197
198/// Build the `_meta` object for `fallow coverage setup --json --explain`.
199#[must_use]
200pub fn coverage_setup_meta() -> Value {
201    json!({
202        "docs_url": COVERAGE_SETUP_DOCS,
203        "field_definitions": {
204            "schema_version": "Coverage setup JSON contract version. Stays at \"1\" for additive opt-in fields such as _meta.",
205            "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.",
206            "package_manager": "Detected package manager used for install and run commands, or null when no package manager signal was found.",
207            "runtime_targets": "Union of runtime targets across emitted members.",
208            "members[]": "Per-runtime-workspace setup recipes. Pure aggregator roots and build-only libraries are omitted.",
209            "members[].name": "Workspace package name from package.json, or the root directory name when package.json has no name.",
210            "members[].path": "Workspace path relative to the command root. The root package is represented as \".\".",
211            "members[].framework_detected": "Runtime framework detected for that member.",
212            "members[].package_manager": "Package manager detected for that member, or inherited from the workspace root when no member-specific signal exists.",
213            "members[].runtime_targets": "Runtime targets produced by that member.",
214            "members[].files_to_edit": "Files in that member that should receive runtime beacon setup code.",
215            "members[].snippets": "Copy-paste setup snippets for that member, with paths relative to the command root.",
216            "members[].dockerfile_snippet": "Environment snippet for file-system capture in that member's containerized Node runtime, or null when not applicable.",
217            "members[].warnings": "Actionable setup caveats discovered for that member.",
218            "config_written": "Always null for --json because JSON setup is side-effect-free and never writes configuration.",
219            "files_to_edit": "Compatibility copy of the primary member's files, with workspace prefixes when the primary member is not the root.",
220            "snippets": "Compatibility copy of the primary member's snippets, with workspace prefixes when the primary member is not the root.",
221            "dockerfile_snippet": "Environment snippet for file-system capture in containerized Node runtimes, or null when not applicable.",
222            "commands": "Package-manager commands needed to install the runtime beacon and sidecar packages.",
223            "next_steps": "Ordered setup workflow after applying the emitted snippets.",
224            "warnings": "Actionable setup caveats discovered while building the recipe."
225        },
226        "enums": {
227            "framework_detected": ["nextjs", "nestjs", "nuxt", "sveltekit", "astro", "remix", "vite", "plain_node", "unknown"],
228            "runtime_targets": ["node", "browser"],
229            "package_manager": ["npm", "pnpm", "yarn", "bun", null]
230        },
231        "warnings": {
232            "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.",
233            "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.",
234            "Package manager was not detected": "No packageManager field or known lockfile was found. Commands fall back to npm.",
235            "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."
236        }
237    })
238}
239
240/// Build the `_meta` object for `fallow coverage analyze --format json --explain`.
241#[must_use]
242pub fn coverage_analyze_meta() -> Value {
243    json!({
244        "docs_url": COVERAGE_ANALYZE_DOCS,
245        "field_definitions": {
246            "schema_version": "Standalone coverage analyze envelope version. \"2\" for the current shape.",
247            "version": "fallow CLI version that produced this output.",
248            "elapsed_ms": "Wall-clock milliseconds spent producing the report.",
249            "runtime_coverage": "Same RuntimeCoverageReport block emitted by `fallow health --runtime-coverage`.",
250            "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.",
251            "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.",
252            "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.",
253            "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.",
254            "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.",
255            "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.",
256            "runtime_coverage.findings[].evidence.static_status": "used = the function is reachable in the AST module graph; unused = it is dead by static analysis.",
257            "runtime_coverage.findings[].evidence.test_coverage": "covered = the local test suite hits the function; not_covered otherwise.",
258            "runtime_coverage.findings[].evidence.test_only_reference": "true = the function is unreachable in the production module graph but still referenced from a file production mode excludes (test, spec, story, fixture, benchmark), so it is not dead code and never earns safe_to_delete; false = both graphs were compared and no such reference exists. Omitted from the JSON entirely when the run applied no production filter or the producing surface carries no second reachability answer.",
259            "runtime_coverage.findings[].evidence.v8_tracking": "tracked = V8 observed the function during the capture window; untracked otherwise.",
260            "runtime_coverage.findings[].actions[].type": "Suggested follow-up identifier. delete-cold-code is emitted on safe_to_delete; review-runtime on review_required.",
261            "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.",
262            "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. importance ranks the risk of a change; use hot_paths[].optimization_target to rank speed work.",
263            "runtime_coverage.hot_paths[].optimization_target": "Speed-work inputs for a hot function: cost_score (invocations multiplied by the per-call cost, uncapped), cost_basis (inner_iterations when V8 block counts exist, else cognitive), cognitive, cyclomatic, line_count, and inner_iterations_per_call (peak block executions per call, block-coverage dumps only). Omitted when the hot path has no stable_id or no static counterpart. cognitive is a static proxy for the work per call, not a measurement.",
264            "runtime_coverage.warnings[].code": "Stable warning identifier. cloud_functions_unmatched flags entries dropped because no AST/static counterpart was found locally. optimization_target_unmatched counts hot paths without an optimization_target: the hot path has no stable_id, or no static function matches its stable_id."
265        },
266        "enums": {
267            "data_source": ["local", "cloud"],
268            "report_verdict": ["clean", "hot-path-touched", "cold-code-detected", "license-expired-grace", "unknown"],
269            "finding_verdict": ["safe_to_delete", "review_required", "coverage_unavailable", "low_traffic", "active", "unknown"],
270            "static_status": ["used", "unused"],
271            "test_only_reference": [true, false],
272            "test_coverage": ["covered", "not_covered"],
273            "v8_tracking": ["tracked", "untracked"],
274            "action_type": ["delete-cold-code", "review-runtime"],
275            "cost_basis": ["inner_iterations", "cognitive"]
276        },
277        "warnings": {
278            "no_runtime_data": "Cloud returned an empty runtime window. Either the period is too narrow or no traces have been ingested yet.",
279            "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."
280        }
281    })
282}
283
284fn action_field_definitions() -> BTreeMap<String, String> {
285    BTreeMap::from([
286        (
287            "actions[]".to_string(),
288            ACTIONS_FIELD_DEFINITION.to_string(),
289        ),
290        (
291            "actions[].auto_fixable".to_string(),
292            ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION.to_string(),
293        ),
294    ])
295}
296
297fn security_field_definitions() -> BTreeMap<String, String> {
298    BTreeMap::from([
299        (
300            "version".to_string(),
301            "fallow CLI version that produced this output.".to_string(),
302        ),
303        (
304            "elapsed_ms".to_string(),
305            "Wall-clock milliseconds spent producing the security report.".to_string(),
306        ),
307        (
308            "config".to_string(),
309            "Privacy-safe config context relevant to security candidate generation.".to_string(),
310        ),
311        (
312            "config.rules.*.configured".to_string(),
313            "Severity from resolved config before the security command forced default-off rules on."
314                .to_string(),
315        ),
316        (
317            "config.rules.*.effective".to_string(),
318            "Severity used for this security command run.".to_string(),
319        ),
320        (
321            "config.categories_include".to_string(),
322            "Configured security category include list. null means unset, [] means explicitly empty."
323                .to_string(),
324        ),
325        (
326            "config.categories_exclude".to_string(),
327            "Configured security category exclude list. null means unset, [] means explicitly empty."
328                .to_string(),
329        ),
330        (
331            "security_findings[]".to_string(),
332            "Unverified security candidates for downstream human or agent verification.".to_string(),
333        ),
334        (
335            "summary.security_findings".to_string(),
336            "Number of security candidates after all filters, gates, and scopes.".to_string(),
337        ),
338        (
339            "summary.by_severity".to_string(),
340            "Fixed high, medium, and low severity counts for summary JSON.".to_string(),
341        ),
342        (
343            "summary.by_category".to_string(),
344            "Candidate counts by catalogue category, or by kind for uncategorized findings."
345                .to_string(),
346        ),
347        (
348            "summary.by_reachability".to_string(),
349            "Fixed reachability and source-backed ranking-signal counts for summary JSON."
350                .to_string(),
351        ),
352        (
353            "summary.by_runtime_state".to_string(),
354            "Fixed production-runtime coverage state counts for summary JSON.".to_string(),
355        ),
356        (
357            "unresolved_edge_files".to_string(),
358            "Number of client files whose import cone contains dynamic edges the graph could not follow."
359                .to_string(),
360        ),
361        (
362            "unresolved_callee_sites".to_string(),
363            "Number of sink-shaped nodes whose callee could not be flattened to a static path."
364                .to_string(),
365        ),
366    ])
367}
368
369fn health_metrics() -> BTreeMap<String, MetaMetric> {
370    let mut metrics = BTreeMap::new();
371    metrics.extend(health_complexity_metrics());
372    metrics.extend(health_population_metrics());
373    metrics.extend(health_churn_and_target_metrics());
374    metrics.extend(health_ownership_metrics());
375    metrics.extend(health_runtime_metrics());
376    metrics.extend(health_styling_metrics());
377    metrics
378}
379
380fn health_population_metrics() -> [(String, MetaMetric); 6] {
381    [
382        health_metric(
383            "avg_cyclomatic",
384            "Average Cyclomatic Complexity",
385            "Mean over authored function, module-scope, and template units before finding filters. Divide the sum of cyclomatic_population group sums by the sum of their counts, rounded to one decimal.",
386            Some("[0, infinity)"),
387            "zero for an empty population; lower is better",
388        ),
389        health_metric(
390            "p90_cyclomatic",
391            "P90 Cyclomatic Complexity",
392            "Nearest-rank 90th percentile over the same units as avg_cyclomatic, including module scopes and templates.",
393            Some("[0, infinity)"),
394            "zero for an empty population; lower is better",
395        ),
396        health_metric(
397            "critical_complexity_pct",
398            "Critical Cyclomatic Share",
399            "Percentage of the cyclomatic unit population at or above the critical threshold, including module scopes and templates.",
400            Some("[0, 100]"),
401            "absent for an empty population; lower is better",
402        ),
403        health_metric(
404            "cyclomatic_population.count",
405            "Cyclomatic Population Count",
406            "Unit count in each disjoint functions, modules, or templates group. Modules contribute to aggregate metrics without producing function findings.",
407            Some("[0, infinity)"),
408            "sum the three counts to obtain the distribution denominator",
409        ),
410        health_metric(
411            "cyclomatic_population.sum",
412            "Cyclomatic Population Sum",
413            "Sum of cyclomatic values in each functions, modules, or templates group before rounding and threshold filtering.",
414            Some("[0, infinity)"),
415            "sum the three groups to obtain the mean numerator",
416        ),
417        health_metric(
418            "cyclomatic_population.max",
419            "Cyclomatic Population Maximum",
420            "Highest cyclomatic value within each functions, modules, or templates group; null when that group has no units.",
421            Some("[1, infinity) or null"),
422            "identifies which kind of unit drives the tail; module units remain aggregate-only",
423        ),
424    ]
425}
426
427fn health_complexity_metrics() -> [(String, MetaMetric); 11] {
428    [
429        health_metric(
430            "cyclomatic",
431            "Cyclomatic Complexity",
432            "McCabe cyclomatic complexity: 1 + number of decision points.",
433            Some("[1, infinity)"),
434            "lower is better; default threshold: 20",
435        ),
436        health_metric(
437            "cognitive",
438            "Cognitive Complexity",
439            "Cognitive complexity penalizes nesting depth and non-linear control flow.",
440            Some("[0, infinity)"),
441            "lower is better; default threshold: 15",
442        ),
443        health_metric(
444            "line_count",
445            "Function Line Count",
446            "Number of lines in the function body.",
447            Some("[1, infinity)"),
448            "context-dependent; long functions may need splitting",
449        ),
450        health_metric(
451            "lines",
452            "File Line Count",
453            "Total lines of code in the file.",
454            Some("[1, infinity)"),
455            "context-dependent; large files may benefit from splitting",
456        ),
457        health_metric(
458            "maintainability_index",
459            "Maintainability Index",
460            "Composite file score combining complexity density, dead code ratio, and coupling.",
461            Some("[0, 100]"),
462            "higher is better",
463        ),
464        health_metric(
465            "complexity_density",
466            "Complexity Density",
467            "Total cyclomatic complexity divided by lines of code.",
468            Some("[0, infinity)"),
469            "lower is better; >1.0 indicates very dense complexity",
470        ),
471        health_metric(
472            "dead_code_ratio",
473            "Dead Code Ratio",
474            "Fraction of value exports with zero references across the project.",
475            Some("[0, 1]"),
476            "lower is better; 0 means all exports are used",
477        ),
478        health_metric(
479            "fan_in",
480            "Fan-in (Importers)",
481            "Number of files that import this file.",
482            Some("[0, infinity)"),
483            "context-dependent; high fan-in files need careful review",
484        ),
485        health_metric(
486            "fan_out",
487            "Fan-out (Imports)",
488            "Number of files this file directly imports.",
489            Some("[0, infinity)"),
490            "lower is better; high fan-out indicates coupling",
491        ),
492        health_metric(
493            "max_render_fan_in",
494            "Render Fan-in (Blast Radius)",
495            "Highest distinct-parent render count across React or Preact components.",
496            Some("[0, infinity)"),
497            "descriptive only; high values mean broad edit ripple",
498        ),
499        health_metric(
500            "crap_max",
501            "Untested Complexity Risk (CRAP)",
502            "Highest Change Risk Anti-Patterns score from complexity and coverage evidence.",
503            Some("[1, infinity)"),
504            "lower is better; high values indicate complex untested code",
505        ),
506    ]
507}
508
509fn health_churn_and_target_metrics() -> [(String, MetaMetric); 10] {
510    [
511        health_metric(
512            "score",
513            "Hotspot Score",
514            "Normalized churn multiplied by normalized complexity.",
515            Some("[0, 100]"),
516            "higher means riskier; prioritize refactoring high-score files",
517        ),
518        health_metric(
519            "weighted_commits",
520            "Weighted Commits",
521            "Recency-weighted commit count using exponential decay.",
522            Some("[0, infinity)"),
523            "higher means more recent churn activity",
524        ),
525        health_metric(
526            "trend",
527            "Churn Trend",
528            "Compares recent vs older commit frequency within the analysis window.",
529            None,
530            "accelerating files need attention; cooling files are stabilizing",
531        ),
532        health_metric(
533            "priority",
534            "Refactoring Priority",
535            "Weighted refactoring score using complexity, hotspots, dead code, fan-in, and fan-out.",
536            Some("[0, 100]"),
537            "higher means more urgent to refactor",
538        ),
539        health_metric(
540            "efficiency",
541            "Efficiency Score",
542            "Priority divided by effort estimate.",
543            Some("[0, 100]"),
544            "higher means better quick-win value",
545        ),
546        health_metric(
547            "effort",
548            "Effort Estimate",
549            "Heuristic effort estimate based on file size, function count, and fan-in.",
550            None,
551            "low means quick win, high needs planning and coordination",
552        ),
553        health_metric(
554            "confidence",
555            "Confidence Level",
556            "Reliability of the recommendation based on data source.",
557            None,
558            "high means act on it; medium or low means verify context",
559        ),
560        health_metric(
561            "health_score",
562            "Health Score",
563            "Project-level aggregate score computed from vital signs and issue signals.",
564            Some("[0, 100]"),
565            "higher is better; missing metrics are not penalized",
566        ),
567        health_metric(
568            "health_score.formula_version",
569            "Health Score Formula Version",
570            "Version of the health-scoring rubric used to produce the current score.",
571            Some("[1, infinity)"),
572            "compare score values only when both formula versions are known and equal",
573        ),
574        health_metric(
575            "health_trend.compared_to.score_formula_version",
576            "Baseline Health Score Formula Version",
577            "Formula version saved with the historical score; absent on legacy or unscored snapshots.",
578            Some("[1, infinity)"),
579            "the score delta is omitted when formula versions are unknown or different; available raw metric trends remain comparable",
580        ),
581    ]
582}
583
584fn health_ownership_metrics() -> [(String, MetaMetric); 6] {
585    [
586        health_metric(
587            "bus_factor",
588            "Bus Factor",
589            "Minimum number of contributors who account for most recent weighted commits.",
590            Some("[1, infinity)"),
591            "lower is higher knowledge-loss risk",
592        ),
593        health_metric(
594            "contributor_count",
595            "Contributor Count",
596            "Number of distinct authors who touched this file in the analysis window.",
597            Some("[0, infinity)"),
598            "higher generally indicates broader knowledge spread",
599        ),
600        health_metric(
601            "share",
602            "Contributor Share",
603            "Recency-weighted share of total weighted commits attributed to a contributor.",
604            Some("[0, 1]"),
605            "share close to 1.0 indicates ownership concentration",
606        ),
607        health_metric(
608            "stale_days",
609            "Stale Days",
610            "Days since this contributor last touched the file.",
611            Some("[0, infinity)"),
612            "high stale days can indicate ownership drift",
613        ),
614        health_metric(
615            "drift",
616            "Ownership Drift",
617            "Whether original authorship and current contribution ownership have diverged.",
618            None,
619            "true means current review ownership may differ from original ownership",
620        ),
621        health_metric(
622            "unowned",
623            "Unowned (Tristate)",
624            "Whether CODEOWNERS exists but has no matching owner for this file.",
625            None,
626            "true on a hotspot is a review-bottleneck risk",
627        ),
628    ]
629}
630
631fn health_runtime_metrics() -> [(String, MetaMetric); 7] {
632    [
633        health_metric(
634            "runtime_coverage_verdict",
635            "Runtime Coverage Verdict",
636            "Overall verdict across runtime-coverage findings.",
637            None,
638            "cold-code-detected is the primary standalone cleanup signal",
639        ),
640        health_metric(
641            "runtime_coverage_state",
642            "Runtime Coverage State",
643            "Per-function runtime observation state.",
644            None,
645            "never-called with static unused is the highest-confidence delete signal",
646        ),
647        health_metric(
648            "runtime_coverage_confidence",
649            "Runtime Coverage Confidence",
650            "Confidence in a runtime-coverage finding.",
651            None,
652            "high means act on it; medium or low means verify context",
653        ),
654        health_metric(
655            "production_invocations",
656            "Production Invocations",
657            "Observed invocation count for the function over the collected coverage window.",
658            Some("[0, infinity)"),
659            "0 plus tracked means cold path; high means active path",
660        ),
661        health_metric(
662            "percent_dead_in_production",
663            "Percent Dead in Production",
664            "Fraction of tracked functions with zero observed invocations, multiplied by 100.",
665            Some("[0, 100]"),
666            "lower is better",
667        ),
668        health_metric(
669            "optimization_cost_score",
670            "Optimization Cost Score",
671            "Invocations multiplied by the per-call cost, on runtime_coverage.hot_paths[].optimization_target. The per-call cost is the peak block executions per call from V8 block coverage (cost_basis inner_iterations), or static cognitive complexity with a minimum of 1 when the function has no usable block counts (cost_basis cognitive).",
672            Some("[0, infinity)"),
673            "higher means a larger speed gain; compare it only between hot paths with the same cost_basis. importance ranks the risk of a change, not the speed gain",
674        ),
675        health_metric(
676            "inner_iterations_per_call",
677            "Inner Iterations per Call",
678            "Peak executions of one block inside a hot function per call, from V8 block coverage.",
679            Some("[1, infinity)"),
680            "1.0 means no block ran more than once per call; 3.0 means a loop body ran 3 times per call. Calls to other functions do not change the value",
681        ),
682    ]
683}
684
685fn health_styling_metrics() -> [(String, MetaMetric); 11] {
686    [
687        health_metric(
688            "styling_health.score",
689            "Styling Health Score",
690            "CSS/styling-axis aggregate score computed from the styling penalty rubric. Present only under --css.",
691            Some("[0, 100]"),
692            "higher is better; missing metrics are not penalized",
693        ),
694        health_metric(
695            "styling_health.formula_version",
696            "Styling Health Formula Version",
697            "Version of the styling-health scoring rubric used to produce the score. Present only under --css.",
698            Some("[1, infinity)"),
699            "bump signals a rubric change; compare scores only within the same version",
700        ),
701        health_metric(
702            "styling_health.penalties.duplication",
703            "Styling Duplication Penalty",
704            "Points deducted for copy-paste declaration blocks, scaled by the share of declarations removable via consolidation. Present only under --css.",
705            Some("[0, 20]"),
706            "lower is better; 0 means no removable duplicate blocks",
707        ),
708        health_metric(
709            "styling_health.penalties.dead_surface",
710            "Styling Dead-Surface Penalty",
711            "Points deducted for unreferenced classes, unused tokens, at-rules, and font-faces, normalized per stylesheet. Present only under --css.",
712            Some("[0, 20]"),
713            "lower is better; 0 means no dead styling surface",
714        ),
715        health_metric(
716            "styling_health.penalties.broken_references",
717            "Styling Broken-References Penalty",
718            "Points deducted for markup classes one edit from a defined class and animations referencing undefined keyframes. Present only under --css.",
719            Some("[0, 15]"),
720            "lower is better; 0 means no broken references",
721        ),
722        health_metric(
723            "styling_health.penalties.token_erosion",
724            "Styling Token-Erosion Penalty",
725            "Points deducted for mixing font-size units past a healthy baseline and Tailwind arbitrary-value bypasses. Present only under --css.",
726            Some("[0, 10]"),
727            "lower is better; 0 means a single source of truth for the scale",
728        ),
729        health_metric(
730            "styling_health.penalties.structural",
731            "Styling Structural Penalty",
732            "Points deducted for !important density above a healthy floor and deep style-rule nesting. Present only under --css.",
733            Some("[0, 10]"),
734            "lower is better; 0 means no structural smells",
735        ),
736        health_metric(
737            "css_analytics.summary.near_duplicate_theme_tokens",
738            "Near-Duplicate Theme Tokens",
739            "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.",
740            Some("[0, infinity)"),
741            "0 means no near-duplicate token candidates were found",
742        ),
743        health_metric(
744            "css_analytics.summary.near_duplicate_css_in_js_tokens",
745            "Near-Duplicate CSS-in-JS Tokens",
746            "Count of CSS-in-JS design tokens whose comparable values are close to another project token. Present only in deep CSS analysis.",
747            Some("[0, infinity)"),
748            "0 means no near-duplicate CSS-in-JS token candidates were found",
749        ),
750        health_metric(
751            "styling_findings[].blast_radius",
752            "Styling Finding Blast Radius",
753            "Static lower-bound count of known consumers affected by a styling finding. Omitted when the family has no reliable blast-radius model.",
754            Some("[0, infinity)"),
755            "0 means no static consumers were found; omitted means unknown",
756        ),
757        health_metric(
758            "styling_findings[].nearest_token.distance",
759            "Nearest Styling Token Distance",
760            "Distance between a token-drift finding and its nearest comparable token. Units depend on the token namespace.",
761            Some("(0, infinity)"),
762            "lower means closer; compare only within the same token namespace",
763        ),
764    ]
765}
766
767fn health_metric(
768    key: impl Into<String>,
769    name: impl Into<String>,
770    description: impl Into<String>,
771    range: Option<&str>,
772    interpretation: impl Into<String>,
773) -> (String, MetaMetric) {
774    (key.into(), metric(name, description, range, interpretation))
775}
776
777fn metric(
778    name: impl Into<String>,
779    description: impl Into<String>,
780    range: Option<&str>,
781    interpretation: impl Into<String>,
782) -> MetaMetric {
783    MetaMetric {
784        name: Some(name.into()),
785        description: Some(description.into()),
786        range: range.map(str::to_string),
787        interpretation: Some(interpretation.into()),
788    }
789}
790
791#[cfg(test)]
792mod tests {
793    use super::*;
794
795    #[test]
796    fn dupes_meta_uses_output_contract_shape() {
797        let meta = dupes_meta();
798        assert_eq!(meta.docs.as_deref(), Some(DUPES_DOCS));
799        assert!(meta.field_definitions.contains_key("actions[]"));
800        assert!(meta.metrics.contains_key("duplication_percentage"));
801        assert!(
802            meta.metrics
803                .contains_key("clone_groups_below_min_occurrences")
804        );
805        for key in [
806            "duplicated_tokens",
807            "spread",
808            "similarity",
809            "clone_groups_ignored",
810            "near_candidates_skipped",
811        ] {
812            let metric = meta.metrics.get(key).expect("duplication metric");
813            assert!(metric.range.is_some(), "{key} must document its range");
814            assert!(
815                metric.interpretation.is_some(),
816                "{key} must document its interpretation"
817            );
818        }
819    }
820
821    #[test]
822    fn health_meta_uses_output_contract_shape() {
823        let meta = health_meta();
824        assert_eq!(meta.docs.as_deref(), Some(HEALTH_DOCS));
825        assert!(meta.field_definitions.contains_key("actions[]"));
826        assert!(meta.metrics.contains_key("cyclomatic"));
827        assert!(meta.metrics.contains_key("health_score"));
828        assert!(meta.metrics.contains_key("health_score.formula_version"));
829        assert!(
830            meta.metrics
831                .contains_key("health_trend.compared_to.score_formula_version")
832        );
833        assert!(meta.metrics.contains_key("max_render_fan_in"));
834        assert!(meta.metrics.contains_key("percent_dead_in_production"));
835        assert!(meta.metrics.contains_key("styling_health.score"));
836        assert!(
837            meta.metrics
838                .contains_key("styling_health.penalties.duplication")
839        );
840        assert!(
841            meta.metrics
842                .contains_key("styling_health.penalties.structural")
843        );
844    }
845
846    #[test]
847    fn security_meta_uses_output_contract_shape() {
848        let meta = security_meta([SecurityRuleMeta {
849            id: "security/example",
850            name: "Example",
851            description: "Example security candidate.",
852            docs_path: "cli/security",
853        }]);
854        assert_eq!(meta.docs.as_deref(), Some(SECURITY_DOCS));
855        assert!(meta.field_definitions.contains_key("security_findings[]"));
856        assert!(meta.metrics.is_empty());
857        assert_eq!(
858            meta.rules["security/example"].docs.as_deref(),
859            Some("https://fallow.tools/docs/cli/security/")
860        );
861    }
862
863    #[test]
864    fn coverage_setup_meta_uses_output_contract_shape() {
865        let meta = coverage_setup_meta();
866        assert_eq!(meta["docs_url"], COVERAGE_SETUP_DOCS);
867        assert!(meta["field_definitions"]["members[]"].is_string());
868        assert!(meta["enums"]["runtime_targets"].is_array());
869        assert!(meta["warnings"]["Package manager was not detected"].is_string());
870    }
871
872    #[test]
873    fn coverage_analyze_meta_uses_output_contract_shape() {
874        let meta = coverage_analyze_meta();
875        assert_eq!(meta["docs_url"], COVERAGE_ANALYZE_DOCS);
876        assert!(meta["field_definitions"]["runtime_coverage.findings[].stable_id"].is_string());
877        assert!(meta["enums"]["action_type"].is_array());
878        assert!(meta["warnings"]["cloud_functions_unmatched"].is_string());
879    }
880}