atm-agent-mcp 0.14.0

MCP proxy for managing Codex agent sessions with ATM team integration
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
//! Auto mail injection for the MCP proxy.
//!
//! Implements FR-8: fetching unread ATM mail and injecting it as `codex-reply`
//! turns into idle Codex threads.
//!
//! # Key types
//!
//! - [`MailEnvelope`] — a single message formatted for injection
//! - [`MailPoller`] — holds polling configuration derived from [`crate::config::AgentMcpConfig`]
//!
//! # Functions
//!
//! - [`fetch_unread_mail`] — read unread messages without marking them read
//! - [`mark_messages_read`] — mark a set of message IDs as read (called only after delivery)
//! - [`build_mail_envelopes`] — convert [`agent_team_mail_core::InboxMessage`] to [`MailEnvelope`]
//! - [`format_mail_turn_content`] — format a slice of envelopes into an injection prompt string

use std::collections::HashSet;
use std::path::PathBuf;
use std::time::Duration;

use agent_team_mail_core::InboxMessage;
use agent_team_mail_core::home::get_home_dir;
use agent_team_mail_core::io::inbox_update;
use agent_team_mail_core::text::truncate_chars;
use serde::{Deserialize, Serialize};

use crate::config::AgentMcpConfig;

// ---------------------------------------------------------------------------
// MailEnvelope
// ---------------------------------------------------------------------------

/// A single inbound message formatted for injection into a Codex turn.
///
/// Wraps the essential metadata from an [`InboxMessage`] together with
/// potentially-truncated text. Serializable so the full envelope can be
/// embedded in the injection prompt.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MailEnvelope {
    /// ATM identity of the sender.
    pub sender: String,
    /// ISO 8601 timestamp of when the message was sent.
    pub timestamp: String,
    /// Unique message ID (used for deduplication and mark-read).
    pub message_id: String,
    /// Message body, possibly truncated.
    pub text: String,
}

// ---------------------------------------------------------------------------
// Formatting
// ---------------------------------------------------------------------------

/// Format a slice of mail envelopes into a prompt string for codex-reply injection.
///
/// Each envelope is rendered with a header line (From / Time / ID) followed by
/// the message body. The entire block is wrapped with a summary count.
///
/// # Examples
///
/// ```
/// use atm_agent_mcp::mail_inject::{MailEnvelope, format_mail_turn_content};
///
/// let env = MailEnvelope {
///     sender: "alice".into(),
///     timestamp: "2026-02-19T10:00:00Z".into(),
///     message_id: "abc".into(),
///     text: "Hello from alice".into(),
/// };
/// let content = format_mail_turn_content(&[env]);
/// assert!(content.contains("1 unread message"));
/// assert!(content.contains("alice"));
/// ```
pub fn format_mail_turn_content(messages: &[MailEnvelope]) -> String {
    let n = messages.len();
    let noun = if n == 1 { "message" } else { "messages" };
    let mut out = format!("You have {n} unread {noun}:\n\n");
    for (i, env) in messages.iter().enumerate() {
        out.push_str(&format!(
            "[{}] From: {} | Time: {} | ID: {}\n{}\n\n",
            i + 1,
            env.sender,
            env.timestamp,
            env.message_id,
            env.text,
        ));
    }
    out.trim_end().to_string()
}

// ---------------------------------------------------------------------------
// Conversion helpers
// ---------------------------------------------------------------------------

/// Convert a slice of [`InboxMessage`] values to [`MailEnvelope`] values.
///
/// Applies:
/// - `max_messages` limit (takes only the first N unread messages)
/// - `max_message_length` truncation: if a message body exceeds the limit,
///   it is cut at that character boundary and `" [...truncated]"` is appended.
///
/// Messages that have no `message_id` are skipped because they cannot be
/// reliably marked read after delivery.
///
/// # Examples
///
/// ```
/// use agent_team_mail_core::InboxMessage;
/// use atm_agent_mcp::mail_inject::build_mail_envelopes;
/// use std::collections::HashMap;
///
/// let msg = InboxMessage {
///     from: "bob".into(),
///     text: "hi".into(),
///     timestamp: "2026-02-19T00:00:00Z".into(),
///     read: false,
///     summary: None,
///     message_id: Some("id-1".into()),
///     unknown_fields: HashMap::new(),
/// };
/// let envelopes = build_mail_envelopes(&[msg], 10, 4096);
/// assert_eq!(envelopes.len(), 1);
/// assert_eq!(envelopes[0].sender, "bob");
/// ```
pub fn build_mail_envelopes(
    messages: &[InboxMessage],
    max_messages: usize,
    max_message_length: usize,
) -> Vec<MailEnvelope> {
    const TRUNCATION_SUFFIX: &str = " [...truncated]";

    messages
        .iter()
        .filter(|m| !m.read && m.message_id.is_some())
        .take(max_messages)
        .map(|m| {
            let text = truncate_chars(&m.text, max_message_length, TRUNCATION_SUFFIX);
            MailEnvelope {
                sender: m.from.clone(),
                timestamp: m.timestamp.clone(),
                message_id: m.message_id.clone().expect("filtered above"),
                text,
            }
        })
        .collect()
}

