jumperless-mcp 0.1.0

MCP server for the Jumperless V5 — persistent USB-serial bridge exposing the firmware API to LLMs
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
//! MicroPython Raw REPL protocol client for the Jumperless V5.
//!
//! Implements the simple Raw REPL mode (Ctrl-A entry, Ctrl-D send, Ctrl-B exit).
//! Raw-paste mode (Ctrl-A + Ctrl-E with flow control) is intentionally NOT
//! implemented in v1 — most code blocks we send fit in serialport's buffer
//! comfortably. Revisit if Phase 0b.5 tools need to send >4KB code blocks.
//!
//! # Protocol reference
//! <https://docs.micropython.org/en/latest/reference/repl.html#raw-mode-and-raw-paste-mode>
//!
//! # Frame shape
//!
//! **Entry:** send `0x01` (Ctrl-A); expect `b"raw REPL; CTRL-B to exit\r\n>"`.
//!
//! **Execution:** write UTF-8 code bytes then `0x04` (Ctrl-D).
//! Response: `b"OK<stdout>\x04<stderr>\x04>"`.
//!
//! **Exit:** send `0x02` (Ctrl-B); returns to the friendly `>>>` REPL.

use std::time::Duration;

use std::io::{Read, Write};
use thiserror::Error;

// ── Protocol constants ─────────────────────────────────────────────────────────

/// Ctrl-A: enter raw REPL mode.
const CTRL_A: u8 = 0x01;
/// Ctrl-B: exit raw REPL mode (return to friendly `>>>` REPL).
const CTRL_B: u8 = 0x02;
/// Ctrl-C: KeyboardInterrupt — interrupt running Python code.
const CTRL_C: u8 = 0x03;
/// Ctrl-D: end-of-code / end-of-frame signal.
const CTRL_D: u8 = 0x04;

/// The prompt MicroPython emits after a successful Ctrl-A.
const RAW_MODE_PROMPT: &[u8] = b"raw REPL; CTRL-B to exit\r\n>";

/// Maximum bytes we'll buffer when reading a response frame.
/// Generous but bounded — prevents runaway reads on misbehaving firmware.
const MAX_FRAME_BYTES: usize = 1 << 17; // 128 KiB

/// How long to wait after the normalization sequence (Ctrl-C, Ctrl-C, Ctrl-B)
/// for the device to process the interrupts and emit any echo / traceback /
/// re-issued prompt before we send Ctrl-A. 100ms is generous on USB CDC
/// (typical processing < 5ms) but cheap and reliable.
const NORMALIZE_DRAIN_MS: u64 = 100;

/// Maximum bytes we'll buffer when reading the raw-mode entry prompt AFTER
/// the normalization sequence. Generous because the prologue may produce
/// significant echo (running-code traceback, paste-mode exit echoes, etc.).
/// 4096 covers any realistic case without enabling true runaway reads.
const MAX_PROMPT_BYTES_RELAXED: usize = 4096;

// ── Error type ─────────────────────────────────────────────────────────────────

/// Errors specific to Raw REPL protocol handling.
#[derive(Debug, Error)]
pub enum ReplError {
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),

    #[error("expected raw-mode prompt 'raw REPL; CTRL-B to exit\\r\\n>', got: {got:?}")]
    HandshakeMismatch { got: Vec<u8> },

    #[error("response frame did not start with 'OK', got: {got:?}")]
    FrameMissingOk { got: Vec<u8> },

    #[error("response frame missing 0x04 separator after stdout, got: {got:?}")]
    FrameMissingFirstSeparator { got: Vec<u8> },

    #[error("response frame missing 0x04 end-of-frame marker, got: {got:?}")]
    FrameMissingEndMarker { got: Vec<u8> },

    #[error("MicroPython error: {stderr}")]
    PythonError { stdout: String, stderr: String },

    #[error("ping failed: expected stdout {expected:?}, got {got:?}")]
    PingFailed { expected: String, got: String },
}

// ── Response type ──────────────────────────────────────────────────────────────

/// Parsed response from an [`exec_code`] call.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReplResponse {
    /// UTF-8 (lossy) decoded bytes printed by the code to stdout.
    pub stdout: String,
    /// UTF-8 (lossy) decoded traceback / error text, if any.
    pub stderr: String,
}

impl ReplResponse {
    /// Returns `true` if the device raised a MicroPython exception.
    pub fn is_error(&self) -> bool {
        !self.stderr.is_empty()
    }
}

// ── Frame parser (pure function — fully testable without hardware) ─────────────

