microsandbox-cli 0.4.5

CLI binary for managing microsandbox environments.
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
//! `msb logs` command — read the captured output of a sandbox.
//!
//! Reads `<sandbox-dir>/logs/exec.log` (the JSON Lines file produced by
//! the runtime's relay tap, see `crates/runtime/lib/exec_log.rs`),
//! decodes each entry, and renders it to the terminal per
//! `design/runtime/sandbox-logs.md` D5.
//!
//! Supports filtering by source (stdout/stderr/system), time window,
//! tail count, regex search, follow mode (polling), and JSON-Lines
//! passthrough. ANSI escape sequences are passed through to TTYs and
//! stripped on pipes by default (matching `ls`/`grep` convention).

use std::io::{IsTerminal, Write};
use std::path::Path;
use std::time::Duration;

use anyhow::{Context, anyhow};
use chrono::{DateTime, Utc};
use clap::{Args, ValueEnum};
use console::style;
use microsandbox_utils::log_text::{base64_decode, split_leading_timestamp, strip_ansi};
use regex::Regex;
use serde::Deserialize;

//--------------------------------------------------------------------------------------------------
// Types
//--------------------------------------------------------------------------------------------------

/// Show the captured output of a sandbox.
#[derive(Debug, Args)]
pub struct LogsArgs {
    /// Sandbox to read logs from.
    pub name: String,

    /// Show only the last N entries.
    #[arg(long)]
    pub tail: Option<usize>,

    /// Show only entries at or after this point. Accepts an RFC 3339
    /// timestamp or a relative duration like `5m`, `2h`, `1d`.
    #[arg(long)]
    pub since: Option<String>,

    /// Show only entries strictly before this point. Same accepted
    /// formats as `--since`.
    #[arg(long)]
    pub until: Option<String>,

    /// Follow the log: keep reading new entries as they are written.
    /// Exits cleanly when the sandbox stops or on Ctrl-C.
    #[arg(short = 'f', long)]
    pub follow: bool,

    /// Prefix each line with the entry's timestamp.
    #[arg(long)]
    pub timestamps: bool,

    /// Sources to include. Repeat or comma-separate to include
    /// multiple. Defaults to `stdout,stderr` (the captured
    /// user-program output).
    #[arg(long, value_enum, value_delimiter = ',')]
    pub source: Vec<SourceFilter>,

    /// Filter entries to those whose body matches this regex.
    #[arg(long)]
    pub grep: Option<String>,

    /// Emit JSON Lines to stdout without decoding (one entry per line).
    #[arg(long)]
    pub json: bool,

    /// ANSI color handling.
    #[arg(long, value_enum, default_value = "auto")]
    pub color: ColorMode,

    /// Alias for `--color=never`.
    #[arg(long, conflicts_with = "color")]
    pub no_color: bool,

    /// Prefix each line with the session id `[id:N]`. Useful when
    /// the same sandbox has many concurrent or sequential exec
    /// sessions and you want to tell them apart.
    #[arg(long)]
    pub show_id: bool,

    /// Color each session's output a distinct color (cycles through
    /// 8 ANSI colors deterministically by session id). Implies
    /// `--show-id`. Honors `--color`/`--no-color`/`NO_COLOR`.
    #[arg(long)]
    pub color_sessions: bool,
}

/// Source-filter selector for `--source`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[value(rename_all = "lowercase")]
pub enum SourceFilter {
    /// Captured stdout from the primary exec session (pipe mode).
    Stdout,

    /// Captured stderr from the primary exec session (pipe mode).
    Stderr,

    /// Merged stdout+stderr from the primary session running in pty
    /// mode (pty allocation merges streams in the kernel before they
    /// leave the guest).
    Output,

    /// Synthetic system entries injected by the host writer
    /// (lifecycle markers) plus runtime/kernel diagnostics merged at
    /// read time.
    System,

    /// All sources: `stdout`, `stderr`, `output`, and `system`.
    All,
}

