atmd 0.2.2

ATM daemon - session registry and broadcast server for Claude Code monitoring
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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
//! Integration tests for the Registry Actor.
//!
//! These tests verify the registry works correctly as a complete system,
//! testing the spawn_registry() function and RegistryHandle interface.
//!
//! Per CLAUDE.md: Tests CAN use `.unwrap()` and `.expect()` - this is allowed.
//! We test the panic-free behavior of production code through assertions.

use atm_core::{AgentType, HookEventType, Model, SessionDomain, SessionId};
use atmd::registry::{spawn_registry, RegistryError, RemovalReason, SessionEvent, MAX_SESSIONS};
use std::time::Duration;
use tokio::time::{sleep, timeout};

// ============================================================================
// Test Helpers
// ============================================================================

/// Helper to create a test session with default values.
fn create_test_session(id: &str) -> SessionDomain {
    SessionDomain::new(
        SessionId::new(id),
        AgentType::GeneralPurpose,
        Model::Sonnet4,
    )
}

/// Helper to create a test session with a specific agent type.
fn create_test_session_with_type(id: &str, agent_type: AgentType) -> SessionDomain {
    SessionDomain::new(SessionId::new(id), agent_type, Model::Sonnet4)
}

// ============================================================================
// Basic Lifecycle Tests
// ============================================================================

#[tokio::test]
async fn test_basic_lifecycle() {
    // Spawn registry
    let handle = spawn_registry();

    // Register
    let session = create_test_session("test-session-1");
    handle
        .register(session)
        .await
        .expect("registration should succeed");

    // Query
    let result = handle.get_session(SessionId::new("test-session-1")).await;
    assert!(result.is_some(), "session should be found");

    // Verify fields
    let view = result.unwrap();
    assert_eq!(view.id.as_str(), "test-session-1");
    assert_eq!(view.model, "Sonnet 4");
    assert_eq!(view.agent_type, "main"); // AgentType::GeneralPurpose.short_name() = "main"
    assert_eq!(view.status_label, "idle"); // New sessions start as Idle

    // Handle should still be connected
    assert!(handle.is_connected());
}

#[tokio::test]
async fn test_register_and_remove() {
    let handle = spawn_registry();

    // Register
    let session = create_test_session("remove-test");
    handle.register(session).await.expect("should register");

    // Verify exists
    assert!(handle
        .get_session(SessionId::new("remove-test"))
        .await
        .is_some());

    // Remove
    handle
        .remove(SessionId::new("remove-test"))
        .await
        .expect("should remove");

    // Verify gone
    assert!(handle
        .get_session(SessionId::new("remove-test"))
        .await
        .is_none());
}

#[tokio::test]
async fn test_duplicate_registration_fails() {
    let handle = spawn_registry();

    // First registration succeeds
    let session1 = create_test_session("duplicate-test");
    handle
        .register(session1)
        .await
        .expect("first should succeed");

    // Second registration with same ID fails
    let session2 = create_test_session("duplicate-test");
    let result = handle.register(session2).await;

    assert!(
        matches!(result, Err(RegistryError::SessionAlreadyExists(_))),
        "expected SessionAlreadyExists error, got: {result:?}"
    );
}

// ============================================================================
// Multiple Sessions Tests
// ============================================================================

#[tokio::test]
async fn test_multiple_sessions() {
    let handle = spawn_registry();

    // Register 5+ sessions
    for i in 0..7 {
        let session = create_test_session(&format!("multi-session-{i}"));
        handle
            .register(session)
            .await
            .unwrap_or_else(|_| panic!("session {i} should register"));
    }

    // Query all sessions
    let sessions = handle.get_all_sessions().await;

    // Verify all present
    assert_eq!(sessions.len(), 7, "should have 7 sessions");

    // Verify each session is findable
    for i in 0..7 {
        let id = SessionId::new(format!("multi-session-{i}"));
        let found = handle.get_session(id).await;
        assert!(found.is_some(), "session {i} should be found");
    }
}

