1use 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
14pub const FEATURE_FLAGS_SCHEMA_VERSION: u32 = 8;
22
23#[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
30pub struct FeatureFlagsOutputInput<'a> {
32 pub schema_version: u32,
34 pub version: String,
36 pub elapsed: Duration,
38 pub flags: &'a [FeatureFlag],
40 pub root: &'a Path,
42 pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
45 pub request_outcomes: Option<crate::RequestOutcomes>,
48 pub meta: Option<FeatureFlagsMeta>,
50 pub retirement: Option<FlagRetirementReport>,
52}
53
54#[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 #[cfg_attr(feature = "schema", schemars(with = "FeatureFlagsSchemaVersion"))]
61 pub schema_version: SchemaVersion,
62 pub version: ToolVersion,
64 pub elapsed_ms: ElapsedMs,
66 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub request_outcomes: Option<crate::RequestOutcomes>,
81 pub feature_flags: Vec<FeatureFlagFinding>,
83 pub total_flags: usize,
85 #[serde(default, skip_serializing_if = "Vec::is_empty")]
101 pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
102 #[serde(default, skip_serializing_if = "Option::is_none")]
109 pub retirement: Option<FlagRetirementReport>,
110 #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
112 pub meta: Option<FeatureFlagsMeta>,
113}
114
115#[derive(Debug, Clone, Serialize)]
117#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
118pub struct FeatureFlagFinding {
119 pub path: String,
121 pub flag_name: String,
123 pub kind: FeatureFlagKind,
125 pub confidence: FeatureFlagConfidence,
127 pub line: u32,
129 pub col: u32,
131 pub actions: Vec<FeatureFlagAction>,
133 #[serde(default, skip_serializing_if = "Option::is_none")]
136 pub sdk_name: Option<String>,
137 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub dead_code_overlap: Option<FeatureFlagDeadCodeOverlap>,
140}
141
142#[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 EnvironmentVariable,
149 SdkCall,
151 ConfigObject,
153}
154
155#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
157#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
158#[serde(rename_all = "lowercase")]
159pub enum FeatureFlagConfidence {
160 High,
162 Medium,
165 Low,
167}
168
169#[derive(Debug, Clone, Serialize)]
171#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
172pub struct FeatureFlagAction {
173 #[serde(rename = "type")]
175 pub kind: FeatureFlagActionType,
176 pub auto_fixable: bool,
178 pub description: String,
180 #[serde(default, skip_serializing_if = "Option::is_none")]
182 pub comment: Option<String>,
183}
184
185#[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 InvestigateFlag,
192 SuppressLine,
194}
195
196#[derive(Debug, Clone, Serialize)]
198#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
199pub struct FeatureFlagDeadCodeOverlap {
200 pub guarded_lines: u32,
202 pub dead_export_count: usize,
204 pub dead_exports: Vec<String>,
206}
207
208#[derive(Debug, Clone, Serialize)]
215#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
216pub struct FeatureFlagsMeta {
217 #[serde(default, skip_serializing_if = "Option::is_none")]
219 pub feature_flags: Option<FeatureFlagsMetaDetails>,
220 #[serde(default, skip_serializing_if = "Option::is_none")]
222 pub telemetry: Option<TelemetryMeta>,
223}
224
225#[derive(Debug, Clone, Serialize)]
227#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
228pub struct FeatureFlagsMetaDetails {
229 pub description: &'static str,
231 pub kinds: FeatureFlagsKindMeta,
233 pub confidence: FeatureFlagsConfidenceMeta,
235 pub docs: &'static str,
237}
238
239#[derive(Debug, Clone, Serialize)]
241#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
242pub struct FeatureFlagsKindMeta {
243 pub environment_variable: &'static str,
245 pub sdk_call: &'static str,
247 pub config_object: &'static str,
249}
250
251#[derive(Debug, Clone, Serialize)]
253#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
254pub struct FeatureFlagsConfidenceMeta {
255 pub high: &'static str,
257 pub medium: &'static str,
259 pub low: &'static str,
261}
262
263#[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 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
292pub 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#[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#[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 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 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}