newt-core 0.8.0

Newt-Agent core types, errors, and the NeMoCode-style tier router
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
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use crossterm::style::ResetColor;
use std::io::{self, IsTerminal, Write};
use std::marker::PhantomData;
use std::time::Duration;

use super::{PromptWindow, ACTIVE_INPUT_CT};

pub const MODAL_CONTROL_HINT: &str = "Esc=back · Ctrl-C/Ctrl-D=exit";

/// The input glyph a modal draws its answer line behind. Shares the chevron
/// morphology of the chat prompt (`newt_tui::prompt`) so a modal reads as the
/// same input surface the user already types at, rather than a second style of
/// prompt stacked under it.
pub const MODAL_INPUT_GLYPH: &str = "❯ ";

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PromptLine {
    Line(String),
    Back,
    Exit,
    Eof,
}

/// The shared raw-mode guard (C2b, #1891): promoted out of this module to
/// `tty::raw_mode` when the RichTUI interaction frame needed it too. Its doc
/// carries the #1770 reasoning this module paid for.
use super::raw_mode::RawModeGuard as RawGuard;

/// Classify one submitted headless line (the piped/non-TTY branch, after its
/// EOF check): a line that is exactly the literal ESC byte is the piped
/// stand-in for the Back control; anything else — including an empty
/// submission — is an answer, with the trailing newline family trimmed. Pure
/// so the piped convention is testable without a terminal or a stdin read
/// (#1823 A0 freeze; the Ok(0) => Eof arm above it stays in the caller).
fn classify_headless_prompt_line(line: &str) -> PromptLine {
    let line = line.trim_end_matches(['\r', '\n']);
    if line == "\u{1b}" {
        PromptLine::Back
    } else {
        PromptLine::Line(line.into())
    }
}

/// Read a line while `window` exclusively owns the terminal, showing what is
/// typed according to `echo`.
///
/// The piped branch below echoes NOTHING either way, so `echo` is a
/// TTY-branch policy: a pipe never renders the value, and a secret read from
/// one is as safe as an ordinary answer.
pub fn read_prompt_window_line(
    window: &PromptWindow,
    prompt: &str,
    echo: Echo,
) -> io::Result<PromptLine> {
    if !io::stdin().is_terminal() || !window.output_is_terminal() {
        window.ask(prompt)?;
        let mut line = String::new();
        if window.read_line_into(&mut line)? == 0 {
            return Ok(PromptLine::Eof);
        }
        return Ok(classify_headless_prompt_line(&line));
    }

    // Check the existing question capability before any config migration;
    // a refused/protocol window must not consume and silence its report.
    window.ensure_can_ask()?;
    let result = {
        let mut notices = Vec::new();
        let accent = modal_accent_enabled(&mut |notice| notices.push(notice));
        for notice in notices {
            if std::io::stderr().is_terminal() {
                // The window already owns the line. Do not re-enter the
                // arbiter through Notice::emit while this owner is active.
                window.notice(&notice.line())?;
            } else {
                notice.diagnostic(crate::tty::LineCaps::None, false, std::io::stderr())?;
            }
        }
        // Keep normal newline translation while delivering permanent notices;
        // the prompt's raw editor begins only once those lines are complete.
        let _guard = take_modal_ownership(window)?;
        window.ask(&render(prompt, "", true, accent)?)?;
        let mut value = String::new();
        loop {
            let key = match event::read()? {
                Event::Key(key) if key.kind != KeyEventKind::Release => key,
                Event::Paste(text) => {
                    value.extend(text.chars().filter(|ch| !ch.is_control()));
                    window.ask(&render(prompt, &echo.display(&value), false, accent)?)?;
                    continue;
                }
                _ => continue,
            };
            if let Some(line) = prompt_control(&key) {
                break line;
            }
            match key.code {
                KeyCode::Enter => break PromptLine::Line(value),
                KeyCode::Backspace => {
                    value.pop();
                    window.ask(&render(prompt, &echo.display(&value), false, accent)?)?;
                }
                KeyCode::Char(ch)
                    if !key.modifiers.contains(KeyModifiers::ALT)
                        && !key.modifiers.contains(KeyModifiers::CONTROL) =>
                {
                    value.push(ch);
                    window.ask(&render(prompt, &echo.display(&value), false, accent)?)?;
                }
                _ => {}
            }
        }
    };
    window.notice("")?;
    Ok(result)
}