#[tokio::test]
async fn test_sessions_with_different_types() {
    let handle = spawn_registry();

    // Register sessions with different agent types
    let types = [
        ("type-general", AgentType::GeneralPurpose),
        ("type-explore", AgentType::Explore),
        ("type-plan", AgentType::Plan),
        ("type-search", AgentType::FileSearch),
        ("type-review", AgentType::CodeReviewer),
    ];

    for (id, agent_type) in types.iter() {
        let session = create_test_session_with_type(id, agent_type.clone());
        handle.register(session).await.expect("should register");
    }

    let sessions = handle.get_all_sessions().await;
    assert_eq!(sessions.len(), 5);

    // Verify types are preserved
    let explore = handle
        .get_session(SessionId::new("type-explore"))
        .await
        .unwrap();
    assert_eq!(explore.agent_type, "explore");
}

// ============================================================================
// Event Subscription Tests
// ============================================================================

#[tokio::test]
async fn test_event_subscription_registered() {
    let handle = spawn_registry();
    let mut rx = handle.subscribe();

    // Register
    let session = create_test_session("event-test");
    handle.register(session).await.unwrap();

    // Should receive Registered event
    let event = timeout(Duration::from_secs(1), rx.recv())
        .await
        .expect("should receive event within timeout")
        .expect("event should be Some");

    match event {
        SessionEvent::Registered {
            session_id,
            agent_type,
        } => {
            assert_eq!(session_id.as_str(), "event-test");
            assert_eq!(agent_type, AgentType::GeneralPurpose);
        }
        _ => panic!("expected Registered event, got {event:?}"),
    }
}

#[tokio::test]
async fn test_event_subscription_removed() {
    let handle = spawn_registry();
    let mut rx = handle.subscribe();

    // Register
    let session = create_test_session("event-remove-test");
    handle.register(session).await.unwrap();

    // Drain registered event
    let _ = timeout(Duration::from_millis(100), rx.recv()).await;

    // Remove
    handle
        .remove(SessionId::new("event-remove-test"))
        .await
        .unwrap();

    // Should receive Removed event
    let event = timeout(Duration::from_secs(1), rx.recv())
        .await
        .expect("should receive event within timeout")
        .expect("event should be Some");

    match event {
        SessionEvent::Removed { session_id, reason } => {
            assert_eq!(session_id.as_str(), "event-remove-test");
            assert!(
                matches!(reason, atmd::registry::RemovalReason::Explicit),
                "expected Explicit removal reason"
            );
        }
        _ => panic!("expected Removed event, got {event:?}"),
    }
}

#[tokio::test]
async fn test_event_subscription_hook_event_update() {
    let handle = spawn_registry();
    let mut rx = handle.subscribe();

    // Register
    let session = create_test_session("hook-event-test");
    handle.register(session).await.unwrap();

    // Drain registered event
    let _ = timeout(Duration::from_millis(100), rx.recv()).await;

    // Apply hook event
    handle
        .apply_hook_event(
            SessionId::new("hook-event-test"),
            HookEventType::PreToolUse,
            Some("Bash".to_string()),
            None, // notification_type
            None, // pid
            None, // tmux_pane
            None, // agent_id
            None, // agent_type
            None, // prompt
        )
        .await
        .unwrap();

    // Should receive Updated event
    let event = timeout(Duration::from_secs(1), rx.recv())
        .await
        .expect("should receive event within timeout")
        .expect("event should be Some");

    match event {
        SessionEvent::Updated { session } => {
            assert_eq!(session.id.as_str(), "hook-event-test");
            assert_eq!(session.status_label, "working");
            assert_eq!(session.activity_detail, Some("Bash".to_string()));
        }
        _ => panic!("expected Updated event, got {event:?}"),
    }
}

// ============================================================================
// Capacity Limit Tests
// ============================================================================

#[tokio::test]
async fn test_capacity_limit() {
    let handle = spawn_registry();

    // Register MAX_SESSIONS
    for i in 0..MAX_SESSIONS {
        let session = create_test_session(&format!("capacity-session-{i}"));
        let result = handle.register(session).await;
        assert!(
            result.is_ok(),
            "session {i} should register, got {result:?}"
        );
    }

    // Verify count
    let sessions = handle.get_all_sessions().await;
    assert_eq!(sessions.len(), MAX_SESSIONS);

    // Try one more - should fail
    let overflow_session = create_test_session("session-overflow");
    let result = handle.register(overflow_session).await;

    assert!(
        matches!(
            result,
            Err(RegistryError::RegistryFull { max: MAX_SESSIONS })
        ),
        "expected RegistryFull error with max={MAX_SESSIONS}, got {result:?}"
    );
}

