fallow-output 2.103.0

Output contract types for fallow reports
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
//! Root JSON output envelopes shared by CLI and programmatic consumers.

use fallow_types::envelope::{ElapsedMs, Meta, SchemaVersion, TelemetryMeta, ToolVersion};
use fallow_types::output::NextStep;
use serde::Serialize;

/// Whether a JSON root envelope keeps the top-level `kind` discriminator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RootEnvelopeMode {
    Tagged,
    Legacy,
}

impl RootEnvelopeMode {
    /// Convert a legacy-envelope flag into the root envelope mode.
    #[must_use]
    pub const fn from_legacy(legacy_envelope: bool) -> Self {
        if legacy_envelope {
            Self::Legacy
        } else {
            Self::Tagged
        }
    }
}

/// Serialize a typed fallow root envelope with the requested discriminator
/// mode.
///
/// # Errors
///
/// Returns a serde error when the provided envelope cannot be converted to a
/// JSON value.
pub fn serialize_json_root_output<T: Serialize>(
    output: T,
    mode: RootEnvelopeMode,
) -> Result<serde_json::Value, serde_json::Error> {
    let mut value = serde_json::to_value(output)?;
    if mode == RootEnvelopeMode::Legacy {
        remove_root_kind(&mut value);
    }
    Ok(value)
}

/// Serialize an output envelope and apply an explicit root discriminator.
///
/// Use this for command surfaces whose runtime shape is already a typed
/// envelope struct and does not need to pass through the schema-only
/// [`FallowOutput`] enum just to get a top-level `kind`.
///
/// # Errors
///
/// Returns a serde error when the provided envelope cannot be converted to a
/// JSON value.
pub fn serialize_named_json_output<T: Serialize>(
    output: T,
    kind: &'static str,
    mode: RootEnvelopeMode,
) -> Result<serde_json::Value, serde_json::Error> {
    let mut value = serde_json::to_value(output)?;
    apply_root_kind(&mut value, kind, mode);
    Ok(value)
}

/// Serialize a typed `fallow audit --format json` envelope with the standard
/// root discriminator policy.
///
/// # Errors
///
/// Returns a serde error when the provided envelope cannot be converted to a
/// JSON value.
pub fn serialize_audit_json_output<
    Verdict,
    Summary,
    Attribution,
    DeadCode,
    Duplication,
    Complexity,
>(
    output: AuditOutput<Verdict, Summary, Attribution, DeadCode, Duplication, Complexity>,
    mode: RootEnvelopeMode,
    analysis_run_id: Option<&str>,
) -> Result<serde_json::Value, serde_json::Error>
where
    Verdict: Serialize,
    Summary: Serialize,
    Attribution: Serialize,
    DeadCode: Serialize,
    Duplication: Serialize,
    Complexity: Serialize,
{
    let mut value = serde_json::to_value(output)?;
    apply_root_kind(&mut value, "audit", mode);
    attach_telemetry_meta(&mut value, analysis_run_id);
    Ok(value)
}

/// Serialize a typed bare `fallow --format json` combined envelope with the
/// standard root discriminator policy.
///
/// # Errors
///
/// Returns a serde error when the provided envelope cannot be converted to a
/// JSON value.
pub fn serialize_combined_json_output<Check, Dupes, Health>(
    output: CombinedOutput<Check, Dupes, Health>,
    mode: RootEnvelopeMode,
    analysis_run_id: Option<&str>,
) -> Result<serde_json::Value, serde_json::Error>
where
    Check: Serialize,
    Dupes: Serialize,
    Health: Serialize,
{
    let mut value = serde_json::to_value(output)?;
    apply_root_kind(&mut value, "combined", mode);
    attach_telemetry_meta(&mut value, analysis_run_id);
    Ok(value)
}

/// Remove only the document-root discriminator. Nested objects may carry their
/// own meaningful `kind` fields, so this intentionally does not recurse.
pub fn remove_root_kind(value: &mut serde_json::Value) {
    if let serde_json::Value::Object(map) = value {
        map.remove("kind");
    }
}

/// Apply a document-root discriminator unless the caller requested the legacy
/// envelope shape.
pub fn apply_root_kind(value: &mut serde_json::Value, kind: &'static str, mode: RootEnvelopeMode) {
    if mode == RootEnvelopeMode::Tagged
        && let serde_json::Value::Object(map) = value
    {
        let existing = std::mem::take(map);
        map.insert(
            "kind".to_string(),
            serde_json::Value::String(kind.to_string()),
        );
        map.extend(existing);
    }
}

