yoyo-agent 0.1.8

A coding agent that evolves itself. Born as 200 lines of Rust, growing up in public.
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
//! Background process management for `/bg` commands.
//! REPL dispatch wiring comes in the next task — these items are public API
//! consumed from `commands.rs` but not yet called from the binary entry point.

use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::Mutex;

use crate::format::{BOLD, CYAN, DIM, GREEN, RED, RESET, YELLOW};

/// Maximum bytes of output to buffer per background job (256KB, same as StreamingBashTool).
const MAX_OUTPUT_BYTES: usize = 256 * 1024;

/// Default number of tail lines shown by `/bg output`.
const DEFAULT_TAIL_LINES: usize = 50;

/// A background shell job with shared output state.
pub struct BackgroundJob {
    pub id: u32,
    pub command: String,
    pub started_at: Instant,
    pub output: Arc<Mutex<String>>,
    pub finished: Arc<AtomicBool>,
    pub exit_code: Arc<std::sync::Mutex<Option<i32>>>,
}

/// Tracks all background jobs and their associated task handles.
#[derive(Clone)]
pub struct BackgroundJobTracker {
    jobs: Arc<std::sync::Mutex<HashMap<u32, BackgroundJob>>>,
    handles: Arc<std::sync::Mutex<HashMap<u32, tokio::task::JoinHandle<()>>>>,
    next_id: Arc<AtomicU32>,
}

impl BackgroundJobTracker {
    pub fn new() -> Self {
        Self {
            jobs: Arc::new(std::sync::Mutex::new(HashMap::new())),
            handles: Arc::new(std::sync::Mutex::new(HashMap::new())),
            next_id: Arc::new(AtomicU32::new(1)),
        }
    }

    /// Spawn a command in the background. Returns the job ID.
    pub fn launch(&self, command: &str) -> u32 {
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        let output = Arc::new(Mutex::new(String::new()));
        let finished = Arc::new(AtomicBool::new(false));
        let exit_code = Arc::new(std::sync::Mutex::new(None));

        let job = BackgroundJob {
            id,
            command: command.to_string(),
            started_at: Instant::now(),
            output: Arc::clone(&output),
            finished: Arc::clone(&finished),
            exit_code: Arc::clone(&exit_code),
        };

        // Spawn the process in a tokio task
        let cmd_string = command.to_string();
        let out = Arc::clone(&output);
        let fin = Arc::clone(&finished);
        let code = Arc::clone(&exit_code);

        let handle = tokio::spawn(async move {
            run_background_command(&cmd_string, out, fin, code).await;
        });

        {
            let mut jobs = self.jobs.lock().unwrap();
            jobs.insert(id, job);
        }
        {
            let mut handles = self.handles.lock().unwrap();
            handles.insert(id, handle);
        }

        id
    }

    /// List all jobs as snapshots (id, command, finished, exit_code, elapsed).
    pub fn list(&self) -> Vec<JobSnapshot> {
        let jobs = self.jobs.lock().unwrap();
        let mut snapshots: Vec<JobSnapshot> = jobs
            .values()
            .map(|j| JobSnapshot {
                id: j.id,
                command: j.command.clone(),
                finished: j.finished.load(Ordering::Relaxed),
                exit_code: *j.exit_code.lock().unwrap(),
                elapsed: j.started_at.elapsed(),
            })
            .collect();
        snapshots.sort_by_key(|s| s.id);
        snapshots
    }

    /// Get the accumulated output for a job.
    pub async fn get_output(&self, id: u32) -> Option<String> {
        let output_arc = {
            let jobs = self.jobs.lock().unwrap();
            jobs.get(&id).map(|j| Arc::clone(&j.output))
        };
        match output_arc {
            Some(out) => {
                let guard = out.lock().await;
                Some(guard.clone())
            }
            None => None,
        }
    }

    /// Kill a running job. Returns true if the job existed and was killed.
    pub async fn kill(&self, id: u32) -> bool {
        // Abort the tokio task
        let handle = {
            let mut handles = self.handles.lock().unwrap();
            handles.remove(&id)
        };

        if let Some(h) = handle {
            h.abort();
            // Mark the job as finished
            let jobs = self.jobs.lock().unwrap();
            if let Some(j) = jobs.get(&id) {
                j.finished.store(true, Ordering::Relaxed);
                let mut code = j.exit_code.lock().unwrap();
                if code.is_none() {
                    *code = Some(-1); // killed
                }
            }
            true
        } else {
            false
        }
    }

