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
//! Client interface for interacting with the RegistryActor.
//!
//! The `RegistryHandle` provides a cheap-to-clone interface for sending commands
//! to the registry actor and subscribing to session events.
//!
//! # Panic-Free Guarantees
//!
//! This module follows CLAUDE.md panic-free policy:
//! - No `.unwrap()`, `.expect()`, `panic!()`, `unreachable!()`, `todo!()`
//! - All fallible operations use `?`, pattern matching, or `unwrap_or`
//! - Channel errors are mapped to `RegistryError::ChannelClosed`

use tokio::sync::{broadcast, mpsc, oneshot};

use atm_core::{HookEventType, SessionDomain, SessionId, SessionView};

use super::commands::{RegistryCommand, RegistryError, SessionEvent};

// ============================================================================
// Registry Handle
// ============================================================================

/// Handle for interacting with the registry actor.
///
/// This is a cheap-to-clone handle that can be shared across tasks.
/// All methods are async and communicate with the actor via channels.
///
/// # Usage
///
/// ```ignore
/// // Clone the handle to share across tasks
/// let handle = registry_handle.clone();
///
/// // Register a session
/// handle.register(session).await?;
///
/// // Get all sessions
/// let sessions = handle.get_all_sessions().await;
///
/// // Subscribe to events
/// let mut rx = handle.subscribe();
/// while let Ok(event) = rx.recv().await {
///     // Handle event
/// }
/// ```
#[derive(Clone)]
pub struct RegistryHandle {
    /// Command sender to the actor
    sender: mpsc::Sender<RegistryCommand>,

    /// Event broadcaster for subscribing to updates
    event_sender: broadcast::Sender<SessionEvent>,
}

impl RegistryHandle {
    /// Create a new registry handle.
    ///
    /// # Arguments
    ///
    /// * `sender` - The command channel sender for communicating with the actor
    /// * `event_sender` - The broadcast sender for subscribing to events
    pub fn new(
        sender: mpsc::Sender<RegistryCommand>,
        event_sender: broadcast::Sender<SessionEvent>,
    ) -> Self {
        Self {
            sender,
            event_sender,
        }
    }

    /// Register a new session in the registry.
    ///
    /// # Errors
    ///
    /// - `RegistryError::SessionAlreadyExists` if a session with this ID exists
    /// - `RegistryError::RegistryFull` if the registry is at maximum capacity
    /// - `RegistryError::ChannelClosed` if the actor has shut down
    pub async fn register(&self, session: SessionDomain) -> Result<(), RegistryError> {
        let (tx, rx) = oneshot::channel();

        self.sender
            .send(RegistryCommand::Register {
                session: Box::new(session),
                respond_to: tx,
            })
            .await
            .map_err(|_| RegistryError::ChannelClosed)?;

        rx.await.map_err(|_| RegistryError::ChannelClosed)?
    }

    /// Update a session from Claude Code status line data.
    ///
    /// Parses the raw JSON and applies updates to the session's
    /// cost, duration, context usage, and lines changed.
    ///
    /// # Errors
    ///
    /// - `RegistryError::SessionNotFound` if the session doesn't exist
    /// - `RegistryError::ParseError` if the JSON is malformed
    /// - `RegistryError::ChannelClosed` if the actor has shut down
    pub async fn update_from_status_line(
        &self,
        session_id: SessionId,
        data: serde_json::Value,
    ) -> Result<(), RegistryError> {
        let (tx, rx) = oneshot::channel();

        self.sender
            .send(RegistryCommand::UpdateFromStatusLine {
                session_id,
                data,
                respond_to: tx,
            })
            .await
            .map_err(|_| RegistryError::ChannelClosed)?;

        rx.await.map_err(|_| RegistryError::ChannelClosed)?
    }

    /// Apply a hook event to a session.
    ///
    /// Updates the session's status based on the event type
    /// (e.g., PreToolUse sets RunningTool, PostToolUse sets Thinking).
    ///
    /// # Arguments
    ///
    /// * `session_id` - The session to update
    /// * `event_type` - Type of hook event
    /// * `tool_name` - Name of the tool (for tool-related events)
    /// * `pid` - Process ID of Claude Code (for lifecycle tracking)
    /// * `tmux_pane` - Tmux pane ID if running in tmux
    ///
    /// # Errors
    ///
    /// - `RegistryError::SessionNotFound` if the session doesn't exist
    /// - `RegistryError::ChannelClosed` if the actor has shut down
    pub async fn apply_hook_event(
        &self,
        session_id: SessionId,
        event_type: HookEventType,
        tool_name: Option<String>,
        notification_type: Option<String>,
        pid: Option<u32>,
        tmux_pane: Option<String>,
        agent_id: Option<String>,
        agent_type: Option<String>,
        prompt: Option<String>,
    ) -> Result<(), RegistryError> {
        let (tx, rx) = oneshot::channel();

        self.sender
            .send(RegistryCommand::ApplyHookEvent {
                session_id,
                event_type,
                tool_name,
                notification_type,
                pid,
                tmux_pane,
                agent_id,
                agent_type,
                prompt,
                respond_to: tx,
            })
            .await
            .map_err(|_| RegistryError::ChannelClosed)?;

        rx.await.map_err(|_| RegistryError::ChannelClosed)?
    }

