mind-cli 0.43.0

A manager for agent tooling (skills, agents, rules, tools) that melds arbitrary git repos and links items into your agent directories.
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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
//! Terminal output context: color, Unicode glyphs, and the `--json` emitter.

use std::sync::OnceLock;

use serde::Serialize;

use crate::error::{MindError, Result};

static CTX: OnceLock<OutputCtx> = OnceLock::new();

/// Serialize `value` as pretty JSON to stdout (for the `--json` flags). Shared by
/// every verb that emits structured output and by `evolve` (selfupdate.rs).
pub(crate) fn print_json<T: Serialize>(value: &T) -> Result<()> {
    let s = serde_json::to_string_pretty(value).map_err(|e| MindError::json("json output", e))?;
    println!("{s}");
    Ok(())
}

/// Serialize `items` wrapped in a versioned envelope `{"schema": 1, "items": [...]}`.
/// Used by `probe --json` and `recall --json` array outputs (CLI-167).
pub(crate) fn print_json_envelope<T: Serialize>(items: &[T]) -> Result<()> {
    #[derive(Serialize)]
    struct Envelope<'a, T: Serialize> {
        schema: u8,
        items: &'a [T],
    }
    print_json(&Envelope { schema: 1, items })
}

/// Emit one advisory line that is NOT part of a verb's machine-readable result:
/// a `note:`-style aside, a skipped-hook disclosure, a degraded-but-continuing
/// remark. Text mode writes it to stdout, byte for byte the `println!` it
/// replaces; `--json` writes it to stderr instead, so stdout stays exactly one
/// JSON document (CLI-217).
///
/// Use this for anything printed on a path that can also reach `print_json`.
/// A line that is already behind an `if out.json { return print_json(..) }`
/// early return can stay a plain `println!`; one that is not, cannot.
// spec: CLI-217
pub fn note(msg: impl AsRef<str>) {
    let msg = msg.as_ref();
    // spec: PRG-5
    crate::progress::suspend(|| {
        if ctx().json {
            eprintln!("{msg}");
        } else {
            println!("{msg}");
        }
    });
}

/// [`note`] with the context's warn marker (`!`) prefixed: the same routing
/// (stdout in text mode, stderr under `--json`, CLI-217) for a line that
/// reports something the user should act on but that did not stop the verb.
// spec: CLI-217
pub fn warn(msg: impl AsRef<str>) {
    let out = ctx();
    note(format!("{} {}", out.warn(), msg.as_ref()));
}

/// Whether the catalog scan's degraded-state warnings are muted (DSC-102).
static SCAN_QUIET: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Mute (or unmute) the catalog scan's degraded-state warnings for this process.
///
/// The TUI sets this for as long as it owns the terminal. Unlike [`set_ctx`],
/// which resolves once from the global flags, this is a live toggle: the scan
/// runs on the TUI's ~1s poll tick (TUI-15), so a warning about a persistent
/// condition (a linked source whose directory is gone, an item manifest that
/// will not parse) is not a one-time notice there but a line written into the
/// alternate screen every second.
///
/// spec: DSC-102
pub fn set_scan_quiet(quiet: bool) {
    SCAN_QUIET.store(quiet, std::sync::atomic::Ordering::Relaxed);
}

/// Whether [`set_scan_quiet`] is currently in effect.
pub fn scan_quiet() -> bool {
    SCAN_QUIET.load(std::sync::atomic::Ordering::Relaxed)
}

/// Emit one degraded-state warning from the catalog scan, unless muted by
/// [`set_scan_quiet`]. `msg` is already composed and sanitized by the caller.
///
/// spec: DSC-102
pub fn scan_warn(msg: impl AsRef<str>) {
    if scan_quiet() {
        return;
    }
    // spec: PRG-5
    crate::progress::suspend(|| eprintln!("{}", msg.as_ref()));
}

/// Install the process-wide output context. Call once, early in `main`, after
/// parsing the global flags. A second call is ignored.
pub fn set_ctx(ctx: OutputCtx) {
    let _ = CTX.set(ctx);
}

/// The process-wide output context. Defaults to plain (no color, no Unicode,
/// json=false) when `set_ctx` was never called — the safe default for unit/
/// integration tests and any non-main caller.
pub fn ctx() -> OutputCtx {
    CTX.get().copied().unwrap_or(OutputCtx {
        json: false,
        color: false,
        unicode: false,
        tui_unicode: false,
        verbose: false,
    })
}

/// Output capabilities resolved once from the global flags + environment.
#[derive(Clone, Copy)]
pub struct OutputCtx {
    pub json: bool,
    pub color: bool,
    pub unicode: bool,
    /// The TUI's Unicode-glyph capability (TUI-65). Unlike `unicode` (the CLI
    /// gate, CLI-151, which couples color and glyphs), this does NOT fold in
    /// `NO_COLOR`: in the TUI, `NO_COLOR` disables only color and the Unicode
    /// markers stay. Only a non-UTF-8 locale, `--ascii`, `--json`, or a non-TTY
    /// stdout force the ASCII glyph fallback.
    pub tui_unicode: bool,
    pub verbose: bool,
}

