ralph-agent-loop 0.3.0

A Rust CLI for managing AI agent loops with a structured JSON task queue
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
//! Stream filtering tests for runner execution output.

use super::super::stream::{StreamSink, display_filtered_json, extract_display_lines};
use crate::constants::buffers::{MAX_BUFFER_SIZE, MAX_LINE_LENGTH};
use crate::runner::{OutputHandler, OutputStream};
use serde_json::json;
use std::io::Cursor;
use std::sync::{Arc, Mutex};

// Re-export spawn functions for testing (they're pub(super) in parent)
use super::super::stream::{spawn_json_reader, spawn_reader};

#[test]
fn extract_display_lines_codex_agent_message() {
    let payload = json!({
        "type": "item.completed",
        "item": {"type": "agent_message", "text": "Hi!"}
    });
    assert_eq!(extract_display_lines(&payload), vec!["Hi!", ""]);
}

#[test]
fn extract_display_lines_codex_reasoning() {
    let payload = json!({
        "type": "item.completed",
        "item": {"type": "reasoning", "text": "Working it out"}
    });
    let lines = extract_display_lines(&payload);
    assert_eq!(lines.len(), 1);

    // Line should contain [Reasoning] prefix and the content text
    // Note: format_reasoning() adds ANSI color codes to the prefix only
    let reasoning_line = &lines[0];
    assert!(reasoning_line.contains("[Reasoning]"));
    assert!(reasoning_line.contains("Working it out"));
}

#[test]
fn extract_display_lines_codex_tool_call() {
    let payload = json!({
        "type": "item.completed",
        "item": {
            "type": "mcp_tool_call",
            "server": "RepoPrompt",
            "tool": "get_file_tree",
            "status": "completed",
            "arguments": {
                "path": "/tmp/project",
                "pattern": "*.rs"
            }
        }
    });
    assert_eq!(
        extract_display_lines(&payload),
        vec!["[Tool] RepoPrompt.get_file_tree (completed) path=/tmp/project pattern=*.rs"]
    );
}

#[test]
fn extract_display_lines_codex_command_execution() {
    let payload = json!({
        "type": "item.started",
        "item": {
            "type": "command_execution",
            "command": "/bin/zsh -lc ls",
            "status": "in_progress",
            "exit_code": null
        }
    });
    assert_eq!(
        extract_display_lines(&payload),
        vec!["[Command] /bin/zsh -lc ls (in_progress)"]
    );
}

#[test]
fn extract_display_lines_claude_result_and_tool_use() {
    let payload = json!({
        "result": "Final answer",
        "type": "assistant",
        "message": {
            "content": [
                {"type": "text", "text": "Streamed text"},
                {"type": "tool_use", "name": "Read", "input": {"file_path": "/tmp/a.txt"}}
            ]
        }
    });
    assert_eq!(
        extract_display_lines(&payload),
        vec![
            "Final answer",
            "Streamed text",
            "[Tool] Read path=/tmp/a.txt"
        ]
    );
}

#[test]
fn extract_display_lines_permission_denial() {
    let payload = json!({
        "permission_denials": [
            {"tool_name": "write"}
        ]
    });
    assert_eq!(
        extract_display_lines(&payload),
        vec!["[Permission denied: write]"]
    );
}

#[test]
fn display_filtered_json_calls_output_handler() {
    let payload = json!({
        "type": "text",
        "part": { "text": "hello" }
    });
    let captured: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
    let handler: OutputHandler = Arc::new(Box::new({
        let captured = Arc::clone(&captured);
        move |text: &str| {
            captured
                .lock()
                .expect("capture lock")
                .push(text.to_string());
        }
    }));

    display_filtered_json(
        &payload,
        &StreamSink::Stdout,
        Some(&handler),
        OutputStream::HandlerOnly,
    )
    .expect("display filtered json");

    let guard = captured.lock().expect("capture lock");
    assert_eq!(guard.as_slice(), &["hello\n".to_string()]);
}

#[test]
fn extract_display_lines_opencode_text() {
    let payload = json!({
        "type": "text",
        "part": { "text": "hello" }
    });
    assert_eq!(extract_display_lines(&payload), vec!["hello"]);
}