    /// Get a single session by ID.
    ///
    /// Returns `None` if the session doesn't exist or if communication
    /// with the actor fails.
    pub async fn get_session(&self, session_id: SessionId) -> Option<SessionView> {
        let (tx, rx) = oneshot::channel();

        self.sender
            .send(RegistryCommand::GetSession {
                session_id,
                respond_to: tx,
            })
            .await
            .ok()?;

        rx.await.ok()?
    }

    /// Get all sessions as views.
    ///
    /// Returns an empty vector if no sessions are registered or if
    /// communication with the actor fails.
    pub async fn get_all_sessions(&self) -> Vec<SessionView> {
        let (tx, rx) = oneshot::channel();

        if self
            .sender
            .send(RegistryCommand::GetAllSessions { respond_to: tx })
            .await
            .is_err()
        {
            return Vec::new();
        }

        rx.await.unwrap_or_default()
    }

    /// Remove a session from the registry.
    ///
    /// # Errors
    ///
    /// - `RegistryError::SessionNotFound` if the session doesn't exist
    /// - `RegistryError::ChannelClosed` if the actor has shut down
    pub async fn remove(&self, session_id: SessionId) -> Result<(), RegistryError> {
        let (tx, rx) = oneshot::channel();

        self.sender
            .send(RegistryCommand::Remove {
                session_id,
                respond_to: tx,
            })
            .await
            .map_err(|_| RegistryError::ChannelClosed)?;

        rx.await.map_err(|_| RegistryError::ChannelClosed)?
    }

    /// Trigger cleanup of stale sessions.
    ///
    /// This is a fire-and-forget operation - it does not wait for
    /// the cleanup to complete or return any result.
    pub async fn cleanup_stale(&self) {
        // Fire-and-forget: ignore send errors (actor may be shutting down)
        let _ = self.sender.send(RegistryCommand::CleanupStale).await;
    }

    /// Register a discovered session (minimal data from /proc scan).
    ///
    /// Creates a minimal session with defaults that will be filled in
    /// when status line updates arrive. If the session already exists,
    /// this is a no-op (returns Ok).
    ///
    /// # Errors
    ///
    /// - `RegistryError::RegistryFull` if the registry is at maximum capacity
    /// - `RegistryError::ChannelClosed` if the actor has shut down
    pub async fn register_discovered(
        &self,
        session_id: SessionId,
        pid: u32,
        cwd: std::path::PathBuf,
        tmux_pane: Option<String>,
    ) -> Result<(), RegistryError> {
        let (tx, rx) = oneshot::channel();

        self.sender
            .send(RegistryCommand::RegisterDiscovered {
                session_id,
                pid,
                cwd,
                tmux_pane,
                respond_to: tx,
            })
            .await
            .map_err(|_| RegistryError::ChannelClosed)?;

        rx.await.map_err(|_| RegistryError::ChannelClosed)?
    }

    /// Subscribe to session events.
    ///
    /// Returns a broadcast receiver that will receive all session events
    /// (registrations, updates, removals) published by the registry actor.
    ///
    /// This is a synchronous operation - it doesn't communicate with the actor.
    pub fn subscribe(&self) -> broadcast::Receiver<SessionEvent> {
        self.event_sender.subscribe()
    }

