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.constant_parameters {
560            self.lines.push(format!(
561                "constant-parameter:{}:{}:{}({}) {} (review candidate)",
562                self.rel(&finding.parameter.path),
563                finding.parameter.line,
564                finding.parameter.function_name,
565                finding.parameter.parameter_name,
566                finding.parameter.reason.as_str(),
567            ));
568        }
569        for finding in &self.results.absent_component_props {
570            self.lines.push(format!(
571                "absent-component-prop:{}:{}:{}.{} (review candidate)",
572                self.rel(&finding.prop.path),
573                finding.prop.line,
574                finding.prop.component_name,
575                finding.prop.prop_name
576            ));
577        }
578        for finding in &self.results.unused_component_props {
579            self.lines.push(format!(
580                "unused-component-prop:{}:{}:{}",
581                self.rel(&finding.prop.path),
582                finding.prop.line,
583                finding.prop.prop_name,
584            ));
585        }
586        for finding in &self.results.unused_component_emits {
587            self.lines.push(format!(
588                "unused-component-emit:{}:{}:{}",
589                self.rel(&finding.emit.path),
590                finding.emit.line,
591                finding.emit.emit_name,
592            ));
593        }
594        for finding in &self.results.unused_component_inputs {
595            self.lines.push(format!(
596                "unused-component-input:{}:{}:{}",
597                self.rel(&finding.input.path),
598                finding.input.line,
599                finding.input.input_name,
600            ));
601        }
602        for finding in &self.results.unused_component_outputs {
603            self.lines.push(format!(
604                "unused-component-output:{}:{}:{}",
605                self.rel(&finding.output.path),
606                finding.output.line,
607                finding.output.output_name,
608            ));
609        }
610    }
611
612    /// Push compact lines for Svelte events, Effect findings, server actions,
613    /// and load-data keys.
614    fn push_component_framework_lines(&mut self) {
615        for finding in &self.results.unused_svelte_events {
616            self.lines.push(format!(
617                "unused-svelte-event:{}:{}:{}",
618                self.rel(&finding.event.path),
619                finding.event.line,
620                finding.event.event_name,
621            ));
622        }
623        for finding in &self.results.duplicate_export_aliases {
624            self.lines.push(format!(
625                "duplicate-export-alias:{}:{}:{}:{}",
626                self.rel(&finding.alias.path),
627                finding.alias.line,
628                finding.alias.local_name,
629                finding.alias.export_names.join(","),
630            ));
631        }
632        for finding in &self.results.unused_effect_layers {
633            self.lines.push(format!(
634                "unused-effect-layer:{}:{}:{}",
635                self.rel(&finding.layer.path),
636                finding.layer.line,
637                finding.layer.name,
638            ));
639        }
640        for finding in &self.results.unused_tagged_errors {
641            self.lines.push(format!(
642                "unused-tagged-error:{}:{}:{}",
643                self.rel(&finding.error.path),
644                finding.error.line,
645                finding.error.name,
646            ));
647        }
648        for finding in &self.results.unproduced_catch_tags {
649            self.lines.push(format!(
650                "unproduced-catch-tag:{}:{}:{}",
651                self.rel(&finding.catch_tag.path),
652                finding.catch_tag.line,
653                finding.catch_tag.tag,
654            ));
655        }
656        for finding in &self.results.unused_server_actions {
657            self.lines.push(format!(
658                "unused-server-action:{}:{}:{}",
659                self.rel(&finding.action.path),
660                finding.action.line,
661                finding.action.action_name,
662            ));
663        }
664        for finding in &self.results.unused_load_data_keys {
665            self.lines.push(format!(
666                "unused-load-data-key:{}:{}:{}",
667                self.rel(&finding.key.path),
668                finding.key.line,
669                finding.key.key_name,
670            ));
671        }
672    }
673
674    fn push_route_lines(&mut self) {
675        for finding in &self.results.route_collisions {
676            self.lines.push(format!(
677                "route-collision:{}:{} (url {})",
678                self.rel(&finding.collision.path),
679                finding.collision.line,
680                finding.collision.url,
681            ));
682        }
683        for finding in &self.results.dynamic_segment_name_conflicts {
684            self.lines.push(format!(
685                "dynamic-segment-name-conflict:{}:{} ({} at {})",
686                self.rel(&finding.conflict.path),
687                finding.conflict.line,
688                finding.conflict.conflicting_segments.join(" vs "),
689                finding.conflict.position,
690            ));
691        }
692    }
693
694    fn push_suppression_lines(&mut self) {
695        for suppression in &self.results.stale_suppressions {
696            self.lines
697                .push(compact_stale_suppression_line(suppression, self.root));
698        }
699    }
700
701    fn push_workspace_lines(&mut self) {
702        for entry in &self.results.unused_catalog_entries {
703            self.lines.push(format!(
704                "unused-catalog-entry:{}:{}:{}:{}",
705                self.rel(&entry.entry.path),
706                entry.entry.line,
707                entry.entry.catalog_name,
708                entry.entry.entry_name,
709            ));
710        }
711        for group in &self.results.empty_catalog_groups {
712            self.lines.push(format!(
713                "empty-catalog-group:{}:{}:{}",
714                self.rel(&group.group.path),
715                group.group.line,
716                group.group.catalog_name,
717            ));
718        }
719        for finding in &self.results.unresolved_catalog_references {
720            self.lines
721                .push(compact_catalog_reference_line(finding, self.root));
722        }
723        for finding in &self.results.unused_dependency_overrides {
724            self.lines
725                .push(compact_unused_override_line(finding, self.root));
726        }
727        for finding in &self.results.misconfigured_dependency_overrides {
728            self.lines
729                .push(compact_misconfigured_override_line(finding, self.root));
730        }
731    }
732}
733
734/// Build grouped compact output lines, each prefixed with the group key.
735///
736/// Format: `group-key\tissue-tag:details`
737#[must_use]
738pub fn build_grouped_compact_lines(groups: &[ResultGroup], root: &Path) -> Vec<String> {
739    groups
740        .iter()
741        .flat_map(|group| {
742            build_compact_lines(&group.results, root)
743                .into_iter()
744                .map(|line| format!("{}\t{line}", group.key))
745        })
746        .collect()
747}
748
749/// Build compact output lines for health results.
750#[must_use]
751pub fn build_health_compact_lines(
752    report: &fallow_output::HealthReport,
753    root: &Path,
754) -> Vec<String> {
755    let mut lines = Vec::new();
756    push_health_score_compact(&mut lines, report);
757    push_vital_signs_compact(&mut lines, report);
758    push_health_findings_compact(&mut lines, &report.findings, root);
759    push_styling_findings_compact(&mut lines, &report.styling_findings, root);
760    push_threshold_overrides_compact(&mut lines, &report.threshold_overrides, root);
761    push_file_scores_compact(&mut lines, &report.file_scores, root);
762    push_coverage_gaps_compact(&mut lines, report, root);
763    push_runtime_sections_compact(&mut lines, report, root);
764    push_hotspots_compact(&mut lines, &report.hotspots, root);
765    push_change_coupling_compact(&mut lines, report.change_coupling.as_ref(), root);
766    push_health_trend_compact(&mut lines, report);
767    push_refactoring_targets_compact(&mut lines, &report.targets, root);
768    lines
769}
770
771fn push_styling_findings_compact(
772    lines: &mut Vec<String>,
773    findings: &[fallow_output::StylingFinding],
774    root: &Path,
775) {
776    for finding in findings {
777        let relative = compact_path(Path::new(&finding.path), root);
778        let severity = match finding.effective_severity {
779            fallow_output::StylingFindingSeverity::Error => "error",
780            fallow_output::StylingFindingSeverity::Warn => "warn",
781        };
782        let value = compact_field_value(&finding.value);
783        lines.push(format!(
784            "{}:{}:{}:{}:severity={},value={}",
785            finding.code, relative, finding.line, finding.sub_kind, severity, value
786        ));
787    }
788}
789
790/// Compact records for the diff-risk findings of `fallow audit`.
791///
792/// Format: `<rule>:<path>:<line>:<evidence>,severity=<severity>[,kind=<kind>]`.
793/// The paths are already root-relative. The line is `0` when the finding is
794/// about the whole file.
795#[must_use]
796pub fn build_diff_risk_compact_lines(report: &fallow_output::DiffRiskReport) -> Vec<String> {
797    report
798        .findings
799        .iter()
800        .map(|finding| {
801            let kind = finding
802                .kind
803                .map_or_else(String::new, |kind| format!(",kind={}", kind.code()));
804            format!(
805                "{}:{}:{}:{},severity={}{kind}",
806                finding.rule.code(),
807                normalize_uri(&finding.path),
808                finding.line.unwrap_or(0),
809                compact_field_value(&finding.evidence),
810                finding.severity.code(),
811            )
812        })
813        .collect()
814}
815
816fn compact_field_value(value: &str) -> String {
817    value
818        .replace([':', ',', '\n', '\r'], " ")
819        .split_whitespace()
820        .collect::<Vec<_>>()
821        .join(" ")
822}
823
824fn push_threshold_overrides_compact(
825    lines: &mut Vec<String>,
826    entries: &[fallow_output::ThresholdOverrideState],
827    root: &Path,
828) {
829    for entry in entries {
830        let status = match entry.status {
831            fallow_output::ThresholdOverrideStatus::Active => "active",
832            fallow_output::ThresholdOverrideStatus::Stale => "stale",
833            fallow_output::ThresholdOverrideStatus::Insufficient => "insufficient",
834            fallow_output::ThresholdOverrideStatus::NoMatch => "no_match",
835        };
836        let target = entry.path.as_ref().map_or_else(
837            || "no-match".to_string(),
838            |path| entry.target_label(&compact_path(path, root)),
839        );
840        let dimension = threshold_override_dimension_label(entry.dimension);
841        let metrics = entry.metrics.map_or(String::new(), |metrics| {
842            let crap = metrics
843                .crap
844                .map_or(String::new(), |value| format!(",crap={value:.1}"));
845            let line_count = metrics
846                .line_count
847                .map_or(String::new(), |value| format!(",lines={value}"));
848            format!(
849                ",cyclomatic={},cognitive={}{}{}",
850                metrics.cyclomatic, metrics.cognitive, line_count, crap
851            )
852        });
853        let outstanding = if entry.outstanding.is_empty() {
854            String::new()
855        } else {
856            format!(
857                ",outstanding={}",
858                entry
859                    .outstanding
860                    .iter()
861                    .map(|value| threshold_override_dimension_label(*value))
862                    .collect::<Vec<_>>()
863                    .join("|")
864            )
865        };
866        lines.push(format!(
867            "threshold-override:{}:{}:{}:{}{}{}",
868            entry.override_index, dimension, status, target, metrics, outstanding
869        ));
870    }
871}
872
873fn threshold_override_dimension_label(
874    dimension: fallow_output::ThresholdOverrideDimension,
875) -> &'static str {
876    match dimension {
877        fallow_output::ThresholdOverrideDimension::Complexity => "complexity",
878        fallow_output::ThresholdOverrideDimension::Crap => "crap",
879    }
880}
881
882fn push_health_score_compact(lines: &mut Vec<String>, report: &fallow_output::HealthReport) {
883    if let Some(ref hs) = report.health_score {
884        lines.push(format!("health-score:{:.1}:{}", hs.score, hs.grade));
885    }
886}
887
888fn push_vital_signs_compact(lines: &mut Vec<String>, report: &fallow_output::HealthReport) {
889    if let Some(ref vs) = report.vital_signs {
890        let mut parts = Vec::new();
891        if vs.total_loc > 0 {
892            parts.push(format!("total_loc={}", vs.total_loc));
893        }
894        parts.push(format!("avg_cyclomatic={:.1}", vs.avg_cyclomatic));
895        parts.push(format!("p90_cyclomatic={}", vs.p90_cyclomatic));
896        if let Some(v) = vs.dead_file_pct {
897            parts.push(format!("dead_file_pct={v:.1}"));
898        }
899        if let Some(v) = vs.dead_export_pct {
900            parts.push(format!("dead_export_pct={v:.1}"));
901        }
902        if let Some(v) = vs.maintainability_avg {
903            parts.push(format!("maintainability_avg={v:.1}"));
904        }
905        if let Some(v) = vs.hotspot_count {
906            parts.push(format!("hotspot_count={v}"));
907        }
908        if let Some(v) = vs.circular_dep_count {
909            parts.push(format!("circular_dep_count={v}"));
910        }
911        if let Some(v) = vs.unused_dep_count {
912            parts.push(format!("unused_dep_count={v}"));
913        }
914        lines.push(format!("vital-signs:{}", parts.join(",")));
915        push_cyclomatic_population_compact(lines, vs);
916    }
917}
918
919fn push_cyclomatic_population_compact(lines: &mut Vec<String>, vs: &fallow_output::VitalSigns) {
920    let Some(population) = &vs.cyclomatic_population else {
921        return;
922    };
923    for (kind, group) in [
924        ("functions", &population.functions),
925        ("modules", &population.modules),
926        ("templates", &population.templates),
927    ] {
928        let max = group
929            .max
930            .map_or_else(|| "null".to_string(), |value| value.to_string());
931        lines.push(format!(
932            "cyclomatic-population:{kind}:count={},sum={},max={max}",
933            group.count, group.sum
934        ));
935    }
936}
937
938/// Serde-name mirror of `ExceededThreshold` for the compact line grammar.
939fn exceeded_compact_label(exceeded: fallow_output::ExceededThreshold) -> &'static str {
940    match exceeded {
941        fallow_output::ExceededThreshold::Cyclomatic => "cyclomatic",
942        fallow_output::ExceededThreshold::Cognitive => "cognitive",
943        fallow_output::ExceededThreshold::Both => "both",
944        fallow_output::ExceededThreshold::Crap => "crap",
945        fallow_output::ExceededThreshold::CyclomaticCrap => "cyclomatic_crap",
946        fallow_output::ExceededThreshold::CognitiveCrap => "cognitive_crap",
947        fallow_output::ExceededThreshold::All => "all",
948        fallow_output::ExceededThreshold::FileLines => "file_lines",
949    }
950}
951
952fn push_health_findings_compact(
953    lines: &mut Vec<String>,
954    findings: &[fallow_output::HealthFinding],
955    root: &Path,
956) {
957    for finding in findings {
958        let relative = compact_path(&finding.path, root);
959        let severity = match finding.severity {
960            fallow_output::FindingSeverity::Critical => "critical",
961            fallow_output::FindingSeverity::High => "high",
962            fallow_output::FindingSeverity::Moderate => "moderate",
963        };
964        let crap_suffix = match finding.crap {
965            Some(crap) => {
966                let coverage = finding
967                    .coverage_pct
968                    .map(|pct| format!(",coverage_pct={pct:.1}"))
969                    .unwrap_or_default();
970                format!(",crap={crap:.1}{coverage}")
971            }
972            None => String::new(),
973        };
974        let file_lines_suffix = finding
975            .max_file_lines
976            .map(|max| format!(",line_count={},max_file_lines={max}", finding.line_count))
977            .unwrap_or_default();
978        // The `high-complexity:` row prefix is deliberately kept even for a
979        // CRAP-only breach (other machine formats route that to
980        // `fallow/high-crap-score`): renaming a line prefix breaks grep-based CI
981        // consumers, and `exceeded=` carries the dimension instead (issue #2163).
982        lines.push(format!(
983            "high-complexity:{}:{}:{}:cyclomatic={},cognitive={},severity={},exceeded={}{}{}",
984            relative,
985            finding.line,
986            finding.name,
987            finding.cyclomatic,
988            finding.cognitive,
989            severity,
990            exceeded_compact_label(finding.exceeded),
991            crap_suffix,
992            file_lines_suffix,
993        ));
994    }
995}
996
997fn push_file_scores_compact(
998    lines: &mut Vec<String>,
999    scores: &[fallow_output::FileHealthScore],
1000    root: &Path,
1001) {
1002    for score in scores {
1003        let relative = compact_path(&score.path, root);
1004        lines.push(format!(
1005            "file-score:{}:mi={:.1},fan_in={},fan_out={},dead={:.2},density={:.2},crap_max={:.1},crap_above={}",
1006            relative,
1007            score.maintainability_index,
1008            score.fan_in,
1009            score.fan_out,
1010            score.dead_code_ratio,
1011            score.complexity_density,
1012            score.crap_max,
1013            score.crap_above_threshold,
1014        ));
1015    }
1016}
1017
1018fn push_coverage_gaps_compact(
1019    lines: &mut Vec<String>,
1020    report: &fallow_output::HealthReport,
1021    root: &Path,
1022) {
1023    if let Some(ref gaps) = report.coverage_gaps {
1024        lines.push(format!(
1025            "coverage-gap-summary:runtime_files={},covered_files={},file_coverage_pct={:.1},untested_files={},untested_exports={}",
1026            gaps.summary.runtime_files,
1027            gaps.summary.covered_files,
1028            gaps.summary.file_coverage_pct,
1029            gaps.summary.untested_files,
1030            gaps.summary.untested_exports,
1031        ));
1032        for item in &gaps.files {
1033            let relative = compact_path(&item.file.path, root);
1034            lines.push(format!(
1035                "untested-file:{}:value_exports={}",
1036                relative, item.file.value_export_count,
1037            ));
1038        }
1039        for item in &gaps.exports {
1040            let relative = compact_path(&item.export.path, root);
1041            lines.push(format!(
1042                "untested-export:{}:{}:{}",
1043                relative, item.export.line, item.export.export_name,
1044            ));
1045        }
1046    }
1047}
1048
1049fn push_runtime_sections_compact(
1050    lines: &mut Vec<String>,
1051    report: &fallow_output::HealthReport,
1052    root: &Path,
1053) {
1054    if let Some(ref production) = report.runtime_coverage {
1055        lines.extend(build_runtime_coverage_compact_lines(production, root));
1056    }
1057    if let Some(ref intelligence) = report.coverage_intelligence {
1058        lines.extend(build_coverage_intelligence_compact_lines(
1059            intelligence,
1060            root,
1061        ));
1062    }
1063}
1064
1065fn compact_ownership_suffix(ownership: Option<&fallow_output::OwnershipMetrics>) -> String {
1066    ownership.map_or_else(String::new, |o| {
1067        let mut parts = vec![
1068            format!("bus={}", o.bus_factor),
1069            format!("contributors={}", o.contributor_count),
1070            format!("top={}", o.top_contributor.identifier),
1071            format!("top_share={:.3}", o.top_contributor.share),
1072        ];
1073        if let Some(owner) = &o.declared_owner {
1074            parts.push(format!("owner={owner}"));
1075        }
1076        if let Some(unowned) = o.unowned {
1077            parts.push(format!("unowned={unowned}"));
1078        }
1079        let state = match o.ownership_state {
1080            fallow_output::OwnershipState::Active => "active",
1081            fallow_output::OwnershipState::Unowned => "unowned",
1082            fallow_output::OwnershipState::DeclaredInactive => "declared_inactive",
1083            fallow_output::OwnershipState::Drifting => "drifting",
1084        };
1085        parts.push(format!("ownership_state={state}"));
1086        if o.drift {
1087            parts.push("drift=true".to_string());
1088        }
1089        format!(",{}", parts.join(","))
1090    })
1091}
1092
1093fn push_hotspots_compact(
1094    lines: &mut Vec<String>,
1095    hotspots: &[fallow_output::HotspotFinding],
1096    root: &Path,
1097) {
1098    for entry in hotspots {
1099        let relative = compact_path(&entry.path, root);
1100        let ownership_suffix = compact_ownership_suffix(entry.ownership.as_ref());
1101        lines.push(format!(
1102            "hotspot:{}:score={:.1},commits={},churn={},density={:.2},fan_in={},trend={}{}",
1103            relative,
1104            entry.score,
1105            entry.commits,
1106            entry.lines_added + entry.lines_deleted,
1107            entry.complexity_density,
1108            entry.fan_in,
1109            entry.trend,
1110            ownership_suffix,
1111        ));
1112    }
1113}
1114
1115/// One line per hidden change-coupling pair:
1116/// `change-coupling:<path_a>:<path_b>:degree=..,shared=..,commits_a=..,commits_b=..,strong=..`.
1117fn push_change_coupling_compact(
1118    lines: &mut Vec<String>,
1119    coupling: Option<&fallow_output::ChangeCouplingReport>,
1120    root: &Path,
1121) {
1122    let Some(coupling) = coupling else {
1123        return;
1124    };
1125    for pair in &coupling.pairs {
1126        lines.push(format!(
1127            "change-coupling:{}:{}:degree={:.2},shared={},commits_a={},commits_b={},strong={}",
1128            compact_path(&pair.path_a, root),
1129            compact_path(&pair.path_b, root),
1130            pair.degree,
1131            pair.shared_revisions,
1132            pair.revisions_a,
1133            pair.revisions_b,
1134            pair.strong,
1135        ));
1136    }
1137}
1138
1139fn push_health_trend_compact(lines: &mut Vec<String>, report: &fallow_output::HealthReport) {
1140    if let Some(ref trend) = report.health_trend {
1141        if let Some(current) = report.health_score.as_ref()
1142            && trend.compared_to.score.is_some()
1143            && !trend.metrics.iter().any(|metric| metric.name == "score")
1144            && fallow_output::health_score_comparison_note(
1145                trend.compared_to.score_formula_version,
1146                Some(current.formula_version),
1147            )
1148            .is_some()
1149        {
1150            let previous_formula = trend
1151                .compared_to
1152                .score_formula_version
1153                .map_or_else(|| "unknown".to_owned(), |version| version.to_string());
1154            lines.push(format!(
1155                "trend:score-omitted:previous_formula={previous_formula},current_formula={}",
1156                current.formula_version,
1157            ));
1158        }
1159        lines.push(format!(
1160            "trend:overall:direction={}",
1161            trend.overall_direction.label()
1162        ));
1163        for m in &trend.metrics {
1164            lines.push(format!(
1165                "trend:{}:previous={:.1},current={:.1},delta={:+.1},direction={}",
1166                m.name,
1167                m.previous,
1168                m.current,
1169                m.delta,
1170                m.direction.label(),
1171            ));
1172        }
1173    }
1174}
1175
1176fn push_refactoring_targets_compact(
1177    lines: &mut Vec<String>,
1178    targets: &[fallow_output::RefactoringTargetFinding],
1179    root: &Path,
1180) {
1181    for target in targets {
1182        let relative = compact_path(&target.path, root);
1183        let category = target.category.compact_label();
1184        let effort = target.effort.label();
1185        let confidence = target.confidence.label();
1186        lines.push(format!(
1187            "refactoring-target:{}:priority={:.1},efficiency={:.1},category={},effort={},confidence={}:{}",
1188            relative,
1189            target.priority,
1190            target.efficiency,
1191            category,
1192            effort,
1193            confidence,
1194            target.recommendation,
1195        ));
1196    }
1197}
1198
1199fn build_runtime_coverage_compact_lines(
1200    production: &fallow_output::RuntimeCoverageReport,
1201    root: &Path,
1202) -> Vec<String> {
1203    let summary = &production.summary;
1204    let null_or = |count: Option<usize>| count.map_or_else(|| "null".to_owned(), |n| n.to_string());
1205    let mut lines = vec![format!(
1206        "runtime-coverage-summary:functions_tracked={},functions_hit={},functions_unhit={},functions_untracked={},coverage_percent={},trace_count={},period_days={},deployments_seen={}",
1207        null_or(summary.functions_tracked),
1208        summary.functions_hit,
1209        null_or(summary.functions_unhit),
1210        summary.functions_untracked,
1211        summary
1212            .coverage_percent
1213            .map_or_else(|| "null".to_owned(), |percent| format!("{percent:.1}")),
1214        production.summary.trace_count,
1215        production.summary.period_days,
1216        production.summary.deployments_seen,
1217    )];
1218    for finding in &production.findings {
1219        let relative = compact_path(&finding.path, root);
1220        let invocations = finding
1221            .invocations
1222            .map_or_else(|| "null".to_owned(), |hits| hits.to_string());
1223        lines.push(format!(
1224            "runtime-coverage:{}:{}:{}:id={},verdict={},invocations={},confidence={}",
1225            relative,
1226            finding.line,
1227            finding.function,
1228            finding.id,
1229            finding.verdict,
1230            invocations,
1231            finding.confidence,
1232        ));
1233    }
1234    for entry in &production.hot_paths {
1235        let relative = compact_path(&entry.path, root);
1236        lines.push(format!(
1237            "production-hot-path:{}:{}:{}:id={},invocations={},percentile={}",
1238            relative, entry.line, entry.function, entry.id, entry.invocations, entry.percentile,
1239        ));
1240    }
1241    lines
1242}
1243
1244fn build_coverage_intelligence_compact_lines(
1245    intelligence: &fallow_output::CoverageIntelligenceReport,
1246    root: &Path,
1247) -> Vec<String> {
1248    let mut lines = vec![format!(
1249        "coverage-intelligence-summary:verdict={},findings={},risky_changes={},high_confidence_deletes={},review_required={},refactor_carefully={},skipped_ambiguous_matches={}",
1250        intelligence.verdict,
1251        intelligence.summary.findings,
1252        intelligence.summary.risky_changes,
1253        intelligence.summary.high_confidence_deletes,
1254        intelligence.summary.review_required,
1255        intelligence.summary.refactor_carefully,
1256        intelligence.summary.skipped_ambiguous_matches,
1257    )];
1258    for finding in &intelligence.findings {
1259        let relative = compact_path(&finding.path, root);
1260        let identity = finding.identity.as_deref().unwrap_or("-");
1261        let signals = finding
1262            .signals
1263            .iter()
1264            .map(ToString::to_string)
1265            .collect::<Vec<_>>()
1266            .join("+");
1267        lines.push(format!(
1268            "coverage-intelligence:{}:{}:{}:id={},verdict={},recommendation={},confidence={},signals={}",
1269            relative,
1270            finding.line,
1271            identity,
1272            finding.id,
1273            finding.verdict,
1274            finding.recommendation,
1275            finding.confidence,
1276            signals,
1277        ));
1278    }
1279    lines
1280}
1281
1282/// Build compact output lines for duplication results.
1283#[must_use]
1284pub fn build_duplication_compact_lines(report: &DuplicationReport, root: &Path) -> Vec<String> {
1285    let fingerprints = CloneFingerprintSet::from_groups(&report.clone_groups);
1286    let mut lines = Vec::new();
1287    for (index, group) in report.clone_groups.iter().enumerate() {
1288        let fingerprint = fingerprints.fingerprint_for_group(group);
1289        for instance in &group.instances {
1290            lines.push(format!(
1291                "code-duplication:{}:{}-{}:fingerprint={},group={},tokens={},lines={},instances={}{}",
1292                compact_path(&instance.file, root),
1293                instance.start_line,
1294                instance.end_line,
1295                fingerprint,
1296                index + 1,
1297                group.token_count,
1298                group.line_count,
1299                group.instances.len(),
1300                if instance.is_symlink {
1301                    ",symlink=true"
1302                } else {
1303                    ""
1304                },
1305            ));
1306        }
1307    }
1308    lines
1309}
1310
1311#[cfg(test)]
1312mod tests {
1313    use std::path::PathBuf;
1314
1315    use fallow_types::duplicates::{CloneGroup, CloneInstance, DuplicationStats};
1316    use fallow_types::output_dead_code::UnusedFileFinding;
1317    use fallow_types::results::{AnalysisResults, UnusedFile};
1318
1319    use super::*;
1320
1321    fn diff_risk_finding(
1322        rule: fallow_output::DiffRiskRule,
1323        kind: Option<fallow_output::WeakenedTestsKind>,
1324        path: &str,
1325        line: Option<u32>,
1326        evidence: &str,
1327        severity: fallow_output::DiffRiskSeverity,
1328    ) -> fallow_output::DiffRiskFinding {
1329        fallow_output::DiffRiskFinding {
1330            rule,
1331            kind,
1332            path: path.to_owned(),
1333            line,
1334            message: "m".to_owned(),
1335            evidence: evidence.to_owned(),
1336            severity,
1337            introduced: true,
1338            related: Vec::new(),
1339            actions: Vec::new(),
1340            suppression: None,
1341        }
1342    }
1343
1344    #[test]
1345    fn diff_risk_compact_lines_follow_the_tag_path_line_subject_grammar() {
1346        let report = fallow_output::DiffRiskReport {
1347            findings: vec![
1348                diff_risk_finding(
1349                    fallow_output::DiffRiskRule::WeakenedTests,
1350                    Some(fallow_output::WeakenedTestsKind::SkipOnly),
1351                    "src/a.test.ts",
1352                    Some(4),
1353                    "it.skip",
1354                    fallow_output::DiffRiskSeverity::Warn,
1355                ),
1356                diff_risk_finding(
1357                    fallow_output::DiffRiskRule::WeakenedTests,
1358                    Some(fallow_output::WeakenedTestsKind::RemovedTests),
1359                    "src/b.test.ts",
1360                    None,
1361                    "test cases: 3 -> 1",
1362                    fallow_output::DiffRiskSeverity::Error,
1363                ),
1364                diff_risk_finding(
1365                    fallow_output::DiffRiskRule::AddedDependency,
1366                    None,
1367                    "package.json",
1368                    Some(7),
1369                    "left-pad@^1.3.0 (dependencies)",
1370                    fallow_output::DiffRiskSeverity::Warn,
1371                ),
1372            ],
1373        };
1374        assert_eq!(
1375            build_diff_risk_compact_lines(&report),
1376            vec![
1377                "weakened-tests:src/a.test.ts:4:it.skip,severity=warn,kind=skip-only".to_owned(),
1378                "weakened-tests:src/b.test.ts:0:test cases 3 -> 1,severity=error,kind=removed-tests"
1379                    .to_owned(),
1380                "added-dependency:package.json:7:left-pad@^1.3.0 (dependencies),severity=warn"
1381                    .to_owned(),
1382            ]
1383        );
1384    }
1385
1386    #[test]
1387    fn compact_cycles_preserve_empty_self_loop_and_cross_package_output() {
1388        use fallow_types::output_dead_code::{CircularDependencyFinding, ReExportCycleFinding};
1389        use fallow_types::results::{CircularDependency, ReExportCycle, ReExportCycleKind};
1390
1391        let root = Path::new("/project");
1392        for (files, cross_package, expected) in [
1393            (vec![], false, "circular-dependency::7:"),
1394            (
1395                vec![root.join("src/a.ts")],
1396                false,
1397                "circular-dependency:src/a.ts:7:src/a.ts → src/a.ts",
1398            ),
1399            (
1400                vec![root.join("src/a.ts"), root.join("src/b.ts")],
1401                true,
1402                "circular-dependency:src/a.ts:7:src/a.ts → src/b.ts → src/a.ts (cross-package)",
1403            ),
1404        ] {
1405            let mut results = AnalysisResults::default();
1406            results
1407                .circular_dependencies
1408                .push(CircularDependencyFinding {
1409                    finding_id: None,
1410                    cycle: CircularDependency {
1411                        length: files.len(),
1412                        files,
1413                        line: 7,
1414                        col: 0,
1415                        edges: vec![],
1416                        is_cross_package: cross_package,
1417                    },
1418                    actions: vec![],
1419                    introduced: None,
1420                    effective_severity: None,
1421                });
1422            assert_eq!(build_compact_lines(&results, root), vec![expected]);
1423        }
1424        for (files, kind, expected) in [
1425            (vec![], ReExportCycleKind::MultiNode, "re-export-cycle::"),
1426            (
1427                vec![root.join("src/a.ts")],
1428                ReExportCycleKind::SelfLoop,
1429                "re-export-cycle:src/a.ts:src/a.ts (self-loop)",
1430            ),
1431            (
1432                vec![root.join("src/a.ts"), root.join("src/b.ts")],
1433                ReExportCycleKind::MultiNode,
1434                "re-export-cycle:src/a.ts:src/a.ts <-> src/b.ts",
1435            ),
1436        ] {
1437            let mut results = AnalysisResults::default();
1438            results.re_export_cycles.push(ReExportCycleFinding {
1439                finding_id: None,
1440                cycle: ReExportCycle { files, kind },
1441                actions: vec![],
1442                introduced: None,
1443                effective_severity: None,
1444            });
1445            assert_eq!(build_compact_lines(&results, root), vec![expected]);
1446        }
1447    }
1448
1449    /// A compact record is what a CI script greps to decide what to delete, so
1450    /// a verdict resting on a file the run never read has to say so on the same
1451    /// line. The field rides in the trailing `,key=value` slot duplication
1452    /// records already use, so the leading colon-separated fields a parser
1453    /// splits on are untouched.
1454    #[test]
1455    fn a_caveated_finding_carries_a_trailing_caveat_field() {
1456        use fallow_types::extract::MemberKind;
1457        use fallow_types::output_dead_code::{ReachabilityCaveat, UnusedDependencyFinding};
1458        use fallow_types::results::{UnusedDependency, UnusedExport};
1459
1460        let root = PathBuf::from("/project");
1461        let mut results = AnalysisResults::default();
1462
1463        let mut file = UnusedFileFinding::with_actions(UnusedFile {
1464            path: root.join("src/dead.ts"),
1465        });
1466        file.reachability_caveats = vec![ReachabilityCaveat::IncompleteImportGraph];
1467        results.unused_files.push(file);
1468
1469        let mut export =
1470            fallow_types::output_dead_code::UnusedExportFinding::with_actions(UnusedExport {
1471                path: root.join("src/lib.ts"),
1472                export_name: "needed".to_owned(),
1473                is_type_only: false,
1474                line: 3,
1475                col: 0,
1476                span_start: 0,
1477                is_re_export: false,
1478                deprecated: false,
1479                deprecated_reason: None,
1480            });
1481        export.reachability_caveats = vec![
1482            ReachabilityCaveat::IncompleteFileAnalysis,
1483            ReachabilityCaveat::IncompleteImportGraph,
1484        ];
1485        results.unused_exports.push(export);
1486
1487        let mut dep = UnusedDependencyFinding::with_actions(UnusedDependency {
1488            package_name: "left-pad".to_owned(),
1489            location: fallow_types::results::DependencyLocation::Dependencies,
1490            path: root.join("package.json"),
1491            line: 5,
1492            used_in_workspaces: Vec::new(),
1493            declared_and_imported_in: Vec::new(),
1494        });
1495        dep.reachability_caveats = vec![ReachabilityCaveat::IncompleteImportGraph];
1496        results.unused_dependencies.push(dep);
1497
1498        let member = |parent: &str, name: &str, kind| fallow_types::results::UnusedMember {
1499            path: root.join("src/lib.ts"),
1500            parent_name: parent.to_owned(),
1501            member_name: name.to_owned(),
1502            kind,
1503            line: 7,
1504            col: 2,
1505        };
1506        let mut enum_member = fallow_types::output_dead_code::UnusedEnumMemberFinding::with_actions(
1507            member("Mode", "Legacy", MemberKind::EnumMember),
1508        );
1509        enum_member.reachability_caveats = vec![ReachabilityCaveat::IncompleteImportGraph];
1510        results.unused_enum_members.push(enum_member);
1511
1512        let mut class_member =
1513            fallow_types::output_dead_code::UnusedClassMemberFinding::with_actions(member(
1514                "Widget",
1515                "render",
1516                MemberKind::ClassMethod,
1517            ));
1518        class_member.reachability_caveats = vec![ReachabilityCaveat::IncompleteImportGraph];
1519        results.unused_class_members.push(class_member);
1520
1521        let mut store_member =
1522            fallow_types::output_dead_code::UnusedStoreMemberFinding::with_actions(member(
1523                "useCart",
1524                "subtotal",
1525                MemberKind::StoreMember,
1526            ));
1527        store_member.reachability_caveats = vec![ReachabilityCaveat::IncompleteImportGraph];
1528        results.unused_store_members.push(store_member);
1529
1530        let lines = build_compact_lines(&results, &root);
1531
1532        assert_eq!(
1533            lines,
1534            vec![
1535                "unused-file:src/dead.ts,caveat=incomplete-import-graph",
1536                "unused-export:src/lib.ts:3:needed,caveat=incomplete-file-analysis+incomplete-import-graph",
1537                "unused-dep:left-pad,caveat=incomplete-import-graph",
1538                "unused-enum-member:src/lib.ts:7:Mode.Legacy,caveat=incomplete-import-graph",
1539                "unused-class-member:src/lib.ts:7:Widget.render,caveat=incomplete-import-graph",
1540                "unused-store-member:src/lib.ts:7:useCart.subtotal,caveat=incomplete-import-graph",
1541            ]
1542        );
1543    }
1544
1545    #[test]
1546    fn compact_unused_file_format_uses_relative_paths() {
1547        let root = PathBuf::from("/project");
1548        let mut results = AnalysisResults::default();
1549        results
1550            .unused_files
1551            .push(UnusedFileFinding::with_actions(UnusedFile {
1552                path: root.join("src/dead.ts"),
1553            }));
1554
1555        let lines = build_compact_lines(&results, &root);
1556
1557        assert_eq!(lines, vec!["unused-file:src/dead.ts"]);
1558    }
1559
1560    #[test]
1561    fn grouped_compact_prefixes_each_issue_with_group_key() {
1562        let root = PathBuf::from("/project");
1563        let mut results = AnalysisResults::default();
1564        results
1565            .unused_files
1566            .push(UnusedFileFinding::with_actions(UnusedFile {
1567                path: root.join("src/dead.ts"),
1568            }));
1569        let groups = vec![ResultGroup {
1570            key: "team-a".to_owned(),
1571            owners: Some(vec!["@team-a".to_owned()]),
1572            results,
1573        }];
1574
1575        let lines = build_grouped_compact_lines(&groups, &root);
1576
1577        assert_eq!(lines, vec!["team-a\tunused-file:src/dead.ts"]);
1578    }
1579
1580    #[test]
1581    fn duplication_compact_lines_include_stable_group_context() {
1582        let root = PathBuf::from("/project");
1583        let report = DuplicationReport {
1584            clone_groups: vec![CloneGroup {
1585                instances: vec![CloneInstance {
1586                    is_symlink: false,
1587                    file: root.join("src/a.ts"),
1588                    start_line: 2,
1589                    end_line: 6,
1590                    start_col: 0,
1591                    end_col: 10,
1592                    fragment: "const duplicated = true;".to_owned(),
1593                }],
1594                token_count: 12,
1595                line_count: 5,
1596                similarity: None,
1597            }],
1598            clone_families: Vec::new(),
1599            mirrored_directories: Vec::new(),
1600            stats: DuplicationStats::default(),
1601        };
1602
1603        let lines = build_duplication_compact_lines(&report, &root);
1604
1605        assert_eq!(lines.len(), 1);
1606        assert!(lines[0].starts_with("code-duplication:src/a.ts:2-6:fingerprint="));
1607        assert!(lines[0].contains(",group=1,tokens=12,lines=5,instances=1"));
1608        assert!(!lines[0].contains("symlink"));
1609    }
1610
1611    #[test]
1612    fn duplication_compact_lines_mark_symlinked_instances() {
1613        let root = PathBuf::from("/project");
1614        let instance = |path: &str, is_symlink: bool| CloneInstance {
1615            is_symlink,
1616            file: root.join(path),
1617            start_line: 1,
1618            end_line: 5,
1619            start_col: 0,
1620            end_col: 0,
1621            fragment: String::new(),
1622        };
1623        let report = DuplicationReport {
1624            clone_groups: vec![CloneGroup {
1625                instances: vec![
1626                    instance("src/link.ts", true),
1627                    instance("src/real.ts", false),
1628                ],
1629                token_count: 12,
1630                line_count: 5,
1631                similarity: None,
1632            }],
1633            clone_families: Vec::new(),
1634            mirrored_directories: Vec::new(),
1635            stats: DuplicationStats::default(),
1636        };
1637
1638        let lines = build_duplication_compact_lines(&report, &root);
1639
1640        assert!(lines[0].starts_with("code-duplication:src/link.ts:1-5:"));
1641        assert!(lines[0].ends_with(",instances=2,symlink=true"));
1642        assert!(lines[1].ends_with(",instances=2"));
1643    }
1644
1645    #[test]
1646    fn health_compact_lines_include_score_and_vital_signs() {
1647        let root = PathBuf::from("/project");
1648        let report = fallow_output::HealthReport {
1649            health_score: Some(fallow_output::HealthScore {
1650                formula_version: 1,
1651                score: 91.2,
1652                grade: "A",
1653                penalties: fallow_output::HealthScorePenalties {
1654                    dead_files: None,
1655                    dead_exports: None,
1656                    complexity: 0.0,
1657                    p90_complexity: 0.0,
1658                    maintainability: None,
1659                    hotspots: None,
1660                    unused_deps: None,
1661                    circular_deps: None,
1662                    unit_size: None,
1663                    coupling: None,
1664                    duplication: None,
1665                    prop_drilling: None,
1666                },
1667            }),
1668            vital_signs: Some(fallow_output::VitalSigns {
1669                total_loc: 120,
1670                avg_cyclomatic: 3.4,
1671                p90_cyclomatic: 8,
1672                ..Default::default()
1673            }),
1674            ..Default::default()
1675        };
1676
1677        let lines = build_health_compact_lines(&report, &root);
1678
1679        assert_eq!(lines[0], "health-score:91.2:A");
1680        assert_eq!(
1681            lines[1],
1682            "vital-signs:total_loc=120,avg_cyclomatic=3.4,p90_cyclomatic=8"
1683        );
1684        assert!(
1685            lines
1686                .iter()
1687                .all(|line| !line.starts_with("cyclomatic-population:"))
1688        );
1689    }
1690
1691    #[test]
1692    fn health_compact_population_rows_preserve_vital_signs_and_order() {
1693        let root = PathBuf::from("/project");
1694        let vitals = fallow_output::VitalSigns {
1695            avg_cyclomatic: 16.0,
1696            p90_cyclomatic: 31,
1697            ..Default::default()
1698        };
1699        let legacy = build_health_compact_lines(
1700            &fallow_output::HealthReport {
1701                vital_signs: Some(vitals.clone()),
1702                ..Default::default()
1703            },
1704            &root,
1705        );
1706        let report = fallow_output::HealthReport {
1707            vital_signs: Some(fallow_output::VitalSigns {
1708                cyclomatic_population: Some(fallow_output::CyclomaticPopulation {
1709                    functions: fallow_output::CyclomaticUnitPopulation {
1710                        count: 1,
1711                        sum: 1,
1712                        max: Some(1),
1713                    },
1714                    modules: fallow_output::CyclomaticUnitPopulation {
1715                        count: 1,
1716                        sum: 31,
1717                        max: Some(31),
1718                    },
1719                    templates: fallow_output::CyclomaticUnitPopulation::default(),
1720                }),
1721                ..vitals
1722            }),
1723            ..Default::default()
1724        };
1725        let lines = build_health_compact_lines(&report, &root);
1726        assert_eq!(lines[0], legacy[0]);
1727        assert_eq!(
1728            &lines[1..],
1729            [
1730                "cyclomatic-population:functions:count=1,sum=1,max=1",
1731                "cyclomatic-population:modules:count=1,sum=31,max=31",
1732                "cyclomatic-population:templates:count=0,sum=0,max=null",
1733            ]
1734        );
1735    }
1736
1737    #[test]
1738    fn health_compact_measured_empty_populations_keep_null_maxima() {
1739        let report = fallow_output::HealthReport {
1740            vital_signs: Some(fallow_output::VitalSigns {
1741                cyclomatic_population: Some(fallow_output::CyclomaticPopulation::default()),
1742                ..Default::default()
1743            }),
1744            ..Default::default()
1745        };
1746        let lines = build_health_compact_lines(&report, &PathBuf::from("/project"));
1747        assert_eq!(
1748            &lines[1..],
1749            [
1750                "cyclomatic-population:functions:count=0,sum=0,max=null",
1751                "cyclomatic-population:modules:count=0,sum=0,max=null",
1752                "cyclomatic-population:templates:count=0,sum=0,max=null",
1753            ]
1754        );
1755    }
1756
1757    #[test]
1758    fn health_compact_lines_include_styling_findings() {
1759        let root = PathBuf::from("/project");
1760        let report = fallow_output::HealthReport {
1761            styling_findings: vec![fallow_output::StylingFinding {
1762                internal: fallow_output::StylingFindingInternal::default(),
1763                code: "css-token-drift".to_string(),
1764                sub_kind: "tailwind-arbitrary-value".to_string(),
1765                path: "/project/src/app.css".to_string(),
1766                line: 6,
1767                value: "--color-brand: rgb(240, 90, 41)".to_string(),
1768                effective_severity: fallow_output::StylingFindingSeverity::Warn,
1769                blast_radius: None,
1770                confidence: None,
1771                agent_disposition: None,
1772                nearest_token: None,
1773                fix_hint: None,
1774                actions: Vec::new(),
1775            }],
1776            ..Default::default()
1777        };
1778
1779        let lines = build_health_compact_lines(&report, &root);
1780
1781        assert_eq!(
1782            lines,
1783            vec![
1784                "css-token-drift:src/app.css:6:tailwind-arbitrary-value:severity=warn,value=--color-brand rgb(240 90 41)"
1785            ]
1786        );
1787    }
1788}