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