agent-team-mail-core 0.13.0

Core library for agent-team-mail: file-based messaging for AI agent teams
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
//! Inbox file operations with atomic writes and conflict detection

use crate::io::{atomic::atomic_swap, error::InboxError, hash::compute_hash, lock::acquire_lock};
use crate::schema::InboxMessage;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};

/// Outcome of an inbox write operation
#[derive(Debug, Clone, PartialEq)]
pub enum WriteOutcome {
    /// Clean write with no conflicts detected
    Success,

    /// Concurrent write detected and merged automatically
    ConflictResolved { merged_messages: usize },

    /// Could not write immediately, message queued for later delivery
    Queued { spool_path: PathBuf },
}

/// Atomically append a message to an inbox with conflict detection
///
/// This implements the atomic write strategy with lock, hash, swap, and
/// conflict merge. If the lock cannot be acquired, the message is spooled
/// for later delivery.
///
/// # Arguments
///
/// * `inbox_path` - Full path to inbox.json file
/// * `message` - Message to append
/// * `team` - Target team name (for spooling)
/// * `agent` - Target agent name (for spooling)
///
/// # Returns
///
/// * `Success` - Message written cleanly
/// * `ConflictResolved` - Concurrent write detected and merged
/// * `Queued` - Lock timeout, message spooled for retry
///
/// # Errors
///
/// Returns `InboxError` for I/O errors, JSON parse errors, or merge failures.
pub fn inbox_append(
    inbox_path: &Path,
    message: &InboxMessage,
    team: &str,
    agent: &str,
) -> Result<WriteOutcome, InboxError> {
    let msg_clone = message.clone();
    match atomic_write_with_conflict_check(inbox_path, |messages| {
        // Deduplication check
        if let Some(ref msg_id) = msg_clone.message_id
            && messages
                .iter()
                .any(|m| m.message_id.as_ref() == Some(msg_id))
        {
            return false;
        }
        messages.push(msg_clone);
        true
    }) {
        Ok(outcome) => Ok(outcome),
        Err(InboxError::LockTimeout { .. }) => {
            // Could not acquire lock - spool for later delivery
            let spool_path = crate::io::spool::spool_message(team, agent, message)?;
            Ok(WriteOutcome::Queued { spool_path })
        }
        Err(e) => Err(e),
    }
}

/// Atomically update messages in an inbox using a closure
///
/// Acquires the inbox lock, reads current messages, applies the update
/// closure, and writes back atomically with conflict detection.
///
/// # Arguments
///
/// * `inbox_path` - Full path to inbox.json file
/// * `team` - Target team name (reserved for future use)
/// * `agent` - Target agent name (reserved for future use)
/// * `update_fn` - Closure that modifies the message vector in place
///
/// # Errors
///
/// Returns `InboxError` for I/O errors, JSON parse errors, lock timeout,
/// or merge failures.
pub fn inbox_update<F>(
    inbox_path: &Path,
    _team: &str,
    _agent: &str,
    update_fn: F,
) -> Result<(), InboxError>
where
    F: FnOnce(&mut Vec<InboxMessage>),
{
    atomic_write_with_conflict_check(inbox_path, |messages| {
        update_fn(messages);
        true
    })?;
    Ok(())
}