/// ANSI color rendering policy for `--color`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[value(rename_all = "lowercase")]
pub enum ColorMode {
    /// Pass ANSI through to TTYs, strip on pipes.
    Auto,

    /// Always pass ANSI through.
    Always,

    /// Always strip ANSI.
    Never,
}

//--------------------------------------------------------------------------------------------------
// Types: internal
//--------------------------------------------------------------------------------------------------

/// Parsed JSON Lines entry from `exec.log`.
#[derive(Debug, Deserialize)]
struct LogEntry {
    /// RFC 3339 timestamp.
    t: String,

    /// Source tag — `"stdout"`, `"stderr"`, `"output"`, or `"system"`.
    s: String,

    /// Decoded body bytes.
    d: String,

    /// Relay-monotonic session id. Present for exec-session entries,
    /// absent for `system` lifecycle markers.
    #[serde(default)]
    id: Option<u64>,

    /// Encoding override. Currently the only legal value is `"b64"`,
    /// indicating `d` is base64. Reserved for future raw-mode capture.
    #[serde(default)]
    e: Option<String>,
}

//--------------------------------------------------------------------------------------------------
// Functions
//--------------------------------------------------------------------------------------------------

/// Execute the `msb logs` command.
pub async fn run(args: LogsArgs) -> anyhow::Result<()> {
    let log_dir = microsandbox::sandbox::logs::log_dir_for(&args.name);
    if !log_dir.exists() {
        return Err(anyhow!(
            "no logs directory for sandbox {:?} (sandbox not found?)",
            &args.name
        ));
    }

    let sources = resolve_sources(&args.source);
    let since = parse_time_arg(args.since.as_deref())?;
    let until = parse_time_arg(args.until.as_deref())?;
    let grep_re = match args.grep.as_deref() {
        Some(pat) => Some(Regex::new(pat).context("invalid --grep regex")?),
        None => None,
    };

    let color_policy = if args.no_color || std::env::var_os("NO_COLOR").is_some() {
        ColorMode::Never
    } else {
        args.color
    };

    // Render the boot-error block first if present (Phase B's
    // boot-error.json sits next to exec.log in the same log_dir).
    render_boot_error_if_present(&log_dir, &args.name, args.json)?;

    // Initial dump (history).
    let mut entries = read_all_entries(&log_dir, sources)?;
    apply_filters(&mut entries, since, until, grep_re.as_ref(), args.tail);
    render_entries(&entries, &args, color_policy)?;

    // Optional follow mode — poll the file for new entries.
    if args.follow {
        let last_t = entries.last().map(|e| e.t.clone());
        follow_loop(
            &log_dir,
            sources,
            &args,
            color_policy,
            last_t,
            grep_re.as_ref(),
        )
        .await?;
    }

    Ok(())
}

//--------------------------------------------------------------------------------------------------
// Functions: Helpers — discovery
//--------------------------------------------------------------------------------------------------

fn resolve_sources(picked: &[SourceFilter]) -> SourceMask {
    if picked.is_empty() {
        // Default = all user-program output, regardless of pty/pipe.
        // Including `output` here means a pty session's logs aren't
        // hidden under the default filter.
        return SourceMask {
            stdout: true,
            stderr: true,
            output: true,
            system: false,
        };
    }
    let mut mask = SourceMask::default();
    for s in picked {
        match s {
            SourceFilter::Stdout => mask.stdout = true,
            SourceFilter::Stderr => mask.stderr = true,
            SourceFilter::Output => mask.output = true,
            SourceFilter::System => mask.system = true,
            SourceFilter::All => {
                mask.stdout = true;
                mask.stderr = true;
                mask.output = true;
                mask.system = true;
            }
        }
    }
    mask
}

#[derive(Debug, Clone, Copy, Default)]
struct SourceMask {
    stdout: bool,
    stderr: bool,
    output: bool,
    system: bool,
}