#[tokio::test]
async fn test_capacity_after_removal() {
    let handle = spawn_registry();

    // Fill to capacity
    for i in 0..MAX_SESSIONS {
        let session = create_test_session(&format!("cap-remove-{i}"));
        handle.register(session).await.expect("should register");
    }

    // Verify full
    let overflow = create_test_session("should-fail");
    assert!(matches!(
        handle.register(overflow).await,
        Err(RegistryError::RegistryFull { .. })
    ));

    // Remove one
    handle
        .remove(SessionId::new("cap-remove-0"))
        .await
        .expect("should remove");

    // Now can register again
    let new_session = create_test_session("new-after-remove");
    handle
        .register(new_session)
        .await
        .expect("should register after removal");

    // Still at capacity
    assert_eq!(handle.get_all_sessions().await.len(), MAX_SESSIONS);
}

// ============================================================================
// Stale Session Cleanup Tests
// ============================================================================

#[tokio::test]
async fn test_cleanup_fresh_sessions_not_removed() {
    let handle = spawn_registry();

    // Register fresh session
    let session = create_test_session("fresh-session");
    handle.register(session).await.unwrap();

    // Trigger cleanup
    handle.cleanup_stale().await;

    // Small delay to let actor process
    sleep(Duration::from_millis(50)).await;

    // Fresh session should still exist
    assert!(
        handle
            .get_session(SessionId::new("fresh-session"))
            .await
            .is_some(),
        "fresh session should not be removed"
    );
}

// Note: Testing dead-process cleanup requires sessions with real PIDs
// that have terminated. The unit tests in actor.rs provide coverage
// for the cleanup logic using synthetic PIDs.

// ============================================================================
// Concurrent Access Tests
// ============================================================================

#[tokio::test]
async fn test_concurrent_registration() {
    let handle = spawn_registry();

    // Spawn multiple tasks to register sessions concurrently
    let mut handles = Vec::new();
    for i in 0..10 {
        let h = handle.clone();
        let task = tokio::spawn(async move {
            let session = create_test_session(&format!("concurrent-{i}"));
            h.register(session).await
        });
        handles.push(task);
    }

    // Wait for all to complete
    let mut results = Vec::new();
    for task in handles {
        let result = task.await.expect("task should complete");
        results.push(result);
    }

    // All should succeed
    for (i, result) in results.iter().enumerate() {
        assert!(result.is_ok(), "registration {i} failed: {result:?}");
    }

    // Verify all sessions registered
    let sessions = handle.get_all_sessions().await;
    assert_eq!(sessions.len(), 10);
}

#[tokio::test]
async fn test_concurrent_queries() {
    let handle = spawn_registry();

    // Pre-register some sessions
    for i in 0..5 {
        let session = create_test_session(&format!("query-{i}"));
        handle.register(session).await.unwrap();
    }

    // Spawn multiple concurrent queries
    let mut query_handles = Vec::new();
    for _ in 0..20 {
        let h = handle.clone();
        let task = tokio::spawn(async move { h.get_all_sessions().await });
        query_handles.push(task);
    }

    // All queries should return consistent results
    let mut results = Vec::new();
    for task in query_handles {
        let result = task.await.expect("query should complete");
        results.push(result);
    }

    for result in results {
        assert_eq!(result.len(), 5, "each query should see 5 sessions");
    }
}

#[tokio::test]
async fn test_concurrent_mixed_operations() {
    let handle = spawn_registry();

    // Pre-register some sessions
    for i in 0..3 {
        let session = create_test_session(&format!("mixed-{i}"));
        handle.register(session).await.unwrap();
    }

    // Spawn mix of operations concurrently
    let mut tasks = Vec::new();

    // Query tasks
    for _ in 0..5 {
        let h = handle.clone();
        tasks.push(tokio::spawn(async move {
            let _ = h.get_all_sessions().await;
            Ok::<_, RegistryError>(())
        }));
    }

    // Register new sessions
    for i in 0..3 {
        let h = handle.clone();
        let id = format!("new-mixed-{i}");
        tasks.push(tokio::spawn(async move {
            let session = create_test_session(&id);
            h.register(session).await
        }));
    }

    // Get specific session tasks
    for i in 0..3 {
        let h = handle.clone();
        let id = SessionId::new(format!("mixed-{i}"));
        tasks.push(tokio::spawn(async move {
            let _ = h.get_session(id).await;
            Ok::<_, RegistryError>(())
        }));
    }

    // Wait for all
    let mut results = Vec::new();
    for task in tasks {
        let result = task.await.expect("task should complete");
        results.push(result);
    }

    // All should succeed
    for result in results {
        assert!(result.is_ok(), "operation failed: {result:?}");
    }

    // Final state should have 6 sessions (3 original + 3 new)
    let sessions = handle.get_all_sessions().await;
    assert_eq!(sessions.len(), 6);
}