/// Attach telemetry metadata to a JSON root object when a run id is available.
pub fn attach_telemetry_meta(value: &mut serde_json::Value, analysis_run_id: Option<&str>) {
    let Some(analysis_run_id) = analysis_run_id else {
        return;
    };
    let serde_json::Value::Object(map) = value else {
        return;
    };
    let meta = map
        .entry("_meta".to_string())
        .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
    if !meta.is_object() {
        *meta = serde_json::Value::Object(serde_json::Map::new());
    }
    if let serde_json::Value::Object(meta_map) = meta {
        meta_map.insert(
            "telemetry".to_string(),
            serde_json::json!({ "analysis_run_id": analysis_run_id }),
        );
    }
}

/// `fallow audit --format json` envelope.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "schema", schemars(title = "fallow audit --format json"))]
pub struct AuditOutput<Verdict, Summary, Attribution, DeadCode, Duplication, Complexity> {
    pub schema_version: SchemaVersion,
    pub version: ToolVersion,
    pub command: AuditCommand,
    pub verdict: Verdict,
    pub changed_files_count: u32,
    pub base_ref: String,
    /// Human-readable provenance of `base_ref`, e.g. `merge-base with
    /// origin/main`, `local main`, or `FALLOW_AUDIT_BASE=upstream/main`.
    /// Present when the base was auto-detected or set via `FALLOW_AUDIT_BASE`;
    /// absent for an explicit `--base` (the ref the user typed is already
    /// self-describing).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base_description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub head_sha: Option<String>,
    pub elapsed_ms: ElapsedMs,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base_snapshot_skipped: Option<bool>,
    pub summary: Summary,
    pub attribution: Attribution,
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<Meta>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dead_code: Option<DeadCode>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duplication: Option<Duplication>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub complexity: Option<Complexity>,
    /// Read-only follow-up commands computed from this run's findings. See
    /// `CheckOutput::next_steps` for the contract.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub next_steps: Vec<NextStep>,
}

/// Audit command singleton carried by [`AuditOutput`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "lowercase")]
pub enum AuditCommand {
    Audit,
}

/// Bare `fallow --format json` envelope.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[cfg_attr(
    feature = "schema",
    schemars(title = "fallow --format json (bare, combined)")
)]
pub struct CombinedOutput<Check, Dupes, Health> {
    pub schema_version: SchemaVersion,
    pub version: ToolVersion,
    pub elapsed_ms: ElapsedMs,
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<CombinedMeta>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub check: Option<Check>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dupes: Option<Dupes>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub health: Option<Health>,
    /// Read-only follow-up commands aggregated across the combined run's
    /// findings. See `CheckOutput::next_steps` for the contract.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub next_steps: Vec<NextStep>,
}

/// Optional `_meta` block for [`CombinedOutput`].
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CombinedMeta {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub check: Option<Meta>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dupes: Option<Meta>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub health: Option<Meta>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub telemetry: Option<TelemetryMeta>,
}

/// Typed root of every fallow JSON envelope shape that serializes as a JSON
/// object and participates in the documented `FallowOutput` contract. The
/// schema derived from this enum drives the document-root `oneOf` in
/// `docs/output-schema.json`.
///
/// The default wire shape now carries a top-level `kind` discriminator so
/// agents and schema-validating clients can select the variant in O(1) instead
/// of probing for unique field presence. `--legacy-envelope` is a one-cycle
/// compatibility flag that removes only this document-root `kind` field from
/// CLI JSON output; nested report objects are not rewritten.
///
/// One envelope is intentionally NOT in this enum:
/// - `CodeClimateOutput` serializes as a bare JSON array
///   (`#[serde(transparent)]`) per the Code Climate / GitLab Code Quality
///   spec; `#[serde(tag = ...)]` cannot internally tag a non-object
///   variant and wrapping the array would break the spec. The root schema
///   carries it as a sibling `oneOf` branch alongside `FallowOutput`.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[cfg_attr(
    feature = "schema",
    schemars(title = "fallow --format json (typed root)")
)]
#[serde(tag = "kind")]
#[allow(
    dead_code,
    reason = "some variants are schema-emit only, but runtime roots serialize through this enum where practical"
)]
pub enum FallowOutput<
    Audit,
    Explain,
    Inspect,
    Trace,
    ReviewEnvelope,
    ReviewReconcile,
    CoverageSetup,
    CoverageAnalyze,
    ListBoundaries,
    Workspaces,
    Health,
    Dupes,
    CheckGrouped,
    Impact,
    ImpactCrossRepo,
    SecuritySummary,
    Security,
    SecuritySurvivors,
    SecurityBlindSpots,
    Check,
    Combined,
    AuditBrief,
    DecisionSurface,
    WalkthroughGuide,
    WalkthroughValidation,
