Skip to main content

fallow_api/
compact_output.rs

1use std::path::Path;
2
3use fallow_engine::duplicates::CloneFingerprintSet;
4use fallow_output::normalize_uri;
5use fallow_types::duplicates::DuplicationReport;
6use fallow_types::output_dead_code::ReachabilityCaveat;
7use fallow_types::results::{AnalysisResults, UnusedExport, UnusedMember};
8
9use crate::ResultGroup;
10
11fn relative_path<'a>(path: &'a Path, root: &Path) -> &'a Path {
12    path.strip_prefix(root).unwrap_or(path)
13}
14
15fn compact_path(path: &Path, root: &Path) -> String {
16    normalize_uri(&relative_path(path, root).display().to_string())
17}
18
19/// The trailing `,caveat=<tokens>` field a compact record carries when the
20/// verdict behind it rests on a file this run never fully analyzed, or an empty
21/// string when it does not.
22///
23/// Compact records are not fixed at four colon-separated fields: duplication
24/// already appends `,fingerprint=...,group=...,tokens=...` after its location,
25/// so a trailing `,key=value` is the format's existing extension point and a
26/// parser that splits on the leading `:` fields is unaffected. Wire tokens are
27/// used rather than the prose labels the human report shows, because compact is
28/// consumed by scripts: `caveat=incomplete-import-graph` greps exactly.
29/// Multiple caveats join with `+`, since `,` already separates fields.
30fn compact_caveat_field(caveats: &[ReachabilityCaveat]) -> String {
31    if caveats.is_empty() {
32        return String::new();
33    }
34    let tokens: Vec<&str> = caveats
35        .iter()
36        .map(|caveat| ReachabilityCaveat::token(*caveat))
37        .collect();
38    format!(",caveat={}", tokens.join("+"))
39}
40
41fn compact_circular_dependency_line(
42    cycle: &fallow_types::output_dead_code::CircularDependencyFinding,
43    root: &Path,
44) -> String {
45    let mut display_chain: Vec<String> = cycle
46        .cycle
47        .files
48        .iter()
49        .map(|path| compact_path(path, root))
50        .collect();
51    if let Some(first) = display_chain.first() {
52        display_chain.push(first.clone());
53    }
54    let first_file = display_chain.first().map_or("", String::as_str);
55    let cross_pkg_tag = if cycle.cycle.is_cross_package {
56        " (cross-package)"
57    } else {
58        ""
59    };
60    format!(
61        "circular-dependency:{}:{}:{}{}",
62        first_file,
63        cycle.cycle.line,
64        display_chain.join(" \u{2192} "),
65        cross_pkg_tag
66    )
67}
68
69fn compact_re_export_cycle_line(
70    cycle: &fallow_types::output_dead_code::ReExportCycleFinding,
71    root: &Path,
72) -> String {
73    let chain: Vec<String> = cycle
74        .cycle
75        .files
76        .iter()
77        .map(|path| compact_path(path, root))
78        .collect();
79    let first_file = chain.first().map_or("", String::as_str);
80    let kind_tag = match cycle.cycle.kind {
81        fallow_types::results::ReExportCycleKind::SelfLoop => " (self-loop)",
82        fallow_types::results::ReExportCycleKind::MultiNode => "",
83    };
84    format!(
85        "re-export-cycle:{}:{}{}",
86        first_file,
87        chain.join(" <-> "),
88        kind_tag
89    )
90}
91
92fn compact_package_cycle_line(
93    cycle: &fallow_types::output_dead_code::PackageCycleFinding,
94    root: &Path,
95) -> String {
96    let (anchor, line) = cycle.cycle.edges.first().map_or_else(
97        || (String::new(), 0),
98        |edge| (compact_path(&edge.path, root), edge.line),
99    );
100    let chain = cycle.cycle.chain(" \u{2192} ");
101    let note = if cycle.cycle.group_truncated {
102        format!(
103            " ({})",
104            fallow_types::results::PackageCycle::GROUP_TRUNCATED_NOTE
105        )
106    } else {
107        String::new()
108    };
109    format!("package-cycle:{anchor}:{line}:{chain}{note}")
110}
111
112fn compact_boundary_violation_line(
113    item: &fallow_types::output_dead_code::BoundaryViolationFinding,
114    root: &Path,
115) -> String {
116    format!(
117        "boundary-violation:{}:{}:{} -> {} ({} -> {})",
118        compact_path(&item.violation.from_path, root),
119        item.violation.line,
120        compact_path(&item.violation.from_path, root),
121        compact_path(&item.violation.to_path, root),
122        item.violation.from_zone,
123        item.violation.to_zone,
124    )
125}
126
127fn compact_boundary_coverage_line(
128    item: &fallow_types::output_dead_code::BoundaryCoverageViolationFinding,
129    root: &Path,
130) -> String {
131    format!(
132        "boundary-coverage:{}:{}:no matching boundary zone",
133        compact_path(&item.violation.path, root),
134        item.violation.line,
135    )
136}
137
138fn compact_boundary_call_line(
139    item: &fallow_types::output_dead_code::BoundaryCallViolationFinding,
140    root: &Path,
141) -> String {
142    format!(
143        "boundary-call:{}:{}:{} forbidden in zone {} (pattern {})",
144        compact_path(&item.violation.path, root),
145        item.violation.line,
146        item.violation.callee,
147        item.violation.zone,
148        item.violation.pattern,
149    )
150}
151
152fn compact_stale_suppression_line(
153    item: &fallow_types::results::StaleSuppression,
154    root: &Path,
155) -> String {
156    format!(
157        "stale-suppression:{}:{}:{}",
158        compact_path(&item.path, root),
159        item.line,
160        item.display_message(),
161    )
162}
163
164fn compact_catalog_reference_line(
165    item: &fallow_types::output_dead_code::UnresolvedCatalogReferenceFinding,
166    root: &Path,
167) -> String {
168    format!(
169        "unresolved-catalog-reference:{}:{}:{}:{}",
170        compact_path(&item.reference.path, root),
171        item.reference.line,
172        item.reference.catalog_name,
173        item.reference.entry_name,
174    )
175}
176
177fn compact_unused_override_line(
178    item: &fallow_types::output_dead_code::UnusedDependencyOverrideFinding,
179    root: &Path,
180) -> String {
181    format!(
182        "unused-dependency-override:{}:{}:{}:{}",
183        compact_path(&item.entry.path, root),
184        item.entry.line,
185        item.entry.source.as_label(),
186        item.entry.raw_key,
187    )
188}
189
190fn compact_misconfigured_override_line(
191    item: &fallow_types::output_dead_code::MisconfiguredDependencyOverrideFinding,
192    root: &Path,
193) -> String {
194    format!(
195        "misconfigured-dependency-override:{}:{}:{}:{}",
196        compact_path(&item.entry.path, root),
197        item.entry.line,
198        item.entry.source.as_label(),
199        item.entry.raw_key,
200    )
201}
202
203/// Build compact output lines for analysis results.
204/// Each issue is represented as a single `prefix:details` line.
205pub fn build_compact_lines(results: &AnalysisResults, root: &Path) -> Vec<String> {
206    CompactLineBuilder::new(results, root).build()
207}
208
209struct CompactLineBuilder<'a> {
210    lines: Vec<String>,
211    results: &'a AnalysisResults,
212    root: &'a Path,
213}
214
215impl<'a> CompactLineBuilder<'a> {
216    fn new(results: &'a AnalysisResults, root: &'a Path) -> Self {
217        Self {
218            lines: Vec::new(),
219            results,
220            root,
221        }
222    }
223
224    fn build(mut self) -> Vec<String> {
225        self.push_core_lines();
226        self.push_unused_dependency_lines();
227        self.push_member_lines();
228        self.push_secondary_dependency_lines();
229        self.push_graph_lines();
230        self.push_workspace_lines();
231        self.lines
232    }
233
234    fn rel(&self, path: &Path) -> String {
235        compact_path(path, self.root)
236    }
237
238    fn unused_export_line(&self, export: &UnusedExport, caveats: &[ReachabilityCaveat]) -> String {
239        let tag = if export.is_re_export {
240            "unused-re-export"
241        } else {
242            "unused-export"
243        };
244        format!(
245            "{}:{}:{}:{}{}",
246            tag,
247            self.rel(&export.path),
248            export.line,
249            export.export_name,
250            compact_caveat_field(caveats)
251        )
252    }
253
254    fn unused_type_line(&self, export: &UnusedExport, caveats: &[ReachabilityCaveat]) -> String {
255        let tag = if export.is_re_export {
256            "unused-re-export-type"
257        } else {
258            "unused-type"
259        };
260        format!(
261            "{}:{}:{}:{}{}",
262            tag,
263            self.rel(&export.path),
264            export.line,
265            export.export_name,
266            compact_caveat_field(caveats)
267        )
268    }
269
270    fn compact_member(
271        &self,
272        member: &UnusedMember,
273        kind: &str,
274        caveats: &[ReachabilityCaveat],
275    ) -> String {
276        format!(
277            "{}:{}:{}:{}.{}{}",
278            kind,
279            self.rel(&member.path),
280            member.line,
281            member.parent_name,
282            member.member_name,
283            compact_caveat_field(caveats)
284        )
285    }
286
287    fn push_core_lines(&mut self) {
288        for file in &self.results.unused_files {
289            self.lines.push(format!(
290                "unused-file:{}{}",
291                self.rel(&file.file.path),
292                compact_caveat_field(&file.reachability_caveats)
293            ));
294        }
295        for export in &self.results.unused_exports {
296            self.lines
297                .push(self.unused_export_line(&export.export, &export.reachability_caveats));
298        }
299        for export in &self.results.unused_types {
300            self.lines
301                .push(self.unused_type_line(&export.export, &export.reachability_caveats));
302        }
303        for leak in &self.results.private_type_leaks {
304            self.lines.push(format!(
305                "private-type-leak:{}:{}:{}->{}",
306                self.rel(&leak.leak.path),
307                leak.leak.line,
308                leak.leak.export_name,
309                leak.leak.type_name
310            ));
311        }
312        for finding in &self.results.deprecated_exports_in_use {
313            self.lines.push(format!(
314                "deprecated-export-in-use:{}:{}:{}",
315                self.rel(&finding.export.path),
316                finding.export.line,
317                finding.export.export_name
318            ));
319        }
320    }
321
322    fn push_unused_dependency_lines(&mut self) {
323        for dep in &self.results.unused_dependencies {
324            self.lines.push(format!(
325                "unused-dep:{}{}",
326                dep.dep.package_name,
327                compact_caveat_field(&dep.reachability_caveats)
328            ));
329        }
330        for dep in &self.results.unused_dev_dependencies {
331            self.lines.push(format!(
332                "unused-devdep:{}{}",
333                dep.dep.package_name,
334                compact_caveat_field(&dep.reachability_caveats)
335            ));
336        }
337        for dep in &self.results.unused_optional_dependencies {
338            self.lines.push(format!(
339                "unused-optionaldep:{}{}",
340                dep.dep.package_name,
341                compact_caveat_field(&dep.reachability_caveats)
342            ));
343        }
344    }
345
346    fn push_member_lines(&mut self) {
347        for member in &self.results.unused_enum_members {
348            self.lines.push(self.compact_member(
349                &member.member,
350                "unused-enum-member",
351                &member.reachability_caveats,
352            ));
353        }
354        for member in &self.results.unused_class_members {
355            self.lines.push(self.compact_member(
356                &member.member,
357                "unused-class-member",
358                &member.reachability_caveats,
359            ));
360        }
361        for member in &self.results.unused_store_members {
362            self.lines.push(self.compact_member(
363                &member.member,
364                "unused-store-member",
365                &member.reachability_caveats,
366            ));
367        }
368        for member in &self.results.unused_namespace_members {
369            self.lines.push(self.compact_member(
370                &member.member,
371                "unused-namespace-member",
372                &member.reachability_caveats,
373            ));
374        }
375        for import in &self.results.unresolved_imports {
376            self.lines.push(format!(
377                "unresolved-import:{}:{}:{}",
378                self.rel(&import.import.path),
379                import.import.line,
380                import.import.specifier
381            ));
382        }
383    }
384
385    fn push_secondary_dependency_lines(&mut self) {
386        for dep in &self.results.unlisted_dependencies {
387            self.lines
388                .push(format!("unlisted-dep:{}", dep.dep.package_name));
389        }
390        for binary in &self.results.unlisted_binaries {
391            for site in &binary.binary.used_in {
392                self.lines.push(format!(
393                    "unlisted-binary:{}:{}:{}",
394                    self.rel(&site.path),
395                    site.line,
396                    binary.binary.binary_name
397                ));
398            }
399        }
400        for dup in &self.results.duplicate_exports {
401            self.lines
402                .push(format!("duplicate-export:{}", dup.export.export_name));
403        }
404        for dep in &self.results.type_only_dependencies {
405            self.lines
406                .push(format!("type-only-dep:{}", dep.dep.package_name));
407        }
408        for dep in &self.results.test_only_dependencies {
409            self.lines
410                .push(format!("test-only-dep:{}", dep.dep.package_name));
411        }
412        for dep in &self.results.dev_dependencies_in_production {
413            self.lines
414                .push(format!("dev-dep-in-prod:{}", dep.dep.package_name));
415        }
416    }
417
418    fn push_graph_lines(&mut self) {
419        self.push_structure_lines();
420        self.push_framework_lines();
421        self.push_component_lines();
422        self.push_route_lines();
423        self.push_suppression_lines();
424    }
425
426    fn push_structure_lines(&mut self) {
427        for cycle in &self.results.circular_dependencies {
428            self.lines
429                .push(compact_circular_dependency_line(cycle, self.root));
430        }
431        for cycle in &self.results.re_export_cycles {
432            self.lines
433                .push(compact_re_export_cycle_line(cycle, self.root));
434        }
435        for cycle in &self.results.package_cycles {
436            self.lines
437                .push(compact_package_cycle_line(cycle, self.root));
438        }
439        for violation in &self.results.boundary_violations {
440            self.lines
441                .push(compact_boundary_violation_line(violation, self.root));
442        }
443        for violation in &self.results.boundary_coverage_violations {
444            self.lines
445                .push(compact_boundary_coverage_line(violation, self.root));
446        }
447        for violation in &self.results.boundary_call_violations {
448            self.lines
449                .push(compact_boundary_call_line(violation, self.root));
450        }
451        for violation in &self.results.policy_violations {
452            self.lines.push(format!(
453                "policy-violation:{}:{}:{} banned by {}/{}",
454                self.rel(&violation.violation.path),
455                violation.violation.line,
456                violation.violation.matched,
457                violation.violation.pack,
458                violation.violation.rule_id,
459            ));
460        }
461    }
462
463    fn push_framework_lines(&mut self) {
464        for finding in &self.results.invalid_client_exports {
465            self.lines.push(format!(
466                "invalid-client-export:{}:{}:{} (from \"{}\")",
467                self.rel(&finding.export.path),
468                finding.export.line,
469                finding.export.export_name,
470                finding.export.directive,
471            ));
472        }
473        for finding in &self.results.mixed_client_server_barrels {
474            self.lines.push(format!(
475                "mixed-client-server-barrel:{}:{}:{} (server-only \"{}\")",
476                self.rel(&finding.barrel.path),
477                finding.barrel.line,
478                finding.barrel.client_origin,
479                finding.barrel.server_origin,
480            ));
481        }
482        for finding in &self.results.misplaced_directives {
483            self.lines.push(format!(
484                "misplaced-directive:{}:{}:{}",
485                self.rel(&finding.directive_site.path),
486                finding.directive_site.line,
487                finding.directive_site.directive,
488            ));
489        }
490        for finding in &self.results.unprovided_injects {
491            self.lines.push(format!(
492                "unprovided-inject:{}:{}:{}",
493                self.rel(&finding.inject.path),
494                finding.inject.line,
495                finding.inject.key_name,
496            ));
497        }
498    }
499
500    fn push_component_lines(&mut self) {
501        self.push_component_member_lines();
502        self.push_component_framework_lines();
503        self.push_component_health_lines();
504    }
505
506    /// Push compact lines for component health findings. Advisory findings stay
507    /// outside `total_issues`; explicit prop enforcement contributes to it.
508    fn push_component_health_lines(&mut self) {
509        for finding in &self.results.prop_drilling_chains {
510            let chain = &finding.chain;
511            let (path, line) = chain
512                .hops
513                .first()
514                .map_or((String::new(), 0), |hop| (self.rel(&hop.file), hop.line));
515            let trail = chain
516                .hops
517                .iter()
518                .map(|hop| hop.component.as_str())
519                .collect::<Vec<_>>()
520                .join(" -> ");
521            self.lines.push(format!(
522                "prop-drilling:{path}:{line}:{} (through {trail}, depth {})",
523                chain.prop, chain.depth,
524            ));
525        }
526        for finding in &self.results.thin_wrappers {
527            let wrapper = &finding.wrapper;
528            self.lines.push(format!(
529                "thin-wrapper:{}:{}:{} (wraps {})",
530                self.rel(&wrapper.file),
531                wrapper.line,
532                wrapper.component,
533                wrapper.child_component,
534            ));
535        }
536        for finding in &self.results.duplicate_prop_shapes {
537            let shape = &finding.shape;
538            self.lines.push(format!(
539                "duplicate-prop-shape:{}:{}:{} (shape {{{}}} shared with {} other components)",
540                self.rel(&shape.file),
541                shape.line,
542                shape.component,
543                shape.shape.join(", "),
544                shape.group_size.saturating_sub(1),
545            ));
546        }
547    }
548
549    /// Push compact lines for unrendered components, props, emits, inputs, and outputs.
550    fn push_component_member_lines(&mut self) {
551        for finding in &self.results.unrendered_components {
552            self.lines.push(format!(
553                "unrendered-component:{}:{}:{}",
554                self.rel(&finding.component.path),
555                finding.component.line,
556                finding.component.component_name,
557            ));
558        }
559        for finding in &self.results.absent_component_props {
560            self.lines.push(format!(
561                "absent-component-prop:{}:{}:{}.{} (review candidate)",
562                self.rel(&finding.prop.path),
563                finding.prop.line,
564                finding.prop.component_name,
565                finding.prop.prop_name
566            ));
567        }
568        for finding in &self.results.unused_component_props {
569            self.lines.push(format!(
570                "unused-component-prop:{}:{}:{}",
571                self.rel(&finding.prop.path),
572                finding.prop.line,
573                finding.prop.prop_name,
574            ));
575        }
576        for finding in &self.results.unused_component_emits {
577            self.lines.push(format!(
578                "unused-component-emit:{}:{}:{}",
579                self.rel(&finding.emit.path),
580                finding.emit.line,
581                finding.emit.emit_name,
582            ));
583        }
584        for finding in &self.results.unused_component_inputs {
585            self.lines.push(format!(
586                "unused-component-input:{}:{}:{}",
587                self.rel(&finding.input.path),
588                finding.input.line,
589                finding.input.input_name,
590            ));
591        }
592        for finding in &self.results.unused_component_outputs {
593            self.lines.push(format!(
594                "unused-component-output:{}:{}:{}",
595                self.rel(&finding.output.path),
596                finding.output.line,
597                finding.output.output_name,
598            ));
599        }
600    }
601
602    /// Push compact lines for Svelte events, Effect findings, server actions,
603    /// and load-data keys.
604    fn push_component_framework_lines(&mut self) {
605        for finding in &self.results.unused_svelte_events {
606            self.lines.push(format!(
607                "unused-svelte-event:{}:{}:{}",
608                self.rel(&finding.event.path),
609                finding.event.line,
610                finding.event.event_name,
611            ));
612        }
613        for finding in &self.results.duplicate_export_aliases {
614            self.lines.push(format!(
615                "duplicate-export-alias:{}:{}:{}:{}",
616                self.rel(&finding.alias.path),
617                finding.alias.line,
618                finding.alias.local_name,
619                finding.alias.export_names.join(","),
620            ));
621        }
622        for finding in &self.results.unused_effect_layers {
623            self.lines.push(format!(
624                "unused-effect-layer:{}:{}:{}",
625                self.rel(&finding.layer.path),
626                finding.layer.line,
627                finding.layer.name,
628            ));
629        }
630        for finding in &self.results.unused_tagged_errors {
631            self.lines.push(format!(
632                "unused-tagged-error:{}:{}:{}",
633                self.rel(&finding.error.path),
634                finding.error.line,
635                finding.error.name,
636            ));
637        }
638        for finding in &self.results.unproduced_catch_tags {
639            self.lines.push(format!(
640                "unproduced-catch-tag:{}:{}:{}",
641                self.rel(&finding.catch_tag.path),
642                finding.catch_tag.line,
643                finding.catch_tag.tag,
644            ));
645        }
646        for finding in &self.results.unused_server_actions {
647            self.lines.push(format!(
648                "unused-server-action:{}:{}:{}",
649                self.rel(&finding.action.path),
650                finding.action.line,
651                finding.action.action_name,
652            ));
653        }
654        for finding in &self.results.unused_load_data_keys {
655            self.lines.push(format!(
656                "unused-load-data-key:{}:{}:{}",
657                self.rel(&finding.key.path),
658                finding.key.line,
659                finding.key.key_name,
660            ));
661        }
662    }
663
664    fn push_route_lines(&mut self) {
665        for finding in &self.results.route_collisions {
666            self.lines.push(format!(
667                "route-collision:{}:{} (url {})",
668                self.rel(&finding.collision.path),
669                finding.collision.line,
670                finding.collision.url,
671            ));
672        }
673        for finding in &self.results.dynamic_segment_name_conflicts {
674            self.lines.push(format!(
675                "dynamic-segment-name-conflict:{}:{} ({} at {})",
676                self.rel(&finding.conflict.path),
677                finding.conflict.line,
678                finding.conflict.conflicting_segments.join(" vs "),
679                finding.conflict.position,
680            ));
681        }
682    }
683
684    fn push_suppression_lines(&mut self) {
685        for suppression in &self.results.stale_suppressions {
686            self.lines
687                .push(compact_stale_suppression_line(suppression, self.root));
688        }
689    }
690
691    fn push_workspace_lines(&mut self) {
692        for entry in &self.results.unused_catalog_entries {
693            self.lines.push(format!(
694                "unused-catalog-entry:{}:{}:{}:{}",
695                self.rel(&entry.entry.path),
696                entry.entry.line,
697                entry.entry.catalog_name,
698                entry.entry.entry_name,
699            ));
700        }
701        for group in &self.results.empty_catalog_groups {
702            self.lines.push(format!(
703                "empty-catalog-group:{}:{}:{}",
704                self.rel(&group.group.path),
705                group.group.line,
706                group.group.catalog_name,
707            ));
708        }
709        for finding in &self.results.unresolved_catalog_references {
710            self.lines
711                .push(compact_catalog_reference_line(finding, self.root));
712        }
713        for finding in &self.results.unused_dependency_overrides {
714            self.lines
715                .push(compact_unused_override_line(finding, self.root));
716        }
717        for finding in &self.results.misconfigured_dependency_overrides {
718            self.lines
719                .push(compact_misconfigured_override_line(finding, self.root));
720        }
721    }
722}
723
724/// Build grouped compact output lines, each prefixed with the group key.
725///
726/// Format: `group-key\tissue-tag:details`
727#[must_use]
728pub fn build_grouped_compact_lines(groups: &[ResultGroup], root: &Path) -> Vec<String> {
729    groups
730        .iter()
731        .flat_map(|group| {
732            build_compact_lines(&group.results, root)
733                .into_iter()
734                .map(|line| format!("{}\t{line}", group.key))
735        })
736        .collect()
737}
738
739/// Build compact output lines for health results.
740#[must_use]
741pub fn build_health_compact_lines(
742    report: &fallow_output::HealthReport,
743    root: &Path,
744) -> Vec<String> {
745    let mut lines = Vec::new();
746    push_health_score_compact(&mut lines, report);
747    push_vital_signs_compact(&mut lines, report);
748    push_health_findings_compact(&mut lines, &report.findings, root);
749    push_styling_findings_compact(&mut lines, &report.styling_findings, root);
750    push_threshold_overrides_compact(&mut lines, &report.threshold_overrides, root);
751    push_file_scores_compact(&mut lines, &report.file_scores, root);
752    push_coverage_gaps_compact(&mut lines, report, root);
753    push_runtime_sections_compact(&mut lines, report, root);
754    push_hotspots_compact(&mut lines, &report.hotspots, root);
755    push_change_coupling_compact(&mut lines, report.change_coupling.as_ref(), root);
756    push_health_trend_compact(&mut lines, report);
757    push_refactoring_targets_compact(&mut lines, &report.targets, root);
758    lines
759}
760
761fn push_styling_findings_compact(
762    lines: &mut Vec<String>,
763    findings: &[fallow_output::StylingFinding],
764    root: &Path,
765) {
766    for finding in findings {
767        let relative = compact_path(Path::new(&finding.path), root);
768        let severity = match finding.effective_severity {
769            fallow_output::StylingFindingSeverity::Error => "error",
770            fallow_output::StylingFindingSeverity::Warn => "warn",
771        };
772        let value = compact_field_value(&finding.value);
773        lines.push(format!(
774            "{}:{}:{}:{}:severity={},value={}",
775            finding.code, relative, finding.line, finding.sub_kind, severity, value
776        ));
777    }
778}
779
780/// Compact records for the diff-risk findings of `fallow audit`.
781///
782/// Format: `<rule>:<path>:<line>:<evidence>,severity=<severity>[,kind=<kind>]`.
783/// The paths are already root-relative. The line is `0` when the finding is
784/// about the whole file.
785#[must_use]
786pub fn build_diff_risk_compact_lines(report: &fallow_output::DiffRiskReport) -> Vec<String> {
787    report
788        .findings
789        .iter()
790        .map(|finding| {
791            let kind = finding
792                .kind
793                .map_or_else(String::new, |kind| format!(",kind={}", kind.code()));
794            format!(
795                "{}:{}:{}:{},severity={}{kind}",
796                finding.rule.code(),
797                normalize_uri(&finding.path),
798                finding.line.unwrap_or(0),
799                compact_field_value(&finding.evidence),
800                finding.severity.code(),
801            )
802        })
803        .collect()
804}
805
806fn compact_field_value(value: &str) -> String {
807    value
808        .replace([':', ',', '\n', '\r'], " ")
809        .split_whitespace()
810        .collect::<Vec<_>>()
811        .join(" ")
812}
813
814fn push_threshold_overrides_compact(
815    lines: &mut Vec<String>,
816    entries: &[fallow_output::ThresholdOverrideState],
817    root: &Path,
818) {
819    for entry in entries {
820        let status = match entry.status {
821            fallow_output::ThresholdOverrideStatus::Active => "active",
822            fallow_output::ThresholdOverrideStatus::Stale => "stale",
823            fallow_output::ThresholdOverrideStatus::Insufficient => "insufficient",
824            fallow_output::ThresholdOverrideStatus::NoMatch => "no_match",
825        };
826        let target = entry.path.as_ref().map_or_else(
827            || "no-match".to_string(),
828            |path| entry.target_label(&compact_path(path, root)),
829        );
830        let dimension = threshold_override_dimension_label(entry.dimension);
831        let metrics = entry.metrics.map_or(String::new(), |metrics| {
832            let crap = metrics
833                .crap
834                .map_or(String::new(), |value| format!(",crap={value:.1}"));
835            let line_count = metrics
836                .line_count
837                .map_or(String::new(), |value| format!(",lines={value}"));
838            format!(
839                ",cyclomatic={},cognitive={}{}{}",
840                metrics.cyclomatic, metrics.cognitive, line_count, crap
841            )
842        });
843        let outstanding = if entry.outstanding.is_empty() {
844            String::new()
845        } else {
846            format!(
847                ",outstanding={}",
848                entry
849                    .outstanding
850                    .iter()
851                    .map(|value| threshold_override_dimension_label(*value))
852                    .collect::<Vec<_>>()
853                    .join("|")
854            )
855        };
856        lines.push(format!(
857            "threshold-override:{}:{}:{}:{}{}{}",
858            entry.override_index, dimension, status, target, metrics, outstanding
859        ));
860    }
861}
862
863fn threshold_override_dimension_label(
864    dimension: fallow_output::ThresholdOverrideDimension,
865) -> &'static str {
866    match dimension {
867        fallow_output::ThresholdOverrideDimension::Complexity => "complexity",
868        fallow_output::ThresholdOverrideDimension::Crap => "crap",
869    }
870}
871
872fn push_health_score_compact(lines: &mut Vec<String>, report: &fallow_output::HealthReport) {
873    if let Some(ref hs) = report.health_score {
874        lines.push(format!("health-score:{:.1}:{}", hs.score, hs.grade));
875    }
876}
877
878fn push_vital_signs_compact(lines: &mut Vec<String>, report: &fallow_output::HealthReport) {
879    if let Some(ref vs) = report.vital_signs {
880        let mut parts = Vec::new();
881        if vs.total_loc > 0 {
882            parts.push(format!("total_loc={}", vs.total_loc));
883        }
884        parts.push(format!("avg_cyclomatic={:.1}", vs.avg_cyclomatic));
885        parts.push(format!("p90_cyclomatic={}", vs.p90_cyclomatic));
886        if let Some(v) = vs.dead_file_pct {
887            parts.push(format!("dead_file_pct={v:.1}"));
888        }
889        if let Some(v) = vs.dead_export_pct {
890            parts.push(format!("dead_export_pct={v:.1}"));
891        }
892        if let Some(v) = vs.maintainability_avg {
893            parts.push(format!("maintainability_avg={v:.1}"));
894        }
895        if let Some(v) = vs.hotspot_count {
896            parts.push(format!("hotspot_count={v}"));
897        }
898        if let Some(v) = vs.circular_dep_count {
899            parts.push(format!("circular_dep_count={v}"));
900        }
901        if let Some(v) = vs.unused_dep_count {
902            parts.push(format!("unused_dep_count={v}"));
903        }
904        lines.push(format!("vital-signs:{}", parts.join(",")));
905        push_cyclomatic_population_compact(lines, vs);
906    }
907}
908
909fn push_cyclomatic_population_compact(lines: &mut Vec<String>, vs: &fallow_output::VitalSigns) {
910    let Some(population) = &vs.cyclomatic_population else {
911        return;
912    };
913    for (kind, group) in [
914        ("functions", &population.functions),
915        ("modules", &population.modules),
916        ("templates", &population.templates),
917    ] {
918        let max = group
919            .max
920            .map_or_else(|| "null".to_string(), |value| value.to_string());
921        lines.push(format!(
922            "cyclomatic-population:{kind}:count={},sum={},max={max}",
923            group.count, group.sum
924        ));
925    }
926}
927
928/// Serde-name mirror of `ExceededThreshold` for the compact line grammar.
929fn exceeded_compact_label(exceeded: fallow_output::ExceededThreshold) -> &'static str {
930    match exceeded {
931        fallow_output::ExceededThreshold::Cyclomatic => "cyclomatic",
932        fallow_output::ExceededThreshold::Cognitive => "cognitive",
933        fallow_output::ExceededThreshold::Both => "both",
934        fallow_output::ExceededThreshold::Crap => "crap",
935        fallow_output::ExceededThreshold::CyclomaticCrap => "cyclomatic_crap",
936        fallow_output::ExceededThreshold::CognitiveCrap => "cognitive_crap",
937        fallow_output::ExceededThreshold::All => "all",
938        fallow_output::ExceededThreshold::FileLines => "file_lines",
939    }
940}
941
942fn push_health_findings_compact(
943    lines: &mut Vec<String>,
944    findings: &[fallow_output::HealthFinding],
945    root: &Path,
946) {
947    for finding in findings {
948        let relative = compact_path(&finding.path, root);
949        let severity = match finding.severity {
950            fallow_output::FindingSeverity::Critical => "critical",
951            fallow_output::FindingSeverity::High => "high",
952            fallow_output::FindingSeverity::Moderate => "moderate",
953        };
954        let crap_suffix = match finding.crap {
955            Some(crap) => {
956                let coverage = finding
957                    .coverage_pct
958                    .map(|pct| format!(",coverage_pct={pct:.1}"))
959                    .unwrap_or_default();
960                format!(",crap={crap:.1}{coverage}")
961            }
962            None => String::new(),
963        };
964        let file_lines_suffix = finding
965            .max_file_lines
966            .map(|max| format!(",line_count={},max_file_lines={max}", finding.line_count))
967            .unwrap_or_default();
968        // The `high-complexity:` row prefix is deliberately kept even for a
969        // CRAP-only breach (other machine formats route that to
970        // `fallow/high-crap-score`): renaming a line prefix breaks grep-based CI
971        // consumers, and `exceeded=` carries the dimension instead (issue #2163).
972        lines.push(format!(
973            "high-complexity:{}:{}:{}:cyclomatic={},cognitive={},severity={},exceeded={}{}{}",
974            relative,
975            finding.line,
976            finding.name,
977            finding.cyclomatic,
978            finding.cognitive,
979            severity,
980            exceeded_compact_label(finding.exceeded),
981            crap_suffix,
982            file_lines_suffix,
983        ));
984    }
985}
986
987fn push_file_scores_compact(
988    lines: &mut Vec<String>,
989    scores: &[fallow_output::FileHealthScore],
990    root: &Path,
991) {
992    for score in scores {
993        let relative = compact_path(&score.path, root);
994        lines.push(format!(
995            "file-score:{}:mi={:.1},fan_in={},fan_out={},dead={:.2},density={:.2},crap_max={:.1},crap_above={}",
996            relative,
997            score.maintainability_index,
998            score.fan_in,
999            score.fan_out,
1000            score.dead_code_ratio,
1001            score.complexity_density,
1002            score.crap_max,
1003            score.crap_above_threshold,
1004        ));
1005    }
1006}
1007
1008fn push_coverage_gaps_compact(
1009    lines: &mut Vec<String>,
1010    report: &fallow_output::HealthReport,
1011    root: &Path,
1012) {
1013    if let Some(ref gaps) = report.coverage_gaps {
1014        lines.push(format!(
1015            "coverage-gap-summary:runtime_files={},covered_files={},file_coverage_pct={:.1},untested_files={},untested_exports={}",
1016            gaps.summary.runtime_files,
1017            gaps.summary.covered_files,
1018            gaps.summary.file_coverage_pct,
1019            gaps.summary.untested_files,
1020            gaps.summary.untested_exports,
1021        ));
1022        for item in &gaps.files {
1023            let relative = compact_path(&item.file.path, root);
1024            lines.push(format!(
1025                "untested-file:{}:value_exports={}",
1026                relative, item.file.value_export_count,
1027            ));
1028        }
1029        for item in &gaps.exports {
1030            let relative = compact_path(&item.export.path, root);
1031            lines.push(format!(
1032                "untested-export:{}:{}:{}",
1033                relative, item.export.line, item.export.export_name,
1034            ));
1035        }
1036    }
1037}
1038
1039fn push_runtime_sections_compact(
1040    lines: &mut Vec<String>,
1041    report: &fallow_output::HealthReport,
1042    root: &Path,
1043) {
1044    if let Some(ref production) = report.runtime_coverage {
1045        lines.extend(build_runtime_coverage_compact_lines(production, root));
1046    }
1047    if let Some(ref intelligence) = report.coverage_intelligence {
1048        lines.extend(build_coverage_intelligence_compact_lines(
1049            intelligence,
1050            root,
1051        ));
1052    }
1053}
1054
1055fn compact_ownership_suffix(ownership: Option<&fallow_output::OwnershipMetrics>) -> String {
1056    ownership.map_or_else(String::new, |o| {
1057        let mut parts = vec![
1058            format!("bus={}", o.bus_factor),
1059            format!("contributors={}", o.contributor_count),
1060            format!("top={}", o.top_contributor.identifier),
1061            format!("top_share={:.3}", o.top_contributor.share),
1062        ];
1063        if let Some(owner) = &o.declared_owner {
1064            parts.push(format!("owner={owner}"));
1065        }
1066        if let Some(unowned) = o.unowned {
1067            parts.push(format!("unowned={unowned}"));
1068        }
1069        let state = match o.ownership_state {
1070            fallow_output::OwnershipState::Active => "active",
1071            fallow_output::OwnershipState::Unowned => "unowned",
1072            fallow_output::OwnershipState::DeclaredInactive => "declared_inactive",
1073            fallow_output::OwnershipState::Drifting => "drifting",
1074        };
1075        parts.push(format!("ownership_state={state}"));
1076        if o.drift {
1077            parts.push("drift=true".to_string());
1078        }
1079        format!(",{}", parts.join(","))
1080    })
1081}
1082
1083fn push_hotspots_compact(
1084    lines: &mut Vec<String>,
1085    hotspots: &[fallow_output::HotspotFinding],
1086    root: &Path,
1087) {
1088    for entry in hotspots {
1089        let relative = compact_path(&entry.path, root);
1090        let ownership_suffix = compact_ownership_suffix(entry.ownership.as_ref());
1091        lines.push(format!(
1092            "hotspot:{}:score={:.1},commits={},churn={},density={:.2},fan_in={},trend={}{}",
1093            relative,
1094            entry.score,
1095            entry.commits,
1096            entry.lines_added + entry.lines_deleted,
1097            entry.complexity_density,
1098            entry.fan_in,
1099            entry.trend,
1100            ownership_suffix,
1101        ));
1102    }
1103}
1104
1105/// One line per hidden change-coupling pair:
1106/// `change-coupling:<path_a>:<path_b>:degree=..,shared=..,commits_a=..,commits_b=..,strong=..`.
1107fn push_change_coupling_compact(
1108    lines: &mut Vec<String>,
1109    coupling: Option<&fallow_output::ChangeCouplingReport>,
1110    root: &Path,
1111) {
1112    let Some(coupling) = coupling else {
1113        return;
1114    };
1115    for pair in &coupling.pairs {
1116        lines.push(format!(
1117            "change-coupling:{}:{}:degree={:.2},shared={},commits_a={},commits_b={},strong={}",
1118            compact_path(&pair.path_a, root),
1119            compact_path(&pair.path_b, root),
1120            pair.degree,
1121            pair.shared_revisions,
1122            pair.revisions_a,
1123            pair.revisions_b,
1124            pair.strong,
1125        ));
1126    }
1127}
1128
1129fn push_health_trend_compact(lines: &mut Vec<String>, report: &fallow_output::HealthReport) {
1130    if let Some(ref trend) = report.health_trend {
1131        if let Some(current) = report.health_score.as_ref()
1132            && trend.compared_to.score.is_some()
1133            && !trend.metrics.iter().any(|metric| metric.name == "score")
1134            && fallow_output::health_score_comparison_note(
1135                trend.compared_to.score_formula_version,
1136                Some(current.formula_version),
1137            )
1138            .is_some()
1139        {
1140            let previous_formula = trend
1141                .compared_to
1142                .score_formula_version
1143                .map_or_else(|| "unknown".to_owned(), |version| version.to_string());
1144            lines.push(format!(
1145                "trend:score-omitted:previous_formula={previous_formula},current_formula={}",
1146                current.formula_version,
1147            ));
1148        }
1149        lines.push(format!(
1150            "trend:overall:direction={}",
1151            trend.overall_direction.label()
1152        ));
1153        for m in &trend.metrics {
1154            lines.push(format!(
1155                "trend:{}:previous={:.1},current={:.1},delta={:+.1},direction={}",
1156                m.name,
1157                m.previous,
1158                m.current,
1159                m.delta,
1160                m.direction.label(),
1161            ));
1162        }
1163    }
1164}
1165
1166fn push_refactoring_targets_compact(
1167    lines: &mut Vec<String>,
1168    targets: &[fallow_output::RefactoringTargetFinding],
1169    root: &Path,
1170) {
1171    for target in targets {
1172        let relative = compact_path(&target.path, root);
1173        let category = target.category.compact_label();
1174        let effort = target.effort.label();
1175        let confidence = target.confidence.label();
1176        lines.push(format!(
1177            "refactoring-target:{}:priority={:.1},efficiency={:.1},category={},effort={},confidence={}:{}",
1178            relative,
1179            target.priority,
1180            target.efficiency,
1181            category,
1182            effort,
1183            confidence,
1184            target.recommendation,
1185        ));
1186    }
1187}
1188
1189fn build_runtime_coverage_compact_lines(
1190    production: &fallow_output::RuntimeCoverageReport,
1191    root: &Path,
1192) -> Vec<String> {
1193    let summary = &production.summary;
1194    let null_or = |count: Option<usize>| count.map_or_else(|| "null".to_owned(), |n| n.to_string());
1195    let mut lines = vec![format!(
1196        "runtime-coverage-summary:functions_tracked={},functions_hit={},functions_unhit={},functions_untracked={},coverage_percent={},trace_count={},period_days={},deployments_seen={}",
1197        null_or(summary.functions_tracked),
1198        summary.functions_hit,
1199        null_or(summary.functions_unhit),
1200        summary.functions_untracked,
1201        summary
1202            .coverage_percent
1203            .map_or_else(|| "null".to_owned(), |percent| format!("{percent:.1}")),
1204        production.summary.trace_count,
1205        production.summary.period_days,
1206        production.summary.deployments_seen,
1207    )];
1208    for finding in &production.findings {
1209        let relative = compact_path(&finding.path, root);
1210        let invocations = finding
1211            .invocations
1212            .map_or_else(|| "null".to_owned(), |hits| hits.to_string());
1213        lines.push(format!(
1214            "runtime-coverage:{}:{}:{}:id={},verdict={},invocations={},confidence={}",
1215            relative,
1216            finding.line,
1217            finding.function,
1218            finding.id,
1219            finding.verdict,
1220            invocations,
1221            finding.confidence,
1222        ));
1223    }
1224    for entry in &production.hot_paths {
1225        let relative = compact_path(&entry.path, root);
1226        lines.push(format!(
1227            "production-hot-path:{}:{}:{}:id={},invocations={},percentile={}",
1228            relative, entry.line, entry.function, entry.id, entry.invocations, entry.percentile,
1229        ));
1230    }
1231    lines
1232}
1233
1234fn build_coverage_intelligence_compact_lines(
1235    intelligence: &fallow_output::CoverageIntelligenceReport,
1236    root: &Path,
1237) -> Vec<String> {
1238    let mut lines = vec![format!(
1239        "coverage-intelligence-summary:verdict={},findings={},risky_changes={},high_confidence_deletes={},review_required={},refactor_carefully={},skipped_ambiguous_matches={}",
1240        intelligence.verdict,
1241        intelligence.summary.findings,
1242        intelligence.summary.risky_changes,
1243        intelligence.summary.high_confidence_deletes,
1244        intelligence.summary.review_required,
1245        intelligence.summary.refactor_carefully,
1246        intelligence.summary.skipped_ambiguous_matches,
1247    )];
1248    for finding in &intelligence.findings {
1249        let relative = compact_path(&finding.path, root);
1250        let identity = finding.identity.as_deref().unwrap_or("-");
1251        let signals = finding
1252            .signals
1253            .iter()
1254            .map(ToString::to_string)
1255            .collect::<Vec<_>>()
1256            .join("+");
1257        lines.push(format!(
1258            "coverage-intelligence:{}:{}:{}:id={},verdict={},recommendation={},confidence={},signals={}",
1259            relative,
1260            finding.line,
1261            identity,
1262            finding.id,
1263            finding.verdict,
1264            finding.recommendation,
1265            finding.confidence,
1266            signals,
1267        ));
1268    }
1269    lines
1270}
1271
1272/// Build compact output lines for duplication results.
1273#[must_use]
1274pub fn build_duplication_compact_lines(report: &DuplicationReport, root: &Path) -> Vec<String> {
1275    let fingerprints = CloneFingerprintSet::from_groups(&report.clone_groups);
1276    let mut lines = Vec::new();
1277    for (index, group) in report.clone_groups.iter().enumerate() {
1278        let fingerprint = fingerprints.fingerprint_for_group(group);
1279        for instance in &group.instances {
1280            lines.push(format!(
1281                "code-duplication:{}:{}-{}:fingerprint={},group={},tokens={},lines={},instances={}{}",
1282                compact_path(&instance.file, root),
1283                instance.start_line,
1284                instance.end_line,
1285                fingerprint,
1286                index + 1,
1287                group.token_count,
1288                group.line_count,
1289                group.instances.len(),
1290                if instance.is_symlink {
1291                    ",symlink=true"
1292                } else {
1293                    ""
1294                },
1295            ));
1296        }
1297    }
1298    lines
1299}
1300
1301#[cfg(test)]
1302mod tests {
1303    use std::path::PathBuf;
1304
1305    use fallow_types::duplicates::{CloneGroup, CloneInstance, DuplicationStats};
1306    use fallow_types::output_dead_code::UnusedFileFinding;
1307    use fallow_types::results::{AnalysisResults, UnusedFile};
1308
1309    use super::*;
1310
1311    fn diff_risk_finding(
1312        rule: fallow_output::DiffRiskRule,
1313        kind: Option<fallow_output::WeakenedTestsKind>,
1314        path: &str,
1315        line: Option<u32>,
1316        evidence: &str,
1317        severity: fallow_output::DiffRiskSeverity,
1318    ) -> fallow_output::DiffRiskFinding {
1319        fallow_output::DiffRiskFinding {
1320            rule,
1321            kind,
1322            path: path.to_owned(),
1323            line,
1324            message: "m".to_owned(),
1325            evidence: evidence.to_owned(),
1326            severity,
1327            introduced: true,
1328            related: Vec::new(),
1329            actions: Vec::new(),
1330            suppression: None,
1331        }
1332    }
1333
1334    #[test]
1335    fn diff_risk_compact_lines_follow_the_tag_path_line_subject_grammar() {
1336        let report = fallow_output::DiffRiskReport {
1337            findings: vec![
1338                diff_risk_finding(
1339                    fallow_output::DiffRiskRule::WeakenedTests,
1340                    Some(fallow_output::WeakenedTestsKind::SkipOnly),
1341                    "src/a.test.ts",
1342                    Some(4),
1343                    "it.skip",
1344                    fallow_output::DiffRiskSeverity::Warn,
1345                ),
1346                diff_risk_finding(
1347                    fallow_output::DiffRiskRule::WeakenedTests,
1348                    Some(fallow_output::WeakenedTestsKind::RemovedTests),
1349                    "src/b.test.ts",
1350                    None,
1351                    "test cases: 3 -> 1",
1352                    fallow_output::DiffRiskSeverity::Error,
1353                ),
1354                diff_risk_finding(
1355                    fallow_output::DiffRiskRule::AddedDependency,
1356                    None,
1357                    "package.json",
1358                    Some(7),
1359                    "left-pad@^1.3.0 (dependencies)",
1360                    fallow_output::DiffRiskSeverity::Warn,
1361                ),
1362            ],
1363        };
1364        assert_eq!(
1365            build_diff_risk_compact_lines(&report),
1366            vec![
1367                "weakened-tests:src/a.test.ts:4:it.skip,severity=warn,kind=skip-only".to_owned(),
1368                "weakened-tests:src/b.test.ts:0:test cases 3 -> 1,severity=error,kind=removed-tests"
1369                    .to_owned(),
1370                "added-dependency:package.json:7:left-pad@^1.3.0 (dependencies),severity=warn"
1371                    .to_owned(),
1372            ]
1373        );
1374    }
1375
1376    #[test]
1377    fn compact_cycles_preserve_empty_self_loop_and_cross_package_output() {
1378        use fallow_types::output_dead_code::{CircularDependencyFinding, ReExportCycleFinding};
1379        use fallow_types::results::{CircularDependency, ReExportCycle, ReExportCycleKind};
1380
1381        let root = Path::new("/project");
1382        for (files, cross_package, expected) in [
1383            (vec![], false, "circular-dependency::7:"),
1384            (
1385                vec![root.join("src/a.ts")],
1386                false,
1387                "circular-dependency:src/a.ts:7:src/a.ts → src/a.ts",
1388            ),
1389            (
1390                vec![root.join("src/a.ts"), root.join("src/b.ts")],
1391                true,
1392                "circular-dependency:src/a.ts:7:src/a.ts → src/b.ts → src/a.ts (cross-package)",
1393            ),
1394        ] {
1395            let mut results = AnalysisResults::default();
1396            results
1397                .circular_dependencies
1398                .push(CircularDependencyFinding {
1399                    finding_id: None,
1400                    cycle: CircularDependency {
1401                        length: files.len(),
1402                        files,
1403                        line: 7,
1404                        col: 0,
1405                        edges: vec![],
1406                        is_cross_package: cross_package,
1407                    },
1408                    actions: vec![],
1409                    introduced: None,
1410                    effective_severity: None,
1411                });
1412            assert_eq!(build_compact_lines(&results, root), vec![expected]);
1413        }
1414        for (files, kind, expected) in [
1415            (vec![], ReExportCycleKind::MultiNode, "re-export-cycle::"),
1416            (
1417                vec![root.join("src/a.ts")],
1418                ReExportCycleKind::SelfLoop,
1419                "re-export-cycle:src/a.ts:src/a.ts (self-loop)",
1420            ),
1421            (
1422                vec![root.join("src/a.ts"), root.join("src/b.ts")],
1423                ReExportCycleKind::MultiNode,
1424                "re-export-cycle:src/a.ts:src/a.ts <-> src/b.ts",
1425            ),
1426        ] {
1427            let mut results = AnalysisResults::default();
1428            results.re_export_cycles.push(ReExportCycleFinding {
1429                finding_id: None,
1430                cycle: ReExportCycle { files, kind },
1431                actions: vec![],
1432                introduced: None,
1433                effective_severity: None,
1434            });
1435            assert_eq!(build_compact_lines(&results, root), vec![expected]);
1436        }
1437    }
1438
1439    /// A compact record is what a CI script greps to decide what to delete, so
1440    /// a verdict resting on a file the run never read has to say so on the same
1441    /// line. The field rides in the trailing `,key=value` slot duplication
1442    /// records already use, so the leading colon-separated fields a parser
1443    /// splits on are untouched.
1444    #[test]
1445    fn a_caveated_finding_carries_a_trailing_caveat_field() {
1446        use fallow_types::extract::MemberKind;
1447        use fallow_types::output_dead_code::{ReachabilityCaveat, UnusedDependencyFinding};
1448        use fallow_types::results::{UnusedDependency, UnusedExport};
1449
1450        let root = PathBuf::from("/project");
1451        let mut results = AnalysisResults::default();
1452
1453        let mut file = UnusedFileFinding::with_actions(UnusedFile {
1454            path: root.join("src/dead.ts"),
1455        });
1456        file.reachability_caveats = vec![ReachabilityCaveat::IncompleteImportGraph];
1457        results.unused_files.push(file);
1458
1459        let mut export =
1460            fallow_types::output_dead_code::UnusedExportFinding::with_actions(UnusedExport {
1461                path: root.join("src/lib.ts"),
1462                export_name: "needed".to_owned(),
1463                is_type_only: false,
1464                line: 3,
1465                col: 0,
1466                span_start: 0,
1467                is_re_export: false,
1468                deprecated: false,
1469                deprecated_reason: None,
1470            });
1471        export.reachability_caveats = vec![
1472            ReachabilityCaveat::IncompleteFileAnalysis,
1473            ReachabilityCaveat::IncompleteImportGraph,
1474        ];
1475        results.unused_exports.push(export);
1476
1477        let mut dep = UnusedDependencyFinding::with_actions(UnusedDependency {
1478            package_name: "left-pad".to_owned(),
1479            location: fallow_types::results::DependencyLocation::Dependencies,
1480            path: root.join("package.json"),
1481            line: 5,
1482            used_in_workspaces: Vec::new(),
1483            declared_and_imported_in: Vec::new(),
1484        });
1485        dep.reachability_caveats = vec![ReachabilityCaveat::IncompleteImportGraph];
1486        results.unused_dependencies.push(dep);
1487
1488        let member = |parent: &str, name: &str, kind| fallow_types::results::UnusedMember {
1489            path: root.join("src/lib.ts"),
1490            parent_name: parent.to_owned(),
1491            member_name: name.to_owned(),
1492            kind,
1493            line: 7,
1494            col: 2,
1495        };
1496        let mut enum_member = fallow_types::output_dead_code::UnusedEnumMemberFinding::with_actions(
1497            member("Mode", "Legacy", MemberKind::EnumMember),
1498        );
1499        enum_member.reachability_caveats = vec![ReachabilityCaveat::IncompleteImportGraph];
1500        results.unused_enum_members.push(enum_member);
1501
1502        let mut class_member =
1503            fallow_types::output_dead_code::UnusedClassMemberFinding::with_actions(member(
1504                "Widget",
1505                "render",
1506                MemberKind::ClassMethod,
1507            ));
1508        class_member.reachability_caveats = vec![ReachabilityCaveat::IncompleteImportGraph];
1509        results.unused_class_members.push(class_member);
1510
1511        let mut store_member =
1512            fallow_types::output_dead_code::UnusedStoreMemberFinding::with_actions(member(
1513                "useCart",
1514                "subtotal",
1515                MemberKind::StoreMember,
1516            ));
1517        store_member.reachability_caveats = vec![ReachabilityCaveat::IncompleteImportGraph];
1518        results.unused_store_members.push(store_member);
1519
1520        let lines = build_compact_lines(&results, &root);
1521
1522        assert_eq!(
1523            lines,
1524            vec![
1525                "unused-file:src/dead.ts,caveat=incomplete-import-graph",
1526                "unused-export:src/lib.ts:3:needed,caveat=incomplete-file-analysis+incomplete-import-graph",
1527                "unused-dep:left-pad,caveat=incomplete-import-graph",
1528                "unused-enum-member:src/lib.ts:7:Mode.Legacy,caveat=incomplete-import-graph",
1529                "unused-class-member:src/lib.ts:7:Widget.render,caveat=incomplete-import-graph",
1530                "unused-store-member:src/lib.ts:7:useCart.subtotal,caveat=incomplete-import-graph",
1531            ]
1532        );
1533    }
1534
1535    #[test]
1536    fn compact_unused_file_format_uses_relative_paths() {
1537        let root = PathBuf::from("/project");
1538        let mut results = AnalysisResults::default();
1539        results
1540            .unused_files
1541            .push(UnusedFileFinding::with_actions(UnusedFile {
1542                path: root.join("src/dead.ts"),
1543            }));
1544
1545        let lines = build_compact_lines(&results, &root);
1546
1547        assert_eq!(lines, vec!["unused-file:src/dead.ts"]);
1548    }
1549
1550    #[test]
1551    fn grouped_compact_prefixes_each_issue_with_group_key() {
1552        let root = PathBuf::from("/project");
1553        let mut results = AnalysisResults::default();
1554        results
1555            .unused_files
1556            .push(UnusedFileFinding::with_actions(UnusedFile {
1557                path: root.join("src/dead.ts"),
1558            }));
1559        let groups = vec![ResultGroup {
1560            key: "team-a".to_owned(),
1561            owners: Some(vec!["@team-a".to_owned()]),
1562            results,
1563        }];
1564
1565        let lines = build_grouped_compact_lines(&groups, &root);
1566
1567        assert_eq!(lines, vec!["team-a\tunused-file:src/dead.ts"]);
1568    }
1569
1570    #[test]
1571    fn duplication_compact_lines_include_stable_group_context() {
1572        let root = PathBuf::from("/project");
1573        let report = DuplicationReport {
1574            clone_groups: vec![CloneGroup {
1575                instances: vec![CloneInstance {
1576                    is_symlink: false,
1577                    file: root.join("src/a.ts"),
1578                    start_line: 2,
1579                    end_line: 6,
1580                    start_col: 0,
1581                    end_col: 10,
1582                    fragment: "const duplicated = true;".to_owned(),
1583                }],
1584                token_count: 12,
1585                line_count: 5,
1586                similarity: None,
1587            }],
1588            clone_families: Vec::new(),
1589            mirrored_directories: Vec::new(),
1590            stats: DuplicationStats::default(),
1591        };
1592
1593        let lines = build_duplication_compact_lines(&report, &root);
1594
1595        assert_eq!(lines.len(), 1);
1596        assert!(lines[0].starts_with("code-duplication:src/a.ts:2-6:fingerprint="));
1597        assert!(lines[0].contains(",group=1,tokens=12,lines=5,instances=1"));
1598        assert!(!lines[0].contains("symlink"));
1599    }
1600
1601    #[test]
1602    fn duplication_compact_lines_mark_symlinked_instances() {
1603        let root = PathBuf::from("/project");
1604        let instance = |path: &str, is_symlink: bool| CloneInstance {
1605            is_symlink,
1606            file: root.join(path),
1607            start_line: 1,
1608            end_line: 5,
1609            start_col: 0,
1610            end_col: 0,
1611            fragment: String::new(),
1612        };
1613        let report = DuplicationReport {
1614            clone_groups: vec![CloneGroup {
1615                instances: vec![
1616                    instance("src/link.ts", true),
1617                    instance("src/real.ts", false),
1618                ],
1619                token_count: 12,
1620                line_count: 5,
1621                similarity: None,
1622            }],
1623            clone_families: Vec::new(),
1624            mirrored_directories: Vec::new(),
1625            stats: DuplicationStats::default(),
1626        };
1627
1628        let lines = build_duplication_compact_lines(&report, &root);
1629
1630        assert!(lines[0].starts_with("code-duplication:src/link.ts:1-5:"));
1631        assert!(lines[0].ends_with(",instances=2,symlink=true"));
1632        assert!(lines[1].ends_with(",instances=2"));
1633    }
1634
1635    #[test]
1636    fn health_compact_lines_include_score_and_vital_signs() {
1637        let root = PathBuf::from("/project");
1638        let report = fallow_output::HealthReport {
1639            health_score: Some(fallow_output::HealthScore {
1640                formula_version: 1,
1641                score: 91.2,
1642                grade: "A",
1643                penalties: fallow_output::HealthScorePenalties {
1644                    dead_files: None,
1645                    dead_exports: None,
1646                    complexity: 0.0,
1647                    p90_complexity: 0.0,
1648                    maintainability: None,
1649                    hotspots: None,
1650                    unused_deps: None,
1651                    circular_deps: None,
1652                    unit_size: None,
1653                    coupling: None,
1654                    duplication: None,
1655                    prop_drilling: None,
1656                },
1657            }),
1658            vital_signs: Some(fallow_output::VitalSigns {
1659                total_loc: 120,
1660                avg_cyclomatic: 3.4,
1661                p90_cyclomatic: 8,
1662                ..Default::default()
1663            }),
1664            ..Default::default()
1665        };
1666
1667        let lines = build_health_compact_lines(&report, &root);
1668
1669        assert_eq!(lines[0], "health-score:91.2:A");
1670        assert_eq!(
1671            lines[1],
1672            "vital-signs:total_loc=120,avg_cyclomatic=3.4,p90_cyclomatic=8"
1673        );
1674        assert!(
1675            lines
1676                .iter()
1677                .all(|line| !line.starts_with("cyclomatic-population:"))
1678        );
1679    }
1680
1681    #[test]
1682    fn health_compact_population_rows_preserve_vital_signs_and_order() {
1683        let root = PathBuf::from("/project");
1684        let vitals = fallow_output::VitalSigns {
1685            avg_cyclomatic: 16.0,
1686            p90_cyclomatic: 31,
1687            ..Default::default()
1688        };
1689        let legacy = build_health_compact_lines(
1690            &fallow_output::HealthReport {
1691                vital_signs: Some(vitals.clone()),
1692                ..Default::default()
1693            },
1694            &root,
1695        );
1696        let report = fallow_output::HealthReport {
1697            vital_signs: Some(fallow_output::VitalSigns {
1698                cyclomatic_population: Some(fallow_output::CyclomaticPopulation {
1699                    functions: fallow_output::CyclomaticUnitPopulation {
1700                        count: 1,
1701                        sum: 1,
1702                        max: Some(1),
1703                    },
1704                    modules: fallow_output::CyclomaticUnitPopulation {
1705                        count: 1,
1706                        sum: 31,
1707                        max: Some(31),
1708                    },
1709                    templates: fallow_output::CyclomaticUnitPopulation::default(),
1710                }),
1711                ..vitals
1712            }),
1713            ..Default::default()
1714        };
1715        let lines = build_health_compact_lines(&report, &root);
1716        assert_eq!(lines[0], legacy[0]);
1717        assert_eq!(
1718            &lines[1..],
1719            [
1720                "cyclomatic-population:functions:count=1,sum=1,max=1",
1721                "cyclomatic-population:modules:count=1,sum=31,max=31",
1722                "cyclomatic-population:templates:count=0,sum=0,max=null",
1723            ]
1724        );
1725    }
1726
1727    #[test]
1728    fn health_compact_measured_empty_populations_keep_null_maxima() {
1729        let report = fallow_output::HealthReport {
1730            vital_signs: Some(fallow_output::VitalSigns {
1731                cyclomatic_population: Some(fallow_output::CyclomaticPopulation::default()),
1732                ..Default::default()
1733            }),
1734            ..Default::default()
1735        };
1736        let lines = build_health_compact_lines(&report, &PathBuf::from("/project"));
1737        assert_eq!(
1738            &lines[1..],
1739            [
1740                "cyclomatic-population:functions:count=0,sum=0,max=null",
1741                "cyclomatic-population:modules:count=0,sum=0,max=null",
1742                "cyclomatic-population:templates:count=0,sum=0,max=null",
1743            ]
1744        );
1745    }
1746
1747    #[test]
1748    fn health_compact_lines_include_styling_findings() {
1749        let root = PathBuf::from("/project");
1750        let report = fallow_output::HealthReport {
1751            styling_findings: vec![fallow_output::StylingFinding {
1752                internal: fallow_output::StylingFindingInternal::default(),
1753                code: "css-token-drift".to_string(),
1754                sub_kind: "tailwind-arbitrary-value".to_string(),
1755                path: "/project/src/app.css".to_string(),
1756                line: 6,
1757                value: "--color-brand: rgb(240, 90, 41)".to_string(),
1758                effective_severity: fallow_output::StylingFindingSeverity::Warn,
1759                blast_radius: None,
1760                confidence: None,
1761                agent_disposition: None,
1762                nearest_token: None,
1763                fix_hint: None,
1764                actions: Vec::new(),
1765            }],
1766            ..Default::default()
1767        };
1768
1769        let lines = build_health_compact_lines(&report, &root);
1770
1771        assert_eq!(
1772            lines,
1773            vec![
1774                "css-token-drift:src/app.css:6:tailwind-arbitrary-value:severity=warn,value=--color-brand rgb(240 90 41)"
1775            ]
1776        );
1777    }
1778}