Skip to main content

logbrew_cli/
error.rs

1//! CLI error types and output rendering.
2
3use crate::ISSUE_STATUS_VALUES_NEXT_STEP;
4use std::borrow::Cow;
5
6/// CLI parsing error.
7#[derive(Debug, thiserror::Error, PartialEq, Eq)]
8pub enum CliError {
9    /// Command is missing or unsupported.
10    #[error("unknown or missing command")]
11    UnknownCommand,
12    /// Command name is unsupported.
13    #[error("unknown command: {command}")]
14    UnknownCommandName {
15        /// Unsupported command name.
16        command: String,
17        /// Suggested next step.
18        next: &'static str,
19    },
20    /// Required command argument is missing.
21    #[error("missing argument: {argument}")]
22    MissingArgument {
23        /// Missing argument name.
24        argument: &'static str,
25        /// Argument-specific next step.
26        next: &'static str,
27    },
28    /// Required flag value is missing.
29    #[error("missing value for {flag}")]
30    MissingFlagValue {
31        /// Flag missing a value.
32        flag: &'static str,
33        /// Flag-specific next step.
34        next: &'static str,
35    },
36    /// Flag is present more than once.
37    #[error("duplicate flag: {flag}")]
38    DuplicateFlag {
39        /// Duplicate flag value.
40        flag: &'static str,
41        /// Flag-specific next step.
42        next: &'static str,
43    },
44    /// Positional argument is unsupported for the selected command.
45    #[error("unexpected argument for {command}: {argument}")]
46    UnexpectedArgument {
47        /// Unexpected argument value.
48        argument: String,
49        /// Command name.
50        command: &'static str,
51        /// Command-specific next step.
52        next: &'static str,
53    },
54    /// Flag is unknown for the selected command.
55    #[error("unknown flag: {flag}")]
56    UnknownFlag {
57        /// Unknown flag value.
58        flag: String,
59        /// Command-specific next step.
60        next: &'static str,
61    },
62    /// Flag is known globally but unsupported for the selected command.
63    #[error("unsupported flag for {command}: {flag}")]
64    UnsupportedFlag {
65        /// Unsupported flag value.
66        flag: String,
67        /// Command name.
68        command: &'static str,
69        /// Command-specific next step.
70        next: &'static str,
71    },
72    /// Resource is unsupported for the selected command.
73    #[error("unknown resource: {resource}")]
74    UnknownResource {
75        /// Unsupported resource value.
76        resource: String,
77        /// Command-specific next step.
78        next: &'static str,
79    },
80    /// Issue status is unsupported.
81    #[error("unknown issue status: {0}")]
82    UnknownStatus(String),
83    /// Trace status is unsupported.
84    #[error("unknown trace status: {0}")]
85    UnknownTraceStatus(String),
86    /// Log level is unsupported.
87    #[error("unknown log level: {0}")]
88    UnknownLogLevel(String),
89    /// Row limit is malformed.
90    #[error("invalid limit: {0}")]
91    InvalidLimit(String),
92    /// Minimum trace duration is malformed.
93    #[error("invalid minimum duration: {0}")]
94    InvalidMinDuration(String),
95    /// Pagination mode is unsupported.
96    #[error("unknown pagination mode")]
97    UnknownPagination,
98    /// Action cursor fields are inconsistent.
99    #[error("invalid action cursor: {0}")]
100    InvalidActionCursor(String),
101    /// Log cursor fields are inconsistent.
102    #[error("invalid log cursor: {0}")]
103    InvalidLogCursor(String),
104    /// Issue cursor fields are inconsistent.
105    #[error("invalid issue cursor: {0}")]
106    InvalidIssueCursor(String),
107    /// Support-ticket cursor fields are inconsistent.
108    #[error("invalid support cursor: {0}")]
109    InvalidSupportCursor(String),
110    /// Support-ticket category is unsupported.
111    #[error("unknown support category")]
112    UnknownSupportCategory,
113    /// Support-ticket identifier is not in the public `sup_` form.
114    #[error("invalid support ticket id")]
115    InvalidSupportTicketId,
116    /// Support context retry key cannot be sent as an HTTP header value.
117    #[error("invalid support retry key")]
118    InvalidSupportRetryKey,
119    /// Support context reply syntax is malformed.
120    #[error("invalid support context reply")]
121    InvalidSupportContextReply,
122    /// Support context history syntax is malformed.
123    #[error("invalid support context command")]
124    InvalidSupportContextCommand,
125    /// Support context text is blank or exceeds the public limit.
126    #[error("invalid support context")]
127    InvalidSupportContext,
128    /// Issue investigation syntax is malformed.
129    #[error("invalid issue investigation command")]
130    InvalidInvestigationCommand,
131    /// Project-scoped doctor syntax is malformed.
132    #[error("invalid project doctor command")]
133    InvalidDoctorCommand,
134    /// Secure project creation syntax is malformed.
135    #[error("invalid project create command")]
136    InvalidProjectCreateCommand,
137    /// Confirmed project archival syntax is malformed.
138    #[error("invalid project archive command")]
139    InvalidProjectArchiveCommand,
140    /// Authenticated project catalog syntax is malformed.
141    #[error("invalid projects command")]
142    InvalidProjectsCommand,
143    /// Native browser login provider is unsupported.
144    #[error("invalid login provider")]
145    InvalidLoginProvider,
146    /// Account usage read syntax is malformed.
147    #[error("invalid usage command")]
148    InvalidUsageCommand,
149    /// Native debug-artifact command syntax is malformed.
150    #[error("invalid native debug-artifact command")]
151    InvalidNativeDebugCommand,
152    /// Native debug-artifact identity is not canonical.
153    #[error("invalid native debug-artifact identity")]
154    InvalidNativeDebugIdentity,
155    /// Project setup source is malformed.
156    #[error("invalid setup source: {0}")]
157    InvalidSetupSource(String),
158}
159
160/// Runtime error for command execution.
161#[derive(Debug, thiserror::Error)]
162pub enum RuntimeError {
163    /// Command-line parsing failed.
164    #[error(transparent)]
165    Cli(#[from] CliError),
166    /// Filesystem or process I/O failed.
167    #[error(transparent)]
168    Io(#[from] std::io::Error),
169    /// HTTP request failed.
170    #[error(transparent)]
171    Http(#[from] reqwest::Error),
172    /// Auth token was missing for an authenticated API call.
173    #[error("not logged in: run logbrew login")]
174    MissingToken,
175    /// API returned a non-success status.
176    #[error("api returned status {status}: {body}")]
177    Api {
178        /// HTTP status code.
179        status: u16,
180        /// Response body.
181        body: String,
182        /// Stable machine-readable auth source key.
183        auth_source: &'static str,
184        /// Concise human auth label.
185        auth_label: &'static str,
186    },
187    /// Status check could not prove API reachability.
188    #[error("LogBrew API unreachable: {message}")]
189    StatusUnavailable {
190        /// Base API URL checked by the CLI.
191        api_url: String,
192        /// Optional HTTP status code returned by `/health`.
193        status_code: Option<u16>,
194        /// Optional response body returned by `/health`.
195        body: Option<String>,
196        /// Whether a local credential is configured.
197        authenticated: bool,
198        /// Stable machine-readable auth source key.
199        auth_source: &'static str,
200        /// Concise human auth label.
201        auth_label: &'static str,
202        /// Human-readable reachability reason.
203        message: String,
204    },
205    /// Command is recognized but not available yet.
206    #[error("{message}")]
207    Unavailable {
208        /// Human-readable unavailable reason.
209        message: &'static str,
210        /// Suggested fallback action.
211        next: &'static str,
212    },
213    /// A successful investigation response violated the public contract.
214    #[error("issue investigation returned an invalid response")]
215    InvestigationResponseInvalid,
216    /// A local Apple native debug artifact failed validation.
217    #[error("native debug artifact is invalid")]
218    NativeDebugArtifactInvalid,
219    /// A native debug-artifact response violated the public contract.
220    #[error("native debug-artifact response is invalid")]
221    NativeDebugResponseInvalid,
222    /// Exact post-upload lookup verification did not match.
223    #[error("native debug-artifact verification failed")]
224    NativeDebugVerificationFailed,
225}
226
227/// Writes a command-line parsing error for humans or agents.
228///
229/// # Errors
230///
231/// Returns an I/O error if writing to the output stream fails.
232pub fn write_cli_error<W: std::io::Write>(
233    error: &CliError,
234    json: bool,
235    output: &mut W,
236) -> Result<(), std::io::Error> {
237    if json {
238        let body = serde_json::json!({
239            "ok": false,
240            "error": cli_error_code(error),
241            "message": error.to_string(),
242            "next": cli_error_next_step(error),
243        });
244        writeln!(output, "{body}")
245    } else {
246        writeln!(output, "{error}")?;
247        writeln!(output, "Next: {}", cli_error_next_step(error))
248    }
249}
250
251/// Writes a runtime error for humans or agents.
252///
253/// # Errors
254///
255/// Returns an I/O error if writing to the output stream fails.
256pub fn write_runtime_error<W: std::io::Write>(
257    error: &RuntimeError,
258    json: bool,
259    output: &mut W,
260) -> Result<(), std::io::Error> {
261    if json {
262        let body = runtime_error_json(error);
263        writeln!(output, "{body}")
264    } else {
265        write_human_runtime_error(error, output)
266    }
267}
268
269/// Writes one body-free native debug-artifact JSON error for agents.
270///
271/// # Errors
272///
273/// Returns an I/O error if writing to the output stream fails.
274pub fn write_native_debug_runtime_error<W: std::io::Write>(
275    error: &RuntimeError,
276    output: &mut W,
277) -> Result<(), std::io::Error> {
278    let body = match error {
279        RuntimeError::Api { status, body, .. } => {
280            let details = ApiErrorDetails::parse(body);
281            let (fallback_code, fallback_next) = native_debug_api_recovery(*status);
282            let code = details
283                .code
284                .as_deref()
285                .and_then(|value| allowed_native_debug_code(*status, value))
286                .unwrap_or(fallback_code);
287            let next = details
288                .next
289                .as_deref()
290                .and_then(|value| allowed_native_debug_next(*status, value))
291                .unwrap_or(fallback_next);
292            serde_json::json!({
293                "ok": false,
294                "error": code,
295                "status": status,
296                "next": next,
297            })
298        }
299        RuntimeError::Cli(_)
300        | RuntimeError::Io(_)
301        | RuntimeError::Http(_)
302        | RuntimeError::MissingToken
303        | RuntimeError::StatusUnavailable { .. }
304        | RuntimeError::Unavailable { .. }
305        | RuntimeError::InvestigationResponseInvalid
306        | RuntimeError::NativeDebugArtifactInvalid
307        | RuntimeError::NativeDebugResponseInvalid
308        | RuntimeError::NativeDebugVerificationFailed => serde_json::json!({
309            "ok": false,
310            "error": runtime_error_code(error),
311            "next": fallback_runtime_error_next_step(error),
312        }),
313    };
314    writeln!(output, "{body}")
315}
316
317/// Returns fixed native debug-artifact recovery derived only from HTTP status.
318const fn native_debug_api_recovery(status: u16) -> (&'static str, &'static str) {
319    match status {
320        400 => (
321            "validation_failed",
322            "check the artifact identity and request scope, then retry",
323        ),
324        401 | 403 => (
325            "unauthorized",
326            "sign in and retry the native debug-artifact command",
327        ),
328        404 => (
329            "not_found",
330            "check the exact project, release, environment, service, UUID, and architecture",
331        ),
332        405 => (
333            "method_not_allowed",
334            "use the supported native debug-artifact request method",
335        ),
336        408 => (
337            "request_timeout",
338            "retry the same native debug-artifact request",
339        ),
340        413 => (
341            "payload_too_large",
342            "reduce the native debug-artifact upload below the documented size limits and retry",
343        ),
344        422 => (
345            "validation_failed",
346            "send manifest and debug_file_N multipart parts from LogBrew Apple release tooling",
347        ),
348        429 => (
349            "rate_limited",
350            "retry the same native debug-artifact command later",
351        ),
352        500..=599 => (
353            "server_error",
354            "retry the same native debug-artifact command later",
355        ),
356        _ => (
357            "unexpected_response",
358            "retry the native debug-artifact command",
359        ),
360    }
361}
362
363/// Allows only fixed native debug-artifact error codes for one status.
364fn allowed_native_debug_code(status: u16, value: &str) -> Option<&'static str> {
365    match (status, value) {
366        (400 | 422, "validation_failed") => Some("validation_failed"),
367        (401 | 403, "unauthorized") => Some("unauthorized"),
368        (404, "not_found") => Some("not_found"),
369        (405, "method_not_allowed") => Some("method_not_allowed"),
370        (408, "request_timeout") => Some("request_timeout"),
371        (413, "payload_too_large") => Some("payload_too_large"),
372        (429, "rate_limited") => Some("rate_limited"),
373        (500..=599, "server_error") => Some("server_error"),
374        _ => None,
375    }
376}
377
378/// Allows only fixed native debug-artifact recovery strings for one status.
379fn allowed_native_debug_next(status: u16, value: &str) -> Option<&'static str> {
380    match (status, value) {
381        (400, "check the artifact identity and request scope, then retry") => {
382            Some("check the artifact identity and request scope, then retry")
383        }
384        (401 | 403, "sign in and retry the native debug-artifact command") => {
385            Some("sign in and retry the native debug-artifact command")
386        }
387        (404, "check the exact project, release, environment, service, UUID, and architecture") => {
388            Some("check the exact project, release, environment, service, UUID, and architecture")
389        }
390        (404, "check the exact project and upload scope") => {
391            Some("check the exact project and upload scope")
392        }
393        (404, "start the native debug artifact upload session again with the same manifest") => {
394            Some("start the native debug artifact upload session again with the same manifest")
395        }
396        (405, "use the supported native debug-artifact request method") => {
397            Some("use the supported native debug-artifact request method")
398        }
399        (408, "retry the same native debug-artifact request") => {
400            Some("retry the same native debug-artifact request")
401        }
402        (
403            413,
404            "reduce the native debug-artifact upload below the documented size limits and retry",
405        ) => Some(
406            "reduce the native debug-artifact upload below the documented size limits and retry",
407        ),
408        (
409            422,
410            "send manifest and debug_file_N multipart parts from LogBrew Apple release tooling",
411        ) => Some(
412            "send manifest and debug_file_N multipart parts from LogBrew Apple release tooling",
413        ),
414        (422, "check the native debug-artifact manifest and retry") => {
415            Some("check the native debug-artifact manifest and retry")
416        }
417        (422, "retry only the missing native debug artifact chunk with its exact digest") => {
418            Some("retry only the missing native debug artifact chunk with its exact digest")
419        }
420        (
421            422,
422            "wait briefly, then retry the same upload completion or verify the exact artifact lookup",
423        ) => Some(
424            "wait briefly, then retry the same upload completion or verify the exact artifact lookup",
425        ),
426        (422, "check the native debug-artifact manifest and upload session, then retry") => {
427            Some("check the native debug-artifact manifest and upload session, then retry")
428        }
429        (429 | 500..=599, "retry the same native debug-artifact request later") => {
430            Some("retry the same native debug-artifact request later")
431        }
432        (429 | 500..=599, "retry the same native debug-artifact command later") => {
433            Some("retry the same native debug-artifact command later")
434        }
435        _ => None,
436    }
437}
438
439/// Writes a runtime error for human readers.
440fn write_human_runtime_error<W: std::io::Write>(
441    error: &RuntimeError,
442    output: &mut W,
443) -> Result<(), std::io::Error> {
444    match error {
445        RuntimeError::StatusUnavailable {
446            api_url,
447            status_code,
448            body,
449            auth_label,
450            message,
451            ..
452        } => {
453            writeln!(output, "LogBrew API unreachable.")?;
454            writeln!(output, "API: {api_url}")?;
455            writeln!(output, "Auth: {auth_label}")?;
456            if let Some(status_code) = status_code {
457                writeln!(output, "Status: {status_code}")?;
458            }
459            if let Some(body) = body.as_ref().filter(|body| !body.is_empty()) {
460                writeln!(output, "Body: {body}")?;
461            } else {
462                writeln!(output, "Reason: {message}")?;
463            }
464            writeln!(output, "Next: {STATUS_UNAVAILABLE_NEXT_STEP}")?;
465            Ok(())
466        }
467        RuntimeError::Api {
468            status,
469            body,
470            auth_label,
471            ..
472        } => {
473            let api_details = ApiErrorDetails::parse(body);
474            writeln!(output, "{error}")?;
475            if let Some(code) = api_details.code.as_deref() {
476                writeln!(output, "Code: {code}")?;
477            }
478            writeln!(output, "Auth: {auth_label}")?;
479            writeln!(output, "Next: {}", api_next_step(*status, &api_details))
480        }
481        RuntimeError::Cli(_)
482        | RuntimeError::Io(_)
483        | RuntimeError::Http(_)
484        | RuntimeError::MissingToken
485        | RuntimeError::InvestigationResponseInvalid
486        | RuntimeError::NativeDebugArtifactInvalid
487        | RuntimeError::NativeDebugResponseInvalid
488        | RuntimeError::NativeDebugVerificationFailed
489        | RuntimeError::Unavailable { .. } => {
490            writeln!(output, "{error}")?;
491            writeln!(output, "Next: {}", runtime_error_next_step(error))?;
492            Ok(())
493        }
494    }
495}
496
497/// Builds a JSON runtime error body for agents.
498fn runtime_error_json(error: &RuntimeError) -> serde_json::Value {
499    match error {
500        RuntimeError::MissingToken
501        | RuntimeError::Unavailable { .. }
502        | RuntimeError::InvestigationResponseInvalid
503        | RuntimeError::NativeDebugArtifactInvalid
504        | RuntimeError::NativeDebugResponseInvalid
505        | RuntimeError::NativeDebugVerificationFailed
506        | RuntimeError::Io(_)
507        | RuntimeError::Http(_) => serde_json::json!({
508            "ok": false,
509            "error": runtime_error_code(error),
510            "message": error.to_string(),
511            "next": runtime_error_next_step(error),
512        }),
513        RuntimeError::Api {
514            status,
515            body,
516            auth_source,
517            ..
518        } => {
519            let api_details = ApiErrorDetails::parse(body);
520            let next = api_next_step(*status, &api_details);
521            serde_json::json!({
522                "ok": false,
523                "error": runtime_error_code(error),
524                "message": error.to_string(),
525                "status": status,
526                "body": body,
527                "api_error": api_details.error.as_deref(),
528                "api_code": api_details.code.as_deref(),
529                "api_next": api_details.next.as_deref(),
530                "auth_source": auth_source,
531                "next": next,
532            })
533        }
534        RuntimeError::StatusUnavailable {
535            api_url,
536            status_code,
537            body,
538            authenticated,
539            auth_source,
540            message,
541            ..
542        } => serde_json::json!({
543            "ok": false,
544            "error": runtime_error_code(error),
545            "status": "unreachable",
546            "status_code": status_code,
547            "body": body,
548            "api_url": api_url,
549            "authenticated": authenticated,
550            "auth_source": auth_source,
551            "message": message,
552            "next": runtime_error_next_step(error),
553        }),
554        RuntimeError::Cli(error) => serde_json::json!({
555            "ok": false,
556            "error": cli_error_code(error),
557            "message": error.to_string(),
558            "next": cli_error_next_step(error),
559        }),
560    }
561}
562
563/// Returns a stable machine-readable parse error code.
564const fn cli_error_code(error: &CliError) -> &'static str {
565    match error {
566        CliError::UnknownCommand | CliError::UnknownCommandName { .. } => "unknown_command",
567        CliError::MissingArgument { .. } => "missing_argument",
568        CliError::MissingFlagValue { .. } => "missing_flag_value",
569        CliError::DuplicateFlag { .. } => "duplicate_flag",
570        CliError::UnexpectedArgument { .. } => "unexpected_argument",
571        CliError::UnknownFlag { .. } => "unknown_flag",
572        CliError::UnsupportedFlag { .. } => "unsupported_flag",
573        CliError::UnknownResource { .. } => "unknown_resource",
574        CliError::UnknownStatus(_) => "unknown_status",
575        CliError::UnknownTraceStatus(_) => "unknown_trace_status",
576        CliError::UnknownLogLevel(_) => "unknown_log_level",
577        CliError::InvalidLimit(_) => "invalid_limit",
578        CliError::InvalidMinDuration(_) => "invalid_min_duration",
579        CliError::UnknownPagination => "unknown_pagination",
580        CliError::InvalidActionCursor(_) => "invalid_action_cursor",
581        CliError::InvalidLogCursor(_) => "invalid_log_cursor",
582        CliError::InvalidIssueCursor(_) => "invalid_issue_cursor",
583        CliError::InvalidSupportCursor(_) => "invalid_support_cursor",
584        CliError::UnknownSupportCategory => "unknown_support_category",
585        CliError::InvalidSupportTicketId => "invalid_support_ticket_id",
586        CliError::InvalidSupportRetryKey => "invalid_support_retry_key",
587        CliError::InvalidSupportContextReply => "invalid_support_context_reply",
588        CliError::InvalidSupportContextCommand => "invalid_support_context_command",
589        CliError::InvalidSupportContext => "invalid_support_context",
590        CliError::InvalidInvestigationCommand => "invalid_investigation_command",
591        CliError::InvalidDoctorCommand => "invalid_doctor_command",
592        CliError::InvalidProjectCreateCommand => "invalid_project_create_command",
593        CliError::InvalidProjectArchiveCommand => "invalid_project_archive_command",
594        CliError::InvalidProjectsCommand => "invalid_projects_command",
595        CliError::InvalidLoginProvider => "invalid_login_provider",
596        CliError::InvalidUsageCommand => "invalid_usage_command",
597        CliError::InvalidNativeDebugCommand | CliError::InvalidNativeDebugIdentity => {
598            "invalid_native_debug_command"
599        }
600        CliError::InvalidSetupSource(_) => "invalid_setup_source",
601    }
602}
603
604/// Returns the next step for a parse error.
605const fn cli_error_next_step(error: &CliError) -> &'static str {
606    match error {
607        CliError::InvalidLimit(_) => "use --limit with a positive whole number",
608        CliError::InvalidMinDuration(_) => "use --min-duration-ms with a non-negative whole number",
609        CliError::UnknownPagination
610        | CliError::InvalidActionCursor(_)
611        | CliError::InvalidLogCursor(_)
612        | CliError::InvalidIssueCursor(_)
613        | CliError::InvalidSupportCursor(_) => {
614            "use --pagination cursor alone for the first page, then use --cursor-time and --cursor-id together from next_cursor"
615        }
616        CliError::UnknownSupportCategory => {
617            "use sdk_install_failure, ingest_failure, auth_failure, project_setup, dashboard_issue, docs_confusion, cli_issue, mobile_issue, billing_question, or other"
618        }
619        CliError::InvalidSupportTicketId => {
620            "use the ticket_id returned by logbrew support create or list"
621        }
622        CliError::InvalidSupportRetryKey => {
623            "use --retry-key with 1 to 128 visible ASCII characters and reuse it only for an exact retry"
624        }
625        CliError::InvalidSupportContextReply => {
626            "use support reply <ticket_id> --context <text> --retry-key <key>"
627        }
628        CliError::InvalidSupportContextCommand => {
629            "use support context <ticket_id> with optional --json"
630        }
631        CliError::InvalidSupportContext => {
632            "use --context with 1 to 4000 characters after trimming whitespace"
633        }
634        CliError::InvalidInvestigationCommand => {
635            "use logbrew investigate issue <issue_id> with optional --json"
636        }
637        CliError::InvalidDoctorCommand => {
638            "use logbrew doctor --project <project_id> with optional --json"
639        }
640        CliError::InvalidProjectCreateCommand => {
641            "use logbrew projects create <name> --ingest-key-file <path> with optional --runtime, --environment, --abandon-retry, and --json"
642        }
643        CliError::InvalidProjectArchiveCommand => {
644            "use logbrew projects archive <project_id> --yes with optional --json"
645        }
646        CliError::InvalidProjectsCommand => {
647            "use logbrew projects with optional --json, or logbrew projects --help"
648        }
649        CliError::InvalidLoginProvider => "use --provider github, gitlab, or bitbucket",
650        CliError::InvalidUsageCommand => "use logbrew usage with optional --json",
651        CliError::InvalidNativeDebugCommand => {
652            "use logbrew debug-artifacts upload <path> --project <project_id> --release <release> --environment <environment> --service <service> with optional --expect-image-uuid, --dry-run, and --json"
653        }
654        CliError::InvalidNativeDebugIdentity => {
655            "use a UUID in 8-4-4-4-12 form and architecture arm64, arm64e, or x86_64"
656        }
657        CliError::InvalidSetupSource(_) => "use --source api, cli, or sdk",
658        CliError::MissingArgument { next, .. }
659        | CliError::MissingFlagValue { next, .. }
660        | CliError::DuplicateFlag { next, .. }
661        | CliError::UnexpectedArgument { next, .. }
662        | CliError::UnsupportedFlag { next, .. }
663        | CliError::UnknownFlag { next, .. }
664        | CliError::UnknownResource { next, .. }
665        | CliError::UnknownCommandName { next, .. } => next,
666        CliError::UnknownCommand => "run logbrew --help",
667        CliError::UnknownStatus(_) => ISSUE_STATUS_VALUES_NEXT_STEP,
668        CliError::UnknownTraceStatus(_) => "use --status error or --status ok",
669        CliError::UnknownLogLevel(_) => "use one of info, warning, error, critical",
670    }
671}
672
673/// Returns a stable machine-readable runtime error code.
674const fn runtime_error_code(error: &RuntimeError) -> &'static str {
675    match error {
676        RuntimeError::Cli(error) => cli_error_code(error),
677        RuntimeError::Io(_) => "io_error",
678        RuntimeError::Http(_) => "http_error",
679        RuntimeError::MissingToken => "not_logged_in",
680        RuntimeError::Api { .. } => "api_error",
681        RuntimeError::StatusUnavailable { .. } => "status_unreachable",
682        RuntimeError::Unavailable { .. } => "unavailable",
683        RuntimeError::InvestigationResponseInvalid => "investigation_response_invalid",
684        RuntimeError::NativeDebugArtifactInvalid => "native_debug_artifact_invalid",
685        RuntimeError::NativeDebugResponseInvalid => "native_debug_response_invalid",
686        RuntimeError::NativeDebugVerificationFailed => "native_debug_verification_failed",
687    }
688}
689
690/// Next step for failed `status` reachability checks.
691const STATUS_UNAVAILABLE_NEXT_STEP: &str = "check LOGBREW_API_URL or network";
692
693/// Parsed public API error details.
694#[derive(Debug, Clone, Default, PartialEq, Eq)]
695struct ApiErrorDetails {
696    /// Human-readable backend error message.
697    error: Option<String>,
698    /// Stable backend error code.
699    code: Option<String>,
700    /// Backend-provided recovery step.
701    next: Option<String>,
702}
703
704impl ApiErrorDetails {
705    /// Parses additive backend error fields from an API response body.
706    fn parse(body: &str) -> Self {
707        let Ok(value) = serde_json::from_str::<serde_json::Value>(body) else {
708            return Self::default();
709        };
710
711        Self {
712            error: json_string_field(&value, "error"),
713            code: json_string_field(&value, "code"),
714            next: json_string_field(&value, "next"),
715        }
716    }
717}
718
719/// Extracts a non-empty string field from a JSON object.
720fn json_string_field(value: &serde_json::Value, key: &str) -> Option<String> {
721    value
722        .get(key)
723        .and_then(serde_json::Value::as_str)
724        .map(str::trim)
725        .filter(|value| !value.is_empty())
726        .map(ToOwned::to_owned)
727}
728
729/// Returns a useful next step for runtime errors when one is known.
730fn runtime_error_next_step(error: &RuntimeError) -> Cow<'static, str> {
731    match error {
732        RuntimeError::Api { status, body, .. } => {
733            let api_details = ApiErrorDetails::parse(body);
734            api_next_step(*status, &api_details)
735        }
736        RuntimeError::Cli(_)
737        | RuntimeError::Io(_)
738        | RuntimeError::Http(_)
739        | RuntimeError::MissingToken
740        | RuntimeError::InvestigationResponseInvalid
741        | RuntimeError::NativeDebugArtifactInvalid
742        | RuntimeError::NativeDebugResponseInvalid
743        | RuntimeError::NativeDebugVerificationFailed
744        | RuntimeError::StatusUnavailable { .. }
745        | RuntimeError::Unavailable { .. } => {
746            Cow::Borrowed(fallback_runtime_error_next_step(error))
747        }
748    }
749}
750
751/// Returns the API next step, preferring backend guidance when available.
752fn api_next_step(status: u16, api_details: &ApiErrorDetails) -> Cow<'static, str> {
753    api_details.next.as_ref().map_or_else(
754        || Cow::Borrowed(fallback_api_next_step(status)),
755        |next| Cow::Owned(next.clone()),
756    )
757}
758
759/// Returns the CLI fallback next step for an API status.
760const fn fallback_api_next_step(status: u16) -> &'static str {
761    match status {
762        401 | 403 => "run logbrew login",
763        400 | 422 => "check command arguments or filters",
764        404 => "check the resource id or filters",
765        429 => "retry later",
766        500..=599 => "check LOGBREW_API_URL or retry later",
767        _ => "check command arguments or retry later",
768    }
769}
770
771/// Returns a useful fallback next step for runtime errors when one is known.
772const fn fallback_runtime_error_next_step(error: &RuntimeError) -> &'static str {
773    match error {
774        RuntimeError::Cli(error) => cli_error_next_step(error),
775        RuntimeError::MissingToken => "run logbrew login",
776        RuntimeError::Api { status, .. } => fallback_api_next_step(*status),
777        RuntimeError::StatusUnavailable { .. } | RuntimeError::Http(_) => {
778            STATUS_UNAVAILABLE_NEXT_STEP
779        }
780        RuntimeError::Unavailable { next, .. } => next,
781        RuntimeError::InvestigationResponseInvalid => {
782            "retry the issue investigation; if it repeats, report the public response contract"
783        }
784        RuntimeError::NativeDebugArtifactInvalid => {
785            "provide one validated Apple dSYM, ZIP, or Mach-O object matching every --expect-image-uuid value"
786        }
787        RuntimeError::NativeDebugResponseInvalid => {
788            "retry the native debug-artifact request; if it repeats, report the public response contract"
789        }
790        RuntimeError::NativeDebugVerificationFailed => {
791            "retry exact native debug-artifact lookup before using native symbolication"
792        }
793        RuntimeError::Io(_) => "check local files and permissions",
794    }
795}