redisctl 0.12.1

Unified CLI for Redis Cloud and Enterprise
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
//! Error types for redisctl
//!
//! Defines structured error types using thiserror for better error handling and user experience.

use colored::Colorize;
use thiserror::Error;

/// Cargo-style diagnostic formatter for CLI errors.
///
/// Produces structured output like:
/// ```text
/// error: cannot determine platform for 'database'
///   You have both cloud and enterprise profiles.
///
///   tip: be explicit about the platform:
///       redisctl cloud database list
///       redisctl enterprise database list
/// ```
pub struct CliDiagnostic {
    message: String,
    detail: Option<String>,
    tips: Vec<(String, Vec<String>)>,
}

impl CliDiagnostic {
    /// Start a new error diagnostic with the given message.
    pub fn error(message: &str) -> Self {
        Self {
            message: message.to_string(),
            detail: None,
            tips: Vec::new(),
        }
    }

    /// Add a detail line below the error message.
    pub fn detail(mut self, text: &str) -> Self {
        self.detail = Some(text.to_string());
        self
    }

    /// Add a tip with optional example commands.
    pub fn tip(mut self, description: &str, commands: &[&str]) -> Self {
        self.tips.push((
            description.to_string(),
            commands.iter().map(|s| s.to_string()).collect(),
        ));
        self
    }

    /// Print the diagnostic to stderr with colored formatting.
    pub fn print(&self) {
        eprint!("{}{}", "error".red().bold(), ": ".bold());
        eprintln!("{}", self.message);

        if let Some(detail) = &self.detail {
            eprintln!("  {}", detail);
        }

        for (description, commands) in &self.tips {
            eprintln!();
            eprint!("  {}{}", "tip".yellow().bold(), ": ".bold());
            eprintln!("{}", description);
            for cmd in commands {
                eprintln!("      {}", cmd);
            }
        }
    }
}

/// Process exit codes, so a script can branch on the kind of failure rather
/// than on the text of the message.
///
/// `USAGE` is 2 to match clap, which already exits 2 when argument parsing
/// fails: both mean the invocation itself was wrong. `GENERIC` stays 1 so
/// anything not yet classified keeps the previous behavior.
pub mod exit_code {
    /// An error with no more specific classification.
    pub const GENERIC: i32 = 1;
    /// The command was invoked incorrectly.
    pub const USAGE: i32 = 2;
    /// Local configuration or profile problem.
    pub const CONFIG: i32 = 3;
    /// Credentials were rejected by the server.
    pub const AUTH: i32 = 4;
    /// The requested resource does not exist.
    pub const NOT_FOUND: i32 = 5;
    /// Input was well-formed but not valid.
    pub const VALIDATION: i32 = 6;
    /// The request conflicts with the current server state.
    pub const CONFLICT: i32 = 7;
    /// The server failed to service an otherwise valid request.
    pub const UPSTREAM: i32 = 8;
    /// The server is rate limiting; retry later.
    pub const RATE_LIMITED: i32 = 9;
    /// The server could not be reached.
    pub const NETWORK: i32 = 10;
    /// The operation did not complete in time.
    pub const TIMEOUT: i32 = 11;
    /// The operation was not confirmed, so nothing was done.
    pub const CANCELLED: i32 = 12;
}

/// Main error type for the redisctl application
#[derive(Error, Debug)]
pub enum RedisCtlError {
    #[error("Configuration error: {0}")]
    Configuration(String),

    #[error("{0}")]
    Other(String),

    #[error("Profile '{name}' not found")]
    ProfileNotFound { name: String },

    #[error("Profile '{name}' is type '{actual_type}' but command requires '{expected_type}'")]
    ProfileTypeMismatch {
        name: String,
        actual_type: String,
        expected_type: String,
        available_profiles: Vec<String>,
    },

    #[error("No {deployment_type} profiles configured. {suggestion}")]
    NoProfileConfigured {
        deployment_type: String,
        suggestion: String,
    },

    #[error("Missing credentials for profile '{name}': {missing_fields}")]
    MissingCredentials {
        name: String,
        missing_fields: String,
    },

    #[error("Authentication failed for profile '{profile_name}': {message}")]
    AuthenticationFailed {
        message: String,
        profile_name: String,
    },

    #[error("API error: {message}")]
    ApiError { message: String },

