vtcode-commons 0.185.1

Shared traits for paths, telemetry, and error reporting reused across VT Code component extractions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
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
#![expect(
    clippy::indexing_slicing,
    reason = "The boundary parser validates byte positions while walking escape sequences; anstream handles plain-text stripping."
)]

//! Shared ANSI escape parser and stripping utilities for VT Code.
//!
//! Plain-text stripping is delegated to `anstream`'s ANSI state machine, which
//! is already a workspace dependency. The hand-rolled parser below remains for
//! the one thing `anstream` does not expose: the byte boundaries and payloads
//! of individual escape sequences (OSC 8 link ranges, echo suppression).
//!
//! See `docs/reference/ansi-in-vtcode.md` for the workspace usage map.

use crate::ansi_codes::{BEL_BYTE, ESC_BYTE};
use anstream::adapter::strip_str;
use anstyle_parse::state::{State, state_change};

const ESC: u8 = ESC_BYTE;
const BEL: u8 = BEL_BYTE;
const DEL: u8 = 0x7f;
const C1_ST: u8 = 0x9c;
const C1_DCS: u8 = 0x90;
const C1_SOS: u8 = 0x98;
const C1_CSI: u8 = 0x9b;
const C1_OSC: u8 = 0x9d;
const C1_PM: u8 = 0x9e;
const C1_APC: u8 = 0x9f;
const CAN: u8 = 0x18;
const SUB: u8 = 0x1a;
const MAX_STRING_SEQUENCE_BYTES: usize = 4096;
const MAX_CSI_SEQUENCE_BYTES: usize = 64;

#[derive(Clone, Copy)]
enum StringSequenceTerminator {
    StOnly,
    BelOrSt,
}

impl StringSequenceTerminator {
    #[inline]
    const fn allows_bel(self) -> bool {
        matches!(self, Self::BelOrSt)
    }
}

#[inline]
fn parse_c1_at(bytes: &[u8], start: usize) -> Option<(u8, usize)> {
    let first = *bytes.get(start)?;
    if (0x80..=0x9f).contains(&first) {
        return Some((first, 1));
    }
    None
}

#[inline]
fn parse_csi(bytes: &[u8], start: usize) -> Option<usize> {
    // ECMA-48 / ISO 6429 CSI grammar:
    // - parameter bytes: 0x30..0x3F
    // - intermediate bytes: 0x20..0x2F
    // - final byte: 0x40..0x7E
    // (See ANSI escape code article on Wikipedia, CSI section.)
    let mut index = start;
    let mut phase = 0u8; // 0=parameter, 1=intermediate
    let mut consumed = 0usize;

    while index < bytes.len() {
        let byte = bytes[index];
        if byte == ESC {
            // VT100: ESC aborts current control sequence and starts a new one.
            return Some(index);
        }
        if byte == CAN || byte == SUB {
            // VT100: CAN/SUB abort current control sequence.
            return Some(index + 1);
        }

        consumed += 1;
        if consumed > MAX_CSI_SEQUENCE_BYTES {
            // Bound malformed or hostile input.
            return Some(index + 1);
        }

        if phase == 0 && (0x30..=0x3f).contains(&byte) {
            index += 1;
            continue;
        }
        if (0x20..=0x2f).contains(&byte) {
            phase = 1;
            index += 1;
            continue;
        }
        if (0x40..=0x7e).contains(&byte) {
            return Some(index + 1);
        }

        // Invalid CSI byte: abort sequence without consuming this byte.
        return Some(index);
    }

    None
}

