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::{CloneFingerprintSet, dominant_identifier};
6use fallow_output::{
7    CloneFamilyAction, CloneGroupAction, CodeClimateIssue, CodeClimateIssueInput,
8    CodeClimateSeverity, clone_family_actions, clone_group_actions, codeclimate_fingerprint_hash,
9    normalize_uri,
10};
11use fallow_types::duplicates::{
12    CloneFamily, CloneGroup, CloneInstance, DuplicationReport, DuplicationStats, MirroredDirectory,
13    RefactoringSuggestion, clone_location_spread,
14};
15use fallow_types::envelope::AuditIntroduced;
16use fallow_types::serde_path;
17use serde::Serialize;
18
19/// A clone instance plus its per-instance owner key (for inline JSON / SARIF
20/// rendering).
21///
22/// Each instance carries its own `owner` field alongside the standard
23/// `CloneInstance` shape (file / start_line / end_line / start_col / end_col /
24/// fragment), so consumers can attribute instances to resolver keys without
25/// re-resolving paths.
26#[derive(Debug, Clone, Serialize)]
27#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
28pub struct AttributedInstance {
29    /// The original clone instance.
30    #[serde(flatten)]
31    pub instance: CloneInstance,
32    /// Resolver key for this specific instance (per-instance, not the
33    /// group-level largest-owner).
34    pub owner: String,
35}
36
37/// A clone group annotated with largest-owner attribution and per-instance
38/// owner keys.
39#[derive(Debug, Clone, Serialize)]
40#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
41pub struct AttributedCloneGroup {
42    /// Largest-owner attribution: the resolver key with the most instances in
43    /// this clone group. Ties broken alphabetically (smallest key wins).
44    pub primary_owner: String,
45    /// Number of tokens in the clone group.
46    pub token_count: usize,
47    /// Number of source lines in the clone group.
48    pub line_count: usize,
49    /// Lowest all-pairs similarity for a near-miss clone group.
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    #[cfg_attr(feature = "schema", schemars(with = "f64"))]
52    pub similarity: Option<f64>,
53    /// Each instance carries its own `owner` field alongside the standard
54    /// CloneInstance shape.
55    pub instances: Vec<AttributedInstance>,
56}
57
58impl AttributedCloneGroup {
59    /// Return the report-scoped fingerprint for this attributed group.
60    #[must_use]
61    pub fn fingerprint(&self, fingerprints: &CloneFingerprintSet) -> String {
62        let instances: Vec<_> = self
63            .instances
64            .iter()
65            .map(|instance| instance.instance.clone())
66            .collect();
67        fingerprints.fingerprint_for_parts(&instances, self.token_count, self.line_count)
68    }
69}
70
71/// Wire-shape envelope for an [`AttributedCloneGroup`] finding (per-bucket
72/// duplication attribution emitted under `fallow dupes --group-by`).
73/// Flattens the attributed group and carries the same typed
74/// `CloneGroupAction` array as `CloneGroupFinding`; no `introduced`
75/// field because `fallow audit` does not run on grouped output.
76#[derive(Debug, Clone, Serialize)]
77#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
78pub struct AttributedCloneGroupFinding {
79    /// The underlying attributed clone group.
80    #[serde(flatten)]
81    pub group: AttributedCloneGroup,
82    /// Stable content fingerprint, usually `dup:<8hex>` and widened on rare
83    /// report collisions. Addressable via `fallow dupes --trace dup:<fp>`.
84    /// Computed from the group's instances, so it matches the top-level
85    /// `clone_groups[].fingerprint` for the same clone.
86    pub fingerprint: String,
87    /// Maximum directory-tree or same-file line distance between instances.
88    pub spread: usize,
89    /// Suggested next steps. Always emitted.
90    pub actions: Vec<CloneGroupAction>,
91}
92
93impl AttributedCloneGroupFinding {
94    /// Build the wrapper with a precomputed report-scoped fingerprint.
95    #[must_use]
96    pub fn with_fingerprint(group: AttributedCloneGroup, fingerprint: String) -> Self {
97        let spread = clone_location_spread(group.instances.iter().map(|instance| {
98            (
99                instance.instance.file.as_path(),
100                instance.instance.start_line,
101                instance.instance.end_line,
102            )
103        }));
104        let actions = clone_group_actions(group.line_count, group.instances.len());
105        Self {
106            group,
107            fingerprint,
108            spread,
109            actions,
110        }
111    }
112}
113
114/// A single grouped duplication bucket. Per-group `stats` are dedup-aware and
115/// computed over the FULL group BEFORE any `--top` truncation.
116#[derive(Debug, Clone, Serialize)]
117#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
118pub struct DuplicationGroup {
119    /// Group label (owner / directory / package / section). `(unowned)` for
120    /// files with no CODEOWNERS rule, `(no section)` for pre-section rules in
121    /// section mode.
122    pub key: String,
123    /// Dedup-aware aggregate stats for the group.
124    pub stats: DuplicationStats,
125    /// Clone groups attributed to this owner, each wrapped with the typed
126    /// `actions[]` array. Each group's `primary_owner` is its largest-owner
127    /// key; per-instance `owner` lets consumers see cross-bucket fan-out
128    /// without re-resolving paths.
129    pub clone_groups: Vec<AttributedCloneGroupFinding>,
130    /// Clone families overlapping this bucket, each wrapped with the typed
131    /// `actions[]` array.
132    pub clone_families: Vec<CloneFamilyFinding>,
133}
134
135impl DuplicationGroup {
136    /// Drop the verbatim source text from every clone instance in this bucket,
137    /// including the copies nested in `clone_families[].groups[]`.
138    pub fn strip_fragments(&mut self) {
139        for finding in &mut self.clone_groups {
140            for instance in &mut finding.group.instances {
141                instance.instance.fragment.clear();
142            }
143        }
144        for family in &mut self.clone_families {
145            for finding in &mut family.groups {
146                finding.group.strip_fragments();
147            }
148        }
149    }
150}
151
152/// Wrapper carrying the resolver mode label and grouped buckets.
153#[derive(Debug, Clone, Serialize)]
154pub struct DuplicationGrouping {
155    /// Resolver mode label (`"owner"`, `"directory"`, `"package"`, `"section"`).
156    pub mode: &'static str,
157    /// One bucket per resolver key.
158    pub groups: Vec<DuplicationGroup>,
159}
160
161/// Why the audit new-only gate demoted an introduced clone group to
162/// inherited. Serializes as a kebab-case string on the wire (for example
163/// `"no-added-lines"`).
164///
165/// Further variants may be added in later releases; consumers should treat an
166/// unknown value as "some demotion reason" rather than failing.
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
168#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
169#[serde(rename_all = "kebab-case")]
170pub enum CloneDemotionReason {
171    /// No instance of the group overlaps an added line in the run's diff: the
172    /// group was re-shaped by removals elsewhere in the changeset, not written
173    /// by it (issue #2164).
174    NoAddedLines,
175}
176
177impl CloneDemotionReason {
178    /// The kebab-case wire literal, obtained from the serde representation so
179    /// human output and JSON cannot diverge.
180    #[must_use]
181    pub fn wire_name(self) -> String {
182        match serde_json::to_value(self) {
183            Ok(serde_json::Value::String(name)) => name,
184            _ => String::new(),
185        }
186    }
187}
188
189/// Wire-shape envelope for a [`CloneGroup`] finding. Flattens the bare
190/// group via `#[serde(flatten)]` and carries a typed `actions` array plus
191/// the optional audit-mode `introduced` flag. The typed envelope replaced
192/// the legacy JSON post-pass injection; a guard test in
193/// `crates/cli/src/report/json.rs` rejects any reintroduced post-pass.
194#[derive(Debug, Clone, Serialize)]
195#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
196pub struct CloneGroupFinding {
197    /// The underlying clone group.
198    #[serde(flatten)]
199    pub group: CloneGroup,
200    /// Stable content fingerprint, usually `dup:<8hex>` and widened on rare
201    /// report collisions. Addressable via `fallow dupes --trace dup:<fp>` (and
202    /// the `trace_clone` MCP tool) to deep-dive this group; shown alongside
203    /// each group in the human listing.
204    pub fingerprint: String,
205    /// Maximum directory-tree or same-file line distance between instances.
206    pub spread: usize,
207    /// Best-effort human-readable name for the clone: the dominant repeated
208    /// identifier across the duplicated fragment (e.g. a shared `parseCsv`
209    /// function). `None` when the clone has no clear dominant name (generic or
210    /// tied identifiers); consumers then fall back to a file-based label. Lets
211    /// editors and agents label a clone by what it is rather than an opaque
212    /// ordinal.
213    #[serde(default, skip_serializing_if = "Option::is_none")]
214    pub suggested_name: Option<String>,
215    /// Suggested next steps: an `extract-shared` primary and a
216    /// `suppress-line` secondary. Always emitted (possibly empty for
217    /// forward-compat).
218    pub actions: Vec<CloneGroupAction>,
219    /// Set by the audit pass when this clone group is introduced relative
220    /// to the merge-base. `None` when serialized directly from Rust.
221    #[serde(default, skip_serializing_if = "Option::is_none")]
222    pub introduced: Option<AuditIntroduced>,
223    /// Set only by `fallow audit` under `--gate new-only`, on groups whose
224    /// `introduced` flag the gate demoted to `false`: why the demotion
225    /// happened. `None` everywhere else, including `fallow dupes
226    /// --format json` (issue #2220).
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub demotion_reason: Option<CloneDemotionReason>,
229}
230
231impl CloneGroupFinding {
232    /// Build the wrapper with a precomputed report-scoped fingerprint.
233    #[must_use]
234    pub fn with_fingerprint(group: CloneGroup, fingerprint: String) -> Self {
235        let spread = group.spread();
236        let suggested_name = dominant_identifier(&group);
237        let actions = clone_group_actions(group.line_count, group.instances.len());
238        Self {
239            fingerprint,
240            spread,
241            suggested_name,
242            group,
243            actions,
244            introduced: None,
245            demotion_reason: None,
246        }
247    }
248}
249
250/// Wire-shape envelope for a [`CloneFamily`] finding.
251///
252/// Unlike most `*Finding` wrappers this one is NOT `#[serde(flatten)]` over
253/// the bare [`CloneFamily`], because the family's nested
254/// `groups: Vec<CloneGroup>` field needs to carry the typed
255/// `CloneGroupFinding` wrapper too (so every nested clone group gets its
256/// own `actions[]` array, matching the legacy post-pass behavior; see issue
257/// #393 regression test). The wire shape stays byte-identical to the
258/// previous post-pass output. No `introduced` field because `fallow audit`
259/// attributes clone groups (not families) when running against a base ref.
260#[derive(Debug, Clone, Serialize)]
261#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
262pub struct CloneFamilyFinding {
263    /// The files involved in this family.
264    #[serde(serialize_with = "serde_path::serialize_vec")]
265    pub files: Vec<PathBuf>,
266    /// Clone groups belonging to this family, each wrapped with typed
267    /// `actions[]` so consumers that read `clone_families[].groups[]`
268    /// directly see the same shape as the top-level `clone_groups[]`.
269    pub groups: Vec<CloneGroupFinding>,
270    /// Total number of duplicated lines across all groups.
271    pub total_duplicated_lines: usize,
272    /// Total number of duplicated tokens across all groups.
273    pub total_duplicated_tokens: usize,
274    /// Refactoring suggestions for this family.
275    pub suggestions: Vec<RefactoringSuggestion>,
276    /// Suggested next steps: an `extract-shared` primary, one
277    /// `apply-suggestion` per `RefactoringSuggestion` on the family, and
278    /// a trailing `suppress-line`. Always emitted (possibly empty for
279    /// forward-compat).
280    pub actions: Vec<CloneFamilyAction>,
281}
282
283impl CloneFamilyFinding {
284    /// Build the wrapper using the report-scoped fingerprint assignment shared
285    /// by all duplication output surfaces.
286    #[must_use]
287    pub fn with_fingerprints(family: CloneFamily, fingerprints: &CloneFingerprintSet) -> Self {
288        let actions = build_clone_family_actions(
289            &family.groups,
290            family.total_duplicated_lines,
291            &family.suggestions,
292        );
293        Self {
294            files: family.files,
295            groups: family
296                .groups
297                .into_iter()
298                .map(|group| {
299                    let fingerprint = fingerprints.fingerprint_for_group(&group);
300                    CloneGroupFinding::with_fingerprint(group, fingerprint)
301                })
302                .collect(),
303            total_duplicated_lines: family.total_duplicated_lines,
304            total_duplicated_tokens: family.total_duplicated_tokens,
305            suggestions: family.suggestions,
306            actions,
307        }
308    }
309}
310
311fn build_clone_family_actions(
312    groups: &[CloneGroup],
313    total_duplicated_lines: usize,
314    suggestions: &[RefactoringSuggestion],
315) -> Vec<CloneFamilyAction> {
316    clone_family_actions(
317        groups.len(),
318        total_duplicated_lines,
319        suggestions
320            .iter()
321            .map(|suggestion| suggestion.description.as_str()),
322    )
323}
324
325/// Wire-shape payload for `fallow dupes --format json` (the body that
326/// flattens into the `DupesOutput` envelope and is also
327/// emitted under the `dupes` / `duplication` key inside the combined and
328/// audit envelopes).
329///
330/// Mirrors [`DuplicationReport`] field-for-field, except `clone_groups`
331/// and `clone_families` carry the typed wrapper envelopes instead of bare
332/// findings, so the schema (and any TS / agent consumer) sees the typed
333/// `actions[]` natively.
334#[derive(Debug, Clone, Serialize)]
335#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
336pub struct DupesReportPayload {
337    /// All detected clone groups, each wrapped with typed actions.
338    pub clone_groups: Vec<CloneGroupFinding>,
339    /// Clone families, each wrapped with typed actions. Inner `groups`
340    /// inside each `CloneFamilyFinding` are themselves wrapped as
341    /// `CloneGroupFinding` entries carrying their own `actions[]` (and
342    /// optional audit-mode `introduced` flag), so JSON-Schema strict
343    /// consumers and TS consumers reading `clone_families[].groups[]` see
344    /// the same shape as the top-level `clone_groups[]` array (preserves
345    /// the issue #393 regression contract).
346    pub clone_families: Vec<CloneFamilyFinding>,
347    /// Mirrored directory pairs.
348    #[serde(default, skip_serializing_if = "Vec::is_empty")]
349    pub mirrored_directories: Vec<MirroredDirectory>,
350    /// Aggregate duplication statistics.
351    pub stats: DuplicationStats,
352}
353
354/// Wire shape of the `dupes` section inside the bare combined envelope.
355///
356/// The section is the standalone payload plus the view of the loaded
357/// duplication baseline. The standalone `dupes` envelope carries the same
358/// `baseline_staleness` key at its root.
359#[derive(Debug, Clone, Serialize)]
360#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
361pub struct CombinedDupesSection {
362    /// The duplication payload, flattened into the section.
363    #[serde(flatten)]
364    pub payload: DupesReportPayload,
365    /// This run's view of the loaded duplication baseline, present only when
366    /// `--dupes-baseline` loaded one. Read `change_scoped` before dividing
367    /// `matched_entries` by `baseline_entries`: a narrowed run can report
368    /// `matched_entries: 0` on a healthy baseline.
369    #[serde(default, skip_serializing_if = "Option::is_none")]
370    pub baseline_staleness: Option<fallow_output::BaselineStaleness>,
371}
372
373impl DupesReportPayload {
374    /// Build the payload from a bare [`DuplicationReport`].
375    #[must_use]
376    pub fn from_report(report: &DuplicationReport) -> Self {
377        let fingerprints = CloneFingerprintSet::from_groups(&report.clone_groups);
378        Self {
379            clone_groups: report
380                .clone_groups
381                .iter()
382                .map(|group| {
383                    CloneGroupFinding::with_fingerprint(
384                        group.clone(),
385                        fingerprints.fingerprint_for_group(group),
386                    )
387                })
388                .collect(),
389            clone_families: report
390                .clone_families
391                .iter()
392                .map(|family| CloneFamilyFinding::with_fingerprints(family.clone(), &fingerprints))
393                .collect(),
394            mirrored_directories: report.mirrored_directories.clone(),
395            stats: report.stats.clone(),
396        }
397    }
398
399    /// Build the payload and drop the verbatim source text when the caller
400    /// asked for a location-only body.
401    ///
402    /// Fingerprints, suggested names and actions are computed by
403    /// [`Self::from_report`], so the text is only removed after every consumer
404    /// that reads it has run.
405    #[must_use]
406    pub fn from_report_with_fragments(report: &DuplicationReport, include_fragments: bool) -> Self {
407        let mut payload = Self::from_report(report);
408        if !include_fragments {
409            payload.strip_fragments();
410        }
411        payload
412    }
413
414    /// Drop the verbatim source text from every clone instance, including the
415    /// copies nested in `clone_families[].groups[]`.
416    pub fn strip_fragments(&mut self) {
417        for finding in &mut self.clone_groups {
418            finding.group.strip_fragments();
419        }
420        for family in &mut self.clone_families {
421            for finding in &mut family.groups {
422                finding.group.strip_fragments();
423            }
424        }
425    }
426}
427
428/// The number of fragment characters in the CodeClimate fingerprint of a
429/// clone instance. The count leaves out `\r`, so a CRLF checkout and an LF
430/// checkout of the same code give the same fingerprint.
431const CODECLIMATE_FRAGMENT_PREFIX_CHARS: usize = 64;
432
433/// Build CodeClimate issues from duplication analysis results.
434///
435/// `fallow-output` owns the CodeClimate wire DTOs. This API layer combines
436/// those DTOs with the engine-owned duplication report so CLI and future
437/// embedders can share the same issue construction policy.
438#[must_use]
439#[expect(
440    clippy::cast_possible_truncation,
441    reason = "line numbers are bounded by source size"
442)]
443pub fn build_duplication_codeclimate(
444    report: &DuplicationReport,
445    root: &Path,
446) -> Vec<CodeClimateIssue> {
447    let mut issues = Vec::new();
448    let fingerprints = CloneFingerprintSet::from_groups(&report.clone_groups);
449
450    for group in &report.clone_groups {
451        let clone_fingerprint = fingerprints.fingerprint_for_group(group);
452        let token_str = group.token_count.to_string();
453        let line_count_str = group.line_count.to_string();
454        let fragment_prefix: String = group
455            .instances
456            .first()
457            .map(|inst| {
458                inst.fragment
459                    .chars()
460                    .filter(|&c| c != '\r')
461                    .take(CODECLIMATE_FRAGMENT_PREFIX_CHARS)
462                    .collect()
463            })
464            .unwrap_or_default();
465
466        for (instance_index, instance) in group.instances.iter().enumerate() {
467            let path = codeclimate_path(&instance.file, root);
468            let start_str = instance.start_line.to_string();
469            let fp = codeclimate_fingerprint_hash(&[
470                "fallow/code-duplication",
471                &path,
472                &start_str,
473                &token_str,
474                &line_count_str,
475                &fragment_prefix,
476            ]);
477            let mut issue = fallow_output::build_codeclimate_issue(CodeClimateIssueInput {
478                check_name: "fallow/code-duplication",
479                description: &format!(
480                    "Code clone {clone_fingerprint} ({} lines, {} instances)",
481                    group.line_count,
482                    group.instances.len()
483                ),
484                severity: CodeClimateSeverity::Minor,
485                category: "Duplication",
486                path: &path,
487                begin_line: Some(instance.start_line as u32),
488                fingerprint: &fp,
489            });
490            issue.location.lines.end = Some(instance.end_line as u32);
491            issue.other_locations = group
492                .instances
493                .iter()
494                .enumerate()
495                .filter(|(peer_index, _)| *peer_index != instance_index)
496                .map(|(_, peer)| fallow_output::CodeClimateLocation {
497                    path: codeclimate_path(&peer.file, root),
498                    lines: fallow_output::CodeClimateLines {
499                        begin: peer.start_line as u32,
500                        end: Some(peer.end_line as u32),
501                    },
502                })
503                .collect();
504            issue.other_locations.sort_by(|a, b| {
505                (&a.path, a.lines.begin, a.lines.end).cmp(&(&b.path, b.lines.begin, b.lines.end))
506            });
507            issues.push(issue);
508        }
509    }
510
511    issues
512}
513
514/// Set the audit attribution on the issues of [`build_duplication_codeclimate`].
515///
516/// `introduced` holds one audit flag per clone group, in report order. Each
517/// group gives one issue per instance, so the instances of one group get the
518/// flag of that group. The inline review comment then states if the change
519/// introduced the clone group.
520pub fn set_duplication_audit_attribution(
521    issues: &mut [CodeClimateIssue],
522    report: &DuplicationReport,
523    introduced: impl IntoIterator<Item = bool>,
524) {
525    let mut remaining = issues;
526    for (group, introduced) in report.clone_groups.iter().zip(introduced) {
527        let count = group.instances.len().min(remaining.len());
528        let (group_issues, rest) = remaining.split_at_mut(count);
529        let context = crate::dead_code_codeclimate::audit_review_context(introduced);
530        for issue in group_issues {
531            issue.audit = Some(context);
532        }
533        remaining = rest;
534    }
535}
536
537fn codeclimate_path(path: &Path, root: &Path) -> String {
538    normalize_uri(
539        &path
540            .strip_prefix(root)
541            .unwrap_or(path)
542            .display()
543            .to_string(),
544    )
545}
546
547#[cfg(test)]
548mod tests {
549    use std::path::Path;
550
551    use fallow_output::{CloneFamilyActionType, CloneGroupActionType};
552    use fallow_types::duplicates::{
553        CloneInstance, DuplicationStats, RefactoringKind, RefactoringSuggestion,
554    };
555
556    use super::*;
557
558    const TEST_FINGERPRINT: &str = "dup:00000000";
559
560    fn instance(path: &str) -> CloneInstance {
561        CloneInstance {
562            is_symlink: false,
563            file: PathBuf::from(path),
564            start_line: 1,
565            end_line: 10,
566            start_col: 0,
567            end_col: 0,
568            fragment: String::new(),
569        }
570    }
571
572    fn group(instances: usize) -> CloneGroup {
573        CloneGroup {
574            instances: (0..instances)
575                .map(|i| instance(&format!("/root/file_{i}.ts")))
576                .collect(),
577            token_count: 100,
578            line_count: 20,
579            similarity: None,
580        }
581    }
582
583    fn report_with_fragment(fragment: &str) -> DuplicationReport {
584        let mut clones = group(2);
585        for instance in &mut clones.instances {
586            instance.fragment = fragment.to_owned();
587        }
588        DuplicationReport {
589            clone_groups: vec![clones],
590            clone_families: Vec::new(),
591            mirrored_directories: Vec::new(),
592            stats: DuplicationStats::default(),
593        }
594    }
595
596    fn codeclimate_fingerprints(fragment: &str) -> Vec<String> {
597        build_duplication_codeclimate(&report_with_fragment(fragment), Path::new("/root"))
598            .into_iter()
599            .map(|issue| issue.fingerprint)
600            .collect()
601    }
602
603    /// The prefix holds more than 64 characters, so each `\r` moves a later
604    /// character out of a raw 64-character prefix.
605    const LF_FRAGMENT: &str = "export function total(items) {\n  let sum = 0;\n  for (const item of items) {\n    sum += item.price;\n  }\n  return sum;\n}\n";
606
607    #[test]
608    fn codeclimate_clone_fingerprints_ignore_crlf_line_endings() {
609        let crlf = LF_FRAGMENT.replace('\n', "\r\n");
610        assert_eq!(
611            codeclimate_fingerprints(LF_FRAGMENT),
612            codeclimate_fingerprints(&crlf)
613        );
614    }
615
616    #[test]
617    fn codeclimate_clone_fingerprints_keep_the_lf_hash() {
618        let prefix: String = LF_FRAGMENT.chars().take(64).collect();
619        let expected: Vec<String> = ["/root/file_0.ts", "/root/file_1.ts"]
620            .iter()
621            .map(|path| {
622                codeclimate_fingerprint_hash(&[
623                    "fallow/code-duplication",
624                    &codeclimate_path(Path::new(path), Path::new("/root")),
625                    "1",
626                    "100",
627                    "20",
628                    &prefix,
629                ])
630            })
631            .collect();
632        assert_eq!(codeclimate_fingerprints(LF_FRAGMENT), expected);
633    }
634
635    #[test]
636    fn duplication_audit_attribution_follows_each_group() {
637        use fallow_output::AuditFindingAttribution as A;
638        let report = DuplicationReport {
639            clone_groups: vec![group(2), group(3)],
640            clone_families: Vec::new(),
641            mirrored_directories: Vec::new(),
642            stats: DuplicationStats::default(),
643        };
644        let root = Path::new("/root");
645        let plain = build_duplication_codeclimate(&report, root);
646        let mut issues = plain.clone();
647        set_duplication_audit_attribution(&mut issues, &report, [false, true]);
648        let attributions: Vec<_> = issues
649            .iter()
650            .map(|issue| issue.audit.map(|context| context.attribution))
651            .collect();
652        assert_eq!(
653            attributions,
654            [
655                Some(A::Inherited),
656                Some(A::Inherited),
657                Some(A::Introduced),
658                Some(A::Introduced),
659                Some(A::Introduced),
660            ]
661        );
662        for (with, without) in issues.iter().zip(&plain) {
663            assert_eq!(with.fingerprint, without.fingerprint);
664            assert_eq!(
665                serde_json::to_value(with).expect("issue serializes"),
666                serde_json::to_value(without).expect("issue serializes"),
667                "the wire shape does not carry the attribution"
668            );
669        }
670    }
671
672    #[test]
673    fn clone_group_finding_position_0_is_extract_shared() {
674        let finding = CloneGroupFinding::with_fingerprint(group(2), TEST_FINGERPRINT.to_string());
675        assert_eq!(finding.actions.len(), 2);
676        assert_eq!(finding.actions[0].kind, CloneGroupActionType::ExtractShared);
677        assert_eq!(finding.actions[1].kind, CloneGroupActionType::SuppressLine);
678        assert!(finding.introduced.is_none());
679        assert!(finding.demotion_reason.is_none());
680    }
681
682    #[test]
683    fn clone_group_finding_omits_audit_only_fields_outside_audit() {
684        // `fallow dupes --format json` serializes findings straight from Rust;
685        // the audit-only `introduced` / `demotion_reason` keys must not appear.
686        let finding = CloneGroupFinding::with_fingerprint(group(2), TEST_FINGERPRINT.to_string());
687        let value = serde_json::to_value(&finding).expect("finding serializes");
688        assert!(value.get("introduced").is_none());
689        assert!(value.get("demotion_reason").is_none());
690    }
691
692    #[test]
693    fn suppressed_fragments_leave_locations_and_fingerprints_intact() {
694        let mut with_text = group(2);
695        for (index, instance) in with_text.instances.iter_mut().enumerate() {
696            instance.fragment = format!("const shared{index} = compute(input);");
697        }
698        let family = CloneFamily {
699            files: vec![PathBuf::from("/root/file_0.ts")],
700            groups: vec![with_text.clone()],
701            total_duplicated_lines: 20,
702            total_duplicated_tokens: 100,
703            suggestions: Vec::new(),
704        };
705        let report = DuplicationReport {
706            clone_groups: vec![with_text],
707            clone_families: vec![family],
708            mirrored_directories: Vec::new(),
709            stats: DuplicationStats::default(),
710        };
711
712        let kept = DupesReportPayload::from_report_with_fragments(&report, true);
713        let dropped = DupesReportPayload::from_report_with_fragments(&report, false);
714
715        assert_eq!(
716            kept.clone_groups[0].fingerprint, dropped.clone_groups[0].fingerprint,
717            "fingerprints are computed before the text is dropped"
718        );
719
720        let kept_value = serde_json::to_value(&kept).expect("payload serializes");
721        assert!(kept_value["clone_groups"][0]["instances"][0]["fragment"].is_string());
722
723        let value = serde_json::to_value(&dropped).expect("payload serializes");
724        let instance = &value["clone_groups"][0]["instances"][0];
725        assert!(
726            instance.get("fragment").is_none(),
727            "the verbatim source text must be absent, not empty"
728        );
729        assert!(instance.get("file").is_some());
730        assert!(instance.get("start_line").is_some());
731        assert!(instance.get("end_col").is_some());
732        assert!(
733            value["clone_families"][0]["groups"][0]["instances"][0]
734                .get("fragment")
735                .is_none(),
736            "nested clone-family copies carry the same text and must be dropped too"
737        );
738    }
739
740    #[test]
741    fn clone_demotion_reason_wire_name_matches_serde_representation() {
742        let reason = CloneDemotionReason::NoAddedLines;
743        assert_eq!(
744            serde_json::to_value(reason).expect("reason serializes"),
745            serde_json::Value::String(reason.wire_name())
746        );
747        assert_eq!(reason.wire_name(), "no-added-lines");
748    }
749
750    #[test]
751    fn attributed_clone_group_finding_actions_match_clone_group_shape() {
752        let attributed = AttributedCloneGroup {
753            primary_owner: "src".to_string(),
754            token_count: 100,
755            line_count: 20,
756            similarity: None,
757            instances: vec![
758                AttributedInstance {
759                    instance: instance("/root/src/a.ts"),
760                    owner: "src".to_string(),
761                },
762                AttributedInstance {
763                    instance: instance("/root/src/b.ts"),
764                    owner: "src".to_string(),
765                },
766            ],
767        };
768        let finding =
769            AttributedCloneGroupFinding::with_fingerprint(attributed, TEST_FINGERPRINT.to_string());
770        assert_eq!(finding.actions.len(), 2);
771        assert_eq!(finding.actions[0].kind, CloneGroupActionType::ExtractShared);
772        assert_eq!(finding.actions[1].kind, CloneGroupActionType::SuppressLine);
773    }
774
775    #[test]
776    fn clone_group_finding_surfaces_dominant_identifier() {
777        let fragment = "function parseCsv() { parseCsv(); parseCsv(); return parseCsv; }";
778        let g = CloneGroup {
779            instances: vec![
780                CloneInstance {
781                    is_symlink: false,
782                    file: PathBuf::from("/root/a.ts"),
783                    start_line: 1,
784                    end_line: 3,
785                    start_col: 0,
786                    end_col: 0,
787                    fragment: fragment.to_string(),
788                },
789                CloneInstance {
790                    is_symlink: false,
791                    file: PathBuf::from("/root/b.ts"),
792                    start_line: 1,
793                    end_line: 3,
794                    start_col: 0,
795                    end_col: 0,
796                    fragment: fragment.to_string(),
797                },
798            ],
799            token_count: 100,
800            line_count: 3,
801            similarity: None,
802        };
803        let finding = CloneGroupFinding::with_fingerprint(g, TEST_FINGERPRINT.to_string());
804        assert_eq!(finding.suggested_name.as_deref(), Some("parseCsv"));
805    }
806
807    #[test]
808    fn clone_group_finding_suggested_name_none_for_unnamed_fragment() {
809        let finding = CloneGroupFinding::with_fingerprint(group(2), TEST_FINGERPRINT.to_string());
810        assert!(finding.suggested_name.is_none());
811    }
812
813    #[test]
814    fn clone_group_finding_description_pluralises_instance_count() {
815        let single = CloneGroupFinding::with_fingerprint(group(1), TEST_FINGERPRINT.to_string());
816        assert!(single.actions[0].description.contains("1 instance"));
817        assert!(!single.actions[0].description.contains("1 instances"));
818        let multi = CloneGroupFinding::with_fingerprint(group(3), TEST_FINGERPRINT.to_string());
819        assert!(multi.actions[0].description.contains("3 instances"));
820    }
821
822    #[test]
823    fn clone_family_finding_position_0_is_extract_shared_then_suggestions_then_suppress() {
824        let family = CloneFamily {
825            files: vec![PathBuf::from("/root/a.ts"), PathBuf::from("/root/b.ts")],
826            groups: vec![group(2), group(2)],
827            total_duplicated_lines: 40,
828            total_duplicated_tokens: 200,
829            suggestions: vec![
830                RefactoringSuggestion {
831                    kind: RefactoringKind::ExtractFunction,
832                    description: "Extract helper".to_string(),
833                    estimated_savings: 10,
834                },
835                RefactoringSuggestion {
836                    kind: RefactoringKind::ExtractModule,
837                    description: "Extract module".to_string(),
838                    estimated_savings: 30,
839                },
840            ],
841        };
842        let fingerprints = CloneFingerprintSet::from_groups(&family.groups);
843        let finding = CloneFamilyFinding::with_fingerprints(family, &fingerprints);
844        assert_eq!(finding.actions.len(), 4);
845        assert_eq!(
846            finding.actions[0].kind,
847            CloneFamilyActionType::ExtractShared
848        );
849        assert_eq!(
850            finding.actions[1].kind,
851            CloneFamilyActionType::ApplySuggestion
852        );
853        assert_eq!(finding.actions[1].description, "Extract helper");
854        assert_eq!(
855            finding.actions[2].kind,
856            CloneFamilyActionType::ApplySuggestion
857        );
858        assert_eq!(finding.actions[2].description, "Extract module");
859        assert_eq!(finding.actions[3].kind, CloneFamilyActionType::SuppressLine);
860        assert_eq!(finding.groups.len(), 2);
861        for inner in &finding.groups {
862            assert_eq!(inner.actions.len(), 2);
863            assert_eq!(inner.actions[0].kind, CloneGroupActionType::ExtractShared);
864            assert_eq!(inner.actions[1].kind, CloneGroupActionType::SuppressLine);
865        }
866    }
867
868    #[test]
869    fn clone_family_finding_with_no_suggestions_emits_two_actions() {
870        let family = CloneFamily {
871            files: vec![PathBuf::from("/root/a.ts")],
872            groups: vec![group(2)],
873            total_duplicated_lines: 20,
874            total_duplicated_tokens: 100,
875            suggestions: Vec::new(),
876        };
877        let fingerprints = CloneFingerprintSet::from_groups(&family.groups);
878        let finding = CloneFamilyFinding::with_fingerprints(family, &fingerprints);
879        assert_eq!(finding.actions.len(), 2);
880        assert_eq!(
881            finding.actions[0].kind,
882            CloneFamilyActionType::ExtractShared
883        );
884        assert_eq!(finding.actions[1].kind, CloneFamilyActionType::SuppressLine);
885    }
886
887    #[test]
888    fn payload_from_report_wraps_all_findings() {
889        let report = DuplicationReport {
890            clone_groups: vec![group(2), group(3)],
891            clone_families: vec![CloneFamily {
892                files: vec![PathBuf::from("/root/a.ts")],
893                groups: vec![group(2)],
894                total_duplicated_lines: 20,
895                total_duplicated_tokens: 100,
896                suggestions: Vec::new(),
897            }],
898            mirrored_directories: Vec::new(),
899            stats: DuplicationStats::default(),
900        };
901        let payload = DupesReportPayload::from_report(&report);
902        assert_eq!(payload.clone_groups.len(), 2);
903        assert_eq!(payload.clone_families.len(), 1);
904        for finding in &payload.clone_groups {
905            assert_eq!(finding.actions.len(), 2);
906        }
907        assert_eq!(payload.clone_families[0].actions.len(), 2);
908    }
909
910    #[test]
911    fn duplication_codeclimate_uses_relative_normalized_paths() {
912        let report = DuplicationReport {
913            clone_groups: vec![CloneGroup {
914                instances: vec![CloneInstance {
915                    is_symlink: false,
916                    file: PathBuf::from("/root/app/[id]/page.tsx"),
917                    start_line: 4,
918                    end_line: 8,
919                    start_col: 0,
920                    end_col: 0,
921                    fragment: "const duplicate = 1;".to_string(),
922                }],
923                token_count: 42,
924                line_count: 5,
925                similarity: None,
926            }],
927            clone_families: Vec::new(),
928            mirrored_directories: Vec::new(),
929            stats: DuplicationStats::default(),
930        };
931
932        let issues = build_duplication_codeclimate(&report, Path::new("/root"));
933
934        assert_eq!(issues.len(), 1);
935        let issue = &issues[0];
936        assert_eq!(issue.check_name, "fallow/code-duplication");
937        assert_eq!(issue.location.path, "app/%5Bid%5D/page.tsx");
938        assert_eq!(issue.location.lines.begin, 4);
939        assert_eq!(issue.categories, vec!["Duplication"]);
940        assert!(issue.description.starts_with("Code clone dup:"));
941        assert_eq!(issue.location.lines.end, Some(8));
942    }
943}