/// A pollable source of terminal control keys during a prompt wait. The trait is
/// the test seam for the web-decision reader-recovery lifecycle (defect 1): a
/// fake implementation can script `Err`/`Back`/`Exit`/`None` sequences without a
/// real terminal, so the gate's recovery logic is unit-testable in the
/// fully-mocked tier. Real terminals use [`PromptControlReader`].
pub trait ControlReader {
    /// Poll for a control key for up to `timeout`. `Ok(None)` on no input;
    /// `Ok(Some(_))` on a control/line/EOF event; `Err` on an I/O failure (an
    /// [`io::ErrorKind::Interrupted`] error is transient and should be retried
    /// on the SAME reader; any other error means the reader is broken).
    fn poll(&mut self, timeout: Duration) -> io::Result<Option<PromptLine>>;
}

/// Holds raw mode for as long as the reader lives — the guard is here for
/// its `Drop`, which is the whole point of owning it.
pub struct PromptControlReader<'w> {
    _raw: RawGuard,
    _window: PhantomData<&'w PromptWindow>,
}

pub fn modal_prompt_controls<'w>(window: &'w PromptWindow) -> io::Result<PromptControlReader<'w>> {
    Ok(PromptControlReader {
        _raw: take_modal_ownership(window)?,
        _window: PhantomData,
    })
}

impl ControlReader for PromptControlReader<'_> {
    fn poll(&mut self, timeout: Duration) -> io::Result<Option<PromptLine>> {
        if !event::poll(timeout)? {
            return Ok(None);
        }
        match event::read()? {
            Event::Key(key) if key.kind != KeyEventKind::Release => Ok(prompt_control(&key)),
            _ => Ok(None),
        }
    }
}

fn prompt_control(key: &KeyEvent) -> Option<PromptLine> {
    let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
    match key.code {
        KeyCode::Char(ch) if ctrl && matches!(ch, 'c' | 'd') => Some(PromptLine::Exit),
        KeyCode::Esc => Some(PromptLine::Back),
        _ => None,
    }
}

/// What a modal read SHOWS of what has been typed.
///
/// A required parameter of [`read_prompt_window_line`], not a default and not
/// a `bool`. A secret prompt that echoes is not a cosmetic defect — the key
/// lands in the scrollback, and from there in whatever captured it. Making
/// the policy unspellable-by-omission is the cheapest way to keep that from
/// being one forgotten argument away, and the interaction path never spells
/// it by hand at all: `present_on_terminal` derives it from the definition,
/// so a `ControlKind::Secret` masks itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Echo {
    /// Show the characters typed. Every ordinary prompt.
    Chars,
    /// Show one `*` per character. A secret still gets keystroke feedback —
    /// a fully silent prompt reads as a hung terminal, per field testing —
    /// without ever showing the value.
    Stars,
}

impl Echo {
    /// What to DISPLAY for `value` under this policy.
    ///
    /// Public because the property worth testing is "the value never appears
    /// in what is shown", and that belongs to callers who ask for secrets —
    /// `newt-tui`'s credential contract asserts it over the real planted key.
    ///
    /// Counts characters, not bytes: a multi-byte key would otherwise draw
    /// more stars than it has characters and leak its byte length.
    #[must_use]
    pub fn display(self, value: &str) -> String {
        match self {
            Self::Chars => value.to_string(),
            Self::Stars => "*".repeat(value.chars().count()),
        }
    }
}