#[inline]
fn parse_string_sequence(bytes: &[u8], start: usize, terminator: StringSequenceTerminator) -> Option<usize> {
    let mut consumed = 0usize;
    for index in start..bytes.len() {
        if bytes[index] == ESC && !(index + 1 < bytes.len() && bytes[index + 1] == b'\\') {
            // VT100: ESC aborts current sequence and begins a new one.
            return Some(index);
        }
        if bytes[index] == CAN || bytes[index] == SUB {
            return Some(index + 1);
        }

        if let Some((c1, len)) = parse_c1_at(bytes, index)
            && c1 == C1_ST
        {
            return Some(index + len);
        }

        match bytes[index] {
            BEL if terminator.allows_bel() => return Some(index + 1),
            ESC if index + 1 < bytes.len() && bytes[index + 1] == b'\\' => return Some(index + 2),
            _ => {}
        }

        consumed += 1;
        if consumed > MAX_STRING_SEQUENCE_BYTES {
            // Cap unbounded strings when terminator is missing.
            return Some(index + 1);
        }
    }
    None
}

#[inline]
fn push_visible_byte(output: &mut Vec<u8>, byte: u8) {
    if matches!(byte, b'\n' | b'\r' | b'\t') || !(byte < 32 || byte == DEL) {
        output.push(byte);
    }
}

#[inline]
fn parse_ansi_sequence_bytes(bytes: &[u8]) -> Option<usize> {
    if bytes.is_empty() {
        return None;
    }

    if let Some((c1, c1_len)) = parse_c1_at(bytes, 0) {
        return match c1 {
            C1_CSI => parse_csi(bytes, c1_len),
            C1_OSC => parse_string_sequence(bytes, c1_len, StringSequenceTerminator::BelOrSt),
            C1_DCS | C1_SOS | C1_PM | C1_APC => parse_string_sequence(bytes, c1_len, StringSequenceTerminator::StOnly),
            _ => Some(c1_len),
        };
    }

    match bytes[0] {
        ESC => {
            if bytes.len() < 2 {
                return None;
            }

            match bytes[1] {
                b'[' => parse_csi(bytes, 2),
                b']' => parse_string_sequence(bytes, 2, StringSequenceTerminator::BelOrSt),
                b'P' | b'^' | b'_' | b'X' => parse_string_sequence(bytes, 2, StringSequenceTerminator::StOnly),
                // Three-byte sequences: ESC + intermediate + final
                // ESC SP {F,G,L,M,N} — 7/8-bit controls, ANSI conformance
                // ESC # {3,4,5,6,8} — DEC line attributes / screen alignment
                // ESC % {@ ,G} — character set selection (ISO 2022)
                // ESC ( C / ESC ) C / ESC * C / ESC + C — G0-G3 designation
                b' ' | b'#' | b'%' | b'(' | b')' | b'*' | b'+' => {
                    if bytes.len() > 2 {
                        Some(3)
                    } else {
                        None
                    }
                }
                next if next < 128 => Some(2),
                _ => Some(1),
            }
        }
        _ => None,
    }
}

/// Strip ANSI escape codes from text, returning a borrowed `Cow` when the
/// input contains no ESC byte.  This is the preferred API for call-sites that
/// want to avoid allocation on the common "no ANSI codes" path.
pub fn strip_ansi_codes(text: &str) -> std::borrow::Cow<'_, str> {
    if !text.contains('\x1b') {
        return std::borrow::Cow::Borrowed(text);
    }
    std::borrow::Cow::Owned(strip_ansi(text))
}

/// Remove the C0 controls that must never reach a transcript.
///
/// `anstream` keeps FF (`0x0C`) because it is ASCII whitespace in its state
/// machine, and the old in-tree stripper removed every control byte except
/// `\n`, `\r`, and `\t` (plus DEL). Keep that contract: the escape-sequence
/// parsing is delegated, but control-byte filtering is owned here.
#[inline]
fn is_transcript_control(byte: u8) -> bool {
    (byte < b' ' && !matches!(byte, b'\n' | b'\r' | b'\t')) || byte == DEL
}

