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