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