brgr-cli 2.15.13

Let Codex or Claude Code hand work to other coding agents, each in its own Herdr pane: the brgr CLI and Herdr plugin.
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
//! Human-facing terminal output for `brgr run`, `brgr status`, and `brgr doctor`.
//!
//! Printed only when stdout is a terminal and `--json` was not given; a pipe
//! or a file gets the same pretty JSON as before, byte for byte. `status --brief`
//! is the exception: the same text on a terminal and in a pipe, with no ANSI.
//! The fields shown can carry text a worker, a prompt, or a harness manifest
//! supplied, so every one is neutralized for a terminal line before it prints.

use std::{fmt::Write as _, io::IsTerminal};

/// Whether the human form may print: only on a terminal, never under
/// `--json`. The terminal check is injected so tests pass it directly rather
/// than allocating a pty.
pub(crate) fn use_human_output(json_output: bool, stdout_is_terminal: bool) -> bool {
    !json_output && stdout_is_terminal
}

/// The real terminal check call sites use; kept beside [`use_human_output`]
/// so the only difference between a terminal and a test is this one line.
pub(crate) fn stdout_is_terminal() -> bool {
    std::io::stdout().is_terminal()
}

/// Unix seconds now, for elapsed columns. A clock before the epoch reads as
/// zero, which the saturating subtraction below turns into `0s`.
pub(crate) fn unix_now() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |duration| duration.as_secs())
}

/// Characters that steer a terminal or change what a line appears to say:
/// C0/C1 controls (ESC among them), bidi controls and isolates, and the
/// zero-width format characters. Each one becomes a plain space.
fn unsafe_display(character: char) -> bool {
    character.is_control()
        || matches!(
            character,
            '\u{061c}' // Arabic letter mark: bidi control outside the LRM block
                | '\u{200b}'..='\u{200f}' // zero-width space, ZWNJ, ZWJ, LRM, RLM
                | '\u{202a}'..='\u{202e}' // bidi embeddings, overrides, PDF
                | '\u{2060}'..='\u{2064}' // word joiner and invisible operators
                | '\u{2066}'..='\u{2069}' // bidi isolates
                | '\u{feff}' // BOM / zero-width no-break space
        )
}

/// Untrusted text on one terminal line: every control or format character
/// (ESC included) becomes a space, so a worker string can never move the
/// cursor, recolor output, or rewrite what was already printed.
pub(crate) fn safe_text(text: &str) -> String {
    text.chars()
        .map(|character| {
            if unsafe_display(character) {
                ' '
            } else {
                character
            }
        })
        .collect()
}

/// [`safe_text`] cut to `max_chars` on a char boundary; a cut earns an
/// ellipsis.
pub(crate) fn cell(text: &str, max_chars: usize) -> String {
    let text = safe_text(text);
    let mut characters = text.chars();
    let cut: String = characters.by_ref().take(max_chars).collect();
    if characters.next().is_some() {
        format!("{cut}…")
    } else {
        cut
    }
}

/// Seconds since the first attempt started; `None` without a clock. A clock
/// change that puts the start in the future clamps to zero.
pub(crate) fn elapsed_seconds(created_at: Option<u64>, now: u64) -> Option<u64> {
    created_at.map(|started| now.saturating_sub(started))
}

/// The objective head on a brief status line: `safe_text`, one line, bounded.
pub(crate) fn objective_head(text: &str) -> String {
    cell(text, CELL_MAX)
}

/// `12s` / `4m` / `2h` since the first attempt started; `-` without a clock.
/// A clock change can put the start in the future: it clamps to `0s`, the
/// same convention the remaining-time column in `status --tree` uses.
pub(crate) fn elapsed_text(created_at: Option<u64>, now: u64) -> String {
    let Some(started) = created_at else {
        return "-".to_owned();
    };
    let elapsed = now.saturating_sub(started);
    if elapsed < 60 {
        format!("{elapsed}s")
    } else if elapsed < 3_600 {
        format!("{}m", elapsed / 60)
    } else {
        format!("{}h", elapsed / 3_600)
    }
}

/// The first eight characters of a task id, as `brgr status` shows it.
fn short_id(task_id: &str) -> String {
    task_id.chars().take(8).collect()
}

/// One `brgr status` table row, already read from the store.
pub(crate) struct StatusRow {
    pub task_id: String,
    pub state: String,
    pub harness: String,
    /// First attempt start in Unix seconds; `None` until an attempt exists.
    pub created_at: Option<u64>,
    pub objective: String,
}