/// Parse the response frame produced by a Ctrl-D send.
///
/// Frame shape: `b"OK<stdout>\x04<stderr>\x04>"`.
///
/// - The leading `b"OK"` is mandatory; its absence indicates a protocol
///   violation (device was not actually in raw mode, or sent an error
///   immediately).
/// - `<stdout>` may be empty (for code that prints nothing).
/// - The first `0x04` separates stdout from stderr.
/// - `<stderr>` may be empty (no exception was raised).
/// - The second `0x04` followed by `>` is the end-of-frame and re-issue of the
///   raw-mode ready prompt.
///
/// Both `stdout` and `stderr` are decoded as UTF-8 lossy (MicroPython may emit
/// raw bytes; we replace invalid sequences with U+FFFD rather than failing).
///
/// Returns [`ReplResponse`] on success, or an appropriate [`ReplError`] variant
/// if the frame is structurally malformed.
///
/// # Known limitation
///
/// The Raw REPL protocol uses 0x04 (Ctrl-D) as an in-band delimiter between
/// stdout and stderr in the response frame. If Python code emits a literal
/// 0x04 byte to stdout (e.g., `print(chr(4))` or binary-data output), this
/// parser will misparse: the embedded 0x04 will be treated as the
/// stdout/stderr separator. The parser cannot distinguish "data byte" from
/// "structural delimiter" because the protocol does not escape or length-prefix.
///
/// For Phase 0b.3 (liveness ping with `print(1+1)`), this cannot trigger —
/// output is pure ASCII. Phase 0b.5 (arbitrary user Python execution) will
/// need an escape strategy or migration to raw-paste mode (which has flow
/// control + length prefixes).
pub fn parse_response_frame(bytes: &[u8]) -> Result<ReplResponse, ReplError> {
    // ── Validate b"OK" prefix ─────────────────────────────────────────────────
    if bytes.len() < 2 || &bytes[..2] != b"OK" {
        return Err(ReplError::FrameMissingOk {
            got: bytes.to_vec(),
        });
    }
    let rest = &bytes[2..];

    // ── Find first 0x04 (stdout ↔ stderr separator) ───────────────────────────
    let sep1 = rest.iter().position(|&b| b == CTRL_D).ok_or_else(|| {
        ReplError::FrameMissingFirstSeparator {
            got: bytes.to_vec(),
        }
    })?;

    let stdout_bytes = &rest[..sep1];
    let after_sep1 = &rest[sep1 + 1..];

    // ── Find second 0x04 (end-of-frame marker), followed by b">" ─────────────
    //
    // We look for `0x04` in `after_sep1`. The `>` after it is the raw-mode
    // ready prompt and is consumed by this parse step (callers should NOT
    // expect the `>` to remain in the stream — it is part of the frame).
    let sep2 = after_sep1
        .iter()
        .position(|&b| b == CTRL_D)
        .ok_or_else(|| ReplError::FrameMissingEndMarker {
            got: bytes.to_vec(),
        })?;

    let stderr_bytes = &after_sep1[..sep2];

    Ok(ReplResponse {
        stdout: String::from_utf8_lossy(stdout_bytes).into_owned(),
        stderr: String::from_utf8_lossy(stderr_bytes).into_owned(),
    })
}

// ── I/O helpers ────────────────────────────────────────────────────────────────

/// Read bytes from `port` until `needle` appears at the end of the accumulated
/// buffer, or until `max_bytes` are consumed.
///
/// Returns the accumulated buffer (inclusive of the needle) on success.
/// Returns `Err(ReplError::HandshakeMismatch)` if `max_bytes` is exhausted
/// before the needle is found.
fn read_until_suffix<P: Read + ?Sized>(
    port: &mut P,
    needle: &[u8],
    max_bytes: usize,
) -> Result<Vec<u8>, ReplError> {
    let mut buf = Vec::with_capacity(needle.len() * 2);
    let mut byte = [0u8; 1];

    loop {
        port.read_exact(&mut byte).map_err(ReplError::Io)?;
        buf.push(byte[0]);

        if buf.len() >= needle.len() && buf.ends_with(needle) {
            return Ok(buf);
        }

        if buf.len() >= max_bytes {
            return Err(ReplError::HandshakeMismatch { got: buf });
        }
    }
}

/// Read bytes from `port` until the two-byte sequence `b"\x04>"` appears at
/// the end of the accumulated buffer, or until `max_bytes` are consumed.
///
/// This is the canonical end-of-frame marker for raw REPL responses.
fn read_until_frame_end<P: Read + ?Sized>(
    port: &mut P,
    max_bytes: usize,
) -> Result<Vec<u8>, ReplError> {
    // The end-of-frame sequence is 0x04 followed by b">". We re-use
    // read_until_suffix but must handle the I/O-error conversion correctly.
    read_until_suffix(port, b"\x04>", max_bytes).map_err(|e| match e {
        // HandshakeMismatch re-wrapped as FrameMissingEndMarker for better context.
        ReplError::HandshakeMismatch { got } => ReplError::FrameMissingEndMarker { got },
        other => other,
    })
}

// ── Public protocol API ────────────────────────────────────────────────────────

