crosslink 0.8.0

A synced issue tracker CLI for multi-agent AI development
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
//! Filesystem watcher for real-time WebSocket events.
//!
//! Uses the `notify` crate to watch the hub cache's `heartbeats/` directory.
//! On file changes, reads the latest heartbeat state, diffs it against the
//! previous snapshot, and broadcasts `heartbeat` and `agent_status` events
//! through the WebSocket broadcast channel.
//!
//! A 30-second polling fallback ensures clients stay up-to-date even when
//! filesystem events are missed (e.g. network mounts, WSL quirks).

use std::collections::HashMap;
use std::path::PathBuf;

use anyhow::Result;
use chrono::{Duration, Utc};
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
use tokio::sync::broadcast;
use tokio::time;

use crate::locks::Heartbeat;
use crate::server::types::{AgentStatus, WsAgentStatusEvent, WsHeartbeatEvent};
use crate::server::ws::WsEvent;
use crate::sync::SyncManager;

/// Polling interval when filesystem events are missed or unavailable.
const POLL_INTERVAL_SECS: u64 = 30;

/// Derive an `AgentStatus` from how stale a heartbeat timestamp is.
///
/// | Age            | Status  |
/// |----------------|---------|
/// | < 5 min        | Active  |
/// | 5 – 30 min     | Idle    |
/// | > 30 min       | Stale   |
#[must_use]
pub fn status_from_heartbeat(heartbeat: &Heartbeat) -> AgentStatus {
    let age = Utc::now() - heartbeat.last_heartbeat;
    if age < Duration::minutes(5) {
        AgentStatus::Active
    } else if age < Duration::minutes(30) {
        AgentStatus::Idle
    } else {
        AgentStatus::Stale
    }
}

/// Spawn a background task that watches the hub cache for heartbeat changes
/// and broadcasts events to all WebSocket clients.
///
/// Returns immediately; the watcher runs until the `tx` sender is dropped.
pub fn start_watcher(crosslink_dir: PathBuf, tx: broadcast::Sender<WsEvent>) {
    tokio::spawn(async move {
        if let Err(e) = run_watcher(crosslink_dir, tx).await {
            tracing::error!("watcher: error: {e}");
        }
    });
}

/// Core watcher loop — watches the heartbeats directory and polls as a fallback.
async fn run_watcher(crosslink_dir: PathBuf, tx: broadcast::Sender<WsEvent>) -> Result<()> {
    let sync = SyncManager::new(&crosslink_dir)?;

    // Hub cache is always at <main-repo-root>/.crosslink/.hub-cache/.
    // We watch the heartbeats/ subdirectory for file-level changes.
    let watch_path = crosslink_dir.join(".hub-cache").join("heartbeats");

    // Bridge notify (sync) → tokio (async) with an mpsc channel.
    // We only need a "something changed" signal; the actual event details are
    // unused — we always re-read the full heartbeat state on any change.
    let (notify_tx, mut notify_rx) = tokio::sync::mpsc::channel::<()>(16);

    // Build the notify watcher.  The closure is called from the notify thread.
    let mut watcher: RecommendedWatcher = {
        let notify_tx = notify_tx.clone();
        notify::recommended_watcher(move |_res: notify::Result<notify::Event>| {
            // INTENTIONAL: non-blocking send; if the channel is full we drop the signal
            // — the next poll will pick up the changes anyway
            let _ = notify_tx.blocking_send(());
        })?
    };

    // Attempt to start watching.  If the directory doesn't exist yet (hub not
    // initialised), fall back to polling only.
    let watch_active = if watch_path.exists() {
        match watcher.watch(&watch_path, RecursiveMode::NonRecursive) {
            Ok(()) => true,
            Err(e) => {
                tracing::warn!(
                    "watcher: could not watch {}: {e}, falling back to polling",
                    watch_path.display()
                );
                false
            }
        }
    } else {
        tracing::info!(
            "watcher: heartbeats directory not found at {}, polling only",
            watch_path.display()
        );
        false
    };

    if watch_active {
        tracing::info!(
            "watcher: watching {} for heartbeat changes",
            watch_path.display()
        );
    }

    // Initial snapshot so we can diff on the first real event.
    let mut last_state: HashMap<String, Heartbeat> = HashMap::new();
    let mut last_statuses: HashMap<String, AgentStatus> = HashMap::new();

    if let Ok(heartbeats) = sync.read_heartbeats_auto() {
        for hb in heartbeats {
            last_statuses.insert(hb.agent_id.clone(), status_from_heartbeat(&hb));
            last_state.insert(hb.agent_id.clone(), hb);
        }
    }

    // Polling timer — first tick fires immediately so we emit any initial state.
    let mut poll_interval = time::interval(time::Duration::from_secs(POLL_INTERVAL_SECS));
    poll_interval.tick().await; // consume the immediate first tick

    loop {
        tokio::select! {
            // Filesystem change notification.
            result = notify_rx.recv() => {
                match result {
                    Some(()) => {
                        diff_and_broadcast(&sync, &mut last_state, &mut last_statuses, &tx);
                    }
                    // Channel closed — all senders dropped, stop the loop.
                    None => break,
                }
            }

            // Fallback poll every 30 seconds.
            _ = poll_interval.tick() => {
                diff_and_broadcast(&sync, &mut last_state, &mut last_statuses, &tx);
            }
        }

        // Stop if all receivers have disconnected (server shutting down).
        if tx.receiver_count() == 0 {
            break;
        }
    }

    Ok(())
}

