Skip to main content

fallow_cli/report/
json.rs

1use std::path::Path;
2use std::process::ExitCode;
3use std::time::Duration;
4
5use fallow_core::duplicates::DuplicationReport;
6use fallow_core::results::AnalysisResults;
7
8use super::emit_json;
9use crate::explain;
10use crate::report::grouping::{OwnershipResolver, ResultGroup};
11
12pub(super) fn print_json(
13    results: &AnalysisResults,
14    root: &Path,
15    elapsed: Duration,
16    explain: bool,
17    regression: Option<&crate::regression::RegressionOutcome>,
18) -> ExitCode {
19    match build_json(results, root, elapsed) {
20        Ok(mut output) => {
21            if let Some(outcome) = regression
22                && let serde_json::Value::Object(ref mut map) = output
23            {
24                map.insert("regression".to_string(), outcome.to_json());
25            }
26            if explain {
27                insert_meta(&mut output, explain::check_meta());
28            }
29            emit_json(&output, "JSON")
30        }
31        Err(e) => {
32            eprintln!("Error: failed to serialize results: {e}");
33            ExitCode::from(2)
34        }
35    }
36}
37
38/// Render grouped analysis results as a single JSON document.
39///
40/// Produces an envelope with `grouped_by` and `total_issues` at the top level,
41/// then a `groups` array where each element contains the group `key`,
42/// `total_issues`, and all the normal result fields with paths relativized.
43#[must_use]
44pub(super) fn print_grouped_json(
45    groups: &[ResultGroup],
46    original: &AnalysisResults,
47    root: &Path,
48    elapsed: Duration,
49    explain: bool,
50    resolver: &OwnershipResolver,
51) -> ExitCode {
52    let root_prefix = format!("{}/", root.display());
53
54    let group_values: Vec<serde_json::Value> = groups
55        .iter()
56        .filter_map(|group| {
57            let mut value = serde_json::to_value(&group.results).ok()?;
58            strip_root_prefix(&mut value, &root_prefix);
59            inject_actions(&mut value);
60
61            if let serde_json::Value::Object(ref mut map) = value {
62                // Insert key and total_issues at the front by rebuilding the map
63                let mut ordered = serde_json::Map::new();
64                ordered.insert("key".to_string(), serde_json::json!(group.key));
65                ordered.insert(
66                    "total_issues".to_string(),
67                    serde_json::json!(group.results.total_issues()),
68                );
69                for (k, v) in map.iter() {
70                    ordered.insert(k.clone(), v.clone());
71                }
72                Some(serde_json::Value::Object(ordered))
73            } else {
74                Some(value)
75            }
76        })
77        .collect();
78
79    let mut output = serde_json::json!({
80        "schema_version": SCHEMA_VERSION,
81        "version": env!("CARGO_PKG_VERSION"),
82        "elapsed_ms": elapsed.as_millis() as u64,
83        "grouped_by": resolver.mode_label(),
84        "total_issues": original.total_issues(),
85        "groups": group_values,
86    });
87
88    if explain {
89        insert_meta(&mut output, explain::check_meta());
90    }
91
92    emit_json(&output, "JSON")
93}
94
95/// JSON output schema version as an integer (independent of tool version).
96///
97/// Bump this when the structure of the JSON output changes in a
98/// backwards-incompatible way (removing/renaming fields, changing types).
99/// Adding new fields is always backwards-compatible and does not require a bump.
100const SCHEMA_VERSION: u32 = 3;
101
102/// Build a JSON envelope with standard metadata fields at the top.
103///
104/// Creates a JSON object with `schema_version`, `version`, and `elapsed_ms`,
105/// then merges all fields from `report_value` into the envelope.
106/// Fields from `report_value` appear after the metadata header.
107fn build_json_envelope(report_value: serde_json::Value, elapsed: Duration) -> serde_json::Value {
108    let mut map = serde_json::Map::new();
109    map.insert(
110        "schema_version".to_string(),
111        serde_json::json!(SCHEMA_VERSION),
112    );
113    map.insert(
114        "version".to_string(),
115        serde_json::json!(env!("CARGO_PKG_VERSION")),
116    );
117    map.insert(
118        "elapsed_ms".to_string(),
119        serde_json::json!(elapsed.as_millis()),
120    );
121    if let serde_json::Value::Object(report_map) = report_value {
122        for (key, value) in report_map {
123            map.insert(key, value);
124        }
125    }
126    serde_json::Value::Object(map)
127}
128
129/// Build the JSON output value for analysis results.
130///
131/// Metadata fields (`schema_version`, `version`, `elapsed_ms`, `total_issues`)
132/// appear first in the output for readability. Paths are made relative to `root`.
133///
134/// # Errors
135///
136/// Returns an error if the results cannot be serialized to JSON.
137pub fn build_json(
138    results: &AnalysisResults,
139    root: &Path,
140    elapsed: Duration,
141) -> Result<serde_json::Value, serde_json::Error> {
142    let results_value = serde_json::to_value(results)?;
143
144    let mut map = serde_json::Map::new();
145    map.insert(
146        "schema_version".to_string(),
147        serde_json::json!(SCHEMA_VERSION),
148    );
149    map.insert(
150        "version".to_string(),
151        serde_json::json!(env!("CARGO_PKG_VERSION")),
152    );
153    map.insert(
154        "elapsed_ms".to_string(),
155        serde_json::json!(elapsed.as_millis()),
156    );
157    map.insert(
158        "total_issues".to_string(),
159        serde_json::json!(results.total_issues()),
160    );
161
162    // Entry-point detection summary (metadata, not serialized via serde)
163    if let Some(ref ep) = results.entry_point_summary {
164        let sources: serde_json::Map<String, serde_json::Value> = ep
165            .by_source
166            .iter()
167            .map(|(k, v)| (k.replace(' ', "_"), serde_json::json!(v)))
168            .collect();
169        map.insert(
170            "entry_points".to_string(),
171            serde_json::json!({
172                "total": ep.total,
173                "sources": sources,
174            }),
175        );
176    }
177
178    // Per-category summary counts for CI dashboard consumption
179    let summary = serde_json::json!({
180        "total_issues": results.total_issues(),
181        "unused_files": results.unused_files.len(),
182        "unused_exports": results.unused_exports.len(),
183        "unused_types": results.unused_types.len(),
184        "unused_dependencies": results.unused_dependencies.len()
185            + results.unused_dev_dependencies.len()
186            + results.unused_optional_dependencies.len(),
187        "unused_enum_members": results.unused_enum_members.len(),
188        "unused_class_members": results.unused_class_members.len(),
189        "unresolved_imports": results.unresolved_imports.len(),
190        "unlisted_dependencies": results.unlisted_dependencies.len(),
191        "duplicate_exports": results.duplicate_exports.len(),
192        "type_only_dependencies": results.type_only_dependencies.len(),
193        "test_only_dependencies": results.test_only_dependencies.len(),
194        "circular_dependencies": results.circular_dependencies.len(),
195        "boundary_violations": results.boundary_violations.len(),
196    });
197    map.insert("summary".to_string(), summary);
198
199    if let serde_json::Value::Object(results_map) = results_value {
200        for (key, value) in results_map {
201            map.insert(key, value);
202        }
203    }
204
205    let mut output = serde_json::Value::Object(map);
206    let root_prefix = format!("{}/", root.display());
207    // strip_root_prefix must run before inject_actions so that injected
208    // action fields (static strings and package names) are not processed
209    // by the path stripper.
210    strip_root_prefix(&mut output, &root_prefix);
211    inject_actions(&mut output);
212    Ok(output)
213}
214
215/// Recursively strip the root prefix from all string values in the JSON tree.
216///
217/// This converts absolute paths (e.g., `/home/runner/work/repo/repo/src/utils.ts`)
218/// to relative paths (`src/utils.ts`) for all output fields.
219fn strip_root_prefix(value: &mut serde_json::Value, prefix: &str) {
220    match value {
221        serde_json::Value::String(s) => {
222            if let Some(rest) = s.strip_prefix(prefix) {
223                *s = rest.to_string();
224            }
225        }
226        serde_json::Value::Array(arr) => {
227            for item in arr {
228                strip_root_prefix(item, prefix);
229            }
230        }
231        serde_json::Value::Object(map) => {
232            for (_, v) in map.iter_mut() {
233                strip_root_prefix(v, prefix);
234            }
235        }
236        _ => {}
237    }
238}
239
240// ── Fix action injection ────────────────────────────────────────
241
242/// Suppress mechanism for an issue type.
243enum SuppressKind {
244    /// `// fallow-ignore-next-line <type>` on the line before.
245    InlineComment,
246    /// `// fallow-ignore-file <type>` at the top of the file.
247    FileComment,
248    /// Add to `ignoreDependencies` in fallow config.
249    ConfigIgnoreDep,
250}
251
252/// Specification for actions to inject per issue type.
253struct ActionSpec {
254    fix_type: &'static str,
255    auto_fixable: bool,
256    description: &'static str,
257    note: Option<&'static str>,
258    suppress: SuppressKind,
259    issue_kind: &'static str,
260}
261
262/// Map an issue array key to its action specification.
263fn actions_for_issue_type(key: &str) -> Option<ActionSpec> {
264    match key {
265        "unused_files" => Some(ActionSpec {
266            fix_type: "delete-file",
267            auto_fixable: false,
268            description: "Delete this file",
269            note: Some(
270                "File deletion may remove runtime functionality not visible to static analysis",
271            ),
272            suppress: SuppressKind::FileComment,
273            issue_kind: "unused-file",
274        }),
275        "unused_exports" => Some(ActionSpec {
276            fix_type: "remove-export",
277            auto_fixable: true,
278            description: "Remove the `export` keyword from the declaration",
279            note: None,
280            suppress: SuppressKind::InlineComment,
281            issue_kind: "unused-export",
282        }),
283        "unused_types" => Some(ActionSpec {
284            fix_type: "remove-export",
285            auto_fixable: true,
286            description: "Remove the `export` (or `export type`) keyword from the type declaration",
287            note: None,
288            suppress: SuppressKind::InlineComment,
289            issue_kind: "unused-type",
290        }),
291        "unused_dependencies" => Some(ActionSpec {
292            fix_type: "remove-dependency",
293            auto_fixable: true,
294            description: "Remove from dependencies in package.json",
295            note: None,
296            suppress: SuppressKind::ConfigIgnoreDep,
297            issue_kind: "unused-dependency",
298        }),
299        "unused_dev_dependencies" => Some(ActionSpec {
300            fix_type: "remove-dependency",
301            auto_fixable: true,
302            description: "Remove from devDependencies in package.json",
303            note: None,
304            suppress: SuppressKind::ConfigIgnoreDep,
305            issue_kind: "unused-dev-dependency",
306        }),
307        "unused_optional_dependencies" => Some(ActionSpec {
308            fix_type: "remove-dependency",
309            auto_fixable: true,
310            description: "Remove from optionalDependencies in package.json",
311            note: None,
312            suppress: SuppressKind::ConfigIgnoreDep,
313            // No IssueKind variant exists for optional deps — uses config suppress only.
314            issue_kind: "unused-dependency",
315        }),
316        "unused_enum_members" => Some(ActionSpec {
317            fix_type: "remove-enum-member",
318            auto_fixable: true,
319            description: "Remove this enum member",
320            note: None,
321            suppress: SuppressKind::InlineComment,
322            issue_kind: "unused-enum-member",
323        }),
324        "unused_class_members" => Some(ActionSpec {
325            fix_type: "remove-class-member",
326            auto_fixable: false,
327            description: "Remove this class member",
328            note: Some("Class member may be used via dependency injection or decorators"),
329            suppress: SuppressKind::InlineComment,
330            issue_kind: "unused-class-member",
331        }),
332        "unresolved_imports" => Some(ActionSpec {
333            fix_type: "resolve-import",
334            auto_fixable: false,
335            description: "Fix the import specifier or install the missing module",
336            note: Some("Verify the module path and check tsconfig paths configuration"),
337            suppress: SuppressKind::InlineComment,
338            issue_kind: "unresolved-import",
339        }),
340        "unlisted_dependencies" => Some(ActionSpec {
341            fix_type: "install-dependency",
342            auto_fixable: false,
343            description: "Add this package to dependencies in package.json",
344            note: Some("Verify this package should be a direct dependency before adding"),
345            suppress: SuppressKind::ConfigIgnoreDep,
346            issue_kind: "unlisted-dependency",
347        }),
348        "duplicate_exports" => Some(ActionSpec {
349            fix_type: "remove-duplicate",
350            auto_fixable: false,
351            description: "Keep one canonical export location and remove the others",
352            note: Some("Review all locations to determine which should be the canonical export"),
353            suppress: SuppressKind::InlineComment,
354            issue_kind: "duplicate-export",
355        }),
356        "type_only_dependencies" => Some(ActionSpec {
357            fix_type: "move-to-dev",
358            auto_fixable: false,
359            description: "Move to devDependencies (only type imports are used)",
360            note: Some(
361                "Type imports are erased at runtime so this dependency is not needed in production",
362            ),
363            suppress: SuppressKind::ConfigIgnoreDep,
364            issue_kind: "type-only-dependency",
365        }),
366        "test_only_dependencies" => Some(ActionSpec {
367            fix_type: "move-to-dev",
368            auto_fixable: false,
369            description: "Move to devDependencies (only test files import this)",
370            note: Some(
371                "Only test files import this package so it does not need to be a production dependency",
372            ),
373            suppress: SuppressKind::ConfigIgnoreDep,
374            issue_kind: "test-only-dependency",
375        }),
376        "circular_dependencies" => Some(ActionSpec {
377            fix_type: "refactor-cycle",
378            auto_fixable: false,
379            description: "Extract shared logic into a separate module to break the cycle",
380            note: Some(
381                "Circular imports can cause initialization issues and make code harder to reason about",
382            ),
383            suppress: SuppressKind::InlineComment,
384            issue_kind: "circular-dependency",
385        }),
386        "boundary_violations" => Some(ActionSpec {
387            fix_type: "refactor-boundary",
388            auto_fixable: false,
389            description: "Move the import through an allowed zone or restructure the dependency",
390            note: Some(
391                "This import crosses an architecture boundary that is not permitted by the configured rules",
392            ),
393            suppress: SuppressKind::InlineComment,
394            issue_kind: "boundary-violation",
395        }),
396        _ => None,
397    }
398}
399
400/// Build the `actions` array for a single issue item.
401fn build_actions(
402    item: &serde_json::Value,
403    issue_key: &str,
404    spec: &ActionSpec,
405) -> serde_json::Value {
406    let mut actions = Vec::with_capacity(2);
407
408    // Primary fix action
409    let mut fix_action = serde_json::json!({
410        "type": spec.fix_type,
411        "auto_fixable": spec.auto_fixable,
412        "description": spec.description,
413    });
414    if let Some(note) = spec.note {
415        fix_action["note"] = serde_json::json!(note);
416    }
417    // Warn about re-exports that may be part of the public API surface.
418    if (issue_key == "unused_exports" || issue_key == "unused_types")
419        && item
420            .get("is_re_export")
421            .and_then(serde_json::Value::as_bool)
422            == Some(true)
423    {
424        fix_action["note"] = serde_json::json!(
425            "This finding originates from a re-export; verify it is not part of your public API before removing"
426        );
427    }
428    actions.push(fix_action);
429
430    // Suppress action — every action carries `auto_fixable` for uniform filtering.
431    match spec.suppress {
432        SuppressKind::InlineComment => {
433            let mut suppress = serde_json::json!({
434                "type": "suppress-line",
435                "auto_fixable": false,
436                "description": "Suppress with an inline comment above the line",
437                "comment": format!("// fallow-ignore-next-line {}", spec.issue_kind),
438            });
439            // duplicate_exports has N locations, not one — flag multi-location scope.
440            if issue_key == "duplicate_exports" {
441                suppress["scope"] = serde_json::json!("per-location");
442            }
443            actions.push(suppress);
444        }
445        SuppressKind::FileComment => {
446            actions.push(serde_json::json!({
447                "type": "suppress-file",
448                "auto_fixable": false,
449                "description": "Suppress with a file-level comment at the top of the file",
450                "comment": format!("// fallow-ignore-file {}", spec.issue_kind),
451            }));
452        }
453        SuppressKind::ConfigIgnoreDep => {
454            // Extract the package name from the item for a concrete suggestion.
455            let pkg = item
456                .get("package_name")
457                .and_then(serde_json::Value::as_str)
458                .unwrap_or("package-name");
459            actions.push(serde_json::json!({
460                "type": "add-to-config",
461                "auto_fixable": false,
462                "description": format!("Add \"{pkg}\" to ignoreDependencies in fallow config"),
463                "config_key": "ignoreDependencies",
464                "value": pkg,
465            }));
466        }
467    }
468
469    serde_json::Value::Array(actions)
470}
471
472/// Inject `actions` arrays into every issue item in the JSON output.
473///
474/// Walks each known issue-type array and appends an `actions` field
475/// to every item, providing machine-actionable fix and suppress hints.
476fn inject_actions(output: &mut serde_json::Value) {
477    let Some(map) = output.as_object_mut() else {
478        return;
479    };
480
481    for (key, value) in map.iter_mut() {
482        let Some(spec) = actions_for_issue_type(key) else {
483            continue;
484        };
485        let Some(arr) = value.as_array_mut() else {
486            continue;
487        };
488        for item in arr {
489            let actions = build_actions(item, key, &spec);
490            if let serde_json::Value::Object(obj) = item {
491                obj.insert("actions".to_string(), actions);
492            }
493        }
494    }
495}
496
497// ── Health action injection ─────────────────────────────────────
498
499/// Build a JSON representation of baseline deltas for the combined JSON envelope.
500///
501/// Accepts a total delta and an iterator of per-category entries to avoid
502/// coupling the report module (compiled in both lib and bin) to the
503/// binary-only `baseline` module.
504pub fn build_baseline_deltas_json<'a>(
505    total_delta: i64,
506    per_category: impl Iterator<Item = (&'a str, usize, usize, i64)>,
507) -> serde_json::Value {
508    let mut per_cat = serde_json::Map::new();
509    for (cat, current, baseline, delta) in per_category {
510        per_cat.insert(
511            cat.to_string(),
512            serde_json::json!({
513                "current": current,
514                "baseline": baseline,
515                "delta": delta,
516            }),
517        );
518    }
519    serde_json::json!({
520        "total_delta": total_delta,
521        "per_category": per_cat
522    })
523}
524
525/// Inject `actions` arrays into complexity findings in a health JSON output.
526///
527/// Walks `findings` and `targets` arrays, appending machine-actionable
528/// fix and suppress hints to each item.
529#[allow(
530    clippy::redundant_pub_crate,
531    reason = "pub(crate) needed — used by audit.rs via re-export, but not part of public API"
532)]
533pub(crate) fn inject_health_actions(output: &mut serde_json::Value) {
534    let Some(map) = output.as_object_mut() else {
535        return;
536    };
537
538    // Complexity findings: refactor the function to reduce complexity
539    if let Some(findings) = map.get_mut("findings").and_then(|v| v.as_array_mut()) {
540        for item in findings {
541            let actions = build_health_finding_actions(item);
542            if let serde_json::Value::Object(obj) = item {
543                obj.insert("actions".to_string(), actions);
544            }
545        }
546    }
547
548    // Refactoring targets: apply the recommended refactoring
549    if let Some(targets) = map.get_mut("targets").and_then(|v| v.as_array_mut()) {
550        for item in targets {
551            let actions = build_refactoring_target_actions(item);
552            if let serde_json::Value::Object(obj) = item {
553                obj.insert("actions".to_string(), actions);
554            }
555        }
556    }
557
558    // Hotspots: files that are both complex and frequently changing
559    if let Some(hotspots) = map.get_mut("hotspots").and_then(|v| v.as_array_mut()) {
560        for item in hotspots {
561            let actions = build_hotspot_actions(item);
562            if let serde_json::Value::Object(obj) = item {
563                obj.insert("actions".to_string(), actions);
564            }
565        }
566    }
567
568    // Coverage gaps: untested files and exports
569    if let Some(gaps) = map.get_mut("coverage_gaps").and_then(|v| v.as_object_mut()) {
570        if let Some(files) = gaps.get_mut("files").and_then(|v| v.as_array_mut()) {
571            for item in files {
572                let actions = build_untested_file_actions(item);
573                if let serde_json::Value::Object(obj) = item {
574                    obj.insert("actions".to_string(), actions);
575                }
576            }
577        }
578        if let Some(exports) = gaps.get_mut("exports").and_then(|v| v.as_array_mut()) {
579            for item in exports {
580                let actions = build_untested_export_actions(item);
581                if let serde_json::Value::Object(obj) = item {
582                    obj.insert("actions".to_string(), actions);
583                }
584            }
585        }
586    }
587}
588
589/// Build the `actions` array for a single complexity finding.
590fn build_health_finding_actions(item: &serde_json::Value) -> serde_json::Value {
591    let name = item
592        .get("name")
593        .and_then(serde_json::Value::as_str)
594        .unwrap_or("function");
595
596    let mut actions = vec![serde_json::json!({
597        "type": "refactor-function",
598        "auto_fixable": false,
599        "description": format!("Refactor `{name}` to reduce complexity (extract helper functions, simplify branching)"),
600        "note": "Consider splitting into smaller functions with single responsibilities",
601    })];
602
603    actions.push(serde_json::json!({
604        "type": "suppress-line",
605        "auto_fixable": false,
606        "description": "Suppress with an inline comment above the function declaration",
607        "comment": "// fallow-ignore-next-line complexity",
608        "placement": "above-function-declaration",
609    }));
610
611    serde_json::Value::Array(actions)
612}
613
614/// Build the `actions` array for a single hotspot entry.
615fn build_hotspot_actions(item: &serde_json::Value) -> serde_json::Value {
616    let path = item
617        .get("path")
618        .and_then(serde_json::Value::as_str)
619        .unwrap_or("file");
620
621    let actions = vec![
622        serde_json::json!({
623            "type": "refactor-file",
624            "auto_fixable": false,
625            "description": format!("Refactor `{path}` — high complexity combined with frequent changes makes this a maintenance risk"),
626            "note": "Prioritize extracting complex functions, adding tests, or splitting the module",
627        }),
628        serde_json::json!({
629            "type": "add-tests",
630            "auto_fixable": false,
631            "description": format!("Add test coverage for `{path}` to reduce change risk"),
632            "note": "Frequently changed complex files benefit most from comprehensive test coverage",
633        }),
634    ];
635
636    serde_json::Value::Array(actions)
637}
638
639/// Build the `actions` array for a single refactoring target.
640fn build_refactoring_target_actions(item: &serde_json::Value) -> serde_json::Value {
641    let recommendation = item
642        .get("recommendation")
643        .and_then(serde_json::Value::as_str)
644        .unwrap_or("Apply the recommended refactoring");
645
646    let category = item
647        .get("category")
648        .and_then(serde_json::Value::as_str)
649        .unwrap_or("refactoring");
650
651    let mut actions = vec![serde_json::json!({
652        "type": "apply-refactoring",
653        "auto_fixable": false,
654        "description": recommendation,
655        "category": category,
656    })];
657
658    // Targets with evidence linking to specific functions get a suppress action
659    if item.get("evidence").is_some() {
660        actions.push(serde_json::json!({
661            "type": "suppress-line",
662            "auto_fixable": false,
663            "description": "Suppress the underlying complexity finding",
664            "comment": "// fallow-ignore-next-line complexity",
665        }));
666    }
667
668    serde_json::Value::Array(actions)
669}
670
671/// Build the `actions` array for an untested file.
672fn build_untested_file_actions(item: &serde_json::Value) -> serde_json::Value {
673    let path = item
674        .get("path")
675        .and_then(serde_json::Value::as_str)
676        .unwrap_or("file");
677
678    serde_json::Value::Array(vec![
679        serde_json::json!({
680            "type": "add-tests",
681            "auto_fixable": false,
682            "description": format!("Add test coverage for `{path}`"),
683            "note": "No test dependency path reaches this runtime file",
684        }),
685        serde_json::json!({
686            "type": "suppress-file",
687            "auto_fixable": false,
688            "description": format!("Suppress coverage gap reporting for `{path}`"),
689            "comment": "// fallow-ignore-file coverage-gaps",
690        }),
691    ])
692}
693
694/// Build the `actions` array for an untested export.
695fn build_untested_export_actions(item: &serde_json::Value) -> serde_json::Value {
696    let path = item
697        .get("path")
698        .and_then(serde_json::Value::as_str)
699        .unwrap_or("file");
700    let export_name = item
701        .get("export_name")
702        .and_then(serde_json::Value::as_str)
703        .unwrap_or("export");
704
705    serde_json::Value::Array(vec![
706        serde_json::json!({
707            "type": "add-test-import",
708            "auto_fixable": false,
709            "description": format!("Import and test `{export_name}` from `{path}`"),
710            "note": "This export is runtime-reachable but no test-reachable module references it",
711        }),
712        serde_json::json!({
713            "type": "suppress-file",
714            "auto_fixable": false,
715            "description": format!("Suppress coverage gap reporting for `{path}`"),
716            "comment": "// fallow-ignore-file coverage-gaps",
717        }),
718    ])
719}
720
721// ── Duplication action injection ────────────────────────────────
722
723/// Inject `actions` arrays into clone families/groups in a duplication JSON output.
724///
725/// Walks `clone_families` and `clone_groups` arrays, appending
726/// machine-actionable fix and config hints to each item.
727#[allow(
728    clippy::redundant_pub_crate,
729    reason = "pub(crate) needed — used by audit.rs via re-export, but not part of public API"
730)]
731pub(crate) fn inject_dupes_actions(output: &mut serde_json::Value) {
732    let Some(map) = output.as_object_mut() else {
733        return;
734    };
735
736    // Clone families: extract shared module/function
737    if let Some(families) = map.get_mut("clone_families").and_then(|v| v.as_array_mut()) {
738        for item in families {
739            let actions = build_clone_family_actions(item);
740            if let serde_json::Value::Object(obj) = item {
741                obj.insert("actions".to_string(), actions);
742            }
743        }
744    }
745
746    // Clone groups: extract shared code
747    if let Some(groups) = map.get_mut("clone_groups").and_then(|v| v.as_array_mut()) {
748        for item in groups {
749            let actions = build_clone_group_actions(item);
750            if let serde_json::Value::Object(obj) = item {
751                obj.insert("actions".to_string(), actions);
752            }
753        }
754    }
755}
756
757/// Build the `actions` array for a single clone family.
758fn build_clone_family_actions(item: &serde_json::Value) -> serde_json::Value {
759    let group_count = item
760        .get("groups")
761        .and_then(|v| v.as_array())
762        .map_or(0, Vec::len);
763
764    let total_lines = item
765        .get("total_duplicated_lines")
766        .and_then(serde_json::Value::as_u64)
767        .unwrap_or(0);
768
769    let mut actions = vec![serde_json::json!({
770        "type": "extract-shared",
771        "auto_fixable": false,
772        "description": format!(
773            "Extract {group_count} duplicated code block{} ({total_lines} lines) into a shared module",
774            if group_count == 1 { "" } else { "s" }
775        ),
776        "note": "These clone groups share the same files, indicating a structural relationship — refactor together",
777    })];
778
779    // Include any refactoring suggestions from the family
780    if let Some(suggestions) = item.get("suggestions").and_then(|v| v.as_array()) {
781        for suggestion in suggestions {
782            if let Some(desc) = suggestion
783                .get("description")
784                .and_then(serde_json::Value::as_str)
785            {
786                actions.push(serde_json::json!({
787                    "type": "apply-suggestion",
788                    "auto_fixable": false,
789                    "description": desc,
790                }));
791            }
792        }
793    }
794
795    actions.push(serde_json::json!({
796        "type": "suppress-line",
797        "auto_fixable": false,
798        "description": "Suppress with an inline comment above the duplicated code",
799        "comment": "// fallow-ignore-next-line code-duplication",
800    }));
801
802    serde_json::Value::Array(actions)
803}
804
805/// Build the `actions` array for a single clone group.
806fn build_clone_group_actions(item: &serde_json::Value) -> serde_json::Value {
807    let instance_count = item
808        .get("instances")
809        .and_then(|v| v.as_array())
810        .map_or(0, Vec::len);
811
812    let line_count = item
813        .get("line_count")
814        .and_then(serde_json::Value::as_u64)
815        .unwrap_or(0);
816
817    let actions = vec![
818        serde_json::json!({
819            "type": "extract-shared",
820            "auto_fixable": false,
821            "description": format!(
822                "Extract duplicated code ({line_count} lines, {instance_count} instance{}) into a shared function",
823                if instance_count == 1 { "" } else { "s" }
824            ),
825        }),
826        serde_json::json!({
827            "type": "suppress-line",
828            "auto_fixable": false,
829            "description": "Suppress with an inline comment above the duplicated code",
830            "comment": "// fallow-ignore-next-line code-duplication",
831        }),
832    ];
833
834    serde_json::Value::Array(actions)
835}
836
837/// Insert a `_meta` key into a JSON object value.
838fn insert_meta(output: &mut serde_json::Value, meta: serde_json::Value) {
839    if let serde_json::Value::Object(map) = output {
840        map.insert("_meta".to_string(), meta);
841    }
842}
843
844pub(super) fn print_health_json(
845    report: &crate::health_types::HealthReport,
846    root: &Path,
847    elapsed: Duration,
848    explain: bool,
849) -> ExitCode {
850    let report_value = match serde_json::to_value(report) {
851        Ok(v) => v,
852        Err(e) => {
853            eprintln!("Error: failed to serialize health report: {e}");
854            return ExitCode::from(2);
855        }
856    };
857
858    let mut output = build_json_envelope(report_value, elapsed);
859    let root_prefix = format!("{}/", root.display());
860    strip_root_prefix(&mut output, &root_prefix);
861    inject_health_actions(&mut output);
862
863    if explain {
864        insert_meta(&mut output, explain::health_meta());
865    }
866
867    emit_json(&output, "JSON")
868}
869
870pub(super) fn print_duplication_json(
871    report: &DuplicationReport,
872    elapsed: Duration,
873    explain: bool,
874) -> ExitCode {
875    let report_value = match serde_json::to_value(report) {
876        Ok(v) => v,
877        Err(e) => {
878            eprintln!("Error: failed to serialize duplication report: {e}");
879            return ExitCode::from(2);
880        }
881    };
882
883    let mut output = build_json_envelope(report_value, elapsed);
884    inject_dupes_actions(&mut output);
885
886    if explain {
887        insert_meta(&mut output, explain::dupes_meta());
888    }
889
890    emit_json(&output, "JSON")
891}
892
893pub(super) fn print_trace_json<T: serde::Serialize>(value: &T) {
894    match serde_json::to_string_pretty(value) {
895        Ok(json) => println!("{json}"),
896        Err(e) => {
897            eprintln!("Error: failed to serialize trace output: {e}");
898            #[expect(
899                clippy::exit,
900                reason = "fatal serialization error requires immediate exit"
901            )]
902            std::process::exit(2);
903        }
904    }
905}
906
907#[cfg(test)]
908mod tests {
909    use super::*;
910    use crate::report::test_helpers::sample_results;
911    use fallow_core::extract::MemberKind;
912    use fallow_core::results::*;
913    use std::path::PathBuf;
914    use std::time::Duration;
915
916    #[test]
917    fn json_output_has_metadata_fields() {
918        let root = PathBuf::from("/project");
919        let results = AnalysisResults::default();
920        let elapsed = Duration::from_millis(123);
921        let output = build_json(&results, &root, elapsed).expect("should serialize");
922
923        assert_eq!(output["schema_version"], 3);
924        assert!(output["version"].is_string());
925        assert_eq!(output["elapsed_ms"], 123);
926        assert_eq!(output["total_issues"], 0);
927    }
928
929    #[test]
930    fn json_output_includes_issue_arrays() {
931        let root = PathBuf::from("/project");
932        let results = sample_results(&root);
933        let elapsed = Duration::from_millis(50);
934        let output = build_json(&results, &root, elapsed).expect("should serialize");
935
936        assert_eq!(output["unused_files"].as_array().unwrap().len(), 1);
937        assert_eq!(output["unused_exports"].as_array().unwrap().len(), 1);
938        assert_eq!(output["unused_types"].as_array().unwrap().len(), 1);
939        assert_eq!(output["unused_dependencies"].as_array().unwrap().len(), 1);
940        assert_eq!(
941            output["unused_dev_dependencies"].as_array().unwrap().len(),
942            1
943        );
944        assert_eq!(output["unused_enum_members"].as_array().unwrap().len(), 1);
945        assert_eq!(output["unused_class_members"].as_array().unwrap().len(), 1);
946        assert_eq!(output["unresolved_imports"].as_array().unwrap().len(), 1);
947        assert_eq!(output["unlisted_dependencies"].as_array().unwrap().len(), 1);
948        assert_eq!(output["duplicate_exports"].as_array().unwrap().len(), 1);
949        assert_eq!(
950            output["type_only_dependencies"].as_array().unwrap().len(),
951            1
952        );
953        assert_eq!(output["circular_dependencies"].as_array().unwrap().len(), 1);
954    }
955
956    #[test]
957    fn json_metadata_fields_appear_first() {
958        let root = PathBuf::from("/project");
959        let results = AnalysisResults::default();
960        let elapsed = Duration::from_millis(0);
961        let output = build_json(&results, &root, elapsed).expect("should serialize");
962        let keys: Vec<&String> = output.as_object().unwrap().keys().collect();
963        assert_eq!(keys[0], "schema_version");
964        assert_eq!(keys[1], "version");
965        assert_eq!(keys[2], "elapsed_ms");
966        assert_eq!(keys[3], "total_issues");
967    }
968
969    #[test]
970    fn json_total_issues_matches_results() {
971        let root = PathBuf::from("/project");
972        let results = sample_results(&root);
973        let total = results.total_issues();
974        let elapsed = Duration::from_millis(0);
975        let output = build_json(&results, &root, elapsed).expect("should serialize");
976
977        assert_eq!(output["total_issues"], total);
978    }
979
980    #[test]
981    fn json_unused_export_contains_expected_fields() {
982        let root = PathBuf::from("/project");
983        let mut results = AnalysisResults::default();
984        results.unused_exports.push(UnusedExport {
985            path: root.join("src/utils.ts"),
986            export_name: "helperFn".to_string(),
987            is_type_only: false,
988            line: 10,
989            col: 4,
990            span_start: 120,
991            is_re_export: false,
992        });
993        let elapsed = Duration::from_millis(0);
994        let output = build_json(&results, &root, elapsed).expect("should serialize");
995
996        let export = &output["unused_exports"][0];
997        assert_eq!(export["export_name"], "helperFn");
998        assert_eq!(export["line"], 10);
999        assert_eq!(export["col"], 4);
1000        assert_eq!(export["is_type_only"], false);
1001        assert_eq!(export["span_start"], 120);
1002        assert_eq!(export["is_re_export"], false);
1003    }
1004
1005    #[test]
1006    fn json_serializes_to_valid_json() {
1007        let root = PathBuf::from("/project");
1008        let results = sample_results(&root);
1009        let elapsed = Duration::from_millis(42);
1010        let output = build_json(&results, &root, elapsed).expect("should serialize");
1011
1012        let json_str = serde_json::to_string_pretty(&output).expect("should stringify");
1013        let reparsed: serde_json::Value =
1014            serde_json::from_str(&json_str).expect("JSON output should be valid JSON");
1015        assert_eq!(reparsed, output);
1016    }
1017
1018    // ── Empty results ───────────────────────────────────────────────
1019
1020    #[test]
1021    fn json_empty_results_produce_valid_structure() {
1022        let root = PathBuf::from("/project");
1023        let results = AnalysisResults::default();
1024        let elapsed = Duration::from_millis(0);
1025        let output = build_json(&results, &root, elapsed).expect("should serialize");
1026
1027        assert_eq!(output["total_issues"], 0);
1028        assert_eq!(output["unused_files"].as_array().unwrap().len(), 0);
1029        assert_eq!(output["unused_exports"].as_array().unwrap().len(), 0);
1030        assert_eq!(output["unused_types"].as_array().unwrap().len(), 0);
1031        assert_eq!(output["unused_dependencies"].as_array().unwrap().len(), 0);
1032        assert_eq!(
1033            output["unused_dev_dependencies"].as_array().unwrap().len(),
1034            0
1035        );
1036        assert_eq!(output["unused_enum_members"].as_array().unwrap().len(), 0);
1037        assert_eq!(output["unused_class_members"].as_array().unwrap().len(), 0);
1038        assert_eq!(output["unresolved_imports"].as_array().unwrap().len(), 0);
1039        assert_eq!(output["unlisted_dependencies"].as_array().unwrap().len(), 0);
1040        assert_eq!(output["duplicate_exports"].as_array().unwrap().len(), 0);
1041        assert_eq!(
1042            output["type_only_dependencies"].as_array().unwrap().len(),
1043            0
1044        );
1045        assert_eq!(output["circular_dependencies"].as_array().unwrap().len(), 0);
1046    }
1047
1048    #[test]
1049    fn json_empty_results_round_trips_through_string() {
1050        let root = PathBuf::from("/project");
1051        let results = AnalysisResults::default();
1052        let elapsed = Duration::from_millis(0);
1053        let output = build_json(&results, &root, elapsed).expect("should serialize");
1054
1055        let json_str = serde_json::to_string(&output).expect("should stringify");
1056        let reparsed: serde_json::Value =
1057            serde_json::from_str(&json_str).expect("should parse back");
1058        assert_eq!(reparsed["total_issues"], 0);
1059    }
1060
1061    // ── Path stripping ──────────────────────────────────────────────
1062
1063    #[test]
1064    fn json_paths_are_relative_to_root() {
1065        let root = PathBuf::from("/project");
1066        let mut results = AnalysisResults::default();
1067        results.unused_files.push(UnusedFile {
1068            path: root.join("src/deep/nested/file.ts"),
1069        });
1070        let elapsed = Duration::from_millis(0);
1071        let output = build_json(&results, &root, elapsed).expect("should serialize");
1072
1073        let path = output["unused_files"][0]["path"].as_str().unwrap();
1074        assert_eq!(path, "src/deep/nested/file.ts");
1075        assert!(!path.starts_with("/project"));
1076    }
1077
1078    #[test]
1079    fn json_strips_root_from_nested_locations() {
1080        let root = PathBuf::from("/project");
1081        let mut results = AnalysisResults::default();
1082        results.unlisted_dependencies.push(UnlistedDependency {
1083            package_name: "chalk".to_string(),
1084            imported_from: vec![ImportSite {
1085                path: root.join("src/cli.ts"),
1086                line: 2,
1087                col: 0,
1088            }],
1089        });
1090        let elapsed = Duration::from_millis(0);
1091        let output = build_json(&results, &root, elapsed).expect("should serialize");
1092
1093        let site_path = output["unlisted_dependencies"][0]["imported_from"][0]["path"]
1094            .as_str()
1095            .unwrap();
1096        assert_eq!(site_path, "src/cli.ts");
1097    }
1098
1099    #[test]
1100    fn json_strips_root_from_duplicate_export_locations() {
1101        let root = PathBuf::from("/project");
1102        let mut results = AnalysisResults::default();
1103        results.duplicate_exports.push(DuplicateExport {
1104            export_name: "Config".to_string(),
1105            locations: vec![
1106                DuplicateLocation {
1107                    path: root.join("src/config.ts"),
1108                    line: 15,
1109                    col: 0,
1110                },
1111                DuplicateLocation {
1112                    path: root.join("src/types.ts"),
1113                    line: 30,
1114                    col: 0,
1115                },
1116            ],
1117        });
1118        let elapsed = Duration::from_millis(0);
1119        let output = build_json(&results, &root, elapsed).expect("should serialize");
1120
1121        let loc0 = output["duplicate_exports"][0]["locations"][0]["path"]
1122            .as_str()
1123            .unwrap();
1124        let loc1 = output["duplicate_exports"][0]["locations"][1]["path"]
1125            .as_str()
1126            .unwrap();
1127        assert_eq!(loc0, "src/config.ts");
1128        assert_eq!(loc1, "src/types.ts");
1129    }
1130
1131    #[test]
1132    fn json_strips_root_from_circular_dependency_files() {
1133        let root = PathBuf::from("/project");
1134        let mut results = AnalysisResults::default();
1135        results.circular_dependencies.push(CircularDependency {
1136            files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
1137            length: 2,
1138            line: 1,
1139            col: 0,
1140            is_cross_package: false,
1141        });
1142        let elapsed = Duration::from_millis(0);
1143        let output = build_json(&results, &root, elapsed).expect("should serialize");
1144
1145        let files = output["circular_dependencies"][0]["files"]
1146            .as_array()
1147            .unwrap();
1148        assert_eq!(files[0].as_str().unwrap(), "src/a.ts");
1149        assert_eq!(files[1].as_str().unwrap(), "src/b.ts");
1150    }
1151
1152    #[test]
1153    fn json_path_outside_root_not_stripped() {
1154        let root = PathBuf::from("/project");
1155        let mut results = AnalysisResults::default();
1156        results.unused_files.push(UnusedFile {
1157            path: PathBuf::from("/other/project/src/file.ts"),
1158        });
1159        let elapsed = Duration::from_millis(0);
1160        let output = build_json(&results, &root, elapsed).expect("should serialize");
1161
1162        let path = output["unused_files"][0]["path"].as_str().unwrap();
1163        assert!(path.contains("/other/project/"));
1164    }
1165
1166    // ── Individual issue type field verification ────────────────────
1167
1168    #[test]
1169    fn json_unused_file_contains_path() {
1170        let root = PathBuf::from("/project");
1171        let mut results = AnalysisResults::default();
1172        results.unused_files.push(UnusedFile {
1173            path: root.join("src/orphan.ts"),
1174        });
1175        let elapsed = Duration::from_millis(0);
1176        let output = build_json(&results, &root, elapsed).expect("should serialize");
1177
1178        let file = &output["unused_files"][0];
1179        assert_eq!(file["path"], "src/orphan.ts");
1180    }
1181
1182    #[test]
1183    fn json_unused_type_contains_expected_fields() {
1184        let root = PathBuf::from("/project");
1185        let mut results = AnalysisResults::default();
1186        results.unused_types.push(UnusedExport {
1187            path: root.join("src/types.ts"),
1188            export_name: "OldInterface".to_string(),
1189            is_type_only: true,
1190            line: 20,
1191            col: 0,
1192            span_start: 300,
1193            is_re_export: false,
1194        });
1195        let elapsed = Duration::from_millis(0);
1196        let output = build_json(&results, &root, elapsed).expect("should serialize");
1197
1198        let typ = &output["unused_types"][0];
1199        assert_eq!(typ["export_name"], "OldInterface");
1200        assert_eq!(typ["is_type_only"], true);
1201        assert_eq!(typ["line"], 20);
1202        assert_eq!(typ["path"], "src/types.ts");
1203    }
1204
1205    #[test]
1206    fn json_unused_dependency_contains_expected_fields() {
1207        let root = PathBuf::from("/project");
1208        let mut results = AnalysisResults::default();
1209        results.unused_dependencies.push(UnusedDependency {
1210            package_name: "axios".to_string(),
1211            location: DependencyLocation::Dependencies,
1212            path: root.join("package.json"),
1213            line: 10,
1214        });
1215        let elapsed = Duration::from_millis(0);
1216        let output = build_json(&results, &root, elapsed).expect("should serialize");
1217
1218        let dep = &output["unused_dependencies"][0];
1219        assert_eq!(dep["package_name"], "axios");
1220        assert_eq!(dep["line"], 10);
1221    }
1222
1223    #[test]
1224    fn json_unused_dev_dependency_contains_expected_fields() {
1225        let root = PathBuf::from("/project");
1226        let mut results = AnalysisResults::default();
1227        results.unused_dev_dependencies.push(UnusedDependency {
1228            package_name: "vitest".to_string(),
1229            location: DependencyLocation::DevDependencies,
1230            path: root.join("package.json"),
1231            line: 15,
1232        });
1233        let elapsed = Duration::from_millis(0);
1234        let output = build_json(&results, &root, elapsed).expect("should serialize");
1235
1236        let dep = &output["unused_dev_dependencies"][0];
1237        assert_eq!(dep["package_name"], "vitest");
1238    }
1239
1240    #[test]
1241    fn json_unused_optional_dependency_contains_expected_fields() {
1242        let root = PathBuf::from("/project");
1243        let mut results = AnalysisResults::default();
1244        results.unused_optional_dependencies.push(UnusedDependency {
1245            package_name: "fsevents".to_string(),
1246            location: DependencyLocation::OptionalDependencies,
1247            path: root.join("package.json"),
1248            line: 12,
1249        });
1250        let elapsed = Duration::from_millis(0);
1251        let output = build_json(&results, &root, elapsed).expect("should serialize");
1252
1253        let dep = &output["unused_optional_dependencies"][0];
1254        assert_eq!(dep["package_name"], "fsevents");
1255        assert_eq!(output["total_issues"], 1);
1256    }
1257
1258    #[test]
1259    fn json_unused_enum_member_contains_expected_fields() {
1260        let root = PathBuf::from("/project");
1261        let mut results = AnalysisResults::default();
1262        results.unused_enum_members.push(UnusedMember {
1263            path: root.join("src/enums.ts"),
1264            parent_name: "Color".to_string(),
1265            member_name: "Purple".to_string(),
1266            kind: MemberKind::EnumMember,
1267            line: 5,
1268            col: 2,
1269        });
1270        let elapsed = Duration::from_millis(0);
1271        let output = build_json(&results, &root, elapsed).expect("should serialize");
1272
1273        let member = &output["unused_enum_members"][0];
1274        assert_eq!(member["parent_name"], "Color");
1275        assert_eq!(member["member_name"], "Purple");
1276        assert_eq!(member["line"], 5);
1277        assert_eq!(member["path"], "src/enums.ts");
1278    }
1279
1280    #[test]
1281    fn json_unused_class_member_contains_expected_fields() {
1282        let root = PathBuf::from("/project");
1283        let mut results = AnalysisResults::default();
1284        results.unused_class_members.push(UnusedMember {
1285            path: root.join("src/api.ts"),
1286            parent_name: "ApiClient".to_string(),
1287            member_name: "deprecatedFetch".to_string(),
1288            kind: MemberKind::ClassMethod,
1289            line: 100,
1290            col: 4,
1291        });
1292        let elapsed = Duration::from_millis(0);
1293        let output = build_json(&results, &root, elapsed).expect("should serialize");
1294
1295        let member = &output["unused_class_members"][0];
1296        assert_eq!(member["parent_name"], "ApiClient");
1297        assert_eq!(member["member_name"], "deprecatedFetch");
1298        assert_eq!(member["line"], 100);
1299    }
1300
1301    #[test]
1302    fn json_unresolved_import_contains_expected_fields() {
1303        let root = PathBuf::from("/project");
1304        let mut results = AnalysisResults::default();
1305        results.unresolved_imports.push(UnresolvedImport {
1306            path: root.join("src/app.ts"),
1307            specifier: "@acme/missing-pkg".to_string(),
1308            line: 7,
1309            col: 0,
1310            specifier_col: 0,
1311        });
1312        let elapsed = Duration::from_millis(0);
1313        let output = build_json(&results, &root, elapsed).expect("should serialize");
1314
1315        let import = &output["unresolved_imports"][0];
1316        assert_eq!(import["specifier"], "@acme/missing-pkg");
1317        assert_eq!(import["line"], 7);
1318        assert_eq!(import["path"], "src/app.ts");
1319    }
1320
1321    #[test]
1322    fn json_unlisted_dependency_contains_import_sites() {
1323        let root = PathBuf::from("/project");
1324        let mut results = AnalysisResults::default();
1325        results.unlisted_dependencies.push(UnlistedDependency {
1326            package_name: "dotenv".to_string(),
1327            imported_from: vec![
1328                ImportSite {
1329                    path: root.join("src/config.ts"),
1330                    line: 1,
1331                    col: 0,
1332                },
1333                ImportSite {
1334                    path: root.join("src/server.ts"),
1335                    line: 3,
1336                    col: 0,
1337                },
1338            ],
1339        });
1340        let elapsed = Duration::from_millis(0);
1341        let output = build_json(&results, &root, elapsed).expect("should serialize");
1342
1343        let dep = &output["unlisted_dependencies"][0];
1344        assert_eq!(dep["package_name"], "dotenv");
1345        let sites = dep["imported_from"].as_array().unwrap();
1346        assert_eq!(sites.len(), 2);
1347        assert_eq!(sites[0]["path"], "src/config.ts");
1348        assert_eq!(sites[1]["path"], "src/server.ts");
1349    }
1350
1351    #[test]
1352    fn json_duplicate_export_contains_locations() {
1353        let root = PathBuf::from("/project");
1354        let mut results = AnalysisResults::default();
1355        results.duplicate_exports.push(DuplicateExport {
1356            export_name: "Button".to_string(),
1357            locations: vec![
1358                DuplicateLocation {
1359                    path: root.join("src/ui.ts"),
1360                    line: 10,
1361                    col: 0,
1362                },
1363                DuplicateLocation {
1364                    path: root.join("src/components.ts"),
1365                    line: 25,
1366                    col: 0,
1367                },
1368            ],
1369        });
1370        let elapsed = Duration::from_millis(0);
1371        let output = build_json(&results, &root, elapsed).expect("should serialize");
1372
1373        let dup = &output["duplicate_exports"][0];
1374        assert_eq!(dup["export_name"], "Button");
1375        let locs = dup["locations"].as_array().unwrap();
1376        assert_eq!(locs.len(), 2);
1377        assert_eq!(locs[0]["line"], 10);
1378        assert_eq!(locs[1]["line"], 25);
1379    }
1380
1381    #[test]
1382    fn json_type_only_dependency_contains_expected_fields() {
1383        let root = PathBuf::from("/project");
1384        let mut results = AnalysisResults::default();
1385        results.type_only_dependencies.push(TypeOnlyDependency {
1386            package_name: "zod".to_string(),
1387            path: root.join("package.json"),
1388            line: 8,
1389        });
1390        let elapsed = Duration::from_millis(0);
1391        let output = build_json(&results, &root, elapsed).expect("should serialize");
1392
1393        let dep = &output["type_only_dependencies"][0];
1394        assert_eq!(dep["package_name"], "zod");
1395        assert_eq!(dep["line"], 8);
1396    }
1397
1398    #[test]
1399    fn json_circular_dependency_contains_expected_fields() {
1400        let root = PathBuf::from("/project");
1401        let mut results = AnalysisResults::default();
1402        results.circular_dependencies.push(CircularDependency {
1403            files: vec![
1404                root.join("src/a.ts"),
1405                root.join("src/b.ts"),
1406                root.join("src/c.ts"),
1407            ],
1408            length: 3,
1409            line: 5,
1410            col: 0,
1411            is_cross_package: false,
1412        });
1413        let elapsed = Duration::from_millis(0);
1414        let output = build_json(&results, &root, elapsed).expect("should serialize");
1415
1416        let cycle = &output["circular_dependencies"][0];
1417        assert_eq!(cycle["length"], 3);
1418        assert_eq!(cycle["line"], 5);
1419        let files = cycle["files"].as_array().unwrap();
1420        assert_eq!(files.len(), 3);
1421    }
1422
1423    // ── Re-export tagging ───────────────────────────────────────────
1424
1425    #[test]
1426    fn json_re_export_flagged_correctly() {
1427        let root = PathBuf::from("/project");
1428        let mut results = AnalysisResults::default();
1429        results.unused_exports.push(UnusedExport {
1430            path: root.join("src/index.ts"),
1431            export_name: "reExported".to_string(),
1432            is_type_only: false,
1433            line: 1,
1434            col: 0,
1435            span_start: 0,
1436            is_re_export: true,
1437        });
1438        let elapsed = Duration::from_millis(0);
1439        let output = build_json(&results, &root, elapsed).expect("should serialize");
1440
1441        assert_eq!(output["unused_exports"][0]["is_re_export"], true);
1442    }
1443
1444    // ── Schema version stability ────────────────────────────────────
1445
1446    #[test]
1447    fn json_schema_version_is_3() {
1448        let root = PathBuf::from("/project");
1449        let results = AnalysisResults::default();
1450        let elapsed = Duration::from_millis(0);
1451        let output = build_json(&results, &root, elapsed).expect("should serialize");
1452
1453        assert_eq!(output["schema_version"], SCHEMA_VERSION);
1454        assert_eq!(output["schema_version"], 3);
1455    }
1456
1457    // ── Version string ──────────────────────────────────────────────
1458
1459    #[test]
1460    fn json_version_matches_cargo_pkg_version() {
1461        let root = PathBuf::from("/project");
1462        let results = AnalysisResults::default();
1463        let elapsed = Duration::from_millis(0);
1464        let output = build_json(&results, &root, elapsed).expect("should serialize");
1465
1466        assert_eq!(output["version"], env!("CARGO_PKG_VERSION"));
1467    }
1468
1469    // ── Elapsed time encoding ───────────────────────────────────────
1470
1471    #[test]
1472    fn json_elapsed_ms_zero_duration() {
1473        let root = PathBuf::from("/project");
1474        let results = AnalysisResults::default();
1475        let output = build_json(&results, &root, Duration::ZERO).expect("should serialize");
1476
1477        assert_eq!(output["elapsed_ms"], 0);
1478    }
1479
1480    #[test]
1481    fn json_elapsed_ms_large_duration() {
1482        let root = PathBuf::from("/project");
1483        let results = AnalysisResults::default();
1484        let elapsed = Duration::from_secs(120);
1485        let output = build_json(&results, &root, elapsed).expect("should serialize");
1486
1487        assert_eq!(output["elapsed_ms"], 120_000);
1488    }
1489
1490    #[test]
1491    fn json_elapsed_ms_sub_millisecond_truncated() {
1492        let root = PathBuf::from("/project");
1493        let results = AnalysisResults::default();
1494        // 500 microseconds = 0 milliseconds (truncated)
1495        let elapsed = Duration::from_micros(500);
1496        let output = build_json(&results, &root, elapsed).expect("should serialize");
1497
1498        assert_eq!(output["elapsed_ms"], 0);
1499    }
1500
1501    // ── Multiple issues of same type ────────────────────────────────
1502
1503    #[test]
1504    fn json_multiple_unused_files() {
1505        let root = PathBuf::from("/project");
1506        let mut results = AnalysisResults::default();
1507        results.unused_files.push(UnusedFile {
1508            path: root.join("src/a.ts"),
1509        });
1510        results.unused_files.push(UnusedFile {
1511            path: root.join("src/b.ts"),
1512        });
1513        results.unused_files.push(UnusedFile {
1514            path: root.join("src/c.ts"),
1515        });
1516        let elapsed = Duration::from_millis(0);
1517        let output = build_json(&results, &root, elapsed).expect("should serialize");
1518
1519        assert_eq!(output["unused_files"].as_array().unwrap().len(), 3);
1520        assert_eq!(output["total_issues"], 3);
1521    }
1522
1523    // ── strip_root_prefix unit tests ────────────────────────────────
1524
1525    #[test]
1526    fn strip_root_prefix_on_string_value() {
1527        let mut value = serde_json::json!("/project/src/file.ts");
1528        strip_root_prefix(&mut value, "/project/");
1529        assert_eq!(value, "src/file.ts");
1530    }
1531
1532    #[test]
1533    fn strip_root_prefix_leaves_non_matching_string() {
1534        let mut value = serde_json::json!("/other/src/file.ts");
1535        strip_root_prefix(&mut value, "/project/");
1536        assert_eq!(value, "/other/src/file.ts");
1537    }
1538
1539    #[test]
1540    fn strip_root_prefix_recurses_into_arrays() {
1541        let mut value = serde_json::json!(["/project/a.ts", "/project/b.ts", "/other/c.ts"]);
1542        strip_root_prefix(&mut value, "/project/");
1543        assert_eq!(value[0], "a.ts");
1544        assert_eq!(value[1], "b.ts");
1545        assert_eq!(value[2], "/other/c.ts");
1546    }
1547
1548    #[test]
1549    fn strip_root_prefix_recurses_into_nested_objects() {
1550        let mut value = serde_json::json!({
1551            "outer": {
1552                "path": "/project/src/nested.ts"
1553            }
1554        });
1555        strip_root_prefix(&mut value, "/project/");
1556        assert_eq!(value["outer"]["path"], "src/nested.ts");
1557    }
1558
1559    #[test]
1560    fn strip_root_prefix_leaves_numbers_and_booleans() {
1561        let mut value = serde_json::json!({
1562            "line": 42,
1563            "is_type_only": false,
1564            "path": "/project/src/file.ts"
1565        });
1566        strip_root_prefix(&mut value, "/project/");
1567        assert_eq!(value["line"], 42);
1568        assert_eq!(value["is_type_only"], false);
1569        assert_eq!(value["path"], "src/file.ts");
1570    }
1571
1572    #[test]
1573    fn strip_root_prefix_handles_empty_string_after_strip() {
1574        // Edge case: the string IS the prefix (without trailing content).
1575        // This shouldn't happen in practice but should not panic.
1576        let mut value = serde_json::json!("/project/");
1577        strip_root_prefix(&mut value, "/project/");
1578        assert_eq!(value, "");
1579    }
1580
1581    #[test]
1582    fn strip_root_prefix_deeply_nested_array_of_objects() {
1583        let mut value = serde_json::json!({
1584            "groups": [{
1585                "instances": [{
1586                    "file": "/project/src/a.ts"
1587                }, {
1588                    "file": "/project/src/b.ts"
1589                }]
1590            }]
1591        });
1592        strip_root_prefix(&mut value, "/project/");
1593        assert_eq!(value["groups"][0]["instances"][0]["file"], "src/a.ts");
1594        assert_eq!(value["groups"][0]["instances"][1]["file"], "src/b.ts");
1595    }
1596
1597    // ── Full sample results round-trip ──────────────────────────────
1598
1599    #[test]
1600    fn json_full_sample_results_total_issues_correct() {
1601        let root = PathBuf::from("/project");
1602        let results = sample_results(&root);
1603        let elapsed = Duration::from_millis(100);
1604        let output = build_json(&results, &root, elapsed).expect("should serialize");
1605
1606        // sample_results adds one of each issue type (12 total).
1607        // unused_files + unused_exports + unused_types + unused_dependencies
1608        // + unused_dev_dependencies + unused_enum_members + unused_class_members
1609        // + unresolved_imports + unlisted_dependencies + duplicate_exports
1610        // + type_only_dependencies + circular_dependencies
1611        assert_eq!(output["total_issues"], results.total_issues());
1612    }
1613
1614    #[test]
1615    fn json_full_sample_no_absolute_paths_in_output() {
1616        let root = PathBuf::from("/project");
1617        let results = sample_results(&root);
1618        let elapsed = Duration::from_millis(0);
1619        let output = build_json(&results, &root, elapsed).expect("should serialize");
1620
1621        let json_str = serde_json::to_string(&output).expect("should stringify");
1622        // The root prefix should be stripped from all paths.
1623        assert!(!json_str.contains("/project/src/"));
1624        assert!(!json_str.contains("/project/package.json"));
1625    }
1626
1627    // ── JSON output is deterministic ────────────────────────────────
1628
1629    #[test]
1630    fn json_output_is_deterministic() {
1631        let root = PathBuf::from("/project");
1632        let results = sample_results(&root);
1633        let elapsed = Duration::from_millis(50);
1634
1635        let output1 = build_json(&results, &root, elapsed).expect("first build");
1636        let output2 = build_json(&results, &root, elapsed).expect("second build");
1637
1638        assert_eq!(output1, output2);
1639    }
1640
1641    // ── Metadata not overwritten by results fields ──────────────────
1642
1643    #[test]
1644    fn json_results_fields_do_not_shadow_metadata() {
1645        // Ensure that serialized results don't contain keys like "schema_version"
1646        // that could overwrite the metadata fields we insert first.
1647        let root = PathBuf::from("/project");
1648        let results = AnalysisResults::default();
1649        let elapsed = Duration::from_millis(99);
1650        let output = build_json(&results, &root, elapsed).expect("should serialize");
1651
1652        // Metadata should reflect our explicit values, not anything from AnalysisResults.
1653        assert_eq!(output["schema_version"], 3);
1654        assert_eq!(output["elapsed_ms"], 99);
1655    }
1656
1657    // ── All 14 issue type arrays present ────────────────────────────
1658
1659    #[test]
1660    fn json_all_issue_type_arrays_present_in_empty_results() {
1661        let root = PathBuf::from("/project");
1662        let results = AnalysisResults::default();
1663        let elapsed = Duration::from_millis(0);
1664        let output = build_json(&results, &root, elapsed).expect("should serialize");
1665
1666        let expected_arrays = [
1667            "unused_files",
1668            "unused_exports",
1669            "unused_types",
1670            "unused_dependencies",
1671            "unused_dev_dependencies",
1672            "unused_optional_dependencies",
1673            "unused_enum_members",
1674            "unused_class_members",
1675            "unresolved_imports",
1676            "unlisted_dependencies",
1677            "duplicate_exports",
1678            "type_only_dependencies",
1679            "test_only_dependencies",
1680            "circular_dependencies",
1681        ];
1682        for key in &expected_arrays {
1683            assert!(
1684                output[key].is_array(),
1685                "expected '{key}' to be an array in JSON output"
1686            );
1687        }
1688    }
1689
1690    // ── insert_meta ─────────────────────────────────────────────────
1691
1692    #[test]
1693    fn insert_meta_adds_key_to_object() {
1694        let mut output = serde_json::json!({ "foo": 1 });
1695        let meta = serde_json::json!({ "docs": "https://example.com" });
1696        insert_meta(&mut output, meta.clone());
1697        assert_eq!(output["_meta"], meta);
1698    }
1699
1700    #[test]
1701    fn insert_meta_noop_on_non_object() {
1702        let mut output = serde_json::json!([1, 2, 3]);
1703        let meta = serde_json::json!({ "docs": "https://example.com" });
1704        insert_meta(&mut output, meta);
1705        // Should not panic or add anything
1706        assert!(output.is_array());
1707    }
1708
1709    #[test]
1710    fn insert_meta_overwrites_existing_meta() {
1711        let mut output = serde_json::json!({ "_meta": "old" });
1712        let meta = serde_json::json!({ "new": true });
1713        insert_meta(&mut output, meta.clone());
1714        assert_eq!(output["_meta"], meta);
1715    }
1716
1717    // ── build_json_envelope ─────────────────────────────────────────
1718
1719    #[test]
1720    fn build_json_envelope_has_metadata_fields() {
1721        let report = serde_json::json!({ "findings": [] });
1722        let elapsed = Duration::from_millis(42);
1723        let output = build_json_envelope(report, elapsed);
1724
1725        assert_eq!(output["schema_version"], 3);
1726        assert!(output["version"].is_string());
1727        assert_eq!(output["elapsed_ms"], 42);
1728        assert!(output["findings"].is_array());
1729    }
1730
1731    #[test]
1732    fn build_json_envelope_metadata_appears_first() {
1733        let report = serde_json::json!({ "data": "value" });
1734        let output = build_json_envelope(report, Duration::from_millis(10));
1735
1736        let keys: Vec<&String> = output.as_object().unwrap().keys().collect();
1737        assert_eq!(keys[0], "schema_version");
1738        assert_eq!(keys[1], "version");
1739        assert_eq!(keys[2], "elapsed_ms");
1740    }
1741
1742    #[test]
1743    fn build_json_envelope_non_object_report() {
1744        // If report_value is not an Object, only metadata fields appear
1745        let report = serde_json::json!("not an object");
1746        let output = build_json_envelope(report, Duration::from_millis(0));
1747
1748        let obj = output.as_object().unwrap();
1749        assert_eq!(obj.len(), 3);
1750        assert!(obj.contains_key("schema_version"));
1751        assert!(obj.contains_key("version"));
1752        assert!(obj.contains_key("elapsed_ms"));
1753    }
1754
1755    // ── strip_root_prefix with null value ──
1756
1757    #[test]
1758    fn strip_root_prefix_null_unchanged() {
1759        let mut value = serde_json::Value::Null;
1760        strip_root_prefix(&mut value, "/project/");
1761        assert!(value.is_null());
1762    }
1763
1764    // ── strip_root_prefix with empty string ──
1765
1766    #[test]
1767    fn strip_root_prefix_empty_string() {
1768        let mut value = serde_json::json!("");
1769        strip_root_prefix(&mut value, "/project/");
1770        assert_eq!(value, "");
1771    }
1772
1773    // ── strip_root_prefix on mixed nested structure ──
1774
1775    #[test]
1776    fn strip_root_prefix_mixed_types() {
1777        let mut value = serde_json::json!({
1778            "path": "/project/src/file.ts",
1779            "line": 42,
1780            "flag": true,
1781            "nested": {
1782                "items": ["/project/a.ts", 99, null, "/project/b.ts"],
1783                "deep": { "path": "/project/c.ts" }
1784            }
1785        });
1786        strip_root_prefix(&mut value, "/project/");
1787        assert_eq!(value["path"], "src/file.ts");
1788        assert_eq!(value["line"], 42);
1789        assert_eq!(value["flag"], true);
1790        assert_eq!(value["nested"]["items"][0], "a.ts");
1791        assert_eq!(value["nested"]["items"][1], 99);
1792        assert!(value["nested"]["items"][2].is_null());
1793        assert_eq!(value["nested"]["items"][3], "b.ts");
1794        assert_eq!(value["nested"]["deep"]["path"], "c.ts");
1795    }
1796
1797    // ── JSON with explain meta for check ──
1798
1799    #[test]
1800    fn json_check_meta_integrates_correctly() {
1801        let root = PathBuf::from("/project");
1802        let results = AnalysisResults::default();
1803        let elapsed = Duration::from_millis(0);
1804        let mut output = build_json(&results, &root, elapsed).expect("should serialize");
1805        insert_meta(&mut output, crate::explain::check_meta());
1806
1807        assert!(output["_meta"]["docs"].is_string());
1808        assert!(output["_meta"]["rules"].is_object());
1809    }
1810
1811    // ── JSON unused member kind serialization ──
1812
1813    #[test]
1814    fn json_unused_member_kind_serialized() {
1815        let root = PathBuf::from("/project");
1816        let mut results = AnalysisResults::default();
1817        results.unused_enum_members.push(UnusedMember {
1818            path: root.join("src/enums.ts"),
1819            parent_name: "Color".to_string(),
1820            member_name: "Red".to_string(),
1821            kind: MemberKind::EnumMember,
1822            line: 3,
1823            col: 2,
1824        });
1825        results.unused_class_members.push(UnusedMember {
1826            path: root.join("src/class.ts"),
1827            parent_name: "Foo".to_string(),
1828            member_name: "bar".to_string(),
1829            kind: MemberKind::ClassMethod,
1830            line: 10,
1831            col: 4,
1832        });
1833
1834        let elapsed = Duration::from_millis(0);
1835        let output = build_json(&results, &root, elapsed).expect("should serialize");
1836
1837        let enum_member = &output["unused_enum_members"][0];
1838        assert!(enum_member["kind"].is_string());
1839        let class_member = &output["unused_class_members"][0];
1840        assert!(class_member["kind"].is_string());
1841    }
1842
1843    // ── Actions injection ──────────────────────────────────────────
1844
1845    #[test]
1846    fn json_unused_export_has_actions() {
1847        let root = PathBuf::from("/project");
1848        let mut results = AnalysisResults::default();
1849        results.unused_exports.push(UnusedExport {
1850            path: root.join("src/utils.ts"),
1851            export_name: "helperFn".to_string(),
1852            is_type_only: false,
1853            line: 10,
1854            col: 4,
1855            span_start: 120,
1856            is_re_export: false,
1857        });
1858        let output = build_json(&results, &root, Duration::ZERO).unwrap();
1859
1860        let actions = output["unused_exports"][0]["actions"].as_array().unwrap();
1861        assert_eq!(actions.len(), 2);
1862
1863        // Fix action
1864        assert_eq!(actions[0]["type"], "remove-export");
1865        assert_eq!(actions[0]["auto_fixable"], true);
1866        assert!(actions[0].get("note").is_none());
1867
1868        // Suppress action
1869        assert_eq!(actions[1]["type"], "suppress-line");
1870        assert_eq!(
1871            actions[1]["comment"],
1872            "// fallow-ignore-next-line unused-export"
1873        );
1874    }
1875
1876    #[test]
1877    fn json_unused_file_has_file_suppress_and_note() {
1878        let root = PathBuf::from("/project");
1879        let mut results = AnalysisResults::default();
1880        results.unused_files.push(UnusedFile {
1881            path: root.join("src/dead.ts"),
1882        });
1883        let output = build_json(&results, &root, Duration::ZERO).unwrap();
1884
1885        let actions = output["unused_files"][0]["actions"].as_array().unwrap();
1886        assert_eq!(actions[0]["type"], "delete-file");
1887        assert_eq!(actions[0]["auto_fixable"], false);
1888        assert!(actions[0]["note"].is_string());
1889        assert_eq!(actions[1]["type"], "suppress-file");
1890        assert_eq!(actions[1]["comment"], "// fallow-ignore-file unused-file");
1891    }
1892
1893    #[test]
1894    fn json_unused_dependency_has_config_suppress_with_package_name() {
1895        let root = PathBuf::from("/project");
1896        let mut results = AnalysisResults::default();
1897        results.unused_dependencies.push(UnusedDependency {
1898            package_name: "lodash".to_string(),
1899            location: DependencyLocation::Dependencies,
1900            path: root.join("package.json"),
1901            line: 5,
1902        });
1903        let output = build_json(&results, &root, Duration::ZERO).unwrap();
1904
1905        let actions = output["unused_dependencies"][0]["actions"]
1906            .as_array()
1907            .unwrap();
1908        assert_eq!(actions[0]["type"], "remove-dependency");
1909        assert_eq!(actions[0]["auto_fixable"], true);
1910
1911        // Config suppress includes actual package name
1912        assert_eq!(actions[1]["type"], "add-to-config");
1913        assert_eq!(actions[1]["config_key"], "ignoreDependencies");
1914        assert_eq!(actions[1]["value"], "lodash");
1915    }
1916
1917    #[test]
1918    fn json_empty_results_have_no_actions_in_empty_arrays() {
1919        let root = PathBuf::from("/project");
1920        let results = AnalysisResults::default();
1921        let output = build_json(&results, &root, Duration::ZERO).unwrap();
1922
1923        // Empty arrays should remain empty
1924        assert!(output["unused_exports"].as_array().unwrap().is_empty());
1925        assert!(output["unused_files"].as_array().unwrap().is_empty());
1926    }
1927
1928    #[test]
1929    fn json_all_issue_types_have_actions() {
1930        let root = PathBuf::from("/project");
1931        let results = sample_results(&root);
1932        let output = build_json(&results, &root, Duration::ZERO).unwrap();
1933
1934        let issue_keys = [
1935            "unused_files",
1936            "unused_exports",
1937            "unused_types",
1938            "unused_dependencies",
1939            "unused_dev_dependencies",
1940            "unused_optional_dependencies",
1941            "unused_enum_members",
1942            "unused_class_members",
1943            "unresolved_imports",
1944            "unlisted_dependencies",
1945            "duplicate_exports",
1946            "type_only_dependencies",
1947            "test_only_dependencies",
1948            "circular_dependencies",
1949        ];
1950
1951        for key in &issue_keys {
1952            let arr = output[key].as_array().unwrap();
1953            if !arr.is_empty() {
1954                let actions = arr[0]["actions"].as_array();
1955                assert!(
1956                    actions.is_some() && !actions.unwrap().is_empty(),
1957                    "missing actions for {key}"
1958                );
1959            }
1960        }
1961    }
1962
1963    // ── Health actions injection ───────────────────────────────────
1964
1965    #[test]
1966    fn health_finding_has_actions() {
1967        let mut output = serde_json::json!({
1968            "findings": [{
1969                "path": "src/utils.ts",
1970                "name": "processData",
1971                "line": 10,
1972                "col": 0,
1973                "cyclomatic": 25,
1974                "cognitive": 30,
1975                "line_count": 150,
1976                "exceeded": "both"
1977            }]
1978        });
1979
1980        inject_health_actions(&mut output);
1981
1982        let actions = output["findings"][0]["actions"].as_array().unwrap();
1983        assert_eq!(actions.len(), 2);
1984        assert_eq!(actions[0]["type"], "refactor-function");
1985        assert_eq!(actions[0]["auto_fixable"], false);
1986        assert!(
1987            actions[0]["description"]
1988                .as_str()
1989                .unwrap()
1990                .contains("processData")
1991        );
1992        assert_eq!(actions[1]["type"], "suppress-line");
1993        assert_eq!(
1994            actions[1]["comment"],
1995            "// fallow-ignore-next-line complexity"
1996        );
1997    }
1998
1999    #[test]
2000    fn refactoring_target_has_actions() {
2001        let mut output = serde_json::json!({
2002            "targets": [{
2003                "path": "src/big-module.ts",
2004                "priority": 85.0,
2005                "efficiency": 42.5,
2006                "recommendation": "Split module: 12 exports, 4 unused",
2007                "category": "split_high_impact",
2008                "effort": "medium",
2009                "confidence": "high",
2010                "evidence": { "unused_exports": 4 }
2011            }]
2012        });
2013
2014        inject_health_actions(&mut output);
2015
2016        let actions = output["targets"][0]["actions"].as_array().unwrap();
2017        assert_eq!(actions.len(), 2);
2018        assert_eq!(actions[0]["type"], "apply-refactoring");
2019        assert_eq!(
2020            actions[0]["description"],
2021            "Split module: 12 exports, 4 unused"
2022        );
2023        assert_eq!(actions[0]["category"], "split_high_impact");
2024        // Target with evidence gets suppress action
2025        assert_eq!(actions[1]["type"], "suppress-line");
2026    }
2027
2028    #[test]
2029    fn refactoring_target_without_evidence_has_no_suppress() {
2030        let mut output = serde_json::json!({
2031            "targets": [{
2032                "path": "src/simple.ts",
2033                "priority": 30.0,
2034                "efficiency": 15.0,
2035                "recommendation": "Consider extracting helper functions",
2036                "category": "extract_complex_functions",
2037                "effort": "small",
2038                "confidence": "medium"
2039            }]
2040        });
2041
2042        inject_health_actions(&mut output);
2043
2044        let actions = output["targets"][0]["actions"].as_array().unwrap();
2045        assert_eq!(actions.len(), 1);
2046        assert_eq!(actions[0]["type"], "apply-refactoring");
2047    }
2048
2049    #[test]
2050    fn health_empty_findings_no_actions() {
2051        let mut output = serde_json::json!({
2052            "findings": [],
2053            "targets": []
2054        });
2055
2056        inject_health_actions(&mut output);
2057
2058        assert!(output["findings"].as_array().unwrap().is_empty());
2059        assert!(output["targets"].as_array().unwrap().is_empty());
2060    }
2061
2062    #[test]
2063    fn hotspot_has_actions() {
2064        let mut output = serde_json::json!({
2065            "hotspots": [{
2066                "path": "src/utils.ts",
2067                "complexity_score": 45.0,
2068                "churn_score": 12,
2069                "hotspot_score": 540.0
2070            }]
2071        });
2072
2073        inject_health_actions(&mut output);
2074
2075        let actions = output["hotspots"][0]["actions"].as_array().unwrap();
2076        assert_eq!(actions.len(), 2);
2077        assert_eq!(actions[0]["type"], "refactor-file");
2078        assert!(
2079            actions[0]["description"]
2080                .as_str()
2081                .unwrap()
2082                .contains("src/utils.ts")
2083        );
2084        assert_eq!(actions[1]["type"], "add-tests");
2085    }
2086
2087    #[test]
2088    fn health_finding_suppress_has_placement() {
2089        let mut output = serde_json::json!({
2090            "findings": [{
2091                "path": "src/utils.ts",
2092                "name": "processData",
2093                "line": 10,
2094                "col": 0,
2095                "cyclomatic": 25,
2096                "cognitive": 30,
2097                "line_count": 150,
2098                "exceeded": "both"
2099            }]
2100        });
2101
2102        inject_health_actions(&mut output);
2103
2104        let suppress = &output["findings"][0]["actions"][1];
2105        assert_eq!(suppress["placement"], "above-function-declaration");
2106    }
2107
2108    // ── Duplication actions injection ─────────────────────────────
2109
2110    #[test]
2111    fn clone_family_has_actions() {
2112        let mut output = serde_json::json!({
2113            "clone_families": [{
2114                "files": ["src/a.ts", "src/b.ts"],
2115                "groups": [
2116                    { "instances": [{"file": "src/a.ts"}, {"file": "src/b.ts"}], "token_count": 100, "line_count": 20 }
2117                ],
2118                "total_duplicated_lines": 20,
2119                "total_duplicated_tokens": 100,
2120                "suggestions": [
2121                    { "kind": "ExtractFunction", "description": "Extract shared validation logic", "estimated_savings": 15 }
2122                ]
2123            }]
2124        });
2125
2126        inject_dupes_actions(&mut output);
2127
2128        let actions = output["clone_families"][0]["actions"].as_array().unwrap();
2129        assert_eq!(actions.len(), 3);
2130        assert_eq!(actions[0]["type"], "extract-shared");
2131        assert_eq!(actions[0]["auto_fixable"], false);
2132        assert!(
2133            actions[0]["description"]
2134                .as_str()
2135                .unwrap()
2136                .contains("20 lines")
2137        );
2138        // Suggestion forwarded as action
2139        assert_eq!(actions[1]["type"], "apply-suggestion");
2140        assert!(
2141            actions[1]["description"]
2142                .as_str()
2143                .unwrap()
2144                .contains("validation logic")
2145        );
2146        // Suppress action
2147        assert_eq!(actions[2]["type"], "suppress-line");
2148        assert_eq!(
2149            actions[2]["comment"],
2150            "// fallow-ignore-next-line code-duplication"
2151        );
2152    }
2153
2154    #[test]
2155    fn clone_group_has_actions() {
2156        let mut output = serde_json::json!({
2157            "clone_groups": [{
2158                "instances": [
2159                    {"file": "src/a.ts", "start_line": 1, "end_line": 10},
2160                    {"file": "src/b.ts", "start_line": 5, "end_line": 14}
2161                ],
2162                "token_count": 50,
2163                "line_count": 10
2164            }]
2165        });
2166
2167        inject_dupes_actions(&mut output);
2168
2169        let actions = output["clone_groups"][0]["actions"].as_array().unwrap();
2170        assert_eq!(actions.len(), 2);
2171        assert_eq!(actions[0]["type"], "extract-shared");
2172        assert!(
2173            actions[0]["description"]
2174                .as_str()
2175                .unwrap()
2176                .contains("10 lines")
2177        );
2178        assert!(
2179            actions[0]["description"]
2180                .as_str()
2181                .unwrap()
2182                .contains("2 instances")
2183        );
2184        assert_eq!(actions[1]["type"], "suppress-line");
2185    }
2186
2187    #[test]
2188    fn dupes_empty_results_no_actions() {
2189        let mut output = serde_json::json!({
2190            "clone_families": [],
2191            "clone_groups": []
2192        });
2193
2194        inject_dupes_actions(&mut output);
2195
2196        assert!(output["clone_families"].as_array().unwrap().is_empty());
2197        assert!(output["clone_groups"].as_array().unwrap().is_empty());
2198    }
2199}