/// Shared atomic write logic for inbox operations
///
/// Acquires lock, reads current file, applies modification via closure,
/// writes atomically with conflict detection and merge.
///
/// The `modify_fn` closure receives the current messages and returns `true`
/// if modifications were made (triggering a write), or `false` to skip
/// the write (e.g., duplicate detection).
fn atomic_write_with_conflict_check<F>(
    inbox_path: &Path,
    modify_fn: F,
) -> Result<WriteOutcome, InboxError>
where
    F: FnOnce(&mut Vec<InboxMessage>) -> bool,
{
    let lock_path = inbox_path.with_extension("lock");
    let tmp_path = inbox_path.with_extension("tmp");

    // Step 1: Acquire lock with retry
    let _lock = acquire_lock(&lock_path, 5)?;

    // Step 2: Read current inbox and compute hash
    let (mut messages, original_hash) = if inbox_path.exists() {
        let content = fs::read(inbox_path).map_err(|e| InboxError::Io {
            path: inbox_path.to_path_buf(),
            source: e,
        })?;
        let hash = compute_hash(&content);
        let msgs: Vec<InboxMessage> =
            serde_json::from_slice(&content).map_err(|e| InboxError::Json {
                path: inbox_path.to_path_buf(),
                source: e,
            })?;
        (msgs, hash)
    } else {
        // New inbox file
        (Vec::new(), compute_hash(b"[]"))
    };

    // Step 3: Apply modification
    if !modify_fn(&mut messages) {
        // No changes needed (e.g., duplicate message)
        return Ok(WriteOutcome::Success);
    }

    // Step 4: Write to tmp file with fsync
    let new_content =
        serde_json::to_vec_pretty(&messages).map_err(|e| InboxError::Json {
            path: tmp_path.clone(),
            source: e,
        })?;

    {
        let mut tmp_file = fs::File::create(&tmp_path).map_err(|e| InboxError::Io {
            path: tmp_path.clone(),
            source: e,
        })?;

        tmp_file
            .write_all(&new_content)
            .map_err(|e| InboxError::Io {
                path: tmp_path.clone(),
                source: e,
            })?;

        tmp_file.sync_all().map_err(|e| InboxError::Io {
            path: tmp_path.clone(),
            source: e,
        })?;
    }

    // Step 5: Atomic swap
    if !inbox_path.exists() {
        // First time creating inbox - just rename
        fs::rename(&tmp_path, inbox_path).map_err(|e| InboxError::Io {
            path: inbox_path.to_path_buf(),
            source: e,
        })?;
        return Ok(WriteOutcome::Success);
    }

    atomic_swap(inbox_path, &tmp_path)?;

    // Step 6: Check for concurrent writes
    let displaced_content = fs::read(&tmp_path).map_err(|e| InboxError::Io {
        path: tmp_path.clone(),
        source: e,
    })?;
    let displaced_hash = compute_hash(&displaced_content);

    let outcome = if displaced_hash != original_hash {
        // Step 7: Conflict detected - merge and re-swap
        let displaced_messages: Vec<InboxMessage> =
            serde_json::from_slice(&displaced_content).map_err(|e| InboxError::Json {
                path: tmp_path.clone(),
                source: e,
            })?;

        // Merge: add messages from displaced that aren't in our version
        let merged = merge_messages(&messages, &displaced_messages);
        let merge_count = merged.len() - messages.len();

        // Write merged version back
        let merged_content =
            serde_json::to_vec_pretty(&merged).map_err(|e| InboxError::Json {
                path: tmp_path.clone(),
                source: e,
            })?;

        fs::write(&tmp_path, &merged_content).map_err(|e| InboxError::Io {
            path: tmp_path.clone(),
            source: e,
        })?;

        // Re-swap
        atomic_swap(inbox_path, &tmp_path)?;

        WriteOutcome::ConflictResolved {
            merged_messages: merge_count,
        }
    } else {
        WriteOutcome::Success
    };

    // Step 8: Lock released automatically on drop
    // Step 9: Delete tmp file
    let _ = fs::remove_file(&tmp_path); // Ignore errors on cleanup

    Ok(outcome)
}