/// Send `Ctrl-A` and verify the raw-mode entry prompt.
///
/// On success the device is in raw REPL mode and ready to accept code.
/// The caller is responsible for exiting via [`exit_raw_mode`].
///
/// **Blocking.** Wrap in `tokio::task::spawn_blocking` when called from async
/// context.
pub fn enter_raw_mode<P: Read + Write + ?Sized>(port: &mut P) -> Result<(), ReplError> {
    // ── Device state normalization (mpremote-canonical sequence) ─────────────
    //
    // The device may be in any of: friendly REPL idle, friendly REPL running
    // user code, raw REPL, or paste mode. Ctrl-A in raw-mode is a documented
    // no-op (the device sends no prompt), so we MUST normalize to friendly
    // REPL before entering raw mode.
    //
    //   Ctrl-C × 2  → KeyboardInterrupt any running code (twice for safety
    //                 against the "first Ctrl-C lands during print()" race)
    //   Ctrl-B      → exit raw mode if in it (no-op in friendly mode)
    //   sleep 100ms → let the device process the interrupts and emit echo
    //                 (>>> prompt, KeyboardInterrupt traceback, etc.)
    //   Ctrl-A      → enter raw mode from known-friendly state
    //
    // After Ctrl-A the device emits b"raw REPL; CTRL-B to exit\r\n>". The
    // accumulated buffer in read_until_suffix will absorb whatever echo came
    // from the normalization sequence (raised to MAX_PROMPT_BYTES_RELAXED to
    // accommodate worst-case "user code was printing a lot" scenarios).
    //
    // Reference: https://docs.micropython.org/en/latest/reference/repl.html
    // mpremote source for the canonical implementation pattern.
    port.write_all(&[CTRL_C, CTRL_C, CTRL_B])
        .map_err(ReplError::Io)?;
    port.flush().map_err(ReplError::Io)?;
    std::thread::sleep(std::time::Duration::from_millis(NORMALIZE_DRAIN_MS));

    port.write_all(&[CTRL_A]).map_err(ReplError::Io)?;
    port.flush().map_err(ReplError::Io)?;

    let _received = read_until_suffix(port, RAW_MODE_PROMPT, MAX_PROMPT_BYTES_RELAXED)?;
    Ok(())
}

/// Send `Ctrl-B` to exit raw REPL mode and return to the friendly `>>>` REPL.
///
/// **Blocking.** Wrap in `tokio::task::spawn_blocking` when called from async
/// context.
pub fn exit_raw_mode<P: Write + ?Sized>(port: &mut P) -> Result<(), ReplError> {
    port.write_all(&[CTRL_B]).map_err(ReplError::Io)?;
    port.flush().map_err(ReplError::Io)?;
    Ok(())
}

/// Execute a Python code snippet in raw REPL mode.
///
/// The caller **must** have called [`enter_raw_mode`] before invoking this
/// function. After the call returns, the device is still in raw mode — send
/// another [`exec_code`] or call [`exit_raw_mode`] when done.
///
/// The code string is sent as UTF-8 bytes, followed by `Ctrl-D`. The response
/// frame is read and parsed via [`parse_response_frame`].
///
/// If MicroPython raised an exception, the returned [`ReplResponse`] will have
/// a non-empty `stderr`; [`ReplResponse::is_error`] returns `true`. This
/// function does NOT return an error in that case — the Python traceback is
/// plumbing, not a protocol failure. Callers that want to propagate Python
/// errors as Rust errors can check `resp.is_error()` and construct
/// `ReplError::PythonError` themselves.
///
/// **Blocking.** Wrap in `tokio::task::spawn_blocking` when called from async
/// context.
pub fn exec_code<P: Read + Write + ?Sized>(
    port: &mut P,
    code: &str,
) -> Result<ReplResponse, ReplError> {
    // Write code then signal end-of-code with Ctrl-D.
    port.write_all(code.as_bytes()).map_err(ReplError::Io)?;
    port.write_all(&[CTRL_D]).map_err(ReplError::Io)?;
    port.flush().map_err(ReplError::Io)?;

    // The response begins with b"OK" so we know the frame has started once we
    // see those two bytes. Then we read until b"\x04>" to capture the full frame.
    //
    // read_until_frame_end accumulates everything including the trailing b"\x04>",
    // so the buffer passed to parse_response_frame includes the end marker.
    let frame = read_until_frame_end(port, MAX_FRAME_BYTES)?;

    parse_response_frame(&frame)
}

/// Lightweight liveness check: execute `print(1+1)` and verify stdout is `"2\r\n"`.
///
/// The caller **must** have called [`enter_raw_mode`] before invoking this.
///
/// **Blocking.** Wrap in `tokio::task::spawn_blocking` when called from async
/// context.
pub fn ping<P: Read + Write + ?Sized>(port: &mut P) -> Result<(), ReplError> {
    let resp = exec_code(port, "print(1+1)")?;
    // MicroPython's print() appends \r\n.
    if resp.stdout.trim() == "2" {
        Ok(())
    } else if resp.is_error() {
        // MicroPython exception during ping — surface the traceback for
        // operator visibility. Distinguishes "device in bad REPL state" from
        // "device unresponsive" or "device returning wrong output".
        Err(ReplError::PythonError {
            stdout: resp.stdout,
            stderr: resp.stderr,
        })
    } else {
        // No exception, but stdout doesn't match "2" — device is responsive
        // but in a degraded state (firmware bug, RAM corruption, etc.).
        Err(ReplError::PingFailed {
            expected: "2".into(),
            got: resp.stdout.trim().to_string(),
        })
    }
}