// ============================================================================
// Hook Event Tests
// ============================================================================

#[tokio::test]
async fn test_hook_event_pre_tool_use() {
    let handle = spawn_registry();

    // Register
    let session = create_test_session("hook-pre");
    handle.register(session).await.unwrap();

    // Apply PreToolUse
    handle
        .apply_hook_event(
            SessionId::new("hook-pre"),
            HookEventType::PreToolUse,
            Some("Write".to_string()),
            None, // notification_type
            None, // pid
            None, // tmux_pane
            None, // agent_id
            None, // agent_type
            None, // prompt
        )
        .await
        .expect("should apply hook event");

    // Verify status changed to working
    let view = handle
        .get_session(SessionId::new("hook-pre"))
        .await
        .unwrap();
    assert_eq!(view.status_label, "working");
    assert_eq!(view.activity_detail, Some("Write".to_string()));
}

#[tokio::test]
async fn test_hook_event_post_tool_use() {
    let handle = spawn_registry();

    // Register
    let session = create_test_session("hook-post");
    handle.register(session).await.unwrap();

    // Apply PreToolUse first
    handle
        .apply_hook_event(
            SessionId::new("hook-post"),
            HookEventType::PreToolUse,
            Some("Bash".to_string()),
            None, // notification_type
            None, // pid
            None, // tmux_pane
            None, // agent_id
            None, // agent_type
            None, // prompt
        )
        .await
        .unwrap();

    // Then PostToolUse
    handle
        .apply_hook_event(
            SessionId::new("hook-post"),
            HookEventType::PostToolUse,
            Some("Bash".to_string()),
            None, // notification_type
            None, // pid
            None, // tmux_pane
            None, // agent_id
            None, // agent_type
            None, // prompt
        )
        .await
        .expect("should apply hook event");

    // Verify status changed to working (thinking is now Working in 3-state model)
    let view = handle
        .get_session(SessionId::new("hook-post"))
        .await
        .unwrap();
    assert_eq!(view.status_label, "working");
}

#[tokio::test]
async fn test_hook_event_nonexistent_session() {
    let handle = spawn_registry();

    // Apply hook event to non-existent session
    // This should succeed silently - hook events race with status line updates,
    // so we gracefully ignore hooks for sessions that don't exist yet.
    let result = handle
        .apply_hook_event(
            SessionId::new("nonexistent"),
            HookEventType::PreToolUse,
            Some("Bash".to_string()),
            None, // notification_type
            None, // pid
            None, // tmux_pane
            None, // agent_id
            None, // agent_type
            None, // prompt
        )
        .await;

    assert!(
        result.is_ok(),
        "hook events for non-existent sessions should be silently ignored"
    );
}

#[tokio::test]
async fn test_hook_event_session_end() {
    let handle = spawn_registry();
    let mut rx = handle.subscribe();

    // Register a session
    let session = create_test_session("session-end-test");
    handle.register(session).await.unwrap();

    // Drain registered event
    let _ = timeout(Duration::from_millis(100), rx.recv()).await;

    // Apply SessionEnd hook
    handle
        .apply_hook_event(
            SessionId::new("session-end-test"),
            HookEventType::SessionEnd,
            None, // tool_name
            None, // notification_type
            None, // pid
            None, // tmux_pane
            None, // agent_id
            None, // agent_type
            None, // prompt
        )
        .await
        .expect("should apply SessionEnd event");

    // Session should be removed
    assert!(
        handle
            .get_session(SessionId::new("session-end-test"))
            .await
            .is_none(),
        "session should be removed after SessionEnd"
    );

    // Should receive Removed event with SessionEnded reason
    let event = timeout(Duration::from_secs(1), rx.recv())
        .await
        .expect("should receive event within timeout")
        .expect("event should be Some");

    match event {
        SessionEvent::Removed { session_id, reason } => {
            assert_eq!(session_id.as_str(), "session-end-test");
            assert!(
                matches!(reason, RemovalReason::SessionEnded),
                "expected SessionEnded removal reason, got: {reason:?}"
            );
        }
        _ => panic!("expected Removed event, got {event:?}"),
    }
}

