agent-team-mail-core 1.1.2

Daemon-free core library for local agent team mail workflows.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use std::backtrace::{Backtrace, BacktraceStatus};
use std::error::Error as StdError;
use std::fmt;

pub use crate::error_codes::AtmErrorCode;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AtmErrorKind {
    Config,
    MissingDocument,
    Address,
    Identity,
    TeamNotFound,
    AgentNotFound,
    MailboxLock,
    MailboxRead,
    MailboxWrite,
    FilePolicy,
    Validation,
    Serialization,
    Timeout,
    ObservabilityEmit,
    ObservabilityBootstrap,
    ObservabilityQuery,
    ObservabilityFollow,
    ObservabilityHealth,
}

#[derive(Debug)]
pub struct AtmError {
    pub code: AtmErrorCode,
    pub(crate) kind: AtmErrorKind,
    pub message: String,
    pub recovery: Option<String>,
    pub source: Option<Box<dyn StdError + Send + Sync>>,
    pub backtrace: Backtrace,
}

impl AtmError {
    pub(crate) fn new(kind: AtmErrorKind, message: impl Into<String>) -> Self {
        Self::new_with_code(kind.default_code(), kind, message)
    }

    pub(crate) fn new_with_code(
        code: AtmErrorCode,
        kind: AtmErrorKind,
        message: impl Into<String>,
    ) -> Self {
        Self {
            code,
            kind,
            message: message.into(),
            recovery: None,
            source: None,
            backtrace: Backtrace::capture(),
        }
    }

    pub fn is_config(&self) -> bool {
        self.kind == AtmErrorKind::Config
    }

    pub fn is_address(&self) -> bool {
        self.kind == AtmErrorKind::Address
    }

    pub fn is_missing_document(&self) -> bool {
        self.kind == AtmErrorKind::MissingDocument
    }

    pub fn is_identity(&self) -> bool {
        self.kind == AtmErrorKind::Identity
    }

    pub fn is_team_not_found(&self) -> bool {
        self.kind == AtmErrorKind::TeamNotFound
    }

    pub fn is_agent_not_found(&self) -> bool {
        self.kind == AtmErrorKind::AgentNotFound
    }

    pub fn is_mailbox_read(&self) -> bool {
        self.kind == AtmErrorKind::MailboxRead
    }

    pub fn is_mailbox_lock(&self) -> bool {
        self.kind == AtmErrorKind::MailboxLock
    }

    pub fn is_mailbox_write(&self) -> bool {
        self.kind == AtmErrorKind::MailboxWrite
    }

    pub fn is_file_policy(&self) -> bool {
        self.kind == AtmErrorKind::FilePolicy
    }

    pub fn is_validation(&self) -> bool {
        self.kind == AtmErrorKind::Validation
    }

    pub fn is_serialization(&self) -> bool {
        self.kind == AtmErrorKind::Serialization
    }

    pub fn is_timeout(&self) -> bool {
        self.kind == AtmErrorKind::Timeout
    }

    pub fn is_observability_emit(&self) -> bool {
        self.kind == AtmErrorKind::ObservabilityEmit
    }

    pub fn is_observability_bootstrap(&self) -> bool {
        self.kind == AtmErrorKind::ObservabilityBootstrap
    }

    pub fn is_observability_query(&self) -> bool {
        self.kind == AtmErrorKind::ObservabilityQuery
    }

    pub fn is_observability_follow(&self) -> bool {
        self.kind == AtmErrorKind::ObservabilityFollow
    }

    pub fn is_observability_health(&self) -> bool {
        self.kind == AtmErrorKind::ObservabilityHealth
    }

    pub fn with_recovery(mut self, recovery: impl Into<String>) -> Self {
        self.recovery = Some(recovery.into());
        self
    }

    pub fn with_source<E>(mut self, source: E) -> Self
    where
        E: StdError + Send + Sync + 'static,
    {
        self.source = Some(Box::new(source));
        self
    }

    /// Return the captured backtrace when one is available.
    pub fn backtrace(&self) -> Option<&Backtrace> {
        (self.backtrace.status() == BacktraceStatus::Captured).then_some(&self.backtrace)
    }

    pub fn home_directory_unavailable() -> Self {
        Self::new_with_code(
            AtmErrorCode::ConfigHomeUnavailable,
            AtmErrorKind::Config,
            "home directory is unavailable",
        )
        .with_recovery("Set ATM_HOME or ensure the OS home directory can be resolved.")
    }

    pub fn address_parse(message: impl Into<String>) -> Self {
        Self::new(
            AtmErrorKind::Address,
            format!("address parse failed: {}", message.into()),
        )
        .with_recovery(
            "Correct the ATM address format and retry with a valid <agent> or <agent>@<team> target.",
        )
    }