fn render(prompt: &str, value: &str, first: bool, accent: bool) -> io::Result<String> {
    let mut out = Vec::new();
    // A modal can arrive directly after arbitrarily-styled tool output. Take
    // ownership of the foreground before drawing any content so the dialog
    // cannot inherit that output's green/grey/etc. The piped branch never
    // calls this renderer, so canonical/headless text stays ANSI-free.
    crossterm::queue!(out, ResetColor)?;
    if first {
        match prompt.rsplit_once('\n') {
            Some((body, answer_row)) => {
                write!(out, "{}\r\n", body.replace('\n', "\r\n"))?;
                write_answer_row(&mut out, answer_row, accent)?;
            }
            None => write_answer_row(&mut out, prompt, accent)?,
        }
    } else {
        crossterm::queue!(
            out,
            crossterm::cursor::MoveToColumn(0),
            crossterm::terminal::Clear(crossterm::terminal::ClearType::CurrentLine)
        )?;
        write_answer_row(
            &mut out,
            prompt.rsplit_once('\n').map_or(prompt, |x| x.1),
            accent,
        )?;
    }
    write!(out, "{value}")?;
    String::from_utf8(out).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
}

/// Draw the final input row. The semantic prompt remains plain text; only the
/// terminal view promotes its active chevron into the shared input accent.
fn write_answer_row(out: &mut Vec<u8>, row: &str, accent: bool) -> io::Result<()> {
    if let Some(crossterm::style::Color::Rgb { r, g, b }) = answer_row_accent(row, accent) {
        // Serialize the resolved policy directly. Crossterm's color command
        // independently memoizes NO_COLOR, which would otherwise suppress an
        // explicit NEWT_COLOR=always after the application had already
        // resolved that explicit flag as the winner.
        write!(out, "\x1b[38;2;{r};{g};{b}m{row}\x1b[0m")?;
    } else {
        write!(out, "{row}")?;
    }
    Ok(())
}

fn answer_row_accent(row: &str, accent: bool) -> Option<crossterm::style::Color> {
    (accent && row == MODAL_INPUT_GLYPH).then_some(ACTIVE_INPUT_CT)
}

