Skip to main content

fallow_api/
audit_output.rs

1//! Shared audit JSON payload contracts for programmatic consumers.
2
3use fallow_config::{AuditGate, AuditWorsened};
4use fallow_output::{AuditCommand, CodeClimateIssue, codeclimate_issues_to_value};
5use fallow_types::envelope::{ElapsedMs, SchemaVersion, ToolVersion};
6use fallow_types::output::NextStep;
7use serde::Serialize;
8
9/// Verdict for the audit command.
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
11#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
12#[serde(rename_all = "snake_case")]
13pub enum AuditVerdict {
14    /// No issues in changed files.
15    Pass,
16    /// Issues found, but all are warn-severity.
17    Warn,
18    /// Error-severity issues found in changed files.
19    Fail,
20}
21
22/// Per-category summary counts for the audit result.
23#[derive(Debug, Clone, Serialize)]
24#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
25pub struct AuditSummary {
26    /// Total dead-code issues reported for the changed files.
27    pub dead_code_issues: usize,
28    /// Whether any reported dead-code issue has error severity.
29    pub dead_code_has_errors: bool,
30    /// True when `--only`, `--skip` or `audit.deadCode = false` skipped the
31    /// dead-code sub-analysis. The dead-code counts are then 0 and do not mean
32    /// a clean result. Omitted when the sub-analysis ran.
33    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
34    pub dead_code_skipped: bool,
35    /// True when `--only`, `--skip` or `audit.health = false` skipped the
36    /// health sub-analysis. The complexity and styling counts are then 0 and
37    /// do not mean a clean result. Omitted when the sub-analysis ran.
38    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
39    pub complexity_skipped: bool,
40    /// True when `--only`, `--skip` or `audit.dupes = false` skipped the
41    /// duplication sub-analysis. The clone-group counts are then 0 and do not
42    /// mean a clean result. Omitted when the sub-analysis ran.
43    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
44    pub duplication_skipped: bool,
45    /// Total complexity findings reported for the changed files.
46    pub complexity_findings: usize,
47    /// Highest cyclomatic complexity among the findings; `None` when there
48    /// are no complexity findings.
49    pub max_cyclomatic: Option<u16>,
50    /// Clone groups touching the changed files.
51    pub duplication_clone_groups: usize,
52}
53
54/// New-vs-inherited issue counts for audit.
55#[derive(Debug, Default, Clone, Serialize)]
56#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
57pub struct AuditAttribution {
58    /// Configured gate: `new-only` fails only on introduced findings,
59    /// `all` also fails on inherited ones.
60    pub gate: AuditGate,
61    /// How a worsened complexity finding affects the verdict under the
62    /// `new-only` gate. `warn` gives at least a `warn` verdict. `error` counts
63    /// the finding like an introduced finding.
64    #[serde(default)]
65    pub worsened: AuditWorsened,
66    /// Dead-code findings absent from the base snapshot.
67    pub dead_code_introduced: usize,
68    /// Dead-code findings already present in the base snapshot.
69    pub dead_code_inherited: usize,
70    /// Complexity findings absent from the base snapshot.
71    pub complexity_introduced: usize,
72    /// Complexity findings already present in the base snapshot.
73    pub complexity_inherited: usize,
74    /// Complexity findings whose `attribution` is `worsened`. These findings
75    /// are in the base snapshot, and a measured value is higher now. They are
76    /// also counted in `complexity_inherited`.
77    #[serde(default)]
78    pub complexity_worsened: usize,
79    /// Clone groups absent from the base snapshot.
80    pub duplication_introduced: usize,
81    /// Clone groups already present in the base snapshot.
82    pub duplication_inherited: usize,
83}
84
85/// Header fields shared by audit JSON and review-brief subtract sections.
86pub struct AuditJsonHeaderInput {
87    /// Output schema version of the envelope.
88    pub schema_version: SchemaVersion,
89    /// Fallow version that produced the output.
90    pub version: ToolVersion,
91    /// Overall audit verdict.
92    pub verdict: AuditVerdict,
93    /// Number of changed files the audit analyzed.
94    pub changed_files_count: u32,
95    /// Git revision the audit compared against.
96    pub base_ref: String,
97    /// Human-readable description of how the base was chosen, such as
98    /// `merge-base with origin/main`; omitted from JSON when `None`.
99    pub base_description: Option<String>,
100    /// Commit SHA of the analyzed head; omitted from JSON when `None`.
101    pub head_sha: Option<String>,
102    /// Audit wall time in milliseconds.
103    pub elapsed_ms: ElapsedMs,
104    /// `Some(true)` when the base snapshot was skipped, so no attribution
105    /// ran; omitted from JSON when `None`.
106    pub base_snapshot_skipped: Option<bool>,
107    /// Per-category issue counts.
108    pub summary: AuditSummary,
109    /// New-vs-inherited counts and the configured gate.
110    pub attribution: AuditAttribution,
111}
112
113/// Typed audit JSON assembly input.
114pub struct AuditJsonOutputInput<DeadCode, Duplication, Complexity> {
115    /// Every gate this run evaluated, absent when it evaluated none. The
116    /// programmatic route runs no CLI-layer gate and leaves this `None`.
117    pub gate_outcomes: Option<fallow_output::GateOutcomes>,
118
119    /// Envelope header fields.
120    pub header: AuditJsonHeaderInput,
121    /// Optional explain metadata block.
122    pub meta: Option<fallow_types::envelope::Meta>,
123    /// Dead-code section payload; `None` omits the section.
124    pub dead_code: Option<DeadCode>,
125    /// Duplication section payload; `None` omits the section.
126    pub duplication: Option<Duplication>,
127    /// Complexity (health) section payload; `None` omits the section.
128    pub complexity: Option<Complexity>,
129    /// Diff-risk findings; an empty report omits the section.
130    pub diff_risk: fallow_output::DiffRiskReport,
131    /// The run notices of the audit; an empty list omits the root member.
132    /// See [`audit_run_notices`].
133    pub workspace_diagnostics: Vec<fallow_types::workspace::WorkspaceDiagnostic>,
134    /// Suggested follow-up commands for the consumer.
135    pub next_steps: Vec<NextStep>,
136}
137
138/// The run notices among the workspace diagnostics of the audit sections,
139/// once each, for the root `workspace_diagnostics` of the audit envelope.
140pub fn audit_run_notices<'a>(
141    sections: impl IntoIterator<Item = &'a [fallow_types::workspace::WorkspaceDiagnostic]>,
142) -> Vec<fallow_types::workspace::WorkspaceDiagnostic> {
143    sections
144        .into_iter()
145        .map(|diagnostics| {
146            diagnostics
147                .iter()
148                .filter(|diagnostic| diagnostic.kind.is_run_notice())
149                .cloned()
150                .collect()
151        })
152        .fold(
153            Vec::new(),
154            fallow_types::workspace::merge_workspace_diagnostics,
155        )
156}
157
158/// Typed audit SARIF assembly input.
159#[derive(Clone, Copy)]
160pub struct AuditSarifOutputInput<'a> {
161    /// Prebuilt dead-code SARIF document whose runs are merged in.
162    pub dead_code: Option<&'a serde_json::Value>,
163    /// Duplication input of the dedicated SARIF run; skipped when the report
164    /// has no clone groups.
165    pub duplication: Option<fallow_output::DuplicationSarifInput<'a>>,
166    /// Prebuilt health SARIF document whose runs are merged in.
167    pub health: Option<&'a serde_json::Value>,
168    /// Diff-risk findings, converted into a dedicated SARIF run; skipped when
169    /// empty.
170    pub diff_risk: Option<&'a fallow_output::DiffRiskReport>,
171}
172
173/// Typed audit CodeClimate assembly input.
174pub struct AuditCodeClimateOutputInput {
175    /// Dead-code issues, emitted first in the combined array.
176    pub dead_code: Vec<CodeClimateIssue>,
177    /// Duplication issues, emitted after dead code.
178    pub duplication: Vec<CodeClimateIssue>,
179    /// Health issues, emitted after duplication.
180    pub health: Vec<CodeClimateIssue>,
181    /// Diff-risk issues, emitted last.
182    pub diff_risk: Vec<CodeClimateIssue>,
183}
184
185#[derive(Serialize)]
186struct AuditHeaderOutput {
187    schema_version: SchemaVersion,
188    version: ToolVersion,
189    command: AuditCommand,
190    verdict: AuditVerdict,
191    changed_files_count: u32,
192    base_ref: String,
193    #[serde(default, skip_serializing_if = "Option::is_none")]
194    base_description: Option<String>,
195    #[serde(default, skip_serializing_if = "Option::is_none")]
196    head_sha: Option<String>,
197    elapsed_ms: ElapsedMs,
198    #[serde(default, skip_serializing_if = "Option::is_none")]
199    base_snapshot_skipped: Option<bool>,
200    summary: AuditSummary,
201    attribution: AuditAttribution,
202}
203
204fn audit_header_output(input: AuditJsonHeaderInput) -> AuditHeaderOutput {
205    AuditHeaderOutput {
206        schema_version: input.schema_version,
207        version: input.version,
208        command: AuditCommand::Audit,
209        verdict: input.verdict,
210        changed_files_count: input.changed_files_count,
211        base_ref: input.base_ref,
212        base_description: input.base_description,
213        head_sha: input.head_sha,
214        elapsed_ms: input.elapsed_ms,
215        base_snapshot_skipped: input.base_snapshot_skipped,
216        summary: input.summary,
217        attribution: input.attribution,
218    }
219}
220
221/// Build the audit header JSON object used by review brief output.
222///
223/// # Errors
224///
225/// Returns a serde error if one of the typed header fields cannot be converted
226/// to JSON.
227pub fn build_audit_header_json(
228    input: AuditJsonHeaderInput,
229) -> Result<serde_json::Value, serde_json::Error> {
230    serde_json::to_value(audit_header_output(input))
231}
232
233/// Build the audit header as an object map for composed output contracts such
234/// as review briefs.
235///
236/// # Errors
237///
238/// Returns a serde error if one of the typed header fields cannot be converted
239/// to JSON, or if the typed header unexpectedly does not serialize to an
240/// object.
241pub fn build_audit_header_map(
242    input: AuditJsonHeaderInput,
243) -> Result<serde_json::Map<String, serde_json::Value>, serde_json::Error> {
244    match build_audit_header_json(input)? {
245        serde_json::Value::Object(header) => Ok(header),
246        _ => unreachable!("AuditHeaderOutput serializes to an object"),
247    }
248}
249
250/// Build the typed audit metadata carried by a review brief envelope.
251#[must_use]
252pub fn build_review_brief_header(
253    input: AuditJsonHeaderInput,
254) -> fallow_output::ReviewBriefHeader<AuditVerdict, AuditSummary, AuditAttribution> {
255    fallow_output::ReviewBriefHeader {
256        version: input.version,
257        verdict: input.verdict,
258        changed_files_count: input.changed_files_count,
259        base_ref: input.base_ref,
260        base_description: input.base_description,
261        head_sha: input.head_sha,
262        elapsed_ms: input.elapsed_ms,
263        base_snapshot_skipped: input.base_snapshot_skipped,
264        summary: input.summary,
265        attribution: input.attribution,
266    }
267}
268
269/// Serialize a typed audit JSON output envelope.
270///
271/// # Errors
272///
273/// Returns a serde error if the envelope or one of its nested payload sections
274/// cannot be converted to JSON.
275pub fn serialize_audit_json<DeadCode, Duplication, Complexity>(
276    input: AuditJsonOutputInput<DeadCode, Duplication, Complexity>,
277    analysis_run_id: Option<&str>,
278) -> Result<serde_json::Value, serde_json::Error>
279where
280    DeadCode: Serialize,
281    Duplication: Serialize,
282    Complexity: Serialize,
283{
284    let header = audit_header_output(input.header);
285    let complexity = input.complexity.map(serde_json::to_value).transpose()?;
286    let output = fallow_output::AuditOutput {
287        schema_version: header.schema_version,
288        version: header.version,
289        command: header.command,
290        verdict: header.verdict,
291        changed_files_count: header.changed_files_count,
292        base_ref: header.base_ref,
293        base_description: header.base_description,
294        head_sha: header.head_sha,
295        elapsed_ms: header.elapsed_ms,
296        base_snapshot_skipped: header.base_snapshot_skipped,
297        summary: header.summary,
298        attribution: header.attribution,
299        gate_outcomes: input.gate_outcomes,
300        meta: input.meta,
301        dead_code: input.dead_code,
302        duplication: input.duplication,
303        complexity,
304        diff_risk: (!input.diff_risk.is_empty()).then_some(input.diff_risk),
305        workspace_diagnostics: input.workspace_diagnostics,
306        next_steps: input.next_steps,
307    };
308    let mut value = fallow_output::serialize_audit_json_output(output, analysis_run_id)?;
309    attach_audit_wire_attribution(&mut value);
310    Ok(value)
311}
312
313/// Attach every wire-only audit attribution derivation in one pass: styling
314/// counts and the duplication demotion counter.
315///
316/// The single entry point for audit-family envelopes (audit JSON and the
317/// review brief), so a future envelope cannot wire one derivation and miss
318/// the other.
319pub fn attach_audit_wire_attribution(value: &mut serde_json::Value) {
320    attach_audit_styling_attribution(value);
321    attach_audit_duplication_demotion_attribution(value);
322    attach_audit_diff_risk_attribution(value);
323}
324
325/// Add `attribution.diff_risk_introduced`, the number of serialized
326/// `diff_risk.findings[]` entries.
327///
328/// Every diff-risk finding is introduced by construction: the rules compare
329/// the base and head text of the change. Always inserted when an
330/// `attribution` object is present: an integer, `0` when the section is
331/// absent. Wire-only, like the styling counts.
332pub fn attach_audit_diff_risk_attribution(value: &mut serde_json::Value) {
333    let introduced = value
334        .get("diff_risk")
335        .and_then(|section| section.get("findings"))
336        .and_then(serde_json::Value::as_array)
337        .map_or(0, Vec::len);
338    if let Some(attribution) = value
339        .get_mut("attribution")
340        .and_then(serde_json::Value::as_object_mut)
341    {
342        attribution.insert(
343            "diff_risk_introduced".to_string(),
344            serde_json::json!(introduced),
345        );
346    }
347}
348
349/// Add `attribution.duplication_demoted`, derived from serialized clone
350/// groups.
351///
352/// Counts `duplication.clone_groups[]` entries carrying a `demotion_reason`
353/// (set by the new-only gate when it demotes an introduced group to
354/// inherited, issue #2220). Always inserted when an `attribution` object is
355/// present: an integer, `0` when the duplication section is absent. Wire-only,
356/// mirroring [`attach_audit_styling_attribution`], so the public Rust
357/// attribution struct stays source-compatible.
358pub fn attach_audit_duplication_demotion_attribution(value: &mut serde_json::Value) {
359    let demoted = value
360        .get("duplication")
361        .and_then(|duplication| duplication.get("clone_groups"))
362        .and_then(serde_json::Value::as_array)
363        .map_or(0, |items| {
364            items
365                .iter()
366                .filter(|item| item.get("demotion_reason").is_some())
367                .count()
368        });
369    if let Some(attribution) = value
370        .get_mut("attribution")
371        .and_then(serde_json::Value::as_object_mut)
372    {
373        attribution.insert(
374            "duplication_demoted".to_string(),
375            serde_json::json!(demoted),
376        );
377    }
378}
379
380/// Add styling attribution totals derived from annotated styling findings.
381///
382/// This keeps the public Rust attribution and finding structs source-compatible
383/// while extending audit-family JSON envelopes with the wire-only fields.
384pub fn attach_audit_styling_attribution(value: &mut serde_json::Value) {
385    let findings = value
386        .get("complexity")
387        .and_then(|complexity| complexity.get("styling_findings"))
388        .and_then(serde_json::Value::as_array);
389    let styling_introduced = findings.map_or(0, |items| {
390        items
391            .iter()
392            .filter(|item| {
393                item.get("introduced").and_then(serde_json::Value::as_bool) == Some(true)
394            })
395            .count()
396    });
397    let styling_inherited = findings.map_or(0, |items| {
398        items
399            .iter()
400            .filter(|item| {
401                item.get("introduced").and_then(serde_json::Value::as_bool) == Some(false)
402            })
403            .count()
404    });
405    if let Some(attribution) = value
406        .get_mut("attribution")
407        .and_then(serde_json::Value::as_object_mut)
408    {
409        attribution.insert(
410            "styling_introduced".to_string(),
411            serde_json::json!(styling_introduced),
412        );
413        attribution.insert(
414            "styling_inherited".to_string(),
415            serde_json::json!(styling_inherited),
416        );
417    }
418}
419
420/// Build the combined SARIF document for `fallow audit`.
421#[must_use]
422pub fn build_audit_sarif(input: AuditSarifOutputInput<'_>) -> serde_json::Value {
423    let mut all_runs = Vec::new();
424
425    if let Some(sarif) = input.dead_code {
426        fallow_output::extend_sarif_runs_with_category(
427            &mut all_runs,
428            sarif,
429            fallow_output::SARIF_CATEGORY_AUDIT_DEAD_CODE,
430        );
431    }
432
433    if let Some(duplication) = input.duplication {
434        fallow_output::extend_sarif_runs_with_duplication(
435            &mut all_runs,
436            duplication,
437            fallow_output::SARIF_CATEGORY_AUDIT_DUPES,
438        );
439    }
440
441    if let Some(sarif) = input.health {
442        fallow_output::extend_sarif_runs_with_category(
443            &mut all_runs,
444            sarif,
445            fallow_output::SARIF_CATEGORY_AUDIT_HEALTH,
446        );
447    }
448
449    if let Some(diff_risk) = input.diff_risk
450        && !diff_risk.is_empty()
451    {
452        all_runs.push(build_audit_diff_risk_sarif_run(diff_risk));
453    }
454
455    serde_json::json!({
456        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
457        "version": "2.1.0",
458        "runs": all_runs,
459    })
460}
461
462fn build_audit_diff_risk_sarif_run(report: &fallow_output::DiffRiskReport) -> serde_json::Value {
463    let mut rules: Vec<fallow_output::DiffRiskRule> =
464        report.findings.iter().map(|finding| finding.rule).collect();
465    rules.sort();
466    rules.dedup();
467    let rule_defs: Vec<serde_json::Value> = rules
468        .iter()
469        .map(|rule| {
470            serde_json::json!({
471                "id": rule.sarif_rule_id(),
472                "shortDescription": { "text": rule.description() },
473                "helpUri": fallow_output::rule_docs_url(&format!("rules/{}", rule.code())),
474            })
475        })
476        .collect();
477    let results: Vec<serde_json::Value> = report
478        .findings
479        .iter()
480        .map(|finding| {
481            let level = match finding.severity {
482                fallow_output::DiffRiskSeverity::Error => "error",
483                fallow_output::DiffRiskSeverity::Warn => "warning",
484            };
485            let mut physical = serde_json::json!({
486                "artifactLocation": { "uri": finding.path },
487            });
488            if let Some(line) = finding.line {
489                physical["region"] = serde_json::json!({ "startLine": line });
490            }
491            let mut result = serde_json::json!({
492                "ruleId": finding.rule.sarif_rule_id(),
493                "level": level,
494                "message": { "text": format!("{} ({})", finding.message, finding.evidence) },
495                "locations": [{ "physicalLocation": physical }],
496            });
497            if !finding.related.is_empty() {
498                result["relatedLocations"] = finding
499                    .related
500                    .iter()
501                    .map(|location| {
502                        serde_json::json!({
503                            "physicalLocation": {
504                                "artifactLocation": { "uri": location.path },
505                                "region": { "startLine": location.line },
506                            }
507                        })
508                    })
509                    .collect();
510            }
511            result
512        })
513        .collect();
514    serde_json::json!({
515        "tool": {
516            "driver": {
517                "name": "fallow",
518                "version": env!("CARGO_PKG_VERSION"),
519                "informationUri": "https://github.com/fallow-rs/fallow",
520                "rules": rule_defs,
521            }
522        },
523        "automationDetails": { "id": fallow_output::SARIF_CATEGORY_AUDIT_DIFF_RISK },
524        "results": results,
525    })
526}
527
528/// Build combined CodeClimate issues for `fallow audit`.
529#[must_use]
530pub fn build_audit_codeclimate_issues(input: AuditCodeClimateOutputInput) -> Vec<CodeClimateIssue> {
531    let mut all_issues = input.dead_code;
532    all_issues.extend(input.duplication);
533    all_issues.extend(input.health);
534    all_issues.extend(input.diff_risk);
535    all_issues
536}
537
538/// Build CodeClimate issues for the diff-risk findings of an audit. Finding
539/// paths are already root-relative.
540#[must_use]
541pub fn build_diff_risk_codeclimate(
542    report: &fallow_output::DiffRiskReport,
543) -> Vec<CodeClimateIssue> {
544    report
545        .findings
546        .iter()
547        .map(|finding| {
548            let check_name = finding.rule.sarif_rule_id();
549            let line = finding.line.unwrap_or(1);
550            let fingerprint = fallow_output::codeclimate_fingerprint_hash(&[
551                &check_name,
552                &finding.path,
553                &line.to_string(),
554                &finding.evidence,
555            ]);
556            fallow_output::build_codeclimate_issue(fallow_output::CodeClimateIssueInput {
557                check_name: &check_name,
558                description: &format!("{} ({})", finding.message, finding.evidence),
559                severity: match finding.severity {
560                    fallow_output::DiffRiskSeverity::Error => {
561                        fallow_output::CodeClimateSeverity::Major
562                    }
563                    fallow_output::DiffRiskSeverity::Warn => {
564                        fallow_output::CodeClimateSeverity::Minor
565                    }
566                },
567                category: "Bug Risk",
568                path: &finding.path,
569                begin_line: finding.line,
570                fingerprint: &fingerprint,
571            })
572        })
573        .collect()
574}
575
576/// Build the combined CodeClimate JSON array for `fallow audit`.
577#[must_use]
578pub fn build_audit_codeclimate(input: AuditCodeClimateOutputInput) -> serde_json::Value {
579    codeclimate_issues_to_value(&build_audit_codeclimate_issues(input))
580}
581
582#[cfg(test)]
583mod tests {
584    use super::*;
585    use fallow_types::duplicates::DuplicationReport;
586
587    #[test]
588    fn audit_verdict_uses_snake_case_wire_names() {
589        let value = serde_json::to_value(AuditVerdict::Pass).expect("serialize verdict");
590        assert_eq!(value, serde_json::json!("pass"));
591    }
592
593    fn header_input() -> AuditJsonHeaderInput {
594        AuditJsonHeaderInput {
595            schema_version: SchemaVersion(7),
596            version: ToolVersion("0.0.0-test".to_string()),
597            verdict: AuditVerdict::Pass,
598            changed_files_count: 5,
599            base_ref: "abc123".to_string(),
600            base_description: Some("merge-base with origin/main".to_string()),
601            head_sha: Some("def456".to_string()),
602            elapsed_ms: ElapsedMs(12),
603            base_snapshot_skipped: Some(true),
604            summary: AuditSummary {
605                dead_code_issues: 0,
606                dead_code_has_errors: false,
607                dead_code_skipped: false,
608                complexity_skipped: false,
609                duplication_skipped: false,
610                complexity_findings: 0,
611                max_cyclomatic: None,
612                duplication_clone_groups: 0,
613            },
614            attribution: AuditAttribution {
615                gate: AuditGate::NewOnly,
616                ..AuditAttribution::default()
617            },
618        }
619    }
620
621    #[test]
622    fn audit_header_json_uses_typed_contract_fields() {
623        let value = build_audit_header_json(header_input()).expect("serialize audit header");
624
625        assert_eq!(value["schema_version"], 7);
626        assert_eq!(value["command"], "audit");
627        assert_eq!(value["base_description"], "merge-base with origin/main");
628        assert_eq!(value["head_sha"], "def456");
629        assert_eq!(value["base_snapshot_skipped"], true);
630    }
631
632    #[test]
633    fn audit_header_map_uses_typed_contract_fields() {
634        let header = build_audit_header_map(header_input()).expect("serialize audit header");
635
636        assert_eq!(header["schema_version"], 7);
637        assert_eq!(header["command"], "audit");
638        assert_eq!(header["base_description"], "merge-base with origin/main");
639    }
640
641    #[test]
642    fn audit_json_serializer_applies_root_kind_and_sections() {
643        let value = serialize_audit_json(
644            AuditJsonOutputInput {
645                gate_outcomes: None,
646                header: header_input(),
647                meta: None,
648                dead_code: Some(serde_json::json!({"total_issues": 0})),
649                duplication: None::<serde_json::Value>,
650                complexity: None::<serde_json::Value>,
651                diff_risk: fallow_output::DiffRiskReport::default(),
652                workspace_diagnostics: Vec::new(),
653                next_steps: Vec::new(),
654            },
655            Some("run-1"),
656        )
657        .expect("serialize audit output");
658
659        assert_eq!(value["kind"], "audit");
660        assert_eq!(value["dead_code"]["total_issues"], 0);
661        assert_eq!(value["_meta"]["telemetry"]["analysis_run_id"], "run-1");
662    }
663
664    #[test]
665    fn audit_sarif_combines_runs_and_duplication_run() {
666        let duplication = DuplicationReport {
667            clone_groups: vec![fallow_types::duplicates::CloneGroup {
668                instances: vec![
669                    fallow_types::duplicates::CloneInstance {
670                        is_symlink: false,
671                        file: "src/a.ts".into(),
672                        start_line: 1,
673                        end_line: 12,
674                        start_col: 1,
675                        end_col: 1,
676                        fragment: "duplicated();".to_string(),
677                    },
678                    fallow_types::duplicates::CloneInstance {
679                        is_symlink: false,
680                        file: "src/b.ts".into(),
681                        start_line: 1,
682                        end_line: 12,
683                        start_col: 1,
684                        end_col: 1,
685                        fragment: "duplicated();".to_string(),
686                    },
687                ],
688                token_count: 40,
689                line_count: 12,
690                similarity: None,
691            }],
692            ..DuplicationReport::default()
693        };
694        let dead_code = serde_json::json!({"runs": [{"automationDetails": {"id": "check"}}]});
695        let health = serde_json::json!({"runs": [{"automationDetails": {"id": "health"}}]});
696
697        let rule_builder = |id: &str, short: &str, level: &str| {
698            serde_json::json!({
699                "id": id,
700                "shortDescription": { "text": short },
701                "defaultConfiguration": { "level": level },
702            })
703        };
704
705        let value = build_audit_sarif(AuditSarifOutputInput {
706            dead_code: Some(&dead_code),
707            duplication: Some(fallow_output::DuplicationSarifInput {
708                report: &duplication,
709                root: std::path::Path::new(""),
710                rule_builder: &rule_builder,
711            }),
712            health: Some(&health),
713            diff_risk: None,
714        });
715
716        assert_eq!(value["version"], "2.1.0");
717        assert_eq!(value["runs"].as_array().expect("runs").len(), 3);
718        let run = &value["runs"][1];
719        assert_eq!(
720            run["automationDetails"]["id"],
721            fallow_output::SARIF_CATEGORY_AUDIT_DUPES
722        );
723        assert_eq!(
724            run["tool"]["driver"]["rules"][0]["id"],
725            "fallow/code-duplication"
726        );
727        let uris: Vec<&str> = run["results"]
728            .as_array()
729            .expect("results")
730            .iter()
731            .map(|result| {
732                result["locations"][0]["physicalLocation"]["artifactLocation"]["uri"]
733                    .as_str()
734                    .expect("each result has a file location")
735            })
736            .collect();
737        assert_eq!(uris, ["src/a.ts", "src/b.ts"]);
738    }
739
740    #[test]
741    fn audit_codeclimate_combines_issue_sections() {
742        let issue = CodeClimateIssue {
743            kind: fallow_output::CodeClimateIssueKind::Issue,
744            check_name: "fallow/test".to_string(),
745            description: "test".to_string(),
746            severity: fallow_output::CodeClimateSeverity::Minor,
747            fingerprint: "abc".to_string(),
748            location: fallow_output::CodeClimateLocation {
749                path: "src/a.ts".to_string(),
750                lines: fallow_output::CodeClimateLines {
751                    begin: 1,
752                    end: None,
753                },
754            },
755            other_locations: Vec::new(),
756            categories: vec!["Bug Risk".to_string()],
757            owner: None,
758            group: None,
759            legacy_fingerprint: None,
760            audit: None,
761        };
762
763        let value = build_audit_codeclimate(AuditCodeClimateOutputInput {
764            dead_code: vec![issue.clone()],
765            duplication: vec![issue.clone()],
766            health: vec![issue.clone()],
767            diff_risk: vec![issue],
768        });
769
770        assert_eq!(value.as_array().expect("issues").len(), 4);
771    }
772}