    /// Check if a job ID exists.
    pub fn exists(&self, id: u32) -> bool {
        let jobs = self.jobs.lock().unwrap();
        jobs.contains_key(&id)
    }

    /// Check if a job is finished.
    pub fn is_finished(&self, id: u32) -> bool {
        let jobs = self.jobs.lock().unwrap();
        jobs.get(&id)
            .map(|j| j.finished.load(Ordering::Relaxed))
            .unwrap_or(false)
    }
}

/// A snapshot of a job's state (no Arc/Mutex — safe to print).
pub struct JobSnapshot {
    pub id: u32,
    pub command: String,
    pub finished: bool,
    pub exit_code: Option<i32>,
    pub elapsed: std::time::Duration,
}

/// Run a shell command, streaming output into the shared buffer.
async fn run_background_command(
    command: &str,
    output: Arc<Mutex<String>>,
    finished: Arc<AtomicBool>,
    exit_code: Arc<std::sync::Mutex<Option<i32>>>,
) {
    use tokio::io::AsyncReadExt;
    use tokio::process::Command;

    let child = Command::new("sh")
        .arg("-c")
        .arg(command)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn();

    let mut child = match child {
        Ok(c) => c,
        Err(e) => {
            let mut out = output.lock().await;
            out.push_str(&format!("Failed to spawn: {e}\n"));
            finished.store(true, Ordering::Relaxed);
            let mut code = exit_code.lock().unwrap();
            *code = Some(-1);
            return;
        }
    };

    let stdout = child.stdout.take();
    let stderr = child.stderr.take();

    // Read stdout and stderr concurrently
    let out_clone = Arc::clone(&output);
    let stdout_task = tokio::spawn(async move {
        if let Some(mut reader) = stdout {
            let mut buf = [0u8; 4096];
            loop {
                match reader.read(&mut buf).await {
                    Ok(0) => break,
                    Ok(n) => {
                        let text = String::from_utf8_lossy(&buf[..n]);
                        let mut out = out_clone.lock().await;
                        // Cap output at MAX_OUTPUT_BYTES
                        if out.len() < MAX_OUTPUT_BYTES {
                            let remaining = MAX_OUTPUT_BYTES - out.len();
                            if text.len() <= remaining {
                                out.push_str(&text);
                            } else {
                                // Find a safe char boundary
                                let mut b = remaining;
                                while b > 0 && !text.is_char_boundary(b) {
                                    b -= 1;
                                }
                                out.push_str(&text[..b]);
                            }
                        }
                    }
                    Err(_) => break,
                }
            }
        }
    });

    let err_clone = Arc::clone(&output);
    let stderr_task = tokio::spawn(async move {
        if let Some(mut reader) = stderr {
            let mut buf = [0u8; 4096];
            loop {
                match reader.read(&mut buf).await {
                    Ok(0) => break,
                    Ok(n) => {
                        let text = String::from_utf8_lossy(&buf[..n]);
                        let mut out = err_clone.lock().await;
                        if out.len() < MAX_OUTPUT_BYTES {
                            let remaining = MAX_OUTPUT_BYTES - out.len();
                            if text.len() <= remaining {
                                out.push_str(&text);
                            } else {
                                let mut b = remaining;
                                while b > 0 && !text.is_char_boundary(b) {
                                    b -= 1;
                                }
                                out.push_str(&text[..b]);
                            }
                        }
                    }
                    Err(_) => break,
                }
            }
        }
    });

    // Wait for both readers to finish
    let _ = stdout_task.await;
    let _ = stderr_task.await;

    // Wait for the process to exit
    match child.wait().await {
        Ok(status) => {
            let mut code = exit_code.lock().unwrap();
            *code = Some(status.code().unwrap_or(-1));
        }
        Err(_) => {
            let mut code = exit_code.lock().unwrap();
            *code = Some(-1);
        }
    }

    finished.store(true, Ordering::Relaxed);
}

/// Format elapsed duration for display.
fn format_elapsed(d: std::time::Duration) -> String {
    let secs = d.as_secs();
    if secs < 60 {
        format!("{secs}s")
    } else if secs < 3600 {
        format!("{}m{}s", secs / 60, secs % 60)
    } else {
        format!("{}h{}m", secs / 3600, (secs % 3600) / 60)
    }
}