/// Read and merge messages from all inbox files for an agent (local + remote origins)
///
/// This reads the local inbox file (`<agent>.json`) and all per-origin files
/// (`<agent>.<hostname>.json`), merges them, deduplicates by `message_id`,
/// and sorts by timestamp.
///
/// # Arguments
///
/// * `team_dir` - Path to team directory (e.g., `~/.claude/teams/my-team`)
/// * `agent_name` - Agent name to read messages for
/// * `hostname_registry` - Optional hostname registry for filtering origin files
///
/// # Returns
///
/// A vector of merged and deduplicated messages, sorted by timestamp.
/// Returns empty vec if no inbox files exist for the agent.
///
/// # Errors
///
/// Returns `InboxError::Io` for file system errors or `InboxError::Json` for parse errors.
pub fn inbox_read_merged(
    team_dir: &Path,
    agent_name: &str,
    hostname_registry: Option<&crate::config::HostnameRegistry>,
) -> Result<Vec<InboxMessage>, InboxError> {
    let inboxes_dir = team_dir.join("inboxes");
    if !inboxes_dir.exists() {
        return Ok(Vec::new());
    }

    // Collect all inbox files for this agent
    let mut all_messages = Vec::new();
    let mut seen_ids: std::collections::HashSet<String> = std::collections::HashSet::new();

    // Read entries from inboxes directory
    let entries = fs::read_dir(&inboxes_dir).map_err(|e| InboxError::Io {
        path: inboxes_dir.clone(),
        source: e,
    })?;

    for entry in entries {
        let entry = entry.map_err(|e| InboxError::Io {
            path: inboxes_dir.clone(),
            source: e,
        })?;

        let path = entry.path();
        if !path.is_file() {
            continue;
        }

        // Check if this is an inbox file for our agent
        let file_name = match path.file_name().and_then(|n| n.to_str()) {
            Some(name) => name,
            None => continue,
        };

        // Must end with .json
        if !file_name.ends_with(".json") {
            continue;
        }

        // Check if this is the local inbox or an origin inbox
        let is_match = if file_name == format!("{agent_name}.json") {
            // Local inbox file
            true
        } else if let Some(stem) = file_name.strip_suffix(".json") {
            // Could be an origin file: <agent>.<hostname>.json
            // Need to check if stem starts with agent_name followed by a dot
            if let Some(suffix) = stem.strip_prefix(&format!("{agent_name}.")) {
                // Check if suffix is a known hostname (if registry provided)
                if let Some(registry) = hostname_registry {
                    registry.is_known_hostname(suffix)
                } else {
                    // No registry - skip origin files (backward compatible)
                    false
                }
            } else {
                false
            }
        } else {
            false
        };

        if !is_match {
            continue;
        }

        // Read and parse the inbox file
        let content = fs::read(&path).map_err(|e| InboxError::Io {
            path: path.clone(),
            source: e,
        })?;

        let messages: Vec<InboxMessage> =
            serde_json::from_slice(&content).map_err(|e| InboxError::Json {
                path: path.clone(),
                source: e,
            })?;

        // Add messages, deduplicating by message_id
        for msg in messages {
            if let Some(ref msg_id) = msg.message_id {
                if seen_ids.contains(msg_id) {
                    continue; // Already seen, skip
                }
                seen_ids.insert(msg_id.clone());
            }
            all_messages.push(msg);
        }
    }

    // Sort by timestamp (stable tie-breaker: message_id)
    all_messages.sort_by(|a, b| {
        match a.timestamp.cmp(&b.timestamp) {
            std::cmp::Ordering::Equal => {
                // Stable tie-breaker: message_id
                match (&a.message_id, &b.message_id) {
                    (Some(id_a), Some(id_b)) => id_a.cmp(id_b),
                    (Some(_), None) => std::cmp::Ordering::Less,
                    (None, Some(_)) => std::cmp::Ordering::Greater,
                    (None, None) => std::cmp::Ordering::Equal,
                }
            }
            other => other,
        }
    });

    Ok(all_messages)
}