> {
    /// `fallow audit --format json`.
    #[serde(rename = "audit")]
    Audit(Audit),
    /// `fallow explain <issue-type> --format json`.
    #[serde(rename = "explain")]
    Explain(Explain),
    /// `fallow inspect --format json`.
    #[serde(rename = "inspect_target")]
    Inspect(Inspect),
    /// `fallow trace <symbol> --format json`.
    #[serde(rename = "trace")]
    Trace(Trace),
    /// `fallow --format review-github` / `--format review-gitlab`.
    #[serde(rename = "review-envelope")]
    ReviewEnvelope(ReviewEnvelope),
    /// `fallow ci reconcile-review --format json`.
    #[serde(rename = "review-reconcile")]
    ReviewReconcile(ReviewReconcile),
    /// `fallow coverage setup --json`.
    #[serde(rename = "coverage-setup")]
    CoverageSetup(CoverageSetup),
    /// `fallow coverage analyze --format json`.
    #[serde(rename = "coverage-analyze")]
    CoverageAnalyze(CoverageAnalyze),
    /// `fallow list --boundaries --format json`.
    #[serde(rename = "list-boundaries")]
    ListBoundaries(ListBoundaries),
    /// `fallow workspaces --format json`.
    #[serde(rename = "list-workspaces")]
    Workspaces(Workspaces),
    /// `fallow health --format json`.
    #[serde(rename = "health")]
    Health(Health),
    /// `fallow dupes --format json`.
    #[serde(rename = "dupes")]
    Dupes(Dupes),
    /// `fallow dead-code --format json --group-by <mode>`.
    #[serde(rename = "dead-code-grouped")]
    CheckGrouped(CheckGrouped),
    /// `fallow impact --format json`.
    #[serde(rename = "impact")]
    Impact(Impact),
    /// `fallow impact --all --format json`.
    #[serde(rename = "impact-cross-repo")]
    ImpactCrossRepo(ImpactCrossRepo),
    /// `fallow security --summary --format json`.
    #[serde(rename = "security")]
    SecuritySummary(SecuritySummary),
    /// `fallow security --format json`.
    #[serde(rename = "security")]
    Security(Security),
    /// `fallow security survivors --format json`.
    #[serde(rename = "security-survivors")]
    SecuritySurvivors(SecuritySurvivors),
    /// `fallow security blind-spots --format json`.
    #[serde(rename = "security-blind-spots")]
    SecurityBlindSpots(SecurityBlindSpots),
    /// `fallow dead-code --format json`.
    #[serde(rename = "dead-code")]
    Check(Check),
    /// Bare `fallow --format json`.
    #[serde(rename = "combined")]
    Combined(Combined),
    /// `fallow audit --brief --format json`.
    #[serde(rename = "audit-brief")]
    AuditBrief(AuditBrief),
    /// `fallow decision-surface --format json`.
    #[serde(rename = "decision-surface")]
    DecisionSurface(DecisionSurface),
    /// `fallow review --walkthrough-guide --format json`.
    #[serde(rename = "review-walkthrough-guide")]
    WalkthroughGuide(WalkthroughGuide),
    /// `fallow review --walkthrough-file --format json`.
    #[serde(rename = "review-walkthrough-validation")]
    WalkthroughValidation(WalkthroughValidation),
}

#[cfg(test)]
mod tests {
    use fallow_types::envelope::{ElapsedMs, SchemaVersion, ToolVersion};
    use serde_json::json;

    use super::*;

    #[test]
    fn root_envelope_mode_maps_legacy_flag() {
        assert_eq!(
            RootEnvelopeMode::from_legacy(false),
            RootEnvelopeMode::Tagged
        );
        assert_eq!(
            RootEnvelopeMode::from_legacy(true),
            RootEnvelopeMode::Legacy
        );
    }