#[test]
fn extract_display_lines_opencode_reasoning() {
    let payload = json!({
        "type": "reasoning",
        "part": { "text": "Considering tool strategy" }
    });
    let lines = extract_display_lines(&payload);
    assert_eq!(lines.len(), 1);
    assert!(lines[0].contains("[Reasoning]"));
    assert!(lines[0].contains("Considering tool strategy"));
}

#[test]
fn extract_display_lines_opencode_tool_use() {
    let payload = json!({
        "type": "tool_use",
        "part": {
            "tool": "read",
            "state": {
                "status": "completed",
                "input": { "filePath": "/tmp/example.txt" }
            }
        }
    });
    assert_eq!(
        extract_display_lines(&payload),
        vec!["[Tool] read (completed) path=/tmp/example.txt"]
    );
}

#[test]
fn extract_display_lines_gemini_tool_use_and_result() {
    let tool_use = json!({
        "type": "tool_use",
        "tool_name": "read_file",
        "parameters": { "file_path": "notes.txt" }
    });
    assert_eq!(
        extract_display_lines(&tool_use),
        vec!["[Tool] read_file path=notes.txt"]
    );

    let tool_result = json!({
        "type": "tool_result",
        "tool_name": "read_file",
        "status": "success"
    });
    assert_eq!(
        extract_display_lines(&tool_result),
        vec!["[Tool] read_file (success)"]
    );
}

#[test]
fn extract_display_lines_gemini_message_assistant() {
    let payload = json!({
        "type": "message",
        "role": "assistant",
        "content": "hi"
    });
    assert_eq!(extract_display_lines(&payload), vec!["hi"]);
}

#[test]
fn extract_display_lines_claude_result_error_payload() {
    let payload = json!({
        "type": "result",
        "is_error": true,
        "errors": ["invalid session id"]
    });
    assert_eq!(
        extract_display_lines(&payload),
        vec!["[Error] invalid session id"]
    );
}

#[test]
fn extract_display_lines_codex_error_event() {
    let payload = json!({
        "type": "error",
        "message": "Session stream failed"
    });
    assert_eq!(
        extract_display_lines(&payload),
        vec!["[Error] Session stream failed"]
    );
}

#[test]
fn extract_display_lines_unknown_event_is_noop() {
    let payload = json!({"type": "unknown"});
    assert!(extract_display_lines(&payload).is_empty());
}

#[test]
fn extract_display_lines_kimi_assistant_with_think() {
    let payload = json!({
        "role": "assistant",
        "content": [
            {"type": "think", "think": "Analyzing the request"},
            {"type": "text", "text": "Hello! How can I help?"}
        ]
    });
    let lines = extract_display_lines(&payload);
    assert_eq!(lines.len(), 2);

    // First line should contain [Reasoning] prefix and the reasoning content
    // Note: format_reasoning() adds ANSI color codes to the prefix only
    let reasoning_line = &lines[0];
    assert!(reasoning_line.contains("[Reasoning]"));
    assert!(reasoning_line.contains("Analyzing the request"));

    // Second line is plain text content
    assert_eq!(lines[1], "Hello! How can I help?");
}

#[test]
fn extract_display_lines_kimi_assistant_text_only() {
    let payload = json!({
        "role": "assistant",
        "content": [
            {"type": "text", "text": "Response text"}
        ]
    });
    assert_eq!(extract_display_lines(&payload), vec!["Response text"]);
}

#[test]
fn extract_display_lines_kimi_with_tool_calls() {
    let payload = json!({
        "role": "assistant",
        "content": [{"type": "text", "text": "Using tool"}],
        "tool_calls": [{"id": "tool_abc123", "type": "function"}]
    });
    // Should extract text content, ignore tool_calls for display
    assert_eq!(extract_display_lines(&payload), vec!["Using tool"]);
}

#[test]
fn extract_display_lines_kimi_empty_content() {
    let payload = json!({
        "role": "assistant",
        "content": []
    });
    assert!(extract_display_lines(&payload).is_empty());
}

