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    RangeMarkerFinding, 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    /// `fallow-ignore-start` and `fallow-ignore-end` markers with a problem.
351    /// A marker with a problem has no effect on clone detection.
352    #[serde(default, skip_serializing_if = "Vec::is_empty")]
353    pub range_marker_problems: Vec<RangeMarkerFinding>,
354    /// Aggregate duplication statistics.
355    pub stats: DuplicationStats,
356}
357
358/// Wire shape of the `dupes` section inside the bare combined envelope.
359///
360/// The section is the standalone payload plus the view of the loaded
361/// duplication baseline. The standalone `dupes` envelope carries the same
362/// `baseline_staleness` key at its root.
363#[derive(Debug, Clone, Serialize)]
364#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
365pub struct CombinedDupesSection {
366    /// The duplication payload, flattened into the section.
367    #[serde(flatten)]
368    pub payload: DupesReportPayload,
369    /// This run's view of the loaded duplication baseline, present only when
370    /// `--dupes-baseline` loaded one. Read `change_scoped` before dividing
371    /// `matched_entries` by `baseline_entries`: a narrowed run can report
372    /// `matched_entries: 0` on a healthy baseline.
373    #[serde(default, skip_serializing_if = "Option::is_none")]
374    pub baseline_staleness: Option<fallow_output::BaselineStaleness>,
375}
376
377impl DupesReportPayload {
378    /// Build the payload from a bare [`DuplicationReport`].
379    #[must_use]
380    pub fn from_report(report: &DuplicationReport) -> Self {
381        let fingerprints = CloneFingerprintSet::from_groups(&report.clone_groups);
382        Self {
383            clone_groups: report
384                .clone_groups
385                .iter()
386                .map(|group| {
387                    CloneGroupFinding::with_fingerprint(
388                        group.clone(),
389                        fingerprints.fingerprint_for_group(group),
390                    )
391                })
392                .collect(),
393            clone_families: report
394                .clone_families
395                .iter()
396                .map(|family| CloneFamilyFinding::with_fingerprints(family.clone(), &fingerprints))
397                .collect(),
398            mirrored_directories: report.mirrored_directories.clone(),
399            range_marker_problems: report.range_marker_problems.clone(),
400            stats: report.stats.clone(),
401        }
402    }
403
404    /// Build the payload and drop the verbatim source text when the caller
405    /// asked for a location-only body.
406    ///
407    /// Fingerprints, suggested names and actions are computed by
408    /// [`Self::from_report`], so the text is only removed after every consumer
409    /// that reads it has run.
410    #[must_use]
411    pub fn from_report_with_fragments(report: &DuplicationReport, include_fragments: bool) -> Self {
412        let mut payload = Self::from_report(report);
413        if !include_fragments {
414            payload.strip_fragments();
415        }
416        payload
417    }
418
419    /// Drop the verbatim source text from every clone instance, including the
420    /// copies nested in `clone_families[].groups[]`.
421    pub fn strip_fragments(&mut self) {
422        for finding in &mut self.clone_groups {
423            finding.group.strip_fragments();
424        }
425        for family in &mut self.clone_families {
426            for finding in &mut family.groups {
427                finding.group.strip_fragments();
428            }
429        }
430    }
431}
432
433/// The number of fragment characters in the CodeClimate fingerprint of a
434/// clone instance. The count leaves out `\r`, so a CRLF checkout and an LF
435/// checkout of the same code give the same fingerprint.
436const CODECLIMATE_FRAGMENT_PREFIX_CHARS: usize = 64;
437
438/// Build CodeClimate issues from duplication analysis results.
439///
440/// `fallow-output` owns the CodeClimate wire DTOs. This API layer combines
441/// those DTOs with the engine-owned duplication report so CLI and future
442/// embedders can share the same issue construction policy.
443#[must_use]
444#[expect(
445    clippy::cast_possible_truncation,
446    reason = "line numbers are bounded by source size"
447)]
448pub fn build_duplication_codeclimate(
449    report: &DuplicationReport,
450    root: &Path,
451) -> Vec<CodeClimateIssue> {
452    let mut issues = Vec::new();
453
454    let fingerprints = CloneFingerprintSet::from_groups(&report.clone_groups);
455    for group in &report.clone_groups {
456        let clone_fingerprint = fingerprints.fingerprint_for_group(group);
457        let token_str = group.token_count.to_string();
458        let line_count_str = group.line_count.to_string();
459        let fragment_prefix: String = group
460            .instances
461            .first()
462            .map(|inst| {
463                inst.fragment
464                    .chars()
465                    .filter(|&c| c != '\r')
466                    .take(CODECLIMATE_FRAGMENT_PREFIX_CHARS)
467                    .collect()
468            })
469            .unwrap_or_default();
470
471        for (instance_index, instance) in group.instances.iter().enumerate() {
472            let path = codeclimate_path(&instance.file, root);
473            let start_str = instance.start_line.to_string();
474            let fp = codeclimate_fingerprint_hash(&[
475                "fallow/code-duplication",
476                &path,
477                &start_str,
478                &token_str,
479                &line_count_str,
480                &fragment_prefix,
481            ]);
482            let mut issue = fallow_output::build_codeclimate_issue(CodeClimateIssueInput {
483                check_name: "fallow/code-duplication",
484                description: &format!(
485                    "{} lines repeat in {} places (clone group {clone_fingerprint})",
486                    group.line_count,
487                    group.instances.len()
488                ),
489                severity: CodeClimateSeverity::Minor,
490                category: "Duplication",
491                path: &path,
492                begin_line: Some(instance.start_line as u32),
493                fingerprint: &fp,
494            });
495            issue.location.lines.end = Some(instance.end_line as u32);
496            issue.other_locations = group
497                .instances
498                .iter()
499                .enumerate()
500                .filter(|(peer_index, _)| *peer_index != instance_index)
501                .map(|(_, peer)| fallow_output::CodeClimateLocation {
502                    path: codeclimate_path(&peer.file, root),
503                    lines: fallow_output::CodeClimateLines {
504                        begin: peer.start_line as u32,
505                        end: Some(peer.end_line as u32),
506                    },
507                })
508                .collect();
509            issue.other_locations.sort_by(|a, b| {
510                (&a.path, a.lines.begin, a.lines.end).cmp(&(&b.path, b.lines.begin, b.lines.end))
511            });
512            issues.push(issue);
513        }
514    }
515
516    issues
517}
518
519/// Set the audit attribution on the issues of [`build_duplication_codeclimate`].
520///
521/// `introduced` holds one audit flag per clone group, in report order. Each
522/// group gives one issue per instance, so the instances of one group get the
523/// flag of that group. The inline review comment then states if the change
524/// introduced the clone group.
525pub fn set_duplication_audit_attribution(
526    issues: &mut [CodeClimateIssue],
527    report: &DuplicationReport,
528    introduced: impl IntoIterator<Item = bool>,
529) {
530    let mut remaining = issues;
531    for (group, introduced) in report.clone_groups.iter().zip(introduced) {
532        let count = group.instances.len().min(remaining.len());
533        let (group_issues, rest) = remaining.split_at_mut(count);
534        let context = crate::dead_code_codeclimate::audit_review_context(introduced);
535        for issue in group_issues {
536            issue.audit = Some(context);
537        }
538        remaining = rest;
539    }
540}
541
542fn codeclimate_path(path: &Path, root: &Path) -> String {
543    normalize_uri(
544        &path
545            .strip_prefix(root)
546            .unwrap_or(path)
547            .display()
548            .to_string(),
549    )
550}
551
552#[cfg(test)]
553mod tests {
554    use std::path::Path;
555
556    use fallow_output::{CloneFamilyActionType, CloneGroupActionType};
557    use fallow_types::duplicates::{
558        CloneInstance, DuplicationStats, RefactoringKind, RefactoringSuggestion,
559    };
560
561    use super::*;
562
563    const TEST_FINGERPRINT: &str = "dup:00000000";
564
565    fn instance(path: &str) -> CloneInstance {
566        CloneInstance {
567            is_symlink: false,
568            file: PathBuf::from(path),
569            start_line: 1,
570            end_line: 10,
571            start_col: 0,
572            end_col: 0,
573            fragment: String::new(),
574        }
575    }
576
577    fn group(instances: usize) -> CloneGroup {
578        CloneGroup {
579            instances: (0..instances)
580                .map(|i| instance(&format!("/root/file_{i}.ts")))
581                .collect(),
582            token_count: 100,
583            line_count: 20,
584            similarity: None,
585        }
586    }
587
588    fn report_with_fragment(fragment: &str) -> DuplicationReport {
589        let mut clones = group(2);
590        for instance in &mut clones.instances {
591            instance.fragment = fragment.to_owned();
592        }
593        DuplicationReport {
594            clone_groups: vec![clones],
595            clone_families: Vec::new(),
596            mirrored_directories: Vec::new(),
597            range_marker_problems: Vec::new(),
598            stats: DuplicationStats::default(),
599        }
600    }
601
602    fn codeclimate_fingerprints(fragment: &str) -> Vec<String> {
603        build_duplication_codeclimate(&report_with_fragment(fragment), Path::new("/root"))
604            .into_iter()
605            .map(|issue| issue.fingerprint)
606            .collect()
607    }
608
609    /// The prefix holds more than 64 characters, so each `\r` moves a later
610    /// character out of a raw 64-character prefix.
611    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";
612
613    #[test]
614    fn codeclimate_clone_fingerprints_ignore_crlf_line_endings() {
615        let crlf = LF_FRAGMENT.replace('\n', "\r\n");
616        assert_eq!(
617            codeclimate_fingerprints(LF_FRAGMENT),
618            codeclimate_fingerprints(&crlf)
619        );
620    }
621
622    #[test]
623    fn codeclimate_clone_fingerprints_keep_the_lf_hash() {
624        let prefix: String = LF_FRAGMENT.chars().take(64).collect();
625        let expected: Vec<String> = ["/root/file_0.ts", "/root/file_1.ts"]
626            .iter()
627            .map(|path| {
628                codeclimate_fingerprint_hash(&[
629                    "fallow/code-duplication",
630                    &codeclimate_path(Path::new(path), Path::new("/root")),
631                    "1",
632                    "100",
633                    "20",
634                    &prefix,
635                ])
636            })
637            .collect();
638        assert_eq!(codeclimate_fingerprints(LF_FRAGMENT), expected);
639    }
640
641    #[test]
642    fn duplication_audit_attribution_follows_each_group() {
643        use fallow_output::AuditFindingAttribution as A;
644        let report = DuplicationReport {
645            clone_groups: vec![group(2), group(3)],
646            clone_families: Vec::new(),
647            mirrored_directories: Vec::new(),
648            range_marker_problems: Vec::new(),
649            stats: DuplicationStats::default(),
650        };
651        let root = Path::new("/root");
652        let plain = build_duplication_codeclimate(&report, root);
653        let mut issues = plain.clone();
654        set_duplication_audit_attribution(&mut issues, &report, [false, true]);
655        let attributions: Vec<_> = issues
656            .iter()
657            .map(|issue| issue.audit.map(|context| context.attribution))
658            .collect();
659        assert_eq!(
660            attributions,
661            [
662                Some(A::Inherited),
663                Some(A::Inherited),
664                Some(A::Introduced),
665                Some(A::Introduced),
666                Some(A::Introduced),
667            ]
668        );
669        for (with, without) in issues.iter().zip(&plain) {
670            assert_eq!(with.fingerprint, without.fingerprint);
671            assert_eq!(
672                serde_json::to_value(with).expect("issue serializes"),
673                serde_json::to_value(without).expect("issue serializes"),
674                "the wire shape does not carry the attribution"
675            );
676        }
677    }
678
679    #[test]
680    fn clone_group_finding_position_0_is_extract_shared() {
681        let finding = CloneGroupFinding::with_fingerprint(group(2), TEST_FINGERPRINT.to_string());
682        assert_eq!(finding.actions.len(), 3);
683        assert_eq!(finding.actions[0].kind, CloneGroupActionType::ExtractShared);
684        assert_eq!(finding.actions[1].kind, CloneGroupActionType::SuppressLine);
685        assert_eq!(finding.actions[2].kind, CloneGroupActionType::SuppressRange);
686        assert!(finding.introduced.is_none());
687        assert!(finding.demotion_reason.is_none());
688    }
689
690    #[test]
691    fn clone_group_finding_omits_audit_only_fields_outside_audit() {
692        // `fallow dupes --format json` serializes findings straight from Rust;
693        // the audit-only `introduced` / `demotion_reason` keys must not appear.
694        let finding = CloneGroupFinding::with_fingerprint(group(2), TEST_FINGERPRINT.to_string());
695        let value = serde_json::to_value(&finding).expect("finding serializes");
696        assert!(value.get("introduced").is_none());
697        assert!(value.get("demotion_reason").is_none());
698    }
699
700    #[test]
701    fn suppressed_fragments_leave_locations_and_fingerprints_intact() {
702        let mut with_text = group(2);
703        for (index, instance) in with_text.instances.iter_mut().enumerate() {
704            instance.fragment = format!("const shared{index} = compute(input);");
705        }
706        let family = CloneFamily {
707            files: vec![PathBuf::from("/root/file_0.ts")],
708            groups: vec![with_text.clone()],
709            total_duplicated_lines: 20,
710            total_duplicated_tokens: 100,
711            suggestions: Vec::new(),
712        };
713        let report = DuplicationReport {
714            clone_groups: vec![with_text],
715            clone_families: vec![family],
716            mirrored_directories: Vec::new(),
717            range_marker_problems: Vec::new(),
718            stats: DuplicationStats::default(),
719        };
720
721        let kept = DupesReportPayload::from_report_with_fragments(&report, true);
722        let dropped = DupesReportPayload::from_report_with_fragments(&report, false);
723
724        assert_eq!(
725            kept.clone_groups[0].fingerprint, dropped.clone_groups[0].fingerprint,
726            "fingerprints are computed before the text is dropped"
727        );
728
729        let kept_value = serde_json::to_value(&kept).expect("payload serializes");
730        assert!(kept_value["clone_groups"][0]["instances"][0]["fragment"].is_string());
731
732        let value = serde_json::to_value(&dropped).expect("payload serializes");
733        let instance = &value["clone_groups"][0]["instances"][0];
734        assert!(
735            instance.get("fragment").is_none(),
736            "the verbatim source text must be absent, not empty"
737        );
738        assert!(instance.get("file").is_some());
739        assert!(instance.get("start_line").is_some());
740        assert!(instance.get("end_col").is_some());
741        assert!(
742            value["clone_families"][0]["groups"][0]["instances"][0]
743                .get("fragment")
744                .is_none(),
745            "nested clone-family copies carry the same text and must be dropped too"
746        );
747    }
748
749    #[test]
750    fn clone_demotion_reason_wire_name_matches_serde_representation() {
751        let reason = CloneDemotionReason::NoAddedLines;
752        assert_eq!(
753            serde_json::to_value(reason).expect("reason serializes"),
754            serde_json::Value::String(reason.wire_name())
755        );
756        assert_eq!(reason.wire_name(), "no-added-lines");
757    }
758
759    #[test]
760    fn attributed_clone_group_finding_actions_match_clone_group_shape() {
761        let attributed = AttributedCloneGroup {
762            primary_owner: "src".to_string(),
763            token_count: 100,
764            line_count: 20,
765            similarity: None,
766            instances: vec![
767                AttributedInstance {
768                    instance: instance("/root/src/a.ts"),
769                    owner: "src".to_string(),
770                },
771                AttributedInstance {
772                    instance: instance("/root/src/b.ts"),
773                    owner: "src".to_string(),
774                },
775            ],
776        };
777        let finding =
778            AttributedCloneGroupFinding::with_fingerprint(attributed, TEST_FINGERPRINT.to_string());
779        assert_eq!(finding.actions.len(), 3);
780        assert_eq!(finding.actions[0].kind, CloneGroupActionType::ExtractShared);
781        assert_eq!(finding.actions[1].kind, CloneGroupActionType::SuppressLine);
782        assert_eq!(finding.actions[2].kind, CloneGroupActionType::SuppressRange);
783    }
784
785    #[test]
786    fn clone_group_finding_surfaces_dominant_identifier() {
787        let fragment = "function parseCsv() { parseCsv(); parseCsv(); return parseCsv; }";
788        let g = CloneGroup {
789            instances: vec![
790                CloneInstance {
791                    is_symlink: false,
792                    file: PathBuf::from("/root/a.ts"),
793                    start_line: 1,
794                    end_line: 3,
795                    start_col: 0,
796                    end_col: 0,
797                    fragment: fragment.to_string(),
798                },
799                CloneInstance {
800                    is_symlink: false,
801                    file: PathBuf::from("/root/b.ts"),
802                    start_line: 1,
803                    end_line: 3,
804                    start_col: 0,
805                    end_col: 0,
806                    fragment: fragment.to_string(),
807                },
808            ],
809            token_count: 100,
810            line_count: 3,
811            similarity: None,
812        };
813        let finding = CloneGroupFinding::with_fingerprint(g, TEST_FINGERPRINT.to_string());
814        assert_eq!(finding.suggested_name.as_deref(), Some("parseCsv"));
815    }
816
817    #[test]
818    fn clone_group_finding_suggested_name_none_for_unnamed_fragment() {
819        let finding = CloneGroupFinding::with_fingerprint(group(2), TEST_FINGERPRINT.to_string());
820        assert!(finding.suggested_name.is_none());
821    }
822
823    #[test]
824    fn clone_group_finding_description_pluralises_instance_count() {
825        let single = CloneGroupFinding::with_fingerprint(group(1), TEST_FINGERPRINT.to_string());
826        assert!(single.actions[0].description.contains("1 instance"));
827        assert!(!single.actions[0].description.contains("1 instances"));
828        let multi = CloneGroupFinding::with_fingerprint(group(3), TEST_FINGERPRINT.to_string());
829        assert!(multi.actions[0].description.contains("3 instances"));
830    }
831
832    #[test]
833    fn clone_family_finding_position_0_is_extract_shared_then_suggestions_then_suppress() {
834        let family = CloneFamily {
835            files: vec![PathBuf::from("/root/a.ts"), PathBuf::from("/root/b.ts")],
836            groups: vec![group(2), group(2)],
837            total_duplicated_lines: 40,
838            total_duplicated_tokens: 200,
839            suggestions: vec![
840                RefactoringSuggestion {
841                    kind: RefactoringKind::ExtractFunction,
842                    description: "Extract helper".to_string(),
843                    estimated_savings: 10,
844                },
845                RefactoringSuggestion {
846                    kind: RefactoringKind::ExtractModule,
847                    description: "Extract module".to_string(),
848                    estimated_savings: 30,
849                },
850            ],
851        };
852        let fingerprints = CloneFingerprintSet::from_groups(&family.groups);
853        let finding = CloneFamilyFinding::with_fingerprints(family, &fingerprints);
854        assert_eq!(finding.actions.len(), 4);
855        assert_eq!(
856            finding.actions[0].kind,
857            CloneFamilyActionType::ExtractShared
858        );
859        assert_eq!(
860            finding.actions[1].kind,
861            CloneFamilyActionType::ApplySuggestion
862        );
863        assert_eq!(finding.actions[1].description, "Extract helper");
864        assert_eq!(
865            finding.actions[2].kind,
866            CloneFamilyActionType::ApplySuggestion
867        );
868        assert_eq!(finding.actions[2].description, "Extract module");
869        assert_eq!(finding.actions[3].kind, CloneFamilyActionType::SuppressLine);
870        assert_eq!(finding.groups.len(), 2);
871        for inner in &finding.groups {
872            assert_eq!(inner.actions.len(), 3);
873            assert_eq!(inner.actions[0].kind, CloneGroupActionType::ExtractShared);
874            assert_eq!(inner.actions[1].kind, CloneGroupActionType::SuppressLine);
875            assert_eq!(inner.actions[2].kind, CloneGroupActionType::SuppressRange);
876        }
877    }
878
879    #[test]
880    fn clone_family_finding_with_no_suggestions_emits_two_actions() {
881        let family = CloneFamily {
882            files: vec![PathBuf::from("/root/a.ts")],
883            groups: vec![group(2)],
884            total_duplicated_lines: 20,
885            total_duplicated_tokens: 100,
886            suggestions: Vec::new(),
887        };
888        let fingerprints = CloneFingerprintSet::from_groups(&family.groups);
889        let finding = CloneFamilyFinding::with_fingerprints(family, &fingerprints);
890        assert_eq!(finding.actions.len(), 2);
891        assert_eq!(
892            finding.actions[0].kind,
893            CloneFamilyActionType::ExtractShared
894        );
895        assert_eq!(finding.actions[1].kind, CloneFamilyActionType::SuppressLine);
896    }
897
898    #[test]
899    fn payload_from_report_wraps_all_findings() {
900        let report = DuplicationReport {
901            clone_groups: vec![group(2), group(3)],
902            clone_families: vec![CloneFamily {
903                files: vec![PathBuf::from("/root/a.ts")],
904                groups: vec![group(2)],
905                total_duplicated_lines: 20,
906                total_duplicated_tokens: 100,
907                suggestions: Vec::new(),
908            }],
909            mirrored_directories: Vec::new(),
910            range_marker_problems: Vec::new(),
911            stats: DuplicationStats::default(),
912        };
913        let payload = DupesReportPayload::from_report(&report);
914        assert_eq!(payload.clone_groups.len(), 2);
915        assert_eq!(payload.clone_families.len(), 1);
916        for finding in &payload.clone_groups {
917            assert_eq!(finding.actions.len(), 3);
918        }
919        assert_eq!(payload.clone_families[0].actions.len(), 2);
920    }
921
922    #[test]
923    fn duplication_codeclimate_uses_relative_normalized_paths() {
924        let report = DuplicationReport {
925            clone_groups: vec![CloneGroup {
926                instances: vec![CloneInstance {
927                    is_symlink: false,
928                    file: PathBuf::from("/root/app/[id]/page.tsx"),
929                    start_line: 4,
930                    end_line: 8,
931                    start_col: 0,
932                    end_col: 0,
933                    fragment: "const duplicate = 1;".to_string(),
934                }],
935                token_count: 42,
936                line_count: 5,
937                similarity: None,
938            }],
939            clone_families: Vec::new(),
940            mirrored_directories: Vec::new(),
941            range_marker_problems: Vec::new(),
942            stats: DuplicationStats::default(),
943        };
944
945        let issues = build_duplication_codeclimate(&report, Path::new("/root"));
946
947        assert_eq!(issues.len(), 1);
948        let issue = &issues[0];
949        assert_eq!(issue.check_name, "fallow/code-duplication");
950        assert_eq!(issue.location.path, "app/%5Bid%5D/page.tsx");
951        assert_eq!(issue.location.lines.begin, 4);
952        assert_eq!(issue.categories, vec!["Duplication"]);
953        assert!(
954            issue.description.contains("(clone group dup:"),
955            "{}",
956            issue.description
957        );
958        assert_eq!(issue.location.lines.end, Some(8));
959    }
960}