impl SourceMask {
    fn includes_exec_sources(&self) -> bool {
        self.stdout || self.stderr || self.output
    }
}

//--------------------------------------------------------------------------------------------------
// Functions: Helpers — boot-error block
//--------------------------------------------------------------------------------------------------

fn render_boot_error_if_present(log_dir: &Path, name: &str, json_mode: bool) -> anyhow::Result<()> {
    let boot_err = match microsandbox_runtime::boot_error::BootError::read(log_dir) {
        Ok(Some(b)) => b,
        Ok(None) => return Ok(()),
        Err(_) => return Ok(()),
    };

    if json_mode {
        // Emit as a synthetic JSON Lines entry tagged s: "boot-error".
        // `d` is a string per the documented schema; consumers that
        // need the structured fields can `JSON.parse(d)`.
        let payload = serde_json::to_string(&boot_err).unwrap_or_default();
        let line = serde_json::json!({
            "t": boot_err.t,
            "s": "boot-error",
            "d": payload,
        });
        println!("{line}");
        return Ok(());
    }

    crate::boot_error_render::render(name, &boot_err);
    eprintln!();
    Ok(())
}

//--------------------------------------------------------------------------------------------------
// Functions: Helpers — reading
//--------------------------------------------------------------------------------------------------

/// Read all entries from `exec.log` (and its rotated siblings) plus
/// optional system sources, ordered chronologically.
fn read_all_entries(log_dir: &Path, sources: SourceMask) -> anyhow::Result<Vec<LogEntry>> {
    let mut entries: Vec<LogEntry> = Vec::new();

    if sources.includes_exec_sources() {
        // Rotated files first (.3 → .2 → .1 → current) so output is
        // chronologically ordered.
        for suffix in [".3", ".2", ".1", ""].iter() {
            let path = if suffix.is_empty() {
                log_dir.join("exec.log")
            } else {
                log_dir.join(format!("exec.log{suffix}"))
            };
            if !path.exists() {
                continue;
            }
            append_jsonl_entries(&path, &mut entries, sources)?;
        }
    }

    if sources.system {
        // Cross-merge runtime.log and kernel.log as `s: "system"`.
        // Both are unstructured text; we synthesize timestamps from
        // file mtimes (kernel.log) or per-line tracing prefixes
        // (runtime.log).
        append_text_log_as_system(&log_dir.join("runtime.log"), &mut entries);
        append_text_log_as_system(&log_dir.join("kernel.log"), &mut entries);

        // Stable sort by parsed timestamp. We parse rather than
        // string-compare because runtime.log uses microsecond-precision
        // RFC 3339 (`.615119Z`) while exec.log uses millisecond
        // (`.969Z`) — lexical compare across mixed precisions gives
        // the wrong order.
        entries.sort_by_key(|e| parse_entry_time(&e.t).unwrap_or(DateTime::<Utc>::MIN_UTC));
    }

    Ok(entries)
}

fn append_jsonl_entries(
    path: &Path,
    out: &mut Vec<LogEntry>,
    sources: SourceMask,
) -> anyhow::Result<()> {
    let bytes = std::fs::read(path).with_context(|| format!("reading {}", path.display()))?;
    let text = String::from_utf8_lossy(&bytes);
    for line in text.lines() {
        if line.is_empty() {
            continue;
        }
        match serde_json::from_str::<LogEntry>(line) {
            Ok(entry) => {
                if entry_passes_source_mask(&entry, sources) {
                    out.push(entry);
                }
            }
            Err(_) => {
                // Skip malformed lines — never let one bad entry
                // poison the whole file.
            }
        }
    }
    Ok(())
}

fn entry_passes_source_mask(entry: &LogEntry, mask: SourceMask) -> bool {
    match entry.s.as_str() {
        "stdout" => mask.stdout,
        "stderr" => mask.stderr,
        "output" => mask.output,
        "system" => mask.system,
        _ => true, // Unknown source: include defensively.
    }
}

