ralph-cli 2.9.2

Command-line interface for Ralph Orchestrator
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
//! Display functions for terminal output.
//!
//! This module contains functions for formatting and printing
//! iteration separators, termination messages, event tables,
//! and other terminal UI elements.

use ralph_core::{EventRecord, TerminationReason, floor_char_boundary, truncate_with_ellipsis};
use ralph_proto::HatId;
use std::collections::HashMap;
use std::time::Duration;

/// ANSI color codes for terminal output.
pub mod colors {
    pub const RESET: &str = "\x1b[0m";
    pub const BOLD: &str = "\x1b[1m";
    pub const DIM: &str = "\x1b[2m";
    pub const GREEN: &str = "\x1b[32m";
    pub const YELLOW: &str = "\x1b[33m";
    pub const RED: &str = "\x1b[31m";
    pub const CYAN: &str = "\x1b[36m";
    pub const BLUE: &str = "\x1b[34m";
    pub const MAGENTA: &str = "\x1b[35m";
}

/// Returns the emoji for a hat ID.
pub fn hat_emoji(hat_id: &str) -> &'static str {
    match hat_id {
        "planner" => "?",
        "builder" => "?",
        "reviewer" => "?",
        _ => "?",
    }
}

/// Prints the iteration demarcation separator.
///
/// Per spec: "Each iteration must be clearly demarcated in the output so users can
/// visually distinguish where one iteration ends and another begins."
///
/// Format:
/// ```text
/// ===============================================================================
///  ITERATION 3 | ? builder | 2m 15s elapsed | 3/100
/// ===============================================================================
/// ```
pub fn print_iteration_separator(
    iteration: u32,
    hat_id: &str,
    elapsed: Duration,
    max_iterations: u32,
    use_colors: bool,
) {
    use colors::*;

    let emoji = hat_emoji(hat_id);
    let elapsed_str = format_elapsed(elapsed);

    // Build the content line (without box chars for measuring)
    let content = format!(
        " ITERATION {} | {} {} | {} elapsed | {}/{}",
        iteration, emoji, hat_id, elapsed_str, iteration, max_iterations
    );

    // Use fixed width of 79 characters for the box (standard terminal width)
    let box_width = 79;
    let separator = "=".repeat(box_width);

    if use_colors {
        println!("\n{BOLD}{CYAN}{separator}{RESET}");
        println!("{BOLD}{CYAN}{content}{RESET}");
        println!("{BOLD}{CYAN}{separator}{RESET}");
    } else {
        println!("\n{separator}");
        println!("{content}");
        println!("{separator}");
    }
}

/// Formats elapsed duration as human-readable string.
pub fn format_elapsed(d: Duration) -> String {
    let total_secs = d.as_secs();
    let hours = total_secs / 3600;
    let minutes = (total_secs % 3600) / 60;
    let seconds = total_secs % 60;

    if hours > 0 {
        format!("{}h {}m {}s", hours, minutes, seconds)
    } else if minutes > 0 {
        format!("{}m {}s", minutes, seconds)
    } else {
        format!("{}s", seconds)
    }
}

/// Truncates a string to max_len characters, adding ellipsis if truncated.
pub fn truncate(s: &str, max_len: usize) -> String {
    truncate_with_ellipsis(s, max_len)
}

/// Prints termination message with status.
pub fn print_termination(
    reason: &TerminationReason,
    state: &ralph_core::LoopState,
    use_colors: bool,
) {
    use colors::*;

    // Determine status color and message based on termination reason
    let (color, icon, label) = match reason {
        TerminationReason::CompletionPromise => (GREEN, "?", "Completion promise detected"),
        TerminationReason::MaxIterations => (YELLOW, "?", "Maximum iterations reached"),
        TerminationReason::MaxRuntime => (YELLOW, "?", "Maximum runtime exceeded"),
        TerminationReason::MaxCost => (YELLOW, "?", "Maximum cost exceeded"),
        TerminationReason::ConsecutiveFailures => (RED, "?", "Too many consecutive failures"),
        TerminationReason::LoopThrashing => (RED, "?", "Loop thrashing detected"),
        TerminationReason::LoopStale => (RED, "?", "Stale loop detected"),
        TerminationReason::ValidationFailure => (RED, "?", "Too many malformed JSONL events"),
        TerminationReason::Stopped => (CYAN, "?", "Manually stopped"),
        TerminationReason::Interrupted => (YELLOW, "?", "Interrupted by signal"),
        TerminationReason::RestartRequested => (CYAN, "", "Restarting by human request"),
        TerminationReason::WorkspaceGone => (RED, "?", "Workspace directory removed"),
        TerminationReason::Cancelled => (CYAN, "", "Cancelled gracefully"),
    };

    let separator = "-".repeat(58);

    if use_colors {
        println!("\n{BOLD}+{separator}+{RESET}");
        println!(
            "{BOLD}|{RESET} {color}{BOLD}{icon}{RESET} Loop terminated: {color}{label}{RESET}"
        );
        println!("{BOLD}+{separator}+{RESET}");
        println!(
            "{BOLD}|{RESET}   Iterations:  {CYAN}{}{RESET}",
            state.iteration
        );
        println!(
            "{BOLD}|{RESET}   Elapsed:     {CYAN}{:.1}s{RESET}",
            state.elapsed().as_secs_f64()
        );
        if state.cumulative_cost > 0.0 {
            println!(
                "{BOLD}|{RESET}   Est. cost:   {CYAN}${:.2}{RESET}",
                state.cumulative_cost
            );
        }
        println!("{BOLD}+{separator}+{RESET}");
    } else {
        println!("\n+{}+", "-".repeat(58));
        println!("| {icon} Loop terminated: {label}");
        println!("+{}+", "-".repeat(58));
        println!("|   Iterations:  {}", state.iteration);
        println!("|   Elapsed:     {:.1}s", state.elapsed().as_secs_f64());
        if state.cumulative_cost > 0.0 {
            println!("|   Est. cost:   ${:.2}", state.cumulative_cost);
        }
        println!("+{}+", "-".repeat(58));
    }
}