#[test]
fn extract_display_lines_kimi_no_role_field() {
    // Without role="assistant", should not be treated as kimi format
    let payload = json!({
        "content": [{"type": "text", "text": "Some text"}]
    });
    assert!(extract_display_lines(&payload).is_empty());
}

#[test]
fn extract_display_lines_pi_message_end_assistant() {
    let payload = json!({
        "type": "message_end",
        "message": {
            "role": "assistant",
            "content": [
                {"type": "text", "text": "Key findings cited in evidence: Alpha"}
            ]
        }
    });
    assert_eq!(
        extract_display_lines(&payload),
        vec!["Key findings cited in evidence: Alpha"]
    );
}

#[test]
fn extract_display_lines_pi_message_end_tool_result() {
    let payload = json!({
        "type": "message_end",
        "message": {
            "role": "toolResult",
            "toolName": "bash",
            "isError": false
        }
    });
    assert_eq!(
        extract_display_lines(&payload),
        vec!["[Tool] bash (completed)"]
    );
}

#[test]
fn extract_display_lines_cursor_tool_call_mcp() {
    let payload = json!({
        "type": "tool_call",
        "tool_call": {
            "mcpToolCall": {
                "args": {
                    "providerIdentifier": "RepoPrompt",
                    "toolName": "list_windows",
                    "args": {}
                }
            }
        }
    });
    assert_eq!(
        extract_display_lines(&payload),
        vec!["[Tool] RepoPrompt.list_windows"]
    );
}

#[test]
fn extract_display_lines_cursor_tool_call_shell() {
    let payload = json!({
        "type": "tool_call",
        "tool_call": {
            "shellToolCall": {
                "args": {
                    "command": "ls -la"
                }
            }
        }
    });
    assert_eq!(
        extract_display_lines(&payload),
        vec!["[Tool] shell cmd=ls -la"]
    );
}

#[test]
fn max_line_length_constant_is_10mb() {
    // Verify the constant is set to expected 10MB value (reduced from 100MB)
    assert_eq!(MAX_LINE_LENGTH, 10 * 1024 * 1024);
}

#[test]
fn max_buffer_size_constant_is_10mb() {
    // Verify the constant is set to expected 10MB value (reduced from 100MB)
    assert_eq!(MAX_BUFFER_SIZE, 10 * 1024 * 1024);
}

#[test]
fn spawn_json_reader_handles_normal_lines() {
    let input = r#"{"type":"text","part":{"text":"hello world"}}"#;
    let reader = Cursor::new(input.as_bytes());
    let buffer: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));
    let session_id_buf: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));

    let handle = spawn_json_reader(
        reader,
        StreamSink::Stdout,
        Arc::clone(&buffer),
        None,
        OutputStream::HandlerOnly,
        session_id_buf,
    );

    let result = handle.join().unwrap();
    assert!(result.is_ok());

    let guard = buffer.lock().unwrap();
    assert!(guard.contains("hello world"));
}

#[test]
fn spawn_json_reader_enforces_line_length_limit() {
    // Create input that exceeds MAX_LINE_LENGTH without newlines
    // Use owned data to satisfy 'static requirement
    let oversized_data: Vec<u8> = vec![b'x'; MAX_LINE_LENGTH + 1000];
    let reader = Cursor::new(oversized_data);
    let buffer: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));
    let session_id_buf: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));

    let handle = spawn_json_reader(
        reader,
        StreamSink::Stdout,
        Arc::clone(&buffer),
        None,
        OutputStream::HandlerOnly,
        session_id_buf,
    );

    let result = handle.join().unwrap();
    assert!(result.is_ok());

    // The shared output buffer should not grow beyond MAX_BUFFER_SIZE.
    // Note: line_buf has MAX_LINE_LENGTH protection, but the shared buffer
    // has MAX_BUFFER_SIZE protection (both are 10MB in current config).
    let guard = buffer.lock().unwrap();
    assert!(guard.len() <= MAX_BUFFER_SIZE);
}

