ralph 0.1.5

A CLI agent harness for running AI coding agents (Codex, Claude, Pi, Gemini)
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
use anyhow::{anyhow, Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs::{self, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

/// Global process registry
static REGISTRY: LazyLock<Mutex<ProcessRegistry>> =
    LazyLock::new(|| Mutex::new(ProcessRegistry::load().unwrap_or_default()));

fn now_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

fn process_is_alive(pid: u32) -> bool {
    #[cfg(target_os = "linux")]
    {
        if std::path::Path::new(&format!("/proc/{}", pid)).exists() {
            return true;
        }
        unix_pid_exists(pid)
    }

    #[cfg(all(unix, not(target_os = "linux")))]
    {
        unix_pid_exists(pid)
    }

    #[cfg(windows)]
    {
        windows_pid_exists(pid)
    }
}

fn send_terminate(pid: u32) -> bool {
    #[cfg(unix)]
    {
        unix_send_signal(pid, "-TERM")
    }

    #[cfg(windows)]
    {
        windows_taskkill(pid, false)
    }
}

fn send_kill(pid: u32) -> bool {
    #[cfg(unix)]
    {
        unix_send_signal(pid, "-KILL")
    }

    #[cfg(windows)]
    {
        windows_taskkill(pid, true)
    }
}

#[cfg(unix)]
fn unix_send_signal(pid: u32, signal: &str) -> bool {
    std::process::Command::new("kill")
        .args([signal, &pid.to_string()])
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

#[cfg(windows)]
fn windows_taskkill(pid: u32, force: bool) -> bool {
    let mut args = vec!["/PID".to_string(), pid.to_string(), "/T".to_string()];
    if force {
        args.push("/F".to_string());
    }
    std::process::Command::new("taskkill")
        .args(args)
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

#[cfg(unix)]
fn unix_pid_exists(pid: u32) -> bool {
    std::process::Command::new("kill")
        .args(["-0", &pid.to_string()])
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

#[cfg(windows)]
fn windows_pid_exists(pid: u32) -> bool {
    let output = std::process::Command::new("tasklist")
        .args(["/FO", "CSV", "/NH", "/FI", &format!("PID eq {}", pid)])
        .output();
    let Ok(output) = output else {
        return false;
    };
    if !output.status.success() {
        return false;
    }
    let stdout = String::from_utf8_lossy(&output.stdout);
    stdout
        .lines()
        .any(|line| line.contains(&format!("\"{}\"", pid)))
}

#[cfg(target_os = "linux")]
fn process_cwd(pid: u32) -> Option<String> {
    fs::read_link(format!("/proc/{}/cwd", pid))
        .map(|p| p.display().to_string())
        .ok()
}

#[cfg(not(target_os = "linux"))]
fn process_cwd(_pid: u32) -> Option<String> {
    None
}

#[cfg(target_os = "linux")]
fn process_started_at(pid: u32) -> Option<u64> {
    fs::metadata(format!("/proc/{}", pid))
        .and_then(|m| m.created())
        .ok()
        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
        .map(|d| d.as_secs())
}

#[cfg(not(target_os = "linux"))]
fn process_started_at(_pid: u32) -> Option<u64> {
    None
}

#[cfg(unix)]
fn find_pids_by_name(name: &str) -> Vec<u32> {
    let output = std::process::Command::new("pgrep")
        .args(["-f", name])
        .output();
    let Ok(output) = output else {
        return Vec::new();
    };
    if !output.status.success() {
        return Vec::new();
    }
    String::from_utf8_lossy(&output.stdout)
        .lines()
        .filter_map(|s| s.trim().parse().ok())
        .collect()
}

#[cfg(windows)]
fn find_pids_by_name(name: &str) -> Vec<u32> {
    let output = std::process::Command::new("tasklist")
        .args(["/FO", "CSV", "/NH"])
        .output();
    let Ok(output) = output else {
        return Vec::new();
    };
    if !output.status.success() {
        return Vec::new();
    }
    let needle = name.to_lowercase();
    String::from_utf8_lossy(&output.stdout)
        .lines()
        .filter_map(|line| {
            let line = line.trim();
            if line.is_empty() || line.starts_with("INFO:") {
                return None;
            }
            let line = line.trim_matches('"');
            let mut parts = line.split("\",\"");
            let image = parts.next()?.to_lowercase();
            let pid_str = parts.next()?;
            if image.contains(&needle) {
                pid_str.parse::<u32>().ok()
            } else {
                None
            }
        })
        .collect()
}

/// Information about a tracked process
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessInfo {
    pub pid: u32,
    pub harness: String,
    pub model: String,
    pub working_dir: String,
    pub started_at: u64,
    pub parent_pid: u32,
    pub tmux_session: Option<String>,
}

impl ProcessInfo {
    /// Check if this process is still running
    pub fn is_alive(&self) -> bool {
        process_is_alive(self.pid)
    }

    /// Get age in seconds
    pub fn age_secs(&self) -> u64 {
        now_secs().saturating_sub(self.started_at)
    }

    /// Format age as human readable
    pub fn age_human(&self) -> String {
        let secs = self.age_secs();
        if secs < 60 {
            format!("{}s", secs)
        } else if secs < 3600 {
            format!("{}m", secs / 60)
        } else if secs < 86400 {
            format!("{}h", secs / 3600)
        } else {
            format!("{}d", secs / 86400)
        }
    }
}

/// Registry of tracked processes
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct ProcessRegistry {
    processes: HashMap<u32, ProcessInfo>,
}

impl ProcessRegistry {
    /// Get path to the pidfile
    fn pidfile_path() -> PathBuf {
        let runtime_dir = std::env::var("XDG_RUNTIME_DIR")
            .map(PathBuf::from)
            .unwrap_or_else(|_| std::env::temp_dir());
        runtime_dir.join("ralph-processes.json")
    }

    /// Load registry from disk
    pub fn load() -> Result<Self> {
        let path = Self::pidfile_path();
        if !path.exists() {
            return Ok(Self::default());
        }
        let content = fs::read_to_string(&path)
            .with_context(|| format!("Failed to read pidfile: {:?}", path))?;
        let registry: Self =
            serde_json::from_str(&content).with_context(|| "Failed to parse pidfile")?;
        Ok(registry)
    }

    /// Save registry to disk
    pub fn save(&self) -> Result<()> {
        let path = Self::pidfile_path();
        let _lock = acquire_lock(&path)?;
        let content = serde_json::to_string_pretty(self)?;
        write_atomic(&path, &content)
            .with_context(|| format!("Failed to write pidfile: {:?}", path))?;
        Ok(())
    }

    /// Register a new process
    pub fn register(&mut self, info: ProcessInfo) {
        self.processes.insert(info.pid, info);
    }

    /// Unregister a process
    pub fn unregister(&mut self, pid: u32) {
        self.processes.remove(&pid);
    }

    /// Get all tracked processes
    pub fn all(&self) -> Vec<&ProcessInfo> {
        self.processes.values().collect()
    }

    /// Get alive processes only
    pub fn alive(&self) -> Vec<&ProcessInfo> {
        self.processes.values().filter(|p| p.is_alive()).collect()
    }

    /// Get dead (orphaned) processes
    #[allow(dead_code)]
    pub fn dead(&self) -> Vec<&ProcessInfo> {
        self.processes.values().filter(|p| !p.is_alive()).collect()
    }

    /// Clean up dead processes from registry
    pub fn cleanup_dead(&mut self) -> usize {
        let dead_pids: Vec<u32> = self
            .processes
            .iter()
            .filter(|(_, p)| !p.is_alive())
            .map(|(pid, _)| *pid)
            .collect();
        let count = dead_pids.len();
        for pid in dead_pids {
            self.processes.remove(&pid);
        }
        count
    }

    /// Get processes for a specific working directory
    pub fn by_working_dir(&self, dir: &str) -> Vec<&ProcessInfo> {
        self.processes
            .values()
            .filter(|p| p.working_dir == dir)
            .collect()
    }

    /// Get processes for a specific harness
    pub fn by_harness(&self, harness: &str) -> Vec<&ProcessInfo> {
        self.processes
            .values()
            .filter(|p| p.harness == harness)
            .collect()
    }
}

struct LockGuard {
    path: PathBuf,
}

impl Drop for LockGuard {
    fn drop(&mut self) {
        let _ = fs::remove_file(&self.path);
    }
}

fn acquire_lock(path: &Path) -> Result<LockGuard> {
    let lock_path = path.with_extension("lock");
    let pid = std::process::id();
    let start = Instant::now();
    let timeout = Duration::from_secs(2);

    loop {
        match OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&lock_path)
        {
            Ok(mut file) => {
                let _ = writeln!(file, "{}", pid);
                return Ok(LockGuard { path: lock_path });
            }
            Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {
                if let Ok(contents) = fs::read_to_string(&lock_path) {
                    match contents.trim().parse::<u32>() {
                        Ok(lock_pid) => {
                            if !process_is_alive(lock_pid) {
                                let _ = fs::remove_file(&lock_path);
                                continue;
                            }
                        }
                        Err(_) => {
                            let _ = fs::remove_file(&lock_path);
                            continue;
                        }
                    }
                }
                if start.elapsed() >= timeout {
                    return Err(anyhow!(
                        "Timed out waiting for process registry lock: {}",
                        lock_path.display()
                    ));
                }
                std::thread::sleep(Duration::from_millis(50));
            }
            Err(err) => return Err(err.into()),
        }
    }
}

fn write_atomic(path: &Path, content: &str) -> Result<()> {
    let tmp_path = path.with_extension(format!("json.tmp.{}", std::process::id()));
    fs::write(&tmp_path, content)?;
    if let Err(err) = fs::rename(&tmp_path, path) {
        if path.exists() {
            let _ = fs::remove_file(path);
            fs::rename(&tmp_path, path)?;
        } else {
            let _ = fs::remove_file(&tmp_path);
            return Err(err.into());
        }
    }
    Ok(())
}

// Public API using global registry

/// Register a spawned process
pub fn register_process(
    pid: u32,
    harness: &str,
    model: &str,
    tmux_session: Option<String>,
) -> Result<()> {
    let working_dir = std::env::current_dir()
        .map(|p| p.display().to_string())
        .unwrap_or_else(|_| "unknown".to_string());

    let info = ProcessInfo {
        pid,
        harness: harness.to_string(),
        model: model.to_string(),
        working_dir,
        started_at: now_secs(),
        parent_pid: std::process::id(),
        tmux_session,
    };

    let mut registry = REGISTRY.lock().unwrap();
    registry.register(info);
    registry.save()?;
    Ok(())
}

/// Unregister a process when it exits
pub fn unregister_process(pid: u32) -> Result<()> {
    let mut registry = REGISTRY.lock().unwrap();
    registry.unregister(pid);
    registry.save()?;
    Ok(())
}

/// List all tracked processes
pub fn list_processes() -> Vec<ProcessInfo> {
    let registry = REGISTRY.lock().unwrap();
    registry.all().into_iter().cloned().collect()
}

/// List alive processes
pub fn list_alive_processes() -> Vec<ProcessInfo> {
    let registry = REGISTRY.lock().unwrap();
    registry.alive().into_iter().cloned().collect()
}

/// Clean dead entries from registry
pub fn cleanup_registry() -> Result<usize> {
    let mut registry = REGISTRY.lock().unwrap();
    let count = registry.cleanup_dead();
    registry.save()?;
    Ok(count)
}

/// Kill a specific process by PID
pub fn kill_process(pid: u32) -> Result<bool> {
    let info = {
        let registry = REGISTRY.lock().unwrap();
        registry.processes.get(&pid).cloned()
    };

    if let Some(info) = info {
        // If it has a tmux session, kill that too
        if let Some(session) = &info.tmux_session {
            let _ = std::process::Command::new("tmux")
                .args(["kill-session", "-t", session])
                .status();
        }
    }

    let alive_before = process_is_alive(pid);
    let terminated = if alive_before {
        send_terminate(pid)
    } else {
        true
    };

    if terminated {
        // Give it a moment to die
        std::thread::sleep(std::time::Duration::from_millis(100));

        // Check if still alive, send hard kill
        if process_is_alive(pid) {
            let _ = send_kill(pid);
        }

        // Unregister from our tracking
        let mut registry = REGISTRY.lock().unwrap();
        registry.unregister(pid);
        let _ = registry.save();
        Ok(true)
    } else {
        Ok(false)
    }
}

/// Kill all tracked processes
pub fn kill_all_processes() -> Result<(usize, usize)> {
    let processes = list_alive_processes();
    let total = processes.len();
    let mut killed = 0;

    for proc in processes {
        if kill_process(proc.pid).unwrap_or(false) {
            killed += 1;
        }
    }

    Ok((killed, total))
}

/// Kill processes matching a filter
pub fn kill_processes_by_dir(dir: &str) -> Result<(usize, usize)> {
    let processes = {
        let registry = REGISTRY.lock().unwrap();
        registry
            .by_working_dir(dir)
            .into_iter()
            .filter(|p| p.is_alive())
            .cloned()
            .collect::<Vec<_>>()
    };

    let total = processes.len();
    let mut killed = 0;

    for proc in processes {
        if kill_process(proc.pid).unwrap_or(false) {
            killed += 1;
        }
    }

    Ok((killed, total))
}

/// Kill processes by harness type
pub fn kill_processes_by_harness(harness: &str) -> Result<(usize, usize)> {
    let processes = {
        let registry = REGISTRY.lock().unwrap();
        registry
            .by_harness(harness)
            .into_iter()
            .filter(|p| p.is_alive())
            .cloned()
            .collect::<Vec<_>>()
    };

    let total = processes.len();
    let mut killed = 0;

    for proc in processes {
        if kill_process(proc.pid).unwrap_or(false) {
            killed += 1;
        }
    }

    Ok((killed, total))
}

/// Find and register orphaned agent processes not in our registry
/// This helps recover from crashes where we lost track
pub fn discover_orphan_processes() -> Result<Vec<ProcessInfo>> {
    let mut orphans = Vec::new();

    // Look for common agent processes
    for harness in &["codex", "claude", "pi", "gemini"] {
        let pids = find_pids_by_name(harness);
        let registry = REGISTRY.lock().unwrap();
        for pid in pids {
            if !registry.processes.contains_key(&pid) {
                let cwd = process_cwd(pid).unwrap_or_else(|| "unknown".to_string());
                let started_at = process_started_at(pid).unwrap_or_else(now_secs);
                orphans.push(ProcessInfo {
                    pid,
                    harness: harness.to_string(),
                    model: "unknown".to_string(),
                    working_dir: cwd,
                    started_at,
                    parent_pid: 0,
                    tmux_session: None,
                });
            }
        }
    }

    Ok(orphans)
}

/// Print process list in a nice format
pub fn print_processes(processes: &[ProcessInfo], show_dead: bool) {
    if processes.is_empty() {
        println!("No tracked processes.");
        return;
    }

    println!(
        "{:<8} {:<10} {:<8} {:<6} {:<40} TMUX",
        "PID", "HARNESS", "STATUS", "AGE", "WORKING_DIR"
    );
    println!("{}", "-".repeat(100));

    for proc in processes {
        let status = if proc.is_alive() { "alive" } else { "dead" };
        if !show_dead && !proc.is_alive() {
            continue;
        }
        let tmux = proc.tmux_session.as_deref().unwrap_or("-");
        let dir = if proc.working_dir.len() > 40 {
            format!("...{}", &proc.working_dir[proc.working_dir.len() - 37..])
        } else {
            proc.working_dir.clone()
        };
        println!(
            "{:<8} {:<10} {:<8} {:<6} {:<40} {}",
            proc.pid,
            proc.harness,
            status,
            proc.age_human(),
            dir,
            tmux
        );
    }
}

/// Print JSON output
pub fn print_processes_json(processes: &[ProcessInfo]) -> Result<()> {
    println!("{}", serde_json::to_string_pretty(processes)?);
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_process_info_age() {
        let info = ProcessInfo {
            pid: 12345,
            harness: "codex".to_string(),
            model: "test".to_string(),
            working_dir: "/tmp".to_string(),
            started_at: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs()
                - 120,
            parent_pid: 1,
            tmux_session: None,
        };

        let age = info.age_secs();
        assert!((119..=121).contains(&age));
        assert_eq!(info.age_human(), "2m");
    }

    #[test]
    fn test_registry_operations() {
        let mut registry = ProcessRegistry::default();

        let info = ProcessInfo {
            pid: 99999,
            harness: "test".to_string(),
            model: "test-model".to_string(),
            working_dir: "/tmp/test".to_string(),
            started_at: 0,
            parent_pid: 1,
            tmux_session: None,
        };

        registry.register(info.clone());
        assert_eq!(registry.all().len(), 1);

        registry.unregister(99999);
        assert_eq!(registry.all().len(), 0);
    }
}