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
8pub const DUPES_DOCS: &str = "https://docs.fallow.tools/cli/dupes";
10
11pub const COVERAGE_SETUP_DOCS: &str = "https://docs.fallow.tools/cli/coverage#agent-readable-json";
13
14pub const COVERAGE_ANALYZE_DOCS: &str = "https://docs.fallow.tools/cli/coverage#analyze";
16
17pub const HEALTH_DOCS: &str = "https://docs.fallow.tools/cli/health";
19
20pub const SECURITY_DOCS: &str = "https://docs.fallow.tools/cli/security";
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub struct SecurityRuleMeta<'a> {
26 pub id: &'a str,
28 pub name: &'a str,
30 pub description: &'a str,
32 pub docs_path: &'a str,
34}
35
36#[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#[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(report_rule_docs_url(rule.docs_path)),
63 },
64 )
65 })
66 .collect(),
67 ..Meta::default()
68 }
69}
70
71#[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#[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#[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.",
263 "runtime_coverage.warnings[].code": "Stable warning identifier. cloud_functions_unmatched flags entries dropped because no AST/static counterpart was found locally."
264 },
265 "enums": {
266 "data_source": ["local", "cloud"],
267 "report_verdict": ["clean", "hot-path-touched", "cold-code-detected", "license-expired-grace", "unknown"],
268 "finding_verdict": ["safe_to_delete", "review_required", "coverage_unavailable", "low_traffic", "active", "unknown"],
269 "static_status": ["used", "unused"],
270 "test_only_reference": [true, false],
271 "test_coverage": ["covered", "not_covered"],
272 "v8_tracking": ["tracked", "untracked"],
273 "action_type": ["delete-cold-code", "review-runtime"]
274 },
275 "warnings": {
276 "no_runtime_data": "Cloud returned an empty runtime window. Either the period is too narrow or no traces have been ingested yet.",
277 "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."
278 }
279 })
280}
281
282fn action_field_definitions() -> BTreeMap<String, String> {
283 BTreeMap::from([
284 (
285 "actions[]".to_string(),
286 ACTIONS_FIELD_DEFINITION.to_string(),
287 ),
288 (
289 "actions[].auto_fixable".to_string(),
290 ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION.to_string(),
291 ),
292 ])
293}
294
295fn security_field_definitions() -> BTreeMap<String, String> {
296 BTreeMap::from([
297 (
298 "version".to_string(),
299 "fallow CLI version that produced this output.".to_string(),
300 ),
301 (
302 "elapsed_ms".to_string(),
303 "Wall-clock milliseconds spent producing the security report.".to_string(),
304 ),
305 (
306 "config".to_string(),
307 "Privacy-safe config context relevant to security candidate generation.".to_string(),
308 ),
309 (
310 "config.rules.*.configured".to_string(),
311 "Severity from resolved config before the security command forced default-off rules on."
312 .to_string(),
313 ),
314 (
315 "config.rules.*.effective".to_string(),
316 "Severity used for this security command run.".to_string(),
317 ),
318 (
319 "config.categories_include".to_string(),
320 "Configured security category include list. null means unset, [] means explicitly empty."
321 .to_string(),
322 ),
323 (
324 "config.categories_exclude".to_string(),
325 "Configured security category exclude list. null means unset, [] means explicitly empty."
326 .to_string(),
327 ),
328 (
329 "security_findings[]".to_string(),
330 "Unverified security candidates for downstream human or agent verification.".to_string(),
331 ),
332 (
333 "summary.security_findings".to_string(),
334 "Number of security candidates after all filters, gates, and scopes.".to_string(),
335 ),
336 (
337 "summary.by_severity".to_string(),
338 "Fixed high, medium, and low severity counts for summary JSON.".to_string(),
339 ),
340 (
341 "summary.by_category".to_string(),
342 "Candidate counts by catalogue category, or by kind for uncategorized findings."
343 .to_string(),
344 ),
345 (
346 "summary.by_reachability".to_string(),
347 "Fixed reachability and source-backed ranking-signal counts for summary JSON."
348 .to_string(),
349 ),
350 (
351 "summary.by_runtime_state".to_string(),
352 "Fixed production-runtime coverage state counts for summary JSON.".to_string(),
353 ),
354 (
355 "unresolved_edge_files".to_string(),
356 "Number of client files whose import cone contains dynamic edges the graph could not follow."
357 .to_string(),
358 ),
359 (
360 "unresolved_callee_sites".to_string(),
361 "Number of sink-shaped nodes whose callee could not be flattened to a static path."
362 .to_string(),
363 ),
364 ])
365}
366
367fn health_metrics() -> BTreeMap<String, MetaMetric> {
368 let mut metrics = BTreeMap::new();
369 metrics.extend(health_complexity_metrics());
370 metrics.extend(health_population_metrics());
371 metrics.extend(health_churn_and_target_metrics());
372 metrics.extend(health_ownership_metrics());
373 metrics.extend(health_runtime_metrics());
374 metrics.extend(health_styling_metrics());
375 metrics
376}
377
378fn health_population_metrics() -> [(String, MetaMetric); 6] {
379 [
380 health_metric(
381 "avg_cyclomatic",
382 "Average Cyclomatic Complexity",
383 "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.",
384 Some("[0, infinity)"),
385 "zero for an empty population; lower is better",
386 ),
387 health_metric(
388 "p90_cyclomatic",
389 "P90 Cyclomatic Complexity",
390 "Nearest-rank 90th percentile over the same units as avg_cyclomatic, including module scopes and templates.",
391 Some("[0, infinity)"),
392 "zero for an empty population; lower is better",
393 ),
394 health_metric(
395 "critical_complexity_pct",
396 "Critical Cyclomatic Share",
397 "Percentage of the cyclomatic unit population at or above the critical threshold, including module scopes and templates.",
398 Some("[0, 100]"),
399 "absent for an empty population; lower is better",
400 ),
401 health_metric(
402 "cyclomatic_population.count",
403 "Cyclomatic Population Count",
404 "Unit count in each disjoint functions, modules, or templates group. Modules contribute to aggregate metrics without producing function findings.",
405 Some("[0, infinity)"),
406 "sum the three counts to obtain the distribution denominator",
407 ),
408 health_metric(
409 "cyclomatic_population.sum",
410 "Cyclomatic Population Sum",
411 "Sum of cyclomatic values in each functions, modules, or templates group before rounding and threshold filtering.",
412 Some("[0, infinity)"),
413 "sum the three groups to obtain the mean numerator",
414 ),
415 health_metric(
416 "cyclomatic_population.max",
417 "Cyclomatic Population Maximum",
418 "Highest cyclomatic value within each functions, modules, or templates group; null when that group has no units.",
419 Some("[1, infinity) or null"),
420 "identifies which kind of unit drives the tail; module units remain aggregate-only",
421 ),
422 ]
423}
424
425fn health_complexity_metrics() -> [(String, MetaMetric); 11] {
426 [
427 health_metric(
428 "cyclomatic",
429 "Cyclomatic Complexity",
430 "McCabe cyclomatic complexity: 1 + number of decision points.",
431 Some("[1, infinity)"),
432 "lower is better; default threshold: 20",
433 ),
434 health_metric(
435 "cognitive",
436 "Cognitive Complexity",
437 "Cognitive complexity penalizes nesting depth and non-linear control flow.",
438 Some("[0, infinity)"),
439 "lower is better; default threshold: 15",
440 ),
441 health_metric(
442 "line_count",
443 "Function Line Count",
444 "Number of lines in the function body.",
445 Some("[1, infinity)"),
446 "context-dependent; long functions may need splitting",
447 ),
448 health_metric(
449 "lines",
450 "File Line Count",
451 "Total lines of code in the file.",
452 Some("[1, infinity)"),
453 "context-dependent; large files may benefit from splitting",
454 ),
455 health_metric(
456 "maintainability_index",
457 "Maintainability Index",
458 "Composite file score combining complexity density, dead code ratio, and coupling.",
459 Some("[0, 100]"),
460 "higher is better",
461 ),
462 health_metric(
463 "complexity_density",
464 "Complexity Density",
465 "Total cyclomatic complexity divided by lines of code.",
466 Some("[0, infinity)"),
467 "lower is better; >1.0 indicates very dense complexity",
468 ),
469 health_metric(
470 "dead_code_ratio",
471 "Dead Code Ratio",
472 "Fraction of value exports with zero references across the project.",
473 Some("[0, 1]"),
474 "lower is better; 0 means all exports are used",
475 ),
476 health_metric(
477 "fan_in",
478 "Fan-in (Importers)",
479 "Number of files that import this file.",
480 Some("[0, infinity)"),
481 "context-dependent; high fan-in files need careful review",
482 ),
483 health_metric(
484 "fan_out",
485 "Fan-out (Imports)",
486 "Number of files this file directly imports.",
487 Some("[0, infinity)"),
488 "lower is better; high fan-out indicates coupling",
489 ),
490 health_metric(
491 "max_render_fan_in",
492 "Render Fan-in (Blast Radius)",
493 "Highest distinct-parent render count across React or Preact components.",
494 Some("[0, infinity)"),
495 "descriptive only; high values mean broad edit ripple",
496 ),
497 health_metric(
498 "crap_max",
499 "Untested Complexity Risk (CRAP)",
500 "Highest Change Risk Anti-Patterns score from complexity and coverage evidence.",
501 Some("[1, infinity)"),
502 "lower is better; high values indicate complex untested code",
503 ),
504 ]
505}
506
507fn health_churn_and_target_metrics() -> [(String, MetaMetric); 8] {
508 [
509 health_metric(
510 "score",
511 "Hotspot Score",
512 "Normalized churn multiplied by normalized complexity.",
513 Some("[0, 100]"),
514 "higher means riskier; prioritize refactoring high-score files",
515 ),
516 health_metric(
517 "weighted_commits",
518 "Weighted Commits",
519 "Recency-weighted commit count using exponential decay.",
520 Some("[0, infinity)"),
521 "higher means more recent churn activity",
522 ),
523 health_metric(
524 "trend",
525 "Churn Trend",
526 "Compares recent vs older commit frequency within the analysis window.",
527 None,
528 "accelerating files need attention; cooling files are stabilizing",
529 ),
530 health_metric(
531 "priority",
532 "Refactoring Priority",
533 "Weighted refactoring score using complexity, hotspots, dead code, fan-in, and fan-out.",
534 Some("[0, 100]"),
535 "higher means more urgent to refactor",
536 ),
537 health_metric(
538 "efficiency",
539 "Efficiency Score",
540 "Priority divided by effort estimate.",
541 Some("[0, 100]"),
542 "higher means better quick-win value",
543 ),
544 health_metric(
545 "effort",
546 "Effort Estimate",
547 "Heuristic effort estimate based on file size, function count, and fan-in.",
548 None,
549 "low means quick win, high needs planning and coordination",
550 ),
551 health_metric(
552 "confidence",
553 "Confidence Level",
554 "Reliability of the recommendation based on data source.",
555 None,
556 "high means act on it; medium or low means verify context",
557 ),
558 health_metric(
559 "health_score",
560 "Health Score",
561 "Project-level aggregate score computed from vital signs and issue signals.",
562 Some("[0, 100]"),
563 "higher is better; missing metrics are not penalized",
564 ),
565 ]
566}
567
568fn health_ownership_metrics() -> [(String, MetaMetric); 6] {
569 [
570 health_metric(
571 "bus_factor",
572 "Bus Factor",
573 "Minimum number of contributors who account for most recent weighted commits.",
574 Some("[1, infinity)"),
575 "lower is higher knowledge-loss risk",
576 ),
577 health_metric(
578 "contributor_count",
579 "Contributor Count",
580 "Number of distinct authors who touched this file in the analysis window.",
581 Some("[0, infinity)"),
582 "higher generally indicates broader knowledge spread",
583 ),
584 health_metric(
585 "share",
586 "Contributor Share",
587 "Recency-weighted share of total weighted commits attributed to a contributor.",
588 Some("[0, 1]"),
589 "share close to 1.0 indicates ownership concentration",
590 ),
591 health_metric(
592 "stale_days",
593 "Stale Days",
594 "Days since this contributor last touched the file.",
595 Some("[0, infinity)"),
596 "high stale days can indicate ownership drift",
597 ),
598 health_metric(
599 "drift",
600 "Ownership Drift",
601 "Whether original authorship and current contribution ownership have diverged.",
602 None,
603 "true means current review ownership may differ from original ownership",
604 ),
605 health_metric(
606 "unowned",
607 "Unowned (Tristate)",
608 "Whether CODEOWNERS exists but has no matching owner for this file.",
609 None,
610 "true on a hotspot is a review-bottleneck risk",
611 ),
612 ]
613}
614
615fn health_runtime_metrics() -> [(String, MetaMetric); 5] {
616 [
617 health_metric(
618 "runtime_coverage_verdict",
619 "Runtime Coverage Verdict",
620 "Overall verdict across runtime-coverage findings.",
621 None,
622 "cold-code-detected is the primary standalone cleanup signal",
623 ),
624 health_metric(
625 "runtime_coverage_state",
626 "Runtime Coverage State",
627 "Per-function runtime observation state.",
628 None,
629 "never-called with static unused is the highest-confidence delete signal",
630 ),
631 health_metric(
632 "runtime_coverage_confidence",
633 "Runtime Coverage Confidence",
634 "Confidence in a runtime-coverage finding.",
635 None,
636 "high means act on it; medium or low means verify context",
637 ),
638 health_metric(
639 "production_invocations",
640 "Production Invocations",
641 "Observed invocation count for the function over the collected coverage window.",
642 Some("[0, infinity)"),
643 "0 plus tracked means cold path; high means active path",
644 ),
645 health_metric(
646 "percent_dead_in_production",
647 "Percent Dead in Production",
648 "Fraction of tracked functions with zero observed invocations, multiplied by 100.",
649 Some("[0, 100]"),
650 "lower is better",
651 ),
652 ]
653}
654
655fn health_styling_metrics() -> [(String, MetaMetric); 11] {
656 [
657 health_metric(
658 "styling_health.score",
659 "Styling Health Score",
660 "CSS/styling-axis aggregate score computed from the styling penalty rubric. Present only under --css.",
661 Some("[0, 100]"),
662 "higher is better; missing metrics are not penalized",
663 ),
664 health_metric(
665 "styling_health.formula_version",
666 "Styling Health Formula Version",
667 "Version of the styling-health scoring rubric used to produce the score. Present only under --css.",
668 Some("[1, infinity)"),
669 "bump signals a rubric change; compare scores only within the same version",
670 ),
671 health_metric(
672 "styling_health.penalties.duplication",
673 "Styling Duplication Penalty",
674 "Points deducted for copy-paste declaration blocks, scaled by the share of declarations removable via consolidation. Present only under --css.",
675 Some("[0, 20]"),
676 "lower is better; 0 means no removable duplicate blocks",
677 ),
678 health_metric(
679 "styling_health.penalties.dead_surface",
680 "Styling Dead-Surface Penalty",
681 "Points deducted for unreferenced classes, unused tokens, at-rules, and font-faces, normalized per stylesheet. Present only under --css.",
682 Some("[0, 20]"),
683 "lower is better; 0 means no dead styling surface",
684 ),
685 health_metric(
686 "styling_health.penalties.broken_references",
687 "Styling Broken-References Penalty",
688 "Points deducted for markup classes one edit from a defined class and animations referencing undefined keyframes. Present only under --css.",
689 Some("[0, 15]"),
690 "lower is better; 0 means no broken references",
691 ),
692 health_metric(
693 "styling_health.penalties.token_erosion",
694 "Styling Token-Erosion Penalty",
695 "Points deducted for mixing font-size units past a healthy baseline and Tailwind arbitrary-value bypasses. Present only under --css.",
696 Some("[0, 10]"),
697 "lower is better; 0 means a single source of truth for the scale",
698 ),
699 health_metric(
700 "styling_health.penalties.structural",
701 "Styling Structural Penalty",
702 "Points deducted for !important density above a healthy floor and deep style-rule nesting. Present only under --css.",
703 Some("[0, 10]"),
704 "lower is better; 0 means no structural smells",
705 ),
706 health_metric(
707 "css_analytics.summary.near_duplicate_theme_tokens",
708 "Near-Duplicate Theme Tokens",
709 "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.",
710 Some("[0, infinity)"),
711 "0 means no near-duplicate token candidates were found",
712 ),
713 health_metric(
714 "css_analytics.summary.near_duplicate_css_in_js_tokens",
715 "Near-Duplicate CSS-in-JS Tokens",
716 "Count of CSS-in-JS design tokens whose comparable values are close to another project token. Present only in deep CSS analysis.",
717 Some("[0, infinity)"),
718 "0 means no near-duplicate CSS-in-JS token candidates were found",
719 ),
720 health_metric(
721 "styling_findings[].blast_radius",
722 "Styling Finding Blast Radius",
723 "Static lower-bound count of known consumers affected by a styling finding. Omitted when the family has no reliable blast-radius model.",
724 Some("[0, infinity)"),
725 "0 means no static consumers were found; omitted means unknown",
726 ),
727 health_metric(
728 "styling_findings[].nearest_token.distance",
729 "Nearest Styling Token Distance",
730 "Distance between a token-drift finding and its nearest comparable token. Units depend on the token namespace.",
731 Some("(0, infinity)"),
732 "lower means closer; compare only within the same token namespace",
733 ),
734 ]
735}
736
737fn health_metric(
738 key: impl Into<String>,
739 name: impl Into<String>,
740 description: impl Into<String>,
741 range: Option<&str>,
742 interpretation: impl Into<String>,
743) -> (String, MetaMetric) {
744 (key.into(), metric(name, description, range, interpretation))
745}
746
747fn metric(
748 name: impl Into<String>,
749 description: impl Into<String>,
750 range: Option<&str>,
751 interpretation: impl Into<String>,
752) -> MetaMetric {
753 MetaMetric {
754 name: Some(name.into()),
755 description: Some(description.into()),
756 range: range.map(str::to_string),
757 interpretation: Some(interpretation.into()),
758 }
759}
760
761fn report_rule_docs_url(docs_path: &str) -> String {
762 format!("https://docs.fallow.tools/{docs_path}")
763}
764
765#[cfg(test)]
766mod tests {
767 use super::*;
768
769 #[test]
770 fn dupes_meta_uses_output_contract_shape() {
771 let meta = dupes_meta();
772 assert_eq!(meta.docs.as_deref(), Some(DUPES_DOCS));
773 assert!(meta.field_definitions.contains_key("actions[]"));
774 assert!(meta.metrics.contains_key("duplication_percentage"));
775 assert!(
776 meta.metrics
777 .contains_key("clone_groups_below_min_occurrences")
778 );
779 for key in [
780 "duplicated_tokens",
781 "spread",
782 "similarity",
783 "clone_groups_ignored",
784 "near_candidates_skipped",
785 ] {
786 let metric = meta.metrics.get(key).expect("duplication metric");
787 assert!(metric.range.is_some(), "{key} must document its range");
788 assert!(
789 metric.interpretation.is_some(),
790 "{key} must document its interpretation"
791 );
792 }
793 }
794
795 #[test]
796 fn health_meta_uses_output_contract_shape() {
797 let meta = health_meta();
798 assert_eq!(meta.docs.as_deref(), Some(HEALTH_DOCS));
799 assert!(meta.field_definitions.contains_key("actions[]"));
800 assert!(meta.metrics.contains_key("cyclomatic"));
801 assert!(meta.metrics.contains_key("health_score"));
802 assert!(meta.metrics.contains_key("max_render_fan_in"));
803 assert!(meta.metrics.contains_key("percent_dead_in_production"));
804 assert!(meta.metrics.contains_key("styling_health.score"));
805 assert!(
806 meta.metrics
807 .contains_key("styling_health.penalties.duplication")
808 );
809 assert!(
810 meta.metrics
811 .contains_key("styling_health.penalties.structural")
812 );
813 }
814
815 #[test]
816 fn security_meta_uses_output_contract_shape() {
817 let meta = security_meta([SecurityRuleMeta {
818 id: "security/example",
819 name: "Example",
820 description: "Example security candidate.",
821 docs_path: "cli/security",
822 }]);
823 assert_eq!(meta.docs.as_deref(), Some(SECURITY_DOCS));
824 assert!(meta.field_definitions.contains_key("security_findings[]"));
825 assert!(meta.metrics.is_empty());
826 assert_eq!(
827 meta.rules["security/example"].docs.as_deref(),
828 Some("https://docs.fallow.tools/cli/security")
829 );
830 }
831
832 #[test]
833 fn coverage_setup_meta_uses_output_contract_shape() {
834 let meta = coverage_setup_meta();
835 assert_eq!(meta["docs_url"], COVERAGE_SETUP_DOCS);
836 assert!(meta["field_definitions"]["members[]"].is_string());
837 assert!(meta["enums"]["runtime_targets"].is_array());
838 assert!(meta["warnings"]["Package manager was not detected"].is_string());
839 }
840
841 #[test]
842 fn coverage_analyze_meta_uses_output_contract_shape() {
843 let meta = coverage_analyze_meta();
844 assert_eq!(meta["docs_url"], COVERAGE_ANALYZE_DOCS);
845 assert!(meta["field_definitions"]["runtime_coverage.findings[].stable_id"].is_string());
846 assert!(meta["enums"]["action_type"].is_array());
847 assert!(meta["warnings"]["cloud_functions_unmatched"].is_string());
848 }
849}