/// Gets the color for a topic based on its prefix.
pub fn get_topic_color(topic: &str) -> &'static str {
    use colors::*;
    if topic.starts_with("task.") {
        CYAN
    } else if topic.starts_with("build.done") {
        GREEN
    } else if topic.starts_with("build.blocked") {
        RED
    } else if topic.starts_with("build.") {
        YELLOW
    } else if topic.starts_with("review.") {
        MAGENTA
    } else {
        BLUE
    }
}

/// Prints a table of event records.
pub fn print_events_table(records: &[EventRecord], use_colors: bool) {
    use colors::*;

    // Header
    if use_colors {
        println!(
            "{BOLD}{DIM}  # | Time     | Iteration | Hat           | Topic              | Triggered      | Payload{RESET}"
        );
        println!(
            "{DIM}----+----------+-----------+---------------+--------------------+----------------+-----------------{RESET}"
        );
    } else {
        println!(
            "  # | Time     | Iteration | Hat           | Topic              | Triggered      | Payload"
        );
        println!(
            "----|----------|-----------|---------------|--------------------|-----------------|-----------------"
        );
    }

    for (i, record) in records.iter().enumerate() {
        let topic_color = get_topic_color(&record.topic);
        let triggered = record.triggered.as_deref().unwrap_or("-");
        let payload_one_line = record.payload.replace('\n', " ");
        let payload_preview = truncate_with_ellipsis(&payload_one_line, 40);

        // Extract time portion (HH:MM:SS) from ISO 8601 timestamp
        let time = record
            .ts
            .find('T')
            .and_then(|t_pos| {
                let after_t = &record.ts[t_pos + 1..];
                // Find end of time (before timezone indicator or end of string)
                let end = after_t
                    .find(|c| c == 'Z' || c == '+' || c == '-')
                    .unwrap_or(after_t.len());
                let time_str = &after_t[..end];
                // Take only HH:MM:SS (usually ASCII), but still ensure we slice on a valid UTF-8
                // boundary for robustness. Otherwise, an unexpected `ts` (e.g. CJK/emoji) can make
                // `&s[..N]` panic.
                let boundary = floor_char_boundary(time_str, 8);
                Some(&time_str[..boundary])
            })
            .unwrap_or("-");

        if use_colors {
            println!(
                "{DIM}{:>3}{RESET} | {:<8} | {:>9} | {:<13} | {topic_color}{:<18}{RESET} | {:<14} | {DIM}{}{RESET}",
                i + 1,
                time,
                record.iteration,
                truncate(&record.hat, 13),
                truncate(&record.topic, 18),
                truncate(triggered, 14),
                payload_preview
            );
        } else {
            println!(
                "{:>3} | {:<8} | {:>9} | {:<13} | {:<18} | {:<14} | {}",
                i + 1,
                time,
                record.iteration,
                truncate(&record.hat, 13),
                truncate(&record.topic, 18),
                truncate(triggered, 14),
                payload_preview
            );
        }
    }

    // Footer
    if use_colors {
        println!("\n{DIM}Total: {} events{RESET}", records.len());
    } else {
        println!("\nTotal: {} events", records.len());
    }
}