    #[test]
    fn legacy_mode_removes_only_root_kind() {
        let mut value = json!({
            "kind": "root",
            "action": {
                "kind": "suppress"
            }
        });

        remove_root_kind(&mut value);

        assert!(value.get("kind").is_none());
        assert_eq!(value["action"]["kind"], "suppress");
    }

    #[test]
    fn apply_root_kind_respects_legacy_mode() {
        let mut value = json!({});

        apply_root_kind(&mut value, "dead_code", RootEnvelopeMode::Legacy);

        assert!(value.get("kind").is_none());
    }

    #[test]
    fn apply_root_kind_sets_tagged_mode() {
        let mut value = json!({});

        apply_root_kind(&mut value, "dead_code", RootEnvelopeMode::Tagged);

        assert_eq!(value["kind"], "dead_code");
    }

    #[test]
    fn attach_telemetry_meta_sets_analysis_run_id() {
        let mut value = json!({});

        attach_telemetry_meta(&mut value, Some("run-123"));

        assert_eq!(
            value["_meta"]["telemetry"]["analysis_run_id"],
            json!("run-123")
        );
    }

    #[test]
    fn attach_telemetry_meta_preserves_non_object_roots() {
        let mut value = json!(["not", "an", "object"]);

        attach_telemetry_meta(&mut value, Some("run-123"));

        assert_eq!(value, json!(["not", "an", "object"]));
    }

    #[test]
    fn serialize_json_root_output_removes_root_kind_in_legacy_mode() {
        let value = serialize_json_root_output(
            json!({
                "kind": "combined",
                "schema_version": 1
            }),
            RootEnvelopeMode::Legacy,
        )
        .expect("root should serialize");

        assert!(value.get("kind").is_none());
        assert_eq!(value["schema_version"], 1);
    }

    #[test]
    fn serialize_named_json_output_applies_explicit_kind() {
        let value = serialize_named_json_output(
            json!({
                "schema_version": 1,
                "summary": { "total": 0 }
            }),
            "example",
            RootEnvelopeMode::Tagged,
        )
        .expect("named output should serialize");

        assert_eq!(value["kind"], "example");
        assert_eq!(value["summary"]["total"], 0);
    }

    #[test]
    fn serialize_audit_json_output_applies_audit_kind() {
        let value = serialize_audit_json_output(
            AuditOutput {
                schema_version: SchemaVersion(7),
                version: ToolVersion("1.2.3".to_string()),
                command: AuditCommand::Audit,
                verdict: "pass",
                changed_files_count: 2,
                base_ref: "origin/main".to_string(),
                base_description: Some("merge-base with origin/main".to_string()),
                head_sha: Some("abc123".to_string()),
                elapsed_ms: ElapsedMs(42),
                base_snapshot_skipped: Some(false),
                summary: json!({ "dead_code_issues": 0 }),
                attribution: json!({ "gate": "new_only" }),
                meta: None,
                dead_code: Some(json!({ "summary": { "total_issues": 0 } })),
                duplication: None::<serde_json::Value>,
                complexity: None::<serde_json::Value>,
                next_steps: Vec::new(),
            },
            RootEnvelopeMode::Tagged,
            Some("run-audit"),
        )
        .expect("audit output should serialize");

        assert_eq!(value["kind"], "audit");
        assert_eq!(value["command"], "audit");
        assert_eq!(value["dead_code"]["summary"]["total_issues"], 0);
        assert_eq!(value["_meta"]["telemetry"]["analysis_run_id"], "run-audit");
    }

    #[test]
    fn serialize_combined_json_output_applies_combined_kind() {
        let value = serialize_combined_json_output(
            CombinedOutput {
                schema_version: SchemaVersion(7),
                version: ToolVersion("1.2.3".to_string()),
                elapsed_ms: ElapsedMs(42),
                meta: None,
                check: Some(json!({ "summary": { "total_issues": 0 } })),
                dupes: None::<serde_json::Value>,
                health: None::<serde_json::Value>,
                next_steps: Vec::new(),
            },
            RootEnvelopeMode::Tagged,
            Some("run-combined"),
        )
        .expect("combined output should serialize");

        assert_eq!(value["kind"], "combined");
        assert_eq!(value["check"]["summary"]["total_issues"], 0);
        assert_eq!(
            value["_meta"]["telemetry"]["analysis_run_id"],
            "run-combined"
        );
    }
}