Skip to main content

fallow_api/
audit_output.rs

1//! Shared audit JSON payload contracts for programmatic consumers.
2
3use fallow_config::AuditGate;
4use fallow_output::{
5    AuditCommand, CodeClimateIssue, RootEnvelopeMode, codeclimate_issues_to_value,
6};
7use fallow_types::duplicates::DuplicationReport;
8use fallow_types::envelope::{ElapsedMs, SchemaVersion, ToolVersion};
9use fallow_types::output::NextStep;
10use serde::Serialize;
11
12/// Verdict for the audit command.
13#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
14#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
15#[serde(rename_all = "snake_case")]
16pub enum AuditVerdict {
17    /// No issues in changed files.
18    Pass,
19    /// Issues found, but all are warn-severity.
20    Warn,
21    /// Error-severity issues found in changed files.
22    Fail,
23}
24
25/// Per-category summary counts for the audit result.
26#[derive(Debug, Clone, Serialize)]
27#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
28pub struct AuditSummary {
29    pub dead_code_issues: usize,
30    pub dead_code_has_errors: bool,
31    pub complexity_findings: usize,
32    pub max_cyclomatic: Option<u16>,
33    pub duplication_clone_groups: usize,
34}
35
36/// New-vs-inherited issue counts for audit.
37#[derive(Debug, Default, Clone, Serialize)]
38#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
39pub struct AuditAttribution {
40    pub gate: AuditGate,
41    pub dead_code_introduced: usize,
42    pub dead_code_inherited: usize,
43    pub complexity_introduced: usize,
44    pub complexity_inherited: usize,
45    pub duplication_introduced: usize,
46    pub duplication_inherited: usize,
47}
48
49/// Header fields shared by audit JSON and review-brief subtract sections.
50pub struct AuditJsonHeaderInput {
51    pub schema_version: SchemaVersion,
52    pub version: ToolVersion,
53    pub verdict: AuditVerdict,
54    pub changed_files_count: u32,
55    pub base_ref: String,
56    pub base_description: Option<String>,
57    pub head_sha: Option<String>,
58    pub elapsed_ms: ElapsedMs,
59    pub base_snapshot_skipped: Option<bool>,
60    pub summary: AuditSummary,
61    pub attribution: AuditAttribution,
62}
63
64/// Typed audit JSON assembly input.
65pub struct AuditJsonOutputInput<DeadCode, Duplication, Complexity> {
66    pub header: AuditJsonHeaderInput,
67    pub dead_code: Option<DeadCode>,
68    pub duplication: Option<Duplication>,
69    pub complexity: Option<Complexity>,
70    pub next_steps: Vec<NextStep>,
71}
72
73/// Typed audit SARIF assembly input.
74#[derive(Clone, Copy)]
75pub struct AuditSarifOutputInput<'a> {
76    pub dead_code: Option<&'a serde_json::Value>,
77    pub duplication: Option<&'a DuplicationReport>,
78    pub health: Option<&'a serde_json::Value>,
79}
80
81/// Typed audit CodeClimate assembly input.
82pub struct AuditCodeClimateOutputInput {
83    pub dead_code: Vec<CodeClimateIssue>,
84    pub duplication: Vec<CodeClimateIssue>,
85    pub health: Vec<CodeClimateIssue>,
86}
87
88#[derive(Serialize)]
89struct AuditHeaderOutput {
90    schema_version: SchemaVersion,
91    version: ToolVersion,
92    command: AuditCommand,
93    verdict: AuditVerdict,
94    changed_files_count: u32,
95    base_ref: String,
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    base_description: Option<String>,
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    head_sha: Option<String>,
100    elapsed_ms: ElapsedMs,
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    base_snapshot_skipped: Option<bool>,
103    summary: AuditSummary,
104    attribution: AuditAttribution,
105}
106
107fn audit_header_output(input: AuditJsonHeaderInput) -> AuditHeaderOutput {
108    AuditHeaderOutput {
109        schema_version: input.schema_version,
110        version: input.version,
111        command: AuditCommand::Audit,
112        verdict: input.verdict,
113        changed_files_count: input.changed_files_count,
114        base_ref: input.base_ref,
115        base_description: input.base_description,
116        head_sha: input.head_sha,
117        elapsed_ms: input.elapsed_ms,
118        base_snapshot_skipped: input.base_snapshot_skipped,
119        summary: input.summary,
120        attribution: input.attribution,
121    }
122}
123
124/// Build the audit header JSON object used by review brief output.
125///
126/// # Errors
127///
128/// Returns a serde error if one of the typed header fields cannot be converted
129/// to JSON.
130pub fn build_audit_header_json(
131    input: AuditJsonHeaderInput,
132) -> Result<serde_json::Value, serde_json::Error> {
133    serde_json::to_value(audit_header_output(input))
134}
135
136/// Build the audit header as an object map for composed output contracts such
137/// as review briefs.
138///
139/// # Errors
140///
141/// Returns a serde error if one of the typed header fields cannot be converted
142/// to JSON, or if the typed header unexpectedly does not serialize to an
143/// object.
144pub fn build_audit_header_map(
145    input: AuditJsonHeaderInput,
146) -> Result<serde_json::Map<String, serde_json::Value>, serde_json::Error> {
147    match build_audit_header_json(input)? {
148        serde_json::Value::Object(header) => Ok(header),
149        _ => unreachable!("AuditHeaderOutput serializes to an object"),
150    }
151}
152
153/// Build the typed audit metadata carried by a review brief envelope.
154#[must_use]
155pub fn build_review_brief_header(
156    input: AuditJsonHeaderInput,
157) -> fallow_output::ReviewBriefHeader<AuditVerdict, AuditSummary, AuditAttribution> {
158    fallow_output::ReviewBriefHeader {
159        version: input.version,
160        verdict: input.verdict,
161        changed_files_count: input.changed_files_count,
162        base_ref: input.base_ref,
163        base_description: input.base_description,
164        head_sha: input.head_sha,
165        elapsed_ms: input.elapsed_ms,
166        base_snapshot_skipped: input.base_snapshot_skipped,
167        summary: input.summary,
168        attribution: input.attribution,
169    }
170}
171
172/// Serialize a typed audit JSON output envelope.
173///
174/// # Errors
175///
176/// Returns a serde error if the envelope or one of its nested payload sections
177/// cannot be converted to JSON.
178pub fn serialize_audit_json<DeadCode, Duplication, Complexity>(
179    input: AuditJsonOutputInput<DeadCode, Duplication, Complexity>,
180    mode: RootEnvelopeMode,
181    analysis_run_id: Option<&str>,
182) -> Result<serde_json::Value, serde_json::Error>
183where
184    DeadCode: Serialize,
185    Duplication: Serialize,
186    Complexity: Serialize,
187{
188    let header = audit_header_output(input.header);
189    let output = fallow_output::AuditOutput {
190        schema_version: header.schema_version,
191        version: header.version,
192        command: header.command,
193        verdict: header.verdict,
194        changed_files_count: header.changed_files_count,
195        base_ref: header.base_ref,
196        base_description: header.base_description,
197        head_sha: header.head_sha,
198        elapsed_ms: header.elapsed_ms,
199        base_snapshot_skipped: header.base_snapshot_skipped,
200        summary: header.summary,
201        attribution: header.attribution,
202        meta: None,
203        dead_code: input.dead_code,
204        duplication: input.duplication,
205        complexity: input.complexity,
206        next_steps: input.next_steps,
207    };
208    fallow_output::serialize_audit_json_output(output, mode, analysis_run_id)
209}
210
211/// Build the combined SARIF document for `fallow audit`.
212#[must_use]
213pub fn build_audit_sarif(input: AuditSarifOutputInput<'_>) -> serde_json::Value {
214    let mut all_runs = Vec::new();
215
216    if let Some(sarif) = input.dead_code {
217        extend_sarif_runs(&mut all_runs, sarif);
218    }
219
220    if let Some(duplication) = input.duplication
221        && !duplication.clone_groups.is_empty()
222    {
223        all_runs.push(build_audit_duplication_sarif_run(duplication));
224    }
225
226    if let Some(sarif) = input.health {
227        extend_sarif_runs(&mut all_runs, sarif);
228    }
229
230    serde_json::json!({
231        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
232        "version": "2.1.0",
233        "runs": all_runs,
234    })
235}
236
237fn extend_sarif_runs(all_runs: &mut Vec<serde_json::Value>, sarif: &serde_json::Value) {
238    if let Some(runs) = sarif.get("runs").and_then(|runs| runs.as_array()) {
239        all_runs.extend(runs.iter().cloned());
240    }
241}
242
243fn build_audit_duplication_sarif_run(duplication: &DuplicationReport) -> serde_json::Value {
244    serde_json::json!({
245        "tool": {
246            "driver": {
247                "name": "fallow",
248                "version": env!("CARGO_PKG_VERSION"),
249                "informationUri": "https://github.com/fallow-rs/fallow",
250            }
251        },
252        "automationDetails": { "id": "fallow/audit/dupes" },
253        "results": duplication.clone_groups.iter().enumerate().map(|(i, group)| {
254            serde_json::json!({
255                "ruleId": "fallow/code-duplication",
256                "level": "warning",
257                "message": {
258                    "text": format!(
259                        "Clone group {} ({} lines, {} instances)",
260                        i + 1,
261                        group.line_count,
262                        group.instances.len()
263                    ),
264                },
265            })
266        }).collect::<Vec<_>>()
267    })
268}
269
270/// Build combined CodeClimate issues for `fallow audit`.
271#[must_use]
272pub fn build_audit_codeclimate_issues(input: AuditCodeClimateOutputInput) -> Vec<CodeClimateIssue> {
273    let mut all_issues = input.dead_code;
274    all_issues.extend(input.duplication);
275    all_issues.extend(input.health);
276    all_issues
277}
278
279/// Build the combined CodeClimate JSON array for `fallow audit`.
280#[must_use]
281pub fn build_audit_codeclimate(input: AuditCodeClimateOutputInput) -> serde_json::Value {
282    codeclimate_issues_to_value(&build_audit_codeclimate_issues(input))
283}
284
285#[cfg(test)]
286mod tests {
287    use super::*;
288
289    #[test]
290    fn audit_verdict_uses_snake_case_wire_names() {
291        let value = serde_json::to_value(AuditVerdict::Pass).expect("serialize verdict");
292        assert_eq!(value, serde_json::json!("pass"));
293    }
294
295    fn header_input() -> AuditJsonHeaderInput {
296        AuditJsonHeaderInput {
297            schema_version: SchemaVersion(7),
298            version: ToolVersion("0.0.0-test".to_string()),
299            verdict: AuditVerdict::Pass,
300            changed_files_count: 5,
301            base_ref: "abc123".to_string(),
302            base_description: Some("merge-base with origin/main".to_string()),
303            head_sha: Some("def456".to_string()),
304            elapsed_ms: ElapsedMs(12),
305            base_snapshot_skipped: Some(true),
306            summary: AuditSummary {
307                dead_code_issues: 0,
308                dead_code_has_errors: false,
309                complexity_findings: 0,
310                max_cyclomatic: None,
311                duplication_clone_groups: 0,
312            },
313            attribution: AuditAttribution {
314                gate: AuditGate::NewOnly,
315                ..AuditAttribution::default()
316            },
317        }
318    }
319
320    #[test]
321    fn audit_header_json_uses_typed_contract_fields() {
322        let value = build_audit_header_json(header_input()).expect("serialize audit header");
323
324        assert_eq!(value["schema_version"], 7);
325        assert_eq!(value["command"], "audit");
326        assert_eq!(value["base_description"], "merge-base with origin/main");
327        assert_eq!(value["head_sha"], "def456");
328        assert_eq!(value["base_snapshot_skipped"], true);
329    }
330
331    #[test]
332    fn audit_header_map_uses_typed_contract_fields() {
333        let header = build_audit_header_map(header_input()).expect("serialize audit header");
334
335        assert_eq!(header["schema_version"], 7);
336        assert_eq!(header["command"], "audit");
337        assert_eq!(header["base_description"], "merge-base with origin/main");
338    }
339
340    #[test]
341    fn audit_json_serializer_applies_root_kind_and_sections() {
342        let value = serialize_audit_json(
343            AuditJsonOutputInput {
344                header: header_input(),
345                dead_code: Some(serde_json::json!({"total_issues": 0})),
346                duplication: None::<serde_json::Value>,
347                complexity: None::<serde_json::Value>,
348                next_steps: Vec::new(),
349            },
350            RootEnvelopeMode::Tagged,
351            Some("run-1"),
352        )
353        .expect("serialize audit output");
354
355        assert_eq!(value["kind"], "audit");
356        assert_eq!(value["dead_code"]["total_issues"], 0);
357        assert_eq!(value["_meta"]["telemetry"]["analysis_run_id"], "run-1");
358    }
359
360    #[test]
361    fn audit_sarif_combines_runs_and_duplication_run() {
362        let duplication = DuplicationReport {
363            clone_groups: vec![fallow_types::duplicates::CloneGroup {
364                instances: vec![
365                    fallow_types::duplicates::CloneInstance {
366                        file: "src/a.ts".into(),
367                        start_line: 1,
368                        end_line: 12,
369                        start_col: 1,
370                        end_col: 1,
371                        fragment: "duplicated();".to_string(),
372                    },
373                    fallow_types::duplicates::CloneInstance {
374                        file: "src/b.ts".into(),
375                        start_line: 1,
376                        end_line: 12,
377                        start_col: 1,
378                        end_col: 1,
379                        fragment: "duplicated();".to_string(),
380                    },
381                ],
382                token_count: 40,
383                line_count: 12,
384            }],
385            ..DuplicationReport::default()
386        };
387        let dead_code = serde_json::json!({"runs": [{"automationDetails": {"id": "check"}}]});
388        let health = serde_json::json!({"runs": [{"automationDetails": {"id": "health"}}]});
389
390        let value = build_audit_sarif(AuditSarifOutputInput {
391            dead_code: Some(&dead_code),
392            duplication: Some(&duplication),
393            health: Some(&health),
394        });
395
396        assert_eq!(value["version"], "2.1.0");
397        assert_eq!(value["runs"].as_array().expect("runs").len(), 3);
398        assert_eq!(
399            value["runs"][1]["automationDetails"]["id"],
400            "fallow/audit/dupes"
401        );
402    }
403
404    #[test]
405    fn audit_codeclimate_combines_issue_sections() {
406        let issue = CodeClimateIssue {
407            kind: fallow_output::CodeClimateIssueKind::Issue,
408            check_name: "fallow/test".to_string(),
409            description: "test".to_string(),
410            severity: fallow_output::CodeClimateSeverity::Minor,
411            fingerprint: "abc".to_string(),
412            location: fallow_output::CodeClimateLocation {
413                path: "src/a.ts".to_string(),
414                lines: fallow_output::CodeClimateLines { begin: 1 },
415            },
416            categories: vec!["Bug Risk".to_string()],
417            owner: None,
418            group: None,
419        };
420
421        let value = build_audit_codeclimate(AuditCodeClimateOutputInput {
422            dead_code: vec![issue.clone()],
423            duplication: vec![issue.clone()],
424            health: vec![issue],
425        });
426
427        assert_eq!(value.as_array().expect("issues").len(), 3);
428    }
429}