    #[error("Invalid input: {message}")]
    InvalidInput { message: String },

    #[error("Cancelled at the confirmation prompt: {prompt}")]
    Cancelled { prompt: String },

    #[error("Command not supported for deployment type '{deployment_type}'")]
    UnsupportedDeploymentType { deployment_type: String },
    #[error("File error for '{path}': {message}")]
    FileError { path: String, message: String },

    #[error("Connection error: {message}")]
    ConnectionError { message: String },

    #[error("Timeout: {message}")]
    Timeout { message: String },

    #[error("Output formatting error: {message}")]
    OutputError { message: String },

    /// Agent-native surface error carrying a stable code + exit code (see
    /// [`crate::structured_error`]). Handled specially in `main` (JSON envelope to stdout,
    /// mapped exit code) rather than the generic 0/1 path.
    #[error("{0}")]
    Structured(Box<crate::structured_error::StructuredError>),
}

/// Result type for redisctl operations
pub type Result<T> = std::result::Result<T, RedisCtlError>;

impl RedisCtlError {
    /// Get helpful suggestions for resolving this error
    pub fn suggestions(&self) -> Vec<String> {
        match self {
            RedisCtlError::ProfileNotFound { name } => vec![
                "List available profiles: redisctl profile list".to_string(),
                format!("Create profile '{}': redisctl profile set {}", name, name),
                "Check profile name spelling".to_string(),
            ],
            RedisCtlError::NoProfileConfigured {
                deployment_type, ..
            } => vec![
                "Run the setup wizard: redisctl profile init".to_string(),
                format!(
                    "Or create manually: redisctl profile set <name> --type {deployment_type} ..."
                ),
                "View profile help: redisctl profile set --help".to_string(),
            ],
            RedisCtlError::MissingCredentials { name, .. } => vec![
                format!(
                    "Update the profile: redisctl profile set {} --type <type> ...",
                    name
                ),
                format!("Check current values: redisctl profile show {}", name),
                "If using environment variables, check they are exported in your shell".to_string(),
            ],
            RedisCtlError::AuthenticationFailed { profile_name, .. } => {
                let mut suggestions = vec![format!(
                    "Check credentials: redisctl profile show {}",
                    profile_name,
                )];
                suggestions.push(format!(
                    "Refresh credentials: redisctl profile set {} --type <type> ... (preserves other settings)",
                    profile_name,
                ));
                suggestions
                    .push("Test connectivity: redisctl profile validate --connect".to_string());
                suggestions
            }
            RedisCtlError::ConnectionError { message }
                if message.contains("certificate")
                    || message.contains("SSL")
                    || message.contains("tls") =>
            {
                vec![
                    "For self-signed certificates, recreate profile with --insecure".to_string(),
                    "Or provide a CA cert: --ca-cert /path/to/ca.pem".to_string(),
                    "Verify the URL uses the correct port (9443 for Enterprise admin)".to_string(),
                ]
            }
            RedisCtlError::ConnectionError { message }
                if message.contains("Connection refused") =>
            {
                vec![
                    "The server is not accepting connections on this address/port".to_string(),
                    "Verify the URL: redisctl profile show <profile>".to_string(),
                    "Check that the server is running and the port is correct".to_string(),
                ]
            }
            RedisCtlError::ConnectionError { message } if message.contains("timed out") => vec![
                "The server did not respond in time".to_string(),
                "Check network connectivity and firewall rules".to_string(),
                "Verify the URL: redisctl profile show <profile>".to_string(),
            ],
            RedisCtlError::ConnectionError { .. } => vec![
                "Check network connectivity to the server".to_string(),
                "Verify the URL: redisctl profile show <profile>".to_string(),
                "Test connectivity: redisctl profile validate --connect".to_string(),
            ],
            RedisCtlError::ApiError { message } if message.contains("404") => vec![
                "Verify the resource ID is correct".to_string(),
                "List available resources to find the correct ID".to_string(),
                "Check that you're using the correct profile".to_string(),
            ],
            RedisCtlError::ProfileTypeMismatch {
                expected_type,
                available_profiles,
                ..
            } => {
                let mut suggestions = Vec::new();
                if available_profiles.is_empty() {
                    suggestions.push(format!(
                        "No {} profiles found. Create one with: redisctl profile set <name> --type {}",
                        expected_type, expected_type
                    ));
                } else {
                    suggestions.push(format!(
                        "Available {} profiles: {}",
                        expected_type,
                        available_profiles.join(", ")
                    ));
                    suggestions.push(format!(
                        "Use one with: redisctl --profile {} <command>",
                        available_profiles[0]
                    ));
                }
                suggestions.push("List all profiles: redisctl profile list".to_string());
                suggestions
            }
            RedisCtlError::UnsupportedDeploymentType { .. } => vec![
                "Check the command documentation: redisctl <command> --help".to_string(),
                "Use the appropriate command for your deployment type".to_string(),
            ],
            RedisCtlError::InvalidInput { .. } => vec![
                "Check the command syntax: redisctl <command> --help".to_string(),
                "Verify input file format is correct (JSON/YAML)".to_string(),
            ],
            RedisCtlError::FileError { path, .. } => vec![
                format!("Check that file exists: {}", path),
                "Verify file permissions are correct".to_string(),
                "Ensure file path is correct (use absolute path if needed)".to_string(),
            ],
            RedisCtlError::Cancelled { .. } => vec![
                "Re-run with --force to skip the confirmation prompt".to_string(),
                "Confirmation prompts require an interactive terminal".to_string(),
                "A declined or unanswerable prompt is a failure, not a no-op".to_string(),
            ],
            RedisCtlError::Configuration(_) => vec![
                "Check the profile: redisctl profile show <name>".to_string(),
                "Verify the config file syntax and required fields".to_string(),
            ],
            _ => vec![],
        }
    }