/// Strip escape sequences and residual control bytes from already-valid UTF-8.
fn strip_plain(text: &str) -> String {
    let mut output = strip_str(text).to_string().into_bytes();
    // Only ASCII control bytes are removed, so no multi-byte UTF-8 sequence
    // can be broken and `from_utf8` reuses the existing allocation.
    output.retain(|byte| !is_transcript_control(*byte));
    String::from_utf8(output).expect("removing ASCII control bytes preserves UTF-8")
}

/// Strip ANSI escape codes from text, keeping only plain text.
///
/// Delegates to `anstream`'s ANSI state machine. An incomplete sequence at the
/// end of the input is dropped rather than emitted as raw control bytes; for
/// chunked input use [`AnsiStripStream`] so a split sequence is not lost.
pub fn strip_ansi(text: &str) -> String {
    strip_plain(text)
}

/// Stateful ANSI stripper for chunked input such as a PTY byte stream.
///
/// `anstream`'s incremental adapter resets its parser to the ground state at
/// each call, so it cannot recover a sequence split across two chunks. This
/// wrapper holds back only the trailing, unterminated escape sequence and
/// re-strips it together with the next chunk. Both the boundary detector and
/// `anstream` use `anstyle_parse`'s state machine, so they cannot disagree on
/// where a sequence ends. The retained suffix is bounded.
#[derive(Default)]
pub struct AnsiStripStream {
    /// Trailing, unterminated escape sequence held back for the next chunk.
    /// Bounded by [`MAX_STRING_SEQUENCE_BYTES`].
    pending: String,
    /// Parser state while discarding an overlong, unterminated sequence.
    ///
    /// The bound on `pending` means a hostile or buggy child could emit an
    /// arbitrarily long OSC string. Once the cap is hit, the rest of that
    /// sequence is dropped until the state machine returns to `Ground`, so
    /// output stays independent of where the PTY read landed without letting
    /// the retained buffer grow without limit.
    discarding: Option<State>,
}

impl AnsiStripStream {
    /// Create a stripper with no retained bytes.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Strip the next chunk, returning its visible text.
    ///
    /// A trailing escape sequence that is incomplete in `chunk` is retained
    /// and prepended to the next call instead of leaking raw control bytes.
    pub fn strip_chunk(&mut self, chunk: &str) -> String {
        let chunk = self.discard_overlong(chunk);
        if chunk.is_empty() {
            return String::new();
        }
        // The common case has no held-back suffix. Avoid copying the whole
        // chunk into `pending`'s buffer only to split it again; PTY output is
        // chunked at high frequency and this path is allocation-sensitive.
        if self.pending.is_empty() {
            return self.strip_ready(chunk);
        }
        let mut combined = std::mem::take(&mut self.pending);
        combined.push_str(chunk);
        self.strip_ready(&combined)
    }

    /// Drop the continuation of an overlong sequence up to its terminator,
    /// returning the first byte after the sequence (if the chunk contains it).
    fn discard_overlong<'a>(&mut self, chunk: &'a str) -> &'a str {
        let Some(mut state) = self.discarding else {
            return chunk;
        };
        for (index, ch) in chunk.char_indices() {
            if !ch.is_ascii() {
                continue;
            }
            let (next, _) = state_change(state, ch as u8);
            if next != State::Anywhere {
                state = next;
            }
            if next == State::Ground {
                self.discarding = None;
                return chunk.split_at(index + ch.len_utf8()).1;
            }
        }
        self.discarding = Some(state);
        ""
    }

    /// Strip `text`, holding back its trailing incomplete sequence for the next call.
    fn strip_ready(&mut self, text: &str) -> String {
        let mut overlong = false;
        let split_at = if text.as_bytes().contains(&ESC) {
            let tail = sequence_tail(text);
            overlong = tail.overlong;
            if overlong {
                self.discarding = Some(tail.state);
            }
            tail.start
        } else {
            text.len()
        };
        let (ready, pending) = text.split_at(split_at);
        if !overlong {
            self.pending.push_str(pending);
        }
        strip_plain(ready)
    }
}

