Skip to main content

atm_error/
error_codes.rs

1//! Stable ATM-owned error-code registry.
2
3use std::fmt;
4use std::str::FromStr;
5
6use serde::{Deserialize, Deserializer, Serialize};
7
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct UnknownAtmErrorCode(pub String);
10
11impl fmt::Display for UnknownAtmErrorCode {
12    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
13        write!(f, "unknown ATM error code: {}", self.0)
14    }
15}
16
17impl std::error::Error for UnknownAtmErrorCode {}
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20pub enum AtmErrorCode {
21    ConfigHomeUnavailable,
22    AtmHomeUnresolved,
23    ConfigParseFailed,
24    ConfigRetiredHookMembersKey,
25    ConfigRetiredLegacyHookKeys,
26    ConfigTeamParseFailed,
27    ConfigTeamMissing,
28    IdentityUnavailable,
29    IdentityInvalid,
30    IdentityConflict,
31    MemberAlreadyExists,
32    MemberNotFound,
33    DaemonUnavailable,
34    RuntimeRootInvalid,
35    RuntimeBootstrapRefused,
36    SocketOverrideForbidden,
37    DaemonMayHaveExecuted,
38    DaemonLifecycleWedge,
39    DaemonLaunchGateRejected,
40    DaemonServingStateRejected,
41    DaemonStaleOwnerRecoveryFailed,
42    DaemonAutoStartFailed,
43    DaemonConnectionSaturated,
44    RemoteDeliveryUnconfirmed,
45    /// The daemon launch argument did not name a supported peer-wire mode.
46    PeerWireModeInvalid,
47    /// A non-launch source attempted to select the daemon peer-wire mode.
48    PeerWireModeSourceForbidden,
49    /// Plaintext diagnostic mode was asked to satisfy authenticated peer work.
50    PeerWirePlaintextAuthenticationRequired,
51    PeerConfigValidationFailed,
52    CertificateOperationFailed,
53    /// A configured peer did not satisfy exact mTLS hostname or pin authentication.
54    PeerAuthenticationFailed,
55    /// A bounded peer transport operation did not finish before its deadline.
56    TransportTimeout,
57    /// A peer transport handshake failed outside configuration or pin authentication.
58    TransportProtocolFailed,
59    BindPreflightFailed,
60    ClientDaemonVersionIncompatible,
61    DaemonAdvisorySessionAlreadyRegistered,
62    DaemonAdvisorySessionNotRegistered,
63    DaemonAdvisorySessionCleanupFailed,
64    AddressParseFailed,
65    TeamUnavailable,
66    TeamInvalid,
67    TeamNotFound,
68    AgentNotFound,
69    MailboxReadFailed,
70    MailboxWriteFailed,
71    MailboxLockFailed,
72    MailboxLockReadOnlyFilesystem,
73    MailboxLockTimeout,
74    InternalError,
75    MessageValidationFailed,
76    /// Search is intentionally local-only until a separately authorized peer
77    /// query protocol exists.
78    SearchLocalOnly,
79    LocalHttpCapabilityInvalid,
80    LocalHttpEndpointSchemaUnsupported,
81    LocalHttpEndpointMissing,
82    LocalHttpEndpointNonLoopback,
83    LocalHttpRuntimeDirectoryMissing,
84    LocalHttpCapabilityRevoked,
85    MessageIdConflict,
86    SelfAddressedSendInvalid,
87    EmptyNudgeTemplateBody,
88    CallerContextRequestInvalid,
89    /// Template catalog content must be strict UTF-8 before any row is admitted.
90    TemplateContentNotUtf8,
91    /// A template passed to the no-include render operation references another template.
92    DecomposedTemplateIncludeForbidden,
93    TemplateLoadFailed,
94    TemplateHashApiFailed,
95    /// The upstream template inspection parser rejected frontmatter or body/directive syntax.
96    TemplateInspectionParseFailed,
97    TemplateRequiredVariableMissing,
98    TemplateRenderVerificationFailed,
99    TemplateIncludeUnresolved,
100    TemplateClassificationInvalid,
101    TemplateWorkflowInvalid,
102    TemplateWorkflowValueInvalid,
103    TemplateTagReserved,
104    /// A bounded local workflow query or lifecycle projection is invalid.
105    WorkflowQueryInvalid,
106    /// Runtime telemetry configuration failed validation and was disabled.
107    WorkflowTelemetryConfigInvalid,
108    /// A best-effort workflow telemetry record was dropped.
109    WorkflowTelemetryDropped,
110    SerializationFailed,
111    FilePolicyRejected,
112    FileReferenceRewriteFailed,
113    WaitTimeout,
114    AckInvalidState,
115    ClearInvalidState,
116    ObservabilityEmitFailed,
117    ObservabilityQueryFailed,
118    ObservabilityFollowFailed,
119    ObservabilityHealthFailed,
120    ObservabilityBootstrapFailed,
121    ObservabilityHealthOk,
122    WarningInvalidTeamMemberSkipped,
123    WarningMailboxRecordSkipped,
124    WarningMalformedAtmFieldIgnored,
125    WarningObservabilityHealthDegraded,
126    WarningSqliteHealthDegraded,
127    WarningOriginInboxEntrySkipped,
128    WarningMissingTeamConfigFallback,
129    WarningSendAlertStateDegraded,
130    WarningIdentityDrift,
131    WarningRosterDrift,
132    WarningBaselineMemberMissing,
133    WarningRestoreInProgress,
134    WarningStaleMailboxLock,
135    WarningHookSkipped,
136    WarningHookExecutionFailed,
137    /// A roster contains explicit local members using both supported backends.
138    RosterMixedLocalBackend,
139    /// A configured Herdr member could not be observed by the presence probe.
140    HerdrAgentNotVisible,
141    PostSendPaneMissing,
142    PostSendTmuxSendFailed,
143    PostSendHerdrPromptFailed,
144    HerdrPromptFailed,
145    HerdrUnavailable,
146    PostSendGraftUnavailable,
147    GraftReceiverAlreadyActive,
148    /// The stored graft receiver lease is owned by a different generation
149    /// than the one making the request (register/refresh/unregister).
150    GraftReceiverNotOwner,
151    /// A receiver refresh found no durable lease row and must re-announce.
152    GraftReceiverNotRegistered,
153    PostSendAdvisoryDeliveryFailed,
154    TestFakeTransportInjectionFailed,
155    HelpTopicNotFound,
156}
157
158impl AtmErrorCode {
159    pub fn as_str(self) -> &'static str {
160        if let Some(value) = self.config_or_identity_str() {
161            return value;
162        }
163        if let Some(value) = self.daemon_or_address_str() {
164            return value;
165        }
166        if let Some(value) = self.mailbox_or_validation_str() {
167            return value;
168        }
169        if let Some(value) = self.observability_or_warning_str() {
170            return value;
171        }
172        self.post_send_or_misc_str()
173    }
174
175    fn config_or_identity_str(self) -> Option<&'static str> {
176        Some(match self {
177            Self::ConfigHomeUnavailable => "ATM_CONFIG_HOME_UNAVAILABLE",
178            Self::AtmHomeUnresolved => "ATM_HOME_UNRESOLVED",
179            Self::ConfigParseFailed => "ATM_CONFIG_PARSE_FAILED",
180            Self::ConfigRetiredHookMembersKey => "ATM_CONFIG_RETIRED_HOOK_MEMBERS_KEY",
181            Self::ConfigRetiredLegacyHookKeys => "ATM_CONFIG_RETIRED_LEGACY_HOOK_KEYS",
182            Self::ConfigTeamParseFailed => "ATM_CONFIG_TEAM_PARSE_FAILED",
183            Self::ConfigTeamMissing => "ATM_CONFIG_TEAM_MISSING",
184            Self::IdentityUnavailable => "ATM_IDENTITY_UNAVAILABLE",
185            Self::IdentityInvalid => "ATM_IDENTITY_INVALID",
186            Self::IdentityConflict => "ATM_IDENTITY_CONFLICT",
187            Self::MemberAlreadyExists => "ATM_MEMBER_ALREADY_EXISTS",
188            Self::MemberNotFound => "ATM_MEMBER_NOT_FOUND",
189            _ => return None,
190        })
191    }
192
193    fn daemon_or_address_str(self) -> Option<&'static str> {
194        Some(match self {
195            Self::DaemonUnavailable => "ATM_DAEMON_UNAVAILABLE",
196            Self::RuntimeRootInvalid => "ATM_RUNTIME_ROOT_INVALID",
197            Self::RuntimeBootstrapRefused => "ATM_RUNTIME_BOOTSTRAP_REFUSED",
198            Self::SocketOverrideForbidden => "ATM_SOCKET_OVERRIDE_FORBIDDEN",
199            Self::DaemonMayHaveExecuted => "ATM_DAEMON_MAY_HAVE_EXECUTED",
200            Self::DaemonLifecycleWedge => "ATM_DAEMON_LIFECYCLE_WEDGE",
201            Self::DaemonLaunchGateRejected => "ATM_DAEMON_LAUNCH_GATE_REJECTED",
202            Self::DaemonServingStateRejected => "ATM_DAEMON_SERVING_STATE_REJECTED",
203            Self::DaemonStaleOwnerRecoveryFailed => "ATM_DAEMON_STALE_OWNER_RECOVERY_FAILED",
204            Self::DaemonAutoStartFailed => "ATM_DAEMON_AUTO_START_FAILED",
205            Self::DaemonConnectionSaturated => "ATM_DAEMON_CONNECTION_SATURATED",
206            Self::RemoteDeliveryUnconfirmed => "REMOTE_DELIVERY_UNCONFIRMED",
207            Self::PeerWireModeInvalid => "ATM_PEER_WIRE_MODE_INVALID",
208            Self::PeerWireModeSourceForbidden => "ATM_PEER_WIRE_MODE_SOURCE_FORBIDDEN",
209            Self::PeerWirePlaintextAuthenticationRequired => {
210                "ATM_PEER_WIRE_PLAINTEXT_AUTHENTICATION_REQUIRED"
211            }
212            Self::PeerConfigValidationFailed => "ATM_PEER_CONFIG_VALIDATION_FAILED",
213            Self::CertificateOperationFailed => "ATM_CERTIFICATE_OPERATION_FAILED",
214            Self::PeerAuthenticationFailed => "ATM_PEER_AUTHENTICATION_FAILED",
215            Self::TransportTimeout => "ATM_TRANSPORT_TIMEOUT",
216            Self::TransportProtocolFailed => "ATM_TRANSPORT_PROTOCOL_FAILED",
217            Self::BindPreflightFailed => "ATM_BIND_PREFLIGHT_FAILED",
218            Self::ClientDaemonVersionIncompatible => "ATM_CLIENT_DAEMON_VERSION_INCOMPATIBLE",
219            Self::DaemonAdvisorySessionAlreadyRegistered => {
220                "ATM_DAEMON_ADVISORY_SESSION_ALREADY_REGISTERED"
221            }
222            Self::DaemonAdvisorySessionNotRegistered => {
223                "ATM_DAEMON_ADVISORY_SESSION_NOT_REGISTERED"
224            }
225            Self::DaemonAdvisorySessionCleanupFailed => {
226                "ATM_DAEMON_ADVISORY_SESSION_CLEANUP_FAILED"
227            }
228            Self::AddressParseFailed => "ATM_ADDRESS_PARSE_FAILED",
229            Self::TeamUnavailable => "ATM_TEAM_UNAVAILABLE",
230            Self::TeamInvalid => "ATM_TEAM_INVALID",
231            Self::TeamNotFound => "ATM_TEAM_NOT_FOUND",
232            Self::AgentNotFound => "ATM_AGENT_NOT_FOUND",
233            _ => return None,
234        })
235    }
236
237    fn mailbox_or_validation_str(self) -> Option<&'static str> {
238        Some(match self {
239            Self::MailboxReadFailed => "ATM_MAILBOX_READ_FAILED",
240            Self::MailboxWriteFailed => "ATM_MAILBOX_WRITE_FAILED",
241            Self::MailboxLockFailed => "ATM_MAILBOX_LOCK_FAILED",
242            Self::MailboxLockReadOnlyFilesystem => "ATM_MAILBOX_LOCK_READ_ONLY_FILESYSTEM",
243            Self::MailboxLockTimeout => "ATM_MAILBOX_LOCK_TIMEOUT",
244            Self::InternalError => "ATM_INTERNAL_ERROR",
245            Self::MessageValidationFailed => "ATM_MESSAGE_VALIDATION_FAILED",
246            Self::SearchLocalOnly => "ATM_SEARCH_LOCAL_ONLY",
247            Self::LocalHttpCapabilityInvalid => "ATM_LOCAL_HTTP_CAPABILITY_INVALID",
248            Self::LocalHttpEndpointSchemaUnsupported => {
249                "ATM_LOCAL_HTTP_ENDPOINT_SCHEMA_UNSUPPORTED"
250            }
251            Self::LocalHttpEndpointMissing => "ATM_LOCAL_HTTP_ENDPOINT_MISSING",
252            Self::LocalHttpEndpointNonLoopback => "ATM_LOCAL_HTTP_ENDPOINT_NON_LOOPBACK",
253            Self::LocalHttpRuntimeDirectoryMissing => "ATM_LOCAL_HTTP_RUNTIME_DIRECTORY_MISSING",
254            Self::LocalHttpCapabilityRevoked => "ATM_LOCAL_HTTP_CAPABILITY_REVOKED",
255            Self::MessageIdConflict => "ATM_MESSAGE_ID_CONFLICT",
256            Self::SelfAddressedSendInvalid => "ATM_SELF_ADDRESSED_SEND_INVALID",
257            Self::EmptyNudgeTemplateBody => "ATM_NUDGE_TEMPLATE_BODY_EMPTY",
258            Self::CallerContextRequestInvalid => "ATM_CALLER_CONTEXT_REQUEST_INVALID",
259            Self::TemplateContentNotUtf8 => "TEMPLATE_CONTENT_NOT_UTF8",
260            Self::DecomposedTemplateIncludeForbidden => "DECOMPOSED_TEMPLATE_INCLUDE_FORBIDDEN",
261            Self::TemplateLoadFailed => "TEMPLATE_LOAD_FAILED",
262            Self::TemplateHashApiFailed => "TEMPLATE_HASH_API_FAILED",
263            Self::TemplateInspectionParseFailed => "TEMPLATE_INSPECTION_PARSE_FAILED",
264            Self::TemplateRequiredVariableMissing => "TEMPLATE_REQUIRED_VARIABLE_MISSING",
265            Self::TemplateRenderVerificationFailed => "TEMPLATE_RENDER_VERIFICATION_FAILED",
266            Self::TemplateIncludeUnresolved => "TEMPLATE_INCLUDE_UNRESOLVED",
267            Self::TemplateClassificationInvalid => "TEMPLATE_CLASSIFICATION_INVALID",
268            Self::TemplateWorkflowInvalid => "TEMPLATE_WORKFLOW_INVALID",
269            Self::TemplateWorkflowValueInvalid => "TEMPLATE_WORKFLOW_VALUE_INVALID",
270            Self::TemplateTagReserved => "TEMPLATE_TAG_RESERVED",
271            Self::WorkflowQueryInvalid => "ATM_WORKFLOW_QUERY_INVALID",
272            Self::WorkflowTelemetryConfigInvalid => "ATM_WORKFLOW_TELEMETRY_CONFIG_INVALID",
273            Self::WorkflowTelemetryDropped => "ATM_WORKFLOW_TELEMETRY_DROPPED",
274            Self::SerializationFailed => "ATM_SERIALIZATION_FAILED",
275            Self::FilePolicyRejected => "ATM_FILE_POLICY_REJECTED",
276            Self::FileReferenceRewriteFailed => "ATM_FILE_REFERENCE_REWRITE_FAILED",
277            Self::WaitTimeout => "ATM_WAIT_TIMEOUT",
278            Self::AckInvalidState => "ATM_ACK_INVALID_STATE",
279            Self::ClearInvalidState => "ATM_CLEAR_INVALID_STATE",
280            _ => return None,
281        })
282    }
283
284    fn observability_or_warning_str(self) -> Option<&'static str> {
285        Some(match self {
286            Self::ObservabilityEmitFailed => "ATM_OBSERVABILITY_EMIT_FAILED",
287            Self::ObservabilityQueryFailed => "ATM_OBSERVABILITY_QUERY_FAILED",
288            Self::ObservabilityFollowFailed => "ATM_OBSERVABILITY_FOLLOW_FAILED",
289            Self::ObservabilityHealthFailed => "ATM_OBSERVABILITY_HEALTH_FAILED",
290            Self::ObservabilityBootstrapFailed => "ATM_OBSERVABILITY_BOOTSTRAP_FAILED",
291            Self::ObservabilityHealthOk => "ATM_OBSERVABILITY_HEALTH_OK",
292            Self::WarningInvalidTeamMemberSkipped => "ATM_WARNING_INVALID_TEAM_MEMBER_SKIPPED",
293            Self::WarningMailboxRecordSkipped => "ATM_WARNING_MAILBOX_RECORD_SKIPPED",
294            Self::WarningMalformedAtmFieldIgnored => "ATM_WARNING_MALFORMED_ATM_FIELD_IGNORED",
295            Self::WarningObservabilityHealthDegraded => "ATM_WARNING_OBSERVABILITY_HEALTH_DEGRADED",
296            Self::WarningSqliteHealthDegraded => "ATM_WARNING_SQLITE_HEALTH_DEGRADED",
297            Self::WarningOriginInboxEntrySkipped => "ATM_WARNING_ORIGIN_INBOX_ENTRY_SKIPPED",
298            Self::WarningMissingTeamConfigFallback => "ATM_WARNING_MISSING_TEAM_CONFIG_FALLBACK",
299            Self::WarningSendAlertStateDegraded => "ATM_WARNING_SEND_ALERT_STATE_DEGRADED",
300            Self::WarningIdentityDrift => "ATM_WARNING_IDENTITY_DRIFT",
301            Self::WarningRosterDrift => "ATM_WARNING_ROSTER_DRIFT",
302            Self::WarningBaselineMemberMissing => "ATM_WARNING_BASELINE_MEMBER_MISSING",
303            Self::WarningRestoreInProgress => "ATM_WARNING_RESTORE_IN_PROGRESS",
304            Self::WarningStaleMailboxLock => "ATM_WARNING_STALE_MAILBOX_LOCK",
305            Self::WarningHookSkipped => "ATM_WARNING_HOOK_SKIPPED",
306            Self::WarningHookExecutionFailed => "ATM_WARNING_HOOK_EXECUTION_FAILED",
307            Self::RosterMixedLocalBackend => "ATM_ROSTER_MIXED_LOCAL_BACKEND",
308            Self::HerdrAgentNotVisible => "ATM_HERDR_AGENT_NOT_VISIBLE",
309            _ => return None,
310        })
311    }
312
313    fn post_send_or_misc_str(self) -> &'static str {
314        match self {
315            Self::PostSendPaneMissing => "ATM_POST_SEND_PANE_MISSING",
316            Self::PostSendTmuxSendFailed => "ATM_POST_SEND_TMUX_SEND_FAILED",
317            Self::PostSendHerdrPromptFailed => "ATM_POST_SEND_HERDR_PROMPT_FAILED",
318            Self::HerdrPromptFailed => "ATM_HERDR_PROMPT_FAILED",
319            Self::HerdrUnavailable => "ATM_HERDR_UNAVAILABLE",
320            Self::PostSendGraftUnavailable => "ATM_POST_SEND_GRAFT_UNAVAILABLE",
321            Self::GraftReceiverAlreadyActive => "ATM_GRAFT_RECEIVER_ALREADY_ACTIVE",
322            Self::GraftReceiverNotOwner => "ATM_GRAFT_RECEIVER_NOT_OWNER",
323            Self::GraftReceiverNotRegistered => "ATM_GRAFT_RECEIVER_NOT_REGISTERED",
324            Self::PostSendAdvisoryDeliveryFailed => "ATM_POST_SEND_ADVISORY_DELIVERY_FAILED",
325            Self::TestFakeTransportInjectionFailed => "ATM_TEST_FAKE_TRANSPORT_INJECTION_FAILED",
326            Self::HelpTopicNotFound => "ATM_HELP_TOPIC_NOT_FOUND",
327            _ => unreachable!("all AtmErrorCode variants must be covered by as_str helpers"),
328        }
329    }
330}
331
332impl FromStr for AtmErrorCode {
333    type Err = UnknownAtmErrorCode;
334
335    fn from_str(value: &str) -> Result<Self, Self::Err> {
336        parse_known_error_code(value).ok_or_else(|| UnknownAtmErrorCode(value.to_owned()))
337    }
338}
339
340fn parse_known_error_code(value: &str) -> Option<AtmErrorCode> {
341    parse_config_or_identity_code(value)
342        .or_else(|| parse_daemon_or_address_code(value))
343        .or_else(|| parse_mailbox_or_validation_code(value))
344        .or_else(|| parse_observability_or_warning_code(value))
345        .or_else(|| parse_post_send_or_misc_code(value))
346}
347
348fn parse_config_or_identity_code(value: &str) -> Option<AtmErrorCode> {
349    Some(match value {
350        "ATM_CONFIG_HOME_UNAVAILABLE" => AtmErrorCode::ConfigHomeUnavailable,
351        "ATM_HOME_UNRESOLVED" => AtmErrorCode::AtmHomeUnresolved,
352        "ATM_CONFIG_PARSE_FAILED" => AtmErrorCode::ConfigParseFailed,
353        "ATM_CONFIG_RETIRED_HOOK_MEMBERS_KEY" => AtmErrorCode::ConfigRetiredHookMembersKey,
354        "ATM_CONFIG_RETIRED_LEGACY_HOOK_KEYS" => AtmErrorCode::ConfigRetiredLegacyHookKeys,
355        "ATM_CONFIG_TEAM_PARSE_FAILED" => AtmErrorCode::ConfigTeamParseFailed,
356        "ATM_CONFIG_TEAM_MISSING" => AtmErrorCode::ConfigTeamMissing,
357        "ATM_IDENTITY_UNAVAILABLE" => AtmErrorCode::IdentityUnavailable,
358        "ATM_IDENTITY_INVALID" => AtmErrorCode::IdentityInvalid,
359        "ATM_IDENTITY_CONFLICT" => AtmErrorCode::IdentityConflict,
360        "ATM_MEMBER_ALREADY_EXISTS" => AtmErrorCode::MemberAlreadyExists,
361        "ATM_MEMBER_NOT_FOUND" => AtmErrorCode::MemberNotFound,
362        _ => return None,
363    })
364}
365
366fn parse_daemon_or_address_code(value: &str) -> Option<AtmErrorCode> {
367    Some(match value {
368        "ATM_DAEMON_UNAVAILABLE" => AtmErrorCode::DaemonUnavailable,
369        "ATM_RUNTIME_ROOT_INVALID" => AtmErrorCode::RuntimeRootInvalid,
370        "ATM_RUNTIME_BOOTSTRAP_REFUSED" => AtmErrorCode::RuntimeBootstrapRefused,
371        "ATM_SOCKET_OVERRIDE_FORBIDDEN" => AtmErrorCode::SocketOverrideForbidden,
372        "ATM_DAEMON_MAY_HAVE_EXECUTED" => AtmErrorCode::DaemonMayHaveExecuted,
373        "ATM_DAEMON_LIFECYCLE_WEDGE" => AtmErrorCode::DaemonLifecycleWedge,
374        "ATM_DAEMON_LAUNCH_GATE_REJECTED" => AtmErrorCode::DaemonLaunchGateRejected,
375        "ATM_DAEMON_SERVING_STATE_REJECTED" => AtmErrorCode::DaemonServingStateRejected,
376        "ATM_DAEMON_STALE_OWNER_RECOVERY_FAILED" => AtmErrorCode::DaemonStaleOwnerRecoveryFailed,
377        "ATM_DAEMON_AUTO_START_FAILED" => AtmErrorCode::DaemonAutoStartFailed,
378        "ATM_DAEMON_CONNECTION_SATURATED" => AtmErrorCode::DaemonConnectionSaturated,
379        "REMOTE_DELIVERY_UNCONFIRMED" => AtmErrorCode::RemoteDeliveryUnconfirmed,
380        "ATM_PEER_WIRE_MODE_INVALID" => AtmErrorCode::PeerWireModeInvalid,
381        "ATM_PEER_WIRE_MODE_SOURCE_FORBIDDEN" => AtmErrorCode::PeerWireModeSourceForbidden,
382        "ATM_PEER_WIRE_PLAINTEXT_AUTHENTICATION_REQUIRED" => {
383            AtmErrorCode::PeerWirePlaintextAuthenticationRequired
384        }
385        "ATM_PEER_CONFIG_VALIDATION_FAILED" => AtmErrorCode::PeerConfigValidationFailed,
386        "ATM_CERTIFICATE_OPERATION_FAILED" => AtmErrorCode::CertificateOperationFailed,
387        "ATM_PEER_AUTHENTICATION_FAILED" => AtmErrorCode::PeerAuthenticationFailed,
388        "ATM_TRANSPORT_TIMEOUT" => AtmErrorCode::TransportTimeout,
389        "ATM_TRANSPORT_PROTOCOL_FAILED" => AtmErrorCode::TransportProtocolFailed,
390        "ATM_BIND_PREFLIGHT_FAILED" => AtmErrorCode::BindPreflightFailed,
391        "ATM_CLIENT_DAEMON_VERSION_INCOMPATIBLE" => AtmErrorCode::ClientDaemonVersionIncompatible,
392        "ATM_DAEMON_ADVISORY_SESSION_ALREADY_REGISTERED" => {
393            AtmErrorCode::DaemonAdvisorySessionAlreadyRegistered
394        }
395        "ATM_DAEMON_ADVISORY_SESSION_NOT_REGISTERED" => {
396            AtmErrorCode::DaemonAdvisorySessionNotRegistered
397        }
398        "ATM_DAEMON_ADVISORY_SESSION_CLEANUP_FAILED" => {
399            AtmErrorCode::DaemonAdvisorySessionCleanupFailed
400        }
401        "ATM_ADDRESS_PARSE_FAILED" => AtmErrorCode::AddressParseFailed,
402        "ATM_TEAM_UNAVAILABLE" => AtmErrorCode::TeamUnavailable,
403        "ATM_TEAM_INVALID" => AtmErrorCode::TeamInvalid,
404        "ATM_TEAM_NOT_FOUND" => AtmErrorCode::TeamNotFound,
405        "ATM_AGENT_NOT_FOUND" => AtmErrorCode::AgentNotFound,
406        _ => return None,
407    })
408}
409
410fn parse_mailbox_or_validation_code(value: &str) -> Option<AtmErrorCode> {
411    Some(match value {
412        "ATM_MAILBOX_READ_FAILED" => AtmErrorCode::MailboxReadFailed,
413        "ATM_MAILBOX_WRITE_FAILED" => AtmErrorCode::MailboxWriteFailed,
414        "ATM_MAILBOX_LOCK_FAILED" => AtmErrorCode::MailboxLockFailed,
415        "ATM_MAILBOX_LOCK_READ_ONLY_FILESYSTEM" => AtmErrorCode::MailboxLockReadOnlyFilesystem,
416        "ATM_MAILBOX_LOCK_TIMEOUT" => AtmErrorCode::MailboxLockTimeout,
417        "ATM_INTERNAL_ERROR" => AtmErrorCode::InternalError,
418        "ATM_MESSAGE_VALIDATION_FAILED" => AtmErrorCode::MessageValidationFailed,
419        "ATM_SEARCH_LOCAL_ONLY" => AtmErrorCode::SearchLocalOnly,
420        "ATM_LOCAL_HTTP_CAPABILITY_INVALID" => AtmErrorCode::LocalHttpCapabilityInvalid,
421        "ATM_LOCAL_HTTP_ENDPOINT_SCHEMA_UNSUPPORTED" => {
422            AtmErrorCode::LocalHttpEndpointSchemaUnsupported
423        }
424        "ATM_LOCAL_HTTP_ENDPOINT_MISSING" => AtmErrorCode::LocalHttpEndpointMissing,
425        "ATM_LOCAL_HTTP_ENDPOINT_NON_LOOPBACK" => AtmErrorCode::LocalHttpEndpointNonLoopback,
426        "ATM_LOCAL_HTTP_RUNTIME_DIRECTORY_MISSING" => {
427            AtmErrorCode::LocalHttpRuntimeDirectoryMissing
428        }
429        "ATM_LOCAL_HTTP_CAPABILITY_REVOKED" => AtmErrorCode::LocalHttpCapabilityRevoked,
430        "ATM_MESSAGE_ID_CONFLICT" => AtmErrorCode::MessageIdConflict,
431        "ATM_SELF_ADDRESSED_SEND_INVALID" => AtmErrorCode::SelfAddressedSendInvalid,
432        "ATM_NUDGE_TEMPLATE_BODY_EMPTY" => AtmErrorCode::EmptyNudgeTemplateBody,
433        "ATM_CALLER_CONTEXT_REQUEST_INVALID" => AtmErrorCode::CallerContextRequestInvalid,
434        "TEMPLATE_CONTENT_NOT_UTF8" => AtmErrorCode::TemplateContentNotUtf8,
435        "DECOMPOSED_TEMPLATE_INCLUDE_FORBIDDEN" => AtmErrorCode::DecomposedTemplateIncludeForbidden,
436        "TEMPLATE_LOAD_FAILED" => AtmErrorCode::TemplateLoadFailed,
437        "TEMPLATE_HASH_API_FAILED" => AtmErrorCode::TemplateHashApiFailed,
438        "TEMPLATE_INSPECTION_PARSE_FAILED" => AtmErrorCode::TemplateInspectionParseFailed,
439        "TEMPLATE_REQUIRED_VARIABLE_MISSING" => AtmErrorCode::TemplateRequiredVariableMissing,
440        "TEMPLATE_RENDER_VERIFICATION_FAILED" => AtmErrorCode::TemplateRenderVerificationFailed,
441        "TEMPLATE_INCLUDE_UNRESOLVED" => AtmErrorCode::TemplateIncludeUnresolved,
442        "TEMPLATE_CLASSIFICATION_INVALID" => AtmErrorCode::TemplateClassificationInvalid,
443        "TEMPLATE_WORKFLOW_INVALID" => AtmErrorCode::TemplateWorkflowInvalid,
444        "TEMPLATE_WORKFLOW_VALUE_INVALID" => AtmErrorCode::TemplateWorkflowValueInvalid,
445        "TEMPLATE_TAG_RESERVED" => AtmErrorCode::TemplateTagReserved,
446        "ATM_WORKFLOW_QUERY_INVALID" => AtmErrorCode::WorkflowQueryInvalid,
447        "ATM_WORKFLOW_TELEMETRY_CONFIG_INVALID" => AtmErrorCode::WorkflowTelemetryConfigInvalid,
448        "ATM_WORKFLOW_TELEMETRY_DROPPED" => AtmErrorCode::WorkflowTelemetryDropped,
449        "ATM_SERIALIZATION_FAILED" => AtmErrorCode::SerializationFailed,
450        "ATM_FILE_POLICY_REJECTED" => AtmErrorCode::FilePolicyRejected,
451        "ATM_FILE_REFERENCE_REWRITE_FAILED" => AtmErrorCode::FileReferenceRewriteFailed,
452        "ATM_WAIT_TIMEOUT" => AtmErrorCode::WaitTimeout,
453        "ATM_ACK_INVALID_STATE" => AtmErrorCode::AckInvalidState,
454        "ATM_CLEAR_INVALID_STATE" => AtmErrorCode::ClearInvalidState,
455        _ => return None,
456    })
457}
458
459fn parse_observability_or_warning_code(value: &str) -> Option<AtmErrorCode> {
460    Some(match value {
461        "ATM_OBSERVABILITY_EMIT_FAILED" => AtmErrorCode::ObservabilityEmitFailed,
462        "ATM_OBSERVABILITY_QUERY_FAILED" => AtmErrorCode::ObservabilityQueryFailed,
463        "ATM_OBSERVABILITY_FOLLOW_FAILED" => AtmErrorCode::ObservabilityFollowFailed,
464        "ATM_OBSERVABILITY_HEALTH_FAILED" => AtmErrorCode::ObservabilityHealthFailed,
465        "ATM_OBSERVABILITY_BOOTSTRAP_FAILED" => AtmErrorCode::ObservabilityBootstrapFailed,
466        "ATM_OBSERVABILITY_HEALTH_OK" => AtmErrorCode::ObservabilityHealthOk,
467        "ATM_WARNING_INVALID_TEAM_MEMBER_SKIPPED" => AtmErrorCode::WarningInvalidTeamMemberSkipped,
468        "ATM_WARNING_MAILBOX_RECORD_SKIPPED" => AtmErrorCode::WarningMailboxRecordSkipped,
469        "ATM_WARNING_MALFORMED_ATM_FIELD_IGNORED" => AtmErrorCode::WarningMalformedAtmFieldIgnored,
470        "ATM_WARNING_OBSERVABILITY_HEALTH_DEGRADED" => {
471            AtmErrorCode::WarningObservabilityHealthDegraded
472        }
473        "ATM_WARNING_SQLITE_HEALTH_DEGRADED" => AtmErrorCode::WarningSqliteHealthDegraded,
474        "ATM_WARNING_ORIGIN_INBOX_ENTRY_SKIPPED" => AtmErrorCode::WarningOriginInboxEntrySkipped,
475        "ATM_WARNING_MISSING_TEAM_CONFIG_FALLBACK" => {
476            AtmErrorCode::WarningMissingTeamConfigFallback
477        }
478        "ATM_WARNING_SEND_ALERT_STATE_DEGRADED" => AtmErrorCode::WarningSendAlertStateDegraded,
479        "ATM_WARNING_IDENTITY_DRIFT" => AtmErrorCode::WarningIdentityDrift,
480        "ATM_WARNING_ROSTER_DRIFT" => AtmErrorCode::WarningRosterDrift,
481        "ATM_WARNING_BASELINE_MEMBER_MISSING" => AtmErrorCode::WarningBaselineMemberMissing,
482        "ATM_WARNING_RESTORE_IN_PROGRESS" => AtmErrorCode::WarningRestoreInProgress,
483        "ATM_WARNING_STALE_MAILBOX_LOCK" => AtmErrorCode::WarningStaleMailboxLock,
484        "ATM_WARNING_HOOK_SKIPPED" => AtmErrorCode::WarningHookSkipped,
485        "ATM_WARNING_HOOK_EXECUTION_FAILED" => AtmErrorCode::WarningHookExecutionFailed,
486        "ATM_ROSTER_MIXED_LOCAL_BACKEND" => AtmErrorCode::RosterMixedLocalBackend,
487        "ATM_HERDR_AGENT_NOT_VISIBLE" => AtmErrorCode::HerdrAgentNotVisible,
488        _ => return None,
489    })
490}
491
492fn parse_post_send_or_misc_code(value: &str) -> Option<AtmErrorCode> {
493    Some(match value {
494        "ATM_POST_SEND_PANE_MISSING" => AtmErrorCode::PostSendPaneMissing,
495        "ATM_POST_SEND_TMUX_SEND_FAILED" => AtmErrorCode::PostSendTmuxSendFailed,
496        "ATM_POST_SEND_HERDR_PROMPT_FAILED" => AtmErrorCode::PostSendHerdrPromptFailed,
497        "ATM_HERDR_PROMPT_FAILED" => AtmErrorCode::HerdrPromptFailed,
498        "ATM_HERDR_UNAVAILABLE" => AtmErrorCode::HerdrUnavailable,
499        "ATM_POST_SEND_GRAFT_UNAVAILABLE" => AtmErrorCode::PostSendGraftUnavailable,
500        "ATM_GRAFT_RECEIVER_ALREADY_ACTIVE" => AtmErrorCode::GraftReceiverAlreadyActive,
501        "ATM_GRAFT_RECEIVER_NOT_OWNER" => AtmErrorCode::GraftReceiverNotOwner,
502        "ATM_GRAFT_RECEIVER_NOT_REGISTERED" => AtmErrorCode::GraftReceiverNotRegistered,
503        "ATM_POST_SEND_ADVISORY_DELIVERY_FAILED" => AtmErrorCode::PostSendAdvisoryDeliveryFailed,
504        "ATM_TEST_FAKE_TRANSPORT_INJECTION_FAILED" => {
505            AtmErrorCode::TestFakeTransportInjectionFailed
506        }
507        "ATM_HELP_TOPIC_NOT_FOUND" => AtmErrorCode::HelpTopicNotFound,
508        _ => return None,
509    })
510}
511
512impl fmt::Display for AtmErrorCode {
513    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
514        f.write_str(self.as_str())
515    }
516}
517
518impl Serialize for AtmErrorCode {
519    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
520    where
521        S: serde::Serializer,
522    {
523        serializer.serialize_str(self.as_str())
524    }
525}
526
527impl<'de> Deserialize<'de> for AtmErrorCode {
528    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
529    where
530        D: Deserializer<'de>,
531    {
532        let value = String::deserialize(deserializer)?;
533        value.parse().map_err(serde::de::Error::custom)
534    }
535}