/// Prints the wave header separator when a wave is detected.
///
/// Format:
/// ```text
/// ── WAVE: 🔍 Reviewer | 3 workers | timeout 600s ─────────────────────────────
/// ```
pub fn print_wave_header(hat_name: &str, worker_count: usize, timeout_secs: u64, use_colors: bool) {
    use colors::*;

    let emoji = hat_emoji(hat_name);
    let content = format!(
        " WAVE: {} {} | {} workers | timeout {}s ",
        emoji, hat_name, worker_count, timeout_secs
    );

    let box_width = 79;
    let content_len = content.len();
    let pad = if content_len + 2 < box_width {
        box_width - content_len - 2
    } else {
        0
    };

    if use_colors {
        eprintln!("\n{BOLD}{MAGENTA}──{content}{}{RESET}", "".repeat(pad));
    } else {
        eprintln!("\n──{content}{}", "".repeat(pad));
    }
}

/// Prints a per-worker completion line as each wave worker finishes.
///
/// Format:
/// ```text
///   ✓ Worker 1/3 done (45s) — ROLE: Rust Reviewer. Focus on ...
///   ✗ Worker 3/3 failed (600s) — ROLE: Documentation Reviewer. Focus on ...
/// ```
pub fn print_wave_worker_done(
    index: u32,
    total: u32,
    duration: Duration,
    success: bool,
    payload_preview: &str,
    use_colors: bool,
) {
    use colors::*;

    let elapsed = format_elapsed(duration);
    let status_word = if success { "done" } else { "failed" };
    let preview = truncate(payload_preview, 60);

    if use_colors {
        let (icon, color) = if success {
            ("", GREEN)
        } else {
            ("", RED)
        };
        eprintln!(
            "  {color}{BOLD}{icon}{RESET} Worker {}/{} {} ({}) — {}",
            index + 1,
            total,
            status_word,
            elapsed,
            preview
        );
    } else {
        let icon = if success { "" } else { "" };
        eprintln!(
            "  {} Worker {}/{} {} ({}) — {}",
            icon,
            index + 1,
            total,
            status_word,
            elapsed,
            preview
        );
    }
}

/// Prints the wave summary separator after all workers finish.
///
/// Format:
/// ```text
/// ── Wave complete: 2 succeeded, 1 failed (52s) ────────────────────────────────
/// ```
pub fn print_wave_summary(
    succeeded: usize,
    failed: usize,
    total_duration: Duration,
    use_colors: bool,
) {
    use colors::*;

    let elapsed = format_elapsed(total_duration);
    let content = format!(
        " Wave complete: {} succeeded, {} failed ({}) ",
        succeeded, failed, elapsed
    );

    let box_width = 79;
    let content_len = content.len();
    let pad = if content_len + 2 < box_width {
        box_width - content_len - 2
    } else {
        0
    };

    if use_colors {
        let summary_color = if failed > 0 { YELLOW } else { GREEN };
        eprintln!("{BOLD}{summary_color}──{content}{}{RESET}", "".repeat(pad));
    } else {
        eprintln!("──{content}{}", "".repeat(pad));
    }
}