/// Merge two message arrays, preserving order and deduplicating by message_id
fn merge_messages(
    our_messages: &[InboxMessage],
    their_messages: &[InboxMessage],
) -> Vec<InboxMessage> {
    let mut merged = our_messages.to_vec();
    let our_ids: std::collections::HashSet<_> = our_messages
        .iter()
        .filter_map(|m| m.message_id.as_ref())
        .collect();

    // Add messages from their version that we don't have
    for msg in their_messages {
        let already_present = if let Some(ref msg_id) = msg.message_id {
            our_ids.contains(msg_id)
        } else {
            // No message_id - check by content (less reliable)
            our_messages
                .iter()
                .any(|m| m.from == msg.from && m.text == msg.text && m.timestamp == msg.timestamp)
        };

        if !already_present {
            merged.push(msg.clone());
        }
    }

    // Sort by timestamp to maintain chronological order
    merged.sort_by(|a, b| a.timestamp.cmp(&b.timestamp));
    merged
}


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

    fn create_test_message(from: &str, text: &str, message_id: Option<String>) -> InboxMessage {
        InboxMessage {
            from: from.to_string(),
            text: text.to_string(),
            timestamp: chrono::Utc::now().to_rfc3339(),
            read: false,
            summary: None,
            message_id,
            unknown_fields: HashMap::new(),
        }
    }

    #[test]
    fn test_inbox_append_new_file() {
        let temp_dir = TempDir::new().unwrap();
        let inbox_path = temp_dir.path().join("agent.json");

        let message = create_test_message("team-lead", "Test message", Some("msg-001".to_string()));

        let outcome = inbox_append(&inbox_path, &message, "test-team", "test-agent").unwrap();
        assert_eq!(outcome, WriteOutcome::Success);

        // Verify file was created and contains message
        let content = fs::read_to_string(&inbox_path).unwrap();
        let messages: Vec<InboxMessage> = serde_json::from_str(&content).unwrap();
        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0].from, "team-lead");
        assert_eq!(messages[0].text, "Test message");
    }

    #[test]
    fn test_inbox_append_existing_file() {
        let temp_dir = TempDir::new().unwrap();
        let inbox_path = temp_dir.path().join("agent.json");

        // Create initial message
        let msg1 = create_test_message("team-lead", "Message 1", Some("msg-001".to_string()));
        inbox_append(&inbox_path, &msg1, "test-team", "test-agent").unwrap();

        // Append second message
        let msg2 = create_test_message("ci-agent", "Message 2", Some("msg-002".to_string()));
        let outcome = inbox_append(&inbox_path, &msg2, "test-team", "test-agent").unwrap();
        assert_eq!(outcome, WriteOutcome::Success);

        // Verify both messages present
        let content = fs::read_to_string(&inbox_path).unwrap();
        let messages: Vec<InboxMessage> = serde_json::from_str(&content).unwrap();
        assert_eq!(messages.len(), 2);
        assert_eq!(messages[0].text, "Message 1");
        assert_eq!(messages[1].text, "Message 2");
    }

    #[test]
    fn test_inbox_append_deduplication() {
        let temp_dir = TempDir::new().unwrap();
        let inbox_path = temp_dir.path().join("agent.json");

        let message = create_test_message("team-lead", "Test message", Some("msg-001".to_string()));

        // First append
        inbox_append(&inbox_path, &message, "test-team", "test-agent").unwrap();

        // Second append with same message_id - should be deduplicated
        let outcome = inbox_append(&inbox_path, &message, "test-team", "test-agent").unwrap();
        assert_eq!(outcome, WriteOutcome::Success);

        // Verify only one message present
        let content = fs::read_to_string(&inbox_path).unwrap();
        let messages: Vec<InboxMessage> = serde_json::from_str(&content).unwrap();
        assert_eq!(messages.len(), 1);
    }

    #[test]
    fn test_merge_messages_no_duplicates() {
        let msg1 = create_test_message("team-lead", "Message 1", Some("msg-001".to_string()));
        let msg2 = create_test_message("ci-agent", "Message 2", Some("msg-002".to_string()));
        let msg3 = create_test_message("qa-agent", "Message 3", Some("msg-003".to_string()));

        let our_messages = vec![msg1.clone(), msg2.clone()];
        let their_messages = vec![msg1.clone(), msg3.clone()];

        let merged = merge_messages(&our_messages, &their_messages);

        assert_eq!(merged.len(), 3);
        assert!(merged.iter().any(|m| m.message_id == Some("msg-001".to_string())));
        assert!(merged.iter().any(|m| m.message_id == Some("msg-002".to_string())));
        assert!(merged.iter().any(|m| m.message_id == Some("msg-003".to_string())));
    }

    #[test]
    fn test_merge_messages_preserves_order() {
        let mut msg1 = create_test_message("team-lead", "Message 1", Some("msg-001".to_string()));
        msg1.timestamp = "2026-02-11T10:00:00Z".to_string();

        let mut msg2 = create_test_message("ci-agent", "Message 2", Some("msg-002".to_string()));
        msg2.timestamp = "2026-02-11T11:00:00Z".to_string();

        let mut msg3 = create_test_message("qa-agent", "Message 3", Some("msg-003".to_string()));
        msg3.timestamp = "2026-02-11T10:30:00Z".to_string();

        let our_messages = vec![msg1.clone(), msg2.clone()];
        let their_messages = vec![msg3.clone()];

        let merged = merge_messages(&our_messages, &their_messages);

        // Should be sorted by timestamp: msg1, msg3, msg2
        assert_eq!(merged.len(), 3);
        assert_eq!(merged[0].timestamp, "2026-02-11T10:00:00Z");
        assert_eq!(merged[1].timestamp, "2026-02-11T10:30:00Z");
        assert_eq!(merged[2].timestamp, "2026-02-11T11:00:00Z");
    }

    #[test]
    fn test_merge_messages_without_message_id() {
        let mut msg1 = create_test_message("team-lead", "Unique message", None);
        msg1.timestamp = "2026-02-11T10:00:00Z".to_string();

        let mut msg2 = create_test_message("team-lead", "Unique message", None);
        msg2.timestamp = "2026-02-11T10:00:00Z".to_string(); // Exact same timestamp

        let our_messages = vec![msg1.clone()];
        let their_messages = vec![msg2.clone()];

        let merged = merge_messages(&our_messages, &their_messages);

        // Should deduplicate by content (from, text, timestamp match)
        assert_eq!(merged.len(), 1);
    }

    #[test]
    fn test_inbox_append_preserves_unknown_fields() {
        let temp_dir = TempDir::new().unwrap();
        let inbox_path = temp_dir.path().join("agent.json");

        // Create inbox with unknown fields
        let json = r#"[{
            "from": "team-lead",
            "text": "Existing message",
            "timestamp": "2026-02-11T10:00:00Z",
            "read": false,
            "unknownField": "should be preserved",
            "futureFeature": {"nested": "data"}
        }]"#;
        fs::write(&inbox_path, json).unwrap();

        // Append new message
        let new_message = create_test_message("ci-agent", "New message", Some("msg-002".to_string()));
        inbox_append(&inbox_path, &new_message, "test-team", "test-agent").unwrap();

        // Verify unknown fields preserved
        let content = fs::read_to_string(&inbox_path).unwrap();
        let messages: Vec<InboxMessage> = serde_json::from_str(&content).unwrap();
        assert_eq!(messages.len(), 2);
        assert!(messages[0].unknown_fields.contains_key("unknownField"));
        assert!(messages[0].unknown_fields.contains_key("futureFeature"));
    }

    #[test]
    fn test_inbox_update_marks_read() {
        let temp_dir = TempDir::new().unwrap();
        let inbox_path = temp_dir.path().join("agent.json");

        // Seed inbox with unread messages
        let msg1 = create_test_message("user-a", "Message 1", Some("msg-001".to_string()));
        let msg2 = create_test_message("user-b", "Message 2", Some("msg-002".to_string()));
        inbox_append(&inbox_path, &msg1, "test-team", "test-agent").unwrap();
        inbox_append(&inbox_path, &msg2, "test-team", "test-agent").unwrap();

        // Mark all as read via inbox_update
        inbox_update(&inbox_path, "test-team", "test-agent", |messages| {
            for msg in messages.iter_mut() {
                msg.read = true;
            }
        })
        .unwrap();

        // Verify all marked as read
        let content = fs::read_to_string(&inbox_path).unwrap();
        let messages: Vec<InboxMessage> = serde_json::from_str(&content).unwrap();
        assert_eq!(messages.len(), 2);
        assert!(messages[0].read);
        assert!(messages[1].read);
    }

    #[test]
    fn test_inbox_update_concurrent_writes() {
        use std::sync::{Arc, Barrier};
        use std::thread;

        let temp_dir = TempDir::new().unwrap();
        let inbox_path = temp_dir.path().join("agent.json");

        // Seed inbox with messages to update
        let msg1 = create_test_message("user-a", "Message 1", Some("msg-001".to_string()));
        let msg2 = create_test_message("user-b", "Message 2", Some("msg-002".to_string()));
        inbox_append(&inbox_path, &msg1, "test-team", "test-agent").unwrap();
        inbox_append(&inbox_path, &msg2, "test-team", "test-agent").unwrap();

        let inbox_path = Arc::new(inbox_path);
        let barrier = Arc::new(Barrier::new(2));

        // Thread 1: Mark messages as read via inbox_update
        let path1 = Arc::clone(&inbox_path);
        let barrier1 = Arc::clone(&barrier);
        let handle1 = thread::spawn(move || {
            barrier1.wait();
            inbox_update(&path1, "test-team", "test-agent", |messages| {
                for msg in messages.iter_mut() {
                    msg.read = true;
                }
            })
            .unwrap();
        });

        // Thread 2: Append a new message via inbox_append
        let path2 = Arc::clone(&inbox_path);
        let barrier2 = Arc::clone(&barrier);
        let handle2 = thread::spawn(move || {
            barrier2.wait();
            let msg3 = create_test_message("user-c", "Message 3", Some("msg-003".to_string()));
            inbox_append(&path2, &msg3, "test-team", "test-agent").unwrap();
        });

        handle1.join().unwrap();
        handle2.join().unwrap();

        // Verify: all messages present (no data loss)
        let content = fs::read_to_string(&*inbox_path).unwrap();
        let messages: Vec<InboxMessage> = serde_json::from_str(&content).unwrap();
        assert_eq!(messages.len(), 3, "No messages should be lost");
        assert!(
            messages.iter().any(|m| m.message_id == Some("msg-001".to_string())),
            "msg-001 should be present"
        );
        assert!(
            messages.iter().any(|m| m.message_id == Some("msg-002".to_string())),
            "msg-002 should be present"
        );
        assert!(
            messages.iter().any(|m| m.message_id == Some("msg-003".to_string())),
            "msg-003 should be present"
        );
    }

    #[test]
    fn test_inbox_read_merged_empty_directory() {
        let temp_dir = TempDir::new().unwrap();
        let team_dir = temp_dir.path();

        // No inboxes directory exists
        let messages = super::inbox_read_merged(team_dir, "agent-1", None).unwrap();
        assert!(messages.is_empty());
    }

    #[test]
    fn test_inbox_read_merged_local_only() {
        let temp_dir = TempDir::new().unwrap();
        let team_dir = temp_dir.path();
        let inboxes_dir = team_dir.join("inboxes");
        fs::create_dir_all(&inboxes_dir).unwrap();

        // Create local inbox file
        let inbox_path = inboxes_dir.join("agent-1.json");
        let msg1 = create_test_message("user-a", "Local message 1", Some("msg-001".to_string()));
        let msg2 = create_test_message("user-b", "Local message 2", Some("msg-002".to_string()));
        let json = serde_json::to_string_pretty(&vec![msg1, msg2]).unwrap();
        fs::write(&inbox_path, json).unwrap();

        // Read merged (no hostname registry)
        let messages = super::inbox_read_merged(team_dir, "agent-1", None).unwrap();
        assert_eq!(messages.len(), 2);
        assert_eq!(messages[0].text, "Local message 1");
        assert_eq!(messages[1].text, "Local message 2");
    }

    #[test]
    fn test_inbox_read_merged_with_origin_files() {
        use crate::config::{HostnameRegistry, RemoteConfig};

        let temp_dir = TempDir::new().unwrap();
        let team_dir = temp_dir.path();
        let inboxes_dir = team_dir.join("inboxes");
        fs::create_dir_all(&inboxes_dir).unwrap();

        // Create hostname registry
        let mut registry = HostnameRegistry::new();
        registry
            .register(RemoteConfig {
                hostname: "remote1".to_string(),
                address: "user@remote1".to_string(),
                ssh_key_path: None,
                aliases: Vec::new(),
            })
            .unwrap();
        registry
            .register(RemoteConfig {
                hostname: "remote2".to_string(),
                address: "user@remote2".to_string(),
                ssh_key_path: None,
                aliases: Vec::new(),
            })
            .unwrap();

        // Create local inbox
        let local_path = inboxes_dir.join("agent-1.json");
        let mut msg1 = create_test_message("user-a", "Local message", Some("msg-001".to_string()));
        msg1.timestamp = "2026-02-11T10:00:00Z".to_string();
        fs::write(&local_path, serde_json::to_string_pretty(&vec![msg1]).unwrap()).unwrap();

        // Create origin inbox from remote1
        let origin1_path = inboxes_dir.join("agent-1.remote1.json");
        let mut msg2 = create_test_message("user-b", "Remote1 message", Some("msg-002".to_string()));
        msg2.timestamp = "2026-02-11T10:05:00Z".to_string();
        fs::write(&origin1_path, serde_json::to_string_pretty(&vec![msg2]).unwrap()).unwrap();

        // Create origin inbox from remote2
        let origin2_path = inboxes_dir.join("agent-1.remote2.json");
        let mut msg3 = create_test_message("user-c", "Remote2 message", Some("msg-003".to_string()));
        msg3.timestamp = "2026-02-11T10:10:00Z".to_string();
        fs::write(&origin2_path, serde_json::to_string_pretty(&vec![msg3]).unwrap()).unwrap();

        // Read merged
        let messages = super::inbox_read_merged(team_dir, "agent-1", Some(&registry)).unwrap();
        assert_eq!(messages.len(), 3);
        assert_eq!(messages[0].text, "Local message");
        assert_eq!(messages[1].text, "Remote1 message");
        assert_eq!(messages[2].text, "Remote2 message");
    }

    #[test]
    fn test_inbox_read_merged_deduplication() {
        use crate::config::{HostnameRegistry, RemoteConfig};

        let temp_dir = TempDir::new().unwrap();
        let team_dir = temp_dir.path();
        let inboxes_dir = team_dir.join("inboxes");
        fs::create_dir_all(&inboxes_dir).unwrap();

        // Create hostname registry
        let mut registry = HostnameRegistry::new();
        registry
            .register(RemoteConfig {
                hostname: "remote1".to_string(),
                address: "user@remote1".to_string(),
                ssh_key_path: None,
                aliases: Vec::new(),
            })
            .unwrap();

        // Create local inbox with duplicate message_id
        let local_path = inboxes_dir.join("agent-1.json");
        let msg1 = create_test_message("user-a", "First occurrence", Some("msg-001".to_string()));
        fs::write(&local_path, serde_json::to_string_pretty(&vec![msg1]).unwrap()).unwrap();

        // Create origin inbox with same message_id
        let origin_path = inboxes_dir.join("agent-1.remote1.json");
        let msg2 = create_test_message("user-b", "Duplicate (should be dropped)", Some("msg-001".to_string()));
        fs::write(&origin_path, serde_json::to_string_pretty(&vec![msg2]).unwrap()).unwrap();

        // Read merged - should deduplicate (directory order is not guaranteed)
        let messages = super::inbox_read_merged(team_dir, "agent-1", Some(&registry)).unwrap();
        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0].message_id, Some("msg-001".to_string()));
        // Text could be either "First occurrence" or "Duplicate (should be dropped)"
        // depending on directory read order (first occurrence wins)
        assert!(
            messages[0].text == "First occurrence" || messages[0].text == "Duplicate (should be dropped)",
            "Expected one of the duplicate messages, got: {}",
            messages[0].text
        );
    }

    #[test]
    fn test_inbox_read_merged_no_message_id() {
        use crate::config::{HostnameRegistry, RemoteConfig};

        let temp_dir = TempDir::new().unwrap();
        let team_dir = temp_dir.path();
        let inboxes_dir = team_dir.join("inboxes");
        fs::create_dir_all(&inboxes_dir).unwrap();

        // Create hostname registry
        let mut registry = HostnameRegistry::new();
        registry
            .register(RemoteConfig {
                hostname: "remote1".to_string(),
                address: "user@remote1".to_string(),
                ssh_key_path: None,
                aliases: Vec::new(),
            })
            .unwrap();

        // Create local inbox without message_id
        let local_path = inboxes_dir.join("agent-1.json");
        let msg1 = create_test_message("user-a", "Message without ID", None);
        fs::write(&local_path, serde_json::to_string_pretty(&vec![msg1]).unwrap()).unwrap();

        // Create origin inbox without message_id
        let origin_path = inboxes_dir.join("agent-1.remote1.json");
        let msg2 = create_test_message("user-b", "Another without ID", None);
        fs::write(&origin_path, serde_json::to_string_pretty(&vec![msg2]).unwrap()).unwrap();

        // Read merged - both should be included (no dedup)
        let messages = super::inbox_read_merged(team_dir, "agent-1", Some(&registry)).unwrap();
        assert_eq!(messages.len(), 2);
    }

    #[test]
    fn test_inbox_read_merged_agent_name_with_dots() {
        use crate::config::{HostnameRegistry, RemoteConfig};

        let temp_dir = TempDir::new().unwrap();
        let team_dir = temp_dir.path();
        let inboxes_dir = team_dir.join("inboxes");
        fs::create_dir_all(&inboxes_dir).unwrap();

        // Create hostname registry
        let mut registry = HostnameRegistry::new();
        registry
            .register(RemoteConfig {
                hostname: "mac-studio".to_string(),
                address: "user@mac".to_string(),
                ssh_key_path: None,
                aliases: Vec::new(),
            })
            .unwrap();

        // Agent name with dots
        let agent_name = "dev.agent";

        // Create local inbox
        let local_path = inboxes_dir.join(format!("{agent_name}.json"));
        let msg1 = create_test_message("user-a", "Local", Some("msg-001".to_string()));
        fs::write(&local_path, serde_json::to_string_pretty(&vec![msg1]).unwrap()).unwrap();

        // Create origin inbox
        let origin_path = inboxes_dir.join(format!("{agent_name}.mac-studio.json"));
        let msg2 = create_test_message("user-b", "Remote", Some("msg-002".to_string()));
        fs::write(&origin_path, serde_json::to_string_pretty(&vec![msg2]).unwrap()).unwrap();

        // Read merged - should handle agent name with dots correctly
        let messages = super::inbox_read_merged(team_dir, agent_name, Some(&registry)).unwrap();
        assert_eq!(messages.len(), 2);
        assert_eq!(messages[0].text, "Local");
        assert_eq!(messages[1].text, "Remote");
    }

    #[test]
    fn test_inbox_read_merged_ignores_unknown_hostnames() {
        use crate::config::{HostnameRegistry, RemoteConfig};

        let temp_dir = TempDir::new().unwrap();
        let team_dir = temp_dir.path();
        let inboxes_dir = team_dir.join("inboxes");
        fs::create_dir_all(&inboxes_dir).unwrap();

        // Create hostname registry with only remote1
        let mut registry = HostnameRegistry::new();
        registry
            .register(RemoteConfig {
                hostname: "remote1".to_string(),
                address: "user@remote1".to_string(),
                ssh_key_path: None,
                aliases: Vec::new(),
            })
            .unwrap();

        // Create local inbox
        let local_path = inboxes_dir.join("agent-1.json");
        let msg1 = create_test_message("user-a", "Local", Some("msg-001".to_string()));
        fs::write(&local_path, serde_json::to_string_pretty(&vec![msg1]).unwrap()).unwrap();

        // Create origin inbox from remote1 (known)
        let origin1_path = inboxes_dir.join("agent-1.remote1.json");
        let msg2 = create_test_message("user-b", "Remote1", Some("msg-002".to_string()));
        fs::write(&origin1_path, serde_json::to_string_pretty(&vec![msg2]).unwrap()).unwrap();

        // Create origin inbox from unknown hostname
        let unknown_path = inboxes_dir.join("agent-1.unknown.json");
        let msg3 = create_test_message("user-c", "Unknown (should be ignored)", Some("msg-003".to_string()));
        fs::write(&unknown_path, serde_json::to_string_pretty(&vec![msg3]).unwrap()).unwrap();

        // Read merged - should ignore unknown hostname
        let messages = super::inbox_read_merged(team_dir, "agent-1", Some(&registry)).unwrap();
        assert_eq!(messages.len(), 2);
        assert!(messages.iter().any(|m| m.text == "Local"));
        assert!(messages.iter().any(|m| m.text == "Remote1"));
        assert!(!messages.iter().any(|m| m.text == "Unknown (should be ignored)"));
    }
}