fallow-output 3.21.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
//! Feature flag output contracts.

use std::path::Path;
use std::time::Duration;

use fallow_types::envelope::{ElapsedMs, SchemaVersion, TelemetryMeta, ToolVersion};
use fallow_types::results::{FeatureFlag, FlagConfidence, FlagKind};
use serde::Serialize;

use crate::root_envelopes::{RootEnvelopeMode, attach_telemetry_meta, serialize_named_json_output};

/// Current schema version for feature-flag JSON output.
pub const FEATURE_FLAGS_SCHEMA_VERSION: u32 = 8;

/// Schema projection for the feature-flags envelope's exact version.
#[cfg(feature = "schema")]
#[allow(dead_code, reason = "schema-only type used by the field projection")]
#[derive(schemars::JsonSchema)]
#[schemars(extend("const" = FEATURE_FLAGS_SCHEMA_VERSION))]
struct FeatureFlagsSchemaVersion(u32);

/// Inputs for building `fallow flags --format json`.
pub struct FeatureFlagsOutputInput<'a> {
    /// Flags output schema version to report.
    pub schema_version: u32,
    /// Fallow CLI version to report.
    pub version: String,
    /// Wall-clock analysis duration; serialized as whole milliseconds.
    pub elapsed: Duration,
    /// Detected flags from the engine.
    pub flags: &'a [FeatureFlag],
    /// Analysis root paths are relativized against.
    pub root: &'a Path,
    /// `_meta` block to attach when `--explain` was passed.
    pub meta: Option<FeatureFlagsMeta>,
}

/// Envelope emitted by `fallow flags --format json`.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "schema", schemars(title = "fallow flags --format json"))]
pub struct FeatureFlagsOutput {
    /// Flags output schema version.
    #[cfg_attr(feature = "schema", schemars(with = "FeatureFlagsSchemaVersion"))]
    pub schema_version: SchemaVersion,
    /// Fallow CLI version that produced this output.
    pub version: ToolVersion,
    /// Wall-clock analysis duration in milliseconds.
    pub elapsed_ms: ElapsedMs,
    /// Detected feature-flag findings.
    pub feature_flags: Vec<FeatureFlagFinding>,
    /// Number of entries in `feature_flags`.
    pub total_flags: usize,
    /// `_meta` block; see [`FeatureFlagsMeta`].
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<FeatureFlagsMeta>,
}

/// One feature flag finding in JSON output.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct FeatureFlagFinding {
    /// File path relative to the analysed root.
    pub path: String,
    /// Detected flag identifier, e.g. the env var or SDK key name.
    pub flag_name: String,
    /// Detection pattern the flag matched.
    pub kind: FeatureFlagKind,
    /// How confident the detector is that this is a real feature flag.
    pub confidence: FeatureFlagConfidence,
    /// 1-based line of the flag usage.
    pub line: u32,
    /// 1-based column of the flag usage.
    pub col: u32,
    /// Suggested follow-up actions (investigate / suppress).
    pub actions: Vec<FeatureFlagAction>,
    /// Flag SDK the call belongs to, for SDK-call findings.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sdk_name: Option<String>,
    /// Overlap with dead-code findings when the flag guards unused exports.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dead_code_overlap: Option<FeatureFlagDeadCodeOverlap>,
}

/// Feature flag kind values emitted in JSON.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum FeatureFlagKind {
    /// Environment-variable read used as a toggle.
    EnvironmentVariable,
    /// Feature-flag SDK evaluation call.
    SdkCall,
    /// Flag key in a configuration object literal.
    ConfigObject,
}

/// Feature flag confidence values emitted in JSON.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "lowercase")]
pub enum FeatureFlagConfidence {
    /// Strong flag signal, e.g. a known SDK call.
    High,
    /// Plausible flag signal with some ambiguity.
    Medium,
    /// Weak signal; likely needs human confirmation.
    Low,
}

/// Per-finding action emitted for feature flag findings.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct FeatureFlagAction {
    /// Action discriminator, serialized as `type`.
    #[serde(rename = "type")]
    pub kind: FeatureFlagActionType,
    /// Whether `fallow fix` can apply the action automatically.
    pub auto_fixable: bool,
    /// Human-readable action description.
    pub description: String,
    /// Suppression comment to insert, for suppress actions.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub comment: Option<String>,
}

/// Feature flag action discriminants.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum FeatureFlagActionType {
    /// Check whether the flag is still needed.
    InvestigateFlag,
    /// Suppress the finding with a `fallow-ignore` line comment.
    SuppressLine,
}