    /// Print a cargo-style diagnostic to stderr using colored formatting.
    /// A stable, machine-readable error code for the -o json/yaml envelope.
    /// Exhaustive on purpose: a new variant must declare its code.
    pub fn code(&self) -> &'static str {
        match self {
            RedisCtlError::Configuration(_) => "configuration",
            RedisCtlError::Other(_) => "error",
            RedisCtlError::ProfileNotFound { .. } => "profile_not_found",
            RedisCtlError::ProfileTypeMismatch { .. } => "profile_type_mismatch",
            RedisCtlError::NoProfileConfigured { .. } => "no_profile_configured",
            RedisCtlError::MissingCredentials { .. } => "missing_credentials",
            RedisCtlError::AuthenticationFailed { .. } => "authentication_failed",
            RedisCtlError::ApiError { .. } => "api_error",
            RedisCtlError::InvalidInput { .. } => "invalid_input",
            RedisCtlError::Cancelled { .. } => "cancelled",
            RedisCtlError::UnsupportedDeploymentType { .. } => "unsupported_deployment_type",
            RedisCtlError::FileError { .. } => "file_error",
            RedisCtlError::ConnectionError { .. } => "connection_error",
            RedisCtlError::Timeout { .. } => "timeout",
            RedisCtlError::OutputError { .. } => "output_error",
            // Agent-native surface errors carry their own stable code.
            RedisCtlError::Structured(se) => se.code,
        }
    }

    /// The process exit code for this error.
    ///
    /// Exhaustive on purpose: a new variant must declare its code. Several
    /// variants share one code, because the taxonomy classifies what a script
    /// should do about the failure, not which variant produced it.
    pub fn exit_code(&self) -> i32 {
        match self {
            // Local configuration: the profile is missing, incomplete, or the
            // wrong type for the command.
            RedisCtlError::Configuration(_)
            | RedisCtlError::ProfileNotFound { .. }
            | RedisCtlError::ProfileTypeMismatch { .. }
            | RedisCtlError::NoProfileConfigured { .. }
            | RedisCtlError::MissingCredentials { .. } => exit_code::CONFIG,

            RedisCtlError::AuthenticationFailed { .. } => exit_code::AUTH,

            // The only variant that carries a server status, so it is the only
            // place not-found, conflict and rate-limited can come from. The
            // status is recovered from the message, as `suggestions` already
            // does for 404.
            RedisCtlError::ApiError { message } => {
                if message.contains("404") {
                    exit_code::NOT_FOUND
                } else if message.contains("409") {
                    exit_code::CONFLICT
                } else if message.contains("429") {
                    exit_code::RATE_LIMITED
                } else {
                    exit_code::UPSTREAM
                }
            }

            RedisCtlError::InvalidInput { .. } => exit_code::VALIDATION,
            RedisCtlError::Cancelled { .. } => exit_code::CANCELLED,

            // The command does not apply to this deployment, or names a file
            // that could not be read: in both cases the invocation was wrong.
            RedisCtlError::UnsupportedDeploymentType { .. } | RedisCtlError::FileError { .. } => {
                exit_code::USAGE
            }

            RedisCtlError::ConnectionError { .. } => exit_code::NETWORK,
            RedisCtlError::Timeout { .. } => exit_code::TIMEOUT,

            // `Other` is the anyhow catch-all and `OutputError` covers
            // serialization and IO; neither is classified yet.
            RedisCtlError::Other(_) | RedisCtlError::OutputError { .. } => exit_code::GENERIC,

            // The agent-native surface publishes its own 1-4 contract (see
            // docs/reference/agent-error-codes.md), where `retryable` is defined as exactly the
            // exit-3 class. Those numbers are carried through unchanged so a caller branching on
            // them keeps working. NOTE: 3 and 4 therefore mean something different here than in
            // the taxonomy above (CONFIG and AUTH) — reconciling the two is a separate decision.
            RedisCtlError::Structured(se) => se.exit_code as i32,
        }
    }

    /// The structured error object emitted under -o json/-o yaml.
    fn envelope(&self) -> serde_json::Value {
        serde_json::json!({
            "error": {
                "code": self.code(),
                "exit_code": self.exit_code(),
                "message": self.to_string(),
                "tips": self.suggestions(),
            }
        })
    }

    /// Print an error to stderr. Under -o json/-o yaml this is a structured
    /// envelope a script can parse; otherwise a cargo-style human diagnostic.
    /// Always stderr, so the -o json success payload on stdout stays clean.
    pub fn print_diagnostic(&self, format: crate::cli::OutputFormat) {
        use crate::cli::OutputFormat;
        match format {
            OutputFormat::Json => {
                let envelope = self.envelope();
                eprintln!(
                    "{}",
                    serde_json::to_string_pretty(&envelope)
                        .unwrap_or_else(|_| envelope.to_string())
                );
            }
            OutputFormat::Yaml => match serde_yaml::to_string(&self.envelope()) {
                Ok(s) => eprint!("{}", s),
                Err(_) => self.print_human_diagnostic(),
            },
            OutputFormat::Auto | OutputFormat::Table => self.print_human_diagnostic(),
        }
    }

    fn print_human_diagnostic(&self) {
        let mut diag = CliDiagnostic::error(&format!("{}", self));

        for suggestion in self.suggestions() {
            diag = diag.tip(&suggestion, &[]);
        }

        diag.print();
    }
}