#[tokio::test]
async fn test_hook_event_session_end_nonexistent() {
    let handle = spawn_registry();

    // Apply SessionEnd to non-existent session (race condition scenario)
    let result = handle
        .apply_hook_event(
            SessionId::new("nonexistent-for-end"),
            HookEventType::SessionEnd,
            None, // tool_name
            None, // notification_type
            None, // pid
            None, // tmux_pane
            None, // agent_id
            None, // agent_type
            None, // prompt
        )
        .await;

    // Should succeed silently (not error)
    assert!(
        result.is_ok(),
        "SessionEnd for non-existent session should succeed silently"
    );
}

// ============================================================================
// Error Handling Tests
// ============================================================================

#[tokio::test]
async fn test_remove_nonexistent_session() {
    let handle = spawn_registry();

    let result = handle.remove(SessionId::new("does-not-exist")).await;

    assert!(
        matches!(result, Err(RegistryError::SessionNotFound(_))),
        "expected SessionNotFound error, got {result:?}"
    );
}

#[tokio::test]
async fn test_get_nonexistent_session_returns_none() {
    let handle = spawn_registry();

    let result = handle.get_session(SessionId::new("nonexistent")).await;

    assert!(
        result.is_none(),
        "should return None for nonexistent session"
    );
}

// ============================================================================
// Handle Clone Tests
// ============================================================================

#[tokio::test]
async fn test_handle_cloning() {
    let handle1 = spawn_registry();
    let handle2 = handle1.clone();

    // Register via handle1
    let session = create_test_session("clone-test");
    handle1.register(session).await.unwrap();

    // Query via handle2
    let result = handle2.get_session(SessionId::new("clone-test")).await;
    assert!(
        result.is_some(),
        "cloned handle should see registered session"
    );

    // Both handles should be connected
    assert!(handle1.is_connected());
    assert!(handle2.is_connected());
}

#[tokio::test]
async fn test_multiple_subscribers() {
    let handle = spawn_registry();

    // Create multiple subscribers
    let mut rx1 = handle.subscribe();
    let mut rx2 = handle.subscribe();
    let mut rx3 = handle.subscribe();

    // Register a session
    let session = create_test_session("multi-sub-test");
    handle.register(session).await.unwrap();

    // All subscribers should receive the event
    let event1 = timeout(Duration::from_secs(1), rx1.recv())
        .await
        .expect("rx1 should receive")
        .expect("event1 should be Some");
    let event2 = timeout(Duration::from_secs(1), rx2.recv())
        .await
        .expect("rx2 should receive")
        .expect("event2 should be Some");
    let event3 = timeout(Duration::from_secs(1), rx3.recv())
        .await
        .expect("rx3 should receive")
        .expect("event3 should be Some");

    // All should be Registered events
    assert!(matches!(event1, SessionEvent::Registered { .. }));
    assert!(matches!(event2, SessionEvent::Registered { .. }));
    assert!(matches!(event3, SessionEvent::Registered { .. }));
}

// ============================================================================
// Session View Field Tests
// ============================================================================

#[tokio::test]
async fn test_session_view_fields() {
    let handle = spawn_registry();

    let session = SessionDomain::new(
        SessionId::new("8e11bfb5-7dc2-432b-9206-928fa5c35731"),
        AgentType::Explore,
        Model::Opus45,
    );
    handle.register(session).await.unwrap();

    let view = handle
        .get_session(SessionId::new("8e11bfb5-7dc2-432b-9206-928fa5c35731"))
        .await
        .unwrap();

    // Verify view fields are correctly populated
    assert_eq!(view.id_short, "8e11bfb5");
    assert_eq!(view.agent_type, "explore");
    assert_eq!(view.model, "Opus 4.5");
    assert_eq!(view.status_label, "idle"); // New sessions start as Idle
    assert!(!view.needs_attention);
}

// ============================================================================
// Cleanup Fire-and-Forget Test
// ============================================================================

