relux-runtime 0.6.0

Internal: runtime for Relux. No semver guarantees.
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
use std::collections::HashMap;
use std::sync::Arc;

use regex::Regex;
use std::sync::Mutex;
use tokio::sync::Notify;

use crate::observe::structured::BufferEventKind;
use crate::observe::structured::EventSeq;
use crate::observe::structured::StructuredLogBuilder;
use crate::observe::structured::Utf8Stream;
use crate::vm::context::FailPattern;

// ─── FailPatternHit ─────────────────────────────────────────────

/// A fail pattern matched in the output buffer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FailPatternHit {
    /// The pattern string that was being watched for (regex source or literal).
    pub(crate) pattern: String,
    /// Whether `pattern` is a regex (`true`) or a literal substring (`false`).
    pub(crate) is_regex: bool,
    /// The actual text in the buffer that matched.
    pub(crate) matched_text: String,
}

// ─── MatchContext ───────────────────────────────────────────────

/// `(before, matched, after)` slices around a match. Used by the VM to push a
/// `BufferEventKind::Matched` describing how the cursor advanced.
///
/// All three strings carry the *full* bytes around the match, untruncated.
/// The viewer reconstructs each shell's append-only buffer from the `grew`
/// stream and validates that `before + matched + after` equals the
/// currently-unmatched buffer tail at the moment of the match.
pub type MatchContext = (String, String, String);

// ─── Tail truncation helpers (failure-context capture only) ────
// `match_context` does NOT use these — match events ship full bytes so the
// viewer can rebuild append-only history losslessly. These helpers are
// kept for `snapshot_tail` and other places that intentionally want a
// human-sized excerpt of the buffer.

fn truncate_before(s: &str, max: usize) -> String {
    if s.len() <= max {
        s.to_string()
    } else {
        let start = s.ceil_char_boundary(s.len() - max);
        format!("...{}", &s[start..])
    }
}

pub(crate) fn regex_error_summary(e: &regex::Error) -> String {
    let full = e.to_string();
    full.lines()
        .rev()
        .find(|l| !l.is_empty())
        .unwrap_or(&full)
        .strip_prefix("error: ")
        .unwrap_or(&full)
        .to_string()
}

fn match_context(text: &str, pos: usize, end_pos: usize, matched: &str) -> MatchContext {
    (
        text[..pos].to_string(),
        matched.to_string(),
        text[end_pos..].to_string(),
    )
}

// ─── Match Types ────────────────────────────────────────────────

/// Marker trait for match payload types.
pub trait MatchKind {}

/// Payload for a literal match.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LiteralMatch(pub String);
impl MatchKind for LiteralMatch {}

/// Payload for a regex match (capture groups by index).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RegexMatch(pub HashMap<String, String>);
impl MatchKind for RegexMatch {}

/// A match result with absolute byte offsets and typed payload.
#[derive(Debug, Clone)]
pub struct Match<T: MatchKind> {
    /// Absolute byte offset of match start (accounts for all prior truncations).
    pub start: usize,
    /// Absolute byte offset of match end.
    pub end: usize,
    /// Bytes consumed (everything up to and including the match, relative to current buffer).
    pub consumed: usize,
    /// The matched content.
    pub value: T,
}

// ─── OutputBuffer ───────────────────────────────────────────────

struct BufferInner {
    /// Cleanly-decoded bytes available for matching. Always valid UTF-8.
    /// Invalid input bytes are surfaced as `U+FFFD` here via `Utf8Stream`,
    /// so byte offsets and char-aware slicing coincide for drains.
    decoded: String,
    /// Absolute byte offset (in decoded coordinates) of the first byte
    /// currently held in `decoded`. Advanced on every drain; used to
    /// compute `Match.start` / `Match.end` across the shell's lifetime.
    base: usize,
    /// Streaming UTF-8 decoder; holds back the trailing bytes of any
    /// incomplete multi-byte sequence until the next `append`.
    utf8: Utf8Stream,
}