/// The `brgr status TASK --brief` block: state, last event, result and
/// decision presence.
pub(crate) struct BriefDetail {
    pub state: String,
    pub last_event: Option<String>,
    pub result: bool,
    pub decision: bool,
}

/// The `brgr status TASK` block, already read from the store.
pub(crate) struct TaskDetail {
    pub task_id: String,
    pub state: String,
    pub harness: String,
    pub model: Option<String>,
    pub workspace: String,
    pub created_at: Option<u64>,
    /// Sealed result outcome; absent until a result exists.
    pub outcome: Option<String>,
    /// Questions awaiting an owner answer; absent when there are none.
    pub questions: Option<u64>,
}

/// What `brgr run` reports, from the same receipt the JSON form prints.
pub(crate) struct RunReceipt {
    pub state: String,
    /// The sealed outcome once a foreground run has finished.
    pub outcome: Option<String>,
    pub harness: String,
    pub workspace: String,
    pub task_id: String,
}

/// One item `brgr doctor` needs the owner to look at. `command` is only set
/// when doctor already has a concrete next command; it is not invented.
pub(crate) struct DoctorProblem {
    pub name: String,
    pub reason: String,
    pub command: Option<String>,
}

/// A display cell is capped so one hostile or huge field cannot stretch a
/// line forever.
const CELL_MAX: usize = 60;

/// Widths in characters of the widest cell in each column, headers included.
fn column_widths(widths: &[usize], cells: &[&str]) -> Vec<usize> {
    let mut widths = widths.to_vec();
    for (index, cell) in cells.iter().enumerate() {
        widths[index] = widths[index].max(cell.chars().count());
    }
    widths
}

fn pad(cell: &str, width: usize) -> String {
    let mut padded = cell.to_owned();
    for _ in cell.chars().count()..width {
        padded.push(' ');
    }
    padded
}

/// The `brgr status` list: a header and one line per task, `no tasks` when
/// the list is empty. `now` is injected so elapsed columns are testable.
pub(crate) fn status_table(rows: &[StatusRow], now: u64) -> String {
    if rows.is_empty() {
        return "no tasks\n".to_owned();
    }
    let headers = ["ID", "STATE", "HARNESS", "ELAPSED", "OBJECTIVE"];
    let mut widths = column_widths(&[0; 5], &headers);
    let cells: Vec<[String; 5]> = rows
        .iter()
        .map(|row| {
            [
                short_id(&row.task_id),
                cell(&row.state, CELL_MAX),
                cell(&row.harness, CELL_MAX),
                elapsed_text(row.created_at, now),
                cell(&row.objective, CELL_MAX),
            ]
        })
        .collect();
    for row in &cells {
        widths = column_widths(&widths, &row.each_ref().map(String::as_str));
    }
    let mut output = String::new();
    for (index, header) in headers.iter().enumerate() {
        if index > 0 {
            output.push_str("  ");
        }
        output.push_str(&pad(header, widths[index]));
    }
    output.push('\n');
    for row in &cells {
        for (index, cell) in row.iter().enumerate() {
            if index > 0 {
                output.push_str("  ");
            }
            // The last column is never padded; the table ends with it.
            if index + 1 == row.len() {
                output.push_str(cell);
            } else {
                output.push_str(&pad(cell, widths[index]));
            }
        }
        output.push('\n');
    }
    output
}

/// `brgr status --brief`: one unpadded line per task, full id, no ANSI.
pub(crate) fn brief_table(rows: &[StatusRow], now: u64) -> String {
    if rows.is_empty() {
        return "no tasks\n".to_owned();
    }
    let mut output = String::new();
    for row in rows {
        let _ = writeln!(
            output,
            "{}  {}  {}  {}  {}",
            row.task_id,
            cell(&row.state, CELL_MAX),
            cell(&row.harness, CELL_MAX),
            elapsed_text(row.created_at, now),
            objective_head(&row.objective),
        );
    }
    output
}

/// `brgr status TASK --brief`: a few lines, no ANSI.
pub(crate) fn brief_task(detail: &BriefDetail) -> String {
    let last_event = detail
        .last_event
        .as_deref()
        .map_or_else(|| "-".to_owned(), safe_text);
    format!(
        "state: {}\nlast_event: {}\nresult: {}\ndecision: {}\n",
        safe_text(&detail.state),
        last_event,
        if detail.result { "yes" } else { "no" },
        if detail.decision { "yes" } else { "no" },
    )
}