impl OutputCtx {
    /// Build from the global `--json`/`--ascii`/`--verbose` flags plus the environment and TTY.
    pub fn detect(json: bool, ascii: bool, verbose: bool) -> Self {
        use std::io::IsTerminal;
        let is_tty = std::io::stdout().is_terminal();
        let no_color = std::env::var_os("NO_COLOR").is_some();
        let utf8_locale = detect_utf8_locale();
        Self {
            verbose,
            ..Self::compute(json, ascii, is_tty, no_color, utf8_locale)
        }
    }

    /// Pure, fully-injected core of `detect` so the gate is unit-testable without
    /// real env/tty. `detect` is just
    /// `compute(json, ascii, stdout_is_tty, no_color_set, utf8_locale)`.
    pub fn compute(
        json: bool,
        ascii: bool,
        is_tty: bool,
        no_color: bool,
        utf8_locale: bool,
    ) -> Self {
        // color and unicode are true ONLY when ALL of: is_tty AND utf8_locale AND NOT
        // no_color AND NOT json AND NOT ascii.
        let rich = is_tty && utf8_locale && !no_color && !json && !ascii;
        Self {
            json,
            color: rich,
            unicode: rich,
            // spec: TUI-65 - the TUI glyph gate omits no_color: NO_COLOR must
            // drop color only, never the Unicode markers.
            tui_unicode: is_tty && utf8_locale && !json && !ascii,
            verbose: false,
        }
    }

    // --- Semantic status markers ---

    /// Installed / success marker.  Unicode "✓" (green) or ASCII "+".
    pub fn ok(&self) -> String {
        if self.unicode {
            self.green("✓")
        } else {
            "+".to_string()
        }
    }

    /// Installed-but-stale marker.  An installed item whose source has moved
    /// ahead -- between [`ok`](Self::ok) (installed and current) and
    /// [`available`](Self::available) (not installed). Unicode "↑" (yellow,
    /// signalling an upgrade is available) or ASCII "^".
    pub fn stale(&self) -> String {
        if self.unicode {
            self.yellow("↑")
        } else {
            "^".to_string()
        }
    }

    /// Available / inactive marker.  Unicode "○" (dim) or ASCII "-".
    pub fn available(&self) -> String {
        if self.unicode {
            self.dim("○")
        } else {
            "-".to_string()
        }
    }

    /// Drift / removed / warn marker.  Unicode "!" (yellow) or ASCII "!".
    pub fn warn(&self) -> String {
        if self.unicode {
            self.yellow("!")
        } else {
            "!".to_string()
        }
    }

    /// Error marker.  Unicode "✗" (red) or ASCII "x".
    pub fn err(&self) -> String {
        if self.unicode {
            self.red("✗")
        } else {
            "x".to_string()
        }
    }

    /// Source / section bullet.  Unicode "●" or ASCII "*".
    pub fn bullet(&self) -> String {
        if self.unicode {
            "●".to_string()
        } else {
            "*".to_string()
        }
    }

    // --- Color wrappers ---

    /// Wrap `s` in green SGR codes, or return `s` unchanged when color is off.
    pub fn green(&self, s: &str) -> String {
        if self.color {
            format!("\x1b[32m{s}\x1b[0m")
        } else {
            s.to_string()
        }
    }

    /// Wrap `s` in yellow SGR codes, or return `s` unchanged when color is off.
    pub fn yellow(&self, s: &str) -> String {
        if self.color {
            format!("\x1b[33m{s}\x1b[0m")
        } else {
            s.to_string()
        }
    }

    /// Wrap `s` in red SGR codes, or return `s` unchanged when color is off.
    pub fn red(&self, s: &str) -> String {
        if self.color {
            format!("\x1b[31m{s}\x1b[0m")
        } else {
            s.to_string()
        }
    }

    /// Wrap `s` in dim SGR codes, or return `s` unchanged when color is off.
    pub fn dim(&self, s: &str) -> String {
        if self.color {
            format!("\x1b[2m{s}\x1b[0m")
        } else {
            s.to_string()
        }
    }

    /// Wrap `s` in bold SGR codes, or return `s` unchanged when color is off.
    pub fn bold(&self, s: &str) -> String {
        if self.color {
            format!("\x1b[1m{s}\x1b[0m")
        } else {
            s.to_string()
        }
    }

    /// Print rows as aligned columns.
    ///
    /// Every column except the last is left-padded to the widest VISIBLE width in
    /// that column; the last column is left as-is; trailing empty cells are trimmed.
    /// Width is measured ignoring ANSI SGR escapes via [`visible_width`].
    /// Columns are separated by two spaces.
    ///
    /// DSC-95: each cell is sanitized (`crate::sanitize::strip_ansi`) before
    /// the line is composed, not after. A cell built from a source-controlled
    /// name can carry an unterminated ANSI/OSC sequence; `strip_ansi_escapes`
    /// is a state machine, so sanitizing the already-composed line would let
    /// that sequence consume whatever a caller appended after it (a role tag,
    /// a status marker) instead of just the hostile cell. Sanitizing per cell
    /// keeps the damage contained to the cell that carried it. This is a
    /// single chokepoint: every `print_rows` caller is covered without having
    /// to sanitize at each call site.
    // spec: CLI-232 DSC-95
    pub fn print_rows(&self, rows: &[Vec<String>]) {
        let Some(ncols) = rows.iter().map(Vec::len).max() else {
            return;
        };
        let rows: Vec<Vec<String>> = rows
            .iter()
            .map(|row| {
                row.iter()
                    .map(|cell| crate::sanitize::strip_ansi(cell))
                    .collect()
            })
            .collect();
        let mut widths = vec![0usize; ncols];
        for row in &rows {
            for (i, cell) in row.iter().enumerate() {
                if i + 1 < ncols {
                    widths[i] = widths[i].max(visible_width(cell));
                }
            }
        }
        for row in &rows {
            let mut line = String::new();
            for (i, cell) in row.iter().enumerate() {
                if i > 0 {
                    line.push_str("  ");
                }
                if i + 1 < ncols {
                    let pad = widths[i].saturating_sub(visible_width(cell));
                    line.push_str(cell);
                    line.extend(std::iter::repeat_n(' ', pad));
                } else {
                    line.push_str(cell);
                }
            }
            println!("{}", line.trim_end());
        }
    }
}