#[derive(Clone)]
pub struct OutputBuffer {
    inner: Arc<Mutex<BufferInner>>,
    pub(crate) notify: Arc<Notify>,
    /// Log builder used to emit buffer events (grew/matched/reset)
    /// while still holding the inner mutex. Optional so unit tests
    /// can construct an `OutputBuffer` without a log surface.
    log: Option<StructuredLogBuilder>,
    shell_name: String,
    shell_marker: String,
}

impl OutputBuffer {
    /// Construct an `OutputBuffer` wired to the given log builder.
    /// `append`/`consume_*`/`clear` emit their corresponding buffer events
    /// on `log` while still holding the inner mutex, preventing a race
    /// between byte appends and event order. The inner mutex is a
    /// `std::sync::Mutex` — every critical section is pure CPU work, so no
    /// `.await` ever happens under the guard and a blocking lock is correct.
    pub fn new(log: StructuredLogBuilder, shell_name: String, shell_marker: String) -> Self {
        Self {
            inner: Arc::new(Mutex::new(BufferInner {
                decoded: String::new(),
                base: 0,
                utf8: Utf8Stream::new(),
            })),
            notify: Arc::new(Notify::new()),
            log: Some(log),
            shell_name,
            shell_marker,
        }
    }

    /// Construct an `OutputBuffer` with no log surface — buffer-event
    /// emissions are silently dropped. Unit-test only.
    #[cfg(test)]
    pub fn for_tests() -> Self {
        Self {
            inner: Arc::new(Mutex::new(BufferInner {
                decoded: String::new(),
                base: 0,
                utf8: Utf8Stream::new(),
            })),
            notify: Arc::new(Notify::new()),
            log: None,
            shell_name: String::new(),
            shell_marker: String::new(),
        }
    }

    pub async fn append(&self, bytes: &[u8]) {
        let mut inner = self.inner.lock().unwrap();
        let decoded = inner.utf8.feed(bytes);
        if !decoded.is_empty() {
            inner.decoded.push_str(&decoded);
            if let Some(log) = &self.log {
                log.push_buffer_event(
                    &self.shell_name,
                    &self.shell_marker,
                    BufferEventKind::Grew { data: decoded },
                );
            }
        }
        drop(inner);
        self.notify.notify_waiters();
    }

    /// Find literal, drain the decoded prefix up to the match end, push the
    /// `Matched` buffer event while still holding the inner lock, and return
    /// the match plus the `EventSeq` of the just-pushed buffer event. All
    /// under one lock.
    pub async fn consume_literal(&self, needle: &str) -> Option<(Match<LiteralMatch>, EventSeq)> {
        let mut inner = self.inner.lock().unwrap();
        let pos = inner.decoded.find(needle)?;
        let end_pos = pos + needle.len();

        let (before, matched_str, after) = match_context(&inner.decoded, pos, end_pos, needle);

        let consumed = end_pos;
        let m = Match {
            start: inner.base + pos,
            end: inner.base + end_pos,
            consumed,
            value: LiteralMatch(needle.to_string()),
        };

        inner.decoded.drain(..end_pos);
        inner.base += end_pos;

        let buffer_seq = self.emit_matched(before, matched_str, after);
        Some((m, buffer_seq))
    }

    /// Find regex, drain via split_to, push the `Matched` buffer event,
    /// and return the match plus the `EventSeq` of the just-pushed
    /// buffer event. All under one lock.
    ///
    /// Guards against partial-line matches: if the match ends at the buffer
    /// boundary and the buffer does not end with a newline, the last line may
    /// still be arriving. In that case we return `None` so the caller waits
    /// for more data rather than consuming an incomplete line.
    pub async fn consume_regex(&self, re: &Regex) -> Option<(Match<RegexMatch>, EventSeq)> {
        let mut inner = self.inner.lock().unwrap();
        let (pos, end_pos, matched_str, captures) = {
            let cap = re.captures(&inner.decoded)?;
            let whole = cap.get(0)?;
            let pos = whole.start();
            let end_pos = whole.end();
            if is_partial_line_match(re, end_pos, &inner.decoded) {
                return None;
            }
            let matched_str = whole.as_str().to_string();
            let mut captures = HashMap::new();
            for i in 0..cap.len() {
                if let Some(m) = cap.get(i) {
                    captures.insert(i.to_string(), m.as_str().to_string());
                }
            }
            (pos, end_pos, matched_str, captures)
        };

        let (before, _, after) = match_context(&inner.decoded, pos, end_pos, &matched_str);

        let consumed = end_pos;
        let m = Match {
            start: inner.base + pos,
            end: inner.base + end_pos,
            consumed,
            value: RegexMatch(captures),
        };

        inner.decoded.drain(..end_pos);
        inner.base += end_pos;

        let buffer_seq = self.emit_matched(before, matched_str, after);
        Some((m, buffer_seq))
    }