/// Whether this interactive TTY should use the active-input accent.
///
/// This mirrors the application's documented runtime precedence without
/// pulling a TUI configuration object into the terminal primitive. An
/// explicit `NEWT_COLOR` wins; otherwise either `NO_COLOR` or `TERM=dumb`
/// disables the accent. The caller is already in the TTY-only branch, so
/// `auto` means color is available here.
fn modal_accent_enabled(report: &mut dyn FnMut(crate::tty::Notice<'static>)) -> bool {
    // Opening a visual prompt must not republish scratch/tool/tenacity/etc.
    // globals. Runtime startup owns publication; this path only reads one
    // resolved TUI field.
    let cfg_color = crate::Config::resolve_runtime_unpublished(report)
        .ok()
        .and_then(|config| config.tui.as_ref().map(|tui| tui.color))
        .unwrap_or_default();
    modal_accent_enabled_with(&|key| std::env::var(key).ok(), cfg_color)
}

fn modal_accent_enabled_with(
    get_env: &dyn Fn(&str) -> Option<String>,
    cfg_color: crate::ColorMode,
) -> bool {
    if let Some(mode) =
        get_env("NEWT_COLOR").and_then(|value| crate::ColorMode::from_keyword(&value))
    {
        return mode.forced().unwrap_or(true);
    }
    if get_env("NO_COLOR").is_some() || get_env("TERM").as_deref() == Some("dumb") {
        return false;
    }
    cfg_color.forced().unwrap_or(true)
}

#[cfg(test)]
mod visual_style {
    use super::{
        answer_row_accent, modal_accent_enabled_with, render, ACTIVE_INPUT_CT, MODAL_INPUT_GLYPH,
    };

    /// A modal can open immediately after arbitrarily styled tool output. Its
    /// body must first return to the terminal default, then only its active
    /// answer chevron gets the input accent, and the typed value starts from
    /// the default again. Otherwise the whole dialog inherits (for example)
    /// a green file-preview tint and reads as ordinary tool output.
    #[test]
    fn the_modal_owns_its_body_and_active_answer_colors() {
        let prompt = format!("Prompt — Write this file? [y/N]\n{MODAL_INPUT_GLYPH}");
        let rendered = render(&prompt, "y", true, true).expect("render");

        assert_eq!(
            rendered,
            "\x1b[0mPrompt — Write this file? [y/N]\r\n\
             \x1b[38;2;255;165;90m❯ \x1b[0my"
        );
        assert_eq!(
            answer_row_accent(MODAL_INPUT_GLYPH, true),
            Some(ACTIVE_INPUT_CT)
        );
        assert_eq!(answer_row_accent(MODAL_INPUT_GLYPH, false), None);
    }

    /// Redraws repaint only the answer row. They must repeat the same explicit
    /// color ownership instead of relying on whatever SGR state the first draw
    /// happened to leave behind.
    #[test]
    fn answer_row_redraw_reasserts_the_active_accent_and_resets_before_value() {
        let prompt = format!("Prompt — Write this file? [y/N]\n{MODAL_INPUT_GLYPH}");
        let rendered = render(&prompt, "yes", false, true).expect("render");

        assert!(
            rendered.ends_with("\x1b[38;2;255;165;90m❯ \x1b[0myes"),
            "answer row did not own its style: {rendered:?}"
        );
        assert!(
            rendered.starts_with("\x1b[0m"),
            "did not reset inherited style"
        );
        assert!(!rendered.contains("Write this file"), "redrew the body too");
    }

    #[test]
    fn long_answer_and_backspace_repaint_one_stable_no_wrap_row() {
        let body = crate::tty::wrap_line(
            "Prompt — choose a destination whose label needs several rows",
            10,
        )
        .join("\n");
        let prompt = format!("{body}\n{MODAL_INPUT_GLYPH}");
        let long_value = "abcdefghijklmnopqrstuvwxyz";
        let after_backspace = &long_value[..long_value.len() - 1];
        let long = render(&prompt, long_value, false, true).expect("long redraw");
        let shorter = render(&prompt, after_backspace, false, true).expect("backspace redraw");

        let mut anchor = Vec::new();
        crossterm::queue!(
            anchor,
            crossterm::style::ResetColor,
            crossterm::cursor::MoveToColumn(0),
            crossterm::terminal::Clear(crossterm::terminal::ClearType::CurrentLine)
        )
        .expect("answer-row anchor");
        let anchor = String::from_utf8(anchor).expect("anchor is UTF-8");

        for (redraw, value) in [(&long, long_value), (&shorter, after_backspace)] {
            assert!(
                redraw.starts_with(&anchor),
                "each edit must return to and clear the same answer row: {redraw:?}"
            );
            assert!(redraw.ends_with(value), "typed value was not repainted");
            assert!(
                !redraw.contains("\r\n"),
                "answer redraw must never advance into another row: {redraw:?}"
            );
            assert!(
                !redraw.contains("\x1b[?7h"),
                "answer redraw must not enable terminal autowrap: {redraw:?}"
            );
        }
    }

    #[test]
    fn modal_accent_obeys_the_runtime_color_precedence() {
        let env = |pairs: &[(&str, &str)]| {
            let pairs = pairs
                .iter()
                .map(|(key, value)| ((*key).to_string(), (*value).to_string()))
                .collect::<Vec<_>>();
            move |key: &str| {
                pairs
                    .iter()
                    .find(|(candidate, _)| candidate == key)
                    .map(|(_, value)| value.clone())
            }
        };

        assert!(modal_accent_enabled_with(&env(&[]), crate::ColorMode::Auto));
        assert!(!modal_accent_enabled_with(
            &env(&[("NO_COLOR", "1")]),
            crate::ColorMode::Always,
        ));
        assert!(!modal_accent_enabled_with(
            &env(&[("TERM", "dumb")]),
            crate::ColorMode::Always,
        ));
        assert!(modal_accent_enabled_with(
            &env(&[
                ("NEWT_COLOR", "always"),
                ("NO_COLOR", "1"),
                ("TERM", "dumb"),
            ]),
            crate::ColorMode::Never
        ));
        assert!(!modal_accent_enabled_with(
            &env(&[("NEWT_COLOR", "mono"), ("TERM", "xterm-256color"),]),
            crate::ColorMode::Always
        ));
        assert!(!modal_accent_enabled_with(
            &env(&[]),
            crate::ColorMode::Never
        ));
        assert!(!modal_accent_enabled_with(
            &env(&[]),
            crate::ColorMode::Mono
        ));
        assert!(modal_accent_enabled_with(&env(&[]), crate::ColorMode::Dark));
    }

    #[test]
    fn modal_color_lookup_uses_the_non_publishing_config_path() {
        let production = include_str!("modal.rs")
            .split("#[cfg(test)]")
            .next()
            .expect("production source");
        let body = production
            .split("fn modal_accent_enabled(")
            .nth(1)
            .and_then(|tail| tail.split("\n}\n").next())
            .expect("modal_accent_enabled body");
        assert!(
            body.contains("Config::resolve_runtime_unpublished(report)"),
            "opening a visual prompt must not publish process-global runtime settings: {body}"
        );
        assert!(
            !body.contains("Config::resolve("),
            "the publishing compatibility resolver returned to the visual path: {body}"
        );
    }
}

fn take_modal_ownership(window: &PromptWindow) -> io::Result<RawGuard> {
    if !io::stdin().is_terminal() || !window.output_is_terminal() {
        return Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "terminal required",
        ));
    }
    RawGuard::enter()
}

