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