/// Builds a map of event topics to hat display information for the TUI.
///
/// This allows the TUI to dynamically resolve which hat should be displayed
/// for any event topic, including custom hats (e.g., "review.security" -> "Security Reviewer").
///
/// Only exact topic patterns (non-wildcard) are included to avoid pattern matching complexity.
pub fn build_tui_hat_map(registry: &ralph_core::HatRegistry) -> HashMap<String, (HatId, String)> {
    let mut map = HashMap::new();

    for hat in registry.all() {
        // For each subscription topic, add exact matches to the map
        for subscription in &hat.subscriptions {
            let topic_str = subscription.to_string();
            // Only add non-wildcard topics
            if !topic_str.contains('*') {
                map.insert(topic_str, (hat.id.clone(), hat.name.clone()));
            }
        }
    }

    map
}

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

    #[test]
    fn test_format_elapsed_seconds_only() {
        let d = Duration::from_secs(45);
        assert_eq!(format_elapsed(d), "45s");
    }

    #[test]
    fn test_format_elapsed_minutes_and_seconds() {
        let d = Duration::from_secs(125); // 2m 5s
        assert_eq!(format_elapsed(d), "2m 5s");
    }

    #[test]
    fn test_format_elapsed_hours_minutes_seconds() {
        let d = Duration::from_secs(3725); // 1h 2m 5s
        assert_eq!(format_elapsed(d), "1h 2m 5s");
    }

    #[test]
    fn test_truncate_short_string() {
        assert_eq!(truncate("hello", 10), "hello");
    }

    #[test]
    fn test_truncate_long_string() {
        assert_eq!(truncate("hello world", 8), "hello...");
    }

    #[test]
    fn test_truncate_does_not_panic_on_multibyte_chars() {
        // Let a multi-byte character straddle the truncation boundary. The old implementation
        // would panic because `&s[..N]` was not on a UTF-8 boundary.
        let s = format!("{}{}", "x".repeat(39), "y".repeat(10));

        let out = truncate(&s, 40);

        // Verify output is valid UTF-8 (iterating `chars()` should not panic).
        for _ in out.chars() {}
        assert!(out.ends_with("..."));
    }

    #[test]
    fn test_print_events_table_does_not_panic_on_multibyte_payload() {
        // Trigger the `payload_preview` truncation path (>40 bytes) and place an emoji near the
        // boundary.
        let payload = format!("{}{}", "x".repeat(39), "y".repeat(10));
        let record = EventRecord {
            ts: "2026-01-23T00:00:00Z".to_string(),
            iteration: 1,
            hat: "hat".to_string(),
            topic: "task.start".to_string(),
            triggered: None,
            payload,
            blocked_count: None,
            wave_id: None,
            wave_index: None,
            wave_total: None,
        };

        print_events_table(&[record], false);
    }

    #[test]
    fn test_print_events_table_does_not_panic_on_multibyte_ts() {
        // Make a multi-byte character land on the "take the first 8 bytes" boundary. The old
        // implementation would panic because `&time_str[..8]` was not a UTF-8 boundary.
        let record = EventRecord {
            ts: "2026-01-23Txxxxxxx✅Z".to_string(),
            iteration: 1,
            hat: "hat".to_string(),
            topic: "task.start".to_string(),
            triggered: None,
            payload: "ok".to_string(),
            blocked_count: None,
            wave_id: None,
            wave_index: None,
            wave_total: None,
        };

        print_events_table(&[record], false);
    }

    #[test]
    fn test_hat_emoji_known_hats() {
        assert_eq!(hat_emoji("planner"), "?");
        assert_eq!(hat_emoji("builder"), "?");
        assert_eq!(hat_emoji("reviewer"), "?");
    }

    #[test]
    fn test_hat_emoji_unknown_hat() {
        assert_eq!(hat_emoji("custom_hat"), "?");
    }

    #[test]
    fn test_build_tui_hat_map_extracts_custom_hats() {
        // Given: A config with custom hats from pr-review preset
        let yaml = r#"
hats:
  security_reviewer:
    name: "Security Reviewer"
    triggers: ["review.security"]
    publishes: ["security.done"]
  correctness_reviewer:
    name: "Correctness Reviewer"
    triggers: ["review.correctness"]
    publishes: ["correctness.done"]
  architecture_reviewer:
    name: "Architecture Reviewer"
    triggers: ["review.architecture", "arch.*"]
    publishes: ["architecture.done"]
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = ralph_core::HatRegistry::from_config(&config);

        // When: Building the TUI hat map
        let hat_map = build_tui_hat_map(&registry);

        // Then: Exact topic patterns should be mapped
        assert_eq!(hat_map.len(), 3, "Should have 3 exact topic mappings");

        // Security reviewer
        assert!(
            hat_map.contains_key("review.security"),
            "Should map review.security topic"
        );
        let (hat_id, hat_display) = &hat_map["review.security"];
        assert_eq!(hat_id.as_str(), "security_reviewer");
        assert_eq!(hat_display, "Security Reviewer");

        // Correctness reviewer
        assert!(
            hat_map.contains_key("review.correctness"),
            "Should map review.correctness topic"
        );
        let (hat_id, hat_display) = &hat_map["review.correctness"];
        assert_eq!(hat_id.as_str(), "correctness_reviewer");
        assert_eq!(hat_display, "Correctness Reviewer");

        // Architecture reviewer - exact topic only
        assert!(
            hat_map.contains_key("review.architecture"),
            "Should map review.architecture topic"
        );
        let (hat_id, hat_display) = &hat_map["review.architecture"];
        assert_eq!(hat_id.as_str(), "architecture_reviewer");
        assert_eq!(hat_display, "Architecture Reviewer");

        // Wildcard patterns should be skipped
        assert!(
            !hat_map.contains_key("arch.*"),
            "Wildcard patterns should not be in the map"
        );
    }

    #[test]
    fn test_build_tui_hat_map_empty_registry() {
        // Given: An empty registry (solo mode)
        let config = RalphConfig::default();
        let registry = ralph_core::HatRegistry::from_config(&config);

        // When: Building the TUI hat map
        let hat_map = build_tui_hat_map(&registry);

        // Then: Map should be empty
        assert_eq!(
            hat_map.len(),
            0,
            "Empty registry should produce empty hat map"
        );
    }

    #[test]
    fn test_build_tui_hat_map_skips_wildcard_patterns() {
        // Given: A config with only wildcard patterns
        let yaml = r#"
hats:
  planner:
    name: "Planner"
    triggers: ["task.*", "build.*"]
    publishes: ["plan.done"]
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = ralph_core::HatRegistry::from_config(&config);

        // When: Building the TUI hat map
        let hat_map = build_tui_hat_map(&registry);

        // Then: Map should be empty (all patterns are wildcards)
        assert_eq!(
            hat_map.len(),
            0,
            "Wildcard-only patterns should produce empty hat map"
        );
    }
}