/// Tail the last N lines of a string.
fn tail_lines(s: &str, n: usize) -> &str {
    let lines: Vec<&str> = s.lines().collect();
    if lines.len() <= n {
        return s;
    }
    let start_line = lines.len() - n;
    // Find byte offset of the start_line-th line
    let mut byte_offset = 0;
    for (i, line) in s.lines().enumerate() {
        if i == start_line {
            break;
        }
        byte_offset += line.len() + 1; // +1 for newline
    }
    // Clamp to string boundary
    if byte_offset >= s.len() {
        ""
    } else {
        &s[byte_offset..]
    }
}

/// Handle the `/bg` command with subcommands.
pub async fn handle_bg(input: &str, tracker: &BackgroundJobTracker) {
    let input = input.trim();

    // Parse subcommand
    let (sub, rest) = match input.find(char::is_whitespace) {
        Some(pos) => (&input[..pos], input[pos..].trim()),
        None => {
            if input.is_empty() {
                ("list", "")
            } else {
                (input, "")
            }
        }
    };

    match sub {
        "run" => handle_bg_run(rest, tracker),
        "list" => handle_bg_list(tracker),
        "output" => handle_bg_output(rest, tracker).await,
        "kill" => handle_bg_kill(rest, tracker).await,
        _ => {
            eprintln!(
                "{RED}Unknown /bg subcommand: {sub}{RESET}\n\
                 Usage: /bg run <cmd> | /bg list | /bg output <id> | /bg kill <id>"
            );
        }
    }
}

fn handle_bg_run(command: &str, tracker: &BackgroundJobTracker) {
    if command.is_empty() {
        eprintln!("{RED}Usage: /bg run <command>{RESET}");
        return;
    }

    let id = tracker.launch(command);
    println!(
        "{GREEN}⚡ Background job {BOLD}[{id}]{RESET}{GREEN} started:{RESET} {DIM}{}{RESET}",
        truncate_command(command, 60)
    );
}

fn handle_bg_list(tracker: &BackgroundJobTracker) {
    let jobs = tracker.list();
    if jobs.is_empty() {
        println!("{DIM}No background jobs{RESET}");
        return;
    }

    println!("{BOLD}{CYAN}Background Jobs{RESET}");
    for job in &jobs {
        let status = if job.finished {
            match job.exit_code {
                Some(0) => format!("{GREEN}✓ done{RESET}"),
                Some(code) => format!("{RED}✗ exit {code}{RESET}"),
                None => format!("{RED}✗ done{RESET}"),
            }
        } else {
            format!("{YELLOW}● running{RESET}")
        };

        let elapsed = format_elapsed(job.elapsed);
        let cmd = truncate_command(&job.command, 50);
        println!(
            "  {BOLD}[{}]{RESET}  {status}  {DIM}{elapsed}{RESET}  {cmd}",
            job.id
        );
    }
}

async fn handle_bg_output(args: &str, tracker: &BackgroundJobTracker) {
    let (id_str, flags) = match args.find(char::is_whitespace) {
        Some(pos) => (&args[..pos], args[pos..].trim()),
        None => (args, ""),
    };

    let id = match id_str.parse::<u32>() {
        Ok(id) => id,
        Err(_) => {
            eprintln!("{RED}Usage: /bg output <id> [--all]{RESET}");
            return;
        }
    };

    if !tracker.exists(id) {
        eprintln!("{RED}No job with ID {id}{RESET}");
        return;
    }

    let show_all = flags.contains("--all");

    match tracker.get_output(id).await {
        Some(output) => {
            if output.is_empty() {
                println!("{DIM}(no output yet){RESET}");
            } else if show_all {
                print!("{output}");
            } else {
                let tail = tail_lines(&output, DEFAULT_TAIL_LINES);
                let total_lines = output.lines().count();
                if total_lines > DEFAULT_TAIL_LINES {
                    println!(
                        "{DIM}... ({} lines omitted, use --all to see everything){RESET}",
                        total_lines - DEFAULT_TAIL_LINES
                    );
                }
                print!("{tail}");
            }
        }
        None => {
            eprintln!("{RED}No job with ID {id}{RESET}");
        }
    }
}

async fn handle_bg_kill(args: &str, tracker: &BackgroundJobTracker) {
    let id_str = args.split_whitespace().next().unwrap_or("");

    let id = match id_str.parse::<u32>() {
        Ok(id) => id,
        Err(_) => {
            eprintln!("{RED}Usage: /bg kill <id>{RESET}");
            return;
        }
    };

    if tracker.is_finished(id) {
        println!("{DIM}Job [{id}] already finished{RESET}");
        return;
    }

    if tracker.kill(id).await {
        println!("{YELLOW}Killed job [{id}]{RESET}");
    } else {
        eprintln!("{RED}No running job with ID {id}{RESET}");
    }
}

