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