// ---------------------------------------------------------------------------
// MailPoller
// ---------------------------------------------------------------------------

/// Polling configuration for auto mail injection (FR-8.2, FR-8.8).
///
/// Built from [`AgentMcpConfig`] via [`MailPoller::new`]. Encapsulates all
/// tunable parameters so the proxy loop does not depend on the full config.
#[derive(Debug, Clone)]
pub struct MailPoller {
    /// How often to poll for new mail when a thread is idle.
    pub poll_interval: Duration,
    /// Maximum number of messages to inject per turn (FR-8.5).
    pub max_messages: usize,
    /// Maximum message body length in chars before truncation (FR-8.5).
    pub max_message_length: usize,
    /// Whether auto-mail injection is enabled globally (FR-8.8).
    pub auto_mail_enabled: bool,
}

impl MailPoller {
    /// Build a [`MailPoller`] from the resolved proxy configuration.
    ///
    /// Reads:
    /// - `config.mail_poll_interval_ms` → [`MailPoller::poll_interval`] (default 5000 ms)
    /// - `config.max_mail_messages` → [`MailPoller::max_messages`] (default 10)
    /// - `config.max_mail_message_length` → [`MailPoller::max_message_length`] (default 4096)
    /// - `config.auto_mail` → [`MailPoller::auto_mail_enabled`] (default true)
    pub fn new(config: &AgentMcpConfig) -> Self {
        Self {
            poll_interval: Duration::from_millis(config.mail_poll_interval_ms),
            max_messages: config.max_mail_messages,
            max_message_length: config.max_mail_message_length,
            auto_mail_enabled: config.auto_mail,
        }
    }

    /// Returns `true` when auto-mail injection is globally enabled.
    pub fn is_enabled(&self) -> bool {
        self.auto_mail_enabled
    }
}

// ---------------------------------------------------------------------------
// Inbox path helper
// ---------------------------------------------------------------------------

/// Build the inbox file path for `identity` in `team`.
///
/// Path: `<home>/.claude/teams/<team>/inboxes/<identity>.json`
fn inbox_path(home: &std::path::Path, team: &str, identity: &str) -> PathBuf {
    home.join(".claude")
        .join("teams")
        .join(team)
        .join("inboxes")
        .join(format!("{identity}.json"))
}

// ---------------------------------------------------------------------------
// fetch_unread_mail
// ---------------------------------------------------------------------------

/// Fetch unread messages for `identity` in `team`, returning formatted envelopes.
///
/// Messages are NOT marked as read here — call [`mark_messages_read`] only
/// after the codex-reply has been successfully written to the child's stdin
/// and the request ID recorded (FR-8.12).
///
/// Returns an empty `Vec` when the inbox does not exist or no unread messages
/// are present.
///
/// # Parameters
///
/// - `identity` — the ATM identity whose inbox should be checked
/// - `team` — the ATM team name
/// - `max_messages` — cap on returned envelopes (FR-8.5)
/// - `max_message_length` — per-message character truncation limit (FR-8.5)
pub fn fetch_unread_mail(
    identity: &str,
    team: &str,
    max_messages: usize,
    max_message_length: usize,
) -> Vec<MailEnvelope> {
    let home = match get_home_dir() {
        Ok(h) => h,
        Err(e) => {
            tracing::warn!("fetch_unread_mail: cannot resolve home dir: {e}");
            return Vec::new();
        }
    };

    let path = inbox_path(&home, team, identity);
    if !path.exists() {
        return Vec::new();
    }

    let content = match std::fs::read(&path) {
        Ok(c) => c,
        Err(e) => {
            tracing::warn!(
                "fetch_unread_mail: cannot read inbox for '{}': {e}",
                identity
            );
            return Vec::new();
        }
    };

    let messages: Vec<InboxMessage> = match serde_json::from_slice(&content) {
        Ok(m) => m,
        Err(e) => {
            tracing::warn!(
                "fetch_unread_mail: failed to parse inbox for '{}': {e}",
                identity
            );
            return Vec::new();
        }
    };

    build_mail_envelopes(&messages, max_messages, max_message_length)
}