// ── Post-timeout recovery helpers ─────────────────────────────────────────────

/// Drain any pending bytes from the serial port's read buffer.
///
/// Reads with a short timeout until the buffer is empty (TimedOut/WouldBlock).
/// Used after exec_code timeouts to clean up bytes the device emitted while
/// the host was no longer listening — without this, the next operation reads
/// stale bytes as the start of its response frame.
///
/// Returns the total number of bytes drained.
///
/// **Blocking.** Wrap in `tokio::task::spawn_blocking` when called from async
/// context.
pub fn drain_read_buffer(port: &mut dyn serialport::SerialPort) -> std::io::Result<usize> {
    let original_timeout = port.timeout();
    port.set_timeout(Duration::from_millis(50))?;
    let mut total = 0usize;
    let mut buf = [0u8; 256];
    loop {
        match port.read(&mut buf) {
            Ok(0) => break,
            Ok(n) => total += n,
            Err(e)
                if e.kind() == std::io::ErrorKind::TimedOut
                    || e.kind() == std::io::ErrorKind::WouldBlock =>
            {
                break
            }
            Err(e) => {
                // Restore timeout before returning error
                let _ = port.set_timeout(original_timeout);
                return Err(e);
            }
        }
    }
    port.set_timeout(original_timeout)?;
    Ok(total)
}