#[test]
fn spawn_json_reader_handles_multiple_lines_within_limit() {
    // Create multiple normal-sized lines
    let lines: Vec<String> = (0..100)
        .map(|i| format!(r#"{{"type":"text","part":{{"text":"line {}"}}}}"#, i))
        .collect();
    let input = lines.join("\n");
    // Use owned data to satisfy 'static requirement
    let reader = Cursor::new(input.into_bytes());
    let buffer: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));
    let session_id_buf: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));

    let handle = spawn_json_reader(
        reader,
        StreamSink::Stdout,
        Arc::clone(&buffer),
        None,
        OutputStream::HandlerOnly,
        session_id_buf,
    );

    let result = handle.join().unwrap();
    assert!(result.is_ok());

    let guard = buffer.lock().unwrap();
    // Buffer should contain all the input since lines are processed and cleared
    assert!(guard.contains("line 0"));
    assert!(guard.contains("line 99"));
}

#[test]
fn spawn_reader_enforces_buffer_limit() {
    // Create input that exceeds MAX_BUFFER_SIZE
    // Use owned data to satisfy 'static requirement
    let oversized_data: Vec<u8> = vec![b'x'; MAX_BUFFER_SIZE + 10000];
    let reader = Cursor::new(oversized_data);
    let buffer: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));

    let handle = spawn_reader(
        reader,
        StreamSink::Stderr,
        Arc::clone(&buffer),
        None,
        OutputStream::HandlerOnly,
    );

    let result = handle.join().unwrap();
    assert!(result.is_ok());

    // The buffer should be truncated to MAX_BUFFER_SIZE
    let guard = buffer.lock().unwrap();
    assert!(guard.len() <= MAX_BUFFER_SIZE);
}

#[test]
fn spawn_reader_handles_normal_output() {
    let input = "Hello, world!\nThis is a test.\n";
    let reader = Cursor::new(input.as_bytes());
    let buffer: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));

    let handle = spawn_reader(
        reader,
        StreamSink::Stderr,
        Arc::clone(&buffer),
        None,
        OutputStream::HandlerOnly,
    );

    let result = handle.join().unwrap();
    assert!(result.is_ok());

    let guard = buffer.lock().unwrap();
    assert_eq!(guard.as_str(), input);
}

#[test]
fn spawn_json_reader_handles_empty_input() {
    let reader = Cursor::new(b"");
    let buffer: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));
    let session_id_buf: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));

    let handle = spawn_json_reader(
        reader,
        StreamSink::Stdout,
        Arc::clone(&buffer),
        None,
        OutputStream::HandlerOnly,
        session_id_buf,
    );

    let result = handle.join().unwrap();
    assert!(result.is_ok());

    let guard = buffer.lock().unwrap();
    assert!(guard.is_empty());
}

#[test]
fn spawn_reader_handles_empty_input() {
    let reader = Cursor::new(b"");
    let buffer: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));

    let handle = spawn_reader(
        reader,
        StreamSink::Stderr,
        Arc::clone(&buffer),
        None,
        OutputStream::HandlerOnly,
    );

    let result = handle.join().unwrap();
    assert!(result.is_ok());

    let guard = buffer.lock().unwrap();
    assert!(guard.is_empty());
}

#[test]
fn spawn_json_reader_handles_line_exactly_at_limit() {
    // Create a line that is exactly at MAX_LINE_LENGTH
    // Use owned data to satisfy 'static requirement
    let exact_size_data: Vec<u8> = vec![b'x'; MAX_LINE_LENGTH];
    let reader = Cursor::new(exact_size_data);
    let buffer: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));
    let session_id_buf: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));

    let handle = spawn_json_reader(
        reader,
        StreamSink::Stdout,
        Arc::clone(&buffer),
        None,
        OutputStream::HandlerOnly,
        session_id_buf,
    );

    let result = handle.join().unwrap();
    assert!(result.is_ok());

    // The buffer should contain exactly MAX_LINE_LENGTH characters
    let guard = buffer.lock().unwrap();
    assert_eq!(guard.len(), MAX_LINE_LENGTH);
}

