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        telemetry_analysis_run_id,
471    } = output;
472    let mut json = serialize_dupes_json_output(output, telemetry_analysis_run_id.as_deref())
473        .map_err(|err| {
474            ProgrammaticError::new(format!("failed to serialize duplication report: {err}"), 2)
475                .with_code("FALLOW_SERIALIZE_DUPLICATION_REPORT")
476                .with_context("dupes")
477        })?;
478    let root_prefix = format!("{}/", root.display());
479    strip_root_prefix(&mut json, &root_prefix);
480    Ok(json)
481}
482
483/// Serialize typed feature-flag output into the JSON compatibility contract.
484///
485/// # Errors
486///
487/// Returns a structured error if the output contract cannot be serialized.
488pub fn serialize_feature_flags_programmatic_json(
489    output: FeatureFlagsProgrammaticOutput,
490) -> ProgrammaticResult<serde_json::Value> {
491    serialize_feature_flags_json_output(output.output, output.telemetry_analysis_run_id.as_deref())
492        .map_err(|err| {
493            ProgrammaticError::new(
494                format!("failed to serialize feature flags report: {err}"),
495                2,
496            )
497            .with_code("FALLOW_SERIALIZE_FEATURE_FLAGS_REPORT")
498            .with_context("feature-flags")
499        })
500}
501
502/// Serialize typed export-trace output into the JSON compatibility contract.
503///
504/// # Errors
505///
506/// Returns a structured error if the trace output cannot be serialized.
507pub fn serialize_trace_export_programmatic_json(
508    output: TraceExportProgrammaticOutput,
509) -> ProgrammaticResult<serde_json::Value> {
510    serialize_trace_programmatic_output(
511        output.output,
512        "export trace",
513        "FALLOW_SERIALIZE_TRACE_EXPORT",
514        "trace_export",
515    )
516}
517
518/// Serialize typed file-trace output into the JSON compatibility contract.
519///
520/// # Errors
521///
522/// Returns a structured error if the trace output cannot be serialized.
523pub fn serialize_trace_file_programmatic_json(
524    output: TraceFileProgrammaticOutput,
525) -> ProgrammaticResult<serde_json::Value> {
526    serialize_trace_programmatic_output(
527        output.output,
528        "file trace",
529        "FALLOW_SERIALIZE_TRACE_FILE",
530        "trace_file",
531    )
532}
533
534/// Serialize typed import-path-trace output into the JSON compatibility contract.
535///
536/// # Errors
537///
538/// Returns a structured error if the trace output cannot be serialized.
539pub fn serialize_trace_import_path_programmatic_json(
540    output: TraceImportPathProgrammaticOutput,
541) -> ProgrammaticResult<serde_json::Value> {
542    serialize_trace_programmatic_output(
543        output.output,
544        "import path trace",
545        "FALLOW_SERIALIZE_TRACE_IMPORT_PATH",
546        "trace_import_path",
547    )
548}
549
550/// Serialize typed dependency-trace output into the JSON compatibility contract.
551///
552/// # Errors
553///
554/// Returns a structured error if the trace output cannot be serialized.
555pub fn serialize_trace_dependency_programmatic_json(
556    output: TraceDependencyProgrammaticOutput,
557) -> ProgrammaticResult<serde_json::Value> {
558    serialize_trace_programmatic_output(
559        output.output,
560        "dependency trace",
561        "FALLOW_SERIALIZE_TRACE_DEPENDENCY",
562        "trace_dependency",
563    )
564}
565
566/// Serialize typed stack-trace resolution into the JSON compatibility contract.
567///
568/// # Errors
569///
570/// Returns a structured error if the trace output cannot be serialized.
571pub fn serialize_trace_error_programmatic_json(
572    output: TraceErrorProgrammaticOutput,
573) -> ProgrammaticResult<serde_json::Value> {
574    serialize_trace_programmatic_output(
575        output.output,
576        "stack-trace resolution",
577        "FALLOW_SERIALIZE_TRACE_ERROR",
578        "trace_error",
579    )
580}
581
582/// Serialize typed clone-trace output into the JSON compatibility contract.
583///
584/// # Errors
585///
586/// Returns a structured error if the trace output cannot be serialized.
587pub fn serialize_trace_clone_programmatic_json(
588    output: TraceCloneProgrammaticOutput,
589) -> ProgrammaticResult<serde_json::Value> {
590    serialize_trace_programmatic_output(
591        output.output,
592        "clone trace",
593        "FALLOW_SERIALIZE_TRACE_CLONE",
594        "trace_clone",
595    )
596}
597
598fn serialize_trace_programmatic_output<T: Serialize>(
599    output: T,
600    context: &'static str,
601    code: &'static str,
602    error_context: &'static str,
603) -> ProgrammaticResult<serde_json::Value> {
604    serde_json::to_value(output).map_err(|err| {
605        ProgrammaticError::new(format!("failed to serialize {context}: {err}"), 2)
606            .with_code(code)
607            .with_context(error_context)
608    })
609}
610
611/// Serialize typed health / complexity output into the JSON compatibility contract.
612///
613/// # Errors
614///
615/// Returns a structured error if the health output contract cannot be serialized.
616pub fn serialize_health_programmatic_json(
617    output: HealthProgrammaticOutput,
618) -> ProgrammaticResult<serde_json::Value> {
619    let HealthProgrammaticOutput {
620        report,
621        grouping,
622        root,
623        elapsed,
624        explain,
625        workspace_diagnostics,
626        next_steps,
627        telemetry_analysis_run_id,
628        request_outcomes,
629    } = output;
630    let (grouped_by, groups, group_filter) = grouping.map_or((None, None, None), |grouping| {
631        (
632            group_by_mode_from_label(grouping.mode),
633            Some(grouping.groups),
634            grouping.filter,
635        )
636    });
637    serialize_health_report_json(HealthJsonReportInput {
638        gate_outcomes: None,
639        request_outcomes,
640        report,
641        root: &root,
642        elapsed,
643        explain,
644        type_aware: None,
645        grouped_by,
646        groups,
647        group_filter,
648        workspace_diagnostics,
649        next_steps,
650        telemetry_analysis_run_id: telemetry_analysis_run_id.as_deref(),
651    })
652    .map_err(|err| {
653        ProgrammaticError::new(format!("failed to serialize health report: {err}"), 2)
654            .with_code("FALLOW_SERIALIZE_HEALTH_REPORT")
655            .with_context("health")
656    })
657}
658
659fn group_by_mode_from_label(label: &str) -> Option<GroupByMode> {
660    match label {
661        "owner" => Some(GroupByMode::Owner),
662        "directory" => Some(GroupByMode::Directory),
663        "package" => Some(GroupByMode::Package),
664        "section" => Some(GroupByMode::Section),
665        _ => None,
666    }
667}
668
669#[cfg(test)]
670mod tests {
671    use super::{serialize_audit_dead_code, serialize_combined_programmatic_json};
672    use crate::DupesReportPayload;
673    use crate::runtime::{
674        CombinedProgrammaticOutput, DeadCodeProgrammaticOutput, DuplicationProgrammaticOutput,
675        HealthProgrammaticOutput,
676    };
677    use fallow_output::{
678        CHECK_SCHEMA_VERSION, CheckOutputInput, DUPES_SCHEMA_VERSION, DupesOutputInput,
679        HealthReport, build_check_output, build_dupes_output,
680    };
681    use fallow_types::duplicates::DuplicationReport;
682    use fallow_types::results::AnalysisResults;
683    use fallow_types::workspace::{WorkspaceDiagnostic, WorkspaceDiagnosticKind};
684    use std::path::Path;
685    use std::time::Duration;
686
687    fn dead_code_output(
688        root: &Path,
689        workspace_diagnostics: Vec<WorkspaceDiagnostic>,
690    ) -> DeadCodeProgrammaticOutput {
691        DeadCodeProgrammaticOutput {
692            output: build_check_output(CheckOutputInput {
693                schema_version: CHECK_SCHEMA_VERSION,
694                version: "0.0.0-test".to_owned(),
695                elapsed: Duration::ZERO,
696                results: AnalysisResults::default(),
697                config_fixable: false,
698                meta: None,
699                workspace_diagnostics,
700                next_steps: Vec::new(),
701            }),
702            root: root.to_path_buf(),
703            config_fixable: false,
704            telemetry_analysis_run_id: None,
705        }
706    }
707
708    /// Issue #2366: the audit envelope's dead-code sub-result carries the run's
709    /// workspace diagnostics root-relative, matching what the CLI audit path
710    /// reads from the registry, and omits the array when there are none.
711    #[test]
712    fn audit_dead_code_section_carries_workspace_diagnostics_root_relative_or_omits_them() {
713        let root = Path::new("/project");
714        let carried = serialize_audit_dead_code(
715            &dead_code_output(
716                root,
717                vec![WorkspaceDiagnostic::new(
718                    root,
719                    root.join("package.json"),
720                    WorkspaceDiagnosticKind::BunLockbOverrideResolutionSkipped,
721                )],
722            ),
723            None,
724        )
725        .expect("audit dead-code JSON");
726        assert_eq!(
727            carried["workspace_diagnostics"][0]["kind"],
728            "bun-lockb-override-resolution-skipped"
729        );
730        assert_eq!(carried["workspace_diagnostics"][0]["path"], "package.json");
731
732        let empty = serialize_audit_dead_code(&dead_code_output(root, Vec::new()), None)
733            .expect("audit dead-code JSON");
734        assert!(
735            empty.get("workspace_diagnostics").is_none(),
736            "an empty list is omitted from the audit dead-code section: {empty}"
737        );
738    }
739
740    fn health_output(
741        root: &Path,
742        workspace_diagnostics: Vec<WorkspaceDiagnostic>,
743    ) -> HealthProgrammaticOutput {
744        HealthProgrammaticOutput {
745            report: HealthReport::default(),
746            grouping: None,
747            root: root.to_path_buf(),
748            elapsed: Duration::ZERO,
749            explain: false,
750            workspace_diagnostics,
751            next_steps: Vec::new(),
752            telemetry_analysis_run_id: None,
753            request_outcomes: None,
754        }
755    }
756
757    fn duplication_output(
758        root: &Path,
759        workspace_diagnostics: Vec<WorkspaceDiagnostic>,
760    ) -> DuplicationProgrammaticOutput {
761        DuplicationProgrammaticOutput {
762            output: build_dupes_output(DupesOutputInput {
763                gate_outcomes: None,
764                request_outcomes: None,
765                baseline_staleness: None,
766                schema_version: DUPES_SCHEMA_VERSION,
767                version: "0.0.0-test".to_owned(),
768                elapsed: Duration::ZERO,
769                report: DupesReportPayload::from_report(&DuplicationReport::default()),
770                clone_groups_shown: 0,
771                clone_groups_omitted: 0,
772                clone_families_shown: 0,
773                clone_families_omitted: 0,
774                grouped_by: None,
775                total_issues: None,
776                groups: None,
777                meta: None,
778                workspace_diagnostics,
779                next_steps: Vec::new(),
780            }),
781            root: root.to_path_buf(),
782            threshold: 0.0,
783            telemetry_analysis_run_id: None,
784        }
785    }
786
787    fn combined_output(
788        root: &Path,
789        dead_code: Option<DeadCodeProgrammaticOutput>,
790        health: Option<HealthProgrammaticOutput>,
791    ) -> CombinedProgrammaticOutput {
792        combined_output_with_duplication(root, dead_code, health, None)
793    }
794
795    fn combined_output_with_duplication(
796        root: &Path,
797        dead_code: Option<DeadCodeProgrammaticOutput>,
798        health: Option<HealthProgrammaticOutput>,
799        duplication: Option<DuplicationProgrammaticOutput>,
800    ) -> CombinedProgrammaticOutput {
801        CombinedProgrammaticOutput {
802            dead_code,
803            duplication,
804            health,
805            root: root.to_path_buf(),
806            elapsed: Duration::ZERO,
807            explain: false,
808            next_steps: Vec::new(),
809            telemetry_analysis_run_id: None,
810            request_outcomes: None,
811            skipped: Vec::new(),
812        }
813    }
814
815    fn bun_lockb_diagnostic(root: &Path) -> WorkspaceDiagnostic {
816        WorkspaceDiagnostic::new(
817            root,
818            root.join("package.json"),
819            WorkspaceDiagnosticKind::BunLockbOverrideResolutionSkipped,
820        )
821    }
822
823    fn large_file_diagnostic(root: &Path, relative: &str) -> WorkspaceDiagnostic {
824        WorkspaceDiagnostic::new(
825            root,
826            root.join(relative),
827            WorkspaceDiagnosticKind::SkippedLargeFile {
828                size_bytes: 6_000_000,
829            },
830        )
831    }
832
833    fn root_kinds(document: &serde_json::Value) -> Vec<String> {
834        document["workspace_diagnostics"]
835            .as_array()
836            .cloned()
837            .unwrap_or_default()
838            .iter()
839            .map(|diagnostic| diagnostic["kind"].as_str().unwrap_or_default().to_owned())
840            .collect()
841    }
842
843    /// Issue #2366: the programmatic combined envelope (MCP `analyze` in code
844    /// mode, NAPI, embedders) carries the run's workspace diagnostics on the
845    /// combined root, root-relative, and omits the array when there are none.
846    #[test]
847    fn combined_programmatic_root_carries_workspace_diagnostics_or_omits_them() {
848        let root = Path::new("/project");
849        let carried = serialize_combined_programmatic_json(combined_output(
850            root,
851            Some(dead_code_output(root, vec![bun_lockb_diagnostic(root)])),
852            None,
853        ))
854        .expect("combined JSON");
855        assert_eq!(
856            carried["workspace_diagnostics"][0]["kind"],
857            "bun-lockb-override-resolution-skipped"
858        );
859        assert_eq!(carried["workspace_diagnostics"][0]["path"], "package.json");
860        assert!(
861            carried["check"].is_object(),
862            "the check section is present, so the absence check below is not vacuous: {carried}"
863        );
864        assert!(
865            carried["check"].get("workspace_diagnostics").is_none(),
866            "the check section is not a second carrier: {carried}"
867        );
868
869        let empty = serialize_combined_programmatic_json(combined_output(
870            root,
871            Some(dead_code_output(root, Vec::new())),
872            None,
873        ))
874        .expect("combined JSON");
875        assert!(
876            empty.get("workspace_diagnostics").is_none(),
877            "an empty list is omitted from the combined root: {empty}"
878        );
879    }
880
881    /// Issue #2366: a programmatic combined run without a dead-code section
882    /// (the `--skip check` / `--only health` shape) still reports the
883    /// diagnostics, taken from the section that did run.
884    #[test]
885    fn combined_programmatic_root_carries_workspace_diagnostics_without_a_dead_code_section() {
886        let root = Path::new("/project");
887        let carried = serialize_combined_programmatic_json(combined_output(
888            root,
889            None,
890            Some(health_output(root, vec![bun_lockb_diagnostic(root)])),
891        ))
892        .expect("combined JSON");
893        assert!(
894            carried.get("check").is_none(),
895            "this run has no check section: {carried}"
896        );
897        assert_eq!(
898            carried["workspace_diagnostics"][0]["kind"],
899            "bun-lockb-override-resolution-skipped"
900        );
901        assert_eq!(carried["workspace_diagnostics"][0]["path"], "package.json");
902    }
903
904    /// Issue #2366: a duplication-only combined run (an embedder driving
905    /// `CombinedOptions` with just `duplication`) reports what that section
906    /// recorded.
907    #[test]
908    fn combined_programmatic_root_carries_workspace_diagnostics_from_a_duplication_only_run() {
909        let root = Path::new("/project");
910        let carried = serialize_combined_programmatic_json(combined_output_with_duplication(
911            root,
912            None,
913            None,
914            Some(duplication_output(
915                root,
916                vec![large_file_diagnostic(root, "src/generated.ts")],
917            )),
918        ))
919        .expect("combined JSON");
920        assert!(
921            carried.get("check").is_none() && carried.get("health").is_none(),
922            "only the dupes section ran: {carried}"
923        );
924        assert_eq!(root_kinds(&carried), ["skipped-large-file"]);
925        assert_eq!(
926            carried["workspace_diagnostics"][0]["path"],
927            "src/generated.ts"
928        );
929    }
930
931    /// Issue #2366: sections of one combined run can record different lists,
932    /// because each analysis walks the project itself and a per-analysis
933    /// `production` mode changes which files that walk sees. The root carries
934    /// the union so nothing the run recorded is dropped, deduplicated so a
935    /// diagnostic two sections both saw is reported once, and in section order
936    /// so a run whose analyses agree matches the standalone `dead-code`
937    /// envelope exactly.
938    #[test]
939    fn combined_programmatic_root_unions_sections_that_recorded_different_diagnostics() {
940        let root = Path::new("/project");
941        let shared = bun_lockb_diagnostic(root);
942        let carried = serialize_combined_programmatic_json(combined_output_with_duplication(
943            root,
944            Some(dead_code_output(
945                root,
946                vec![shared.clone(), large_file_diagnostic(root, "src/big.ts")],
947            )),
948            Some(health_output(root, vec![shared.clone()])),
949            Some(duplication_output(
950                root,
951                vec![shared, large_file_diagnostic(root, "src/other.ts")],
952            )),
953        ))
954        .expect("combined JSON");
955        assert_eq!(
956            root_kinds(&carried),
957            [
958                "bun-lockb-override-resolution-skipped",
959                "skipped-large-file",
960                "skipped-large-file",
961            ],
962            "the union keeps dead-code order first and drops the repeats: {}",
963            carried["workspace_diagnostics"]
964        );
965        let paths: Vec<&str> = carried["workspace_diagnostics"]
966            .as_array()
967            .expect("array")
968            .iter()
969            .map(|diagnostic| diagnostic["path"].as_str().unwrap_or_default())
970            .collect();
971        assert_eq!(paths, ["package.json", "src/big.ts", "src/other.ts"]);
972    }
973
974    /// Issue #2366: a diagnostic only the health or duplication section
975    /// recorded still reaches the root when the dead-code section recorded
976    /// nothing, the direction that a `production: { deadCode: true }` split
977    /// produces on a real project.
978    #[test]
979    fn combined_programmatic_root_keeps_diagnostics_an_empty_dead_code_section_missed() {
980        let root = Path::new("/project");
981        let carried = serialize_combined_programmatic_json(combined_output_with_duplication(
982            root,
983            Some(dead_code_output(root, Vec::new())),
984            Some(health_output(
985                root,
986                vec![large_file_diagnostic(root, "src/big.test.ts")],
987            )),
988            None,
989        ))
990        .expect("combined JSON");
991        assert_eq!(root_kinds(&carried), ["skipped-large-file"]);
992        assert_eq!(
993            carried["workspace_diagnostics"][0]["path"],
994            "src/big.test.ts"
995        );
996    }
997}