/// Visible (display) width of `s`, ignoring ANSI SGR escape sequences like
/// `"\x1b[32m"` ... `"\x1b[0m"`. Uses `unicode-width` for each surviving char's
/// terminal column width (0 for combining marks, 1 for most, 2 for wide
/// CJK/emoji), not a raw char count, so a row containing wide characters
/// aligns with plain-ASCII rows instead of coming up short by however many
/// double-width characters it has.
pub fn visible_width(s: &str) -> usize {
    use unicode_width::UnicodeWidthChar;
    let mut count = 0usize;
    let mut chars = s.chars();
    while let Some(c) = chars.next() {
        if c == '\x1b' {
            // Consume the rest of the CSI/SGR sequence: '[' then digits/semicolons
            // then a single letter terminator (e.g. 'm').
            if chars.next() == Some('[') {
                for c2 in chars.by_ref() {
                    if c2.is_ascii_alphabetic() {
                        break;
                    }
                }
            }
            // If the char after ESC is not '[', we consumed just ESC and one unknown
            // char; we don't count either but we already advanced past them.
        } else {
            count += c.width().unwrap_or(0);
        }
    }
    count
}

/// The width plain output wraps to: `COLUMNS` when set to a number, else the
/// terminal's width when stdout is one, else 80. Never below 40, so a tiny or
/// bogus value still leaves room for a prefix and a word.
pub fn term_width() -> usize {
    use std::io::IsTerminal;
    let env = std::env::var("COLUMNS")
        .ok()
        .and_then(|v| v.trim().parse::<usize>().ok());
    let tty = || {
        std::io::stdout()
            .is_terminal()
            .then(|| crossterm::terminal::size().ok())
            .flatten()
            .map(|(cols, _)| usize::from(cols))
    };
    env.or_else(tty).unwrap_or(80).max(40)
}

/// Lay `tokens` out on lines no wider than `width`, joined by single spaces:
/// the first line starts with `first`, each later one with `cont` (a hanging
/// indent). A line breaks only between tokens, so a token wider than the room
/// left overflows its own line rather than being split.
pub fn wrap_tokens<S: AsRef<str>>(
    tokens: &[S],
    first: &str,
    cont: &str,
    width: usize,
) -> Vec<String> {
    let mut lines = Vec::new();
    let mut line = first.to_string();
    let mut empty = true;
    for token in tokens {
        let token = token.as_ref();
        if !empty && visible_width(&line) + 1 + visible_width(token) > width {
            lines.push(std::mem::replace(&mut line, cont.to_string()));
            empty = true;
        }
        if !empty {
            line.push(' ');
        }
        line.push_str(token);
        empty = false;
    }
    lines.push(line);
    lines
}

