Skip to main content

harn_vm/stdlib/
io.rs

1use std::cell::{Cell, RefCell};
2use std::collections::{BTreeMap, VecDeque};
3#[cfg(not(unix))]
4use std::io::BufRead;
5use std::io::{IsTerminal, Read, Write};
6use std::marker::PhantomData;
7use std::rc::Rc;
8use std::sync::atomic::Ordering;
9use std::sync::Mutex;
10#[cfg(unix)]
11use std::time::{Duration, Instant};
12
13use crate::stdlib::macros::{harn_builtin, VmBuiltinDef};
14use crate::stdlib::options::{self, ErrorKind, OptionsParser};
15use crate::value::{VmError, VmValue};
16use crate::vm::Vm;
17
18use super::logging::{vm_build_log_line, vm_escape_json_str_quoted, VM_MIN_LOG_LEVEL};
19
20#[derive(Clone, Copy, Default)]
21struct TtyMock {
22    stdin: Option<bool>,
23    stdout: Option<bool>,
24    stderr: Option<bool>,
25}
26
27#[derive(Clone, Copy, Default, PartialEq)]
28enum ColorMode {
29    #[default]
30    Auto,
31    Always,
32    Never,
33}
34
35#[derive(Clone, Debug)]
36struct ReadLineOptions {
37    prompt: String,
38    timeout_ms: Option<u64>,
39    trim: bool,
40    echo: bool,
41    raw: bool,
42}
43
44impl Default for ReadLineOptions {
45    fn default() -> Self {
46        Self {
47            prompt: String::new(),
48            timeout_ms: None,
49            trim: true,
50            echo: true,
51            raw: false,
52        }
53    }
54}
55
56#[derive(Debug, PartialEq, Eq)]
57enum ReadLineOutcome {
58    Ok(String),
59    Eof,
60    #[cfg(unix)]
61    Timeout,
62    #[cfg(unix)]
63    Interrupt,
64    Error(String),
65}
66
67enum MockReadLine {
68    Line(String),
69    Eof,
70    Unset,
71}
72
73thread_local! {
74    static STDIN_MOCK: RefCell<Option<String>> = const { RefCell::new(None) };
75    static STDIN_LINES: RefCell<Option<VecDeque<String>>> = const { RefCell::new(None) };
76    static STDIN_ALLOWED: Cell<bool> = const { Cell::new(true) };
77    static STDOUT_ALLOWED: Cell<bool> = const { Cell::new(true) };
78    static STDERR_BUFFER: RefCell<String> = const { RefCell::new(String::new()) };
79    static STDERR_CAPTURING: RefCell<bool> = const { RefCell::new(false) };
80    static STDOUT_PASSTHROUGH: RefCell<bool> = const { RefCell::new(false) };
81    static TTY_MOCK: RefCell<TtyMock> = const { RefCell::new(TtyMock { stdin: None, stdout: None, stderr: None }) };
82    static COLOR_MODE: RefCell<ColorMode> = const { RefCell::new(ColorMode::Auto) };
83}
84
85static STDIN_READ_LOCK: Mutex<()> = Mutex::new(());
86
87/// Restores current-thread stdio ownership when dropped.
88#[must_use]
89pub struct StdioReservationGuard {
90    stdin_previous: bool,
91    stdout_previous: bool,
92    _thread_bound: PhantomData<Rc<()>>,
93}
94
95impl Drop for StdioReservationGuard {
96    fn drop(&mut self) {
97        STDIN_ALLOWED.set(self.stdin_previous);
98        STDOUT_ALLOWED.set(self.stdout_previous);
99    }
100}
101
102/// Reserve ambient stdin and stdout for a control protocol on this thread.
103///
104/// Guest stdin appears closed, explicit stdin mocks still take precedence,
105/// and stdout remains captured by the VM instead of reaching the protocol.
106pub fn reserve_stdio_for_current_thread() -> StdioReservationGuard {
107    StdioReservationGuard {
108        stdin_previous: STDIN_ALLOWED.replace(false),
109        stdout_previous: STDOUT_ALLOWED.replace(false),
110        _thread_bound: PhantomData,
111    }
112}
113
114pub(crate) const MODULE_BUILTINS: &[&VmBuiltinDef] = &[
115    &LOG_BUILTIN_DEF,
116    &COLOR_BUILTIN_DEF,
117    &BOLD_BUILTIN_DEF,
118    &DIM_BUILTIN_DEF,
119    &SET_COLOR_MODE_BUILTIN_DEF,
120    &ANSI_ENABLED_BUILTIN_DEF,
121    &READ_STDIN_BUILTIN_DEF,
122    &IO_READ_LINE_BUILTIN_DEF,
123    &IO_WRITE_STDERR_BUILTIN_DEF,
124    &IO_WRITE_STDOUT_BUILTIN_DEF,
125    &IO_PRINT_BUILTIN_DEF,
126    &IO_PRINTLN_BUILTIN_DEF,
127    &IO_EPRINT_BUILTIN_DEF,
128    &IO_EPRINTLN_BUILTIN_DEF,
129    &IS_STDIN_TTY_BUILTIN_DEF,
130    &IS_STDOUT_TTY_BUILTIN_DEF,
131    &IS_STDERR_TTY_BUILTIN_DEF,
132    &MOCK_STDIN_BUILTIN_DEF,
133    &UNMOCK_STDIN_BUILTIN_DEF,
134    &MOCK_TTY_BUILTIN_DEF,
135    &UNMOCK_TTY_BUILTIN_DEF,
136    &CAPTURE_STDERR_START_BUILTIN_DEF,
137    &CAPTURE_STDERR_TAKE_BUILTIN_DEF,
138    &UUID_BUILTIN_DEF,
139    &UUID_PARSE_BUILTIN_DEF,
140    &UUID_V7_BUILTIN_DEF,
141    &UUID_V5_BUILTIN_DEF,
142    &UUID_NIL_BUILTIN_DEF,
143    &LOG_DEBUG_BUILTIN_DEF,
144    &LOG_INFO_BUILTIN_DEF,
145    &LOG_WARN_BUILTIN_DEF,
146    &LOG_ERROR_BUILTIN_DEF,
147    &LOG_SET_LEVEL_BUILTIN_DEF,
148    &PROGRESS_BUILTIN_DEF,
149    &LOG_JSON_BUILTIN_DEF,
150];
151
152/// Reset all io thread-local state for test isolation.
153pub(crate) fn reset_io_state() {
154    STDIN_MOCK.with(|s| *s.borrow_mut() = None);
155    STDIN_LINES.with(|s| *s.borrow_mut() = None);
156    STDERR_BUFFER.with(|s| s.borrow_mut().clear());
157    STDERR_CAPTURING.with(|s| *s.borrow_mut() = false);
158    STDOUT_PASSTHROUGH.with(|s| *s.borrow_mut() = false);
159    TTY_MOCK.with(|t| *t.borrow_mut() = TtyMock::default());
160    COLOR_MODE.with(|m| *m.borrow_mut() = ColorMode::Auto);
161}
162
163/// Enable or disable direct stdout writes for CLI-style runs.
164///
165/// The VM normally captures stdout in-memory so tests and embedding callers
166/// can inspect it after execution. Interactive CLI programs need prompts to
167/// appear before `read_line()` blocks, so `harn run` enables this mode and
168/// streams `print`/`println`/`log` immediately.
169pub fn set_stdout_passthrough(enabled: bool) -> bool {
170    STDOUT_PASSTHROUGH.with(|state| {
171        let previous = *state.borrow();
172        *state.borrow_mut() = enabled;
173        previous
174    })
175}
176
177/// Drain and return the buffered stderr output. The CLI flushes this to
178/// the real stderr at the end of execution.
179pub fn take_stderr_buffer() -> String {
180    STDERR_BUFFER.with(|s| std::mem::take(&mut *s.borrow_mut()))
181}
182
183pub(crate) fn write_stderr(line: &str) {
184    if crate::run_events::sink_active() {
185        crate::run_events::emit(crate::run_events::RunEvent::Stderr {
186            payload: line.to_string(),
187        });
188        return;
189    }
190    let capturing = STDERR_CAPTURING.with(|c| *c.borrow());
191    if capturing {
192        STDERR_BUFFER.with(|s| s.borrow_mut().push_str(line));
193    } else {
194        let mut stderr = std::io::stderr().lock();
195        let _ = stderr.write_all(line.as_bytes());
196        let _ = stderr.flush();
197    }
198}
199
200pub(crate) fn write_stdout(out: &mut String, text: &str) {
201    if crate::run_events::sink_active() {
202        crate::run_events::emit(crate::run_events::RunEvent::Stdout {
203            payload: text.to_string(),
204        });
205        return;
206    }
207    if STDOUT_ALLOWED.get() && stdout_passthrough_enabled() {
208        let mut stdout = std::io::stdout().lock();
209        let _ = stdout.write_all(text.as_bytes());
210        let _ = stdout.flush();
211    } else {
212        out.push_str(text);
213    }
214}
215
216pub(crate) fn write_ambient_stdout(text: &str) {
217    if !STDOUT_ALLOWED.get() {
218        return;
219    }
220    let mut stdout = std::io::stdout().lock();
221    let _ = stdout.write_all(text.as_bytes());
222    let _ = stdout.flush();
223}
224
225fn stdout_passthrough_enabled() -> bool {
226    STDOUT_PASSTHROUGH.with(|state| *state.borrow())
227}
228
229fn read_stdin_all_real() -> Option<String> {
230    let mut buf = String::new();
231    if std::io::stdin().lock().read_to_string(&mut buf).is_ok() {
232        Some(buf)
233    } else {
234        None
235    }
236}
237
238#[cfg(not(unix))]
239fn read_stdin_line_real() -> Option<String> {
240    let mut buf = String::new();
241    if std::io::stdin().lock().read_line(&mut buf).is_ok() {
242        if buf.is_empty() {
243            None
244        } else {
245            // Trim trailing \n / \r\n but keep internal whitespace.
246            if buf.ends_with('\n') {
247                buf.pop();
248                if buf.ends_with('\r') {
249                    buf.pop();
250                }
251            }
252            Some(buf)
253        }
254    } else {
255        None
256    }
257}
258
259fn pop_mock_line() -> MockReadLine {
260    STDIN_LINES.with(|lines| {
261        let mut borrow = lines.borrow_mut();
262        if let Some(queue) = borrow.as_mut() {
263            return queue
264                .pop_front()
265                .map(MockReadLine::Line)
266                .unwrap_or(MockReadLine::Eof);
267        }
268        MockReadLine::Unset
269    })
270}
271
272fn read_mock_line() -> MockReadLine {
273    match pop_mock_line() {
274        MockReadLine::Unset => {}
275        other => return other,
276    }
277    let bulk = STDIN_MOCK.with(|s| s.borrow_mut().take());
278    let Some(text) = bulk else {
279        return MockReadLine::Unset;
280    };
281    let mut lines: VecDeque<String> = text.split('\n').map(String::from).collect();
282    // Keep legacy read_line semantics: a final newline terminates the last
283    // line rather than producing one more empty line.
284    if matches!(lines.back(), Some(line) if line.is_empty()) {
285        lines.pop_back();
286    }
287    let first = lines.pop_front();
288    STDIN_LINES.with(|q| *q.borrow_mut() = Some(lines));
289    first.map(MockReadLine::Line).unwrap_or(MockReadLine::Eof)
290}
291
292fn normalize_read_line_value(mut line: String, trim: bool) -> String {
293    if line.ends_with('\r') {
294        line.pop();
295    }
296    if trim {
297        line.trim().to_string()
298    } else {
299        line
300    }
301}
302
303fn read_line_result(outcome: ReadLineOutcome) -> VmValue {
304    let mut out = BTreeMap::new();
305    match outcome {
306        ReadLineOutcome::Ok(value) => {
307            out.insert("ok".to_string(), VmValue::Bool(true));
308            out.insert("status".to_string(), VmValue::string("ok"));
309            out.insert("value".to_string(), VmValue::string(value));
310        }
311        ReadLineOutcome::Eof => {
312            out.insert("ok".to_string(), VmValue::Bool(false));
313            out.insert("status".to_string(), VmValue::string("eof"));
314        }
315        #[cfg(unix)]
316        ReadLineOutcome::Timeout => {
317            out.insert("ok".to_string(), VmValue::Bool(false));
318            out.insert("status".to_string(), VmValue::string("timeout"));
319        }
320        #[cfg(unix)]
321        ReadLineOutcome::Interrupt => {
322            out.insert("ok".to_string(), VmValue::Bool(false));
323            out.insert("status".to_string(), VmValue::string("interrupt"));
324        }
325        ReadLineOutcome::Error(error) => {
326            out.insert("ok".to_string(), VmValue::Bool(false));
327            out.insert("status".to_string(), VmValue::string("error"));
328            out.insert("error".to_string(), VmValue::string(error));
329        }
330    }
331    VmValue::dict(out)
332}
333
334const READ_LINE_FN: &str = "std/io.read_line";
335
336fn parse_read_line_timeout_ms(value: Option<&VmValue>) -> Result<Option<u64>, VmError> {
337    match value {
338        None | Some(VmValue::Nil) => Ok(None),
339        Some(VmValue::Int(value)) | Some(VmValue::Duration(value)) => {
340            if *value < 0 {
341                return Err(VmError::Runtime(format!(
342                    "{READ_LINE_FN}: `timeout_ms` must be non-negative"
343                )));
344            }
345            Ok(Some(*value as u64))
346        }
347        Some(value) => Err(VmError::Runtime(format!(
348            "{READ_LINE_FN}: `timeout_ms` must be an int, duration, or nil (got {})",
349            value.type_name()
350        ))),
351    }
352}
353
354fn parse_read_line_options(args: &[VmValue]) -> Result<ReadLineOptions, VmError> {
355    if args.len() > 1 {
356        return Err(VmError::Runtime(format!(
357            "{READ_LINE_FN}: expected at most one options dict"
358        )));
359    }
360    let Some(dict) =
361        options::optional_dict_arg(args, 0, READ_LINE_FN, "options", ErrorKind::Runtime)?
362    else {
363        return Ok(ReadLineOptions::default());
364    };
365    let mut parser = OptionsParser::new(READ_LINE_FN, dict, ErrorKind::Runtime);
366    let options = ReadLineOptions {
367        prompt: parser.optional_string_raw("prompt")?.unwrap_or_default(),
368        timeout_ms: parse_read_line_timeout_ms(parser.raw("timeout_ms"))?,
369        trim: parser.bool_or("trim", true)?,
370        echo: parser.bool_or("echo", true)?,
371        raw: parser.bool_or("raw", false)?,
372    };
373    parser.finish_strict(&[])?;
374    Ok(options)
375}
376
377fn read_line_from_mock_or_real(options: &ReadLineOptions) -> ReadLineOutcome {
378    let _lock = match STDIN_READ_LOCK.lock() {
379        Ok(lock) => lock,
380        Err(_) => return ReadLineOutcome::Error("stdin read lock is poisoned".to_string()),
381    };
382    if !options.prompt.is_empty() {
383        write_stderr(&options.prompt);
384    }
385    match read_mock_line() {
386        MockReadLine::Line(line) => {
387            return ReadLineOutcome::Ok(normalize_read_line_value(line, options.trim));
388        }
389        MockReadLine::Eof => return ReadLineOutcome::Eof,
390        MockReadLine::Unset => {}
391    }
392    if !STDIN_ALLOWED.get() {
393        return ReadLineOutcome::Eof;
394    }
395    read_stdin_line_real_with_options(options)
396}
397
398#[cfg(unix)]
399struct TerminalModeGuard {
400    fd: libc::c_int,
401    original: Option<libc::termios>,
402}
403
404#[cfg(unix)]
405impl TerminalModeGuard {
406    fn install(fd: libc::c_int, options: &ReadLineOptions) -> Result<Self, String> {
407        let mut original = std::mem::MaybeUninit::<libc::termios>::uninit();
408        let fd_is_terminal = unsafe { libc::isatty(fd) == 1 };
409        if !fd_is_terminal || (options.echo && !options.raw) {
410            return Ok(Self { fd, original: None });
411        }
412        if unsafe { libc::tcgetattr(fd, original.as_mut_ptr()) } != 0 {
413            return Err(std::io::Error::last_os_error().to_string());
414        }
415        let original = unsafe { original.assume_init() };
416        let mut updated = original;
417        if !options.echo {
418            updated.c_lflag &= !libc::ECHO;
419        }
420        if options.raw {
421            updated.c_lflag &= !libc::ICANON;
422            updated.c_cc[libc::VMIN] = 0;
423            updated.c_cc[libc::VTIME] = 0;
424        }
425        if unsafe { libc::tcsetattr(fd, libc::TCSANOW, &raw const updated) } != 0 {
426            return Err(std::io::Error::last_os_error().to_string());
427        }
428        Ok(Self {
429            fd,
430            original: Some(original),
431        })
432    }
433}
434
435#[cfg(unix)]
436impl Drop for TerminalModeGuard {
437    fn drop(&mut self) {
438        if let Some(original) = &self.original {
439            let _ = unsafe { libc::tcsetattr(self.fd, libc::TCSANOW, original) };
440        }
441    }
442}
443
444#[cfg(unix)]
445const READ_LINE_INTERRUPT_POLL: Duration = Duration::from_millis(20);
446
447#[cfg(unix)]
448fn read_line_elapsed_ms(start: Instant) -> u64 {
449    start.elapsed().as_millis().min(u128::from(u64::MAX)) as u64
450}
451
452#[cfg(unix)]
453fn read_line_timeout_remaining_ms(options: &ReadLineOptions, start: Instant) -> Option<u64> {
454    let timeout_ms = options.timeout_ms?;
455    Some(timeout_ms.saturating_sub(read_line_elapsed_ms(start)))
456}
457
458#[cfg(unix)]
459fn read_line_timed_out(options: &ReadLineOptions, start: Instant) -> bool {
460    matches!(read_line_timeout_remaining_ms(options, start), Some(0))
461}
462
463#[cfg(unix)]
464fn read_line_interrupt_poll_ms() -> libc::c_int {
465    READ_LINE_INTERRUPT_POLL
466        .as_millis()
467        .min(libc::c_int::MAX as u128) as libc::c_int
468}
469
470#[cfg(unix)]
471fn poll_timeout(options: &ReadLineOptions, start: Instant) -> libc::c_int {
472    let heartbeat = crate::op_interrupt::installed().then_some(read_line_interrupt_poll_ms());
473    match (read_line_timeout_remaining_ms(options, start), heartbeat) {
474        (Some(remaining), Some(heartbeat)) => {
475            remaining.min(heartbeat as u64).min(libc::c_int::MAX as u64) as libc::c_int
476        }
477        (Some(remaining), None) => remaining.min(libc::c_int::MAX as u64) as libc::c_int,
478        (None, Some(heartbeat)) => heartbeat,
479        (None, None) => -1,
480    }
481}
482
483#[cfg(unix)]
484fn finish_read_line(bytes: Vec<u8>, trim: bool) -> ReadLineOutcome {
485    match String::from_utf8(bytes) {
486        Ok(line) => ReadLineOutcome::Ok(normalize_read_line_value(line, trim)),
487        Err(_) => ReadLineOutcome::Error("stdin line was not valid UTF-8".to_string()),
488    }
489}
490
491#[cfg(unix)]
492fn read_line_from_fd_unix(fd: libc::c_int, options: &ReadLineOptions) -> ReadLineOutcome {
493    let _terminal_mode = match TerminalModeGuard::install(fd, options) {
494        Ok(guard) => guard,
495        Err(error) => return ReadLineOutcome::Error(error),
496    };
497    let start = Instant::now();
498    let mut bytes = Vec::new();
499    loop {
500        if crate::op_interrupt::requested() {
501            return ReadLineOutcome::Interrupt;
502        }
503        let mut pollfd = libc::pollfd {
504            fd,
505            events: libc::POLLIN,
506            revents: 0,
507        };
508        let ready = unsafe { libc::poll(&raw mut pollfd, 1, poll_timeout(options, start)) };
509        if ready == 0 {
510            if read_line_timed_out(options, start) {
511                return ReadLineOutcome::Timeout;
512            }
513            continue;
514        }
515        if ready < 0 {
516            let error = std::io::Error::last_os_error();
517            if error.raw_os_error() == Some(libc::EINTR) {
518                return ReadLineOutcome::Interrupt;
519            }
520            return ReadLineOutcome::Error(error.to_string());
521        }
522        if pollfd.revents & libc::POLLNVAL != 0 {
523            return ReadLineOutcome::Error("stdin fd is invalid".to_string());
524        }
525        if pollfd.revents & (libc::POLLIN | libc::POLLHUP | libc::POLLERR) == 0 {
526            continue;
527        }
528        let mut byte = [0u8; 1];
529        let read = unsafe { libc::read(fd, byte.as_mut_ptr().cast(), 1) };
530        if read == 0 {
531            return if bytes.is_empty() {
532                ReadLineOutcome::Eof
533            } else {
534                finish_read_line(bytes, options.trim)
535            };
536        }
537        if read < 0 {
538            let error = std::io::Error::last_os_error();
539            match error.raw_os_error() {
540                Some(libc::EINTR) => return ReadLineOutcome::Interrupt,
541                Some(libc::EAGAIN) => continue,
542                _ => return ReadLineOutcome::Error(error.to_string()),
543            }
544        }
545        match byte[0] {
546            b'\n' => return finish_read_line(bytes, options.trim),
547            b'\r' if options.raw => return finish_read_line(bytes, options.trim),
548            0x03 if options.raw => return ReadLineOutcome::Interrupt,
549            0x04 if options.raw && bytes.is_empty() => return ReadLineOutcome::Eof,
550            0x04 if options.raw => return finish_read_line(bytes, options.trim),
551            value => bytes.push(value),
552        }
553    }
554}
555
556#[cfg(unix)]
557fn read_stdin_line_real_with_options(options: &ReadLineOptions) -> ReadLineOutcome {
558    read_line_from_fd_unix(libc::STDIN_FILENO, options)
559}
560
561#[cfg(not(unix))]
562fn read_stdin_line_real_with_options(options: &ReadLineOptions) -> ReadLineOutcome {
563    if !options.echo || options.raw {
564        return ReadLineOutcome::Error(
565            "std/io.read_line echo=false/raw=true is only implemented on Unix hosts".to_string(),
566        );
567    }
568    if options.timeout_ms.is_some() {
569        return ReadLineOutcome::Error(
570            "std/io.read_line timeout_ms is only implemented on Unix hosts".to_string(),
571        );
572    }
573    match read_stdin_line_real() {
574        Some(line) => ReadLineOutcome::Ok(normalize_read_line_value(line, options.trim)),
575        None => ReadLineOutcome::Eof,
576    }
577}
578
579pub(crate) fn is_tty_for(stream: &str) -> bool {
580    let mocked = TTY_MOCK.with(|t| {
581        let mock = *t.borrow();
582        match stream {
583            "stdin" => mock.stdin,
584            "stdout" => mock.stdout,
585            "stderr" => mock.stderr,
586            _ => None,
587        }
588    });
589    if let Some(v) = mocked {
590        return v;
591    }
592    match stream {
593        "stdin" => std::io::stdin().is_terminal(),
594        "stdout" => std::io::stdout().is_terminal(),
595        "stderr" => std::io::stderr().is_terminal(),
596        _ => false,
597    }
598}
599
600fn ansi_enabled_for_stream(stream: &str) -> bool {
601    let mode = COLOR_MODE.with(|m| *m.borrow());
602    match mode {
603        ColorMode::Always => true,
604        ColorMode::Never => false,
605        ColorMode::Auto => {
606            if std::env::var_os("FORCE_COLOR").is_some() {
607                return true;
608            }
609            if std::env::var_os("NO_COLOR").is_some() {
610                return false;
611            }
612            is_tty_for(stream)
613        }
614    }
615}
616
617pub(crate) fn register_io_builtins(vm: &mut Vm) {
618    for def in MODULE_BUILTINS {
619        vm.register_builtin_def(def);
620    }
621}
622
623#[harn_builtin(
624    sig = "log(message: any) -> nil",
625    category = "io",
626    doc = "Write a Harn-prefixed message to stdout."
627)]
628fn log_builtin(args: &[VmValue], out: &mut String) -> Result<VmValue, VmError> {
629    let msg = args.first().map(|a| a.display()).unwrap_or_default();
630    write_stdout(out, &format!("[harn] {msg}\n"));
631    Ok(VmValue::Nil)
632}
633
634#[harn_builtin(
635    sig = "color(text: any, color: string) -> string",
636    category = "io",
637    doc = "Apply an ANSI foreground color when color output is enabled."
638)]
639fn color_builtin(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
640    let text = args.first().map(|a| a.display()).unwrap_or_default();
641    let name = args.get(1).map(|a| a.display()).unwrap_or_default();
642    if !ansi_enabled_for_stream("stdout") {
643        return Ok(VmValue::String(arcstr::ArcStr::from(text)));
644    }
645    Ok(VmValue::String(arcstr::ArcStr::from(ansi_colorize(
646        &text, &name,
647    ))))
648}
649
650#[harn_builtin(
651    sig = "bold(text: any) -> string",
652    category = "io",
653    doc = "Apply ANSI bold styling when color output is enabled."
654)]
655fn bold_builtin(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
656    let text = args.first().map(|a| a.display()).unwrap_or_default();
657    if !ansi_enabled_for_stream("stdout") {
658        return Ok(VmValue::String(arcstr::ArcStr::from(text)));
659    }
660    Ok(VmValue::String(arcstr::ArcStr::from(format!(
661        "\u{1b}[1m{text}\u{1b}[0m"
662    ))))
663}
664
665#[harn_builtin(
666    sig = "dim(text: any) -> string",
667    category = "io",
668    doc = "Apply ANSI dim styling when color output is enabled."
669)]
670fn dim_builtin(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
671    let text = args.first().map(|a| a.display()).unwrap_or_default();
672    if !ansi_enabled_for_stream("stdout") {
673        return Ok(VmValue::String(arcstr::ArcStr::from(text)));
674    }
675    Ok(VmValue::String(arcstr::ArcStr::from(format!(
676        "\u{1b}[2m{text}\u{1b}[0m"
677    ))))
678}
679
680#[harn_builtin(
681    sig = "set_color_mode(mode: string) -> nil",
682    category = "io",
683    doc = "Set ANSI color handling to auto, always, or never."
684)]
685fn set_color_mode_builtin(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
686    let mode = args.first().map(|a| a.display()).unwrap_or_default();
687    let parsed = match mode.as_str() {
688        "auto" => ColorMode::Auto,
689        "always" => ColorMode::Always,
690        "never" => ColorMode::Never,
691        other => {
692            return Err(VmError::Thrown(VmValue::String(arcstr::ArcStr::from(
693                format!(
694                "set_color_mode: invalid mode '{other}'. Expected 'auto', 'always', or 'never'."
695            ),
696            ))));
697        }
698    };
699    COLOR_MODE.with(|m| *m.borrow_mut() = parsed);
700    Ok(VmValue::Nil)
701}
702
703#[harn_builtin(
704    sig = "__ansi_enabled(stream?: string) -> bool",
705    category = "io",
706    doc = "Return whether ANSI styling is enabled for stdin, stdout, or stderr."
707)]
708fn ansi_enabled_builtin(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
709    let stream = args
710        .first()
711        .map(|a| a.display())
712        .unwrap_or_else(|| "stdout".to_string());
713    match stream.as_str() {
714        "stdin" | "stdout" | "stderr" => Ok(VmValue::Bool(ansi_enabled_for_stream(&stream))),
715        other => Err(VmError::Thrown(VmValue::String(arcstr::ArcStr::from(
716            format!(
717            "__ansi_enabled: invalid stream '{other}'. Expected 'stdin', 'stdout', or 'stderr'."
718        ),
719        )))),
720    }
721}
722
723#[harn_builtin(
724    sig = "read_stdin() -> string",
725    category = "io",
726    doc = "Read all remaining stdin as a string."
727)]
728fn read_stdin_builtin(_args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
729    // Drain any remaining mocked stdin first.
730    let mocked = STDIN_MOCK.with(|s| s.borrow_mut().take());
731    if let Some(buf) = mocked {
732        // After read_stdin, future read_line calls return nil because stdin is consumed.
733        STDIN_LINES.with(|lines| *lines.borrow_mut() = Some(VecDeque::new()));
734        return Ok(VmValue::String(arcstr::ArcStr::from(buf)));
735    }
736    if !STDIN_ALLOWED.get() {
737        return Ok(VmValue::Nil);
738    }
739    match read_stdin_all_real() {
740        Some(s) => Ok(VmValue::String(arcstr::ArcStr::from(s))),
741        None => Ok(VmValue::Nil),
742    }
743}
744
745pub(crate) fn read_line_legacy_value() -> VmValue {
746    let options = ReadLineOptions {
747        trim: false,
748        ..ReadLineOptions::default()
749    };
750    match read_line_from_mock_or_real(&options) {
751        ReadLineOutcome::Ok(line) => VmValue::String(arcstr::ArcStr::from(line)),
752        ReadLineOutcome::Eof => VmValue::Nil,
753        #[cfg(unix)]
754        ReadLineOutcome::Timeout => VmValue::Nil,
755        #[cfg(unix)]
756        ReadLineOutcome::Interrupt => VmValue::Nil,
757        ReadLineOutcome::Error(_) => VmValue::Nil,
758    }
759}
760
761pub(crate) fn read_line_structured_value(args: &[VmValue]) -> Result<VmValue, VmError> {
762    let options = parse_read_line_options(args)?;
763    Ok(read_line_result(read_line_from_mock_or_real(&options)))
764}
765
766#[harn_builtin(
767    sig = "__io_read_line(options?: any) -> dict",
768    category = "io",
769    doc = "Read one line from stdin with structured status metadata."
770)]
771fn io_read_line_builtin(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
772    read_line_structured_value(args)
773}
774
775#[harn_builtin(
776    sig = "__io_write_stderr(message: any) -> nil",
777    category = "io",
778    doc = "Write text to stderr without appending a newline."
779)]
780fn io_write_stderr_builtin(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
781    let msg = args.first().map(|a| a.display()).unwrap_or_default();
782    write_stderr(&msg);
783    Ok(VmValue::Nil)
784}
785
786#[harn_builtin(
787    sig = "__io_write_stdout(message: any) -> nil",
788    category = "io",
789    doc = "Write text to stdout without appending a newline."
790)]
791fn io_write_stdout_builtin(args: &[VmValue], out: &mut String) -> Result<VmValue, VmError> {
792    let msg = args.first().map(|a| a.display()).unwrap_or_default();
793    write_stdout(out, &msg);
794    Ok(VmValue::Nil)
795}
796
797#[harn_builtin(
798    sig = "__io_print(...args: any) -> nil",
799    category = "io",
800    doc = "Internal compatibility bridge for stdout without newline."
801)]
802fn io_print_builtin(args: &[VmValue], out: &mut String) -> Result<VmValue, VmError> {
803    let msg = args.first().map(|a| a.display()).unwrap_or_default();
804    write_stdout(out, &msg);
805    Ok(VmValue::Nil)
806}
807
808#[harn_builtin(
809    sig = "__io_println(...args: any) -> nil",
810    category = "io",
811    doc = "Internal compatibility bridge for stdout with newline."
812)]
813fn io_println_builtin(args: &[VmValue], out: &mut String) -> Result<VmValue, VmError> {
814    let msg = args.first().map(|a| a.display()).unwrap_or_default();
815    write_stdout(out, &format!("{msg}\n"));
816    Ok(VmValue::Nil)
817}
818
819#[harn_builtin(
820    sig = "__io_eprint(message: any) -> nil",
821    category = "io",
822    doc = "Internal compatibility bridge for stderr without newline."
823)]
824fn io_eprint_builtin(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
825    let msg = args.first().map(|a| a.display()).unwrap_or_default();
826    write_stderr(&msg);
827    Ok(VmValue::Nil)
828}
829
830#[harn_builtin(
831    sig = "__io_eprintln(message: any) -> nil",
832    category = "io",
833    doc = "Internal compatibility bridge for stderr with newline."
834)]
835fn io_eprintln_builtin(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
836    let msg = args.first().map(|a| a.display()).unwrap_or_default();
837    write_stderr(&format!("{msg}\n"));
838    Ok(VmValue::Nil)
839}
840
841#[harn_builtin(
842    sig = "is_stdin_tty() -> bool",
843    category = "io",
844    doc = "Return whether stdin is attached to a terminal."
845)]
846fn is_stdin_tty_builtin(_args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
847    Ok(VmValue::Bool(is_tty_for("stdin")))
848}
849
850#[harn_builtin(
851    sig = "is_stdout_tty() -> bool",
852    category = "io",
853    doc = "Return whether stdout is attached to a terminal."
854)]
855fn is_stdout_tty_builtin(_args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
856    Ok(VmValue::Bool(is_tty_for("stdout")))
857}
858
859#[harn_builtin(
860    sig = "is_stderr_tty() -> bool",
861    category = "io",
862    doc = "Return whether stderr is attached to a terminal."
863)]
864fn is_stderr_tty_builtin(_args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
865    Ok(VmValue::Bool(is_tty_for("stderr")))
866}
867
868#[harn_builtin(
869    sig = "mock_stdin(text: string) -> nil",
870    category = "io",
871    doc = "Install mocked stdin text for tests."
872)]
873fn mock_stdin_builtin(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
874    let text = args.first().map(|a| a.display()).unwrap_or_default();
875    STDIN_MOCK.with(|s| *s.borrow_mut() = Some(text));
876    STDIN_LINES.with(|s| *s.borrow_mut() = None);
877    Ok(VmValue::Nil)
878}
879
880#[harn_builtin(
881    sig = "unmock_stdin() -> nil",
882    category = "io",
883    doc = "Clear mocked stdin text and line state."
884)]
885fn unmock_stdin_builtin(_args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
886    STDIN_MOCK.with(|s| *s.borrow_mut() = None);
887    STDIN_LINES.with(|s| *s.borrow_mut() = None);
888    Ok(VmValue::Nil)
889}
890
891#[harn_builtin(
892    sig = "mock_tty(stream: string, is_tty: bool) -> nil",
893    category = "io",
894    doc = "Override terminal detection for stdin, stdout, or stderr."
895)]
896fn mock_tty_builtin(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
897    let stream = args.first().map(|a| a.display()).unwrap_or_default();
898    let is_tty = matches!(args.get(1), Some(VmValue::Bool(true)));
899    TTY_MOCK.with(|t| {
900        let mut mock = t.borrow_mut();
901        match stream.as_str() {
902            "stdin" => mock.stdin = Some(is_tty),
903            "stdout" => mock.stdout = Some(is_tty),
904            "stderr" => mock.stderr = Some(is_tty),
905            other => {
906                return Err(VmError::Thrown(VmValue::String(arcstr::ArcStr::from(
907                    format!(
908                    "mock_tty: invalid stream '{other}'. Expected 'stdin', 'stdout', or 'stderr'."
909                ),
910                ))));
911            }
912        }
913        Ok(VmValue::Nil)
914    })
915}
916
917#[harn_builtin(
918    sig = "unmock_tty() -> nil",
919    category = "io",
920    doc = "Clear terminal detection overrides."
921)]
922fn unmock_tty_builtin(_args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
923    TTY_MOCK.with(|t| *t.borrow_mut() = TtyMock::default());
924    Ok(VmValue::Nil)
925}
926
927#[harn_builtin(
928    sig = "capture_stderr_start() -> nil",
929    category = "io",
930    doc = "Start capturing stderr into an in-memory buffer."
931)]
932fn capture_stderr_start_builtin(_args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
933    STDERR_CAPTURING.with(|c| *c.borrow_mut() = true);
934    STDERR_BUFFER.with(|s| s.borrow_mut().clear());
935    Ok(VmValue::Nil)
936}
937
938#[harn_builtin(
939    sig = "capture_stderr_take() -> string",
940    category = "io",
941    doc = "Stop stderr capture and return the buffered text."
942)]
943fn capture_stderr_take_builtin(_args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
944    let buf = STDERR_BUFFER.with(|s| std::mem::take(&mut *s.borrow_mut()));
945    STDERR_CAPTURING.with(|c| *c.borrow_mut() = false);
946    Ok(VmValue::String(arcstr::ArcStr::from(buf)))
947}
948
949#[harn_builtin(
950    sig = "uuid() -> string",
951    category = "io",
952    doc = "Generate a random version 4 UUID."
953)]
954fn uuid_builtin(_args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
955    Ok(VmValue::String(arcstr::ArcStr::from(
956        uuid::Uuid::new_v4().to_string(),
957    )))
958}
959
960#[harn_builtin(
961    sig = "uuid_parse(value: any) -> string",
962    category = "io",
963    doc = "Parse and normalize a UUID string, or return nil."
964)]
965fn uuid_parse_builtin(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
966    let raw = args.first().map(|a| a.display()).unwrap_or_default();
967    match uuid::Uuid::parse_str(&raw) {
968        Ok(uuid) => Ok(VmValue::String(arcstr::ArcStr::from(uuid.to_string()))),
969        Err(_) => Ok(VmValue::Nil),
970    }
971}
972
973#[harn_builtin(
974    sig = "uuid_v7() -> string",
975    category = "io",
976    doc = "Generate a time-ordered version 7 UUID."
977)]
978fn uuid_v7_builtin(_args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
979    Ok(VmValue::String(arcstr::ArcStr::from(
980        uuid::Uuid::now_v7().to_string(),
981    )))
982}
983
984#[harn_builtin(
985    sig = "uuid_v5(namespace: string, name: string) -> string",
986    category = "io",
987    doc = "Generate a deterministic version 5 UUID."
988)]
989fn uuid_v5_builtin(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
990    if args.len() < 2 {
991        return Err(VmError::Runtime(
992            "uuid_v5(namespace, name): requires namespace and name".to_string(),
993        ));
994    }
995    let namespace_raw = args[0].display();
996    let namespace = uuid_v5_namespace(&namespace_raw).ok_or_else(|| {
997        VmError::Runtime("uuid_v5: namespace must be a UUID or one of dns/url/oid/x500".to_string())
998    })?;
999    let name = args[1].display();
1000    Ok(VmValue::String(arcstr::ArcStr::from(
1001        uuid::Uuid::new_v5(&namespace, name.as_bytes()).to_string(),
1002    )))
1003}
1004
1005#[harn_builtin(
1006    sig = "uuid_nil() -> string",
1007    category = "io",
1008    doc = "Return the nil UUID."
1009)]
1010fn uuid_nil_builtin(_args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
1011    Ok(VmValue::String(arcstr::ArcStr::from(
1012        uuid::Uuid::nil().to_string(),
1013    )))
1014}
1015
1016pub(crate) fn prompt_user_value(args: &[VmValue], out: &mut String) -> Result<VmValue, VmError> {
1017    let msg = args.first().map(|a| a.display()).unwrap_or_default();
1018    write_stdout(out, &msg);
1019    let options = ReadLineOptions {
1020        trim: false,
1021        ..ReadLineOptions::default()
1022    };
1023    match read_line_from_mock_or_real(&options) {
1024        ReadLineOutcome::Ok(line) => Ok(VmValue::String(arcstr::ArcStr::from(
1025            line.trim_end().to_string(),
1026        ))),
1027        ReadLineOutcome::Eof => Ok(VmValue::Nil),
1028        #[cfg(unix)]
1029        ReadLineOutcome::Timeout => Ok(VmValue::Nil),
1030        #[cfg(unix)]
1031        ReadLineOutcome::Interrupt => Ok(VmValue::Nil),
1032        ReadLineOutcome::Error(_) => Ok(VmValue::Nil),
1033    }
1034}
1035
1036pub(crate) fn read_password_legacy_value(prompt: &str) -> Result<VmValue, VmError> {
1037    let options = ReadLineOptions {
1038        prompt: prompt.to_string(),
1039        trim: false,
1040        echo: false,
1041        ..ReadLineOptions::default()
1042    };
1043    match read_line_from_mock_or_real(&options) {
1044        ReadLineOutcome::Ok(line) => Ok(VmValue::String(arcstr::ArcStr::from(line))),
1045        ReadLineOutcome::Eof => Err(VmError::Runtime(
1046            "HarnessTerm.read_password: stdin reached EOF".to_string(),
1047        )),
1048        #[cfg(unix)]
1049        ReadLineOutcome::Timeout => Err(VmError::Runtime(
1050            "HarnessTerm.read_password: stdin read timed out".to_string(),
1051        )),
1052        #[cfg(unix)]
1053        ReadLineOutcome::Interrupt => Err(VmError::Runtime(
1054            "HarnessTerm.read_password: stdin read was interrupted".to_string(),
1055        )),
1056        ReadLineOutcome::Error(error) => Err(VmError::Runtime(format!(
1057            "HarnessTerm.read_password: {error}"
1058        ))),
1059    }
1060}
1061
1062#[harn_builtin(
1063    sig = "log_debug(message: any, fields?: dict) -> nil",
1064    category = "io",
1065    doc = "Write a structured debug log line."
1066)]
1067fn log_debug_builtin(args: &[VmValue], out: &mut String) -> Result<VmValue, VmError> {
1068    vm_write_log("debug", 0, args, out);
1069    Ok(VmValue::Nil)
1070}
1071
1072#[harn_builtin(
1073    sig = "log_info(message: any, fields?: dict) -> nil",
1074    category = "io",
1075    doc = "Write a structured info log line."
1076)]
1077fn log_info_builtin(args: &[VmValue], out: &mut String) -> Result<VmValue, VmError> {
1078    vm_write_log("info", 1, args, out);
1079    Ok(VmValue::Nil)
1080}
1081
1082#[harn_builtin(
1083    sig = "log_warn(message: any, fields?: dict) -> nil",
1084    category = "io",
1085    doc = "Write a structured warning log line."
1086)]
1087fn log_warn_builtin(args: &[VmValue], out: &mut String) -> Result<VmValue, VmError> {
1088    vm_write_log("warn", 2, args, out);
1089    Ok(VmValue::Nil)
1090}
1091
1092#[harn_builtin(
1093    sig = "log_error(message: any, fields?: dict) -> nil",
1094    category = "io",
1095    doc = "Write a structured error log line."
1096)]
1097fn log_error_builtin(args: &[VmValue], out: &mut String) -> Result<VmValue, VmError> {
1098    vm_write_log("error", 3, args, out);
1099    Ok(VmValue::Nil)
1100}
1101
1102#[harn_builtin(
1103    sig = "log_set_level(level: string) -> nil",
1104    category = "io",
1105    doc = "Set the minimum structured log level."
1106)]
1107fn log_set_level_builtin(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
1108    let level_str = args.first().map(|a| a.display()).unwrap_or_default();
1109    match super::logging::vm_level_to_u8(&level_str) {
1110        Some(n) => {
1111            VM_MIN_LOG_LEVEL.store(n, Ordering::Relaxed);
1112            Ok(VmValue::Nil)
1113        }
1114        None => Err(VmError::Thrown(VmValue::String(arcstr::ArcStr::from(
1115            format!(
1116                "log_set_level: invalid level '{level_str}'. Expected debug, info, warn, or error"
1117            ),
1118        )))),
1119    }
1120}
1121
1122#[harn_builtin(
1123    sig = "progress(phase: string, message: string, progress_or_options?: any, total?: int) -> nil",
1124    category = "io",
1125    doc = "Write a human-readable progress log line."
1126)]
1127fn progress_builtin(args: &[VmValue], out: &mut String) -> Result<VmValue, VmError> {
1128    write_stdout(out, &render_progress_line(args));
1129    Ok(VmValue::Nil)
1130}
1131
1132#[harn_builtin(
1133    sig = "log_json(key: string, value?: any) -> nil",
1134    category = "io",
1135    doc = "Write a structured JSON log line."
1136)]
1137fn log_json_builtin(args: &[VmValue], out: &mut String) -> Result<VmValue, VmError> {
1138    let key = args.first().map(|a| a.display()).unwrap_or_default();
1139    let value = args.get(1).cloned().unwrap_or(VmValue::Nil);
1140    let json_val = super::logging::vm_value_to_json_fragment(&value);
1141    let ts = super::logging::vm_format_timestamp_utc();
1142    let line = format!(
1143        "{{\"ts\":{},\"key\":{},\"value\":{}}}\n",
1144        vm_escape_json_str_quoted(&ts),
1145        vm_escape_json_str_quoted(&key),
1146        json_val,
1147    );
1148    write_stdout(out, &line);
1149    Ok(VmValue::Nil)
1150}
1151
1152fn uuid_v5_namespace(raw: &str) -> Option<uuid::Uuid> {
1153    match raw.to_ascii_lowercase().as_str() {
1154        "dns" | "namespace_dns" => Some(uuid::Uuid::NAMESPACE_DNS),
1155        "url" | "namespace_url" => Some(uuid::Uuid::NAMESPACE_URL),
1156        "oid" | "namespace_oid" => Some(uuid::Uuid::NAMESPACE_OID),
1157        "x500" | "namespace_x500" => Some(uuid::Uuid::NAMESPACE_X500),
1158        _ => uuid::Uuid::parse_str(raw).ok(),
1159    }
1160}
1161
1162fn render_progress_line(args: &[VmValue]) -> String {
1163    let phase = args.first().map(|a| a.display()).unwrap_or_default();
1164    let message = args.get(1).map(|a| a.display()).unwrap_or_default();
1165
1166    if let Some(options) = args.get(2).and_then(|arg| arg.as_dict()) {
1167        if let Some(mode) = progress_dict_str(options, "mode") {
1168            match mode {
1169                "spinner" => {
1170                    let step = progress_dict_int(options, "step")
1171                        .or_else(|| progress_dict_int(options, "current"))
1172                        .unwrap_or(0);
1173                    let frame = spinner_frame(step);
1174                    return format!("[{phase}] {frame} {message}\n");
1175                }
1176                "bar" => {
1177                    let current = progress_dict_int(options, "current").unwrap_or(0);
1178                    let total = progress_dict_int(options, "total").unwrap_or(0);
1179                    let width = progress_dict_int(options, "width")
1180                        .unwrap_or(10)
1181                        .clamp(3, 40) as usize;
1182                    let bar = render_progress_bar(current, total, width);
1183                    return format!("[{phase}] {bar} {message} ({current}/{total})\n");
1184                }
1185                _ => {}
1186            }
1187        }
1188    }
1189
1190    let progress = args.get(2).and_then(|a| a.as_int());
1191    let total = args.get(3).and_then(|a| a.as_int());
1192    match (progress, total) {
1193        (Some(p), Some(t)) => format!("[{phase}] {message} ({p}/{t})\n"),
1194        (Some(p), None) => format!("[{phase}] {message} ({p}%)\n"),
1195        _ => format!("[{phase}] {message}\n"),
1196    }
1197}
1198
1199fn progress_dict_int(options: &crate::value::DictMap, key: &str) -> Option<i64> {
1200    options.get(key).and_then(|value| value.as_int())
1201}
1202
1203fn progress_dict_str<'a>(options: &'a crate::value::DictMap, key: &str) -> Option<&'a str> {
1204    match options.get(key) {
1205        Some(VmValue::String(value)) => Some(value.as_ref()),
1206        _ => None,
1207    }
1208}
1209
1210fn spinner_frame(step: i64) -> &'static str {
1211    match step.rem_euclid(4) {
1212        0 => "|",
1213        1 => "/",
1214        2 => "-",
1215        _ => "\\",
1216    }
1217}
1218
1219fn render_progress_bar(current: i64, total: i64, width: usize) -> String {
1220    if total <= 0 {
1221        return format!("[{}]", "-".repeat(width));
1222    }
1223
1224    let clamped = current.clamp(0, total);
1225    let filled = ((clamped as f64 / total as f64) * width as f64).round() as usize;
1226    let filled = filled.min(width);
1227    let empty = width.saturating_sub(filled);
1228    format!("[{}{}]", "#".repeat(filled), "-".repeat(empty))
1229}
1230
1231fn vm_write_log(level: &str, level_num: u8, args: &[VmValue], out: &mut String) {
1232    if level_num < VM_MIN_LOG_LEVEL.load(Ordering::Relaxed) {
1233        return;
1234    }
1235    let msg = args.first().map(|a| a.display()).unwrap_or_default();
1236    let fields = args.get(1).and_then(|v| {
1237        if let VmValue::Dict(d) = v {
1238            Some(&**d)
1239        } else {
1240            None
1241        }
1242    });
1243    let line = vm_build_log_line(level, &msg, fields);
1244    write_stdout(out, &line);
1245}
1246
1247fn ansi_colorize(text: &str, name: &str) -> String {
1248    let code = match name {
1249        "black" => "30",
1250        "red" => "31",
1251        "green" => "32",
1252        "yellow" => "33",
1253        "blue" => "34",
1254        "magenta" => "35",
1255        "cyan" => "36",
1256        "white" => "37",
1257        "bright_black" | "gray" | "grey" => "90",
1258        "bright_red" => "91",
1259        "bright_green" => "92",
1260        "bright_yellow" => "93",
1261        "bright_blue" => "94",
1262        "bright_magenta" => "95",
1263        "bright_cyan" => "96",
1264        "bright_white" => "97",
1265        _ => return text.to_string(),
1266    };
1267    format!("\u{1b}[{code}m{text}\u{1b}[0m")
1268}
1269
1270#[cfg(test)]
1271mod tests {
1272    use crate::value::VmDictExt;
1273    use std::collections::BTreeMap;
1274    #[cfg(unix)]
1275    use std::sync::atomic::{AtomicBool, Ordering};
1276    #[cfg(unix)]
1277    use std::sync::Arc;
1278    #[cfg(unix)]
1279    use std::time::Instant;
1280
1281    use crate::value::VmValue;
1282
1283    use super::{
1284        mock_stdin_builtin, read_line_from_mock_or_real, read_stdin_builtin, render_progress_bar,
1285        render_progress_line, reserve_stdio_for_current_thread, reset_io_state,
1286        set_stdout_passthrough, spinner_frame, stdout_passthrough_enabled, ReadLineOptions,
1287        ReadLineOutcome, STDIN_ALLOWED, STDOUT_ALLOWED,
1288    };
1289
1290    static_assertions::assert_not_impl_any!(super::StdioReservationGuard: Send, Sync);
1291
1292    #[test]
1293    fn stdout_passthrough_state_toggles() {
1294        reset_io_state();
1295
1296        assert!(!stdout_passthrough_enabled());
1297        assert!(!set_stdout_passthrough(true));
1298        assert!(stdout_passthrough_enabled());
1299
1300        assert!(set_stdout_passthrough(false));
1301        assert!(!stdout_passthrough_enabled());
1302    }
1303
1304    #[test]
1305    fn scoped_stdio_reservation_is_repeatable_and_restores_prior_policy() {
1306        reset_io_state();
1307        assert!(STDIN_ALLOWED.get());
1308        assert!(STDOUT_ALLOWED.get());
1309
1310        {
1311            let _outer = reserve_stdio_for_current_thread();
1312            assert_eq!(
1313                read_line_from_mock_or_real(&ReadLineOptions::default()),
1314                ReadLineOutcome::Eof
1315            );
1316            assert!(matches!(
1317                read_stdin_builtin(&[], &mut String::new()).unwrap(),
1318                VmValue::Nil
1319            ));
1320            assert!(matches!(
1321                read_stdin_builtin(&[], &mut String::new()).unwrap(),
1322                VmValue::Nil
1323            ));
1324            mock_stdin_builtin(&[VmValue::string("fixture")], &mut String::new()).unwrap();
1325            assert_eq!(
1326                read_stdin_builtin(&[], &mut String::new())
1327                    .unwrap()
1328                    .display(),
1329                "fixture"
1330            );
1331            assert!(matches!(
1332                read_stdin_builtin(&[], &mut String::new()).unwrap(),
1333                VmValue::Nil
1334            ));
1335            {
1336                let _inner = reserve_stdio_for_current_thread();
1337                assert!(!STDIN_ALLOWED.get());
1338                assert!(!STDOUT_ALLOWED.get());
1339            }
1340            assert!(!STDIN_ALLOWED.get());
1341            assert!(!STDOUT_ALLOWED.get());
1342        }
1343
1344        assert!(STDIN_ALLOWED.get());
1345        assert!(STDOUT_ALLOWED.get());
1346    }
1347
1348    #[test]
1349    fn progress_bar_mode_renders_hash_bar() {
1350        let mut options = BTreeMap::new();
1351        options.put_str("mode", "bar");
1352        options.insert("current".to_string(), VmValue::Int(3));
1353        options.insert("total".to_string(), VmValue::Int(5));
1354        options.insert("width".to_string(), VmValue::Int(10));
1355
1356        let line = render_progress_line(&[
1357            VmValue::String(arcstr::ArcStr::from("build")),
1358            VmValue::String(arcstr::ArcStr::from("Compiling")),
1359            VmValue::dict(options),
1360        ]);
1361
1362        assert_eq!(line, "[build] [######----] Compiling (3/5)\n");
1363    }
1364
1365    #[test]
1366    fn progress_spinner_mode_uses_step_to_pick_frame() {
1367        let mut options = BTreeMap::new();
1368        options.put_str("mode", "spinner");
1369        options.insert("step".to_string(), VmValue::Int(2));
1370
1371        let line = render_progress_line(&[
1372            VmValue::String(arcstr::ArcStr::from("sync")),
1373            VmValue::String(arcstr::ArcStr::from("Waiting")),
1374            VmValue::dict(options),
1375        ]);
1376
1377        assert_eq!(line, "[sync] - Waiting\n");
1378        assert_eq!(spinner_frame(3), "\\");
1379    }
1380
1381    #[test]
1382    fn progress_bar_falls_back_to_empty_bar_for_zero_total() {
1383        assert_eq!(render_progress_bar(2, 0, 5), "[-----]");
1384    }
1385
1386    #[test]
1387    fn read_line_options_preserve_prompt_whitespace() {
1388        let mut options = BTreeMap::new();
1389        options.put_str("prompt", "  > ");
1390        options.insert("trim".to_string(), VmValue::Bool(false));
1391
1392        let parsed = super::parse_read_line_options(&[VmValue::dict(options)]).unwrap();
1393
1394        assert_eq!(parsed.prompt, "  > ");
1395        assert!(!parsed.trim);
1396    }
1397
1398    #[test]
1399    fn read_line_options_reject_unknown_keys() {
1400        let mut options = BTreeMap::new();
1401        options.put_str("promtp", "> ");
1402
1403        let err = super::parse_read_line_options(&[VmValue::dict(options)]).unwrap_err();
1404
1405        match err {
1406            crate::value::VmError::Runtime(message) => assert!(message.contains("promtp")),
1407            other => panic!("expected Runtime error, got {other:?}"),
1408        }
1409    }
1410
1411    #[cfg(unix)]
1412    struct FdGuard(libc::c_int);
1413
1414    #[cfg(unix)]
1415    impl Drop for FdGuard {
1416        fn drop(&mut self) {
1417            let _ = unsafe { libc::close(self.0) };
1418        }
1419    }
1420
1421    #[cfg(unix)]
1422    fn pipe_pair() -> (FdGuard, FdGuard) {
1423        let mut fds = [0; 2];
1424        assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0);
1425        (FdGuard(fds[0]), FdGuard(fds[1]))
1426    }
1427
1428    #[cfg(unix)]
1429    #[test]
1430    fn read_line_from_fd_times_out_without_data() {
1431        let (read_fd, _write_fd) = pipe_pair();
1432        let outcome = super::read_line_from_fd_unix(
1433            read_fd.0,
1434            &ReadLineOptions {
1435                timeout_ms: Some(10),
1436                ..ReadLineOptions::default()
1437            },
1438        );
1439
1440        assert_eq!(outcome, ReadLineOutcome::Timeout);
1441    }
1442
1443    #[cfg(unix)]
1444    #[test]
1445    fn read_line_from_fd_observes_interrupt_without_stdin_activity() {
1446        let (read_fd, _write_fd) = pipe_pair();
1447        let cancel = Arc::new(AtomicBool::new(false));
1448        let cancel_from_thread = Arc::clone(&cancel);
1449        let _guard = crate::op_interrupt::install(Some(cancel), None);
1450        let interrupter = std::thread::spawn(move || {
1451            // No fixed "wait for the reader to park" sleep: the reader re-checks
1452            // the cancel flag every `READ_LINE_INTERRUPT_POLL` heartbeat, so it
1453            // observes this store within one interval regardless of ordering.
1454            // A blind sleep would only add wall time and reintroduce a race.
1455            cancel_from_thread.store(true, Ordering::SeqCst);
1456        });
1457
1458        let started = Instant::now();
1459        let outcome = super::read_line_from_fd_unix(read_fd.0, &ReadLineOptions::default());
1460
1461        interrupter.join().expect("interrupter thread joins");
1462        assert_eq!(outcome, ReadLineOutcome::Interrupt);
1463        assert!(
1464            started.elapsed() < super::READ_LINE_INTERRUPT_POLL * 25,
1465            "interrupt heartbeat should wake idle read_line within a few poll \
1466             intervals, took {:?}",
1467            started.elapsed()
1468        );
1469    }
1470
1471    #[cfg(unix)]
1472    #[test]
1473    fn read_line_from_fd_honors_trim_option() {
1474        let (read_fd, write_fd) = pipe_pair();
1475        let payload = b"  alpha  \n";
1476        assert_eq!(
1477            unsafe { libc::write(write_fd.0, payload.as_ptr().cast(), payload.len()) },
1478            payload.len() as isize
1479        );
1480        let outcome = super::read_line_from_fd_unix(
1481            read_fd.0,
1482            &ReadLineOptions {
1483                timeout_ms: Some(100),
1484                trim: false,
1485                ..ReadLineOptions::default()
1486            },
1487        );
1488
1489        assert_eq!(outcome, ReadLineOutcome::Ok("  alpha  ".to_string()));
1490    }
1491}