/// The `brgr status TASK` block: key lines plus where to get the full JSON.
pub(crate) fn task_detail(detail: &TaskDetail, now: u64) -> String {
    let mut output = String::new();
    let mut line = |key: &str, value: &str| {
        let _ = writeln!(output, "{key}: {value}");
    };
    line("task", &detail.task_id);
    line("state", &safe_text(&detail.state));
    line("harness", &safe_text(&detail.harness));
    line(
        "model",
        &detail
            .model
            .as_deref()
            .map_or_else(|| "-".to_owned(), safe_text),
    );
    line("workspace", &safe_text(&detail.workspace));
    line("elapsed", &elapsed_text(detail.created_at, now));
    if let Some(outcome) = &detail.outcome {
        line("result", &safe_text(outcome));
    }
    if let Some(questions) = detail.questions {
        line("questions", &questions.to_string());
    }
    let _ = writeln!(output, "full detail: brgr status {} --json", detail.task_id);
    output
}

/// Prints a `brgr run` receipt in the right form for the current stdout:
/// the human block on a terminal, the JSON envelope everywhere else.
pub(crate) fn print_run_receipt(
    receipt: &serde_json::Value,
    human: &RunReceipt,
    json_output: bool,
) {
    if use_human_output(json_output, stdout_is_terminal()) {
        print!("{}", run_receipt(human));
    } else {
        crate::print_value(receipt, json_output);
    }
}

/// Prints a `brgr doctor` report: the human summary on a terminal, then the
/// JSON envelope a pipe or `--json` already printed.
pub(crate) fn print_doctor(
    value: &serde_json::Value,
    problems: &[DoctorProblem],
    json_output: bool,
) {
    if use_human_output(json_output, stdout_is_terminal()) {
        print!("{}", doctor_summary(problems));
    }
    crate::print_value(value, json_output);
}

/// The `brgr doctor` summary: `ok`, or one line per problem. The first problem
/// is prefixed with `needs_attention:`; later lines are the name and reason.
pub(crate) fn doctor_summary(problems: &[DoctorProblem]) -> String {
    if problems.is_empty() {
        return "ok\n".to_owned();
    }
    let mut output = String::new();
    for (index, problem) in problems.iter().enumerate() {
        if index == 0 {
            output.push_str("needs_attention: ");
        }
        let name = safe_text(&problem.name);
        let reason = safe_text(&problem.reason);
        match problem.command.as_deref() {
            Some(command) => {
                let command = safe_text(command);
                let _ = writeln!(output, "{name} ({reason}: {command})");
            }
            None => {
                let _ = writeln!(output, "{name} ({reason})");
            }
        }
    }
    output
}