    /// Check fail pattern against buffer, then try to consume literal — under one lock.
    /// Returns Err if fail pattern found, Ok(Some) if literal consumed, Ok(None) if not found.
    /// On success the `Matched` buffer event is pushed before releasing the lock.
    pub async fn fail_check_consume_literal(
        &self,
        needle: &str,
        fail_pattern: Option<&FailPattern>,
    ) -> Result<Option<(Match<LiteralMatch>, EventSeq)>, FailPatternHit> {
        let mut inner = self.inner.lock().unwrap();

        // Check fail pattern first
        if let Some(fp) = fail_pattern
            && let Some(hit) = check_fail_in_buffer(&inner.decoded, fp)
        {
            return Err(hit);
        }

        // Try to consume the literal
        let Some(pos) = inner.decoded.find(needle) else {
            return Ok(None);
        };
        let end_pos = pos + needle.len();

        let (before, matched_str, after) = match_context(&inner.decoded, pos, end_pos, needle);

        let consumed = end_pos;
        let m = Match {
            start: inner.base + pos,
            end: inner.base + end_pos,
            consumed,
            value: LiteralMatch(needle.to_string()),
        };

        inner.decoded.drain(..end_pos);
        inner.base += end_pos;

        let buffer_seq = self.emit_matched(before, matched_str, after);
        Ok(Some((m, buffer_seq)))
    }

    /// Check fail pattern against buffer, then try to consume regex — under one lock.
    /// Returns Err if fail pattern found, Ok(Some) if regex consumed, Ok(None) if not found.
    /// On success the `Matched` buffer event is pushed before releasing the lock.
    pub async fn fail_check_consume_regex(
        &self,
        re: &Regex,
        fail_pattern: Option<&FailPattern>,
    ) -> Result<Option<(Match<RegexMatch>, EventSeq)>, FailPatternHit> {
        let mut inner = self.inner.lock().unwrap();

        // Check fail pattern first
        if let Some(fp) = fail_pattern
            && let Some(hit) = check_fail_in_buffer(&inner.decoded, fp)
        {
            return Err(hit);
        }

        let (pos, end_pos, matched_str, captures) = {
            let Some(cap) = re.captures(&inner.decoded) else {
                return Ok(None);
            };
            let Some(whole) = cap.get(0) else {
                return Ok(None);
            };
            let pos = whole.start();
            let end_pos = whole.end();
            if is_partial_line_match(re, end_pos, &inner.decoded) {
                return Ok(None);
            }
            let matched_str = whole.as_str().to_string();
            let mut captures = HashMap::new();
            for i in 0..cap.len() {
                if let Some(m) = cap.get(i) {
                    captures.insert(i.to_string(), m.as_str().to_string());
                }
            }
            (pos, end_pos, matched_str, captures)
        };

        let (before, _, after) = match_context(&inner.decoded, pos, end_pos, &matched_str);

        let consumed = end_pos;
        let m = Match {
            start: inner.base + pos,
            end: inner.base + end_pos,
            consumed,
            value: RegexMatch(captures),
        };

        inner.decoded.drain(..end_pos);
        inner.base += end_pos;

        let buffer_seq = self.emit_matched(before, matched_str, after);
        Ok(Some((m, buffer_seq)))
    }

    /// Push a `Matched` buffer event on the log, if one is wired up.
    /// Returns the event seq (or `0` when no log is configured).
    fn emit_matched(&self, before: String, matched: String, after: String) -> EventSeq {
        if let Some(log) = &self.log {
            log.push_buffer_event(
                &self.shell_name,
                &self.shell_marker,
                BufferEventKind::Matched {
                    before,
                    matched,
                    after,
                },
            )
        } else {
            0
        }
    }

