Skip to main content

fallow_api/
dupes_output.rs

1//! Shared duplication JSON payload contracts for programmatic consumers.
2
3use std::path::{Path, PathBuf};
4
5use fallow_engine::duplicates::{
6    CloneFingerprintSet, clone_fingerprint, dominant_identifier, fingerprint_for_fragment,
7};
8use fallow_output::{
9    CloneFamilyAction, CloneGroupAction, CodeClimateIssue, CodeClimateIssueInput,
10    CodeClimateSeverity, clone_family_actions, clone_group_actions, codeclimate_fingerprint_hash,
11    normalize_uri,
12};
13use fallow_types::duplicates::{
14    CloneFamily, CloneGroup, CloneInstance, DuplicationReport, DuplicationStats, MirroredDirectory,
15    RefactoringSuggestion, clone_location_spread,
16};
17use fallow_types::envelope::AuditIntroduced;
18use fallow_types::serde_path;
19use serde::Serialize;
20
21/// A clone instance plus its per-instance owner key (for inline JSON / SARIF
22/// rendering).
23///
24/// Each instance carries its own `owner` field alongside the standard
25/// `CloneInstance` shape (file / start_line / end_line / start_col / end_col /
26/// fragment), so consumers can attribute instances to resolver keys without
27/// re-resolving paths.
28#[derive(Debug, Clone, Serialize)]
29#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
30pub struct AttributedInstance {
31    /// The original clone instance.
32    #[serde(flatten)]
33    pub instance: CloneInstance,
34    /// Resolver key for this specific instance (per-instance, not the
35    /// group-level largest-owner).
36    pub owner: String,
37}
38
39/// A clone group annotated with largest-owner attribution and per-instance
40/// owner keys.
41#[derive(Debug, Clone, Serialize)]
42#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
43pub struct AttributedCloneGroup {
44    /// Largest-owner attribution: the resolver key with the most instances in
45    /// this clone group. Ties broken alphabetically (smallest key wins).
46    pub primary_owner: String,
47    /// Number of tokens in the clone group.
48    pub token_count: usize,
49    /// Number of source lines in the clone group.
50    pub line_count: usize,
51    /// Lowest all-pairs similarity for a near-miss clone group.
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    #[cfg_attr(feature = "schema", schemars(with = "f64"))]
54    pub similarity: Option<f64>,
55    /// Each instance carries its own `owner` field alongside the standard
56    /// CloneInstance shape.
57    pub instances: Vec<AttributedInstance>,
58}
59
60impl AttributedCloneGroup {
61    /// Return the report-scoped fingerprint for this attributed group.
62    #[must_use]
63    pub fn fingerprint(&self, fingerprints: &CloneFingerprintSet) -> String {
64        let instances: Vec<_> = self
65            .instances
66            .iter()
67            .map(|instance| instance.instance.clone())
68            .collect();
69        fingerprints.fingerprint_for_parts(&instances, self.token_count, self.line_count)
70    }
71}
72
73/// Wire-shape envelope for an [`AttributedCloneGroup`] finding (per-bucket
74/// duplication attribution emitted under `fallow dupes --group-by`).
75/// Flattens the attributed group and carries the same typed
76/// `CloneGroupAction` array as `CloneGroupFinding`; no `introduced`
77/// field because `fallow audit` does not run on grouped output.
78#[derive(Debug, Clone, Serialize)]
79#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
80pub struct AttributedCloneGroupFinding {
81    /// The underlying attributed clone group.
82    #[serde(flatten)]
83    pub group: AttributedCloneGroup,
84    /// Stable content fingerprint, usually `dup:<8hex>` and widened on rare
85    /// report collisions. Addressable via `fallow dupes --trace dup:<fp>`.
86    /// Computed from the group's instances, so it matches the top-level
87    /// `clone_groups[].fingerprint` for the same clone.
88    pub fingerprint: String,
89    /// Maximum directory-tree or same-file line distance between instances.
90    pub spread: usize,
91    /// Suggested next steps. Always emitted.
92    pub actions: Vec<CloneGroupAction>,
93}
94
95impl AttributedCloneGroupFinding {
96    /// Build the wrapper from an [`AttributedCloneGroup`].
97    #[allow(
98        dead_code,
99        reason = "kept for focused wrapper tests and non-report construction paths"
100    )]
101    #[must_use]
102    pub fn with_actions(group: AttributedCloneGroup) -> Self {
103        let fingerprint = group.instances.first().map_or_else(
104            || fingerprint_for_fragment(""),
105            |ai| fingerprint_for_fragment(&ai.instance.fragment),
106        );
107        Self::with_fingerprint(group, fingerprint)
108    }
109
110    /// Build the wrapper with a precomputed report-scoped fingerprint.
111    #[must_use]
112    pub fn with_fingerprint(group: AttributedCloneGroup, fingerprint: String) -> Self {
113        let spread = clone_location_spread(group.instances.iter().map(|instance| {
114            (
115                instance.instance.file.as_path(),
116                instance.instance.start_line,
117                instance.instance.end_line,
118            )
119        }));
120        let actions = clone_group_actions(group.line_count, group.instances.len());
121        Self {
122            group,
123            fingerprint,
124            spread,
125            actions,
126        }
127    }
128}
129
130/// A single grouped duplication bucket. Per-group `stats` are dedup-aware and
131/// computed over the FULL group BEFORE any `--top` truncation.
132#[derive(Debug, Clone, Serialize)]
133#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
134pub struct DuplicationGroup {
135    /// Group label (owner / directory / package / section). `(unowned)` for
136    /// files with no CODEOWNERS rule, `(no section)` for pre-section rules in
137    /// section mode.
138    pub key: String,
139    /// Dedup-aware aggregate stats for the group.
140    pub stats: DuplicationStats,
141    /// Clone groups attributed to this owner, each wrapped with the typed
142    /// `actions[]` array. Each group's `primary_owner` is its largest-owner
143    /// key; per-instance `owner` lets consumers see cross-bucket fan-out
144    /// without re-resolving paths.
145    pub clone_groups: Vec<AttributedCloneGroupFinding>,
146    /// Clone families overlapping this bucket, each wrapped with the typed
147    /// `actions[]` array.
148    pub clone_families: Vec<CloneFamilyFinding>,
149}
150
151/// Wrapper carrying the resolver mode label and grouped buckets.
152#[derive(Debug, Clone, Serialize)]
153pub struct DuplicationGrouping {
154    /// Resolver mode label (`"owner"`, `"directory"`, `"package"`, `"section"`).
155    pub mode: &'static str,
156    /// One bucket per resolver key.
157    pub groups: Vec<DuplicationGroup>,
158}
159
160/// Why the audit new-only gate demoted an introduced clone group to
161/// inherited. Serializes as a kebab-case string on the wire (for example
162/// `"no-added-lines"`).
163///
164/// Further variants may be added in later releases; consumers should treat an
165/// unknown value as "some demotion reason" rather than failing.
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
167#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
168#[serde(rename_all = "kebab-case")]
169pub enum CloneDemotionReason {
170    /// No instance of the group overlaps an added line in the run's diff: the
171    /// group was re-shaped by removals elsewhere in the changeset, not written
172    /// by it (issue #2164).
173    NoAddedLines,
174}
175
176impl CloneDemotionReason {
177    /// The kebab-case wire literal, obtained from the serde representation so
178    /// human output and JSON cannot diverge.
179    #[must_use]
180    pub fn wire_name(self) -> String {
181        match serde_json::to_value(self) {
182            Ok(serde_json::Value::String(name)) => name,
183            _ => String::new(),
184        }
185    }
186}
187
188/// Wire-shape envelope for a [`CloneGroup`] finding. Flattens the bare
189/// group via `#[serde(flatten)]` and carries a typed `actions` array plus
190/// the optional audit-mode `introduced` flag. The typed envelope replaced
191/// the legacy JSON post-pass injection; a guard test in
192/// `crates/cli/src/report/json.rs` rejects any reintroduced post-pass.
193#[derive(Debug, Clone, Serialize)]
194#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
195pub struct CloneGroupFinding {
196    /// The underlying clone group.
197    #[serde(flatten)]
198    pub group: CloneGroup,
199    /// Stable content fingerprint, usually `dup:<8hex>` and widened on rare
200    /// report collisions. Addressable via `fallow dupes --trace dup:<fp>` (and
201    /// the `trace_clone` MCP tool) to deep-dive this group; shown alongside
202    /// each group in the human listing.
203    pub fingerprint: String,
204    /// Maximum directory-tree or same-file line distance between instances.
205    pub spread: usize,
206    /// Best-effort human-readable name for the clone: the dominant repeated
207    /// identifier across the duplicated fragment (e.g. a shared `parseCsv`
208    /// function). `None` when the clone has no clear dominant name (generic or
209    /// tied identifiers); consumers then fall back to a file-based label. Lets
210    /// editors and agents label a clone by what it is rather than an opaque
211    /// ordinal.
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub suggested_name: Option<String>,
214    /// Suggested next steps: an `extract-shared` primary and a
215    /// `suppress-line` secondary. Always emitted (possibly empty for
216    /// forward-compat).
217    pub actions: Vec<CloneGroupAction>,
218    /// Set by the audit pass when this clone group is introduced relative
219    /// to the merge-base. `None` when serialized directly from Rust.
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub introduced: Option<AuditIntroduced>,
222    /// Set only by `fallow audit` under `--gate new-only`, on groups whose
223    /// `introduced` flag the gate demoted to `false`: why the demotion
224    /// happened. `None` everywhere else, including `fallow dupes
225    /// --format json` (issue #2220).
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub demotion_reason: Option<CloneDemotionReason>,
228}
229
230impl CloneGroupFinding {
231    /// Build the wrapper from a raw [`CloneGroup`].
232    #[allow(
233        dead_code,
234        reason = "kept for focused wrapper tests and non-report construction paths"
235    )]
236    #[must_use]
237    pub fn with_actions(group: CloneGroup) -> Self {
238        let fingerprint = clone_fingerprint(&group.instances);
239        Self::with_fingerprint(group, fingerprint)
240    }
241
242    /// Build the wrapper with a precomputed report-scoped fingerprint.
243    #[must_use]
244    pub fn with_fingerprint(group: CloneGroup, fingerprint: String) -> Self {
245        let spread = group.spread();
246        let suggested_name = dominant_identifier(&group);
247        let actions = clone_group_actions(group.line_count, group.instances.len());
248        Self {
249            fingerprint,
250            spread,
251            suggested_name,
252            group,
253            actions,
254            introduced: None,
255            demotion_reason: None,
256        }
257    }
258}
259
260/// Wire-shape envelope for a [`CloneFamily`] finding.
261///
262/// Unlike most `*Finding` wrappers this one is NOT `#[serde(flatten)]` over
263/// the bare [`CloneFamily`], because the family's nested
264/// `groups: Vec<CloneGroup>` field needs to carry the typed
265/// `CloneGroupFinding` wrapper too (so every nested clone group gets its
266/// own `actions[]` array, matching the legacy post-pass behavior; see issue
267/// #393 regression test). The wire shape stays byte-identical to the
268/// previous post-pass output. No `introduced` field because `fallow audit`
269/// attributes clone groups (not families) when running against a base ref.
270#[derive(Debug, Clone, Serialize)]
271#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
272pub struct CloneFamilyFinding {
273    /// The files involved in this family.
274    #[serde(serialize_with = "serde_path::serialize_vec")]
275    pub files: Vec<PathBuf>,
276    /// Clone groups belonging to this family, each wrapped with typed
277    /// `actions[]` so consumers that read `clone_families[].groups[]`
278    /// directly see the same shape as the top-level `clone_groups[]`.
279    pub groups: Vec<CloneGroupFinding>,
280    /// Total number of duplicated lines across all groups.
281    pub total_duplicated_lines: usize,
282    /// Total number of duplicated tokens across all groups.
283    pub total_duplicated_tokens: usize,
284    /// Refactoring suggestions for this family.
285    pub suggestions: Vec<RefactoringSuggestion>,
286    /// Suggested next steps: an `extract-shared` primary, one
287    /// `apply-suggestion` per `RefactoringSuggestion` on the family, and
288    /// a trailing `suppress-line`. Always emitted (possibly empty for
289    /// forward-compat).
290    pub actions: Vec<CloneFamilyAction>,
291}
292
293impl CloneFamilyFinding {
294    /// Build the wrapper from a raw [`CloneFamily`].
295    #[allow(
296        dead_code,
297        reason = "kept for focused wrapper tests and non-report construction paths"
298    )]
299    #[must_use]
300    pub fn with_actions(family: CloneFamily) -> Self {
301        let fingerprints = CloneFingerprintSet::from_groups(&family.groups);
302        Self::with_fingerprints(family, &fingerprints)
303    }
304
305    /// Build the wrapper using the report-scoped fingerprint assignment shared
306    /// by all duplication output surfaces.
307    #[must_use]
308    pub fn with_fingerprints(family: CloneFamily, fingerprints: &CloneFingerprintSet) -> Self {
309        let actions = build_clone_family_actions(
310            &family.groups,
311            family.total_duplicated_lines,
312            &family.suggestions,
313        );
314        Self {
315            files: family.files,
316            groups: family
317                .groups
318                .into_iter()
319                .map(|group| {
320                    let fingerprint = fingerprints.fingerprint_for_group(&group);
321                    CloneGroupFinding::with_fingerprint(group, fingerprint)
322                })
323                .collect(),
324            total_duplicated_lines: family.total_duplicated_lines,
325            total_duplicated_tokens: family.total_duplicated_tokens,
326            suggestions: family.suggestions,
327            actions,
328        }
329    }
330}
331
332fn build_clone_family_actions(
333    groups: &[CloneGroup],
334    total_duplicated_lines: usize,
335    suggestions: &[RefactoringSuggestion],
336) -> Vec<CloneFamilyAction> {
337    clone_family_actions(
338        groups.len(),
339        total_duplicated_lines,
340        suggestions
341            .iter()
342            .map(|suggestion| suggestion.description.as_str()),
343    )
344}
345
346/// Wire-shape payload for `fallow dupes --format json` (the body that
347/// flattens into the `DupesOutput` envelope and is also
348/// emitted under the `dupes` / `duplication` key inside the combined and
349/// audit envelopes).
350///
351/// Mirrors [`DuplicationReport`] field-for-field, except `clone_groups`
352/// and `clone_families` carry the typed wrapper envelopes instead of bare
353/// findings, so the schema (and any TS / agent consumer) sees the typed
354/// `actions[]` natively.
355#[derive(Debug, Clone, Serialize)]
356#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
357pub struct DupesReportPayload {
358    /// All detected clone groups, each wrapped with typed actions.
359    pub clone_groups: Vec<CloneGroupFinding>,
360    /// Clone families, each wrapped with typed actions. Inner `groups`
361    /// inside each `CloneFamilyFinding` are themselves wrapped as
362    /// `CloneGroupFinding` entries carrying their own `actions[]` (and
363    /// optional audit-mode `introduced` flag), so JSON-Schema strict
364    /// consumers and TS consumers reading `clone_families[].groups[]` see
365    /// the same shape as the top-level `clone_groups[]` array (preserves
366    /// the issue #393 regression contract).
367    pub clone_families: Vec<CloneFamilyFinding>,
368    /// Mirrored directory pairs.
369    #[serde(default, skip_serializing_if = "Vec::is_empty")]
370    pub mirrored_directories: Vec<MirroredDirectory>,
371    /// Aggregate duplication statistics.
372    pub stats: DuplicationStats,
373}
374
375impl DupesReportPayload {
376    /// Build the payload from a bare [`DuplicationReport`].
377    #[must_use]
378    pub fn from_report(report: &DuplicationReport) -> Self {
379        let fingerprints = CloneFingerprintSet::from_groups(&report.clone_groups);
380        Self {
381            clone_groups: report
382                .clone_groups
383                .iter()
384                .map(|group| {
385                    CloneGroupFinding::with_fingerprint(
386                        group.clone(),
387                        fingerprints.fingerprint_for_group(group),
388                    )
389                })
390                .collect(),
391            clone_families: report
392                .clone_families
393                .iter()
394                .map(|family| CloneFamilyFinding::with_fingerprints(family.clone(), &fingerprints))
395                .collect(),
396            mirrored_directories: report.mirrored_directories.clone(),
397            stats: report.stats.clone(),
398        }
399    }
400}
401
402/// Build CodeClimate issues from duplication analysis results.
403///
404/// `fallow-output` owns the CodeClimate wire DTOs. This API layer combines
405/// those DTOs with the engine-owned duplication report so CLI and future
406/// embedders can share the same issue construction policy.
407#[must_use]
408#[expect(
409    clippy::cast_possible_truncation,
410    reason = "line numbers are bounded by source size"
411)]
412pub fn build_duplication_codeclimate(
413    report: &DuplicationReport,
414    root: &Path,
415) -> Vec<CodeClimateIssue> {
416    let mut issues = Vec::new();
417
418    for (i, group) in report.clone_groups.iter().enumerate() {
419        let token_str = group.token_count.to_string();
420        let line_count_str = group.line_count.to_string();
421        let fragment_prefix: String = group
422            .instances
423            .first()
424            .map(|inst| inst.fragment.chars().take(64).collect())
425            .unwrap_or_default();
426
427        for instance in &group.instances {
428            let path = codeclimate_path(&instance.file, root);
429            let start_str = instance.start_line.to_string();
430            let fp = codeclimate_fingerprint_hash(&[
431                "fallow/code-duplication",
432                &path,
433                &start_str,
434                &token_str,
435                &line_count_str,
436                &fragment_prefix,
437            ]);
438            issues.push(fallow_output::build_codeclimate_issue(
439                CodeClimateIssueInput {
440                    check_name: "fallow/code-duplication",
441                    description: &format!(
442                        "Code clone group {} ({} lines, {} instances)",
443                        i + 1,
444                        group.line_count,
445                        group.instances.len()
446                    ),
447                    severity: CodeClimateSeverity::Minor,
448                    category: "Duplication",
449                    path: &path,
450                    begin_line: Some(instance.start_line as u32),
451                    fingerprint: &fp,
452                },
453            ));
454        }
455    }
456
457    issues
458}
459
460fn codeclimate_path(path: &Path, root: &Path) -> String {
461    normalize_uri(
462        &path
463            .strip_prefix(root)
464            .unwrap_or(path)
465            .display()
466            .to_string(),
467    )
468}
469
470#[cfg(test)]
471mod tests {
472    use std::path::Path;
473
474    use fallow_output::{CloneFamilyActionType, CloneGroupActionType};
475    use fallow_types::duplicates::{
476        CloneInstance, DuplicationStats, RefactoringKind, RefactoringSuggestion,
477    };
478
479    use super::*;
480
481    fn instance(path: &str) -> CloneInstance {
482        CloneInstance {
483            file: PathBuf::from(path),
484            start_line: 1,
485            end_line: 10,
486            start_col: 0,
487            end_col: 0,
488            fragment: String::new(),
489        }
490    }
491
492    fn group(instances: usize) -> CloneGroup {
493        CloneGroup {
494            instances: (0..instances)
495                .map(|i| instance(&format!("/root/file_{i}.ts")))
496                .collect(),
497            token_count: 100,
498            line_count: 20,
499            similarity: None,
500        }
501    }
502
503    #[test]
504    fn clone_group_finding_position_0_is_extract_shared() {
505        let finding = CloneGroupFinding::with_actions(group(2));
506        assert_eq!(finding.actions.len(), 2);
507        assert_eq!(finding.actions[0].kind, CloneGroupActionType::ExtractShared);
508        assert_eq!(finding.actions[1].kind, CloneGroupActionType::SuppressLine);
509        assert!(finding.introduced.is_none());
510        assert!(finding.demotion_reason.is_none());
511    }
512
513    #[test]
514    fn clone_group_finding_omits_audit_only_fields_outside_audit() {
515        // `fallow dupes --format json` serializes findings straight from Rust;
516        // the audit-only `introduced` / `demotion_reason` keys must not appear.
517        let finding = CloneGroupFinding::with_actions(group(2));
518        let value = serde_json::to_value(&finding).expect("finding serializes");
519        assert!(value.get("introduced").is_none());
520        assert!(value.get("demotion_reason").is_none());
521    }
522
523    #[test]
524    fn clone_demotion_reason_wire_name_matches_serde_representation() {
525        let reason = CloneDemotionReason::NoAddedLines;
526        assert_eq!(
527            serde_json::to_value(reason).expect("reason serializes"),
528            serde_json::Value::String(reason.wire_name())
529        );
530        assert_eq!(reason.wire_name(), "no-added-lines");
531    }
532
533    #[test]
534    fn attributed_clone_group_finding_actions_match_clone_group_shape() {
535        let attributed = AttributedCloneGroup {
536            primary_owner: "src".to_string(),
537            token_count: 100,
538            line_count: 20,
539            similarity: None,
540            instances: vec![
541                AttributedInstance {
542                    instance: instance("/root/src/a.ts"),
543                    owner: "src".to_string(),
544                },
545                AttributedInstance {
546                    instance: instance("/root/src/b.ts"),
547                    owner: "src".to_string(),
548                },
549            ],
550        };
551        let finding = AttributedCloneGroupFinding::with_actions(attributed);
552        assert_eq!(finding.actions.len(), 2);
553        assert_eq!(finding.actions[0].kind, CloneGroupActionType::ExtractShared);
554        assert_eq!(finding.actions[1].kind, CloneGroupActionType::SuppressLine);
555    }
556
557    #[test]
558    fn clone_group_finding_surfaces_dominant_identifier() {
559        let fragment = "function parseCsv() { parseCsv(); parseCsv(); return parseCsv; }";
560        let g = CloneGroup {
561            instances: vec![
562                CloneInstance {
563                    file: PathBuf::from("/root/a.ts"),
564                    start_line: 1,
565                    end_line: 3,
566                    start_col: 0,
567                    end_col: 0,
568                    fragment: fragment.to_string(),
569                },
570                CloneInstance {
571                    file: PathBuf::from("/root/b.ts"),
572                    start_line: 1,
573                    end_line: 3,
574                    start_col: 0,
575                    end_col: 0,
576                    fragment: fragment.to_string(),
577                },
578            ],
579            token_count: 100,
580            line_count: 3,
581            similarity: None,
582        };
583        let finding = CloneGroupFinding::with_actions(g);
584        assert_eq!(finding.suggested_name.as_deref(), Some("parseCsv"));
585    }
586
587    #[test]
588    fn clone_group_finding_suggested_name_none_for_unnamed_fragment() {
589        let finding = CloneGroupFinding::with_actions(group(2));
590        assert!(finding.suggested_name.is_none());
591    }
592
593    #[test]
594    fn clone_group_finding_description_pluralises_instance_count() {
595        let single = CloneGroupFinding::with_actions(group(1));
596        assert!(single.actions[0].description.contains("1 instance"));
597        assert!(!single.actions[0].description.contains("1 instances"));
598        let multi = CloneGroupFinding::with_actions(group(3));
599        assert!(multi.actions[0].description.contains("3 instances"));
600    }
601
602    #[test]
603    fn clone_family_finding_position_0_is_extract_shared_then_suggestions_then_suppress() {
604        let family = CloneFamily {
605            files: vec![PathBuf::from("/root/a.ts"), PathBuf::from("/root/b.ts")],
606            groups: vec![group(2), group(2)],
607            total_duplicated_lines: 40,
608            total_duplicated_tokens: 200,
609            suggestions: vec![
610                RefactoringSuggestion {
611                    kind: RefactoringKind::ExtractFunction,
612                    description: "Extract helper".to_string(),
613                    estimated_savings: 10,
614                },
615                RefactoringSuggestion {
616                    kind: RefactoringKind::ExtractModule,
617                    description: "Extract module".to_string(),
618                    estimated_savings: 30,
619                },
620            ],
621        };
622        let finding = CloneFamilyFinding::with_actions(family);
623        assert_eq!(finding.actions.len(), 4);
624        assert_eq!(
625            finding.actions[0].kind,
626            CloneFamilyActionType::ExtractShared
627        );
628        assert_eq!(
629            finding.actions[1].kind,
630            CloneFamilyActionType::ApplySuggestion
631        );
632        assert_eq!(finding.actions[1].description, "Extract helper");
633        assert_eq!(
634            finding.actions[2].kind,
635            CloneFamilyActionType::ApplySuggestion
636        );
637        assert_eq!(finding.actions[2].description, "Extract module");
638        assert_eq!(finding.actions[3].kind, CloneFamilyActionType::SuppressLine);
639        assert_eq!(finding.groups.len(), 2);
640        for inner in &finding.groups {
641            assert_eq!(inner.actions.len(), 2);
642            assert_eq!(inner.actions[0].kind, CloneGroupActionType::ExtractShared);
643            assert_eq!(inner.actions[1].kind, CloneGroupActionType::SuppressLine);
644        }
645    }
646
647    #[test]
648    fn clone_family_finding_with_no_suggestions_emits_two_actions() {
649        let family = CloneFamily {
650            files: vec![PathBuf::from("/root/a.ts")],
651            groups: vec![group(2)],
652            total_duplicated_lines: 20,
653            total_duplicated_tokens: 100,
654            suggestions: Vec::new(),
655        };
656        let finding = CloneFamilyFinding::with_actions(family);
657        assert_eq!(finding.actions.len(), 2);
658        assert_eq!(
659            finding.actions[0].kind,
660            CloneFamilyActionType::ExtractShared
661        );
662        assert_eq!(finding.actions[1].kind, CloneFamilyActionType::SuppressLine);
663    }
664
665    #[test]
666    fn payload_from_report_wraps_all_findings() {
667        let report = DuplicationReport {
668            clone_groups: vec![group(2), group(3)],
669            clone_families: vec![CloneFamily {
670                files: vec![PathBuf::from("/root/a.ts")],
671                groups: vec![group(2)],
672                total_duplicated_lines: 20,
673                total_duplicated_tokens: 100,
674                suggestions: Vec::new(),
675            }],
676            mirrored_directories: Vec::new(),
677            stats: DuplicationStats::default(),
678        };
679        let payload = DupesReportPayload::from_report(&report);
680        assert_eq!(payload.clone_groups.len(), 2);
681        assert_eq!(payload.clone_families.len(), 1);
682        for finding in &payload.clone_groups {
683            assert_eq!(finding.actions.len(), 2);
684        }
685        assert_eq!(payload.clone_families[0].actions.len(), 2);
686    }
687
688    #[test]
689    fn duplication_codeclimate_uses_relative_normalized_paths() {
690        let report = DuplicationReport {
691            clone_groups: vec![CloneGroup {
692                instances: vec![CloneInstance {
693                    file: PathBuf::from("/root/app/[id]/page.tsx"),
694                    start_line: 4,
695                    end_line: 8,
696                    start_col: 0,
697                    end_col: 0,
698                    fragment: "const duplicate = 1;".to_string(),
699                }],
700                token_count: 42,
701                line_count: 5,
702                similarity: None,
703            }],
704            clone_families: Vec::new(),
705            mirrored_directories: Vec::new(),
706            stats: DuplicationStats::default(),
707        };
708
709        let issues = build_duplication_codeclimate(&report, Path::new("/root"));
710
711        assert_eq!(issues.len(), 1);
712        let issue = &issues[0];
713        assert_eq!(issue.check_name, "fallow/code-duplication");
714        assert_eq!(issue.location.path, "app/%5Bid%5D/page.tsx");
715        assert_eq!(issue.location.lines.begin, 4);
716        assert_eq!(issue.categories, vec!["Duplication"]);
717        assert!(issue.description.contains("Code clone group 1"));
718    }
719}