/// Where an unterminated escape sequence starts, and the parser state at EOF.
struct SequenceTail {
    /// Byte offset where the trailing incomplete sequence begins; `text.len()`
    /// when the input ends in a complete sequence or was too long to retain.
    start: usize,
    /// Parser state after the whole input, used to resume in discard mode.
    state: State,
    /// Whether the trailing sequence exceeded the retention cap.
    overlong: bool,
}

/// Locate the trailing, unterminated escape sequence.
///
/// Uses the same `anstyle_parse` state machine as `anstream`. A second,
/// hand-rolled grammar here would classify sequences differently (notably a
/// C0 control inside CSI) and make output depend on where a PTY read landed.
fn sequence_tail(text: &str) -> SequenceTail {
    let mut state = State::Ground;
    let mut candidate = None;
    for (index, ch) in text.char_indices() {
        if !ch.is_ascii() {
            // Validated UTF-8 bytes are printable and do not affect ANSI state.
            continue;
        }
        if state == State::Ground && ch == '\x1b' {
            candidate = Some(index);
        }
        let (next, _) = state_change(state, ch as u8);
        if next != State::Anywhere {
            state = next;
        }
    }

    if state == State::Ground {
        return SequenceTail { start: text.len(), state, overlong: false };
    }
    // A non-Ground state without an ASCII ESC start can only come from 8-bit
    // C1 bytes, which `anstream` treats as printable UTF-8 rather than controls.
    let Some(start) = candidate else {
        return SequenceTail { start: text.len(), state, overlong: false };
    };
    if text.len() - start > MAX_STRING_SEQUENCE_BYTES {
        return SequenceTail { start: text.len(), state, overlong: true };
    }
    SequenceTail { start, state, overlong: false }
}

/// Strip ANSI escape codes from arbitrary bytes, preserving non-control bytes.
///
/// This is the preferred API when input may contain raw C1 (8-bit) controls.
fn strip_ansi_bytes(input: &[u8]) -> Vec<u8> {
    let mut output = Vec::with_capacity(input.len());
    let bytes = input;
    let mut i = 0;

    while i < bytes.len() {
        // Pre-slice to the remaining portion so all indexing below shares one bounds edge.
        let rest = &bytes[i..];

        if (rest[0] == ESC || parse_c1_at(bytes, i).is_some())
            && let Some(len) = parse_ansi_sequence_bytes(rest)
        {
            i += len;
            continue;
        }
        if rest[0] == ESC || parse_c1_at(bytes, i).is_some() {
            // Incomplete/unterminated control sequence at end of available text.
            break;
        }

        push_visible_byte(&mut output, rest[0]);
        i += 1;
    }
    output
}

/// Parse and determine the length of the ANSI escape sequence at the start of text.
///
/// This boundary parser is deliberately conservative: an invalid byte inside a
/// CSI (including a C0 control other than ESC/CAN/SUB) aborts the sequence
/// without consuming that byte. PTY echo suppression uses it to skip escape
/// sequences without swallowing following command text on malformed input.
/// [`strip_ansi`] follows `anstream`'s ECMA-48 state machine instead, where a
/// C0 control inside CSI is executed and the sequence continues; the two
/// parsers therefore disagree on that malformed input by design.
pub fn parse_ansi_sequence(text: &str) -> Option<usize> {
    let bytes = text.as_bytes();
    parse_ansi_sequence_bytes(bytes)
}

/// ANSI stripping for ASCII-only text.
///
/// Retained for API compatibility; this now shares [`strip_ansi`]'s parser.
/// Two deliberate contract changes from the old copy-raw-spans implementation:
/// C0 controls and DEL are filtered (as in [`strip_ansi`]), and an unterminated
/// escape sequence at the end of the input is dropped instead of kept — the
/// latter would leak raw control bytes when a PTY chunk splits a sequence.
pub fn strip_ansi_ascii_only(text: &str) -> String {
    strip_ansi(text)
}