/// Read a plain-text log file (runtime.log / kernel.log) and append
/// each line as a synthetic `s: "system"` entry.
fn append_text_log_as_system(path: &Path, out: &mut Vec<LogEntry>) {
    if !path.exists() {
        return;
    }
    let bytes = match std::fs::read(path) {
        Ok(b) => b,
        Err(_) => return,
    };
    let text = String::from_utf8_lossy(&bytes);
    let mtime_iso = file_mtime_rfc3339(path).unwrap_or_else(now_rfc3339);

    for line in text.lines() {
        if line.is_empty() {
            continue;
        }
        // tracing-formatted lines start with ANSI color escapes
        // around the timestamp (`\x1b[2m2026-…Z\x1b[0m  INFO …`).
        // Strip ANSI first so the leading-timestamp parser sees a
        // bare RFC 3339 token. Fall back to file mtime if that
        // still fails (e.g. unstructured kernel.log).
        let stripped = strip_ansi(line);
        let (t, body) = match split_leading_timestamp(&stripped) {
            Some((t, body)) => (t.to_string(), body.to_string()),
            None => (mtime_iso.clone(), stripped.clone()),
        };
        out.push(LogEntry {
            t,
            s: "system".into(),
            d: format!("{}\n", body),
            id: None,
            e: None,
        });
    }
}

fn file_mtime_rfc3339(path: &Path) -> Option<String> {
    let meta = std::fs::metadata(path).ok()?;
    let modified = meta.modified().ok()?;
    let dt: DateTime<Utc> = modified.into();
    Some(dt.to_rfc3339_opts(chrono::SecondsFormat::Millis, true))
}

fn now_rfc3339() -> String {
    Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
}

//--------------------------------------------------------------------------------------------------
// Functions: Helpers — filters
//--------------------------------------------------------------------------------------------------

fn apply_filters(
    entries: &mut Vec<LogEntry>,
    since: Option<DateTime<Utc>>,
    until: Option<DateTime<Utc>>,
    grep: Option<&Regex>,
    tail: Option<usize>,
) {
    if let Some(s) = since {
        entries.retain(|e| match parse_entry_time(&e.t) {
            Some(t) => t >= s,
            None => true,
        });
    }
    if let Some(u) = until {
        entries.retain(|e| match parse_entry_time(&e.t) {
            Some(t) => t < u,
            None => true,
        });
    }
    if let Some(re) = grep {
        entries.retain(|e| re.is_match(&e.d));
    }
    if let Some(n) = tail
        && entries.len() > n
    {
        let drop = entries.len() - n;
        entries.drain(0..drop);
    }
}

fn parse_time_arg(input: Option<&str>) -> anyhow::Result<Option<DateTime<Utc>>> {
    let Some(raw) = input else {
        return Ok(None);
    };
    // RFC 3339 first.
    if let Ok(dt) = DateTime::parse_from_rfc3339(raw) {
        return Ok(Some(dt.with_timezone(&Utc)));
    }
    // Relative duration like 5m / 2h / 1d / 30s.
    let dur = parse_duration(raw).with_context(|| {
        format!("could not parse time {raw:?} (expected RFC 3339 or `5m` etc.)")
    })?;
    Ok(Some(Utc::now() - chrono::Duration::from_std(dur)?))
}

fn parse_duration(raw: &str) -> Option<Duration> {
    if raw.is_empty() {
        return None;
    }
    let (num_str, unit) = raw.split_at(raw.len() - 1);
    let n: u64 = num_str.parse().ok()?;
    let secs = match unit {
        "s" => n,
        "m" => n * 60,
        "h" => n * 60 * 60,
        "d" => n * 60 * 60 * 24,
        _ => return None,
    };
    Some(Duration::from_secs(secs))
}

fn parse_entry_time(t: &str) -> Option<DateTime<Utc>> {
    DateTime::parse_from_rfc3339(t)
        .ok()
        .map(|d| d.with_timezone(&Utc))
}

