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