/// Detect if text contains unicode characters that need special handling
#[must_use]
pub fn contains_unicode(text: &str) -> bool {
    text.bytes().any(|b| b >= 0x80)
}

#[cfg(test)]
mod tests {
    use super::{
        AnsiStripStream, CAN, MAX_STRING_SEQUENCE_BYTES, SUB, parse_ansi_sequence_bytes, push_visible_byte, strip_ansi,
        strip_ansi_ascii_only,
    };

    #[test]
    fn strips_esc_csi_sequences() {
        let input = "a\x1b[31mred\x1b[0mz";
        assert_eq!(strip_ansi(input), "aredz");
        assert_eq!(strip_ansi_ascii_only(input), "aredz");
    }

    #[test]
    fn utf8_encoded_c1_is_not_reprocessed_as_control() {
        // XTerm/ECMA-48: controls are processed once; decoded UTF-8 text is not reprocessed as C1.
        let input = "a\u{009b}31mred";
        assert_eq!(strip_ansi(input), input);
    }

    #[test]
    fn strip_removes_ascii_del_control() {
        let input = format!("a{}b", char::from(0x7f));
        assert_eq!(strip_ansi(&input), "ab");
    }

    #[test]
    fn strip_removes_c0_controls_except_line_whitespace() {
        // anstream treats FF (0x0C) as printable ASCII whitespace; the shared
        // stripper must still remove it so raw control bytes never reach a
        // transcript. VT (0x0B) and the other C0 controls are filtered too.
        // ESC (0x1B) is an escape-sequence introducer, not a plain control
        // byte; its behavior is covered by the sequence tests above.
        for code in (0x00..0x20).filter(|&code| !matches!(code, b'\n' | b'\r' | b'\t' | 0x1b)) {
            let input = format!("a{}b", char::from(code));
            assert_eq!(strip_ansi(&input), "ab", "control byte 0x{code:02x}");

            let mut stream = AnsiStripStream::new();
            assert_eq!(stream.strip_chunk(&input), "ab", "control byte 0x{code:02x}");
        }
    }

    #[test]
    fn csi_aborts_on_esc_then_new_sequence_parses() {
        let input = "a\x1b[31\x1b[32mgreen\x1b[0mz";
        assert_eq!(strip_ansi(input), "agreenz");
    }

    #[test]
    fn csi_aborts_on_can_and_sub() {
        let can = format!("a\x1b[31{}b", char::from(CAN));
        let sub = format!("a\x1b[31{}b", char::from(SUB));
        assert_eq!(strip_ansi(&can), "ab");
        assert_eq!(strip_ansi(&sub), "ab");
    }

    #[test]
    fn osc_aborts_on_esc_non_st() {
        let input = "a\x1b]title\x1b[31mred\x1b[0mz";
        assert_eq!(strip_ansi(input), "aredz");
    }

    #[test]
    fn osc_program_status_reports_are_stripped() {
        // Nested OSC 7501 from child output must never reach the terminal:
        // VT Code re-projects children with generic labels instead. Both
        // terminator forms apply; surrounding text survives on both sides.
        let st = "out\x1b]7501;state=working:app=tool:msg=V29ya2luZw==\x1b\\done";
        assert_eq!(strip_ansi(st), "outdone");
        let bel = "out\x1b]7501;state=blocked:kind=permission\x07done";
        assert_eq!(strip_ansi(bel), "outdone");
    }

    #[test]
    fn incomplete_sequence_drops_tail() {
        let input = "text\x1b[31";
        assert_eq!(strip_ansi(input), "text");
    }

    #[test]
    fn ascii_only_incomplete_sequence_drops_tail() {
        // The old ASCII fast path kept the unterminated tail, which leaked raw
        // escape bytes into transcripts when a PTY chunk split a sequence.
        let input = "text\x1b[31";
        assert_eq!(strip_ansi_ascii_only(input), "text");
    }