/// Dead-code overlap block attached when a flag guards unused exports.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct FeatureFlagDeadCodeOverlap {
    /// Lines inside the flag-guarded region.
    pub guarded_lines: u32,
    /// Number of unused exports the flag guards.
    pub dead_export_count: usize,
    /// Names of the unused exports the flag guards.
    pub dead_exports: Vec<String>,
}

/// Optional `_meta` block for [`FeatureFlagsOutput`]. Both fields are optional
/// because the two contributors are independent: `feature_flags` details are
/// present only with `--explain`, and `telemetry` is injected post-pass by
/// [`attach_telemetry_meta`] whenever an analysis run id is available (which is
/// the default path). Mirrors `Meta` / `CombinedMeta`, which also model
/// `telemetry` as an optional, never-required property.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct FeatureFlagsMeta {
    /// Feature-flag detection explanations, emitted only with `--explain`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub feature_flags: Option<FeatureFlagsMetaDetails>,
    /// Local telemetry correlation metadata for agent follow-up runs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub telemetry: Option<TelemetryMeta>,
}

/// Feature flag explanatory metadata.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct FeatureFlagsMetaDetails {
    /// What the flags command reports.
    pub description: &'static str,
    /// Explanation of each `kind` value.
    pub kinds: FeatureFlagsKindMeta,
    /// Explanation of each `confidence` value.
    pub confidence: FeatureFlagsConfidenceMeta,
    /// Public documentation URL for the flags command.
    pub docs: &'static str,
}

/// Feature flag kind explanations.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct FeatureFlagsKindMeta {
    /// Explanation of the `environment_variable` kind.
    pub environment_variable: &'static str,
    /// Explanation of the `sdk_call` kind.
    pub sdk_call: &'static str,
    /// Explanation of the `config_object` kind.
    pub config_object: &'static str,
}

/// Feature flag confidence explanations.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct FeatureFlagsConfidenceMeta {
    /// Explanation of the `high` confidence level.
    pub high: &'static str,
    /// Explanation of the `medium` confidence level.
    pub medium: &'static str,
    /// Explanation of the `low` confidence level.
    pub low: &'static str,
}

/// Build the typed feature flags output envelope.
#[must_use]
pub fn build_feature_flags_output(input: FeatureFlagsOutputInput<'_>) -> FeatureFlagsOutput {
    let feature_flags = input
        .flags
        .iter()
        .map(|flag| feature_flag_finding(flag, input.root))
        .collect();
    FeatureFlagsOutput {
        schema_version: SchemaVersion(input.schema_version),
        version: ToolVersion(input.version),
        elapsed_ms: ElapsedMs(input.elapsed.as_millis() as u64),
        feature_flags,
        total_flags: input.flags.len(),
        meta: input.meta,
    }
}

/// Serialize `fallow flags --format json`.
///
/// # Errors
///
/// Returns a serde error when the feature flags output cannot be converted to
/// JSON.
pub fn serialize_feature_flags_json_output(
    output: FeatureFlagsOutput,
    mode: RootEnvelopeMode,
    analysis_run_id: Option<&str>,
) -> Result<serde_json::Value, serde_json::Error> {
    let mut value = serialize_named_json_output(output, "feature-flags", mode)?;
    attach_telemetry_meta(&mut value, analysis_run_id);
    Ok(value)
}

/// Metadata emitted when `fallow flags --explain --format json` is requested.
#[must_use]
pub const fn feature_flags_meta() -> FeatureFlagsMeta {
    FeatureFlagsMeta {
        telemetry: None,
        feature_flags: Some(FeatureFlagsMetaDetails {
            description: "Feature flag patterns detected via AST analysis",
            kinds: FeatureFlagsKindMeta {
                environment_variable: "process.env.FEATURE_* pattern (high confidence)",
                sdk_call: "Feature flag SDK function call (high confidence)",
                config_object: "Config object property access matching flag keywords (low confidence, heuristic)",
            },
            confidence: FeatureFlagsConfidenceMeta {
                high: "Unambiguous pattern match (env vars, direct SDK calls)",
                medium: "Pattern match with some ambiguity",
                low: "Heuristic match (config objects), may produce false positives",
            },
            docs: "https://docs.fallow.tools/cli/flags",
        }),
    }
}

fn feature_flag_finding(flag: &FeatureFlag, root: &Path) -> FeatureFlagFinding {
    let path = flag
        .path
        .strip_prefix(root)
        .unwrap_or(&flag.path)
        .to_string_lossy()
        .replace('\\', "/");
    FeatureFlagFinding {
        path,
        flag_name: flag.flag_name.clone(),
        kind: feature_flag_kind(flag.kind),
        confidence: feature_flag_confidence(flag.confidence),
        line: flag.line,
        col: flag.col,
        actions: feature_flag_actions(&flag.flag_name),
        sdk_name: flag.sdk_name.clone(),
        dead_code_overlap: feature_flag_dead_code_overlap(flag),
    }
}