    pub fn identity_unavailable() -> Self {
        Self::new_with_code(
            AtmErrorCode::IdentityUnavailable,
            AtmErrorKind::Identity,
            "identity is not configured",
        )
        .with_recovery("Set ATM_IDENTITY or provide an explicit command identity override when the command supports one.")
    }

    pub fn team_unavailable() -> Self {
        Self::new_with_code(
            AtmErrorCode::TeamUnavailable,
            AtmErrorKind::TeamNotFound,
            "team is not configured",
        )
        .with_recovery("Pass an explicit team in the address or configure a default team.")
    }

    pub fn team_not_found(team: &str) -> Self {
        Self::new(
            AtmErrorKind::TeamNotFound,
            format!("team '{team}' was not found"),
        )
        .with_recovery("Create the team config or target a different team.")
    }

    pub fn agent_not_found(agent: &str, team: &str) -> Self {
        Self::new(
            AtmErrorKind::AgentNotFound,
            format!("agent '{agent}' was not found in team '{team}'"),
        )
        .with_recovery("Update the team membership or target a different recipient.")
    }

    pub fn validation(message: impl Into<String>) -> Self {
        Self::new(AtmErrorKind::Validation, message).with_recovery(
            "Correct the invalid ATM input or mailbox state, then retry the command with a valid target or argument.",
        )
    }

    pub fn missing_document(message: impl Into<String>) -> Self {
        Self::new(AtmErrorKind::MissingDocument, message).with_recovery(
            "Restore the missing ATM document or recreate it through the documented team-management workflow before retrying.",
        )
    }

    pub fn file_policy(message: impl Into<String>) -> Self {
        Self::new(AtmErrorKind::FilePolicy, message).with_recovery(
            "Update the referenced file, path, or policy inputs so they satisfy ATM file-policy rules before retrying the command.",
        )
    }

    pub fn mailbox_read(message: impl Into<String>) -> Self {
        Self::new(AtmErrorKind::MailboxRead, message).with_recovery(
            "Check ATM_HOME, mailbox file permissions, and mailbox JSON syntax before retrying the ATM command.",
        )
    }

    pub fn mailbox_lock(message: impl Into<String>) -> Self {
        Self::new(AtmErrorKind::MailboxLock, message).with_recovery(
            "Retry after other ATM mailbox activity completes, or wait for the competing process to release its mailbox lock.",
        )
    }

    pub fn mailbox_lock_read_only_filesystem(
        operation: impl fmt::Display,
        path: &std::path::Path,
    ) -> Self {
        Self::new_with_code(
            AtmErrorCode::MailboxLockReadOnlyFilesystem,
            AtmErrorKind::MailboxLock,
            format!(
                "mailbox lock {operation} failed for {}: filesystem is read-only",
                path.display()
            ),
        )
        .with_recovery(
            "Remount the filesystem read-write or point ATM at a writable home with ATM_HOME or --home, then retry the ATM command.",
        )
    }

    pub fn mailbox_lock_timeout(path: &std::path::Path) -> Self {
        Self::new_with_code(
            AtmErrorCode::MailboxLockTimeout,
            AtmErrorKind::MailboxLock,
            format!(
                "timed out waiting for mailbox lock on {}",
                path.display()
            ),
        )
        .with_recovery(
            "Retry after the competing ATM process finishes, or investigate whether another process is holding the mailbox lock unexpectedly.",
        )
    }

    pub fn mailbox_write(message: impl Into<String>) -> Self {
        Self::new(AtmErrorKind::MailboxWrite, message).with_recovery(
            "Check that the mailbox/workflow path is writable, has free space, and was not modified concurrently before retrying the ATM command.",
        )
    }

    pub fn observability_emit(message: impl Into<String>) -> Self {
        Self::new(AtmErrorKind::ObservabilityEmit, message).with_recovery(
            "Verify the observability sink is writable or temporarily disable retained logging while investigating.",
        )
    }

    pub fn observability_bootstrap(message: impl Into<String>) -> Self {
        Self::new(AtmErrorKind::ObservabilityBootstrap, message).with_recovery(
            "Check the configured observability backend, log directory permissions, and any local path overrides before retrying ATM commands.",
        )
    }

    pub fn observability_query(message: impl Into<String>) -> Self {
        Self::new(AtmErrorKind::ObservabilityQuery, message).with_recovery(
            "Confirm retained logs exist and the observability backend supports queries for the selected sink and time range.",
        )
    }

    pub fn observability_follow(message: impl Into<String>) -> Self {
        Self::new(AtmErrorKind::ObservabilityFollow, message).with_recovery(
            "Check that follow/tail is enabled for the active sink and retry with a narrower query if the stream is unavailable.",
        )
    }