#[cfg(all(test, unix))]
mod raw_guard_tests {
    use super::RawGuard;

    /// stdin as a real pty for the duration of a test: `RawGuard` operates on
    /// `STDIN_FILENO`, and only a terminal has termios. Restores fd 0 on drop.
    struct StdinPty {
        saved: libc::c_int,
        master: libc::c_int,
    }

    impl StdinPty {
        fn install() -> Self {
            // SAFETY: openpty + dup2 on descriptors this test owns; restored
            // in Drop.
            unsafe {
                let (mut master, mut slave) = (-1, -1);
                assert_eq!(
                    libc::openpty(
                        &mut master,
                        &mut slave,
                        std::ptr::null_mut(),
                        std::ptr::null_mut::<libc::termios>(),
                        std::ptr::null_mut::<libc::winsize>()
                    ),
                    0
                );
                let saved = libc::dup(0);
                assert!(libc::dup2(slave, 0) >= 0);
                libc::close(slave);
                Self { saved, master }
            }
        }
        fn lflag() -> libc::tcflag_t {
            // SAFETY: tcgetattr into a zeroed termios.
            unsafe {
                let mut t: libc::termios = std::mem::zeroed();
                assert_eq!(libc::tcgetattr(0, &mut t), 0);
                t.c_lflag
            }
        }
        fn set_canonical_echo(on: bool) {
            // SAFETY: termios round-trip on fd 0 (our pty slave).
            unsafe {
                let mut t: libc::termios = std::mem::zeroed();
                assert_eq!(libc::tcgetattr(0, &mut t), 0);
                if on {
                    t.c_lflag |= libc::ICANON | libc::ECHO;
                } else {
                    t.c_lflag &= !(libc::ICANON | libc::ECHO);
                }
                assert_eq!(libc::tcsetattr(0, libc::TCSANOW, &t), 0);
            }
        }
    }

    impl Drop for StdinPty {
        fn drop(&mut self) {
            // SAFETY: putting fd 0 back and closing what we opened.
            unsafe {
                libc::dup2(self.saved, 0);
                libc::close(self.saved);
                libc::close(self.master);
            }
        }
    }

    /// The bug (#1669 cockpit): with crossterm's process-global raw-mode
    /// state already set by another owner, `enable_raw_mode` is a no-op, so a
    /// modal opened over a canonical+echo tty stayed canonical — keys buffered
    /// until Enter and echoed by the kernel over the editor. The guard must
    /// take raw mode by ITSELF, whatever crossterm believes.
    #[serial_test::serial(tty_arbiter)]
    #[test]
    fn the_guard_takes_raw_mode_regardless_of_crossterms_global_state() {
        let _stdin = StdinPty::install();
        StdinPty::set_canonical_echo(true);
        // Simulate the cockpit: crossterm already thinks raw mode is on.
        let _ = crossterm::terminal::enable_raw_mode();
        // …but the tty is canonical+echo (the line-reader path just set it).
        StdinPty::set_canonical_echo(true);
        assert!(
            StdinPty::lflag() & libc::ICANON != 0,
            "precondition: canonical"
        );
        {
            let _guard = RawGuard::enter().expect("raw");
            let l = StdinPty::lflag();
            assert_eq!(
                l & libc::ICANON,
                0,
                "the modal's read must be non-canonical"
            );
            assert_eq!(
                l & libc::ECHO,
                0,
                "the kernel must not echo over the editor"
            );
        }
        // Restored to EXACTLY the prior state — canonical+echo, which the
        // enclosing `StdinToken` then restores in turn.
        let l = StdinPty::lflag();
        assert!(
            l & libc::ICANON != 0 && l & libc::ECHO != 0,
            "prior mode restored on drop"
        );
        let _ = crossterm::terminal::disable_raw_mode();
    }
}