#[tokio::test]
async fn test_cleanup_dead_processes_is_fire_and_forget() {
    let handle = spawn_registry();

    // cleanup_stale should complete quickly without waiting for result
    let start = std::time::Instant::now();
    handle.cleanup_stale().await;
    let elapsed = start.elapsed();

    // Should be nearly instant (fire-and-forget)
    assert!(
        elapsed < Duration::from_millis(100),
        "cleanup_stale took too long: {elapsed:?}"
    );
}

// ============================================================================
// Status Line Update Tests (via auto-registration)
// ============================================================================

#[tokio::test]
async fn test_update_from_status_line_auto_registers() {
    let handle = spawn_registry();

    // Use the current process PID (a real PID that set_pid can validate)
    let current_pid = std::process::id();

    // Update for non-existent session should auto-register
    // Note: PID is required for auto-registration with PID-as-primary-key design
    let status_json = serde_json::json!({
        "session_id": "auto-register-test",
        "pid": current_pid,
        "model": {"id": "claude-sonnet-4-20250514"},
        "cost": {"total_cost_usd": 0.15, "total_duration_ms": 10000},
        "context_window": {"total_input_tokens": 2500, "context_window_size": 200000}
    });

    let result = handle
        .update_from_status_line(SessionId::new("auto-register-test"), status_json)
        .await;

    assert!(result.is_ok(), "auto-registration should succeed");

    // Session should now exist
    let view = handle
        .get_session(SessionId::new("auto-register-test"))
        .await;
    assert!(view.is_some(), "auto-registered session should be findable");
}

#[tokio::test]
async fn test_update_from_status_line_updates_existing() {
    let handle = spawn_registry();

    // First register normally
    let session = create_test_session("update-test");
    handle.register(session).await.unwrap();

    // Then update via status line
    let status_json = serde_json::json!({
        "session_id": "update-test",
        "model": {"id": "claude-sonnet-4-20250514"},
        "cost": {"total_cost_usd": 0.50, "total_duration_ms": 30000},
        "context_window": {"total_input_tokens": 10000, "context_window_size": 200000}
    });

    let result = handle
        .update_from_status_line(SessionId::new("update-test"), status_json)
        .await;

    assert!(result.is_ok(), "update should succeed");

    // Verify cost was updated
    let view = handle
        .get_session(SessionId::new("update-test"))
        .await
        .unwrap();
    assert!(
        view.cost_usd > 0.4,
        "cost should be updated to ~0.50, got {}",
        view.cost_usd
    );
}

// ============================================================================
// Phase 1: Subagent & Project Field Tests
// ============================================================================

#[tokio::test]
async fn test_hook_event_forwards_agent_fields() {
    let handle = spawn_registry();
    let mut rx = handle.subscribe();

    // Register a parent session
    let session = create_test_session("parent-for-subagent");
    handle.register(session).await.unwrap();

    // Drain registered event
    let _ = timeout(Duration::from_millis(100), rx.recv()).await;

    // Send SubagentStart hook with agent_id and agent_type
    handle
        .apply_hook_event(
            SessionId::new("parent-for-subagent"),
            HookEventType::SubagentStart,
            None,
            None,
            None,
            None,
            Some("subagent-001".to_string()),
            Some("explore".to_string()),
            None, // prompt
        )
        .await
        .expect("SubagentStart hook should succeed");

    // The parent session should still be accessible and working
    let view = handle
        .get_session(SessionId::new("parent-for-subagent"))
        .await
        .expect("parent session should exist");
    // SubagentStart is a pre-event, so session stays working
    assert_eq!(view.status_label, "working");
}