//--------------------------------------------------------------------------------------------------
// Functions: Helpers — rendering
//--------------------------------------------------------------------------------------------------

fn render_entries(entries: &[LogEntry], args: &LogsArgs, color: ColorMode) -> anyhow::Result<()> {
    if args.json {
        let stdout = std::io::stdout();
        let mut out = stdout.lock();
        for entry in entries {
            // Re-emit verbatim as a single JSON Lines line. We
            // serialize from our parsed struct so that any malformed
            // fields are normalized.
            let line = serde_json::to_string(&serde_json::json!({
                "t": entry.t,
                "s": entry.s,
                "d": entry.d,
                "id": entry.id,
                "e": entry.e,
            }))?;
            writeln!(out, "{line}")?;
        }
        return Ok(());
    }

    for entry in entries {
        render_one(entry, args, color)?;
    }
    Ok(())
}

fn render_one(entry: &LogEntry, args: &LogsArgs, color: ColorMode) -> anyhow::Result<()> {
    // Resolve the body bytes (decode base64 if e == "b64"; else use d).
    let body = decode_body(entry);
    let body = apply_color_policy(&body, color);

    // --color-sessions implies --show-id. Resolve both flags + the
    // ANSI policy into a single per-line decoration.
    let want_id_prefix = args.show_id || args.color_sessions;
    let want_session_color = args.color_sessions && color_active(color);

    let body = if want_session_color && let Some(id) = entry.id {
        wrap_in_session_color(&body, id)
    } else {
        body
    };

    let id_prefix = if want_id_prefix {
        Some(format_id_prefix(entry.id, want_session_color))
    } else {
        None
    };

    let final_text = if args.timestamps {
        prefix_with_timestamp(&entry.t, id_prefix.as_deref(), &body)
    } else if let Some(prefix) = id_prefix {
        // Apply id prefix to each line of the body.
        prefix_each_line(&prefix, &body)
    } else {
        body
    };

    // Write every entry to stdout. Splitting by source across stdout
    // and stderr seemed cleaner in theory but produces visible
    // reordering in practice — the two fds buffer independently and
    // the OS can flush them out of chronological order. Users who
    // want to filter by stream still have `--source` and the JSON
    // output mode for programmatic processing.
    let stdout = std::io::stdout();
    let mut out = stdout.lock();
    out.write_all(final_text.as_bytes())?;
    Ok(())
}

/// Whether ANSI color is being emitted given the current policy
/// (used to decide whether session coloring should produce escapes).
fn color_active(mode: ColorMode) -> bool {
    match mode {
        ColorMode::Always => true,
        ColorMode::Never => false,
        ColorMode::Auto => {
            std::io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none()
        }
    }
}

/// 8-color palette used for `--color-sessions`. Skips the colors
/// reserved by the style guide for status semantics
/// (red=error, yellow=warn, dim/gray=secondary) and avoids black /
/// bright-white which collide with terminal background.
const SESSION_PALETTE: &[u8] = &[
    36, // cyan
    35, // magenta
    32, // green
    34, // blue
    96, // bright cyan
    95, // bright magenta
    92, // bright green
    94, // bright blue
];

fn session_color_code(id: u64) -> u8 {
    SESSION_PALETTE[(id as usize) % SESSION_PALETTE.len()]
}

fn wrap_in_session_color(body: &str, id: u64) -> String {
    let code = session_color_code(id);
    // Re-wrap each line independently so background terminal state
    // (e.g. user paging) isn't left with a dangling color escape.
    let mut out = String::with_capacity(body.len() + 16);
    for line in body.split_inclusive('\n') {
        if line == "\n" {
            out.push('\n');
            continue;
        }
        out.push_str(&format!("\x1b[{code}m"));
        if let Some(stripped) = line.strip_suffix('\n') {
            out.push_str(stripped);
            out.push_str("\x1b[0m");
            out.push('\n');
        } else {
            out.push_str(line);
            out.push_str("\x1b[0m");
        }
    }
    out
}