/// A0 freeze (#1823): the piped/headless prompt-line convention, pinned. The
/// deliberately different terminal path (key-by-key with prompt_control) has
/// its own weekly PTY tier; THIS is the contract `newt solve`-when-piped and
/// the eval harness rely on.
///
/// Boundary of this pin: these tests exercise the pure classifier directly;
/// the guard that `read_prompt_window_line`'s non-TTY branch still CALLS it
/// is the dead-code lint under the zero-warnings gate (the fn's only
/// production caller is that branch). The C0/C1 slice that reworks the
/// branch inherits responsibility for re-pinning the wiring.
#[cfg(test)]
mod headless_line_tests {
    use super::*;

    #[test]
    fn a_literal_esc_line_is_the_piped_back_control() {
        assert_eq!(classify_headless_prompt_line("\u{1b}\n"), PromptLine::Back);
        assert_eq!(classify_headless_prompt_line("\u{1b}"), PromptLine::Back);
    }

    #[test]
    fn an_answer_keeps_its_content_and_loses_only_the_newline_family() {
        assert_eq!(
            classify_headless_prompt_line("qwen2.5-coder:7b\r\n"),
            PromptLine::Line("qwen2.5-coder:7b".into())
        );
        // Interior whitespace is the answer's own business.
        assert_eq!(
            classify_headless_prompt_line("  padded  \n"),
            PromptLine::Line("  padded  ".into())
        );
    }

    #[test]
    fn an_explicitly_empty_submission_is_an_empty_answer_not_a_control() {
        // EOF (Ok(0)) is classified UPSTREAM as PromptLine::Eof; an empty line
        // that WAS submitted stays an answer — the distinction
        // request_user_input's typed outcomes depend on.
        assert_eq!(
            classify_headless_prompt_line("\n"),
            PromptLine::Line(String::new())
        );
    }

    #[test]
    fn esc_with_trailing_content_is_an_answer_not_back() {
        assert_eq!(
            classify_headless_prompt_line("\u{1b}[A\n"),
            PromptLine::Line("\u{1b}[A".into())
        );
    }
}

/// **The wiring pin A0 deferred to this slice** (C0b, #1860).
///
/// `headless_line_tests` above exercises the pure classifier directly, and
/// its own doc records the boundary: *"the guard that
/// `read_prompt_window_line`'s non-TTY branch still CALLS it is the
/// dead-code lint … The C0/C1 slice that reworks the branch inherits
/// responsibility for re-pinning the wiring."* C0b discharges that.
///
/// The dead-code lint is a weak guard for this: it proves the function has
/// SOME caller, not that the piped branch is the caller, so moving the call
/// into a test helper would keep the lint quiet while the piped convention
/// silently stopped applying.
///
/// **C0b changes nothing here.** The epic's global acceptance criterion —
/// *"Headless/protocol modes never wait, choose defaults, or emit terminal
/// bytes"* — and this A0 freeze do not conflict, because `!is_terminal()` is
/// a property of a file descriptor and not a mode. This branch serves a
/// PIPED-but-ANSWERED session (the eval harness, `printf … | newt solve`)
/// where a writer is present and an answer is coming; the epic's criterion
/// governs headless/protocol modes, which never construct a `PromptWindow`
/// at all and are served by `crate::markup::headless`. The same C0 bullet
/// that carries the criterion also says to *preserve pipe behavior*, which
/// only coheres under that reading.
#[cfg(test)]
mod c0b_wiring {
    /// The production half of this file, with the test modules removed.
    fn production_source() -> String {
        include_str!("modal.rs")
            .split("#[cfg(test)]")
            .next()
            .expect("the production half")
            .to_string()
            + include_str!("modal.rs")
                .split("#[cfg(all(test, unix))]")
                .next()
                .expect("the production half")
    }

