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    PeerConfigValidationFailed,
46    CertificateOperationFailed,
47    BindPreflightFailed,
48    ClientDaemonVersionIncompatible,
49    DaemonAdvisorySessionAlreadyRegistered,
50    DaemonAdvisorySessionNotRegistered,
51    DaemonAdvisorySessionCleanupFailed,
52    AddressParseFailed,
53    TeamUnavailable,
54    TeamInvalid,
55    TeamNotFound,
56    AgentNotFound,
57    MailboxReadFailed,
58    MailboxWriteFailed,
59    MailboxLockFailed,
60    MailboxLockReadOnlyFilesystem,
61    MailboxLockTimeout,
62    InternalError,
63    MessageValidationFailed,
64    /// Search is intentionally local-only until a separately authorized peer
65    /// query protocol exists.
66    SearchLocalOnly,
67    LocalHttpCapabilityInvalid,
68    LocalHttpEndpointSchemaUnsupported,
69    LocalHttpEndpointMissing,
70    LocalHttpEndpointNonLoopback,
71    LocalHttpRuntimeDirectoryMissing,
72    LocalHttpCapabilityRevoked,
73    MessageIdConflict,
74    SelfAddressedSendInvalid,
75    EmptyNudgeTemplateBody,
76    CallerContextRequestInvalid,
77    /// Template catalog content must be strict UTF-8 before any row is admitted.
78    TemplateContentNotUtf8,
79    /// A template passed to the no-include render operation references another template.
80    DecomposedTemplateIncludeForbidden,
81    TemplateLoadFailed,
82    TemplateHashApiFailed,
83    /// The upstream template inspection parser rejected frontmatter or body/directive syntax.
84    TemplateInspectionParseFailed,
85    TemplateRequiredVariableMissing,
86    TemplateRenderVerificationFailed,
87    TemplateIncludeUnresolved,
88    TemplateClassificationInvalid,
89    TemplateWorkflowInvalid,
90    TemplateWorkflowValueInvalid,
91    TemplateTagReserved,
92    /// A bounded local workflow query or lifecycle projection is invalid.
93    WorkflowQueryInvalid,
94    /// Runtime telemetry configuration failed validation and was disabled.
95    WorkflowTelemetryConfigInvalid,
96    /// A best-effort workflow telemetry record was dropped.
97    WorkflowTelemetryDropped,
98    SerializationFailed,
99    FilePolicyRejected,
100    FileReferenceRewriteFailed,
101    WaitTimeout,
102    AckInvalidState,
103    ClearInvalidState,
104    ObservabilityEmitFailed,
105    ObservabilityQueryFailed,
106    ObservabilityFollowFailed,
107    ObservabilityHealthFailed,
108    ObservabilityBootstrapFailed,
109    ObservabilityHealthOk,
110    WarningInvalidTeamMemberSkipped,
111    WarningMailboxRecordSkipped,
112    WarningMalformedAtmFieldIgnored,
113    WarningObservabilityHealthDegraded,
114    WarningSqliteHealthDegraded,
115    WarningOriginInboxEntrySkipped,
116    WarningMissingTeamConfigFallback,
117    WarningSendAlertStateDegraded,
118    WarningIdentityDrift,
119    WarningRosterDrift,
120    WarningBaselineMemberMissing,
121    WarningRestoreInProgress,
122    WarningStaleMailboxLock,
123    WarningHookSkipped,
124    WarningHookExecutionFailed,
125    PostSendPaneMissing,
126    PostSendTmuxSendFailed,
127    PostSendGraftUnavailable,
128    GraftReceiverAlreadyActive,
129    PostSendAdvisoryDeliveryFailed,
130    TestFakeTransportInjectionFailed,
131    HelpTopicNotFound,
132}
133
134impl AtmErrorCode {
135    pub fn as_str(self) -> &'static str {
136        if let Some(value) = self.config_or_identity_str() {
137            return value;
138        }
139        if let Some(value) = self.daemon_or_address_str() {
140            return value;
141        }
142        if let Some(value) = self.mailbox_or_validation_str() {
143            return value;
144        }
145        if let Some(value) = self.observability_or_warning_str() {
146            return value;
147        }
148        self.post_send_or_misc_str()
149    }
150
151    fn config_or_identity_str(self) -> Option<&'static str> {
152        Some(match self {
153            Self::ConfigHomeUnavailable => "ATM_CONFIG_HOME_UNAVAILABLE",
154            Self::AtmHomeUnresolved => "ATM_HOME_UNRESOLVED",
155            Self::ConfigParseFailed => "ATM_CONFIG_PARSE_FAILED",
156            Self::ConfigRetiredHookMembersKey => "ATM_CONFIG_RETIRED_HOOK_MEMBERS_KEY",
157            Self::ConfigRetiredLegacyHookKeys => "ATM_CONFIG_RETIRED_LEGACY_HOOK_KEYS",
158            Self::ConfigTeamParseFailed => "ATM_CONFIG_TEAM_PARSE_FAILED",
159            Self::ConfigTeamMissing => "ATM_CONFIG_TEAM_MISSING",
160            Self::IdentityUnavailable => "ATM_IDENTITY_UNAVAILABLE",
161            Self::IdentityInvalid => "ATM_IDENTITY_INVALID",
162            Self::IdentityConflict => "ATM_IDENTITY_CONFLICT",
163            Self::MemberAlreadyExists => "ATM_MEMBER_ALREADY_EXISTS",
164            Self::MemberNotFound => "ATM_MEMBER_NOT_FOUND",
165            _ => return None,
166        })
167    }
168
169    fn daemon_or_address_str(self) -> Option<&'static str> {
170        Some(match self {
171            Self::DaemonUnavailable => "ATM_DAEMON_UNAVAILABLE",
172            Self::RuntimeRootInvalid => "ATM_RUNTIME_ROOT_INVALID",
173            Self::RuntimeBootstrapRefused => "ATM_RUNTIME_BOOTSTRAP_REFUSED",
174            Self::SocketOverrideForbidden => "ATM_SOCKET_OVERRIDE_FORBIDDEN",
175            Self::DaemonMayHaveExecuted => "ATM_DAEMON_MAY_HAVE_EXECUTED",
176            Self::DaemonLifecycleWedge => "ATM_DAEMON_LIFECYCLE_WEDGE",
177            Self::DaemonLaunchGateRejected => "ATM_DAEMON_LAUNCH_GATE_REJECTED",
178            Self::DaemonServingStateRejected => "ATM_DAEMON_SERVING_STATE_REJECTED",
179            Self::DaemonStaleOwnerRecoveryFailed => "ATM_DAEMON_STALE_OWNER_RECOVERY_FAILED",
180            Self::DaemonAutoStartFailed => "ATM_DAEMON_AUTO_START_FAILED",
181            Self::DaemonConnectionSaturated => "ATM_DAEMON_CONNECTION_SATURATED",
182            Self::RemoteDeliveryUnconfirmed => "REMOTE_DELIVERY_UNCONFIRMED",
183            Self::PeerConfigValidationFailed => "ATM_PEER_CONFIG_VALIDATION_FAILED",
184            Self::CertificateOperationFailed => "ATM_CERTIFICATE_OPERATION_FAILED",
185            Self::BindPreflightFailed => "ATM_BIND_PREFLIGHT_FAILED",
186            Self::ClientDaemonVersionIncompatible => "ATM_CLIENT_DAEMON_VERSION_INCOMPATIBLE",
187            Self::DaemonAdvisorySessionAlreadyRegistered => {
188                "ATM_DAEMON_ADVISORY_SESSION_ALREADY_REGISTERED"
189            }
190            Self::DaemonAdvisorySessionNotRegistered => {
191                "ATM_DAEMON_ADVISORY_SESSION_NOT_REGISTERED"
192            }
193            Self::DaemonAdvisorySessionCleanupFailed => {
194                "ATM_DAEMON_ADVISORY_SESSION_CLEANUP_FAILED"
195            }
196            Self::AddressParseFailed => "ATM_ADDRESS_PARSE_FAILED",
197            Self::TeamUnavailable => "ATM_TEAM_UNAVAILABLE",
198            Self::TeamInvalid => "ATM_TEAM_INVALID",
199            Self::TeamNotFound => "ATM_TEAM_NOT_FOUND",
200            Self::AgentNotFound => "ATM_AGENT_NOT_FOUND",
201            _ => return None,
202        })
203    }
204
205    fn mailbox_or_validation_str(self) -> Option<&'static str> {
206        Some(match self {
207            Self::MailboxReadFailed => "ATM_MAILBOX_READ_FAILED",
208            Self::MailboxWriteFailed => "ATM_MAILBOX_WRITE_FAILED",
209            Self::MailboxLockFailed => "ATM_MAILBOX_LOCK_FAILED",
210            Self::MailboxLockReadOnlyFilesystem => "ATM_MAILBOX_LOCK_READ_ONLY_FILESYSTEM",
211            Self::MailboxLockTimeout => "ATM_MAILBOX_LOCK_TIMEOUT",
212            Self::InternalError => "ATM_INTERNAL_ERROR",
213            Self::MessageValidationFailed => "ATM_MESSAGE_VALIDATION_FAILED",
214            Self::SearchLocalOnly => "ATM_SEARCH_LOCAL_ONLY",
215            Self::LocalHttpCapabilityInvalid => "ATM_LOCAL_HTTP_CAPABILITY_INVALID",
216            Self::LocalHttpEndpointSchemaUnsupported => {
217                "ATM_LOCAL_HTTP_ENDPOINT_SCHEMA_UNSUPPORTED"
218            }
219            Self::LocalHttpEndpointMissing => "ATM_LOCAL_HTTP_ENDPOINT_MISSING",
220            Self::LocalHttpEndpointNonLoopback => "ATM_LOCAL_HTTP_ENDPOINT_NON_LOOPBACK",
221            Self::LocalHttpRuntimeDirectoryMissing => "ATM_LOCAL_HTTP_RUNTIME_DIRECTORY_MISSING",
222            Self::LocalHttpCapabilityRevoked => "ATM_LOCAL_HTTP_CAPABILITY_REVOKED",
223            Self::MessageIdConflict => "ATM_MESSAGE_ID_CONFLICT",
224            Self::SelfAddressedSendInvalid => "ATM_SELF_ADDRESSED_SEND_INVALID",
225            Self::EmptyNudgeTemplateBody => "ATM_NUDGE_TEMPLATE_BODY_EMPTY",
226            Self::CallerContextRequestInvalid => "ATM_CALLER_CONTEXT_REQUEST_INVALID",
227            Self::TemplateContentNotUtf8 => "TEMPLATE_CONTENT_NOT_UTF8",
228            Self::DecomposedTemplateIncludeForbidden => "DECOMPOSED_TEMPLATE_INCLUDE_FORBIDDEN",
229            Self::TemplateLoadFailed => "TEMPLATE_LOAD_FAILED",
230            Self::TemplateHashApiFailed => "TEMPLATE_HASH_API_FAILED",
231            Self::TemplateInspectionParseFailed => "TEMPLATE_INSPECTION_PARSE_FAILED",
232            Self::TemplateRequiredVariableMissing => "TEMPLATE_REQUIRED_VARIABLE_MISSING",
233            Self::TemplateRenderVerificationFailed => "TEMPLATE_RENDER_VERIFICATION_FAILED",
234            Self::TemplateIncludeUnresolved => "TEMPLATE_INCLUDE_UNRESOLVED",
235            Self::TemplateClassificationInvalid => "TEMPLATE_CLASSIFICATION_INVALID",
236            Self::TemplateWorkflowInvalid => "TEMPLATE_WORKFLOW_INVALID",
237            Self::TemplateWorkflowValueInvalid => "TEMPLATE_WORKFLOW_VALUE_INVALID",
238            Self::TemplateTagReserved => "TEMPLATE_TAG_RESERVED",
239            Self::WorkflowQueryInvalid => "ATM_WORKFLOW_QUERY_INVALID",
240            Self::WorkflowTelemetryConfigInvalid => "ATM_WORKFLOW_TELEMETRY_CONFIG_INVALID",
241            Self::WorkflowTelemetryDropped => "ATM_WORKFLOW_TELEMETRY_DROPPED",
242            Self::SerializationFailed => "ATM_SERIALIZATION_FAILED",
243            Self::FilePolicyRejected => "ATM_FILE_POLICY_REJECTED",
244            Self::FileReferenceRewriteFailed => "ATM_FILE_REFERENCE_REWRITE_FAILED",
245            Self::WaitTimeout => "ATM_WAIT_TIMEOUT",
246            Self::AckInvalidState => "ATM_ACK_INVALID_STATE",
247            Self::ClearInvalidState => "ATM_CLEAR_INVALID_STATE",
248            _ => return None,
249        })
250    }
251
252    fn observability_or_warning_str(self) -> Option<&'static str> {
253        Some(match self {
254            Self::ObservabilityEmitFailed => "ATM_OBSERVABILITY_EMIT_FAILED",
255            Self::ObservabilityQueryFailed => "ATM_OBSERVABILITY_QUERY_FAILED",
256            Self::ObservabilityFollowFailed => "ATM_OBSERVABILITY_FOLLOW_FAILED",
257            Self::ObservabilityHealthFailed => "ATM_OBSERVABILITY_HEALTH_FAILED",
258            Self::ObservabilityBootstrapFailed => "ATM_OBSERVABILITY_BOOTSTRAP_FAILED",
259            Self::ObservabilityHealthOk => "ATM_OBSERVABILITY_HEALTH_OK",
260            Self::WarningInvalidTeamMemberSkipped => "ATM_WARNING_INVALID_TEAM_MEMBER_SKIPPED",
261            Self::WarningMailboxRecordSkipped => "ATM_WARNING_MAILBOX_RECORD_SKIPPED",
262            Self::WarningMalformedAtmFieldIgnored => "ATM_WARNING_MALFORMED_ATM_FIELD_IGNORED",
263            Self::WarningObservabilityHealthDegraded => "ATM_WARNING_OBSERVABILITY_HEALTH_DEGRADED",
264            Self::WarningSqliteHealthDegraded => "ATM_WARNING_SQLITE_HEALTH_DEGRADED",
265            Self::WarningOriginInboxEntrySkipped => "ATM_WARNING_ORIGIN_INBOX_ENTRY_SKIPPED",
266            Self::WarningMissingTeamConfigFallback => "ATM_WARNING_MISSING_TEAM_CONFIG_FALLBACK",
267            Self::WarningSendAlertStateDegraded => "ATM_WARNING_SEND_ALERT_STATE_DEGRADED",
268            Self::WarningIdentityDrift => "ATM_WARNING_IDENTITY_DRIFT",
269            Self::WarningRosterDrift => "ATM_WARNING_ROSTER_DRIFT",
270            Self::WarningBaselineMemberMissing => "ATM_WARNING_BASELINE_MEMBER_MISSING",
271            Self::WarningRestoreInProgress => "ATM_WARNING_RESTORE_IN_PROGRESS",
272            Self::WarningStaleMailboxLock => "ATM_WARNING_STALE_MAILBOX_LOCK",
273            Self::WarningHookSkipped => "ATM_WARNING_HOOK_SKIPPED",
274            Self::WarningHookExecutionFailed => "ATM_WARNING_HOOK_EXECUTION_FAILED",
275            _ => return None,
276        })
277    }
278
279    fn post_send_or_misc_str(self) -> &'static str {
280        match self {
281            Self::PostSendPaneMissing => "ATM_POST_SEND_PANE_MISSING",
282            Self::PostSendTmuxSendFailed => "ATM_POST_SEND_TMUX_SEND_FAILED",
283            Self::PostSendGraftUnavailable => "ATM_POST_SEND_GRAFT_UNAVAILABLE",
284            Self::GraftReceiverAlreadyActive => "ATM_GRAFT_RECEIVER_ALREADY_ACTIVE",
285            Self::PostSendAdvisoryDeliveryFailed => "ATM_POST_SEND_ADVISORY_DELIVERY_FAILED",
286            Self::TestFakeTransportInjectionFailed => "ATM_TEST_FAKE_TRANSPORT_INJECTION_FAILED",
287            Self::HelpTopicNotFound => "ATM_HELP_TOPIC_NOT_FOUND",
288            _ => unreachable!("all AtmErrorCode variants must be covered by as_str helpers"),
289        }
290    }
291}
292
293impl FromStr for AtmErrorCode {
294    type Err = UnknownAtmErrorCode;
295
296    fn from_str(value: &str) -> Result<Self, Self::Err> {
297        parse_known_error_code(value).ok_or_else(|| UnknownAtmErrorCode(value.to_owned()))
298    }
299}
300
301fn parse_known_error_code(value: &str) -> Option<AtmErrorCode> {
302    parse_config_or_identity_code(value)
303        .or_else(|| parse_daemon_or_address_code(value))
304        .or_else(|| parse_mailbox_or_validation_code(value))
305        .or_else(|| parse_observability_or_warning_code(value))
306        .or_else(|| parse_post_send_or_misc_code(value))
307}
308
309fn parse_config_or_identity_code(value: &str) -> Option<AtmErrorCode> {
310    Some(match value {
311        "ATM_CONFIG_HOME_UNAVAILABLE" => AtmErrorCode::ConfigHomeUnavailable,
312        "ATM_HOME_UNRESOLVED" => AtmErrorCode::AtmHomeUnresolved,
313        "ATM_CONFIG_PARSE_FAILED" => AtmErrorCode::ConfigParseFailed,
314        "ATM_CONFIG_RETIRED_HOOK_MEMBERS_KEY" => AtmErrorCode::ConfigRetiredHookMembersKey,
315        "ATM_CONFIG_RETIRED_LEGACY_HOOK_KEYS" => AtmErrorCode::ConfigRetiredLegacyHookKeys,
316        "ATM_CONFIG_TEAM_PARSE_FAILED" => AtmErrorCode::ConfigTeamParseFailed,
317        "ATM_CONFIG_TEAM_MISSING" => AtmErrorCode::ConfigTeamMissing,
318        "ATM_IDENTITY_UNAVAILABLE" => AtmErrorCode::IdentityUnavailable,
319        "ATM_IDENTITY_INVALID" => AtmErrorCode::IdentityInvalid,
320        "ATM_IDENTITY_CONFLICT" => AtmErrorCode::IdentityConflict,
321        "ATM_MEMBER_ALREADY_EXISTS" => AtmErrorCode::MemberAlreadyExists,
322        "ATM_MEMBER_NOT_FOUND" => AtmErrorCode::MemberNotFound,
323        _ => return None,
324    })
325}
326
327fn parse_daemon_or_address_code(value: &str) -> Option<AtmErrorCode> {
328    Some(match value {
329        "ATM_DAEMON_UNAVAILABLE" => AtmErrorCode::DaemonUnavailable,
330        "ATM_RUNTIME_ROOT_INVALID" => AtmErrorCode::RuntimeRootInvalid,
331        "ATM_RUNTIME_BOOTSTRAP_REFUSED" => AtmErrorCode::RuntimeBootstrapRefused,
332        "ATM_SOCKET_OVERRIDE_FORBIDDEN" => AtmErrorCode::SocketOverrideForbidden,
333        "ATM_DAEMON_MAY_HAVE_EXECUTED" => AtmErrorCode::DaemonMayHaveExecuted,
334        "ATM_DAEMON_LIFECYCLE_WEDGE" => AtmErrorCode::DaemonLifecycleWedge,
335        "ATM_DAEMON_LAUNCH_GATE_REJECTED" => AtmErrorCode::DaemonLaunchGateRejected,
336        "ATM_DAEMON_SERVING_STATE_REJECTED" => AtmErrorCode::DaemonServingStateRejected,
337        "ATM_DAEMON_STALE_OWNER_RECOVERY_FAILED" => AtmErrorCode::DaemonStaleOwnerRecoveryFailed,
338        "ATM_DAEMON_AUTO_START_FAILED" => AtmErrorCode::DaemonAutoStartFailed,
339        "ATM_DAEMON_CONNECTION_SATURATED" => AtmErrorCode::DaemonConnectionSaturated,
340        "REMOTE_DELIVERY_UNCONFIRMED" => AtmErrorCode::RemoteDeliveryUnconfirmed,
341        "ATM_PEER_CONFIG_VALIDATION_FAILED" => AtmErrorCode::PeerConfigValidationFailed,
342        "ATM_CERTIFICATE_OPERATION_FAILED" => AtmErrorCode::CertificateOperationFailed,
343        "ATM_BIND_PREFLIGHT_FAILED" => AtmErrorCode::BindPreflightFailed,
344        "ATM_CLIENT_DAEMON_VERSION_INCOMPATIBLE" => AtmErrorCode::ClientDaemonVersionIncompatible,
345        "ATM_DAEMON_ADVISORY_SESSION_ALREADY_REGISTERED" => {
346            AtmErrorCode::DaemonAdvisorySessionAlreadyRegistered
347        }
348        "ATM_DAEMON_ADVISORY_SESSION_NOT_REGISTERED" => {
349            AtmErrorCode::DaemonAdvisorySessionNotRegistered
350        }
351        "ATM_DAEMON_ADVISORY_SESSION_CLEANUP_FAILED" => {
352            AtmErrorCode::DaemonAdvisorySessionCleanupFailed
353        }
354        "ATM_ADDRESS_PARSE_FAILED" => AtmErrorCode::AddressParseFailed,
355        "ATM_TEAM_UNAVAILABLE" => AtmErrorCode::TeamUnavailable,
356        "ATM_TEAM_INVALID" => AtmErrorCode::TeamInvalid,
357        "ATM_TEAM_NOT_FOUND" => AtmErrorCode::TeamNotFound,
358        "ATM_AGENT_NOT_FOUND" => AtmErrorCode::AgentNotFound,
359        _ => return None,
360    })
361}
362
363fn parse_mailbox_or_validation_code(value: &str) -> Option<AtmErrorCode> {
364    Some(match value {
365        "ATM_MAILBOX_READ_FAILED" => AtmErrorCode::MailboxReadFailed,
366        "ATM_MAILBOX_WRITE_FAILED" => AtmErrorCode::MailboxWriteFailed,
367        "ATM_MAILBOX_LOCK_FAILED" => AtmErrorCode::MailboxLockFailed,
368        "ATM_MAILBOX_LOCK_READ_ONLY_FILESYSTEM" => AtmErrorCode::MailboxLockReadOnlyFilesystem,
369        "ATM_MAILBOX_LOCK_TIMEOUT" => AtmErrorCode::MailboxLockTimeout,
370        "ATM_INTERNAL_ERROR" => AtmErrorCode::InternalError,
371        "ATM_MESSAGE_VALIDATION_FAILED" => AtmErrorCode::MessageValidationFailed,
372        "ATM_SEARCH_LOCAL_ONLY" => AtmErrorCode::SearchLocalOnly,
373        "ATM_LOCAL_HTTP_CAPABILITY_INVALID" => AtmErrorCode::LocalHttpCapabilityInvalid,
374        "ATM_LOCAL_HTTP_ENDPOINT_SCHEMA_UNSUPPORTED" => {
375            AtmErrorCode::LocalHttpEndpointSchemaUnsupported
376        }
377        "ATM_LOCAL_HTTP_ENDPOINT_MISSING" => AtmErrorCode::LocalHttpEndpointMissing,
378        "ATM_LOCAL_HTTP_ENDPOINT_NON_LOOPBACK" => AtmErrorCode::LocalHttpEndpointNonLoopback,
379        "ATM_LOCAL_HTTP_RUNTIME_DIRECTORY_MISSING" => {
380            AtmErrorCode::LocalHttpRuntimeDirectoryMissing
381        }
382        "ATM_LOCAL_HTTP_CAPABILITY_REVOKED" => AtmErrorCode::LocalHttpCapabilityRevoked,
383        "ATM_MESSAGE_ID_CONFLICT" => AtmErrorCode::MessageIdConflict,
384        "ATM_SELF_ADDRESSED_SEND_INVALID" => AtmErrorCode::SelfAddressedSendInvalid,
385        "ATM_NUDGE_TEMPLATE_BODY_EMPTY" => AtmErrorCode::EmptyNudgeTemplateBody,
386        "ATM_CALLER_CONTEXT_REQUEST_INVALID" => AtmErrorCode::CallerContextRequestInvalid,
387        "TEMPLATE_CONTENT_NOT_UTF8" => AtmErrorCode::TemplateContentNotUtf8,
388        "DECOMPOSED_TEMPLATE_INCLUDE_FORBIDDEN" => AtmErrorCode::DecomposedTemplateIncludeForbidden,
389        "TEMPLATE_LOAD_FAILED" => AtmErrorCode::TemplateLoadFailed,
390        "TEMPLATE_HASH_API_FAILED" => AtmErrorCode::TemplateHashApiFailed,
391        "TEMPLATE_INSPECTION_PARSE_FAILED" => AtmErrorCode::TemplateInspectionParseFailed,
392        "TEMPLATE_REQUIRED_VARIABLE_MISSING" => AtmErrorCode::TemplateRequiredVariableMissing,
393        "TEMPLATE_RENDER_VERIFICATION_FAILED" => AtmErrorCode::TemplateRenderVerificationFailed,
394        "TEMPLATE_INCLUDE_UNRESOLVED" => AtmErrorCode::TemplateIncludeUnresolved,
395        "TEMPLATE_CLASSIFICATION_INVALID" => AtmErrorCode::TemplateClassificationInvalid,
396        "TEMPLATE_WORKFLOW_INVALID" => AtmErrorCode::TemplateWorkflowInvalid,
397        "TEMPLATE_WORKFLOW_VALUE_INVALID" => AtmErrorCode::TemplateWorkflowValueInvalid,
398        "TEMPLATE_TAG_RESERVED" => AtmErrorCode::TemplateTagReserved,
399        "ATM_WORKFLOW_QUERY_INVALID" => AtmErrorCode::WorkflowQueryInvalid,
400        "ATM_WORKFLOW_TELEMETRY_CONFIG_INVALID" => AtmErrorCode::WorkflowTelemetryConfigInvalid,
401        "ATM_WORKFLOW_TELEMETRY_DROPPED" => AtmErrorCode::WorkflowTelemetryDropped,
402        "ATM_SERIALIZATION_FAILED" => AtmErrorCode::SerializationFailed,
403        "ATM_FILE_POLICY_REJECTED" => AtmErrorCode::FilePolicyRejected,
404        "ATM_FILE_REFERENCE_REWRITE_FAILED" => AtmErrorCode::FileReferenceRewriteFailed,
405        "ATM_WAIT_TIMEOUT" => AtmErrorCode::WaitTimeout,
406        "ATM_ACK_INVALID_STATE" => AtmErrorCode::AckInvalidState,
407        "ATM_CLEAR_INVALID_STATE" => AtmErrorCode::ClearInvalidState,
408        _ => return None,
409    })
410}
411
412fn parse_observability_or_warning_code(value: &str) -> Option<AtmErrorCode> {
413    Some(match value {
414        "ATM_OBSERVABILITY_EMIT_FAILED" => AtmErrorCode::ObservabilityEmitFailed,
415        "ATM_OBSERVABILITY_QUERY_FAILED" => AtmErrorCode::ObservabilityQueryFailed,
416        "ATM_OBSERVABILITY_FOLLOW_FAILED" => AtmErrorCode::ObservabilityFollowFailed,
417        "ATM_OBSERVABILITY_HEALTH_FAILED" => AtmErrorCode::ObservabilityHealthFailed,
418        "ATM_OBSERVABILITY_BOOTSTRAP_FAILED" => AtmErrorCode::ObservabilityBootstrapFailed,
419        "ATM_OBSERVABILITY_HEALTH_OK" => AtmErrorCode::ObservabilityHealthOk,
420        "ATM_WARNING_INVALID_TEAM_MEMBER_SKIPPED" => AtmErrorCode::WarningInvalidTeamMemberSkipped,
421        "ATM_WARNING_MAILBOX_RECORD_SKIPPED" => AtmErrorCode::WarningMailboxRecordSkipped,
422        "ATM_WARNING_MALFORMED_ATM_FIELD_IGNORED" => AtmErrorCode::WarningMalformedAtmFieldIgnored,
423        "ATM_WARNING_OBSERVABILITY_HEALTH_DEGRADED" => {
424            AtmErrorCode::WarningObservabilityHealthDegraded
425        }
426        "ATM_WARNING_SQLITE_HEALTH_DEGRADED" => AtmErrorCode::WarningSqliteHealthDegraded,
427        "ATM_WARNING_ORIGIN_INBOX_ENTRY_SKIPPED" => AtmErrorCode::WarningOriginInboxEntrySkipped,
428        "ATM_WARNING_MISSING_TEAM_CONFIG_FALLBACK" => {
429            AtmErrorCode::WarningMissingTeamConfigFallback
430        }
431        "ATM_WARNING_SEND_ALERT_STATE_DEGRADED" => AtmErrorCode::WarningSendAlertStateDegraded,
432        "ATM_WARNING_IDENTITY_DRIFT" => AtmErrorCode::WarningIdentityDrift,
433        "ATM_WARNING_ROSTER_DRIFT" => AtmErrorCode::WarningRosterDrift,
434        "ATM_WARNING_BASELINE_MEMBER_MISSING" => AtmErrorCode::WarningBaselineMemberMissing,
435        "ATM_WARNING_RESTORE_IN_PROGRESS" => AtmErrorCode::WarningRestoreInProgress,
436        "ATM_WARNING_STALE_MAILBOX_LOCK" => AtmErrorCode::WarningStaleMailboxLock,
437        "ATM_WARNING_HOOK_SKIPPED" => AtmErrorCode::WarningHookSkipped,
438        "ATM_WARNING_HOOK_EXECUTION_FAILED" => AtmErrorCode::WarningHookExecutionFailed,
439        _ => return None,
440    })
441}
442
443fn parse_post_send_or_misc_code(value: &str) -> Option<AtmErrorCode> {
444    Some(match value {
445        "ATM_POST_SEND_PANE_MISSING" => AtmErrorCode::PostSendPaneMissing,
446        "ATM_POST_SEND_TMUX_SEND_FAILED" => AtmErrorCode::PostSendTmuxSendFailed,
447        "ATM_POST_SEND_GRAFT_UNAVAILABLE" => AtmErrorCode::PostSendGraftUnavailable,
448        "ATM_GRAFT_RECEIVER_ALREADY_ACTIVE" => AtmErrorCode::GraftReceiverAlreadyActive,
449        "ATM_POST_SEND_ADVISORY_DELIVERY_FAILED" => AtmErrorCode::PostSendAdvisoryDeliveryFailed,
450        "ATM_TEST_FAKE_TRANSPORT_INJECTION_FAILED" => {
451            AtmErrorCode::TestFakeTransportInjectionFailed
452        }
453        "ATM_HELP_TOPIC_NOT_FOUND" => AtmErrorCode::HelpTopicNotFound,
454        _ => return None,
455    })
456}
457
458impl fmt::Display for AtmErrorCode {
459    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
460        f.write_str(self.as_str())
461    }
462}
463
464impl Serialize for AtmErrorCode {
465    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
466    where
467        S: serde::Serializer,
468    {
469        serializer.serialize_str(self.as_str())
470    }
471}
472
473impl<'de> Deserialize<'de> for AtmErrorCode {
474    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
475    where
476        D: Deserializer<'de>,
477    {
478        let value = String::deserialize(deserializer)?;
479        value.parse().map_err(serde::de::Error::custom)
480    }
481}