// ---------------------------------------------------------------------------
// mark_messages_read
// ---------------------------------------------------------------------------

/// Mark the specified message IDs as read in `identity`'s inbox in `team`.
///
/// This is a best-effort operation: failures are logged as warnings but do
/// not propagate. Callers should invoke this only **after** the codex-reply
/// has been written to the child stdin and the request ID has been recorded
/// (FR-8.12).
///
/// Messages whose `message_id` is `None` are never matched, consistent with
/// how [`build_mail_envelopes`] skips them.
pub fn mark_messages_read(identity: &str, team: &str, message_ids: &[String]) {
    if message_ids.is_empty() {
        return;
    }

    let home = match get_home_dir() {
        Ok(h) => h,
        Err(e) => {
            tracing::warn!("mark_messages_read: cannot resolve home dir: {e}");
            return;
        }
    };

    let path = inbox_path(&home, team, identity);
    if !path.exists() {
        return;
    }

    let ids_set: HashSet<&str> = message_ids.iter().map(|s| s.as_str()).collect();
    if let Err(e) = inbox_update(&path, team, identity, |messages| {
        for msg in messages.iter_mut() {
            if let Some(ref mid) = msg.message_id {
                if ids_set.contains(mid.as_str()) {
                    msg.read = true;
                }
            }
        }
    }) {
        tracing::warn!("mark_messages_read: failed atomic update for '{}': {e}", identity);
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use agent_team_mail_core::InboxMessage;
    use serial_test::serial;
    use std::collections::HashMap;
    use std::fs;
    use tempfile::TempDir;

    // -----------------------------------------------------------------------
    // Test helpers
    // -----------------------------------------------------------------------

    fn set_atm_home(dir: &TempDir) {
        unsafe { std::env::set_var("ATM_HOME", dir.path()) };
    }

    fn unset_atm_home() {
        unsafe { std::env::remove_var("ATM_HOME") };
    }

    fn make_msg(from: &str, text: &str, read: bool, id: Option<&str>) -> InboxMessage {
        InboxMessage {
            from: from.to_string(),
            text: text.to_string(),
            timestamp: "2026-02-19T10:00:00Z".to_string(),
            read,
            summary: None,
            message_id: id.map(|s| s.to_string()),
            unknown_fields: HashMap::new(),
        }
    }

    fn seed_inbox(home: &std::path::Path, team: &str, agent: &str, messages: &[InboxMessage]) {
        let dir = home
            .join(".claude")
            .join("teams")
            .join(team)
            .join("inboxes");
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join(format!("{agent}.json"));
        fs::write(&path, serde_json::to_string_pretty(messages).unwrap()).unwrap();
    }

    fn read_inbox_file(home: &std::path::Path, team: &str, agent: &str) -> Vec<InboxMessage> {
        let path = home
            .join(".claude")
            .join("teams")
            .join(team)
            .join("inboxes")
            .join(format!("{agent}.json"));
        let content = fs::read_to_string(&path).unwrap();
        serde_json::from_str(&content).unwrap()
    }

    // -----------------------------------------------------------------------
    // format_mail_turn_content
    // -----------------------------------------------------------------------

    #[test]
    fn format_single_message() {
        let env = MailEnvelope {
            sender: "alice".into(),
            timestamp: "2026-02-19T10:00:00Z".into(),
            message_id: "msg-1".into(),
            text: "Hello from alice".into(),
        };
        let content = format_mail_turn_content(&[env]);
        assert!(content.contains("1 unread message"), "singular noun");
        assert!(content.contains("[1]"));
        assert!(content.contains("alice"));
        assert!(content.contains("msg-1"));
        assert!(content.contains("Hello from alice"));
    }

    #[test]
    fn format_multiple_messages_plural_noun() {
        let envs: Vec<MailEnvelope> = (0..3)
            .map(|i| MailEnvelope {
                sender: format!("sender{i}"),
                timestamp: "2026-02-19T10:00:00Z".into(),
                message_id: format!("id-{i}"),
                text: format!("body {i}"),
            })
            .collect();
        let content = format_mail_turn_content(&envs);
        assert!(content.contains("3 unread messages"), "plural noun");
        assert!(content.contains("[3]"));
    }

    // -----------------------------------------------------------------------
    // build_mail_envelopes
    // -----------------------------------------------------------------------

    #[test]
    fn build_envelopes_skips_read_messages() {
        let messages = vec![
            make_msg("a", "unread", false, Some("id-1")),
            make_msg("b", "already read", true, Some("id-2")),
        ];
        let envelopes = build_mail_envelopes(&messages, 10, 4096);
        assert_eq!(envelopes.len(), 1);
        assert_eq!(envelopes[0].message_id, "id-1");
    }

    #[test]
    fn build_envelopes_skips_messages_without_id() {
        let messages = vec![
            make_msg("a", "no id", false, None),
            make_msg("b", "has id", false, Some("id-1")),
        ];
        let envelopes = build_mail_envelopes(&messages, 10, 4096);
        assert_eq!(envelopes.len(), 1);
        assert_eq!(envelopes[0].message_id, "id-1");
    }

    #[test]
    fn build_envelopes_max_messages_limit() {
        let messages: Vec<InboxMessage> = (0..10)
            .map(|i| make_msg("s", &format!("msg{i}"), false, Some(&format!("id-{i}"))))
            .collect();
        let envelopes = build_mail_envelopes(&messages, 3, 4096);
        assert_eq!(envelopes.len(), 3);
    }

    #[test]
    fn build_envelopes_truncates_long_text() {
        let long_text = "x".repeat(100);
        let messages = vec![make_msg("a", &long_text, false, Some("id-1"))];
        let envelopes = build_mail_envelopes(&messages, 10, 10);
        assert_eq!(envelopes.len(), 1);
        assert!(envelopes[0].text.ends_with(" [...truncated]"));
        // Verify first 10 chars of content preserved
        let expected_prefix: String = long_text.chars().take(10).collect();
        let actual_prefix: String = envelopes[0].text.chars().take(10).collect();
        assert_eq!(actual_prefix, expected_prefix);
    }

    #[test]
    fn build_envelopes_no_truncation_at_exact_limit() {
        let text = "x".repeat(50);
        let messages = vec![make_msg("a", &text, false, Some("id-1"))];
        let envelopes = build_mail_envelopes(&messages, 10, 50);
        assert_eq!(envelopes[0].text, text);
        assert!(!envelopes[0].text.contains("truncated"));
    }

    #[test]
    fn build_envelopes_truncation_is_utf8_safe() {
        let text = "é".repeat(20);
        let messages = vec![make_msg("a", &text, false, Some("id-1"))];
        let envelopes = build_mail_envelopes(&messages, 10, 5);
        assert_eq!(envelopes.len(), 1);
        assert!(envelopes[0].text.ends_with(" [...truncated]"));
    }

    // -----------------------------------------------------------------------
    // MailPoller::new
    // -----------------------------------------------------------------------

    #[test]
    fn mail_poller_uses_config_defaults() {
        let config = AgentMcpConfig::default();
        let poller = MailPoller::new(&config);
        assert_eq!(poller.poll_interval, Duration::from_millis(5000));
        assert_eq!(poller.max_messages, 10);
        assert_eq!(poller.max_message_length, 4096);
        assert!(poller.is_enabled());
    }

    #[test]
    fn mail_poller_disabled_when_auto_mail_false() {
        let config = AgentMcpConfig {
            auto_mail: false,
            ..Default::default()
        };
        let poller = MailPoller::new(&config);
        assert!(!poller.is_enabled());
    }

    #[test]
    fn mail_poller_custom_values() {
        let config = AgentMcpConfig {
            mail_poll_interval_ms: 2000,
            max_mail_messages: 5,
            max_mail_message_length: 1024,
            ..Default::default()
        };
        let poller = MailPoller::new(&config);
        assert_eq!(poller.poll_interval, Duration::from_millis(2000));
        assert_eq!(poller.max_messages, 5);
        assert_eq!(poller.max_message_length, 1024);
    }

    // -----------------------------------------------------------------------
    // fetch_unread_mail
    // -----------------------------------------------------------------------

    #[test]
    #[serial]
    fn fetch_returns_empty_when_inbox_missing() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);
        let envelopes = fetch_unread_mail("nobody", "team", 10, 4096);
        unset_atm_home();
        assert!(envelopes.is_empty());
    }

    #[test]
    #[serial]
    fn fetch_returns_unread_envelopes() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        seed_inbox(
            dir.path(),
            "team",
            "agent",
            &[
                make_msg("alice", "hello", false, Some("id-1")),
                make_msg("bob", "already read", true, Some("id-2")),
            ],
        );

        let envelopes = fetch_unread_mail("agent", "team", 10, 4096);
        unset_atm_home();

        assert_eq!(envelopes.len(), 1);
        assert_eq!(envelopes[0].sender, "alice");
        assert_eq!(envelopes[0].message_id, "id-1");
    }

    #[test]
    #[serial]
    fn fetch_does_not_mark_messages_read() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        seed_inbox(
            dir.path(),
            "team",
            "agent",
            &[make_msg("alice", "hello", false, Some("id-1"))],
        );

        fetch_unread_mail("agent", "team", 10, 4096);
        let messages = read_inbox_file(dir.path(), "team", "agent");
        unset_atm_home();

        assert!(!messages[0].read, "fetch must not mark messages as read");
    }

    // -----------------------------------------------------------------------
    // mark_messages_read
    // -----------------------------------------------------------------------

    #[test]
    #[serial]
    fn mark_read_updates_inbox_file() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        seed_inbox(
            dir.path(),
            "team",
            "agent",
            &[
                make_msg("a", "msg1", false, Some("id-1")),
                make_msg("b", "msg2", false, Some("id-2")),
            ],
        );

        mark_messages_read("agent", "team", &["id-1".to_string()]);
        let messages = read_inbox_file(dir.path(), "team", "agent");
        unset_atm_home();

        let msg1 = messages.iter().find(|m| m.message_id.as_deref() == Some("id-1")).unwrap();
        let msg2 = messages.iter().find(|m| m.message_id.as_deref() == Some("id-2")).unwrap();
        assert!(msg1.read, "id-1 should be marked read");
        assert!(!msg2.read, "id-2 should remain unread");
    }

    #[test]
    #[serial]
    fn mark_read_noop_on_empty_id_list() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        seed_inbox(
            dir.path(),
            "team",
            "agent",
            &[make_msg("a", "msg", false, Some("id-1"))],
        );

        mark_messages_read("agent", "team", &[]);
        let messages = read_inbox_file(dir.path(), "team", "agent");
        unset_atm_home();

        assert!(!messages[0].read, "no messages should be marked when ids list is empty");
    }

    #[test]
    #[serial]
    fn mark_read_noop_when_inbox_missing() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);
        // Should not panic when inbox doesn't exist
        mark_messages_read("nobody", "team", &["id-1".to_string()]);
        unset_atm_home();
    }

    // -----------------------------------------------------------------------
    // Delivery sequencing: fetch → format → dispatch → mark-read
    // -----------------------------------------------------------------------

    #[test]
    #[serial]
    fn full_injection_sequence_marks_read_only_after_delivery() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        seed_inbox(
            dir.path(),
            "team",
            "agent",
            &[
                make_msg("alice", "msg-a", false, Some("m-a")),
                make_msg("bob", "msg-b", false, Some("m-b")),
            ],
        );

        // Step 1: fetch (no mark-read yet)
        let envelopes = fetch_unread_mail("agent", "team", 10, 4096);
        assert_eq!(envelopes.len(), 2);

        // Step 2: messages still unread
        {
            let msgs = read_inbox_file(dir.path(), "team", "agent");
            assert!(msgs.iter().all(|m| !m.read), "must remain unread before delivery");
        }

        // Step 3: format content (simulates writing to child stdin)
        let content = format_mail_turn_content(&envelopes);
        assert!(content.contains("alice"));

        // Step 4: mark read (called after successful child write)
        let ids: Vec<String> = envelopes.iter().map(|e| e.message_id.clone()).collect();
        mark_messages_read("agent", "team", &ids);

        // Step 5: verify messages are now read
        let msgs = read_inbox_file(dir.path(), "team", "agent");
        unset_atm_home();
        assert!(msgs.iter().all(|m| m.read), "all messages should be marked read after delivery");
    }
}