    /// The body of `fn <name>`, by brace depth.
    fn function_body(source: &str, name: &str) -> Option<String> {
        let anchor = format!("fn {name}(");
        let start = source.find(&anchor)?;
        let mut depth = 0i32;
        let mut opened = false;
        let mut body = String::new();
        for ch in source[start..].chars() {
            body.push(ch);
            match ch {
                '{' => {
                    depth += 1;
                    opened = true;
                }
                '}' => depth -= 1,
                _ => {}
            }
            if opened && depth <= 0 {
                break;
            }
        }
        opened.then_some(body)
    }

    /// **The piped branch still classifies through the frozen convention.**
    #[test]
    fn the_non_tty_branch_still_calls_the_frozen_classifier() {
        let source = production_source();
        let body = function_body(&source, "read_prompt_window_line")
            .expect("`fn read_prompt_window_line` not found at all");
        assert!(
            body.contains("is_terminal()"),
            "the non-TTY branch is gone from the reader: {body}"
        );
        assert!(
            body.contains("classify_headless_prompt_line(&line)"),
            "the piped branch no longer routes through the A0-frozen \
             classifier — the convention `newt solve`-when-piped and the eval \
             harness rely on is silently not applying: {body}"
        );
        // The EOF arm stays upstream of the classifier, which is what makes
        // an explicitly-submitted empty line distinguishable from Ctrl-D.
        assert!(
            body.contains("PromptLine::Eof"),
            "the Ok(0) => Eof arm left the reader: {body}"
        );
    }

    /// **Anti-vacuous twin.** The extractor must fail on a branch that
    /// stopped calling the classifier, or the guard above passes on any
    /// file it cannot parse.
    #[test]
    fn the_wiring_guard_notices_a_branch_that_stopped_classifying() {
        let rewired = "fn read_prompt_window_line(w: &W, p: &str) -> R {\n\
                       if !io::stdin().is_terminal() {\n\
                           return Ok(PromptLine::Line(line));\n\
                       }\n\
                       }";
        let body = function_body(rewired, "read_prompt_window_line").expect("body");
        assert!(
            !body.contains("classify_headless_prompt_line(&line)"),
            "the twin's fixture already classifies, so it proves nothing"
        );
        // ...and the real one does, so the guard discriminates.
        let real = production_source();
        assert!(function_body(&real, "read_prompt_window_line")
            .expect("body")
            .contains("classify_headless_prompt_line(&line)"));
    }
}

#[cfg(test)]
mod echo_policy {
    use super::Echo;

    /// A masked read shows one `*` per CHARACTER, never per byte.
    ///
    /// Byte-counting would leak the key's length — a 20-character key with
    /// a multi-byte character in it would draw more stars than it has
    /// characters, and the difference is information about the secret.
    #[test]
    fn stars_mask_by_character_and_never_reveal_the_value() {
        assert_eq!(Echo::Stars.display("sk-live-abc"), "***********");
        assert_eq!(Echo::Stars.display(""), "");
        // Multi-byte: 3 chars, 3 stars — not 7 bytes, 7 stars.
        assert_eq!(Echo::Stars.display("é☃x"), "***");
        // The value itself never appears in what is displayed.
        for secret in ["sk-live-abc", "é☃x", "hunter2"] {
            let shown = Echo::Stars.display(secret);
            assert!(
                !shown.contains(secret),
                "the value leaked into the masked display: {shown:?}"
            );
        }
    }

    /// **The anti-vacuous twin.** If `display` always returned stars — or
    /// always returned the empty string — the assertions above would pass
    /// while the ordinary prompt drew nothing. `Chars` must be verbatim.
    #[test]
    fn chars_show_the_value_verbatim() {
        assert_eq!(Echo::Chars.display("sk-live-abc"), "sk-live-abc");
        assert_eq!(Echo::Chars.display("é☃x"), "é☃x");
        assert_eq!(Echo::Chars.display(""), "");
        assert_ne!(
            Echo::Chars.display("hunter2"),
            Echo::Stars.display("hunter2"),
            "the two policies must actually differ"
        );
    }
}