    #[test]
    fn strips_common_progress_redraw_sequences() {
        // Common pattern for dynamic CLI updates:
        // carriage return + erase line + redraw text.
        let input = "\r\x1b[2KProgress 10%\r\x1b[2KDone\n";
        assert_eq!(strip_ansi(input), "\rProgress 10%\rDone\n");
    }

    #[test]
    fn strips_cursor_navigation_sequences() {
        let input = "left\x1b[1D!\nup\x1b[1Arow";
        assert_eq!(strip_ansi(input), "left!\nuprow");
    }

    #[test]
    fn strip_ansi_bytes_supports_raw_c1_csi() {
        let input = [b'a', 0x9b, b'3', b'1', b'm', b'r', b'e', b'd', 0x9b, b'0', b'm', b'z'];
        let out = super::strip_ansi_bytes(&input);
        assert_eq!(out, b"aredz");
    }

    #[test]
    fn strip_ansi_bytes_supports_raw_c1_osc_and_st() {
        let mut input = b"pre".to_vec();
        input.extend_from_slice(&[0x9d]);
        input.extend_from_slice(b"8;;https://example.com");
        input.extend_from_slice(&[0x9c]);
        input.extend_from_slice(b"link");
        input.extend_from_slice(&[0x9d]);
        input.extend_from_slice(b"8;;");
        input.extend_from_slice(&[0x9c]);
        input.extend_from_slice(b"post");
        let out = super::strip_ansi_bytes(&input);
        assert_eq!(out, b"prelinkpost");
    }

    #[test]
    fn csi_respects_parameter_intermediate_final_grammar() {
        // Parameter bytes ("1;2"), intermediate bytes (" "), then final ("m")
        let input = "a\x1b[1;2 mred\x1b[0mz";
        assert_eq!(strip_ansi(input), "aredz");
    }

    #[test]
    fn malformed_csi_control_byte_lets_next_final_byte_terminate() {
        // Per the ECMA-48/DEC state machine, a C0 control inside CSI is
        // executed but does not abort the sequence. The next byte in 0x40..=0x7e
        // ('v') is therefore the final byte and is consumed with the sequence.
        let malformed = format!("a\x1b[12{}visible", char::from(0x10));
        assert_eq!(strip_ansi(&malformed), "aisible");
    }

    #[test]
    fn boundary_parser_stays_conservative_on_malformed_csi() {
        // Echo suppression relies on the boundary parser not swallowing text
        // that follows a malformed CSI, so it intentionally disagrees with
        // `strip_ansi` about where the sequence ends.
        let malformed = format!("\x1b[12{}visible", char::from(0x10));
        let len = super::parse_ansi_sequence(&malformed).expect("sequence length");
        assert_eq!(malformed.split_at(len).0, "\x1b[12");
        assert_eq!(strip_ansi(&malformed), "isible");
    }

    #[test]
    fn strips_wikipedia_sgr_8bit_color_pattern() {
        let input = "x\x1b[38;5;196mred\x1b[0my";
        assert_eq!(strip_ansi(input), "xredy");
    }

    #[test]
    fn strips_wikipedia_sgr_truecolor_pattern() {
        let input = "x\x1b[48;2;12;34;56mblock\x1b[0my";
        assert_eq!(strip_ansi(input), "xblocky");
    }

    #[test]
    fn strips_wikipedia_osc8_hyperlink_pattern() {
        let input = "go \x1b]8;;https://example.com\x1b\\here\x1b]8;;\x1b\\ now";
        assert_eq!(strip_ansi(input), "go here now");
    }

    #[test]
    fn strips_dec_private_mode_csi() {
        let input = "a\x1b[?25lb\x1b[?25hc";
        assert_eq!(strip_ansi(input), "abc");
    }