    /// Check fail pattern against current buffer (peek only, no drain).
    pub async fn check_fail_pattern(
        &self,
        fail_pattern: Option<&FailPattern>,
    ) -> Option<FailPatternHit> {
        let fp = fail_pattern?;
        let inner = self.inner.lock().unwrap();
        check_fail_in_buffer(&inner.decoded, fp)
    }

    /// Drain the cleanly-decoded portion of the buffer, advancing base.
    /// Trailing bytes of an incomplete UTF-8 sequence stay carried over inside
    /// `Utf8Stream`, to be completed by a future `append`. Emits a `Reset`
    /// buffer event carrying the consumed prefix — byte-identical to the
    /// concatenation of `Grew` payloads emitted since the previous reset —
    /// before releasing the lock. Returns the consumed prefix.
    pub async fn clear(&self) -> String {
        let mut inner = self.inner.lock().unwrap();
        let consumed = std::mem::take(&mut inner.decoded);
        inner.base += consumed.len();
        if let Some(log) = &self.log {
            log.push_buffer_event(
                &self.shell_name,
                &self.shell_marker,
                BufferEventKind::Reset {
                    consumed: consumed.clone(),
                },
            );
        }
        consumed
    }

    /// Return the tail of the current buffer (last `n` chars) as a string.
    pub async fn snapshot_tail(&self, n: usize) -> String {
        let inner = self.inner.lock().unwrap();
        truncate_before(&inner.decoded, n)
    }

    /// Return remaining unmatched buffer data (decoded prefix as bytes).
    /// Pending bytes of an incomplete UTF-8 sequence held back by
    /// `Utf8Stream` are not returned.
    pub async fn remaining(&self) -> Vec<u8> {
        let inner = self.inner.lock().unwrap();
        inner.decoded.as_bytes().to_vec()
    }
}

/// Returns `true` if a `$`-anchored regex matched at the buffer boundary
/// where the buffer does not end with a newline — meaning the last line may
/// still be arriving and `$` matched end-of-string rather than end-of-line.
///
/// Only applies when the regex source ends with an *unescaped* `$` anchor.
/// Patterns ending in `\$` (literal dollar sign) are not anchored. Patterns
/// without a trailing `$` are never deferred.
fn is_partial_line_match(re: &Regex, match_end: usize, text: &str) -> bool {
    has_trailing_anchor(re.as_str()) && match_end == text.len() && !text.ends_with('\n')
}

/// `true` iff `src` ends in an unescaped `$` anchor. Counts the run of
/// trailing backslashes before the final `$`: an even count (including zero)
/// means the `$` is not escaped.
fn has_trailing_anchor(src: &str) -> bool {
    let Some(stripped) = src.strip_suffix('$') else {
        return false;
    };
    let trailing_backslashes = stripped.bytes().rev().take_while(|&b| b == b'\\').count();
    trailing_backslashes % 2 == 0
}

/// Check if a fail pattern matches in the given text. Returns (pattern_str, matched_text).
fn check_fail_in_buffer(text: &str, pattern: &FailPattern) -> Option<FailPatternHit> {
    match pattern {
        FailPattern::Regex(re) => {
            let m = re.find(text)?;
            Some(FailPatternHit {
                pattern: re.as_str().to_string(),
                is_regex: true,
                matched_text: m.as_str().to_string(),
            })
        }
        FailPattern::Literal(s) => {
            text.find(s.as_str())?;
            Some(FailPatternHit {
                pattern: s.clone(),
                is_regex: false,
                matched_text: s.clone(),
            })
        }
    }
}

