Skip to main content

fallow_output/
feature_flags.rs

1//! Feature flag output contracts.
2
3use std::path::Path;
4use std::time::Duration;
5
6use fallow_types::envelope::{ElapsedMs, SchemaVersion, TelemetryMeta, ToolVersion};
7use fallow_types::flag_retirement::FlagRetirementReport;
8use fallow_types::results::{FeatureFlag, FlagConfidence, FlagKind};
9use fallow_types::workspace::WorkspaceDiagnostic;
10use serde::Serialize;
11
12use crate::root_envelopes::{attach_telemetry_meta, serialize_named_json_output};
13
14/// Current schema version for feature-flag JSON output.
15///
16/// Unmoved by the additive `workspace_diagnostics[]` field: it carries
17/// `skip_serializing_if`, so a run that records no diagnostic emits the same
18/// bytes as before. This is the rule `docs/backwards-compatibility.md` states
19/// for additive optional fields, and the precedent the bare combined envelope
20/// set when it gained the same array.
21pub const FEATURE_FLAGS_SCHEMA_VERSION: u32 = 8;
22
23/// Schema projection for the feature-flags envelope's exact version.
24#[cfg(feature = "schema")]
25#[expect(dead_code, reason = "schema-only type used by the field projection")]
26#[derive(schemars::JsonSchema)]
27#[schemars(extend("const" = FEATURE_FLAGS_SCHEMA_VERSION))]
28struct FeatureFlagsSchemaVersion(u32);
29
30/// Inputs for building `fallow flags --format json`.
31pub struct FeatureFlagsOutputInput<'a> {
32    /// Flags output schema version to report.
33    pub schema_version: u32,
34    /// Fallow CLI version to report.
35    pub version: String,
36    /// Wall-clock analysis duration; serialized as whole milliseconds.
37    pub elapsed: Duration,
38    /// Detected flags from the engine.
39    pub flags: &'a [FeatureFlag],
40    /// Analysis root paths are relativized against.
41    pub root: &'a Path,
42    /// Workspace- and source-discovery diagnostics the run recorded. Passed
43    /// absolute; the builder relativizes them against `root`.
44    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
45    /// What became of the narrowing requests the run received, or `None` when
46    /// it received none.
47    pub request_outcomes: Option<crate::RequestOutcomes>,
48    /// `_meta` block to attach when `--explain` was passed.
49    pub meta: Option<FeatureFlagsMeta>,
50    /// Retirement report, present only with `--retirement`.
51    pub retirement: Option<FlagRetirementReport>,
52}
53
54/// Envelope emitted by `fallow flags --format json`.
55#[derive(Debug, Clone, Serialize)]
56#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
57#[cfg_attr(feature = "schema", schemars(title = "fallow flags --format json"))]
58pub struct FeatureFlagsOutput {
59    /// Flags output schema version.
60    #[cfg_attr(feature = "schema", schemars(with = "FeatureFlagsSchemaVersion"))]
61    pub schema_version: SchemaVersion,
62    /// Fallow CLI version that produced this output.
63    pub version: ToolVersion,
64    /// Wall-clock analysis duration in milliseconds.
65    pub elapsed_ms: ElapsedMs,
66    /// What the run was asked to narrow and whether it did. See
67    /// [`crate::RequestOutcomes`] for the full contract.
68    ///
69    /// `fallow flags` accepts `--changed-since`, and an unresolvable ref widens
70    /// the scan to the whole project rather than failing the run. Until this
71    /// member existed the only account of that was a stderr line, which `--quiet`
72    /// removes, so a flag inventory read as scoped to the change could silently
73    /// be the whole project's (issue #2734).
74    ///
75    /// The command applies no diff filter, so the object carries the
76    /// `changed-since` entry only. Omitted when the run was asked for nothing,
77    /// which keeps a scan that passed no narrowing flag byte-identical and moves
78    /// no `schema_version`.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub request_outcomes: Option<crate::RequestOutcomes>,
81    /// Detected feature-flag findings.
82    pub feature_flags: Vec<FeatureFlagFinding>,
83    /// Number of entries in `feature_flags`.
84    pub total_flags: usize,
85    /// Workspace-discovery and source-discovery diagnostics for the run. See
86    /// `CheckOutput::workspace_diagnostics` for the full contract.
87    ///
88    /// A flags run walks and parses the project like every other analysis, so
89    /// it records the same discovery kinds: a `skipped-large-file`,
90    /// `skipped-minified-file`, or `source-read-failure` file was never
91    /// scanned for flags, a `source-parse-degraded` file was scanned from a
92    /// partial module, and a `source-nesting-too-deep` file was not scanned. Each is a reason a flag can be missing from
93    /// `feature_flags[]`, which is exactly what a consumer reading a
94    /// zero-result run needs to know. The analysis-stage kinds appear here
95    /// too: the scan correlates flags with dead exports, so it runs the
96    /// dead-code analyze pass that records them.
97    ///
98    /// Omitted when empty, so a project with no discovery noise sees no
99    /// change.
100    #[serde(default, skip_serializing_if = "Vec::is_empty")]
101    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
102    /// One row per flag with the reasons the flag can be retired.
103    ///
104    /// Present only with `--retirement`. Without that option the key is
105    /// omitted, so the envelope stays byte-identical and `schema_version`
106    /// does not move. The per-site `feature_flags[]` array is the same with
107    /// and without the option.
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub retirement: Option<FlagRetirementReport>,
110    /// `_meta` block; see [`FeatureFlagsMeta`].
111    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
112    pub meta: Option<FeatureFlagsMeta>,
113}
114
115/// One feature flag finding in JSON output.
116#[derive(Debug, Clone, Serialize)]
117#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
118pub struct FeatureFlagFinding {
119    /// File path relative to the analysed root.
120    pub path: String,
121    /// Detected flag identifier, e.g. the env var or SDK key name.
122    pub flag_name: String,
123    /// Detection pattern the flag matched.
124    pub kind: FeatureFlagKind,
125    /// How confident the detector is that this is a real feature flag.
126    pub confidence: FeatureFlagConfidence,
127    /// 1-based line of the flag usage.
128    pub line: u32,
129    /// 1-based column of the flag usage.
130    pub col: u32,
131    /// Suggested follow-up actions (investigate / suppress).
132    pub actions: Vec<FeatureFlagAction>,
133    /// Flag SDK the call belongs to, for SDK-call findings. Absent for a
134    /// `medium` confidence call, because no flag import confirms the SDK.
135    #[serde(default, skip_serializing_if = "Option::is_none")]
136    pub sdk_name: Option<String>,
137    /// Overlap with dead-code findings when the flag guards unused exports.
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub dead_code_overlap: Option<FeatureFlagDeadCodeOverlap>,
140}
141
142/// Feature flag kind values emitted in JSON.
143#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
144#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
145#[serde(rename_all = "snake_case")]
146pub enum FeatureFlagKind {
147    /// Environment-variable read used as a toggle.
148    EnvironmentVariable,
149    /// Feature-flag SDK evaluation call.
150    SdkCall,
151    /// Flag key in a configuration object literal.
152    ConfigObject,
153}
154
155/// Feature flag confidence values emitted in JSON.
156#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
157#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
158#[serde(rename_all = "lowercase")]
159pub enum FeatureFlagConfidence {
160    /// Strong flag signal, e.g. a known SDK call.
161    High,
162    /// Plausible flag signal with some ambiguity, e.g. a generic SDK name
163    /// such as `isEnabled` in a file that imports no flag SDK or flag module.
164    Medium,
165    /// Weak signal; likely needs human confirmation.
166    Low,
167}
168
169/// Per-finding action emitted for feature flag findings.
170#[derive(Debug, Clone, Serialize)]
171#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
172pub struct FeatureFlagAction {
173    /// Action discriminator, serialized as `type`.
174    #[serde(rename = "type")]
175    pub kind: FeatureFlagActionType,
176    /// Whether `fallow fix` can apply the action automatically.
177    pub auto_fixable: bool,
178    /// Human-readable action description.
179    pub description: String,
180    /// Suppression comment to insert, for suppress actions.
181    #[serde(default, skip_serializing_if = "Option::is_none")]
182    pub comment: Option<String>,
183}
184
185/// Feature flag action discriminants.
186#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
187#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
188#[serde(rename_all = "kebab-case")]
189pub enum FeatureFlagActionType {
190    /// Check whether the flag is still needed.
191    InvestigateFlag,
192    /// Suppress the finding with a `fallow-ignore` line comment.
193    SuppressLine,
194}
195
196/// Dead-code overlap block attached when a flag guards unused exports.
197#[derive(Debug, Clone, Serialize)]
198#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
199pub struct FeatureFlagDeadCodeOverlap {
200    /// Lines inside the flag-guarded region.
201    pub guarded_lines: u32,
202    /// Number of unused exports the flag guards.
203    pub dead_export_count: usize,
204    /// Names of the unused exports the flag guards.
205    pub dead_exports: Vec<String>,
206}
207
208/// Optional `_meta` block for [`FeatureFlagsOutput`]. Both fields are optional
209/// because the two contributors are independent: `feature_flags` details are
210/// present only with `--explain`, and `telemetry` is injected post-pass by
211/// [`attach_telemetry_meta`] whenever an analysis run id is available (which is
212/// the default path). Mirrors `Meta` / `CombinedMeta`, which also model
213/// `telemetry` as an optional, never-required property.
214#[derive(Debug, Clone, Serialize)]
215#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
216pub struct FeatureFlagsMeta {
217    /// Feature-flag detection explanations, emitted only with `--explain`.
218    #[serde(default, skip_serializing_if = "Option::is_none")]
219    pub feature_flags: Option<FeatureFlagsMetaDetails>,
220    /// Local telemetry correlation metadata for agent follow-up runs.
221    #[serde(default, skip_serializing_if = "Option::is_none")]
222    pub telemetry: Option<TelemetryMeta>,
223}
224
225/// Feature flag explanatory metadata.
226#[derive(Debug, Clone, Serialize)]
227#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
228pub struct FeatureFlagsMetaDetails {
229    /// What the flags command reports.
230    pub description: &'static str,
231    /// Explanation of each `kind` value.
232    pub kinds: FeatureFlagsKindMeta,
233    /// Explanation of each `confidence` value.
234    pub confidence: FeatureFlagsConfidenceMeta,
235    /// Public documentation URL for the flags command.
236    pub docs: &'static str,
237}
238
239/// Feature flag kind explanations.
240#[derive(Debug, Clone, Serialize)]
241#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
242pub struct FeatureFlagsKindMeta {
243    /// Explanation of the `environment_variable` kind.
244    pub environment_variable: &'static str,
245    /// Explanation of the `sdk_call` kind.
246    pub sdk_call: &'static str,
247    /// Explanation of the `config_object` kind.
248    pub config_object: &'static str,
249}
250
251/// Feature flag confidence explanations.
252#[derive(Debug, Clone, Serialize)]
253#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
254pub struct FeatureFlagsConfidenceMeta {
255    /// Explanation of the `high` confidence level.
256    pub high: &'static str,
257    /// Explanation of the `medium` confidence level.
258    pub medium: &'static str,
259    /// Explanation of the `low` confidence level.
260    pub low: &'static str,
261}
262
263/// Build the typed feature flags output envelope.
264#[must_use]
265pub fn build_feature_flags_output(input: FeatureFlagsOutputInput<'_>) -> FeatureFlagsOutput {
266    let feature_flags = input
267        .flags
268        .iter()
269        .map(|flag| feature_flag_finding(flag, input.root))
270        .collect();
271    // This envelope has no post-serialisation root-prefix strip, so the
272    // diagnostics are relativized here or they reach the wire as host paths.
273    let root = input.root;
274    let workspace_diagnostics = input
275        .workspace_diagnostics
276        .into_iter()
277        .map(|diagnostic| diagnostic.into_root_relative(root))
278        .collect();
279    FeatureFlagsOutput {
280        schema_version: SchemaVersion(input.schema_version),
281        version: ToolVersion(input.version),
282        elapsed_ms: ElapsedMs(input.elapsed.as_millis() as u64),
283        request_outcomes: input.request_outcomes,
284        feature_flags,
285        total_flags: input.flags.len(),
286        workspace_diagnostics,
287        retirement: input.retirement,
288        meta: input.meta,
289    }
290}
291
292/// Serialize `fallow flags --format json`.
293///
294/// # Errors
295///
296/// Returns a serde error when the feature flags output cannot be converted to
297/// JSON.
298pub fn serialize_feature_flags_json_output(
299    output: FeatureFlagsOutput,
300    analysis_run_id: Option<&str>,
301) -> Result<serde_json::Value, serde_json::Error> {
302    let mut value = serialize_named_json_output(output, "feature-flags")?;
303    attach_telemetry_meta(&mut value, analysis_run_id);
304    Ok(value)
305}
306
307/// Metadata emitted when `fallow flags --explain --format json` is requested.
308#[must_use]
309pub const fn feature_flags_meta() -> FeatureFlagsMeta {
310    FeatureFlagsMeta {
311        telemetry: None,
312        feature_flags: Some(FeatureFlagsMetaDetails {
313            description: "Feature flag patterns detected via AST analysis",
314            kinds: FeatureFlagsKindMeta {
315                environment_variable: "process.env.FEATURE_* pattern (high confidence)",
316                sdk_call: "Feature flag SDK function call (high confidence, or medium for a generic SDK name without a flag import)",
317                config_object: "Config object property access matching flag keywords (low confidence, heuristic)",
318            },
319            confidence: FeatureFlagsConfidenceMeta {
320                high: "Unambiguous pattern match (env vars, specific SDK calls, generic SDK calls in a file that imports a flag SDK or flag module)",
321                medium: "Pattern match with some ambiguity: a generic SDK name such as isEnabled, getValue or useFeature in a file that imports no flag SDK or flag module",
322                low: "Heuristic match (config objects), may produce false positives",
323            },
324            docs: "https://fallow.tools/docs/cli/flags/",
325        }),
326    }
327}
328
329/// The SDK name that the output of a flag site shows.
330///
331/// A generic SDK method such as `isEnabled` in a file that imports no flag
332/// SDK has `Medium` confidence. Its SDK name is only the default provider of
333/// the method name, so the output names no SDK for it. The engine keeps the
334/// name, because the vendor-state match uses it.
335#[must_use]
336pub fn reported_sdk_name(flag: &FeatureFlag) -> Option<&str> {
337    let unconfirmed = flag.kind == FlagKind::SdkCall && flag.confidence == FlagConfidence::Medium;
338    if unconfirmed {
339        return None;
340    }
341    flag.sdk_name.as_deref()
342}
343
344fn feature_flag_finding(flag: &FeatureFlag, root: &Path) -> FeatureFlagFinding {
345    let path = flag
346        .path
347        .strip_prefix(root)
348        .unwrap_or(&flag.path)
349        .to_string_lossy()
350        .replace('\\', "/");
351    FeatureFlagFinding {
352        path,
353        flag_name: flag.flag_name.clone(),
354        kind: feature_flag_kind(flag.kind),
355        confidence: feature_flag_confidence(flag.confidence),
356        line: flag.line,
357        col: flag.col,
358        actions: feature_flag_actions(&flag.flag_name),
359        sdk_name: reported_sdk_name(flag).map(str::to_string),
360        dead_code_overlap: feature_flag_dead_code_overlap(flag),
361    }
362}
363
364const fn feature_flag_kind(kind: FlagKind) -> FeatureFlagKind {
365    match kind {
366        FlagKind::EnvironmentVariable => FeatureFlagKind::EnvironmentVariable,
367        FlagKind::SdkCall => FeatureFlagKind::SdkCall,
368        FlagKind::ConfigObject => FeatureFlagKind::ConfigObject,
369    }
370}
371
372const fn feature_flag_confidence(confidence: FlagConfidence) -> FeatureFlagConfidence {
373    match confidence {
374        FlagConfidence::High => FeatureFlagConfidence::High,
375        FlagConfidence::Medium => FeatureFlagConfidence::Medium,
376        FlagConfidence::Low => FeatureFlagConfidence::Low,
377    }
378}
379
380fn feature_flag_actions(flag_name: &str) -> Vec<FeatureFlagAction> {
381    vec![
382        FeatureFlagAction {
383            kind: FeatureFlagActionType::InvestigateFlag,
384            auto_fixable: false,
385            description: format!("Verify whether feature flag '{flag_name}' is still active"),
386            comment: None,
387        },
388        FeatureFlagAction {
389            kind: FeatureFlagActionType::SuppressLine,
390            auto_fixable: false,
391            description: "Suppress with an inline comment".to_string(),
392            comment: Some("// fallow-ignore-next-line feature-flag".to_string()),
393        },
394    ]
395}
396
397fn feature_flag_dead_code_overlap(flag: &FeatureFlag) -> Option<FeatureFlagDeadCodeOverlap> {
398    if flag.guarded_dead_exports.is_empty() {
399        return None;
400    }
401    let guarded_lines = flag
402        .guard_line_start
403        .and_then(|start| flag.guard_line_end.map(|end| end.saturating_sub(start) + 1))
404        .unwrap_or(0);
405    Some(FeatureFlagDeadCodeOverlap {
406        guarded_lines,
407        dead_export_count: flag.guarded_dead_exports.len(),
408        dead_exports: flag.guarded_dead_exports.clone(),
409    })
410}
411
412#[cfg(test)]
413mod tests {
414    use super::*;
415    use std::path::PathBuf;
416
417    fn flag() -> FeatureFlag {
418        FeatureFlag {
419            path: PathBuf::from("/repo/src/app.ts"),
420            flag_name: "FEATURE_CHECKOUT".to_string(),
421            kind: FlagKind::EnvironmentVariable,
422            confidence: FlagConfidence::High,
423            line: 10,
424            col: 4,
425            guard_span_start: None,
426            guard_span_end: None,
427            sdk_name: None,
428            guard_line_start: Some(10),
429            guard_line_end: Some(12),
430            guarded_dead_exports: vec!["legacyCheckout".to_string()],
431        }
432    }
433
434    #[test]
435    fn feature_flags_json_output_uses_output_owned_root_contract() {
436        let output = build_feature_flags_output(FeatureFlagsOutputInput {
437            schema_version: 7,
438            version: "0.0.0".to_string(),
439            elapsed: Duration::from_millis(4),
440            flags: &[flag()],
441            root: Path::new("/repo"),
442            workspace_diagnostics: Vec::new(),
443            request_outcomes: None,
444            meta: Some(feature_flags_meta()),
445            retirement: None,
446        });
447
448        let value = serialize_feature_flags_json_output(output, Some("run-flags"))
449            .expect("feature flags output should serialize");
450
451        assert_eq!(value["kind"], "feature-flags");
452        assert_eq!(value["feature_flags"][0]["path"], "src/app.ts");
453        assert_eq!(
454            value["feature_flags"][0]["dead_code_overlap"]["guarded_lines"],
455            3
456        );
457        assert_eq!(
458            value["_meta"]["feature_flags"]["docs"],
459            "https://fallow.tools/docs/cli/flags/"
460        );
461        assert_eq!(value["_meta"]["telemetry"]["analysis_run_id"], "run-flags");
462    }
463
464    #[test]
465    fn feature_flags_json_output_without_explain_emits_telemetry_only_meta() {
466        // The default path (no --explain) leaves `meta` as None, so the only
467        // `_meta` contributor is the post-pass telemetry injection. The typed
468        // `FeatureFlagsMeta` must model this telemetry-only shape (both fields
469        // optional) so the emitted document conforms to the published schema.
470        let output = build_feature_flags_output(FeatureFlagsOutputInput {
471            schema_version: 7,
472            version: "0.0.0".to_string(),
473            elapsed: Duration::from_millis(4),
474            flags: &[flag()],
475            root: Path::new("/repo"),
476            workspace_diagnostics: Vec::new(),
477            request_outcomes: None,
478            meta: None,
479            retirement: None,
480        });
481
482        let value = serialize_feature_flags_json_output(output, Some("run-flags"))
483            .expect("feature flags output should serialize");
484
485        assert_eq!(value["_meta"]["telemetry"]["analysis_run_id"], "run-flags");
486        assert!(
487            value["_meta"].get("feature_flags").is_none(),
488            "feature_flags details are absent without --explain"
489        );
490    }
491
492    #[test]
493    fn recorded_diagnostics_reach_the_flags_envelope_root_relative() {
494        // A flags run that skipped a file scanned it for nothing. Without this
495        // array the skip was unreachable from both channels on this command:
496        // stderr no longer carries every kind, and the envelope had no key.
497        let output = build_feature_flags_output(FeatureFlagsOutputInput {
498            schema_version: FEATURE_FLAGS_SCHEMA_VERSION,
499            version: "0.0.0".to_string(),
500            elapsed: Duration::from_millis(4),
501            flags: &[flag()],
502            root: Path::new("/repo"),
503            workspace_diagnostics: vec![WorkspaceDiagnostic::new(
504                Path::new("/repo"),
505                PathBuf::from("/repo/src/generated.ts"),
506                fallow_types::workspace::WorkspaceDiagnosticKind::SkippedLargeFile {
507                    size_bytes: 9_000_000,
508                },
509            )],
510            request_outcomes: None,
511            meta: None,
512            retirement: None,
513        });
514
515        let value = serialize_feature_flags_json_output(output, None)
516            .expect("feature flags output should serialize");
517
518        assert_eq!(
519            value["workspace_diagnostics"][0]["path"], "src/generated.ts",
520            "the envelope has no post-serialisation strip, so the builder must relativize"
521        );
522        assert_eq!(
523            value["workspace_diagnostics"][0]["kind"], "skipped-large-file",
524            "the typed kind reaches the wire, envelope was {value}"
525        );
526    }
527
528    #[test]
529    fn a_clean_run_omits_the_diagnostics_key_entirely() {
530        let output = build_feature_flags_output(FeatureFlagsOutputInput {
531            schema_version: FEATURE_FLAGS_SCHEMA_VERSION,
532            version: "0.0.0".to_string(),
533            elapsed: Duration::from_millis(4),
534            flags: &[flag()],
535            root: Path::new("/repo"),
536            workspace_diagnostics: Vec::new(),
537            request_outcomes: None,
538            meta: None,
539            retirement: None,
540        });
541
542        let value = serialize_feature_flags_json_output(output, None)
543            .expect("feature flags output should serialize");
544
545        assert!(
546            value.get("workspace_diagnostics").is_none(),
547            "an empty array is omitted so a quiet project sees no wire change"
548        );
549    }
550
551    #[test]
552    fn explain_meta_names_the_medium_case_of_sdk_calls() {
553        let meta = feature_flags_meta()
554            .feature_flags
555            .expect("flags meta has details");
556        assert!(
557            !meta.kinds.sdk_call.contains("(high confidence)"),
558            "an sdk_call can be medium, so the kind must not claim high only: {}",
559            meta.kinds.sdk_call
560        );
561        assert!(
562            meta.confidence.medium.contains("isEnabled"),
563            "medium must name the generic SDK case: {}",
564            meta.confidence.medium
565        );
566    }
567}