impl From<redis_cloud::CloudError> for RedisCtlError {
    fn from(err: redis_cloud::CloudError) -> Self {
        match err {
            redis_cloud::CloudError::AuthenticationFailed { message } => {
                RedisCtlError::AuthenticationFailed {
                    message,
                    profile_name: "<unknown>".to_string(),
                }
            }
            redis_cloud::CloudError::ConnectionError(message) => {
                RedisCtlError::ConnectionError { message }
            }
            _ => RedisCtlError::ApiError {
                message: err.to_string(),
            },
        }
    }
}

impl From<redis_enterprise::RestError> for RedisCtlError {
    fn from(err: redis_enterprise::RestError) -> Self {
        match err {
            redis_enterprise::RestError::AuthenticationFailed => {
                RedisCtlError::AuthenticationFailed {
                    message: "Authentication failed".to_string(),
                    profile_name: "<unknown>".to_string(),
                }
            }
            redis_enterprise::RestError::Unauthorized => RedisCtlError::AuthenticationFailed {
                message: "401 Unauthorized: Invalid username or password. Check your credentials."
                    .to_string(),
                profile_name: "<unknown>".to_string(),
            },
            redis_enterprise::RestError::NotFound => RedisCtlError::ApiError {
                message: "404 Not Found: The requested resource does not exist".to_string(),
            },
            redis_enterprise::RestError::ApiError { code, message } => RedisCtlError::ApiError {
                message: format!("HTTP {}: {}", code, message),
            },
            redis_enterprise::RestError::ServerError(msg) => RedisCtlError::ApiError {
                message: format!("Server error (5xx): {}", msg),
            },
            redis_enterprise::RestError::RequestFailed(reqwest_err) => {
                RedisCtlError::ConnectionError {
                    message: reqwest_err.to_string(),
                }
            }
            redis_enterprise::RestError::ConnectionError(msg) => {
                RedisCtlError::ConnectionError { message: msg }
            }
            redis_enterprise::RestError::ValidationError(msg) => {
                RedisCtlError::InvalidInput { message: msg }
            }
            _ => RedisCtlError::ApiError {
                message: err.to_string(),
            },
        }
    }
}

