Skip to main content

fallow_api/
runtime_json.rs

1//! JSON protocol serializers for typed programmatic runtime output.
2//!
3//! Runtime entry points return typed output from [`crate::runtime`]. CLI, MCP,
4//! NAPI, and other protocol surfaces call these serializers at their JSON
5//! boundary.
6
7use crate::{
8    ProgrammaticError,
9    runtime::{
10        ArchitectureProgrammaticOutput, AuditProgrammaticOutput,
11        BoundaryViolationsProgrammaticOutput, CircularDependenciesProgrammaticOutput,
12        CombinedProgrammaticOutput, DeadCodeProgrammaticOutput, DecisionSurfaceProgrammaticOutput,
13        DuplicationProgrammaticOutput, FeatureFlagsProgrammaticOutput, HealthJsonReportInput,
14        HealthProgrammaticOutput, TraceCloneProgrammaticOutput, TraceDependencyProgrammaticOutput,
15        TraceErrorProgrammaticOutput, TraceExportProgrammaticOutput, TraceFileProgrammaticOutput,
16        TraceImportPathProgrammaticOutput, serialize_health_report_json,
17    },
18};
19use fallow_output::{
20    AUDIT_SCHEMA_VERSION, CheckOutput, GroupByMode, build_decision_surface_output,
21    serialize_architecture_json_output, serialize_check_json_output,
22    serialize_decision_surface_json_output, serialize_dupes_json_output,
23    serialize_feature_flags_json_output, strip_root_prefix,
24};
25use fallow_types::envelope::{ElapsedMs, SchemaVersion, ToolVersion};
26use fallow_types::workspace::{WorkspaceDiagnostic, merge_workspace_diagnostics};
27use serde::Serialize;
28use std::path::Path;
29use std::time::Duration;
30
31type ProgrammaticResult<T> = Result<T, ProgrammaticError>;
32
33/// Serialize typed combined output into the stable JSON compatibility contract.
34///
35/// # Errors
36///
37/// Returns a structured error if one of the combined sections cannot serialize.
38pub fn serialize_combined_programmatic_json(
39    output: CombinedProgrammaticOutput,
40) -> ProgrammaticResult<serde_json::Value> {
41    let CombinedProgrammaticOutput {
42        dead_code,
43        duplication,
44        health,
45        root,
46        elapsed,
47        explain,
48        next_steps,
49        telemetry_analysis_run_id,
50        request_outcomes,
51        skipped,
52    } = output;
53    let workspace_diagnostics =
54        combined_workspace_diagnostics(dead_code.as_ref(), health.as_ref(), duplication.as_ref());
55    crate::serialize_combined_json(crate::CombinedJsonOutputInput {
56        package_baselines: crate::first_package_baselines([
57            dead_code
58                .as_ref()
59                .map(|run| run.output.package_baselines.as_slice()),
60            duplication
61                .as_ref()
62                .map(|run| run.output.package_baselines.as_slice()),
63        ]),
64        gate_outcomes: None,
65        request_outcomes,
66        check: dead_code
67            .as_ref()
68            .map(|dead_code| crate::CombinedCheckJsonSection {
69                results: &dead_code.output.results,
70                root: &dead_code.root,
71                elapsed: Duration::from_millis(dead_code.output.elapsed_ms.0),
72                config_fixable: dead_code.config_fixable,
73                extras: crate::CheckJsonExtraOutputs::default(),
74            }),
75        dupes: duplication
76            .as_ref()
77            .map(|duplication| &duplication.output.report),
78        health: health.as_ref().map(|health| &health.report),
79        root: &root,
80        elapsed,
81        explain,
82        type_aware: None,
83        workspace_diagnostics,
84        next_steps,
85        telemetry_analysis_run_id: telemetry_analysis_run_id.as_deref(),
86        skipped,
87    })
88    .map_err(|err| {
89        ProgrammaticError::new(format!("failed to serialize combined report: {err}"), 2)
90            .with_code("FALLOW_SERIALIZE_COMBINED_REPORT")
91            .with_context("combined")
92    })
93}
94
95/// Union the combined run's workspace diagnostics across its typed sections.
96///
97/// Each section captured the list as of the moment its own analysis finished,
98/// and those lists can differ: a combined run walks the project once per
99/// analysis, per-analysis `production` modes can give those walks different
100/// file sets, and each walk clears the previous walk's source-discovery
101/// entries. No single section therefore holds everything the run recorded, so
102/// the root carries the deduplicated union in section order (dead code, then
103/// health, then duplication) and a run missing a section (`--skip check`,
104/// `--only health`, `--only dupes`) still reports what its remaining analyses
105/// recorded.
106///
107/// Each section carries the diagnostics owned by its run. The combined root
108/// unions those values without importing process-global history.
109fn combined_workspace_diagnostics(
110    dead_code: Option<&DeadCodeProgrammaticOutput>,
111    health: Option<&HealthProgrammaticOutput>,
112    duplication: Option<&DuplicationProgrammaticOutput>,
113) -> Vec<WorkspaceDiagnostic> {
114    let merged = merge_workspace_diagnostics(
115        dead_code.map_or_else(Vec::new, |dead_code| {
116            dead_code.output.workspace_diagnostics.clone()
117        }),
118        health.map_or_else(Vec::new, |health| health.workspace_diagnostics.clone()),
119    );
120    merge_workspace_diagnostics(
121        merged,
122        duplication.map_or_else(Vec::new, |duplication| {
123            duplication.output.workspace_diagnostics.clone()
124        }),
125    )
126}
127
128/// Serialize typed decision-surface output into the stable JSON contract.
129///
130/// # Errors
131///
132/// Returns a structured error if the decision-surface payload cannot serialize.
133pub fn serialize_decision_surface_programmatic_json(
134    output: DecisionSurfaceProgrammaticOutput,
135) -> ProgrammaticResult<serde_json::Value> {
136    let DecisionSurfaceProgrammaticOutput {
137        surface,
138        elapsed: _,
139        telemetry_analysis_run_id,
140    } = output;
141    let payload = build_decision_surface_output(&surface);
142    serialize_decision_surface_json_output(payload, telemetry_analysis_run_id.as_deref()).map_err(
143        |err| {
144            ProgrammaticError::new(format!("failed to serialize decision surface: {err}"), 2)
145                .with_code("FALLOW_SERIALIZE_DECISION_SURFACE")
146                .with_context("decision-surface")
147        },
148    )
149}
150
151/// Serialize typed audit output into the stable JSON compatibility contract.
152///
153/// # Errors
154///
155/// Returns a structured error if one of the audit sections cannot serialize.
156pub fn serialize_audit_programmatic_json(
157    output: AuditProgrammaticOutput,
158) -> ProgrammaticResult<serde_json::Value> {
159    let base_snapshot = output.base_snapshot.as_ref();
160    let dead_code = output
161        .dead_code
162        .as_ref()
163        .map(|dead_code| serialize_audit_dead_code(dead_code, base_snapshot))
164        .transpose()?;
165    let duplication = output
166        .duplication
167        .as_ref()
168        .map(|duplication| serialize_audit_duplication(duplication, base_snapshot))
169        .transpose()?;
170    let complexity = output
171        .complexity
172        .as_ref()
173        .map(|complexity| serialize_audit_complexity(complexity, base_snapshot))
174        .transpose()?;
175
176    crate::serialize_audit_json(
177        crate::AuditJsonOutputInput {
178            gate_outcomes: None,
179            header: crate::AuditJsonHeaderInput {
180                schema_version: SchemaVersion(AUDIT_SCHEMA_VERSION),
181                version: ToolVersion(env!("CARGO_PKG_VERSION").to_string()),
182                verdict: output.verdict,
183                changed_files_count: u32::try_from(output.changed_files_count).unwrap_or(u32::MAX),
184                base_ref: output.base_ref,
185                base_description: output.base_description,
186                head_sha: output.head_sha,
187                elapsed_ms: ElapsedMs(
188                    u64::try_from(output.elapsed.as_millis()).unwrap_or(u64::MAX),
189                ),
190                base_snapshot_skipped: output.base_snapshot_skipped,
191                summary: output.summary,
192                attribution: output.attribution,
193            },
194            meta: None,
195            dead_code,
196            duplication,
197            complexity,
198            diff_risk: output.diff_risk,
199            workspace_diagnostics: crate::audit_run_notices(
200                [
201                    output
202                        .dead_code
203                        .as_ref()
204                        .map(|section| section.output.workspace_diagnostics.as_slice()),
205                    output
206                        .duplication
207                        .as_ref()
208                        .map(|section| section.output.workspace_diagnostics.as_slice()),
209                    output
210                        .complexity
211                        .as_ref()
212                        .map(|section| section.workspace_diagnostics.as_slice()),
213                ]
214                .into_iter()
215                .flatten(),
216            ),
217            next_steps: output.next_steps,
218        },
219        output.telemetry_analysis_run_id.as_deref(),
220    )
221    .map_err(|err| {
222        ProgrammaticError::new(format!("failed to serialize audit report: {err}"), 2)
223            .with_code("FALLOW_SERIALIZE_AUDIT_REPORT")
224            .with_context("audit")
225    })
226}
227
228/// Serialize the audit envelope's dead-code sub-result.
229///
230/// The sub-result is a `CheckOutput` body, so it carries the run's
231/// `workspace_diagnostics[]` the way the standalone `dead-code` envelope and
232/// the combined `check` section do. The two audit routes agree on everything
233/// the dead-code analysis records. The programmatic route serializes the typed
234/// output's by-value session snapshot, while the CLI route serializes the same
235/// snapshot from `CheckResult`. Neither route rereads process-global diagnostic
236/// history while building the envelope, so output is independent of call order
237/// and of later analysis walks in the same process.
238fn serialize_audit_dead_code(
239    output: &DeadCodeProgrammaticOutput,
240    base_snapshot: Option<&crate::AuditProgrammaticKeySnapshot>,
241) -> ProgrammaticResult<serde_json::Value> {
242    let mut json = crate::serialize_check_json_payload(crate::CheckJsonPayloadInput {
243        results: &output.output.results,
244        root: &output.root,
245        elapsed: Duration::from_millis(output.output.elapsed_ms.0),
246        config_fixable: output.config_fixable,
247        extras: crate::CheckJsonExtraOutputs::default(),
248        workspace_diagnostics: output.output.workspace_diagnostics.clone(),
249    })
250    .map_err(|err| {
251        ProgrammaticError::new(format!("failed to serialize audit dead-code: {err}"), 2)
252            .with_code("FALLOW_SERIALIZE_AUDIT_DEAD_CODE")
253            .with_context("audit.deadCode")
254    })?;
255    if let Some(base) = base_snapshot {
256        if has_persisted_introduced_flags(&json) {
257            crate::audit_keys::annotate_stale_suppressions_json(
258                &mut json,
259                &output.output.results,
260                &output.root,
261                &base.dead_code,
262            );
263        } else {
264            crate::audit_keys::annotate_dead_code_json(
265                &mut json,
266                &output.output.results,
267                &output.root,
268                &base.dead_code,
269            );
270        }
271    }
272    Ok(json)
273}
274
275fn serialize_audit_duplication(
276    output: &DuplicationProgrammaticOutput,
277    base_snapshot: Option<&crate::AuditProgrammaticKeySnapshot>,
278) -> ProgrammaticResult<serde_json::Value> {
279    let mut json = serde_json::to_value(&output.output.report).map_err(|err| {
280        ProgrammaticError::new(format!("failed to serialize audit duplication: {err}"), 2)
281            .with_code("FALLOW_SERIALIZE_AUDIT_DUPLICATION")
282            .with_context("audit.duplication")
283    })?;
284    let root_prefix = format!("{}/", output.root.display());
285    strip_root_prefix(&mut json, &root_prefix);
286    if let Some(base) = base_snapshot
287        && !has_persisted_introduced_flags(&json)
288    {
289        annotate_audit_duplication_json(&mut json, output, &base.dupes);
290    }
291    Ok(json)
292}
293
294fn serialize_audit_complexity(
295    output: &HealthProgrammaticOutput,
296    base_snapshot: Option<&crate::AuditProgrammaticKeySnapshot>,
297) -> ProgrammaticResult<serde_json::Value> {
298    let mut json = serde_json::to_value(&output.report).map_err(|err| {
299        ProgrammaticError::new(format!("failed to serialize audit complexity: {err}"), 2)
300            .with_code("FALLOW_SERIALIZE_AUDIT_COMPLEXITY")
301            .with_context("audit.complexity")
302    })?;
303    let root_prefix = format!("{}/", output.root.display());
304    strip_root_prefix(&mut json, &root_prefix);
305    if let Some(base) = base_snapshot {
306        crate::audit_keys::annotate_health_json(
307            &mut json,
308            &output.report,
309            &output.root,
310            &base.health,
311        );
312    }
313    Ok(json)
314}
315
316fn has_persisted_introduced_flags(json: &serde_json::Value) -> bool {
317    json.as_object().is_some_and(|object| {
318        object.values().any(|value| {
319            value
320                .as_array()
321                .is_some_and(|items| items.iter().any(|item| item.get("introduced").is_some()))
322        })
323    })
324}
325
326fn annotate_audit_duplication_json(
327    json: &mut serde_json::Value,
328    output: &DuplicationProgrammaticOutput,
329    base: &rustc_hash::FxHashSet<String>,
330) {
331    let Some(items) = json
332        .get_mut("clone_groups")
333        .and_then(serde_json::Value::as_array_mut)
334    else {
335        return;
336    };
337    for (item, group) in items.iter_mut().zip(&output.output.report.clone_groups) {
338        if let serde_json::Value::Object(map) = item {
339            let key = crate::audit_keys::dupe_group_key(&group.group, &output.root);
340            map.insert(
341                "introduced".to_string(),
342                serde_json::json!(!base.contains(&key)),
343            );
344        }
345    }
346}
347
348/// Serialize typed dead-code output into the stable JSON compatibility contract.
349///
350/// # Errors
351///
352/// Returns a structured error if the output contract cannot be serialized.
353pub fn serialize_dead_code_programmatic_json(
354    output: DeadCodeProgrammaticOutput,
355) -> ProgrammaticResult<serde_json::Value> {
356    let DeadCodeProgrammaticOutput {
357        output,
358        root,
359        config_fixable: _,
360        telemetry_analysis_run_id,
361    } = output;
362    serialize_check_programmatic_output(
363        output,
364        &root,
365        telemetry_analysis_run_id.as_deref(),
366        "dead-code",
367        "FALLOW_SERIALIZE_DEAD_CODE_REPORT",
368    )
369}
370
371/// Serialize typed circular-dependency output into the JSON compatibility contract.
372///
373/// # Errors
374///
375/// Returns a structured error if the output contract cannot be serialized.
376pub fn serialize_circular_dependencies_programmatic_json(
377    output: CircularDependenciesProgrammaticOutput,
378) -> ProgrammaticResult<serde_json::Value> {
379    let CircularDependenciesProgrammaticOutput {
380        output,
381        root,
382        telemetry_analysis_run_id,
383    } = output;
384    serialize_check_programmatic_output(
385        output,
386        &root,
387        telemetry_analysis_run_id.as_deref(),
388        "circular-dependencies",
389        "FALLOW_SERIALIZE_CIRCULAR_DEPENDENCIES_REPORT",
390    )
391}
392
393/// Serialize typed `fallow architecture` output into its JSON contract:
394/// `kind: "architecture"` with its own `schema_version`.
395///
396/// # Errors
397///
398/// Returns a structured error if the output contract cannot be serialized.
399pub fn serialize_architecture_programmatic_json(
400    output: ArchitectureProgrammaticOutput,
401) -> ProgrammaticResult<serde_json::Value> {
402    let ArchitectureProgrammaticOutput {
403        output,
404        root,
405        telemetry_analysis_run_id,
406    } = output;
407    let mut json = serialize_architecture_json_output(output, telemetry_analysis_run_id.as_deref())
408        .map_err(|err| {
409            ProgrammaticError::new(format!("failed to serialize architecture report: {err}"), 2)
410                .with_code("FALLOW_SERIALIZE_ARCHITECTURE_REPORT")
411                .with_context("architecture")
412        })?;
413    let root_prefix = format!("{}/", root.display());
414    strip_root_prefix(&mut json, &root_prefix);
415    Ok(json)
416}
417
418/// Serialize typed boundary-family output into the JSON compatibility contract.
419///
420/// # Errors
421///
422/// Returns a structured error if the output contract cannot be serialized.
423pub fn serialize_boundary_violations_programmatic_json(
424    output: BoundaryViolationsProgrammaticOutput,
425) -> ProgrammaticResult<serde_json::Value> {
426    let BoundaryViolationsProgrammaticOutput {
427        output,
428        root,
429        telemetry_analysis_run_id,
430    } = output;
431    serialize_check_programmatic_output(
432        output,
433        &root,
434        telemetry_analysis_run_id.as_deref(),
435        "boundary-violations",
436        "FALLOW_SERIALIZE_BOUNDARY_VIOLATIONS_REPORT",
437    )
438}
439
440fn serialize_check_programmatic_output(
441    output: CheckOutput,
442    root: &Path,
443    telemetry_analysis_run_id: Option<&str>,
444    context: &'static str,
445    code: &'static str,
446) -> ProgrammaticResult<serde_json::Value> {
447    let mut json =
448        serialize_check_json_output(output, telemetry_analysis_run_id).map_err(|err| {
449            ProgrammaticError::new(format!("failed to serialize {context} report: {err}"), 2)
450                .with_code(code)
451                .with_context(context)
452        })?;
453    let root_prefix = format!("{}/", root.display());
454    strip_root_prefix(&mut json, &root_prefix);
455    Ok(json)
456}
457
458/// Serialize typed duplication output into the JSON compatibility contract.
459///
460/// # Errors
461///
462/// Returns a structured error if the output contract cannot be serialized.
463pub fn serialize_duplication_programmatic_json(
464    output: DuplicationProgrammaticOutput,
465) -> ProgrammaticResult<serde_json::Value> {
466    let DuplicationProgrammaticOutput {
467        output,
468        root,
469        threshold: _,
470        ignored_clone_groups: _,
471        telemetry_analysis_run_id,
472    } = output;
473    let mut json = serialize_dupes_json_output(output, telemetry_analysis_run_id.as_deref())
474        .map_err(|err| {
475            ProgrammaticError::new(format!("failed to serialize duplication report: {err}"), 2)
476                .with_code("FALLOW_SERIALIZE_DUPLICATION_REPORT")
477                .with_context("dupes")
478        })?;
479    let root_prefix = format!("{}/", root.display());
480    strip_root_prefix(&mut json, &root_prefix);
481    Ok(json)
482}
483
484/// Serialize typed feature-flag output into the JSON compatibility contract.
485///
486/// # Errors
487///
488/// Returns a structured error if the output contract cannot be serialized.
489pub fn serialize_feature_flags_programmatic_json(
490    output: FeatureFlagsProgrammaticOutput,
491) -> ProgrammaticResult<serde_json::Value> {
492    serialize_feature_flags_json_output(output.output, output.telemetry_analysis_run_id.as_deref())
493        .map_err(|err| {
494            ProgrammaticError::new(
495                format!("failed to serialize feature flags report: {err}"),
496                2,
497            )
498            .with_code("FALLOW_SERIALIZE_FEATURE_FLAGS_REPORT")
499            .with_context("feature-flags")
500        })
501}
502
503/// Serialize typed export-trace output into the JSON compatibility contract.
504///
505/// # Errors
506///
507/// Returns a structured error if the trace output cannot be serialized.
508pub fn serialize_trace_export_programmatic_json(
509    output: TraceExportProgrammaticOutput,
510) -> ProgrammaticResult<serde_json::Value> {
511    serialize_trace_programmatic_output(
512        output.output,
513        "export trace",
514        "FALLOW_SERIALIZE_TRACE_EXPORT",
515        "trace_export",
516    )
517}
518
519/// Serialize typed file-trace output into the JSON compatibility contract.
520///
521/// # Errors
522///
523/// Returns a structured error if the trace output cannot be serialized.
524pub fn serialize_trace_file_programmatic_json(
525    output: TraceFileProgrammaticOutput,
526) -> ProgrammaticResult<serde_json::Value> {
527    serialize_trace_programmatic_output(
528        output.output,
529        "file trace",
530        "FALLOW_SERIALIZE_TRACE_FILE",
531        "trace_file",
532    )
533}
534
535/// Serialize typed import-path-trace output into the JSON compatibility contract.
536///
537/// # Errors
538///
539/// Returns a structured error if the trace output cannot be serialized.
540pub fn serialize_trace_import_path_programmatic_json(
541    output: TraceImportPathProgrammaticOutput,
542) -> ProgrammaticResult<serde_json::Value> {
543    serialize_trace_programmatic_output(
544        output.output,
545        "import path trace",
546        "FALLOW_SERIALIZE_TRACE_IMPORT_PATH",
547        "trace_import_path",
548    )
549}
550
551/// Serialize typed dependency-trace output into the JSON compatibility contract.
552///
553/// # Errors
554///
555/// Returns a structured error if the trace output cannot be serialized.
556pub fn serialize_trace_dependency_programmatic_json(
557    output: TraceDependencyProgrammaticOutput,
558) -> ProgrammaticResult<serde_json::Value> {
559    serialize_trace_programmatic_output(
560        output.output,
561        "dependency trace",
562        "FALLOW_SERIALIZE_TRACE_DEPENDENCY",
563        "trace_dependency",
564    )
565}
566
567/// Serialize typed stack-trace resolution into the JSON compatibility contract.
568///
569/// # Errors
570///
571/// Returns a structured error if the trace output cannot be serialized.
572pub fn serialize_trace_error_programmatic_json(
573    output: TraceErrorProgrammaticOutput,
574) -> ProgrammaticResult<serde_json::Value> {
575    serialize_trace_programmatic_output(
576        output.output,
577        "stack-trace resolution",
578        "FALLOW_SERIALIZE_TRACE_ERROR",
579        "trace_error",
580    )
581}
582
583/// Serialize typed clone-trace output into the JSON compatibility contract.
584///
585/// # Errors
586///
587/// Returns a structured error if the trace output cannot be serialized.
588pub fn serialize_trace_clone_programmatic_json(
589    output: TraceCloneProgrammaticOutput,
590) -> ProgrammaticResult<serde_json::Value> {
591    serialize_trace_programmatic_output(
592        output.output,
593        "clone trace",
594        "FALLOW_SERIALIZE_TRACE_CLONE",
595        "trace_clone",
596    )
597}
598
599fn serialize_trace_programmatic_output<T: Serialize>(
600    output: T,
601    context: &'static str,
602    code: &'static str,
603    error_context: &'static str,
604) -> ProgrammaticResult<serde_json::Value> {
605    serde_json::to_value(output).map_err(|err| {
606        ProgrammaticError::new(format!("failed to serialize {context}: {err}"), 2)
607            .with_code(code)
608            .with_context(error_context)
609    })
610}
611
612/// Serialize typed health / complexity output into the JSON compatibility contract.
613///
614/// # Errors
615///
616/// Returns a structured error if the health output contract cannot be serialized.
617pub fn serialize_health_programmatic_json(
618    output: HealthProgrammaticOutput,
619) -> ProgrammaticResult<serde_json::Value> {
620    let HealthProgrammaticOutput {
621        report,
622        grouping,
623        root,
624        elapsed,
625        explain,
626        workspace_diagnostics,
627        next_steps,
628        telemetry_analysis_run_id,
629        request_outcomes,
630    } = output;
631    let (grouped_by, groups, group_filter) = grouping.map_or((None, None, None), |grouping| {
632        (
633            group_by_mode_from_label(grouping.mode),
634            Some(grouping.groups),
635            grouping.filter,
636        )
637    });
638    serialize_health_report_json(HealthJsonReportInput {
639        gate_outcomes: None,
640        request_outcomes,
641        report,
642        root: &root,
643        elapsed,
644        explain,
645        type_aware: None,
646        grouped_by,
647        groups,
648        group_filter,
649        workspace_diagnostics,
650        next_steps,
651        telemetry_analysis_run_id: telemetry_analysis_run_id.as_deref(),
652    })
653    .map_err(|err| {
654        ProgrammaticError::new(format!("failed to serialize health report: {err}"), 2)
655            .with_code("FALLOW_SERIALIZE_HEALTH_REPORT")
656            .with_context("health")
657    })
658}
659
660fn group_by_mode_from_label(label: &str) -> Option<GroupByMode> {
661    match label {
662        "owner" => Some(GroupByMode::Owner),
663        "directory" => Some(GroupByMode::Directory),
664        "package" => Some(GroupByMode::Package),
665        "section" => Some(GroupByMode::Section),
666        _ => None,
667    }
668}
669
670#[cfg(test)]
671mod tests {
672    use super::{serialize_audit_dead_code, serialize_combined_programmatic_json};
673    use crate::DupesReportPayload;
674    use crate::runtime::{
675        CombinedProgrammaticOutput, DeadCodeProgrammaticOutput, DuplicationProgrammaticOutput,
676        HealthProgrammaticOutput,
677    };
678    use fallow_output::{
679        CHECK_SCHEMA_VERSION, CheckOutputInput, DUPES_SCHEMA_VERSION, DupesOutputInput,
680        HealthReport, build_check_output, build_dupes_output,
681    };
682    use fallow_types::duplicates::DuplicationReport;
683    use fallow_types::results::AnalysisResults;
684    use fallow_types::workspace::{WorkspaceDiagnostic, WorkspaceDiagnosticKind};
685    use std::path::Path;
686    use std::time::Duration;
687
688    fn dead_code_output(
689        root: &Path,
690        workspace_diagnostics: Vec<WorkspaceDiagnostic>,
691    ) -> DeadCodeProgrammaticOutput {
692        DeadCodeProgrammaticOutput {
693            output: build_check_output(CheckOutputInput {
694                schema_version: CHECK_SCHEMA_VERSION,
695                version: "0.0.0-test".to_owned(),
696                elapsed: Duration::ZERO,
697                results: AnalysisResults::default(),
698                config_fixable: false,
699                meta: None,
700                workspace_diagnostics,
701                next_steps: Vec::new(),
702            }),
703            root: root.to_path_buf(),
704            config_fixable: false,
705            telemetry_analysis_run_id: None,
706        }
707    }
708
709    /// Issue #2366: the audit envelope's dead-code sub-result carries the run's
710    /// workspace diagnostics root-relative, matching what the CLI audit path
711    /// reads from the registry, and omits the array when there are none.
712    #[test]
713    fn audit_dead_code_section_carries_workspace_diagnostics_root_relative_or_omits_them() {
714        let root = Path::new("/project");
715        let carried = serialize_audit_dead_code(
716            &dead_code_output(
717                root,
718                vec![WorkspaceDiagnostic::new(
719                    root,
720                    root.join("package.json"),
721                    WorkspaceDiagnosticKind::BunLockbOverrideResolutionSkipped,
722                )],
723            ),
724            None,
725        )
726        .expect("audit dead-code JSON");
727        assert_eq!(
728            carried["workspace_diagnostics"][0]["kind"],
729            "bun-lockb-override-resolution-skipped"
730        );
731        assert_eq!(carried["workspace_diagnostics"][0]["path"], "package.json");
732
733        let empty = serialize_audit_dead_code(&dead_code_output(root, Vec::new()), None)
734            .expect("audit dead-code JSON");
735        assert!(
736            empty.get("workspace_diagnostics").is_none(),
737            "an empty list is omitted from the audit dead-code section: {empty}"
738        );
739    }
740
741    fn health_output(
742        root: &Path,
743        workspace_diagnostics: Vec<WorkspaceDiagnostic>,
744    ) -> HealthProgrammaticOutput {
745        HealthProgrammaticOutput {
746            report: HealthReport::default(),
747            grouping: None,
748            root: root.to_path_buf(),
749            elapsed: Duration::ZERO,
750            explain: false,
751            workspace_diagnostics,
752            next_steps: Vec::new(),
753            telemetry_analysis_run_id: None,
754            request_outcomes: None,
755        }
756    }
757
758    fn duplication_output(
759        root: &Path,
760        workspace_diagnostics: Vec<WorkspaceDiagnostic>,
761    ) -> DuplicationProgrammaticOutput {
762        DuplicationProgrammaticOutput {
763            output: build_dupes_output(DupesOutputInput {
764                gate_outcomes: None,
765                request_outcomes: None,
766                baseline_staleness: None,
767                schema_version: DUPES_SCHEMA_VERSION,
768                version: "0.0.0-test".to_owned(),
769                elapsed: Duration::ZERO,
770                report: DupesReportPayload::from_report(&DuplicationReport::default()),
771                clone_groups_shown: 0,
772                clone_groups_omitted: 0,
773                clone_families_shown: 0,
774                clone_families_omitted: 0,
775                grouped_by: None,
776                total_issues: None,
777                groups: None,
778                meta: None,
779                workspace_diagnostics,
780                next_steps: Vec::new(),
781            }),
782            root: root.to_path_buf(),
783            threshold: 0.0,
784            ignored_clone_groups: Vec::new(),
785            telemetry_analysis_run_id: None,
786        }
787    }
788
789    fn combined_output(
790        root: &Path,
791        dead_code: Option<DeadCodeProgrammaticOutput>,
792        health: Option<HealthProgrammaticOutput>,
793    ) -> CombinedProgrammaticOutput {
794        combined_output_with_duplication(root, dead_code, health, None)
795    }
796
797    fn combined_output_with_duplication(
798        root: &Path,
799        dead_code: Option<DeadCodeProgrammaticOutput>,
800        health: Option<HealthProgrammaticOutput>,
801        duplication: Option<DuplicationProgrammaticOutput>,
802    ) -> CombinedProgrammaticOutput {
803        CombinedProgrammaticOutput {
804            dead_code,
805            duplication,
806            health,
807            root: root.to_path_buf(),
808            elapsed: Duration::ZERO,
809            explain: false,
810            next_steps: Vec::new(),
811            telemetry_analysis_run_id: None,
812            request_outcomes: None,
813            skipped: Vec::new(),
814        }
815    }
816
817    fn bun_lockb_diagnostic(root: &Path) -> WorkspaceDiagnostic {
818        WorkspaceDiagnostic::new(
819            root,
820            root.join("package.json"),
821            WorkspaceDiagnosticKind::BunLockbOverrideResolutionSkipped,
822        )
823    }
824
825    fn large_file_diagnostic(root: &Path, relative: &str) -> WorkspaceDiagnostic {
826        WorkspaceDiagnostic::new(
827            root,
828            root.join(relative),
829            WorkspaceDiagnosticKind::SkippedLargeFile {
830                size_bytes: 6_000_000,
831            },
832        )
833    }
834
835    fn root_kinds(document: &serde_json::Value) -> Vec<String> {
836        document["workspace_diagnostics"]
837            .as_array()
838            .cloned()
839            .unwrap_or_default()
840            .iter()
841            .map(|diagnostic| diagnostic["kind"].as_str().unwrap_or_default().to_owned())
842            .collect()
843    }
844
845    /// Issue #2366: the programmatic combined envelope (MCP `analyze` in code
846    /// mode, NAPI, embedders) carries the run's workspace diagnostics on the
847    /// combined root, root-relative, and omits the array when there are none.
848    #[test]
849    fn combined_programmatic_root_carries_workspace_diagnostics_or_omits_them() {
850        let root = Path::new("/project");
851        let carried = serialize_combined_programmatic_json(combined_output(
852            root,
853            Some(dead_code_output(root, vec![bun_lockb_diagnostic(root)])),
854            None,
855        ))
856        .expect("combined JSON");
857        assert_eq!(
858            carried["workspace_diagnostics"][0]["kind"],
859            "bun-lockb-override-resolution-skipped"
860        );
861        assert_eq!(carried["workspace_diagnostics"][0]["path"], "package.json");
862        assert!(
863            carried["check"].is_object(),
864            "the check section is present, so the absence check below is not vacuous: {carried}"
865        );
866        assert!(
867            carried["check"].get("workspace_diagnostics").is_none(),
868            "the check section is not a second carrier: {carried}"
869        );
870
871        let empty = serialize_combined_programmatic_json(combined_output(
872            root,
873            Some(dead_code_output(root, Vec::new())),
874            None,
875        ))
876        .expect("combined JSON");
877        assert!(
878            empty.get("workspace_diagnostics").is_none(),
879            "an empty list is omitted from the combined root: {empty}"
880        );
881    }
882
883    /// Issue #2366: a programmatic combined run without a dead-code section
884    /// (the `--skip check` / `--only health` shape) still reports the
885    /// diagnostics, taken from the section that did run.
886    #[test]
887    fn combined_programmatic_root_carries_workspace_diagnostics_without_a_dead_code_section() {
888        let root = Path::new("/project");
889        let carried = serialize_combined_programmatic_json(combined_output(
890            root,
891            None,
892            Some(health_output(root, vec![bun_lockb_diagnostic(root)])),
893        ))
894        .expect("combined JSON");
895        assert!(
896            carried.get("check").is_none(),
897            "this run has no check section: {carried}"
898        );
899        assert_eq!(
900            carried["workspace_diagnostics"][0]["kind"],
901            "bun-lockb-override-resolution-skipped"
902        );
903        assert_eq!(carried["workspace_diagnostics"][0]["path"], "package.json");
904    }
905
906    /// Issue #2366: a duplication-only combined run (an embedder driving
907    /// `CombinedOptions` with just `duplication`) reports what that section
908    /// recorded.
909    #[test]
910    fn combined_programmatic_root_carries_workspace_diagnostics_from_a_duplication_only_run() {
911        let root = Path::new("/project");
912        let carried = serialize_combined_programmatic_json(combined_output_with_duplication(
913            root,
914            None,
915            None,
916            Some(duplication_output(
917                root,
918                vec![large_file_diagnostic(root, "src/generated.ts")],
919            )),
920        ))
921        .expect("combined JSON");
922        assert!(
923            carried.get("check").is_none() && carried.get("health").is_none(),
924            "only the dupes section ran: {carried}"
925        );
926        assert_eq!(root_kinds(&carried), ["skipped-large-file"]);
927        assert_eq!(
928            carried["workspace_diagnostics"][0]["path"],
929            "src/generated.ts"
930        );
931    }
932
933    /// Issue #2366: sections of one combined run can record different lists,
934    /// because each analysis walks the project itself and a per-analysis
935    /// `production` mode changes which files that walk sees. The root carries
936    /// the union so nothing the run recorded is dropped, deduplicated so a
937    /// diagnostic two sections both saw is reported once, and in section order
938    /// so a run whose analyses agree matches the standalone `dead-code`
939    /// envelope exactly.
940    #[test]
941    fn combined_programmatic_root_unions_sections_that_recorded_different_diagnostics() {
942        let root = Path::new("/project");
943        let shared = bun_lockb_diagnostic(root);
944        let carried = serialize_combined_programmatic_json(combined_output_with_duplication(
945            root,
946            Some(dead_code_output(
947                root,
948                vec![shared.clone(), large_file_diagnostic(root, "src/big.ts")],
949            )),
950            Some(health_output(root, vec![shared.clone()])),
951            Some(duplication_output(
952                root,
953                vec![shared, large_file_diagnostic(root, "src/other.ts")],
954            )),
955        ))
956        .expect("combined JSON");
957        assert_eq!(
958            root_kinds(&carried),
959            [
960                "bun-lockb-override-resolution-skipped",
961                "skipped-large-file",
962                "skipped-large-file",
963            ],
964            "the union keeps dead-code order first and drops the repeats: {}",
965            carried["workspace_diagnostics"]
966        );
967        let paths: Vec<&str> = carried["workspace_diagnostics"]
968            .as_array()
969            .expect("array")
970            .iter()
971            .map(|diagnostic| diagnostic["path"].as_str().unwrap_or_default())
972            .collect();
973        assert_eq!(paths, ["package.json", "src/big.ts", "src/other.ts"]);
974    }
975
976    /// Issue #2366: a diagnostic only the health or duplication section
977    /// recorded still reaches the root when the dead-code section recorded
978    /// nothing, the direction that a `production: { deadCode: true }` split
979    /// produces on a real project.
980    #[test]
981    fn combined_programmatic_root_keeps_diagnostics_an_empty_dead_code_section_missed() {
982        let root = Path::new("/project");
983        let carried = serialize_combined_programmatic_json(combined_output_with_duplication(
984            root,
985            Some(dead_code_output(root, Vec::new())),
986            Some(health_output(
987                root,
988                vec![large_file_diagnostic(root, "src/big.test.ts")],
989            )),
990            None,
991        ))
992        .expect("combined JSON");
993        assert_eq!(root_kinds(&carried), ["skipped-large-file"]);
994        assert_eq!(
995            carried["workspace_diagnostics"][0]["path"],
996            "src/big.test.ts"
997        );
998    }
999}