#[test]
fn spawn_json_reader_handles_partial_line_at_eof() {
    // Create a partial line (no trailing newline) that should still be processed
    let partial_line = r#"{"type":"text","part":{"text":"partial"}}"#;
    let reader = Cursor::new(partial_line.as_bytes());
    let buffer: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));
    let session_id_buf: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));

    let handle = spawn_json_reader(
        reader,
        StreamSink::Stdout,
        Arc::clone(&buffer),
        None,
        OutputStream::HandlerOnly,
        session_id_buf,
    );

    let result = handle.join().unwrap();
    assert!(result.is_ok());

    let guard = buffer.lock().unwrap();
    assert!(guard.contains("partial"));
}

#[test]
fn extract_display_lines_kimi_tool_result_shows_completed() {
    // Tool results show "(completed)" rather than content to avoid verbose output
    let payload = json!({
        "role": "tool",
        "content": [{"type": "text", "text": "file contents here"}],
        "tool_call_id": "call_1",
        "tool_name": "read_file"
    });
    let result = extract_display_lines(&payload);
    assert_eq!(result.len(), 1);
    // format_tool_call produces "[Tool] tool_name (completed)" format
    assert!(result[0].contains("[Tool]"));
    assert!(result[0].contains("read_file"));
    assert!(result[0].contains("(completed)"));
    // Should NOT contain the actual content
    assert!(!result[0].contains("file contents here"));
}

#[test]
fn extract_display_lines_kimi_tool_result_without_tool_name() {
    // Without tool_name, defaults to "Tool"
    let payload = json!({
        "role": "tool",
        "content": [{"type": "text", "text": "output data"}],
        "tool_call_id": "call_1"
    });
    let result = extract_display_lines(&payload);
    assert_eq!(result.len(), 1);
    // format_tool_call produces "[Tool] Tool (completed)" format when tool_name is missing
    assert!(result[0].contains("[Tool]"));
    assert!(result[0].contains("Tool"));
    assert!(result[0].contains("(completed)"));
}

#[test]
fn extract_display_lines_kimi_tool_result_empty_content() {
    // Empty content still shows (completed)
    let payload = json!({
        "role": "tool",
        "content": [],
        "tool_call_id": "call_1",
        "tool_name": "search"
    });
    let result = extract_display_lines(&payload);
    assert_eq!(result.len(), 1);
    // format_tool_call produces "[Tool] tool_name (completed)" format
    assert!(result[0].contains("[Tool]"));
    assert!(result[0].contains("search"));
    assert!(result[0].contains("(completed)"));
}

#[test]
fn extract_display_lines_kimi_tool_result_no_content_field() {
    // No content field still shows (completed)
    let payload = json!({
        "role": "tool",
        "tool_call_id": "call_1",
        "tool_name": "list_files"
    });
    let result = extract_display_lines(&payload);
    assert_eq!(result.len(), 1);
    // format_tool_call produces "[Tool] tool_name (completed)" format
    assert!(result[0].contains("[Tool]"));
    assert!(result[0].contains("list_files"));
    assert!(result[0].contains("(completed)"));
}

#[test]
fn extract_display_lines_kimi_assistant_with_mixed_content() {
    // Test assistant message with both text and think parts
    let payload = json!({
        "role": "assistant",
        "content": [
            {"type": "think", "think": "Let me analyze this"},
            {"type": "text", "text": "Here's the answer"}
        ]
    });
    let result = extract_display_lines(&payload);
    assert_eq!(result.len(), 2);
    assert!(result[0].contains("Let me analyze this"));
    assert_eq!(result[1], "Here's the answer");
}

#[test]
fn extract_display_lines_kimi_tool_result_multiple_content_parts() {
    // Multiple content parts still just show single (completed) line
    let payload = json!({
        "role": "tool",
        "content": [
            {"type": "text", "text": "First part"},
            {"type": "text", "text": "Second part"}
        ],
        "tool_call_id": "call_1",
        "tool_name": "bash"
    });
    let result = extract_display_lines(&payload);
    assert_eq!(result.len(), 1);
    // format_tool_call produces "[Tool] tool_name (completed)" format
    assert!(result[0].contains("[Tool]"));
    assert!(result[0].contains("bash"));
    assert!(result[0].contains("(completed)"));
}