Skip to main content

fallow_api/
compact_output.rs

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