impl From<serde_json::Error> for RedisCtlError {
    fn from(err: serde_json::Error) -> Self {
        RedisCtlError::OutputError {
            message: format!("JSON error: {}", err),
        }
    }
}

impl From<std::io::Error> for RedisCtlError {
    fn from(err: std::io::Error) -> Self {
        RedisCtlError::OutputError {
            message: format!("IO error: {}", err),
        }
    }
}

impl From<anyhow::Error> for RedisCtlError {
    fn from(err: anyhow::Error) -> Self {
        // {:#} renders the full anyhow context chain (message: cause: cause),
        // and Other keeps the message as-is, instead of dropping the cause and
        // mislabeling every anyhow-wrapped API, IO, or JSON error as a
        // "Configuration error".
        RedisCtlError::Other(format!("{:#}", err))
    }
}

impl From<redisctl_core::AuthError> for RedisCtlError {
    fn from(err: redisctl_core::AuthError) -> Self {
        match err {
            redisctl_core::AuthError::Network(e) => RedisCtlError::ConnectionError {
                message: e.to_string(),
            },
            redisctl_core::AuthError::Transport(m) => RedisCtlError::ConnectionError { message: m },
            other => RedisCtlError::AuthenticationFailed {
                message: other.to_string(),
                profile_name: "<login>".to_string(),
            },
        }
    }
}

impl From<redisctl_core::ConfigError> for RedisCtlError {
    fn from(err: redisctl_core::ConfigError) -> Self {
        match err {
            redisctl_core::ConfigError::ProfileNotFound { name } => {
                RedisCtlError::ProfileNotFound { name }
            }
            redisctl_core::ConfigError::NoProfilesOfType {
                deployment_type,
                suggestion,
            } => RedisCtlError::NoProfileConfigured {
                deployment_type,
                suggestion,
            },
            other => RedisCtlError::Configuration(other.to_string()),
        }
    }
}

impl From<redisctl_core::ClientResolutionError> for RedisCtlError {
    fn from(err: redisctl_core::ClientResolutionError) -> Self {
        match err {
            redisctl_core::ClientResolutionError::Config(config_error) => config_error.into(),
            redisctl_core::ClientResolutionError::ProfileTypeMismatch {
                name,
                actual_type,
                expected_type,
                available_profiles,
            } => RedisCtlError::ProfileTypeMismatch {
                name,
                actual_type: actual_type.to_string(),
                expected_type: expected_type.to_string(),
                available_profiles,
            },
            redisctl_core::ClientResolutionError::MissingCredentials {
                profile_name,
                missing_fields,
                ..
            } => RedisCtlError::MissingCredentials {
                name: profile_name,
                missing_fields,
            },
            redisctl_core::ClientResolutionError::CloudClient(cloud_error) => cloud_error.into(),
            redisctl_core::ClientResolutionError::EnterpriseClient(enterprise_error) => {
                enterprise_error.into()
            }
        }
    }
}

