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