fn format_id_prefix(id: Option<u64>, colored: bool) -> String {
    match id {
        Some(id) => {
            if colored {
                let code = session_color_code(id);
                format!("\x1b[{code}m[id:{id:>3}]\x1b[0m ")
            } else {
                format!("[id:{id:>3}] ")
            }
        }
        None => "[id:sys] ".to_string(),
    }
}

fn prefix_each_line(prefix: &str, body: &str) -> String {
    if body.is_empty() {
        return body.to_string();
    }
    let mut out = String::with_capacity(body.len() + prefix.len() * 2);
    let mut first = true;
    for line in body.split_inclusive('\n') {
        if first {
            out.push_str(prefix);
            first = false;
        } else if !line.is_empty() && line != "\n" {
            out.push_str(prefix);
        }
        out.push_str(line);
    }
    out
}

fn decode_body(entry: &LogEntry) -> String {
    match entry.e.as_deref() {
        Some("b64") => base64_decode(&entry.d)
            .map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
            .unwrap_or_else(|| entry.d.clone()),
        _ => entry.d.clone(),
    }
}

fn apply_color_policy(body: &str, mode: ColorMode) -> String {
    let strip = match mode {
        ColorMode::Always => false,
        ColorMode::Never => true,
        ColorMode::Auto => !std::io::stdout().is_terminal(),
    };
    if strip {
        strip_ansi(body)
    } else {
        body.to_string()
    }
}

fn prefix_with_timestamp(t: &str, id_prefix: Option<&str>, body: &str) -> String {
    if body.is_empty() {
        return body.to_string();
    }
    let ts = style(t).dim().to_string();
    let id_prefix = id_prefix.unwrap_or("");
    let mut out = String::with_capacity(body.len() + t.len() + id_prefix.len() + 4);
    let mut first = true;
    for line in body.split_inclusive('\n') {
        if first {
            out.push_str(&ts);
            out.push('\t');
            out.push_str(id_prefix);
            first = false;
        } else if !line.is_empty() && line != "\n" {
            // Continuation lines: pad with spaces of the same visual
            // width as the timestamp + tab so multi-line bodies read
            // cleanly.
            out.push_str(&" ".repeat(t.len()));
            out.push('\t');
            out.push_str(id_prefix);
        }
        out.push_str(line);
    }
    out
}

//--------------------------------------------------------------------------------------------------
// Functions: Helpers — follow mode
//--------------------------------------------------------------------------------------------------

async fn follow_loop(
    log_dir: &Path,
    sources: SourceMask,
    args: &LogsArgs,
    color: ColorMode,
    mut last_t: Option<String>,
    grep_re: Option<&Regex>,
) -> anyhow::Result<()> {
    let path = log_dir.join("exec.log");
    let (mut last_size, mut last_inode) = match std::fs::metadata(&path) {
        Ok(m) => (m.len(), inode_from_meta(&m)),
        Err(_) => (0u64, 0u64),
    };

    loop {
        tokio::time::sleep(Duration::from_millis(200)).await;

        let Ok(meta) = std::fs::metadata(&path) else {
            // File missing — sandbox stopped or removed. Exit cleanly.
            break;
        };
        let inode = inode_from_meta(&meta);
        let size = meta.len();

        // Detect rotation (inode changed, or size shrank): re-read the
        // whole file from the top.
        let need_full_reread = inode != last_inode || size < last_size;

        if !need_full_reread && size == last_size {
            continue;
        }

        let mut new_entries: Vec<LogEntry> = Vec::new();
        if sources.includes_exec_sources() {
            append_jsonl_entries(&path, &mut new_entries, sources)?;
        }

        // Filter to only entries newer than the last we rendered.
        let cutoff = last_t.clone();
        new_entries.retain(|e| match cutoff.as_deref() {
            Some(c) => e.t.as_str() > c,
            None => true,
        });

        if let Some(re) = grep_re {
            new_entries.retain(|e| re.is_match(&e.d));
        }

        for entry in &new_entries {
            render_one(entry, args, color)?;
            last_t = Some(entry.t.clone());
        }

        last_size = size;
        last_inode = inode;
    }
    Ok(())
}