// ─── Tests ──────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use std::path::PathBuf;
    use std::time::Instant;

    use super::*;
    use crate::observe::progress;
    use regex::RegexBuilder;

    /// Construct an `OutputBuffer` wired to a fresh `StructuredLogBuilder`,
    /// returning both so tests can assert on the buffer events that the
    /// `OutputBuffer` emits.
    fn wired_buffer() -> (
        OutputBuffer,
        StructuredLogBuilder,
        tokio::sync::mpsc::UnboundedReceiver<crate::observe::progress::ProgressEvent>,
    ) {
        let (tx, rx) = progress::channel();
        let sources = relux_core::table::SharedTable::new();
        let builder = StructuredLogBuilder::new(
            tx,
            Instant::now(),
            sources,
            Arc::from(PathBuf::from("/project").as_path()),
        );
        let buf = OutputBuffer::new(builder.clone(), "sh".into(), "m".into());
        (buf, builder, rx)
    }

    /// Inspect the last buffer event the builder accumulated.
    fn last_matched(builder: &StructuredLogBuilder) -> Option<(String, String, String)> {
        let events = builder.buffer_events_for_tests();
        events.last().and_then(|ev| match &ev.kind {
            BufferEventKind::Matched {
                before,
                matched,
                after,
            } => Some((before.clone(), matched.clone(), after.clone())),
            _ => None,
        })
    }

    /// Inspect the last `Reset` buffer event the builder accumulated.
    fn last_reset(builder: &StructuredLogBuilder) -> Option<String> {
        let events = builder.buffer_events_for_tests();
        events.last().and_then(|ev| match &ev.kind {
            BufferEventKind::Reset { consumed } => Some(consumed.clone()),
            _ => None,
        })
    }

    /// Collect every `Grew` payload the builder has accumulated, in order.
    fn all_grew(builder: &StructuredLogBuilder) -> Vec<String> {
        builder
            .buffer_events_for_tests()
            .iter()
            .filter_map(|ev| match &ev.kind {
                BufferEventKind::Grew { data } => Some(data.clone()),
                _ => None,
            })
            .collect()
    }

    // ── truncate_before ──────────────────────────────────────────────

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

    #[test]
    fn truncate_before_exact_length_unchanged() {
        assert_eq!(truncate_before("hello", 5), "hello");
    }

    #[test]
    fn truncate_before_keeps_last_n_chars() {
        assert_eq!(truncate_before("hello world", 5), "...world");
    }

    #[test]
    fn truncate_before_empty_string() {
        assert_eq!(truncate_before("", 5), "");
    }

    #[test]
    fn truncate_before_max_zero() {
        assert_eq!(truncate_before("hello", 0), "...");
    }

    // ── OutputBuffer::append / remaining ────────────────────────────

    #[tokio::test]
    async fn output_buffer_append_and_remaining() {
        let buf = OutputBuffer::for_tests();
        buf.append(b"hello").await;
        assert_eq!(buf.remaining().await, b"hello");
    }

    #[tokio::test]
    async fn output_buffer_append_empty_bytes() {
        let buf = OutputBuffer::for_tests();
        buf.append(b"").await;
        assert!(buf.remaining().await.is_empty());
    }

    // ── OutputBuffer::consume_literal ────────────────────────────────

    #[tokio::test]
    async fn consume_literal_basic() {
        let (buf, builder, _rx) = wired_buffer();
        buf.append(b"hello world").await;
        let (m, _buffer_seq) = buf.consume_literal("hello").await.unwrap();
        assert_eq!(m.start, 0);
        assert_eq!(m.end, 5);
        assert_eq!(m.consumed, 5);
        assert_eq!(m.value.0, "hello");
        let (before, matched, after) = last_matched(&builder).expect("matched event");
        assert_eq!(before, "");
        assert_eq!(matched, "hello");
        assert_eq!(after, " world");
        // Buffer should have " world" remaining
        assert_eq!(buf.remaining().await, b" world");
    }

    #[tokio::test]
    async fn consume_literal_drains_up_to_match_end() {
        let buf = OutputBuffer::for_tests();
        buf.append(b"prefix MATCH suffix").await;
        let (m, _) = buf.consume_literal("MATCH").await.unwrap();
        assert_eq!(m.start, 7);
        assert_eq!(m.end, 12);
        assert_eq!(m.consumed, 12);
        assert_eq!(buf.remaining().await, b" suffix");
    }

    #[tokio::test]
    async fn consume_literal_not_found() {
        let buf = OutputBuffer::for_tests();
        buf.append(b"hello world").await;
        assert!(buf.consume_literal("xyz").await.is_none());
        assert_eq!(buf.remaining().await, b"hello world");
    }

    #[tokio::test]
    async fn consume_literal_absolute_offsets_after_drain() {
        let buf = OutputBuffer::for_tests();
        buf.append(b"aaa bbb ccc").await;
        let (m1, _) = buf.consume_literal("aaa").await.unwrap();
        assert_eq!(m1.start, 0);
        assert_eq!(m1.end, 3);
        let (m2, _) = buf.consume_literal("bbb").await.unwrap();
        assert_eq!(m2.start, 4);
        assert_eq!(m2.end, 7);
        assert_eq!(buf.remaining().await, b" ccc");
    }

    #[tokio::test]
    async fn consume_literal_context_carries_full_before_and_after() {
        let (buf, builder, _rx) = wired_buffer();
        let huge_prefix = "x".repeat(500);
        let huge_suffix = "y".repeat(500);
        buf.append(format!("{huge_prefix}MATCH{huge_suffix}").as_bytes())
            .await;
        let _ = buf.consume_literal("MATCH").await.unwrap();
        let (before, matched, after) = last_matched(&builder).expect("matched event");
        assert_eq!(before, huge_prefix);
        assert_eq!(matched, "MATCH");
        assert_eq!(after, huge_suffix);
    }

    #[tokio::test]
    async fn consume_literal_handles_invalid_utf8_in_buffer() {
        // Regression test: invalid bytes (here 0xFF) must not corrupt offsets
        // for the drain after the match — `Utf8Stream` surfaces them as a
        // U+FFFD replacement and matching works in decoded coordinates.
        let buf = OutputBuffer::for_tests();
        let mut bytes = b"prefix".to_vec();
        bytes.push(0xFF);
        bytes.extend_from_slice(b"MATCH suffix");
        buf.append(&bytes).await;
        let (m, _) = buf.consume_literal("MATCH").await.expect("found");
        assert_eq!(m.value.0, "MATCH");
        assert_eq!(buf.remaining().await, " suffix".as_bytes());
    }

    // ── OutputBuffer::consume_regex ──────────────────────────────────

    #[tokio::test]
    async fn consume_regex_basic() {
        let buf = OutputBuffer::for_tests();
        buf.append(b"abc 123 def").await;
        let re = Regex::new(r"\d+").unwrap();
        let (m, _) = buf.consume_regex(&re).await.unwrap();
        assert_eq!(m.start, 4);
        assert_eq!(m.end, 7);
        assert_eq!(m.value.0.get("0").unwrap(), "123");
        assert_eq!(buf.remaining().await, b" def");
    }

    #[tokio::test]
    async fn consume_regex_with_captures() {
        let buf = OutputBuffer::for_tests();
        buf.append(b"name: Alice age: 30\n").await;
        let re = Regex::new(r"name: (\w+) age: (\d+)").unwrap();
        let (m, _) = buf.consume_regex(&re).await.unwrap();
        assert_eq!(m.start, 0);
        assert_eq!(m.end, 19);
        assert_eq!(m.value.0.get("0").unwrap(), "name: Alice age: 30");
        assert_eq!(m.value.0.get("1").unwrap(), "Alice");
        assert_eq!(m.value.0.get("2").unwrap(), "30");
    }

    #[tokio::test]
    async fn consume_regex_not_found() {
        let buf = OutputBuffer::for_tests();
        buf.append(b"hello world").await;
        let re = Regex::new(r"\d+").unwrap();
        assert!(buf.consume_regex(&re).await.is_none());
        assert_eq!(buf.remaining().await, b"hello world");
    }

    #[tokio::test]
    async fn consume_regex_absolute_offsets_after_drain() {
        let buf = OutputBuffer::for_tests();
        buf.append(b"aaa 123 bbb 456\n").await;
        let re = Regex::new(r"\d+").unwrap();
        let (m1, _) = buf.consume_regex(&re).await.unwrap();
        assert_eq!(m1.start, 4);
        assert_eq!(m1.end, 7);
        let (m2, _) = buf.consume_regex(&re).await.unwrap();
        assert_eq!(m2.start, 12);
        assert_eq!(m2.end, 15);
    }

    // ── Partial-line guard ─────────────────────────────────────────

    #[tokio::test]
    async fn consume_regex_defers_partial_line() {
        let buf = OutputBuffer::for_tests();
        buf.append(b"hello wor").await;
        let re = RegexBuilder::new(r"^(.+)$")
            .multi_line(true)
            .build()
            .unwrap();
        assert!(buf.consume_regex(&re).await.is_none());
        assert_eq!(buf.remaining().await, b"hello wor");

        buf.append(b"ld\n").await;
        let (m, _) = buf.consume_regex(&re).await.unwrap();
        assert_eq!(m.value.0.get("0").unwrap(), "hello world");
    }

    #[tokio::test]
    async fn consume_regex_allows_match_before_partial_tail() {
        let buf = OutputBuffer::for_tests();
        buf.append(b"first line\nsecond li").await;
        let re = RegexBuilder::new(r"^(.+)$")
            .multi_line(true)
            .build()
            .unwrap();
        let (m, _) = buf.consume_regex(&re).await.unwrap();
        assert_eq!(m.value.0.get("1").unwrap(), "first line");
    }

    #[tokio::test]
    async fn fail_check_consume_regex_defers_partial_line() {
        let buf = OutputBuffer::for_tests();
        buf.append(b"partial data").await;
        let re = RegexBuilder::new(r"^(.+)$")
            .multi_line(true)
            .build()
            .unwrap();
        let result = buf.fail_check_consume_regex(&re, None).await;
        assert!(result.unwrap().is_none());

        buf.append(b"\n").await;
        let result = buf.fail_check_consume_regex(&re, None).await;
        let (m, _) = result.unwrap().unwrap();
        assert_eq!(m.value.0.get("0").unwrap(), "partial data");
    }

    #[tokio::test]
    async fn consume_regex_handles_invalid_utf8_in_buffer() {
        let buf = OutputBuffer::for_tests();
        let mut bytes = b"abc".to_vec();
        bytes.push(0xFF);
        bytes.extend_from_slice(b" 123 def");
        buf.append(&bytes).await;
        let re = Regex::new(r"\d+").unwrap();
        let (m, _) = buf.consume_regex(&re).await.expect("found");
        assert_eq!(m.value.0.get("0").unwrap(), "123");
        assert_eq!(buf.remaining().await, " def".as_bytes());
    }

    #[tokio::test]
    async fn consume_regex_does_not_defer_on_escaped_trailing_dollar() {
        let buf = OutputBuffer::for_tests();
        buf.append(b"price: $9").await;
        // Pattern source ends with `$` literally, but it is escaped (`\$`),
        // so it is NOT an anchor. Must not be treated as a partial-line match.
        let re = Regex::new(r"price: \$\d+").unwrap();
        let (m, _) = buf
            .consume_regex(&re)
            .await
            .expect("escaped trailing dollar must not defer");
        assert_eq!(m.value.0.get("0").unwrap(), "price: $9");
    }

    // ── has_trailing_anchor ─────────────────────────────────────────

    #[test]
    fn has_trailing_anchor_unescaped() {
        assert!(super::has_trailing_anchor("foo$"));
        assert!(super::has_trailing_anchor(r"^(.+)$"));
        // Two backslashes = an escaped backslash followed by an anchor.
        assert!(super::has_trailing_anchor(r"foo\\$"));
    }

    #[test]
    fn has_trailing_anchor_escaped() {
        assert!(!super::has_trailing_anchor(r"price: \$"));
        // Three backslashes = escaped backslash + escaped dollar.
        assert!(!super::has_trailing_anchor(r"foo\\\$"));
    }

    #[test]
    fn has_trailing_anchor_no_dollar() {
        assert!(!super::has_trailing_anchor("foo"));
        assert!(!super::has_trailing_anchor(""));
    }

    // ── OutputBuffer::clear ─────────────────────────────────────────

    #[tokio::test]
    async fn clear_empties_buffer_and_returns_consumed() {
        let buf = OutputBuffer::for_tests();
        buf.append(b"hello world").await;
        let consumed = buf.clear().await;
        assert_eq!(consumed, "hello world");
        assert!(buf.remaining().await.is_empty());
    }

    #[tokio::test]
    async fn clear_advances_base_correctly() {
        let buf = OutputBuffer::for_tests();
        buf.append(b"hello world").await;
        let _ = buf.clear().await;
        buf.append(b"abc 123\n").await;
        let re = Regex::new(r"\d+").unwrap();
        let (m, _) = buf.consume_regex(&re).await.unwrap();
        // base should be 11 (from clear) + 4 (from "abc ") = absolute offset 15
        assert_eq!(m.start, 15);
        assert_eq!(m.end, 18);
    }

    #[tokio::test]
    async fn clear_drops_incomplete_utf8_trailing_sequence() {
        let (buf, builder, _rx) = wired_buffer();
        // U+1F389 PARTY POPPER, encoded as F0 9F 8E 89. Feed "ok" then only
        // the first two bytes of the codepoint — Utf8Stream holds them back.
        buf.append(b"ok").await;
        buf.append(&[0xF0, 0x9F]).await;
        let _ = buf.clear().await;
        let consumed = last_reset(&builder).expect("reset event");
        // Only the decoded prefix is emitted; the partial bytes are silently
        // held back (verified separately in clear_preserves_partial_utf8_in_buffer).
        assert_eq!(consumed, "ok");
    }

    #[tokio::test]
    async fn clear_consumed_equals_sum_of_grew_payloads() {
        let (buf, builder, _rx) = wired_buffer();
        buf.append(b"alpha ").await;
        buf.append(b"beta ").await;
        buf.append("gamma\n".as_bytes()).await;
        let grew_sum: String = all_grew(&builder).concat();
        let _ = buf.clear().await;
        let consumed = last_reset(&builder).expect("reset event");
        assert_eq!(consumed, grew_sum);
        assert_eq!(consumed, "alpha beta gamma\n");
    }

    #[tokio::test]
    async fn clear_preserves_partial_utf8_in_buffer() {
        let (buf, builder, _rx) = wired_buffer();
        // First two bytes of U+1F389 only — entire buffer is `pending`.
        buf.append(&[0xF0, 0x9F]).await;
        let _ = buf.clear().await;
        let consumed = last_reset(&builder).expect("reset event");
        assert_eq!(consumed, "");
        // Now finish the codepoint — Grew should fire with the completed char,
        // proving the partial bytes survived the reset.
        buf.append(&[0x8E, 0x89]).await;
        let grew: Vec<String> = all_grew(&builder);
        assert_eq!(grew.last().map(String::as_str), Some("\u{1F389}"));
    }

    // ── OutputBuffer::snapshot_tail ─────────────────────────────────

    #[tokio::test]
    async fn snapshot_tail_returns_truncated_tail() {
        let buf = OutputBuffer::for_tests();
        buf.append(b"hello world").await;
        let tail = buf.snapshot_tail(5).await;
        assert_eq!(tail, "...world");
    }

    #[tokio::test]
    async fn snapshot_tail_full_content_when_short() {
        let buf = OutputBuffer::for_tests();
        buf.append(b"hi").await;
        let tail = buf.snapshot_tail(80).await;
        assert_eq!(tail, "hi");
    }

    // ── check_fail_in_buffer ────────────────────────────────────────

    #[test]
    fn check_fail_in_buffer_regex_match() {
        let fp = FailPattern::Regex(Regex::new(r"ERROR").unwrap());
        let hit = check_fail_in_buffer("some ERROR here", &fp).unwrap();
        assert_eq!(hit.pattern, "ERROR");
        assert_eq!(hit.matched_text, "ERROR");
    }

    #[test]
    fn check_fail_in_buffer_regex_no_match() {
        let fp = FailPattern::Regex(Regex::new(r"ERROR").unwrap());
        assert!(check_fail_in_buffer("all good", &fp).is_none());
    }

    #[test]
    fn check_fail_in_buffer_literal_match() {
        let fp = FailPattern::Literal("FATAL".to_string());
        let hit = check_fail_in_buffer("got FATAL crash", &fp).unwrap();
        assert_eq!(hit.pattern, "FATAL");
        assert_eq!(hit.matched_text, "FATAL");
    }

    #[test]
    fn check_fail_in_buffer_literal_no_match() {
        let fp = FailPattern::Literal("FATAL".to_string());
        assert!(check_fail_in_buffer("all good", &fp).is_none());
    }
}