    #[test]
    fn strips_mintty_overstrike_mode_sequences() {
        // mintty/VK100 overstrike switching: SGR `8:7` enables overstrike,
        // `28` returns to overwriting mode, and `?20h`/`?20l` are the
        // private-mode forms. All are consumed like any other CSI sequence.
        let input = "a\x1b[8:7mb\x1b[28mc\x1b[?20hd\x1b[?20le";
        assert_eq!(strip_ansi(input), "abcde");
        assert_eq!(strip_ansi_ascii_only(input), "abcde");
    }

    #[test]
    fn strips_three_byte_esc_sequences() {
        // ESC # 8 = DEC screen alignment test
        let input = "a\x1b#8b";
        assert_eq!(strip_ansi(input), "ab");

        // ESC ( B = designate US ASCII as G0
        let input2 = "a\x1b(Bb";
        assert_eq!(strip_ansi(input2), "ab");

        // ESC SP F = 7-bit controls
        let input3 = "a\x1b Fb";
        assert_eq!(strip_ansi(input3), "ab");

        // ESC % G = select UTF-8
        let input4 = "a\x1b%Gb";
        assert_eq!(strip_ansi(input4), "ab");
    }

    #[test]
    fn incomplete_three_byte_esc_sequence_drops_tail() {
        // ESC # at end — incomplete, should not consume past end
        let input = "text\x1b#";
        assert_eq!(strip_ansi(input), "text");
    }

    /// Reference stripper built from the in-tree boundary parser, independent
    /// of `anstream`. Used as the oracle for the delegation refactor.
    fn legacy_strip(text: &str) -> String {
        let bytes = text.as_bytes();
        let mut output = Vec::with_capacity(bytes.len());
        let mut index = 0;
        while index < bytes.len() {
            let next_esc = bytes[index..]
                .iter()
                .position(|&b| b == b'\x1b')
                .map_or(bytes.len(), |o| index + o);
            for &byte in &bytes[index..next_esc] {
                push_visible_byte(&mut output, byte);
            }
            index = next_esc;
            if index >= bytes.len() {
                break;
            }
            if let Some(len) = parse_ansi_sequence_bytes(&bytes[index..]) {
                index += len;
            } else {
                break;
            }
        }
        String::from_utf8(output).expect("filtering ASCII controls cannot break UTF-8")
    }

    #[test]
    fn anstream_matches_legacy_stripper_on_structured_corpus() {
        let cases = [
            "plain text",
            "a\x1b[31mred\x1b[0mz",
            "\r\x1b[2KProgress 10%\r\x1b[2KDone\n",
            "go \x1b]8;;https://example.com\x1b\\here\x1b]8;;\x1b\\ now",
            "out\x1b]7501;state=working\x07done",
            "a\x1b#8b",
            "a\x1b(Bb",
            "a\x1b Fb",
            "a\x1b%Gb",
            "a\x1b[31\x1b[32mgreen\x1b[0mz",
            "a\u{009b}31mred",
            "x\x1b[38;5;196mred\x1b[0my",
            "a\x1b[?25lb\x1b[?25hc",
            "text\x1b[31",
        ];
        for case in cases {
            assert_eq!(strip_ansi(case), legacy_strip(case), "case {case:?}");
        }
    }

    #[test]
    fn strip_stream_keeps_parser_state_across_split_sequences() {
        let mut stream = AnsiStripStream::new();
        let mut visible = stream.strip_chunk("text\x1b[3");
        // Neither half is a valid sequence on its own; only together do they
        // form SGR. A stateless stripper would leak "31m" into the output.
        visible.push_str(&stream.strip_chunk("1mred\x1b[0mz"));
        assert_eq!(visible, "textredz");

        let mut stream = AnsiStripStream::new();
        let mut visible = stream.strip_chunk("pre\x1b]8;;https://exa");
        visible.push_str(&stream.strip_chunk("mple.com\x1b\\linkpost"));
        assert_eq!(visible, "prelinkpost");
    }