impl From<redisctl_core::error::CoreError> for RedisCtlError {
    fn from(err: redisctl_core::error::CoreError) -> Self {
        match err {
            redisctl_core::error::CoreError::TaskTimeout(duration) => RedisCtlError::Timeout {
                message: format!("Operation timed out after {} seconds", duration.as_secs()),
            },
            redisctl_core::error::CoreError::TaskFailed(msg) => RedisCtlError::ApiError {
                message: format!("Task failed: {}", msg),
            },
            redisctl_core::error::CoreError::Validation(msg) => {
                RedisCtlError::InvalidInput { message: msg }
            }
            redisctl_core::error::CoreError::Config(msg) => RedisCtlError::Configuration(msg),
            redisctl_core::error::CoreError::Cloud(cloud_err) => RedisCtlError::from(cloud_err),
            redisctl_core::error::CoreError::Enterprise(enterprise_err) => {
                RedisCtlError::from(enterprise_err)
            }
        }
    }
}

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

    fn api(message: &str) -> RedisCtlError {
        RedisCtlError::ApiError {
            message: message.to_string(),
        }
    }

    #[test]
    fn variants_map_to_their_taxonomy_codes() {
        assert_eq!(
            RedisCtlError::Configuration("bad".into()).exit_code(),
            exit_code::CONFIG
        );
        assert_eq!(
            RedisCtlError::ProfileNotFound { name: "p".into() }.exit_code(),
            exit_code::CONFIG
        );
        assert_eq!(
            RedisCtlError::AuthenticationFailed {
                message: "no".into(),
                profile_name: "p".into(),
            }
            .exit_code(),
            exit_code::AUTH
        );
        assert_eq!(
            RedisCtlError::InvalidInput {
                message: "no".into(),
            }
            .exit_code(),
            exit_code::VALIDATION
        );
        assert_eq!(
            RedisCtlError::Cancelled {
                prompt: "delete?".into(),
            }
            .exit_code(),
            exit_code::CANCELLED
        );
        assert_eq!(
            RedisCtlError::FileError {
                path: "/nope".into(),
                message: "missing".into(),
            }
            .exit_code(),
            exit_code::USAGE
        );
        assert_eq!(
            RedisCtlError::ConnectionError {
                message: "refused".into(),
            }
            .exit_code(),
            exit_code::NETWORK
        );
        assert_eq!(
            RedisCtlError::Timeout {
                message: "slow".into(),
            }
            .exit_code(),
            exit_code::TIMEOUT
        );
        assert_eq!(
            RedisCtlError::Other("unclassified".into()).exit_code(),
            exit_code::GENERIC
        );
    }

    #[test]
    fn api_errors_split_by_status() {
        assert_eq!(
            api("404 Not Found: no such database").exit_code(),
            exit_code::NOT_FOUND
        );
        assert_eq!(
            api("HTTP 409: database already exists").exit_code(),
            exit_code::CONFLICT
        );
        assert_eq!(
            api("HTTP 429: slow down").exit_code(),
            exit_code::RATE_LIMITED
        );
        assert_eq!(
            api("Server error (5xx): boom").exit_code(),
            exit_code::UPSTREAM
        );
    }

    // The envelope is the script-facing contract: it must carry the same exit
    // code the process actually returns.
    #[test]
    fn envelope_carries_the_exit_code() {
        let err = RedisCtlError::Timeout {
            message: "slow".into(),
        };
        let envelope = err.envelope();
        assert_eq!(envelope["error"]["exit_code"], exit_code::TIMEOUT);
        assert_eq!(envelope["error"]["code"], "timeout");
    }

    // Nothing is allowed to collapse back to a bare 1 except the two variants
    // that are explicitly unclassified.
    #[test]
    fn classified_variants_do_not_return_generic() {
        for err in [
            RedisCtlError::NoProfileConfigured {
                deployment_type: "cloud".into(),
                suggestion: "create one".into(),
            },
            RedisCtlError::MissingCredentials {
                name: "p".into(),
                missing_fields: "api_key".into(),
            },
            RedisCtlError::UnsupportedDeploymentType {
                deployment_type: "cloud".into(),
            },
            api("HTTP 500: boom"),
        ] {
            assert_ne!(err.exit_code(), exit_code::GENERIC, "{err}");
        }
    }

    #[test]
    fn config_errors_keep_actionable_profile_types() {
        let missing = RedisCtlError::from(redisctl_core::ConfigError::ProfileNotFound {
            name: "missing".into(),
        });
        assert!(matches!(
            missing,
            RedisCtlError::ProfileNotFound { ref name } if name == "missing"
        ));

        let empty = RedisCtlError::from(redisctl_core::ConfigError::NoProfilesOfType {
            deployment_type: "cloud".into(),
            suggestion: "create one".into(),
        });
        assert!(matches!(
            empty,
            RedisCtlError::NoProfileConfigured {
                ref deployment_type,
                ref suggestion,
            } if deployment_type == "cloud" && suggestion == "create one"
        ));
    }
}