    pub fn observability_health(message: impl Into<String>) -> Self {
        Self::new(AtmErrorKind::ObservabilityHealth, message).with_recovery(
            "Inspect the observability backend health, file sink path, and query backend status, then rerun `atm doctor`.",
        )
    }
}

impl fmt::Display for AtmError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)?;
        if let Some(recovery) = &self.recovery {
            write!(f, "\n  Recovery: {recovery}")?;
        }
        Ok(())
    }
}

impl StdError for AtmError {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        self.source
            .as_deref()
            .map(|source| source as &(dyn StdError + 'static))
    }
}

impl From<serde_json::Error> for AtmError {
    fn from(source: serde_json::Error) -> Self {
        Self::new(AtmErrorKind::Serialization, format!("json error: {source}"))
            .with_recovery(
                "Inspect the JSON payload for structural errors and verify the schema matches the expected format.",
            )
            .with_source(source)
    }
}

impl From<toml::de::Error> for AtmError {
    fn from(source: toml::de::Error) -> Self {
        Self::new(AtmErrorKind::Config, format!("toml error: {source}"))
            .with_recovery(
                "Inspect the TOML file for syntax errors and verify all required fields are present.",
            )
            .with_source(source)
    }
}

impl AtmErrorKind {
    const fn default_code(self) -> AtmErrorCode {
        match self {
            Self::Config => AtmErrorCode::ConfigParseFailed,
            Self::MissingDocument => AtmErrorCode::ConfigTeamMissing,
            Self::Address => AtmErrorCode::AddressParseFailed,
            Self::Identity => AtmErrorCode::IdentityUnavailable,
            Self::TeamNotFound => AtmErrorCode::TeamNotFound,
            Self::AgentNotFound => AtmErrorCode::AgentNotFound,
            Self::MailboxLock => AtmErrorCode::MailboxLockFailed,
            Self::MailboxRead => AtmErrorCode::MailboxReadFailed,
            Self::MailboxWrite => AtmErrorCode::MailboxWriteFailed,
            Self::FilePolicy => AtmErrorCode::FilePolicyRejected,
            Self::Validation => AtmErrorCode::MessageValidationFailed,
            Self::Serialization => AtmErrorCode::SerializationFailed,
            Self::Timeout => AtmErrorCode::WaitTimeout,
            Self::ObservabilityEmit => AtmErrorCode::ObservabilityEmitFailed,
            Self::ObservabilityBootstrap => AtmErrorCode::ObservabilityBootstrapFailed,
            Self::ObservabilityQuery => AtmErrorCode::ObservabilityQueryFailed,
            Self::ObservabilityFollow => AtmErrorCode::ObservabilityFollowFailed,
            Self::ObservabilityHealth => AtmErrorCode::ObservabilityHealthFailed,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::backtrace::Backtrace;

    use super::{AtmError, AtmErrorCode};

    #[test]
    fn observability_error_helpers_use_expected_codes() {
        assert_eq!(
            AtmError::observability_emit("emit failed").code,
            AtmErrorCode::ObservabilityEmitFailed
        );
        assert_eq!(
            AtmError::observability_bootstrap("bootstrap failed").code,
            AtmErrorCode::ObservabilityBootstrapFailed
        );
        assert_eq!(
            AtmError::observability_query("query failed").code,
            AtmErrorCode::ObservabilityQueryFailed
        );
        assert_eq!(
            AtmError::observability_follow("follow failed").code,
            AtmErrorCode::ObservabilityFollowFailed
        );
        assert_eq!(
            AtmError::observability_health("health failed").code,
            AtmErrorCode::ObservabilityHealthFailed
        );
    }

    #[test]
    fn mailbox_write_helper_includes_recovery_guidance() {
        let error = AtmError::mailbox_write("write failed");

        assert!(error.is_mailbox_write());
        assert!(
            error
                .recovery
                .as_deref()
                .is_some_and(|value| value.contains("writable"))
        );
    }

    #[test]
    fn display_remains_concise_when_backtrace_is_captured() {
        let mut error = AtmError::validation("boom");
        error.backtrace = Backtrace::force_capture();

        let rendered = error.to_string();
        assert!(rendered.contains("boom"));
        assert!(!rendered.contains("Backtrace:"));
        assert!(error.backtrace().is_some());
    }

    #[test]
    fn display_handles_absent_backtrace() {
        let mut error = AtmError::validation("boom");
        error.backtrace = Backtrace::disabled();

        let rendered = error.to_string();
        assert!(rendered.contains("boom"));
        assert!(!rendered.contains("Backtrace:"));
        assert!(error.backtrace().is_none());
    }
}