    #[test]
    fn strip_stream_output_is_independent_of_chunk_boundaries() {
        // A C0 control inside CSI is executed, not an abort: the next 0x40..=0x7e
        // byte is the sequence's final byte. Both the boundary detector and
        // anstream must agree, or visible text appears/disappears based on the
        // arbitrary PTY read boundary.
        let whole = "PRE\x1b[31mMID\x1b[12\x10visiblePOST";
        let expected = strip_ansi(whole);
        for split in 0..=whole.len() {
            if !whole.is_char_boundary(split) {
                continue;
            }
            let (first, second) = whole.split_at(split);
            let mut stream = AnsiStripStream::new();
            let mut visible = stream.strip_chunk(first);
            visible.push_str(&stream.strip_chunk(second));
            assert_eq!(visible, expected, "split at byte {split}");
        }
    }

    #[test]
    fn strip_stream_passes_plain_text_through_unchanged() {
        let mut stream = AnsiStripStream::new();
        assert_eq!(stream.strip_chunk("plain text\n"), "plain text\n");
        assert_eq!(stream.strip_chunk("second\rline"), "second\rline");
    }

    /// The retained suffix is capped, but an overlong OSC string must still
    /// not leak its continuation into the transcript when a PTY read splits it.
    #[test]
    fn strip_stream_handles_overlong_incomplete_sequence_at_chunk_boundary() {
        for terminator in ["\x1b\\", "\x07"] {
            let mut payload = String::from("PRE\x1b]8;;");
            payload.push_str(&"x".repeat(MAX_STRING_SEQUENCE_BYTES + 16));
            payload.push_str(terminator);
            payload.push_str("POST");
            let expected = strip_ansi(&payload);
            assert_eq!(expected, "PREPOST", "terminator {terminator:?}");

            for split in [
                "PRE\x1b]8;;".len() + 8,
                "PRE\x1b]8;;".len() + MAX_STRING_SEQUENCE_BYTES - 1,
                "PRE\x1b]8;;".len() + MAX_STRING_SEQUENCE_BYTES + 8,
                payload.len() - terminator.len(),
            ] {
                let (first, second) = payload.split_at(split);
                let mut stream = AnsiStripStream::new();
                let mut visible = stream.strip_chunk(first);
                assert!(stream.pending.len() <= MAX_STRING_SEQUENCE_BYTES, "retention cap");
                visible.push_str(&stream.strip_chunk(second));
                assert!(stream.pending.is_empty(), "buffer released after terminator");
                assert_eq!(visible, expected, "split at {split}, terminator {terminator:?}");
            }
        }
    }

    /// A PTY read can end at any byte boundary. Streaming output must match
    /// one-shot stripping for every possible split, not just hand-picked ones.
    #[test]
    fn strip_stream_matches_one_shot_for_every_chunk_boundary() {
        let cases = [
            "a\x1b[31mred\x1b[0mz",
            "go \x1b]8;;https://example.com\x1b\\here\x1b]8;;\x1b\\ now",
            "out\x1b]7501;state=working\x07done",
            "a\x1b#8b",
            "a\x1b(Bb",
            "a\x1b[31\x1b[32mgreen\x1b[0mz",
            "\r\x1b[2KProgress 10%\r\x1b[2KDone\n",
            "text\x1b[31",
            "a\u{009b}31mred",
            "x\x1b[38;5;196mred\x1b[0my",
        ];
        for case in cases {
            let expected = strip_ansi(case);
            for index in 0..=case.len() {
                if !case.is_char_boundary(index) {
                    continue;
                }
                let (first, second) = case.split_at(index);
                let mut stream = AnsiStripStream::new();
                let mut visible = stream.strip_chunk(first);
                visible.push_str(&stream.strip_chunk(second));
                assert_eq!(visible, expected, "split at {index} of {case:?}");
            }
        }
    }
}