/// Read current heartbeats, diff against `last_state`, and broadcast events.
///
/// Broadcasts a `WsHeartbeatEvent` for every heartbeat that is new or has a
/// newer timestamp.  When the derived `AgentStatus` also changes, broadcasts a
/// `WsAgentStatusEvent` as well.
fn diff_and_broadcast(
    sync: &SyncManager,
    last_state: &mut HashMap<String, Heartbeat>,
    last_statuses: &mut HashMap<String, AgentStatus>,
    tx: &broadcast::Sender<WsEvent>,
) {
    let heartbeats = match sync.read_heartbeats_auto() {
        Ok(h) => h,
        Err(e) => {
            tracing::warn!("watcher: failed to read heartbeats: {e}");
            return;
        }
    };

    let mut current_state: HashMap<String, Heartbeat> = HashMap::new();
    for hb in heartbeats {
        current_state.insert(hb.agent_id.clone(), hb);
    }

    for (agent_id, hb) in &current_state {
        let is_new_or_updated = last_state
            .get(agent_id)
            .is_none_or(|prev| prev.last_heartbeat != hb.last_heartbeat);

        if is_new_or_updated {
            // INTENTIONAL: broadcast failure is harmless when no WebSocket subscribers are connected
            let _ = tx.send(WsEvent::Heartbeat(WsHeartbeatEvent {
                event_type: crate::server::types::WsEventType::Heartbeat,
                agent_id: agent_id.clone(),
                timestamp: hb.last_heartbeat,
                active_issue_id: hb.active_issue_id,
            }));

            // Broadcast agent_status only when the derived status changes.
            let new_status = status_from_heartbeat(hb);
            let status_changed = last_statuses.get(agent_id) != Some(&new_status);

            if status_changed {
                // INTENTIONAL: broadcast failure is harmless when no WebSocket subscribers are connected
                let _ = tx.send(WsEvent::AgentStatus(WsAgentStatusEvent {
                    event_type: crate::server::types::WsEventType::AgentStatus,
                    agent_id: agent_id.clone(),
                    status: new_status.clone(),
                }));
                last_statuses.insert(agent_id.clone(), new_status);
            }
        }
    }

    *last_state = current_state;
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Utc;
    use std::process::Command;
    use tempfile::tempdir;

    fn make_heartbeat(agent_id: &str, age_minutes: i64) -> Heartbeat {
        Heartbeat {
            agent_id: agent_id.to_string(),
            last_heartbeat: Utc::now() - Duration::minutes(age_minutes),
            active_issue_id: None,
            machine_id: "test-machine".to_string(),
        }
    }

    /// Set up a real git repo with a bare remote, init the hub cache, and
    /// return a ready-to-use `SyncManager` along with the temp dirs so they
    /// aren't dropped prematurely.
    fn setup_watcher_env() -> (tempfile::TempDir, tempfile::TempDir, SyncManager) {
        let remote_dir = tempdir().unwrap();
        let work_dir = tempdir().unwrap();

        // Init bare remote
        Command::new("git")
            .current_dir(remote_dir.path())
            .args(["init", "--bare", "-b", "main"])
            .output()
            .unwrap();

        // Init work repo
        Command::new("git")
            .current_dir(work_dir.path())
            .args(["init", "-b", "main"])
            .output()
            .unwrap();

        for args in [
            vec!["config", "user.email", "test@test.local"],
            vec!["config", "user.name", "Test"],
            vec![
                "remote",
                "add",
                "origin",
                remote_dir.path().to_str().unwrap(),
            ],
        ] {
            Command::new("git")
                .current_dir(work_dir.path())
                .args(&args)
                .output()
                .unwrap();
        }

        // Initial commit + push
        std::fs::write(work_dir.path().join("README.md"), "# test\n").unwrap();
        Command::new("git")
            .current_dir(work_dir.path())
            .args(["add", "."])
            .output()
            .unwrap();
        Command::new("git")
            .current_dir(work_dir.path())
            .args(["commit", "-m", "init", "--no-gpg-sign"])
            .output()
            .unwrap();
        Command::new("git")
            .current_dir(work_dir.path())
            .args(["push", "-u", "origin", "main"])
            .output()
            .unwrap();

        let crosslink_dir = work_dir.path().join(".crosslink");
        std::fs::create_dir_all(&crosslink_dir).unwrap();
        std::fs::write(
            crosslink_dir.join("hook-config.json"),
            r#"{"remote":"origin"}"#,
        )
        .unwrap();

        let sync = SyncManager::new(&crosslink_dir).unwrap();
        sync.init_cache().unwrap();

        (work_dir, remote_dir, sync)
    }

    /// Write a heartbeat JSON file directly into the hub cache's heartbeats dir.
    fn write_heartbeat_file(sync: &SyncManager, hb: &Heartbeat) {
        let hb_dir = sync.cache_path().join("heartbeats");
        std::fs::create_dir_all(&hb_dir).unwrap();
        let json = serde_json::to_string_pretty(hb).unwrap();
        std::fs::write(hb_dir.join(format!("{}.json", hb.agent_id)), json).unwrap();
    }

    #[test]
    fn test_diff_and_broadcast_new_agent() {
        let (_work, _remote, sync) = setup_watcher_env();
        let (tx, mut rx) = broadcast::channel::<WsEvent>(16);
        let mut last_state: HashMap<String, Heartbeat> = HashMap::new();
        let mut last_statuses: HashMap<String, AgentStatus> = HashMap::new();

        // Write a fresh (active) heartbeat
        let hb = Heartbeat {
            agent_id: "worker-1".to_string(),
            last_heartbeat: Utc::now(),
            active_issue_id: Some(42),
            machine_id: "test-host".to_string(),
        };
        write_heartbeat_file(&sync, &hb);

        diff_and_broadcast(&sync, &mut last_state, &mut last_statuses, &tx);

        // Expect Heartbeat + AgentStatus events
        let ev1 = rx.try_recv().expect("Heartbeat event");
        let ev2 = rx.try_recv().expect("AgentStatus event");
        assert!(rx.try_recv().is_err(), "no extra events");

        assert!(matches!(ev1, WsEvent::Heartbeat(_)));
        assert!(matches!(ev2, WsEvent::AgentStatus(_)));

        if let WsEvent::Heartbeat(e) = ev1 {
            assert_eq!(e.agent_id, "worker-1");
            assert_eq!(e.active_issue_id, Some(42));
        }
        if let WsEvent::AgentStatus(e) = ev2 {
            assert_eq!(e.agent_id, "worker-1");
            assert_eq!(e.status, AgentStatus::Active);
        }

        assert_eq!(last_state.len(), 1);
        assert_eq!(last_statuses.len(), 1);
    }

    #[test]
    fn test_diff_and_broadcast_unchanged() {
        let (_work, _remote, sync) = setup_watcher_env();
        let (tx, mut rx) = broadcast::channel::<WsEvent>(16);
        let mut last_state: HashMap<String, Heartbeat> = HashMap::new();
        let mut last_statuses: HashMap<String, AgentStatus> = HashMap::new();

        let hb = Heartbeat {
            agent_id: "worker-2".to_string(),
            last_heartbeat: Utc::now() - Duration::minutes(2),
            active_issue_id: None,
            machine_id: "test-host".to_string(),
        };
        write_heartbeat_file(&sync, &hb);

        // First call: should emit events
        diff_and_broadcast(&sync, &mut last_state, &mut last_statuses, &tx);
        // Drain
        while rx.try_recv().is_ok() {}

        // Second call with same file: should emit nothing
        diff_and_broadcast(&sync, &mut last_state, &mut last_statuses, &tx);
        assert!(rx.try_recv().is_err(), "no events for unchanged heartbeat");
    }

    #[test]
    fn test_diff_and_broadcast_updated_timestamp() {
        let (_work, _remote, sync) = setup_watcher_env();
        let (tx, mut rx) = broadcast::channel::<WsEvent>(16);
        let mut last_state: HashMap<String, Heartbeat> = HashMap::new();
        let mut last_statuses: HashMap<String, AgentStatus> = HashMap::new();

        let hb1 = Heartbeat {
            agent_id: "worker-3".to_string(),
            last_heartbeat: Utc::now() - Duration::minutes(2),
            active_issue_id: None,
            machine_id: "test-host".to_string(),
        };
        write_heartbeat_file(&sync, &hb1);
        diff_and_broadcast(&sync, &mut last_state, &mut last_statuses, &tx);
        while rx.try_recv().is_ok() {}

        // Update timestamp (still Active, so status shouldn't change)
        let hb2 = Heartbeat {
            last_heartbeat: Utc::now() - Duration::minutes(1),
            ..hb1
        };
        write_heartbeat_file(&sync, &hb2);
        diff_and_broadcast(&sync, &mut last_state, &mut last_statuses, &tx);

        // Should emit Heartbeat but NOT AgentStatus (status unchanged: Active→Active)
        let ev = rx.try_recv().expect("Heartbeat event");
        assert!(matches!(ev, WsEvent::Heartbeat(_)));
        // No AgentStatus event since status is still Active
        assert!(
            rx.try_recv().is_err(),
            "no AgentStatus when status unchanged"
        );
    }

    #[test]
    fn test_diff_and_broadcast_status_change() {
        let (_work, _remote, sync) = setup_watcher_env();
        let (tx, mut rx) = broadcast::channel::<WsEvent>(16);
        let mut last_state: HashMap<String, Heartbeat> = HashMap::new();
        let mut last_statuses: HashMap<String, AgentStatus> = HashMap::new();

        // Start as Idle (10 minutes old)
        let hb1 = Heartbeat {
            agent_id: "worker-4".to_string(),
            last_heartbeat: Utc::now() - Duration::minutes(10),
            active_issue_id: None,
            machine_id: "test-host".to_string(),
        };
        write_heartbeat_file(&sync, &hb1);
        diff_and_broadcast(&sync, &mut last_state, &mut last_statuses, &tx);
        while rx.try_recv().is_ok() {}

        // Now change to Stale (35 minutes old) — different timestamp AND different status
        let hb2 = Heartbeat {
            last_heartbeat: Utc::now() - Duration::minutes(35),
            ..hb1
        };
        write_heartbeat_file(&sync, &hb2);
        diff_and_broadcast(&sync, &mut last_state, &mut last_statuses, &tx);

        let ev1 = rx.try_recv().expect("Heartbeat event");
        let ev2 = rx.try_recv().expect("AgentStatus event");
        assert!(rx.try_recv().is_err(), "no extra events");

        assert!(matches!(ev1, WsEvent::Heartbeat(_)));
        assert!(matches!(ev2, WsEvent::AgentStatus(_)));
        if let WsEvent::AgentStatus(e) = ev2 {
            assert_eq!(e.status, AgentStatus::Stale);
        }
    }

    #[test]
    fn test_diff_and_broadcast_read_error_returns_gracefully() {
        // Create a SyncManager pointing to a non-existent crosslink dir.
        // read_heartbeats_auto will return an error / empty list gracefully.
        let dir = tempdir().unwrap();
        let crosslink_dir = dir.path().join(".crosslink");
        std::fs::create_dir_all(&crosslink_dir).unwrap();

        // SyncManager::new succeeds; cache dir doesn't exist so read_heartbeats_auto
        // returns Ok(vec![]) (empty) rather than an error, since the heartbeats dir
        // simply doesn't exist yet.
        let sync = SyncManager::new(&crosslink_dir).unwrap();

        let (tx, mut rx) = broadcast::channel::<WsEvent>(16);
        let mut last_state: HashMap<String, Heartbeat> = HashMap::new();
        let mut last_statuses: HashMap<String, AgentStatus> = HashMap::new();

        // Should not panic; no heartbeats → no events
        diff_and_broadcast(&sync, &mut last_state, &mut last_statuses, &tx);
        assert!(rx.try_recv().is_err(), "no events when no heartbeats");
    }

    #[test]
    fn test_status_active() {
        let hb = make_heartbeat("a1", 2);
        assert_eq!(status_from_heartbeat(&hb), AgentStatus::Active);
    }

    #[test]
    fn test_status_idle() {
        let hb = make_heartbeat("a1", 10);
        assert_eq!(status_from_heartbeat(&hb), AgentStatus::Idle);
    }

    #[test]
    fn test_status_stale() {
        let hb = make_heartbeat("a1", 45);
        assert_eq!(status_from_heartbeat(&hb), AgentStatus::Stale);
    }

    #[test]
    fn test_status_boundary_five_min() {
        // Exactly 5 minutes old — should be Idle, not Active.
        let hb = make_heartbeat("a1", 5);
        assert_eq!(status_from_heartbeat(&hb), AgentStatus::Idle);
    }

    #[test]
    fn test_status_boundary_thirty_min() {
        // Exactly 30 minutes old — should be Stale, not Idle.
        let hb = make_heartbeat("a1", 30);
        assert_eq!(status_from_heartbeat(&hb), AgentStatus::Stale);
    }

    #[test]
    fn test_diff_broadcasts_new_heartbeat() {
        let (tx, mut rx) = broadcast::channel::<WsEvent>(16);
        let mut last_state: HashMap<String, Heartbeat> = HashMap::new();
        let mut last_statuses: HashMap<String, AgentStatus> = HashMap::new();

        let hb = make_heartbeat("worker-1", 1);
        let mut current: HashMap<String, Heartbeat> = HashMap::new();
        current.insert("worker-1".to_string(), hb);

        // Simulate diff logic directly.
        for (agent_id, hb) in &current {
            let is_new = !last_state.contains_key(agent_id);
            if is_new {
                let _ = tx.send(WsEvent::Heartbeat(WsHeartbeatEvent {
                    event_type: crate::server::types::WsEventType::Heartbeat,
                    agent_id: agent_id.clone(),
                    timestamp: hb.last_heartbeat,
                    active_issue_id: hb.active_issue_id,
                }));
                let new_status = status_from_heartbeat(hb);
                let _ = tx.send(WsEvent::AgentStatus(WsAgentStatusEvent {
                    event_type: crate::server::types::WsEventType::AgentStatus,
                    agent_id: agent_id.clone(),
                    status: new_status.clone(),
                }));
                last_statuses.insert(agent_id.clone(), new_status);
            }
        }
        last_state = current;

        // Should have received 2 events: Heartbeat + AgentStatus.
        let ev1 = rx.try_recv().unwrap();
        let ev2 = rx.try_recv().unwrap();
        assert!(rx.try_recv().is_err(), "no extra events");

        assert!(matches!(ev1, WsEvent::Heartbeat(_)));
        assert!(matches!(ev2, WsEvent::AgentStatus(_)));
        assert_eq!(last_state.len(), 1);
        assert_eq!(last_statuses.len(), 1);
    }

    #[test]
    fn test_diff_no_broadcast_on_unchanged() {
        let (tx, mut rx) = broadcast::channel::<WsEvent>(16);
        let mut last_state: HashMap<String, Heartbeat> = HashMap::new();

        let hb = make_heartbeat("worker-1", 1);
        last_state.insert("worker-1".to_string(), hb.clone());

        let mut current: HashMap<String, Heartbeat> = HashMap::new();
        current.insert("worker-1".to_string(), hb); // same timestamp

        // Simulate diff logic for unchanged heartbeat.
        for (agent_id, hb) in &current {
            let is_new_or_updated = last_state
                .get(agent_id)
                .is_none_or(|prev| prev.last_heartbeat != hb.last_heartbeat);
            if is_new_or_updated {
                let _ = tx.send(WsEvent::Heartbeat(WsHeartbeatEvent {
                    event_type: crate::server::types::WsEventType::Heartbeat,
                    agent_id: agent_id.clone(),
                    timestamp: hb.last_heartbeat,
                    active_issue_id: hb.active_issue_id,
                }));
            }
        }

        // Should have received 0 events since the timestamp did not change.
        assert!(rx.try_recv().is_err(), "no events for unchanged heartbeat");
    }
}