    /// Check if the actor is still running.
    ///
    /// Returns `true` if the command channel is still open.
    pub fn is_connected(&self) -> bool {
        !self.sender.is_closed()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use atm_core::{AgentType, Model};

    fn create_test_handle() -> (RegistryHandle, mpsc::Receiver<RegistryCommand>) {
        let (cmd_tx, cmd_rx) = mpsc::channel(16);
        let (event_tx, _event_rx) = broadcast::channel(16);
        let handle = RegistryHandle::new(cmd_tx, event_tx);
        (handle, cmd_rx)
    }

    fn create_test_session(id: &str) -> SessionDomain {
        SessionDomain::new(
            SessionId::new(id),
            AgentType::GeneralPurpose,
            Model::Sonnet4,
        )
    }

    #[tokio::test]
    async fn test_handle_is_clone() {
        let (handle, _rx) = create_test_handle();
        let _cloned = handle.clone();
        // Compiles = test passes
    }

    #[tokio::test]
    async fn test_register_sends_command() {
        let (handle, mut rx) = create_test_handle();

        let session = create_test_session("test-123");

        // Spawn task to handle the command
        let cmd_handler = tokio::spawn(async move {
            if let Some(RegistryCommand::Register {
                session,
                respond_to,
            }) = rx.recv().await
            {
                assert_eq!(session.id.as_str(), "test-123");
                let _ = respond_to.send(Ok(()));
                return true;
            }
            false
        });

        let result = handle.register(session).await;
        assert!(result.is_ok());
        assert!(cmd_handler.await.unwrap());
    }

    #[tokio::test]
    async fn test_register_channel_closed_error() {
        let (handle, rx) = create_test_handle();
        drop(rx); // Close the channel

        let session = create_test_session("test-123");
        let result = handle.register(session).await;

        assert!(matches!(result, Err(RegistryError::ChannelClosed)));
    }

    #[tokio::test]
    async fn test_get_session_returns_none_on_channel_close() {
        let (handle, rx) = create_test_handle();
        drop(rx);

        let result = handle.get_session(SessionId::new("test-123")).await;
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_get_all_sessions_returns_empty_on_channel_close() {
        let (handle, rx) = create_test_handle();
        drop(rx);

        let result = handle.get_all_sessions().await;
        assert!(result.is_empty());
    }

    #[tokio::test]
    async fn test_cleanup_stale_fire_and_forget() {
        let (handle, mut rx) = create_test_handle();

        // Spawn task to receive the command
        let cmd_handler = tokio::spawn(async move {
            if let Some(RegistryCommand::CleanupStale) = rx.recv().await {
                return true;
            }
            false
        });

        handle.cleanup_stale().await;
        assert!(cmd_handler.await.unwrap());
    }

    #[tokio::test]
    async fn test_cleanup_stale_ignores_closed_channel() {
        let (handle, rx) = create_test_handle();
        drop(rx);

        // Should not panic or error
        handle.cleanup_stale().await;
    }

    #[tokio::test]
    async fn test_subscribe_returns_receiver() {
        let (handle, _rx) = create_test_handle();

        let _subscriber = handle.subscribe();
        // Compiles and returns = test passes
    }

    #[tokio::test]
    async fn test_is_connected() {
        let (handle, rx) = create_test_handle();

        assert!(handle.is_connected());

        drop(rx);
        // Need to send to detect closure
        let _ = handle.sender.send(RegistryCommand::CleanupStale).await;

        // After dropping receiver and attempting send, channel should be closed
        assert!(!handle.is_connected());
    }

    #[tokio::test]
    async fn test_update_from_status_line() {
        let (handle, mut rx) = create_test_handle();

        let cmd_handler = tokio::spawn(async move {
            if let Some(RegistryCommand::UpdateFromStatusLine {
                session_id,
                data,
                respond_to,
            }) = rx.recv().await
            {
                assert_eq!(session_id.as_str(), "test-123");
                assert!(data.get("model").is_some());
                let _ = respond_to.send(Ok(()));
                return true;
            }
            false
        });

        let data = serde_json::json!({
            "model": {"id": "claude-sonnet-4-20250514"},
            "cost": {"total_cost_usd": 0.25}
        });

        let result = handle
            .update_from_status_line(SessionId::new("test-123"), data)
            .await;
        assert!(result.is_ok());
        assert!(cmd_handler.await.unwrap());
    }

    #[tokio::test]
    async fn test_apply_hook_event() {
        let (handle, mut rx) = create_test_handle();

        let cmd_handler = tokio::spawn(async move {
            if let Some(RegistryCommand::ApplyHookEvent {
                session_id,
                event_type,
                tool_name,
                notification_type,
                pid,
                tmux_pane,
                agent_id: _,
                agent_type: _,
                prompt: _,
                respond_to,
            }) = rx.recv().await
            {
                assert_eq!(session_id.as_str(), "test-123");
                assert!(matches!(event_type, HookEventType::PreToolUse));
                assert_eq!(tool_name, Some("Bash".to_string()));
                assert_eq!(notification_type, None);
                assert_eq!(pid, Some(12345));
                assert_eq!(tmux_pane, Some("%5".to_string()));
                let _ = respond_to.send(Ok(()));
                return true;
            }
            false
        });

        let result = handle
            .apply_hook_event(
                SessionId::new("test-123"),
                HookEventType::PreToolUse,
                Some("Bash".to_string()),
                None, // notification_type
                Some(12345),
                Some("%5".to_string()),
                None, // agent_id
                None, // agent_type
                None, // prompt
            )
            .await;
        assert!(result.is_ok());
        assert!(cmd_handler.await.unwrap());
    }

    #[tokio::test]
    async fn test_remove() {
        let (handle, mut rx) = create_test_handle();

        let cmd_handler = tokio::spawn(async move {
            if let Some(RegistryCommand::Remove {
                session_id,
                respond_to,
            }) = rx.recv().await
            {
                assert_eq!(session_id.as_str(), "test-123");
                let _ = respond_to.send(Ok(()));
                return true;
            }
            false
        });

        let result = handle.remove(SessionId::new("test-123")).await;
        assert!(result.is_ok());
        assert!(cmd_handler.await.unwrap());
    }
}