const fn feature_flag_kind(kind: FlagKind) -> FeatureFlagKind {
    match kind {
        FlagKind::EnvironmentVariable => FeatureFlagKind::EnvironmentVariable,
        FlagKind::SdkCall => FeatureFlagKind::SdkCall,
        FlagKind::ConfigObject => FeatureFlagKind::ConfigObject,
    }
}

const fn feature_flag_confidence(confidence: FlagConfidence) -> FeatureFlagConfidence {
    match confidence {
        FlagConfidence::High => FeatureFlagConfidence::High,
        FlagConfidence::Medium => FeatureFlagConfidence::Medium,
        FlagConfidence::Low => FeatureFlagConfidence::Low,
    }
}

fn feature_flag_actions(flag_name: &str) -> Vec<FeatureFlagAction> {
    vec![
        FeatureFlagAction {
            kind: FeatureFlagActionType::InvestigateFlag,
            auto_fixable: false,
            description: format!("Verify whether feature flag '{flag_name}' is still active"),
            comment: None,
        },
        FeatureFlagAction {
            kind: FeatureFlagActionType::SuppressLine,
            auto_fixable: false,
            description: "Suppress with an inline comment".to_string(),
            comment: Some("// fallow-ignore-next-line feature-flag".to_string()),
        },
    ]
}

fn feature_flag_dead_code_overlap(flag: &FeatureFlag) -> Option<FeatureFlagDeadCodeOverlap> {
    if flag.guarded_dead_exports.is_empty() {
        return None;
    }
    let guarded_lines = flag
        .guard_line_start
        .and_then(|start| flag.guard_line_end.map(|end| end.saturating_sub(start) + 1))
        .unwrap_or(0);
    Some(FeatureFlagDeadCodeOverlap {
        guarded_lines,
        dead_export_count: flag.guarded_dead_exports.len(),
        dead_exports: flag.guarded_dead_exports.clone(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    fn flag() -> FeatureFlag {
        FeatureFlag {
            path: PathBuf::from("/repo/src/app.ts"),
            flag_name: "FEATURE_CHECKOUT".to_string(),
            kind: FlagKind::EnvironmentVariable,
            confidence: FlagConfidence::High,
            line: 10,
            col: 4,
            guard_span_start: None,
            guard_span_end: None,
            sdk_name: None,
            guard_line_start: Some(10),
            guard_line_end: Some(12),
            guarded_dead_exports: vec!["legacyCheckout".to_string()],
        }
    }

    #[test]
    fn feature_flags_json_output_uses_output_owned_root_contract() {
        let output = build_feature_flags_output(FeatureFlagsOutputInput {
            schema_version: 7,
            version: "0.0.0".to_string(),
            elapsed: Duration::from_millis(4),
            flags: &[flag()],
            root: Path::new("/repo"),
            meta: Some(feature_flags_meta()),
        });

        let value = serialize_feature_flags_json_output(
            output,
            RootEnvelopeMode::Tagged,
            Some("run-flags"),
        )
        .expect("feature flags output should serialize");

        assert_eq!(value["kind"], "feature-flags");
        assert_eq!(value["feature_flags"][0]["path"], "src/app.ts");
        assert_eq!(
            value["feature_flags"][0]["dead_code_overlap"]["guarded_lines"],
            3
        );
        assert_eq!(
            value["_meta"]["feature_flags"]["docs"],
            "https://docs.fallow.tools/cli/flags"
        );
        assert_eq!(value["_meta"]["telemetry"]["analysis_run_id"], "run-flags");
    }

    #[test]
    fn feature_flags_json_output_without_explain_emits_telemetry_only_meta() {
        // The default path (no --explain) leaves `meta` as None, so the only
        // `_meta` contributor is the post-pass telemetry injection. The typed
        // `FeatureFlagsMeta` must model this telemetry-only shape (both fields
        // optional) so the emitted document conforms to the published schema.
        let output = build_feature_flags_output(FeatureFlagsOutputInput {
            schema_version: 7,
            version: "0.0.0".to_string(),
            elapsed: Duration::from_millis(4),
            flags: &[flag()],
            root: Path::new("/repo"),
            meta: None,
        });

        let value = serialize_feature_flags_json_output(
            output,
            RootEnvelopeMode::Tagged,
            Some("run-flags"),
        )
        .expect("feature flags output should serialize");

        assert_eq!(value["_meta"]["telemetry"]["analysis_run_id"], "run-flags");
        assert!(
            value["_meta"].get("feature_flags").is_none(),
            "feature_flags details are absent without --explain"
        );
    }
}