#[cfg(unix)]
fn inode_from_meta(meta: &std::fs::Metadata) -> u64 {
    use std::os::unix::fs::MetadataExt;
    meta.ino()
}

#[cfg(not(unix))]
fn inode_from_meta(_meta: &std::fs::Metadata) -> u64 {
    0
}

//--------------------------------------------------------------------------------------------------
// Tests
//--------------------------------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_duration_basic() {
        assert_eq!(parse_duration("5m"), Some(Duration::from_secs(300)));
        assert_eq!(parse_duration("2h"), Some(Duration::from_secs(7200)));
        assert_eq!(parse_duration("30s"), Some(Duration::from_secs(30)));
        assert_eq!(parse_duration("1d"), Some(Duration::from_secs(86400)));
        assert_eq!(parse_duration("xyz"), None);
        assert_eq!(parse_duration(""), None);
    }

    #[test]
    fn parse_time_accepts_rfc3339() {
        let parsed = parse_time_arg(Some("2026-04-30T20:32:59.690Z"))
            .unwrap()
            .unwrap();
        let expected = DateTime::parse_from_rfc3339("2026-04-30T20:32:59.690Z")
            .unwrap()
            .with_timezone(&Utc);
        assert_eq!(parsed, expected);
    }

    #[test]
    fn parse_time_accepts_relative() {
        let parsed = parse_time_arg(Some("5m")).unwrap().unwrap();
        // Should be in the past, within ~10 seconds of "now - 5min".
        let now = Utc::now();
        let diff = (now - parsed).num_seconds();
        assert!((290..=310).contains(&diff), "diff was {diff}");
    }

    #[test]
    fn strip_ansi_removes_color_and_cursor() {
        let s = "\x1b[31merror\x1b[0m\x1b[2J\x1b[H text";
        let stripped = strip_ansi(s);
        assert_eq!(stripped, "error text");
    }

    #[test]
    fn strip_ansi_preserves_plain_text() {
        let s = "hello\nworld\n";
        assert_eq!(strip_ansi(s), s);
    }

    #[test]
    fn source_mask_default_excludes_system() {
        let mask = resolve_sources(&[]);
        assert!(mask.stdout && mask.stderr && mask.output && !mask.system);
    }

    #[test]
    fn source_mask_all() {
        let mask = resolve_sources(&[SourceFilter::All]);
        assert!(mask.stdout && mask.stderr && mask.output && mask.system);
    }

    #[test]
    fn source_mask_output_only() {
        let mask = resolve_sources(&[SourceFilter::Output]);
        assert!(mask.output && !mask.stdout && !mask.stderr && !mask.system);
    }

    #[test]
    fn apply_filters_tail_keeps_last_n() {
        let mut entries: Vec<LogEntry> = (0..5)
            .map(|i| LogEntry {
                t: format!("2026-04-30T00:00:0{i}.000Z"),
                s: "stdout".into(),
                d: format!("line {i}"),
                id: Some(1),
                e: None,
            })
            .collect();
        apply_filters(&mut entries, None, None, None, Some(2));
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].d, "line 3");
        assert_eq!(entries[1].d, "line 4");
    }

    #[test]
    fn apply_filters_grep() {
        let mut entries: Vec<LogEntry> = vec![
            LogEntry {
                t: "1".into(),
                s: "stdout".into(),
                d: "ok".into(),
                id: Some(1),
                e: None,
            },
            LogEntry {
                t: "2".into(),
                s: "stdout".into(),
                d: "error: bad".into(),
                id: Some(1),
                e: None,
            },
        ];
        let re = Regex::new("error").unwrap();
        apply_filters(&mut entries, None, None, Some(&re), None);
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].d, "error: bad");
    }
}