/// Send Ctrl-C (0x03) to abort any device-side script execution.
///
/// Used as part of the post-timeout cleanup: stops the still-running
/// Python interpreter on the device so the next exec_code starts clean.
///
/// **Blocking.** Wrap in `tokio::task::spawn_blocking` when called from async
/// context.
pub fn send_ctrl_c(port: &mut dyn serialport::SerialPort) -> std::io::Result<()> {
    port.write_all(&[0x03])?;
    port.flush()?;
    Ok(())
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::VecDeque;
    use std::io::{self, Read, Write};
    use std::time::Duration;

    // ── MockPort ──────────────────────────────────────────────────────────────

    /// Scripted in-memory Read+Write stub for testing protocol functions without
    /// real hardware.
    ///
    /// **Note:** This mock satisfies up to `buf.len()` bytes per `read()` call.
    /// Real `serialport` implementations commonly return short reads (1-8 bytes
    /// per call even when more are buffered). The production code uses
    /// `read_exact` (one byte at a time inside `read_until_suffix`), so the
    /// short-read difference does not affect the tested code paths. Future tests
    /// that exercise `read()` directly should construct a `MockPort` variant
    /// that simulates short reads.
    ///
    /// * `read_data` — bytes the "device" will return when `read_exact` is called.
    /// * `write_data` — bytes the test code wrote, captured for inspection.
    struct MockPort {
        read_data: VecDeque<u8>,
        pub write_data: Vec<u8>,
    }

    impl MockPort {
        fn new(read_bytes: impl Into<Vec<u8>>) -> Self {
            MockPort {
                read_data: VecDeque::from(read_bytes.into()),
                write_data: Vec::new(),
            }
        }
    }

    impl Read for MockPort {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            let n = buf.len().min(self.read_data.len());
            if n == 0 {
                // Simulate blocking port: UnexpectedEof when device has no more
                // scripted bytes. Tests must supply enough bytes.
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "MockPort: no more scripted bytes",
                ));
            }
            for (dst, src) in buf[..n].iter_mut().zip(self.read_data.drain(..n)) {
                *dst = src;
            }
            Ok(n)
        }
    }

    impl Write for MockPort {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.write_data.extend_from_slice(buf);
            Ok(buf.len())
        }
        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    // ── parse_response_frame tests (pure-function, no I/O) ────────────────────

    #[test]
    fn parse_simple_ok_response() {
        // exec("1+1") on the REPL would give "OK2\x04\x04>" because the REPL
        // evaluates and prints the result. Direct print: "OKhello\x04\x04>".
        // Here: arithmetic result echoed as stdout.
        let bytes = b"OK2\x04\x04>";
        let r = parse_response_frame(bytes).unwrap();
        assert_eq!(r.stdout, "2");
        assert_eq!(r.stderr, "");
        assert!(!r.is_error());
    }

    #[test]
    fn parse_response_with_stderr() {
        let bytes = b"OK\x04Traceback...\x04>";
        let r = parse_response_frame(bytes).unwrap();
        assert_eq!(r.stdout, "");
        assert_eq!(r.stderr, "Traceback...");
        assert!(r.is_error());
    }

    #[test]
    fn parse_response_missing_ok_returns_error() {
        let bytes = b"ERR\x04\x04>";
        let err = parse_response_frame(bytes).unwrap_err();
        assert!(
            matches!(err, ReplError::FrameMissingOk { .. }),
            "expected FrameMissingOk, got: {err:?}"
        );
    }

    #[test]
    fn parse_response_empty_bytes_returns_missing_ok() {
        let bytes = b"";
        let err = parse_response_frame(bytes).unwrap_err();
        assert!(matches!(err, ReplError::FrameMissingOk { .. }));
    }

    #[test]
    fn parse_response_missing_first_separator_returns_error() {
        // Has OK prefix but only one 0x04 (the end-marker), so no separator.
        // Actually parse_response_frame would interpret the single \x04 as the
        // first separator with empty stderr — we need NO \x04 at all.
        let bytes = b"OKsome output without any ctrl-d";
        let err = parse_response_frame(bytes).unwrap_err();
        assert!(
            matches!(err, ReplError::FrameMissingFirstSeparator { .. }),
            "expected FrameMissingFirstSeparator, got: {err:?}"
        );
    }

    #[test]
    fn parse_response_missing_end_marker_returns_error() {
        // Has one \x04 but not the second one.
        let bytes = b"OKsome output\x04stderr but no end marker";
        let err = parse_response_frame(bytes).unwrap_err();
        assert!(
            matches!(err, ReplError::FrameMissingEndMarker { .. }),
            "expected FrameMissingEndMarker, got: {err:?}"
        );
    }

    #[test]
    fn parse_response_with_print_output() {
        // print('hello') produces stdout = "hello\r\n"
        let bytes = b"OKhello\r\n\x04\x04>";
        let r = parse_response_frame(bytes).unwrap();
        assert_eq!(r.stdout, "hello\r\n");
        assert_eq!(r.stderr, "");
    }

    #[test]
    fn parse_response_empty_stdout_and_stderr() {
        // Code that produces no output and no error: exec("pass") or exec("x=1")
        let bytes = b"OK\x04\x04>";
        let r = parse_response_frame(bytes).unwrap();
        assert_eq!(r.stdout, "");
        assert_eq!(r.stderr, "");
        assert!(!r.is_error());
    }

    #[test]
    fn parse_response_with_multiple_lines_and_error() {
        let bytes = b"OKline1\r\nline2\r\n\x04Traceback (most recent call last):\r\n  File \"<stdin>\", line 2\r\nNameError: name 'x' is not defined\r\n\x04>";
        let r = parse_response_frame(bytes).unwrap();
        assert!(r.stdout.contains("line1"), "stdout: {:?}", r.stdout);
        assert!(r.stdout.contains("line2"), "stdout: {:?}", r.stdout);
        assert!(r.stderr.contains("NameError"), "stderr: {:?}", r.stderr);
        assert!(r.is_error());
    }

    #[test]
    fn parse_response_with_only_stderr() {
        // Code raises immediately with no stdout.
        let bytes = b"OK\x04ZeroDivisionError: division by zero\r\n\x04>";
        let r = parse_response_frame(bytes).unwrap();
        assert_eq!(r.stdout, "");
        assert!(r.stderr.contains("ZeroDivisionError"));
    }

    // ── enter_raw_mode tests (MockPort) ───────────────────────────────────────

    #[test]
    fn enter_raw_mode_succeeds_on_correct_prompt() {
        // Device sends the exact raw-mode prompt after Ctrl-A.
        let mut port = MockPort::new(b"raw REPL; CTRL-B to exit\r\n>".to_vec());
        enter_raw_mode(&mut port).unwrap();
        // Verify normalization sequence + Ctrl-A were written.
        assert_eq!(port.write_data, &[CTRL_C, CTRL_C, CTRL_B, CTRL_A]);
    }

    #[test]
    fn enter_raw_mode_succeeds_when_prompt_has_prefix() {
        // Real devices may echo `\r\n` or partial `>>>` before the prompt.
        let mut scripted = b"\r\n>>>".to_vec();
        scripted.extend_from_slice(b"raw REPL; CTRL-B to exit\r\n>");
        let mut port = MockPort::new(scripted);
        enter_raw_mode(&mut port).unwrap();
    }

    #[test]
    fn enter_raw_mode_fails_on_wrong_prompt() {
        // Device returns garbage — not a raw REPL capable device or wrong port.
        // Buffer must exceed MAX_PROMPT_BYTES_RELAXED (4096) to exhaust the
        // read limit and return HandshakeMismatch rather than UnexpectedEof.
        let mut port = MockPort::new(vec![b'X'; MAX_PROMPT_BYTES_RELAXED + 1]);
        let err = enter_raw_mode(&mut port).unwrap_err();
        assert!(
            matches!(err, ReplError::HandshakeMismatch { .. }),
            "expected HandshakeMismatch, got: {err:?}"
        );
    }

    #[test]
    fn enter_raw_mode_handles_device_already_in_raw_mode() {
        // Device was in raw mode (e.g., from prior unclean disconnect).
        // Ctrl-C/C/B normalization sequence is silent or produces minimal echo
        // in raw mode; then Ctrl-A triggers the prompt.
        let mut port = MockPort::new(b"raw REPL; CTRL-B to exit\r\n>".to_vec());
        enter_raw_mode(&mut port).unwrap();
    }

    #[test]
    fn enter_raw_mode_handles_device_running_code() {
        // Device was running user code (e.g. an infinite loop). Ctrl-C
        // interrupts and emits a KeyboardInterrupt traceback + friendly prompt.
        // Then Ctrl-B is a no-op in friendly mode. Then Ctrl-A produces the
        // raw-mode prompt.
        let mut scripted = Vec::new();
        scripted.extend_from_slice(b"\r\nTraceback (most recent call last):\r\n");
        scripted.extend_from_slice(b"  File \"<stdin>\", line 1, in <module>\r\n");
        scripted.extend_from_slice(b"KeyboardInterrupt: \r\n");
        scripted.extend_from_slice(b">>> ");
        // ↑ response to Ctrl-C/C; Ctrl-B is no-op in friendly mode.
        scripted.extend_from_slice(b"raw REPL; CTRL-B to exit\r\n>");
        // ↑ response to Ctrl-A.
        let mut port = MockPort::new(scripted);
        enter_raw_mode(&mut port).unwrap();
    }

    #[test]
    fn enter_raw_mode_handles_idle_friendly_repl() {
        // Device was in friendly REPL idle. Ctrl-C twice may echo >>> twice.
        // Ctrl-B is a no-op. Ctrl-A produces the raw-mode prompt.
        let mut scripted = Vec::new();
        scripted.extend_from_slice(b"\r\n>>> \r\n>>> ");
        scripted.extend_from_slice(b"raw REPL; CTRL-B to exit\r\n>");
        let mut port = MockPort::new(scripted);
        enter_raw_mode(&mut port).unwrap();
    }

    // ── exec_code + ping tests (MockPort) ─────────────────────────────────────

    #[test]
    fn exec_code_sends_code_and_ctrl_d() {
        // exec_code should write code bytes + 0x04, then read the frame.
        // Script the device response: "OK2\x04\x04>"
        let mut port = MockPort::new(b"OK2\x04\x04>".to_vec());
        let resp = exec_code(&mut port, "1+1").unwrap();
        assert_eq!(resp.stdout, "2");
        // Check bytes written: "1+1" + Ctrl-D
        assert_eq!(port.write_data, b"1+1\x04");
        // Guard against MockPort over-supply: all scripted bytes must be consumed.
        assert!(
            port.read_data.is_empty(),
            "MockPort had unconsumed bytes after exec_code: {:?}",
            port.read_data
        );
    }

    #[test]
    fn exec_code_returns_python_stderr_without_erroring() {
        // A Python exception should come back as ReplResponse.is_error() == true,
        // NOT as a Rust Err — exec_code itself does not fail on Python errors.
        let mut port = MockPort::new(b"OK\x04NameError: x\r\n\x04>".to_vec());
        let resp = exec_code(&mut port, "x").unwrap();
        assert_eq!(resp.stdout, "");
        assert!(resp.stderr.contains("NameError"));
        assert!(resp.is_error());
    }

    #[test]
    fn ping_succeeds_on_correct_response() {
        // print(1+1) on MicroPython gives "2\r\n" on stdout.
        let mut port = MockPort::new(b"OK2\r\n\x04\x04>".to_vec());
        ping(&mut port).unwrap();
    }

    #[test]
    fn ping_fails_on_wrong_output() {
        // If the device is broken and returns "3" instead of "2".
        let mut port = MockPort::new(b"OK3\r\n\x04\x04>".to_vec());
        let err = ping(&mut port).unwrap_err();
        assert!(
            matches!(err, ReplError::PingFailed { .. }),
            "expected PingFailed, got: {err:?}"
        );
    }

    #[test]
    fn ping_returns_python_error_on_exception() {
        // Synthetic frame: empty stdout, populated stderr — device raised an
        // exception during exec_code("print(1+1)").
        let mut port =
            MockPort::new(b"OK\x04ZeroDivisionError: division by zero\r\n\x04>".to_vec());
        let err = ping(&mut port).unwrap_err();
        match err {
            ReplError::PythonError { stdout, stderr } => {
                assert_eq!(stdout, "");
                assert!(stderr.contains("ZeroDivisionError"));
            }
            other => panic!("expected PythonError, got: {other:?}"),
        }
    }

    #[test]
    fn exit_raw_mode_sends_ctrl_b() {
        let mut port = MockPort::new(vec![]); // no reads expected
        exit_raw_mode(&mut port).unwrap();
        assert_eq!(port.write_data, &[CTRL_B]);
    }

    // ── Ceremony script MockPort round-trip tests ─────────────────────────────
    //
    // These tests verify that the ceremony scripts produce a clean protocol
    // exchange through a MockPort — correct framing, no Rust-level errors, and
    // no device-side Python exception in the simulated response. They do NOT
    // validate the visual output on the hardware; that requires live-hardware
    // smoke testing. The design brief for Phase 0b.3.5 explicitly called for
    // this "doesn't fail the protocol exchange" gate.

    #[test]
    fn connect_script_round_trips_through_mock_port() {
        use crate::ceremony::CEREMONY_CONNECT_SCRIPT;

        // Simulate the device acknowledging the script execution with an empty-
        // stdout, empty-stderr response: "OK\x04\x04>". The ceremony script only
        // runs side-effect Python (overlay/OLED calls); it does not print to
        // stdout, so this is the realistic device response.
        let mock_response = b"OK\x04\x04>".to_vec();
        let mut port = MockPort::new(mock_response);

        let resp = exec_code(&mut port, CEREMONY_CONNECT_SCRIPT).unwrap();
        assert!(
            !resp.is_error(),
            "connect ceremony script raised a Python exception in mock: stderr={:?}",
            resp.stderr
        );
        // Assert write-side correctness: exec_code must send the script bytes + Ctrl-D.
        let mut expected_write = CEREMONY_CONNECT_SCRIPT.as_bytes().to_vec();
        expected_write.push(0x04); // Ctrl-D terminator
        assert_eq!(
            port.write_data, expected_write,
            "exec_code did not send connect ceremony script + Ctrl-D"
        );
        // Guard against MockPort over-supply: all scripted bytes must be consumed.
        assert!(
            port.read_data.is_empty(),
            "MockPort had unconsumed bytes: {:?}",
            port.read_data
        );
    }

    #[test]
    fn disconnect_script_round_trips_through_mock_port() {
        use crate::ceremony::CEREMONY_DISCONNECT_SCRIPT;

        // Same rationale as connect: disconnect script is side-effect only,
        // no stdout output expected from the device.
        let mock_response = b"OK\x04\x04>".to_vec();
        let mut port = MockPort::new(mock_response);

        let resp = exec_code(&mut port, CEREMONY_DISCONNECT_SCRIPT).unwrap();
        assert!(
            !resp.is_error(),
            "disconnect ceremony script raised a Python exception in mock: stderr={:?}",
            resp.stderr
        );
        // Assert write-side correctness: exec_code must send the script bytes + Ctrl-D.
        let mut expected_write = CEREMONY_DISCONNECT_SCRIPT.as_bytes().to_vec();
        expected_write.push(0x04); // Ctrl-D terminator
        assert_eq!(
            port.write_data, expected_write,
            "exec_code did not send disconnect ceremony script + Ctrl-D"
        );
        // Guard against MockPort over-supply: all scripted bytes must be consumed.
        assert!(
            port.read_data.is_empty(),
            "MockPort had unconsumed bytes: {:?}",
            port.read_data
        );
    }

    // ── MockSerialPort ────────────────────────────────────────────────────────
    //
    // A mock that implements the full `serialport::SerialPort` trait so we can
    // test drain_read_buffer and send_ctrl_c, which take `&mut dyn SerialPort`.
    //
    // Implements the minimum needed to satisfy the trait; most methods return
    // `Err(serialport::Error::new(serialport::ErrorKind::Unknown, "mock"))`.
    // The methods actually exercised by our helpers (set_timeout, timeout, read,
    // write, flush) are fully implemented.

    struct MockSerialPort {
        /// Bytes the mock will return on read().
        /// When empty, returns TimedOut to simulate an idle buffer.
        read_data: VecDeque<u8>,
        /// Bytes written to the mock, captured for inspection.
        pub write_data: Vec<u8>,
        /// Timeout value tracked across set_timeout / timeout calls.
        pub timeout_value: Duration,
    }

    impl MockSerialPort {
        fn new(read_bytes: impl Into<Vec<u8>>) -> Self {
            MockSerialPort {
                read_data: VecDeque::from(read_bytes.into()),
                write_data: Vec::new(),
                timeout_value: Duration::from_millis(500),
            }
        }
    }

    impl Read for MockSerialPort {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            let n = buf.len().min(self.read_data.len());
            if n == 0 {
                // Empty buffer → simulate timeout (idle serial port)
                return Err(io::Error::new(
                    io::ErrorKind::TimedOut,
                    "mock: buffer empty",
                ));
            }
            for (dst, src) in buf[..n].iter_mut().zip(self.read_data.drain(..n)) {
                *dst = src;
            }
            Ok(n)
        }
    }

    impl Write for MockSerialPort {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.write_data.extend_from_slice(buf);
            Ok(buf.len())
        }
        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    fn mock_sp_err() -> serialport::Error {
        serialport::Error::new(serialport::ErrorKind::Unknown, "mock: not implemented")
    }

    impl serialport::SerialPort for MockSerialPort {
        fn name(&self) -> Option<String> {
            Some("mock".to_string())
        }
        fn baud_rate(&self) -> serialport::Result<u32> {
            Ok(115_200)
        }
        fn data_bits(&self) -> serialport::Result<serialport::DataBits> {
            Ok(serialport::DataBits::Eight)
        }
        fn flow_control(&self) -> serialport::Result<serialport::FlowControl> {
            Ok(serialport::FlowControl::None)
        }
        fn parity(&self) -> serialport::Result<serialport::Parity> {
            Ok(serialport::Parity::None)
        }
        fn stop_bits(&self) -> serialport::Result<serialport::StopBits> {
            Ok(serialport::StopBits::One)
        }
        fn timeout(&self) -> Duration {
            self.timeout_value
        }
        fn set_baud_rate(&mut self, _: u32) -> serialport::Result<()> {
            Err(mock_sp_err())
        }
        fn set_data_bits(&mut self, _: serialport::DataBits) -> serialport::Result<()> {
            Err(mock_sp_err())
        }
        fn set_flow_control(&mut self, _: serialport::FlowControl) -> serialport::Result<()> {
            Err(mock_sp_err())
        }
        fn set_parity(&mut self, _: serialport::Parity) -> serialport::Result<()> {
            Err(mock_sp_err())
        }
        fn set_stop_bits(&mut self, _: serialport::StopBits) -> serialport::Result<()> {
            Err(mock_sp_err())
        }
        fn set_timeout(&mut self, timeout: Duration) -> serialport::Result<()> {
            self.timeout_value = timeout;
            Ok(())
        }
        fn write_request_to_send(&mut self, _: bool) -> serialport::Result<()> {
            Err(mock_sp_err())
        }
        fn write_data_terminal_ready(&mut self, _: bool) -> serialport::Result<()> {
            Err(mock_sp_err())
        }
        fn read_clear_to_send(&mut self) -> serialport::Result<bool> {
            Err(mock_sp_err())
        }
        fn read_data_set_ready(&mut self) -> serialport::Result<bool> {
            Err(mock_sp_err())
        }
        fn read_ring_indicator(&mut self) -> serialport::Result<bool> {
            Err(mock_sp_err())
        }
        fn read_carrier_detect(&mut self) -> serialport::Result<bool> {
            Err(mock_sp_err())
        }
        fn bytes_to_read(&self) -> serialport::Result<u32> {
            Ok(self.read_data.len() as u32)
        }
        fn bytes_to_write(&self) -> serialport::Result<u32> {
            Ok(0)
        }
        fn clear(&self, _: serialport::ClearBuffer) -> serialport::Result<()> {
            Err(mock_sp_err())
        }
        fn try_clone(&self) -> serialport::Result<Box<dyn serialport::SerialPort>> {
            Err(mock_sp_err())
        }
        fn set_break(&self) -> serialport::Result<()> {
            Err(mock_sp_err())
        }
        fn clear_break(&self) -> serialport::Result<()> {
            Err(mock_sp_err())
        }
    }

    // ── drain_read_buffer tests ───────────────────────────────────────────────

    /// drain_read_buffer drains all available bytes and returns the count.
    #[test]
    fn drain_read_buffer_consumes_all_bytes() {
        let mut port = MockSerialPort::new(b"stale garbage bytes".to_vec());
        let drained = drain_read_buffer(&mut port).unwrap();
        assert_eq!(drained, 19, "should drain all 19 bytes");
        assert!(
            port.read_data.is_empty(),
            "read_data should be empty after drain"
        );
    }

    /// drain_read_buffer on an empty buffer returns 0 (no error).
    #[test]
    fn drain_read_buffer_empty_returns_zero() {
        let mut port = MockSerialPort::new(b"".to_vec());
        let drained = drain_read_buffer(&mut port).unwrap();
        assert_eq!(drained, 0, "empty buffer should drain 0 bytes");
    }

    /// drain_read_buffer restores the original timeout after draining.
    #[test]
    fn drain_read_buffer_restores_timeout() {
        let mut port = MockSerialPort::new(b"abc".to_vec());
        port.timeout_value = Duration::from_millis(500);
        drain_read_buffer(&mut port).unwrap();
        assert_eq!(
            port.timeout_value,
            Duration::from_millis(500),
            "timeout must be restored to original 500ms after drain"
        );
    }

    // ── send_ctrl_c tests ─────────────────────────────────────────────────────

    /// send_ctrl_c writes exactly one 0x03 byte and flushes.
    #[test]
    fn send_ctrl_c_writes_ctrl_c_byte() {
        let mut port = MockSerialPort::new(b"".to_vec());
        send_ctrl_c(&mut port).unwrap();
        assert_eq!(
            port.write_data,
            &[0x03],
            "send_ctrl_c must write exactly 0x03 (Ctrl-C)"
        );
    }
}