/// The `brgr run` receipt: a few key lines, ending with `task: <full id>`.
pub(crate) fn run_receipt(receipt: &RunReceipt) -> String {
    let mut output = String::new();
    let _ = writeln!(output, "state: {}", safe_text(&receipt.state));
    if let Some(outcome) = &receipt.outcome {
        let _ = writeln!(output, "outcome: {}", safe_text(outcome));
    }
    let _ = writeln!(output, "harness: {}", safe_text(&receipt.harness));
    let _ = writeln!(output, "workspace: {}", safe_text(&receipt.workspace));
    // The last line is the machine-detectable id: `task: <full task id>`.
    let _ = writeln!(output, "task: {}", receipt.task_id);
    output
}

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

    fn row(
        task_id: &str,
        state: &str,
        harness: &str,
        created_at: Option<u64>,
        objective: &str,
    ) -> StatusRow {
        StatusRow {
            task_id: task_id.to_owned(),
            state: state.to_owned(),
            harness: harness.to_owned(),
            created_at,
            objective: objective.to_owned(),
        }
    }

    #[test]
    fn human_output_needs_a_terminal_and_no_json_flag() {
        assert!(use_human_output(false, true));
        assert!(!use_human_output(true, true));
        assert!(!use_human_output(false, false));
        assert!(!use_human_output(true, false));
    }

    #[test]
    fn an_empty_status_list_says_no_tasks() {
        assert_eq!(status_table(&[], 1_000), "no tasks\n");
    }

    #[test]
    fn brief_table_is_one_line_per_task_with_the_full_id() {
        let rows = vec![row(
            "2b2c279a-b8e1-43a8-846c-cb8344a301d7",
            "terminal",
            "local.gjc",
            Some(940),
            "Review this change",
        )];
        let text = brief_table(&rows, 1_000);
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines.len(), 1, "{text}");
        assert!(lines[0].starts_with("2b2c279a-b8e1-43a8-846c-cb8344a301d7"));
        assert!(lines[0].contains("terminal"));
        assert!(lines[0].contains("local.gjc"));
        assert!(lines[0].contains("1m"));
        assert!(lines[0].contains("Review this change"));
        assert!(!text.contains('\u{1b}'));
    }

    #[test]
    fn brief_objective_head_strips_control_bidi_and_zero_width() {
        let head = objective_head("ok\n\u{1b}[31m\u{202e}\u{200b}hidden");
        assert!(!head.contains('\n'));
        assert!(!head.contains('\u{1b}'));
        assert!(!head.contains('\u{202e}'));
        assert!(!head.contains('\u{200b}'));
        assert!(head.contains("hidden"), "{head}");
    }

    #[test]
    fn brief_task_lists_state_last_event_result_and_decision() {
        let text = brief_task(&BriefDetail {
            state: "terminal".to_owned(),
            last_event: Some("terminal".to_owned()),
            result: true,
            decision: false,
        });
        assert_eq!(
            text,
            "state: terminal\nlast_event: terminal\nresult: yes\ndecision: no\n"
        );
    }

    #[test]
    fn the_status_table_is_a_header_plus_one_line_per_task() {
        let rows = vec![
            row(
                "2b2c279a-b8e1-43a8-846c-cb8344a301d7",
                "terminal",
                "local.gjc",
                Some(940),
                "Review this change",
            ),
            row(
                "aaaaaaaa-1111-4111-8111-111111111111",
                "running",
                "local.opencode",
                Some(1_000),
                "Second task",
            ),
        ];
        let text = status_table(&rows, 1_000);
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines.len(), 3, "{text}");
        assert!(lines[0].contains("ID"), "{text}");
        assert!(lines[0].contains("STATE"), "{text}");
        assert!(lines[0].contains("HARNESS"), "{text}");
        assert!(lines[0].contains("ELAPSED"), "{text}");
        assert!(lines[0].contains("OBJECTIVE"), "{text}");
        assert_eq!(&lines[1][..8], "2b2c279a");
        assert!(lines[1].contains("terminal"));
        assert!(lines[1].contains("local.gjc"));
        assert!(lines[1].contains("1m"));
        assert!(lines[1].contains("Review this change"));
        assert_eq!(&lines[2][..8], "aaaaaaaa");
        assert!(lines[2].contains("0s"), "{text}");
        assert!(!text.contains("2b2c279a-b8e1-43a8-846c-cb8344a301d7"));
    }

    #[test]
    fn elapsed_is_dash_without_a_clock_then_seconds_minutes_hours() {
        assert_eq!(elapsed_text(None, 1_000), "-");
        assert_eq!(elapsed_text(Some(988), 1_000), "12s");
        assert_eq!(elapsed_text(Some(0), 12), "12s");
        assert_eq!(elapsed_text(Some(760), 1_000), "4m");
        assert_eq!(elapsed_text(Some(0), 7_200), "2h");
        assert_eq!(elapsed_text(Some(0), 86_400), "24h");
        // A clock change can put the start in the future; it clamps, never
        // wraps or reports a negative age.
        assert_eq!(elapsed_text(Some(2_000), 1_000), "0s");
    }

    #[test]
    fn the_objective_cell_cuts_at_sixty_chars_with_an_ellipsis() {
        let exact = "a".repeat(60);
        assert_eq!(cell(&exact, 60), exact);
        let over = "b".repeat(61);
        let shown = cell(&over, 60);
        assert_eq!(shown.chars().count(), 61, "{shown}");
        assert!(shown.ends_with('…'));
        assert_eq!(&shown[..60], &over[..60]);
    }

    #[test]
    fn the_objective_cell_does_not_split_a_multibyte_character() {
        let mut objective = "ê°€".repeat(61);
        let shown = cell(&objective, 60);
        assert_eq!(shown.chars().count(), 61);
        assert_eq!(&shown[..180], &objective[..180]);
        objective.insert(0, 'é');
        let shown = cell(&objective, 60);
        assert_eq!(shown.chars().count(), 61);
        assert!(shown.starts_with('é'));
        assert!(shown.ends_with('…'));
    }

    #[test]
    fn the_arabic_letter_mark_cannot_reorder_a_line() {
        // U+061C ALM is a bidi control in the same class as LRM/RLM: an
        // invisible character that changes how the terminal orders the line.
        let text = safe_text("owner\u{061c}name");
        assert!(!text.contains('\u{061c}'), "{text:?}");
        assert_eq!(text, "owner name");
    }

    #[test]
    fn untrusted_text_loses_every_terminal_control_character() {
        assert_eq!(safe_text("plain"), "plain");
        assert_eq!(safe_text("a\nb\tc"), "a b c");
        assert_eq!(safe_text("ok\u{1b}[31mred"), "ok [31mred");
        assert_eq!(safe_text("\u{1b}[2Jhidden"), " [2Jhidden");
        // Bidi overrides and zero-width format characters are as hostile as
        // ESC on a terminal line.
        assert_eq!(safe_text("a\u{202e}b"), "a b");
        assert_eq!(safe_text("a\u{200b}b"), "a b");
        assert_eq!(safe_text("a\u{2066}b"), "a b");
        assert_eq!(safe_text("a\u{feff}b"), "a b");
        // A C0/C1 sweep leaves only spaces behind.
        let hostile: String = (0_u32..0xa0)
            .filter_map(char::from_u32)
            .filter(|c| c.is_control())
            .collect();
        assert!(safe_text(&hostile).chars().all(|c| c == ' '));
    }

    #[test]
    fn a_cell_is_sanitized_before_it_is_cut() {
        // The escape never reaches the terminal even when the cut lands
        // mid-sequence, and control characters count toward the 60.
        let hostile = "\u{1b}[2J".repeat(20);
        let shown = cell(&hostile, 60);
        assert!(!shown.contains('\u{1b}'));
        assert!(shown.contains("[2J"), "{shown}");
        assert_eq!(shown.chars().count(), 61, "{shown}");
    }

    #[test]
    fn task_detail_lists_the_summary_then_points_at_json() {
        let detail = TaskDetail {
            task_id: "2b2c279a-b8e1-43a8-846c-cb8344a301d7".to_owned(),
            state: "terminal".to_owned(),
            harness: "local.gjc".to_owned(),
            model: Some("swe-1.6".to_owned()),
            workspace: "/tmp/work tree".to_owned(),
            created_at: Some(940),
            outcome: Some("candidate".to_owned()),
            questions: Some(2),
        };
        let text = task_detail(&detail, 1_000);
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines[0], "task: 2b2c279a-b8e1-43a8-846c-cb8344a301d7");
        assert_eq!(lines[1], "state: terminal");
        assert_eq!(lines[2], "harness: local.gjc");
        assert_eq!(lines[3], "model: swe-1.6");
        assert_eq!(lines[4], "workspace: /tmp/work tree");
        assert_eq!(lines[5], "elapsed: 1m");
        assert_eq!(lines[6], "result: candidate");
        assert_eq!(lines[7], "questions: 2");
        assert_eq!(
            lines[8],
            "full detail: brgr status 2b2c279a-b8e1-43a8-846c-cb8344a301d7 --json"
        );
        assert_eq!(lines.len(), 9, "{text}");
    }

    #[test]
    fn task_detail_omits_missing_model_result_and_questions() {
        let detail = TaskDetail {
            task_id: "2b2c279a-b8e1-43a8-846c-cb8344a301d7".to_owned(),
            state: "running".to_owned(),
            harness: "local.gjc".to_owned(),
            model: None,
            workspace: "/tmp/work".to_owned(),
            created_at: None,
            outcome: None,
            questions: None,
        };
        let text = task_detail(&detail, 1_000);
        assert!(text.contains("model: -"));
        assert!(text.contains("elapsed: -"));
        assert!(!text.contains("result:"));
        assert!(!text.contains("questions:"));
        assert!(
            text.ends_with(
                "full detail: brgr status 2b2c279a-b8e1-43a8-846c-cb8344a301d7 --json\n"
            )
        );
    }

    #[test]
    fn task_detail_sanitizes_untrusted_fields() {
        let detail = TaskDetail {
            task_id: "2b2c279a-b8e1-43a8-846c-cb8344a301d7".to_owned(),
            state: "running".to_owned(),
            harness: "local.gjc\u{1b}[31m".to_owned(),
            model: None,
            workspace: "/tmp/work\n/etc".to_owned(),
            created_at: None,
            outcome: None,
            questions: None,
        };
        let text = task_detail(&detail, 1_000);
        assert!(!text.contains('\u{1b}'), "{text:?}");
        assert!(text.contains("harness: local.gjc [31m"));
        assert!(text.contains("workspace: /tmp/work /etc"));
    }

    #[test]
    fn run_receipt_ends_with_the_full_task_id() {
        let receipt = RunReceipt {
            state: "starting".to_owned(),
            outcome: None,
            harness: "local.gjc".to_owned(),
            workspace: "/tmp/work".to_owned(),
            task_id: "2b2c279a-b8e1-43a8-846c-cb8344a301d7".to_owned(),
        };
        let text = run_receipt(&receipt);
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines[0], "state: starting");
        assert_eq!(lines[1], "harness: local.gjc");
        assert_eq!(lines[2], "workspace: /tmp/work");
        assert_eq!(
            lines.last(),
            Some(&"task: 2b2c279a-b8e1-43a8-846c-cb8344a301d7")
        );
    }

    #[test]
    fn run_receipt_shows_a_finished_runs_outcome() {
        let receipt = RunReceipt {
            state: "terminal".to_owned(),
            outcome: Some("candidate".to_owned()),
            harness: "local.gjc".to_owned(),
            workspace: "/tmp/work".to_owned(),
            task_id: "2b2c279a-b8e1-43a8-846c-cb8344a301d7".to_owned(),
        };
        let text = run_receipt(&receipt);
        assert!(text.contains("outcome: candidate"), "{text}");
        assert!(text.ends_with("task: 2b2c279a-b8e1-43a8-846c-cb8344a301d7\n"));
    }

    #[test]
    fn run_receipt_sanitizes_workspace_and_harness() {
        let receipt = RunReceipt {
            state: "starting".to_owned(),
            outcome: None,
            harness: "bad\u{1b}[31m".to_owned(),
            workspace: "/tmp/a\u{202e}b".to_owned(),
            task_id: "2b2c279a-b8e1-43a8-846c-cb8344a301d7".to_owned(),
        };
        let text = run_receipt(&receipt);
        assert!(!text.contains('\u{1b}'), "{text:?}");
        assert!(!text.contains('\u{202e}'), "{text:?}");
        assert!(text.contains("harness: bad [31m"), "{text}");
        assert!(text.contains("workspace: /tmp/a b"), "{text}");
        assert!(text.ends_with("task: 2b2c279a-b8e1-43a8-846c-cb8344a301d7\n"));
    }

    #[test]
    fn doctor_summary_for_one_problem_names_the_item_and_the_fix_command() {
        let text = doctor_summary(&[DoctorProblem {
            name: "local.cline".to_owned(),
            reason: "recertify".to_owned(),
            command: Some("brgr harness recertify local.cline".to_owned()),
        }]);
        let first = text.lines().next().expect("summary has a first line");
        assert_eq!(
            first,
            "needs_attention: local.cline (recertify: brgr harness recertify local.cline)"
        );
        assert_eq!(text.lines().count(), 1, "{text}");
    }

    #[test]
    fn doctor_summary_when_there_is_no_problem_is_ok() {
        assert_eq!(doctor_summary(&[]), "ok\n");
    }

    #[test]
    fn doctor_summary_lists_each_problem_on_its_own_line() {
        let text = doctor_summary(&[
            DoctorProblem {
                name: "local.cline".to_owned(),
                reason: "recertify".to_owned(),
                command: Some("brgr harness recertify local.cline".to_owned()),
            },
            DoctorProblem {
                name: "codex_trace".to_owned(),
                reason: "not verified: codex-cli 0.162.1, verified baseline 0.160".to_owned(),
                command: None,
            },
        ]);
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(
            lines[0],
            "needs_attention: local.cline (recertify: brgr harness recertify local.cline)"
        );
        assert_eq!(
            lines[1],
            "codex_trace (not verified: codex-cli 0.162.1, verified baseline 0.160)"
        );
        assert_eq!(lines.len(), 2, "{text}");
    }

    #[test]
    fn doctor_summary_sanitizes_harness_and_manifest_text() {
        let text = doctor_summary(&[DoctorProblem {
            name: "local.bad\u{1b}[31m".to_owned(),
            reason: "recertify\nnow".to_owned(),
            command: Some("brgr harness recertify local.bad\u{202e}".to_owned()),
        }]);
        assert!(!text.contains('\u{1b}'), "{text:?}");
        assert!(!text.contains('\u{202e}'), "{text:?}");
        assert_eq!(text.lines().count(), 1, "{text}");
        assert!(text.contains("local.bad [31m"), "{text}");
        assert!(text.contains("recertify now"), "{text}");
    }
}