#[tokio::test]
async fn test_project_resolution_on_discovery() {
    // This test verifies that project resolution functions work correctly
    // when given a real git repo path. The functions are in atm-core and
    // will be wired into the actor in a later phase.
    use atm_core::{resolve_project_root, resolve_worktree_info};
    use std::fs;

    let handle = spawn_registry();

    // Create a temp dir with a .git directory to simulate a git repo
    let dir = tempfile::tempdir().unwrap();
    let repo_path = dir.path().join("myproject");
    fs::create_dir_all(repo_path.join(".git")).unwrap();
    fs::create_dir_all(repo_path.join("src")).unwrap();
    fs::write(repo_path.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap();

    let working_dir = repo_path.join("src");
    let cwd_str = working_dir.to_str().unwrap();

    // Verify project resolution works
    let project_root = resolve_project_root(cwd_str);
    assert_eq!(
        project_root,
        Some(repo_path.to_string_lossy().to_string()),
        "should resolve project root from subdirectory"
    );

    // Verify worktree info resolution
    let (wt_path, branch) = resolve_worktree_info(repo_path.to_str().unwrap());
    assert_eq!(wt_path, Some(repo_path.to_str().unwrap().to_string()));
    assert_eq!(branch, Some("main".to_string()));

    // Register a discovered session with this working directory
    let current_pid = std::process::id();
    handle
        .register_discovered(
            SessionId::new("project-test-session"),
            current_pid,
            working_dir.clone(),
            None,
        )
        .await
        .expect("discovery registration should succeed");

    // Verify session was registered with working_directory populated
    let view = handle
        .get_session(SessionId::new("project-test-session"))
        .await
        .expect("session should exist");

    // working_directory should be set from the discovery path
    assert!(
        view.working_directory.is_some(),
        "working_directory should be populated from discovery"
    );
}

// ============================================================================
// CWD Change Detection Tests
// ============================================================================

#[tokio::test]
async fn test_status_line_cwd_change_updates_git_info() {
    let handle = spawn_registry();

    // Create two temp repos to simulate a worktree switch
    let dir = tempfile::tempdir().unwrap();
    let repo_a = dir.path().join("repo-a");
    let repo_b = dir.path().join("repo-b");
    std::fs::create_dir_all(repo_a.join(".git")).unwrap();
    std::fs::create_dir_all(repo_b.join(".git")).unwrap();
    std::fs::write(repo_a.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap();
    std::fs::write(repo_b.join(".git/HEAD"), "ref: refs/heads/feature-x\n").unwrap();

    let current_pid = std::process::id();

    // Register via discovery in repo_a
    handle
        .register_discovered(
            SessionId::new("cwd-change-test"),
            current_pid,
            repo_a.clone(),
            None,
        )
        .await
        .expect("should register");

    let view = handle
        .get_session(SessionId::new("cwd-change-test"))
        .await
        .unwrap();
    assert_eq!(view.worktree_branch.as_deref(), Some("main"));
    assert_eq!(view.project_root.as_deref(), Some(repo_a.to_str().unwrap()));

    // Now send a status line update with cwd pointing to repo_b
    let status_json = serde_json::json!({
        "session_id": "cwd-change-test",
        "pid": current_pid,
        "cwd": repo_b.to_str().unwrap(),
        "model": {"id": "claude-sonnet-4-20250514"},
        "cost": {"total_cost_usd": 0.25, "total_duration_ms": 5000},
        "context_window": {"total_input_tokens": 1000, "context_window_size": 200000}
    });

    handle
        .update_from_status_line(SessionId::new("cwd-change-test"), status_json)
        .await
        .expect("status update should succeed");

    // Verify git info was re-resolved to repo_b
    let view = handle
        .get_session(SessionId::new("cwd-change-test"))
        .await
        .unwrap();
    assert_eq!(
        view.worktree_branch.as_deref(),
        Some("feature-x"),
        "branch should update to repo_b's branch"
    );
    assert_eq!(
        view.project_root.as_deref(),
        Some(repo_b.to_str().unwrap()),
        "project_root should update to repo_b"
    );
    // Cost should also be updated (not wiped)
    assert!(
        view.cost_usd > 0.2,
        "cost should be updated from status line, got {}",
        view.cost_usd
    );
}

#[tokio::test]
async fn test_status_line_same_cwd_does_not_re_resolve() {
    let handle = spawn_registry();
    let mut rx = handle.subscribe();

    let dir = tempfile::tempdir().unwrap();
    let repo = dir.path().join("same-cwd-repo");
    std::fs::create_dir_all(repo.join(".git")).unwrap();
    std::fs::write(repo.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap();

    let current_pid = std::process::id();

    // Register via discovery
    handle
        .register_discovered(
            SessionId::new("same-cwd-test"),
            current_pid,
            repo.clone(),
            None,
        )
        .await
        .unwrap();

    // Drain events
    while timeout(Duration::from_millis(50), rx.recv()).await.is_ok() {}

    // Send status line with SAME cwd
    let status_json = serde_json::json!({
        "session_id": "same-cwd-test",
        "pid": current_pid,
        "cwd": repo.to_str().unwrap(),
        "model": {"id": "claude-sonnet-4-20250514"},
        "cost": {"total_cost_usd": 0.10, "total_duration_ms": 1000},
        "context_window": {"total_input_tokens": 500, "context_window_size": 200000}
    });

    handle
        .update_from_status_line(SessionId::new("same-cwd-test"), status_json)
        .await
        .unwrap();

    // Session should still have correct info
    let view = handle
        .get_session(SessionId::new("same-cwd-test"))
        .await
        .unwrap();
    assert_eq!(view.worktree_branch.as_deref(), Some("main"));
}

// ============================================================================
// Metadata Preservation on Rescan Tests
// ============================================================================

#[tokio::test]
async fn test_rescan_preserves_metadata_for_existing_pid() {
    let handle = spawn_registry();

    let dir = tempfile::tempdir().unwrap();
    let repo = dir.path().join("preserve-repo");
    std::fs::create_dir_all(repo.join(".git")).unwrap();
    std::fs::write(repo.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap();

    let current_pid = std::process::id();

    // Register via discovery with pending-{pid} id
    handle
        .register_discovered(
            SessionId::new("pending-discover"),
            current_pid,
            repo.clone(),
            None,
        )
        .await
        .unwrap();

    // Upgrade via status line (gives it a real session id and cost data)
    let status_json = serde_json::json!({
        "session_id": "real-session-id",
        "pid": current_pid,
        "cwd": repo.to_str().unwrap(),
        "model": {"id": "claude-sonnet-4-20250514"},
        "cost": {"total_cost_usd": 1.50, "total_duration_ms": 60000},
        "context_window": {
            "total_input_tokens": 50000,
            "total_output_tokens": 10000,
            "context_window_size": 200000
        }
    });

    handle
        .update_from_status_line(SessionId::new("real-session-id"), status_json)
        .await
        .unwrap();

    // Verify cost was accumulated
    let view = handle
        .get_session(SessionId::new("real-session-id"))
        .await
        .expect("session should exist with real id");
    assert!(
        view.cost_usd > 1.0,
        "cost should be ~1.50, got {}",
        view.cost_usd
    );

    // Now simulate a rescan (re-discovery with a new pending id)
    handle
        .register_discovered(
            SessionId::new("pending-rescan"),
            current_pid,
            repo.clone(),
            None,
        )
        .await
        .unwrap();

    // Session should still be accessible and metadata preserved
    // Note: session_id will have been updated to the new pending id
    let view = handle
        .get_session(SessionId::new("pending-rescan"))
        .await
        .expect("session should exist under new id");
    assert!(
        view.cost_usd > 1.0,
        "cost should be preserved after rescan (~1.50), got {}",
        view.cost_usd
    );
}

#[tokio::test]
async fn test_rescan_refreshes_git_info() {
    let handle = spawn_registry();

    let dir = tempfile::tempdir().unwrap();
    let repo = dir.path().join("rescan-git-repo");
    std::fs::create_dir_all(repo.join(".git")).unwrap();
    std::fs::write(repo.join(".git/HEAD"), "ref: refs/heads/old-branch\n").unwrap();

    let current_pid = std::process::id();

    // Initial discovery
    handle
        .register_discovered(
            SessionId::new("rescan-git-test"),
            current_pid,
            repo.clone(),
            None,
        )
        .await
        .unwrap();

    let view = handle
        .get_session(SessionId::new("rescan-git-test"))
        .await
        .unwrap();
    assert_eq!(view.worktree_branch.as_deref(), Some("old-branch"));

    // Simulate branch change on disk
    std::fs::write(repo.join(".git/HEAD"), "ref: refs/heads/new-branch\n").unwrap();

    // Re-discover (rescan) — should pick up new branch
    handle
        .register_discovered(
            SessionId::new("rescan-git-test-2"),
            current_pid,
            repo.clone(),
            None,
        )
        .await
        .unwrap();

    let view = handle
        .get_session(SessionId::new("rescan-git-test-2"))
        .await
        .unwrap();
    assert_eq!(
        view.worktree_branch.as_deref(),
        Some("new-branch"),
        "rescan should pick up updated branch"
    );
}