/// Detect whether the active locale advertises UTF-8.
///
/// Checks `LC_ALL`, `LC_CTYPE`, `LANG` in that order (first set wins).
/// Returns `false` when none is set (conservative ASCII default).
pub(crate) fn detect_utf8_locale() -> bool {
    for var in &["LC_ALL", "LC_CTYPE", "LANG"] {
        if let Ok(val) = std::env::var(var)
            && !val.is_empty()
        {
            let lower = val.to_lowercase();
            return lower.contains("utf-8") || lower.contains("utf8");
        }
    }
    false
}

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

    // --- helpers ---

    fn plain() -> OutputCtx {
        OutputCtx::compute(false, false, false, false, false)
    }

    fn rich() -> OutputCtx {
        OutputCtx::compute(false, false, true, false, true)
    }

    // ==========================================================================
    // compute truth table
    // ==========================================================================

    /// All five inputs true -> color and unicode are true.
    #[test]
    fn compute_all_true_yields_rich() {
        let ctx = OutputCtx::compute(false, false, true, false, true);
        assert!(ctx.color, "color should be true when all conditions met");
        assert!(
            ctx.unicode,
            "unicode should be true when all conditions met"
        );
        assert!(!ctx.json);
    }

    /// json=true disables color and unicode even when everything else permits it.
    #[test]
    fn compute_json_disables_color() {
        let ctx = OutputCtx::compute(true, false, true, false, true);
        assert!(!ctx.color, "json disables color");
        assert!(!ctx.unicode, "json disables unicode");
        assert!(ctx.json);
    }

    /// ascii=true disables color and unicode even when everything else permits it.
    #[test]
    fn compute_ascii_disables_color() {
        let ctx = OutputCtx::compute(false, true, true, false, true);
        assert!(!ctx.color, "ascii flag disables color");
        assert!(!ctx.unicode, "ascii flag disables unicode");
    }

    /// is_tty=false disables color and unicode.
    #[test]
    fn compute_non_tty_disables_color() {
        let ctx = OutputCtx::compute(false, false, false, false, true);
        assert!(!ctx.color, "non-tty disables color");
        assert!(!ctx.unicode, "non-tty disables unicode");
    }

    /// no_color=true disables color and unicode.
    #[test]
    fn compute_no_color_env_disables_color() {
        let ctx = OutputCtx::compute(false, false, true, true, true);
        assert!(!ctx.color, "NO_COLOR disables color");
        assert!(!ctx.unicode, "NO_COLOR disables unicode");
    }

    /// utf8_locale=false disables color and unicode.
    #[test]
    fn compute_non_utf8_locale_disables_color() {
        let ctx = OutputCtx::compute(false, false, true, false, false);
        assert!(!ctx.color, "non-utf8 locale disables color");
        assert!(!ctx.unicode, "non-utf8 locale disables unicode");
    }

    /// NO_COLOR keeps the TUI glyph capability: `tui_unicode` stays true when
    /// only `no_color` is hostile, while the CLI gate (`color`/`unicode`) goes
    /// off. This is the wiring the TUI reads for its markers, so it pins that
    /// `NO_COLOR=1 mind probe` renders monochrome Unicode, not ASCII fallback.
    // spec: TUI-65
    #[test]
    fn compute_no_color_keeps_tui_unicode() {
        let ctx = OutputCtx::compute(false, false, true, true, true);
        assert!(!ctx.color, "NO_COLOR disables color");
        assert!(!ctx.unicode, "NO_COLOR disables the CLI unicode gate");
        assert!(
            ctx.tui_unicode,
            "NO_COLOR must NOT disable the TUI glyph capability (TUI-65)"
        );
    }

    /// Each genuinely Unicode-hostile signal forces the TUI glyph fallback.
    // spec: TUI-65
    #[test]
    fn compute_tui_unicode_off_for_hostile_modes() {
        // json, ascii, non-tty, non-utf8 locale.
        for (json, ascii, tty, utf8) in [
            (true, false, true, true),
            (false, true, true, true),
            (false, false, false, true),
            (false, false, true, false),
        ] {
            let ctx = OutputCtx::compute(json, ascii, tty, false, utf8);
            assert!(
                !ctx.tui_unicode,
                "tui_unicode must be false (json={json} ascii={ascii} tty={tty} utf8={utf8})"
            );
        }
    }

    /// color and unicode are always equal (same conjunction). This is the CLI
    /// contract (CLI-151 couples them); the TUI's glyph capability is the
    /// separate `tui_unicode` field, which deliberately diverges under
    /// NO_COLOR (TUI-65).
    #[test]
    fn compute_color_and_unicode_always_equal() {
        for json in [false, true] {
            for ascii in [false, true] {
                for tty in [false, true] {
                    for no_color in [false, true] {
                        for utf8 in [false, true] {
                            let ctx = OutputCtx::compute(json, ascii, tty, no_color, utf8);
                            assert_eq!(
                                ctx.color, ctx.unicode,
                                "color and unicode must be equal \
                                 (json={json} ascii={ascii} tty={tty} no_color={no_color} utf8={utf8})"
                            );
                        }
                    }
                }
            }
        }
    }

    // ==========================================================================
    // Glyph selection
    // ==========================================================================

    #[test]
    fn ok_unicode_contains_checkmark_and_ansi() {
        let s = rich().ok();
        assert!(s.contains('✓'), "ok() unicode should contain ✓, got {s:?}");
        assert!(
            s.contains('\x1b'),
            "ok() unicode should contain ANSI code, got {s:?}"
        );
    }

    #[test]
    fn ok_ascii_is_plus_no_ansi() {
        let s = plain().ok();
        assert_eq!(s, "+", "ok() ascii should be '+', got {s:?}");
        assert!(!s.contains('\x1b'), "ok() ascii must not contain ANSI code");
    }

    #[test]
    fn stale_unicode_contains_uparrow_and_ansi() {
        // spec: CLI-155
        let s = rich().stale();
        assert!(
            s.contains('↑'),
            "stale() unicode should contain ↑, got {s:?}"
        );
        assert!(
            s.contains('\x1b'),
            "stale() unicode should contain ANSI code, got {s:?}"
        );
    }

    #[test]
    fn stale_ascii_is_caret_no_ansi() {
        // spec: CLI-155
        let s = plain().stale();
        assert_eq!(s, "^", "stale() ascii should be '^', got {s:?}");
        assert!(
            !s.contains('\x1b'),
            "stale() ascii must not contain ANSI code"
        );
    }

    #[test]
    fn available_unicode_contains_circle_and_ansi() {
        let s = rich().available();
        assert!(
            s.contains('○'),
            "available() unicode should contain ○, got {s:?}"
        );
        assert!(
            s.contains('\x1b'),
            "available() unicode should contain ANSI code"
        );
    }

    #[test]
    fn available_ascii_is_dash_no_ansi() {
        let s = plain().available();
        assert_eq!(s, "-", "available() ascii should be '-', got {s:?}");
        assert!(!s.contains('\x1b'));
    }

    #[test]
    fn warn_unicode_contains_bang_and_ansi() {
        let s = rich().warn();
        assert!(s.contains('!'), "warn() unicode should contain '!'");
        assert!(
            s.contains('\x1b'),
            "warn() unicode should contain ANSI code"
        );
    }

    #[test]
    fn warn_ascii_is_bang_no_ansi() {
        let s = plain().warn();
        assert_eq!(s, "!", "warn() ascii should be '!'");
        assert!(!s.contains('\x1b'));
    }

    #[test]
    fn err_unicode_contains_cross_and_ansi() {
        let s = rich().err();
        assert!(s.contains('✗'), "err() unicode should contain ✗, got {s:?}");
        assert!(s.contains('\x1b'), "err() unicode should contain ANSI code");
    }

    #[test]
    fn err_ascii_is_x_no_ansi() {
        let s = plain().err();
        assert_eq!(s, "x", "err() ascii should be 'x', got {s:?}");
        assert!(!s.contains('\x1b'));
    }

    #[test]
    fn bullet_unicode_is_filled_circle_no_ansi_wrap() {
        let s = rich().bullet();
        assert!(
            s.contains('●'),
            "bullet() unicode should contain ●, got {s:?}"
        );
        // bullet() is not color-wrapped; it has no SGR codes
        assert!(
            !s.contains('\x1b'),
            "bullet() should not contain ANSI codes"
        );
    }

    #[test]
    fn bullet_ascii_is_star_no_ansi() {
        let s = plain().bullet();
        assert_eq!(s, "*", "bullet() ascii should be '*', got {s:?}");
        assert!(!s.contains('\x1b'));
    }

    // ==========================================================================
    // Color wrappers
    // ==========================================================================

    #[test]
    fn color_wrappers_are_noop_when_color_off() {
        let ctx = plain();
        assert_eq!(ctx.green("hi"), "hi");
        assert_eq!(ctx.yellow("hi"), "hi");
        assert_eq!(ctx.red("hi"), "hi");
        assert_eq!(ctx.dim("hi"), "hi");
        assert_eq!(ctx.bold("hi"), "hi");
    }

    #[test]
    fn color_wrappers_wrap_and_reset_when_color_on() {
        let ctx = rich();
        let g = ctx.green("hi");
        assert!(g.starts_with("\x1b[32m"), "green should start with SGR 32");
        assert!(g.ends_with("\x1b[0m"), "green should end with reset");
        assert!(g.contains("hi"), "green should contain the text");

        let y = ctx.yellow("hi");
        assert!(y.starts_with("\x1b[33m"), "yellow should start with SGR 33");
        assert!(y.ends_with("\x1b[0m"));

        let r = ctx.red("hi");
        assert!(r.starts_with("\x1b[31m"), "red should start with SGR 31");
        assert!(r.ends_with("\x1b[0m"));

        let d = ctx.dim("hi");
        assert!(d.starts_with("\x1b[2m"), "dim should start with SGR 2");
        assert!(d.ends_with("\x1b[0m"));

        let b = ctx.bold("hi");
        assert!(b.starts_with("\x1b[1m"), "bold should start with SGR 1");
        assert!(b.ends_with("\x1b[0m"));
    }

    // ==========================================================================
    // visible_width
    // ==========================================================================

    // wrap_tokens

    #[test]
    fn wrap_tokens_keeps_a_short_list_on_one_line() {
        let lines = wrap_tokens(&["a,", "b,", "c"], "members: ", "         ", 40);
        assert_eq!(lines, vec!["members: a, b, c"]);
    }

    #[test]
    fn wrap_tokens_breaks_between_tokens_with_a_hanging_indent() {
        let tokens = [
            "skill:review,",
            "rule:style,",
            "agent:planner,",
            "skill:deploy",
        ];
        let lines = wrap_tokens(&tokens, "  m: ", "     ", 30);
        assert_eq!(
            lines,
            vec![
                "  m: skill:review, rule:style,",
                "     agent:planner,",
                "     skill:deploy",
            ]
        );
        assert!(lines.iter().all(|l| visible_width(l) <= 30), "{lines:?}");
    }

    #[test]
    fn wrap_tokens_lets_an_oversized_token_overflow_its_own_line() {
        let long = "x".repeat(50);
        let lines = wrap_tokens(&["a", long.as_str(), "b"], "> ", "  ", 20);
        assert_eq!(
            lines,
            vec!["> a".to_string(), format!("  {long}"), "  b".into()]
        );
    }

    #[test]
    fn wrap_tokens_with_no_tokens_is_the_bare_prefix() {
        let lines = wrap_tokens::<&str>(&[], "members: ", "  ", 40);
        assert_eq!(lines, vec!["members: "]);
    }

    #[test]
    fn visible_width_plain_string_counts_chars() {
        assert_eq!(visible_width("hello"), 5);
        assert_eq!(visible_width(""), 0);
        assert_eq!(visible_width("abc"), 3);
    }

    #[test]
    fn visible_width_colored_equals_plain_width() {
        // A colored "hello" (5 chars) must measure 5, not count the ANSI bytes.
        let colored = "\x1b[32mhello\x1b[0m";
        assert_eq!(
            visible_width(colored),
            5,
            "ANSI codes must not count toward width"
        );
    }

    #[test]
    fn visible_width_multibyte_counts_chars_not_bytes() {
        // "✓" is 3 bytes in UTF-8 but 1 char.
        assert_eq!(visible_width("✓"), 1);
        // "●" is also 3 bytes.
        assert_eq!(visible_width("●"), 1);
        // Combined with ANSI.
        let s = "\x1b[32m✓\x1b[0m";
        assert_eq!(
            visible_width(s),
            1,
            "multi-byte char inside ANSI must count as 1"
        );
    }

    #[test]
    fn visible_width_strips_multiple_escapes() {
        // A string with several SGR codes interspersed.
        let s = "\x1b[1mhello\x1b[0m \x1b[31mworld\x1b[0m";
        // "hello world" = 11 chars (including the space).
        assert_eq!(visible_width(s), 11);
    }

    #[test]
    fn visible_width_counts_wide_cjk_chars_as_two_columns() {
        // A CJK character occupies two terminal columns, not one -- unlike a raw
        // char count (the pre-unicode-width behavior), which would misalign a row
        // containing CJK/emoji against a plain-ASCII row of the same char count.
        assert_eq!(
            visible_width("\u{4e2d}"),
            2,
            "one wide CJK char is 2 columns"
        );
        assert_eq!(
            visible_width("\u{4e2d}\u{6587}"),
            4,
            "two wide CJK chars are 4 columns"
        );
        // Mixed ASCII + wide: 3 narrow (1 each) + 1 wide (2) = 5.
        assert_eq!(visible_width("ab\u{4e2d}c"), 5);
    }

    // ==========================================================================
    // print_rows alignment
    // ==========================================================================

    /// Collect print_rows output by capturing stdout via a Vec<u8> pipe.
    /// Since print_rows uses println! we test alignment logic separately.
    ///
    /// We verify the alignment by inspecting the widths the algorithm would
    /// compute for given rows, mirroring the internal logic.
    fn compute_column_widths(rows: &[Vec<String>]) -> Vec<usize> {
        let Some(ncols) = rows.iter().map(Vec::len).max() else {
            return vec![];
        };
        let mut widths = vec![0usize; ncols];
        for row in rows {
            for (i, cell) in row.iter().enumerate() {
                if i + 1 < ncols {
                    widths[i] = widths[i].max(visible_width(cell));
                }
            }
        }
        widths
    }

    #[test]
    fn print_rows_alignment_plain_cells() {
        let rows = vec![
            vec!["a".to_string(), "bc".to_string(), "desc1".to_string()],
            vec!["xyz".to_string(), "d".to_string(), "desc2".to_string()],
        ];
        let widths = compute_column_widths(&rows);
        // col 0: max("a"=1, "xyz"=3) = 3
        assert_eq!(widths[0], 3, "col 0 width should be 3");
        // col 1: max("bc"=2, "d"=1) = 2
        assert_eq!(widths[1], 2, "col 1 width should be 2");
        // col 2 (last): not padded, so width stays 0
        assert_eq!(widths[2], 0, "last col not padded");
    }

    #[test]
    fn print_rows_colored_cell_aligns_same_as_uncolored() {
        // A colored "+  " should have the same visible width as plain "+" when
        // computing column widths.
        let colored_plus = "\x1b[32m+\x1b[0m".to_string();
        let plain_plus = "+".to_string();

        let rows_colored = vec![
            vec![
                colored_plus.clone(),
                "long-name".to_string(),
                "desc".to_string(),
            ],
            vec!["x".to_string(), "n".to_string(), "desc2".to_string()],
        ];
        let rows_plain = vec![
            vec![
                plain_plus.clone(),
                "long-name".to_string(),
                "desc".to_string(),
            ],
            vec!["x".to_string(), "n".to_string(), "desc2".to_string()],
        ];

        let widths_colored = compute_column_widths(&rows_colored);
        let widths_plain = compute_column_widths(&rows_plain);

        assert_eq!(
            widths_colored[0], widths_plain[0],
            "colored and plain cells in the same column must produce the same width: \
             colored={} plain={}",
            widths_colored[0], widths_plain[0]
        );
    }

    #[test]
    fn print_rows_single_column_no_padding() {
        // A single-column table: the one column is the last column, so no
        // alignment padding is computed.
        let rows = vec![vec!["hello".to_string()], vec!["world!".to_string()]];
        let widths = compute_column_widths(&rows);
        // Only one column, it is the last column, so its width slot stays 0.
        assert_eq!(widths[0], 0);
    }

    #[test]
    fn print_rows_empty_rows_no_panic() {
        let ctx = plain();
        // Must not panic.
        ctx.print_rows(&[]);
        ctx.print_rows(&[vec![]]);
    }

    // ==========================================================================
    // print_rows sanitization (DSC-95 / CLI-232)
    // ==========================================================================

    /// `print_rows` must sanitize each cell BEFORE composing the line, not
    /// after: `strip_ansi_escapes::strip` is a state machine, and an
    /// unterminated OSC sequence (`\x1b]` with no terminator) in one cell
    /// would consume the rest of an already-composed line -- including a
    /// later cell in the same row -- if sanitization ran post-composition.
    /// This re-execs the test binary (println! output can't be captured
    /// in-process) to prove the later cell survives and the escape is gone.
    // spec: CLI-232 DSC-95
    #[test]
    fn print_rows_sanitizes_each_cell_before_composing_the_line() {
        const ENV: &str = "MIND_TEST_PRINT_ROWS_HOSTILE_CELL";
        const SURVIVOR: &str = "ZZ-PRINT-ROWS-SURVIVOR-ZZ";

        if std::env::var_os(ENV).is_some() {
            // Child role: print one row whose first cell carries an
            // unterminated OSC sequence, and whose second (last) cell is the
            // survivor marker. If sanitization ran on the composed line
            // instead of per-cell, the OSC's runaway consumption would eat
            // the survivor marker too.
            plain().print_rows(&[vec!["evil\x1b]".to_string(), SURVIVOR.to_string()]]);
            std::process::exit(0);
        }

        let exe = std::env::current_exe().expect("path of the running test binary");
        let out = std::process::Command::new(exe)
            .args([
                "--exact",
                "render::tests::print_rows_sanitizes_each_cell_before_composing_the_line",
                "--nocapture",
                "--test-threads=1",
            ])
            .env(ENV, "1")
            .output()
            .expect("re-exec the test binary");
        let stdout = String::from_utf8_lossy(&out.stdout);
        assert!(
            !stdout.contains('\x1b'),
            "the escape sequence must not reach the terminal: {stdout:?}"
        );
        assert!(
            stdout.contains(SURVIVOR),
            "the second cell must survive sanitizing the first cell in \
             isolation, not disappear because sanitization ran on the \
             composed line: {stdout:?}"
        );
        assert!(
            stdout.contains("evil"),
            "the non-hostile prefix of the first cell must still be printed \
             (this is not a fail-closed/erase-the-item response): {stdout:?}"
        );
    }

    // ==========================================================================
    // verbose orthogonality (CLI-162)
    // ==========================================================================

    /// `detect` propagates the `verbose` argument into the context verbatim.
    // spec: CLI-162
    #[test]
    fn detect_propagates_verbose_flag() {
        assert!(
            OutputCtx::detect(false, false, true).verbose,
            "detect(_, _, true) must yield verbose=true"
        );
        assert!(
            !OutputCtx::detect(false, false, false).verbose,
            "detect(_, _, false) must yield verbose=false"
        );
    }

    /// `verbose` is orthogonal to the color/unicode gate: toggling it does not
    /// change color or unicode for otherwise-identical inputs. Whatever the
    /// ambient TTY/locale/env resolves to, both contexts must agree on color and
    /// unicode; only `verbose` differs.
    // spec: CLI-162
    #[test]
    fn verbose_does_not_affect_color_or_unicode() {
        for json in [false, true] {
            for ascii in [false, true] {
                let off = OutputCtx::detect(json, ascii, false);
                let on = OutputCtx::detect(json, ascii, true);
                assert_eq!(
                    off.color, on.color,
                    "verbose must not change color (json={json} ascii={ascii})"
                );
                assert_eq!(
                    off.unicode, on.unicode,
                    "verbose must not change unicode (json={json} ascii={ascii})"
                );
                assert_eq!(
                    off.json, on.json,
                    "verbose must not change json (json={json} ascii={ascii})"
                );
                assert!(!off.verbose, "verbose=false expected");
                assert!(on.verbose, "verbose=true expected");
            }
        }
    }

    /// `compute` always leaves `verbose` false (it is set only by `detect`).
    // spec: CLI-162
    #[test]
    fn compute_leaves_verbose_false() {
        for tty in [false, true] {
            for utf8 in [false, true] {
                let ctx = OutputCtx::compute(false, false, tty, false, utf8);
                assert!(
                    !ctx.verbose,
                    "compute must not set verbose (tty={tty} utf8={utf8})"
                );
            }
        }
    }

    // ==========================================================================
    // Process-global ctx / set_ctx
    // ==========================================================================

    /// Before set_ctx is ever called (or when the OnceLock has not yet been
    /// populated in this process), ctx() returns the plain default.
    ///
    /// Note on set-once semantics: OnceLock is set exactly once per process.
    /// Tests share the process, so only the first set_ctx call wins. We keep
    /// the default-check test separate from the set-and-read test and accept
    /// that only one ordering is observable in a given run; the Rust test
    /// harness may run tests in any order. The assertions below are written so
    /// they hold regardless of which test runs first:
    ///   - ctx_default_is_plain checks the plain fallback value, which is the
    ///     same value that would be returned if set_ctx was never called AND if
    ///     set_ctx was called with a plain context.
    ///   - ctx_set_then_get checks that after set_ctx the returned value
    ///     reflects whatever was set (even if an earlier test already set it,
    ///     because the harness cannot call set_ctx with a different value once
    ///     it is already set; we use a plain ctx so both orderings are consistent).
    #[test]
    fn ctx_default_is_plain() {
        // Whether or not set_ctx has been called, ctx() must never panic and
        // must return a valid OutputCtx.  The plain default has all fields false.
        // If set_ctx was already called with a non-plain value in this process
        // run, this test would observe that value instead — but set_ctx is only
        // called from tests here, and all calls below use the plain context, so
        // the observed value will always have color=false, unicode=false,
        // json=false regardless of ordering.
        let c = ctx();
        assert!(!c.color, "default/plain ctx must have color=false");
        assert!(!c.unicode, "default/plain ctx must have unicode=false");
        assert!(!c.json, "default/plain ctx must have json=false");
    }

    // ==========================================================================
    // CLI-217: note / warn routing
    // ==========================================================================

    /// Turns a re-exec of this test binary into a one-shot emitter for the
    /// routing checks below. Value is `text` or `json`.
    const ROUTING_MODE_ENV: &str = "MIND_TEST_RENDER_ROUTING_MODE";
    /// Sentinels chosen so they cannot collide with anything libtest itself
    /// prints (the test name, `running 1 test`, `ok`).
    const NOTE_SENTINEL: &str = "ZZ-RENDER-ROUTING-NOTE-ZZ";
    const WARN_SENTINEL: &str = "ZZ-RENDER-ROUTING-WARN-ZZ";
    const ROUTING_TEST: &str = "render::tests::note_and_warn_route_by_output_mode";

    /// Re-run this binary filtered to the routing test with `mode` installed,
    /// and return its (stdout, stderr).
    fn routing_probe(mode: &str) -> (String, String) {
        let exe = std::env::current_exe().expect("path of the running test binary");
        let out = std::process::Command::new(exe)
            .args(["--exact", ROUTING_TEST, "--nocapture", "--test-threads=1"])
            .env(ROUTING_MODE_ENV, mode)
            .output()
            .expect("re-exec the test binary");
        (
            String::from_utf8_lossy(&out.stdout).into_owned(),
            String::from_utf8_lossy(&out.stderr).into_owned(),
        )
    }

    /// `note`/`warn` are the single chokepoint CLI-217 rests on, and seven call
    /// sites across `install.rs` and `commands.rs` were converted onto them.
    /// Every other test of that conversion is end-to-end through one caller, so
    /// none of them pins the helper's own contract; a helper that always wrote
    /// to stderr, or that dropped the warn marker, would satisfy all of them
    /// (they assert "the note is on stderr under --json", never "and on stdout
    /// otherwise, with its marker").
    ///
    /// The routing cannot be observed in-process: `ctx()` is a set-once
    /// `OnceLock` shared by every test in this binary, and the helpers write to
    /// the real fds rather than returning a string. So this test re-executes
    /// the test binary filtered to itself, with the mode in an env var; the
    /// child installs that context, emits one `note` and one `warn`, and exits.
    // spec: CLI-217
    #[test]
    fn note_and_warn_route_by_output_mode() {
        if let Ok(mode) = std::env::var(ROUTING_MODE_ENV) {
            // Child role: emit, then exit before libtest prints anything else.
            set_ctx(OutputCtx {
                json: mode == "json",
                color: false,
                unicode: false,
                tui_unicode: false,
                verbose: false,
            });
            note(NOTE_SENTINEL);
            warn(WARN_SENTINEL);
            std::process::exit(0);
        }

        // Text mode: both lines go to stdout, byte for byte the `println!` they
        // replaced, and `warn` carries the context's marker.
        let (text_out, text_err) = routing_probe("text");
        assert!(
            text_out.contains(NOTE_SENTINEL),
            "text mode must write a note to STDOUT (this is the `println!` the \
             conversion replaced): stdout={text_out:?} stderr={text_err:?}"
        );
        assert!(
            !text_err.contains(NOTE_SENTINEL),
            "text mode must not move the note to stderr: {text_err:?}"
        );
        assert!(
            text_out.contains(&format!("! {WARN_SENTINEL}")),
            "warn must prefix the context's warn marker (`!`) and land on \
             stdout in text mode: {text_out:?}"
        );
        assert!(
            !text_err.contains(WARN_SENTINEL),
            "text mode must not move the warning to stderr: {text_err:?}"
        );

        // --json: both lines move to stderr so stdout stays exactly one JSON
        // document. They are ROUTED, not dropped.
        let (json_out, json_err) = routing_probe("json");
        assert!(
            !json_out.contains(NOTE_SENTINEL),
            "under --json a note must never touch stdout: {json_out:?}"
        );
        assert!(
            json_err.contains(NOTE_SENTINEL),
            "under --json the note must still be emitted, on stderr: \
             stdout={json_out:?} stderr={json_err:?}"
        );
        assert!(
            !json_out.contains(WARN_SENTINEL),
            "under --json a warning must never touch stdout: {json_out:?}"
        );
        assert!(
            json_err.contains(&format!("! {WARN_SENTINEL}")),
            "under --json the warning must still be emitted on stderr, marker \
             and all (json forces the capability gate off, so the marker is the \
             ASCII `!`): {json_err:?}"
        );
    }

    /// set_ctx installs a value that ctx() then returns.
    ///
    /// OnceLock is set-once: only the first set_ctx call in this process wins.
    /// We use a plain OutputCtx so the assertion is consistent regardless of
    /// whether ctx_default_is_plain ran first.
    #[test]
    fn ctx_set_then_get_reflects_installed_value() {
        let installed = OutputCtx {
            json: false,
            color: false,
            unicode: false,
            tui_unicode: false,
            verbose: false,
        };
        set_ctx(installed);
        let got = ctx();
        assert_eq!(got.json, installed.json);
        assert_eq!(got.color, installed.color);
        assert_eq!(got.unicode, installed.unicode);
        assert_eq!(got.verbose, installed.verbose);
    }
}