/// Truncate a command string for display.
fn truncate_command(cmd: &str, max: usize) -> String {
    let cmd = cmd.lines().next().unwrap_or(cmd); // first line only
    if cmd.len() <= max {
        cmd.to_string()
    } else {
        // Safe char boundary truncation
        let mut b = max.saturating_sub(1);
        while b > 0 && !cmd.is_char_boundary(b) {
            b -= 1;
        }
        format!("{}", &cmd[..b])
    }
}

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

    fn create_tracker() -> BackgroundJobTracker {
        BackgroundJobTracker::new()
    }

    #[tokio::test]
    async fn test_launch_and_list() {
        let tracker = create_tracker();
        let id = tracker.launch("echo hello");
        assert_eq!(id, 1);

        // Wait for the short command to finish
        tokio::time::sleep(std::time::Duration::from_millis(500)).await;

        let jobs = tracker.list();
        assert_eq!(jobs.len(), 1);
        assert_eq!(jobs[0].id, 1);
        assert!(jobs[0].finished);
        assert_eq!(jobs[0].exit_code, Some(0));
    }

    #[tokio::test]
    async fn test_output_capture() {
        let tracker = create_tracker();
        let id = tracker.launch("echo hello && echo world");

        // Wait for the command to finish
        tokio::time::sleep(std::time::Duration::from_millis(500)).await;

        let output = tracker.get_output(id).await.unwrap();
        assert!(
            output.contains("hello"),
            "output should contain 'hello': {output}"
        );
        assert!(
            output.contains("world"),
            "output should contain 'world': {output}"
        );
    }

    #[tokio::test]
    async fn test_kill_running() {
        let tracker = create_tracker();
        let id = tracker.launch("sleep 60");

        // Give it a moment to start
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;

        // Should be running
        assert!(!tracker.is_finished(id));

        // Kill it
        let killed = tracker.kill(id).await;
        assert!(killed);

        // Should be marked finished
        assert!(tracker.is_finished(id));
    }

    #[tokio::test]
    async fn test_job_ids_increment() {
        let tracker = create_tracker();
        let id1 = tracker.launch("echo one");
        let id2 = tracker.launch("echo two");
        assert_eq!(id1, 1);
        assert_eq!(id2, 2);
    }

    #[test]
    fn test_tail_lines() {
        let text = "line1\nline2\nline3\nline4\nline5\n";
        let tail = tail_lines(text, 2);
        assert!(tail.contains("line4"));
        assert!(tail.contains("line5"));
        assert!(!tail.contains("line3"));
    }

    #[test]
    fn test_tail_lines_short() {
        let text = "line1\nline2\n";
        let tail = tail_lines(text, 5);
        assert_eq!(tail, text);
    }

    #[test]
    fn test_truncate_command() {
        let short = "echo hi";
        assert_eq!(truncate_command(short, 20), "echo hi");

        let long = "echo this is a very long command that should be truncated";
        let truncated = truncate_command(long, 20);
        assert!(truncated.len() <= 24); // 20 + "…" (3 bytes)
        assert!(truncated.ends_with(''));
    }

    #[test]
    fn test_truncate_command_multibyte() {
        let cmd = "echo ✓✓✓✓✓✓✓✓✓✓";
        let truncated = truncate_command(cmd, 10);
        // Should not panic on multi-byte chars
        assert!(truncated.ends_with(''));
    }

    #[test]
    fn test_format_elapsed() {
        assert_eq!(format_elapsed(std::time::Duration::from_secs(5)), "5s");
        assert_eq!(format_elapsed(std::time::Duration::from_secs(65)), "1m5s");
        assert_eq!(format_elapsed(std::time::Duration::from_secs(3665)), "1h1m");
    }

    #[tokio::test]
    async fn test_exists() {
        let tracker = create_tracker();
        assert!(!tracker.exists(1));
        let id = tracker.launch("echo hi");
        assert!(tracker.exists(id));
        assert!(!tracker.exists(99));
    }

    #[tokio::test]
    async fn test_failed_command() {
        let tracker = create_tracker();
        tracker.launch("exit 42");

        tokio::time::sleep(std::time::Duration::from_millis(500)).await;

        let jobs = tracker.list();
        assert_eq!(jobs.len(), 1);
        assert!(jobs[0].finished);
        assert_eq!(jobs[0].exit_code, Some(42));
    }
}