yosh 0.2.7

A POSIX-compliant shell implemented in Rust
Documentation
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
use nix::sys::wait::{WaitPidFlag, WaitStatus, waitpid};
use nix::unistd::Pid;

use super::Executor;
use crate::env::jobs::{self, JobSpecError, JobStatus};
use crate::error::{RuntimeErrorKind, ShellError};
use crate::signal;

/// Result of waiting for a foreground job.
pub(super) struct ForegroundWaitResult {
    /// Exit status of the last process to report.
    pub(super) last_status: i32,
    /// Per-process exit statuses (pid, exit_code) in reporting order — used by pipefail.
    pub(super) process_statuses: Vec<(nix::unistd::Pid, i32)>,
    /// Whether the job was stopped (e.g., Ctrl+Z) rather than exiting.
    pub(super) stopped: bool,
}

/// Strip the leading `%` (and optional `?`) from a job spec string for
/// inclusion in error messages. Matches bash: `wait %sleep` with ambiguous
/// match reports `wait: sleep: ambiguous job spec`, not `%sleep:`.
/// Inputs that don't start with `%` are returned unchanged.
fn strip_job_spec_prefix(spec: &str) -> &str {
    match spec.strip_prefix('%') {
        Some(rest) => rest.strip_prefix('?').unwrap_or(rest),
        None => spec,
    }
}

/// Parsed form of a `jobs [-l|-p] [--] [job_spec...]` invocation.
#[derive(Debug)]
struct JobsOpts {
    long_format: bool,
    pgid_only: bool,
    operands: Vec<String>,
}

/// Parse `jobs` flags + operands. Returns `Err(message)` on unknown
/// option; `message` is already prefixed (e.g., `"jobs: -x: invalid option"`)
/// for the caller to write to stderr verbatim.
fn parse_options(args: &[String]) -> Result<JobsOpts, String> {
    let mut long_format = false;
    let mut pgid_only = false;
    let mut idx = 0;

    while idx < args.len() {
        let a = &args[idx];
        if a == "--" {
            idx += 1;
            break;
        }
        if !a.starts_with('-') || a == "-" {
            break;
        }
        for ch in a[1..].chars() {
            match ch {
                'l' => long_format = true,
                'p' => pgid_only = true,
                other => return Err(format!("jobs: -{}: invalid option", other)),
            }
        }
        idx += 1;
    }

    let operands = args[idx..].to_vec();
    Ok(JobsOpts {
        long_format,
        pgid_only,
        operands,
    })
}

impl Executor {
    /// POSIX wait builtin: wait for background jobs.
    pub(super) fn builtin_wait(&mut self, args: &[String]) -> Result<i32, ShellError> {
        let target_pids: Vec<Pid> = if args.is_empty() {
            self.env
                .process
                .jobs
                .all_jobs()
                .filter(|j| j.status == JobStatus::Running)
                .map(|j| j.pgid)
                .collect()
        } else {
            let mut pids = Vec::new();
            for arg in args {
                if arg.starts_with('%') {
                    match self.env.process.jobs.resolve_job_spec(arg) {
                        Ok(job_id) => {
                            if let Some(job) = self.env.process.jobs.get(job_id) {
                                pids.push(job.pgid);
                            } else {
                                return Err(ShellError::runtime(
                                    RuntimeErrorKind::CommandNotFound,
                                    format!("wait: {}: no such job", arg),
                                ));
                            }
                        }
                        Err(JobSpecError::Ambiguous) => {
                            let display = strip_job_spec_prefix(arg);
                            return Err(ShellError::runtime(
                                RuntimeErrorKind::CommandNotFound,
                                format!("wait: {}: ambiguous job spec", display),
                            ));
                        }
                        Err(_) => {
                            return Err(ShellError::runtime(
                                RuntimeErrorKind::CommandNotFound,
                                format!("wait: {}: no such job", arg),
                            ));
                        }
                    }
                } else {
                    match arg.parse::<i32>() {
                        Ok(n) => pids.push(Pid::from_raw(n)),
                        Err(_) => {
                            return Err(ShellError::runtime(
                                RuntimeErrorKind::InvalidArgument,
                                format!("wait: {}: not a pid or valid job spec", arg),
                            ));
                        }
                    }
                }
            }
            pids
        };

        if target_pids.is_empty() {
            return Ok(self.env.exec.last_exit_status);
        }

        let mut last_status = 0;

        for pid in &target_pids {
            // Check if already completed in jobs table
            let already_done = self
                .env
                .process
                .jobs
                .all_jobs()
                .find(|j| j.pgid == *pid)
                .and_then(|j| match j.status {
                    JobStatus::Done(code) => Some(code),
                    JobStatus::Terminated(sig) => Some(128 + sig),
                    _ => None,
                });
            if let Some(s) = already_done {
                last_status = s;
                continue;
            }

            loop {
                match waitpid(*pid, Some(WaitPidFlag::WNOHANG)) {
                    Ok(WaitStatus::Exited(p, code)) => {
                        self.env
                            .process
                            .jobs
                            .update_status(p, JobStatus::Done(code));
                        last_status = code;
                        break;
                    }
                    Ok(WaitStatus::Signaled(p, sig, _)) => {
                        let code = 128 + sig as i32;
                        self.env
                            .process
                            .jobs
                            .update_status(p, JobStatus::Terminated(sig as i32));
                        last_status = code;
                        break;
                    }
                    Ok(WaitStatus::StillAlive) => {
                        // Poll self-pipe with a short timeout so we also notice
                        // SIGCHLD (which is not written to the self-pipe).
                        let pipe_fd = signal::self_pipe_read_fd();
                        let mut fds = [nix::poll::PollFd::new(
                            unsafe { std::os::fd::BorrowedFd::borrow_raw(pipe_fd) },
                            nix::poll::PollFlags::POLLIN,
                        )];
                        match nix::poll::poll(&mut fds, nix::poll::PollTimeout::from(50u16)) {
                            Ok(_)
                                if fds[0]
                                    .revents()
                                    .is_some_and(|r| r.contains(nix::poll::PollFlags::POLLIN)) =>
                            {
                                let signals = signal::drain_pending_signals();
                                if !signals.is_empty() {
                                    self.process_pending_signals();
                                    last_status = 128 + *signals.last().unwrap();
                                    return Ok(last_status);
                                }
                            }
                            Err(nix::errno::Errno::EINTR) => {
                                // Interrupted — retry waitpid
                            }
                            _ => {
                                // Timeout or no self-pipe data — retry waitpid
                            }
                        }
                    }
                    Err(nix::errno::Errno::ECHILD) => {
                        let err = ShellError::runtime(
                            RuntimeErrorKind::CommandNotFound,
                            format!("wait: pid {} is not a child of this shell", pid),
                        );
                        eprintln!("{}", err);
                        last_status = 127;
                        break;
                    }
                    Err(_) | Ok(_) => break,
                }
            }
        }

        Ok(last_status)
    }

    pub(super) fn builtin_jobs(&mut self, args: &[String]) -> Result<i32, ShellError> {
        let opts = match parse_options(args) {
            Ok(o) => o,
            Err(msg) => {
                eprintln!("yosh: {}", msg);
                return Ok(1);
            }
        };

        // Decide which job IDs to print.
        let mut exit_status = 0;
        let job_ids: Vec<crate::env::jobs::JobId> = if opts.operands.is_empty() {
            self.env.process.jobs.all_jobs().map(|j| j.id).collect()
        } else {
            let mut resolved = Vec::with_capacity(opts.operands.len());
            for spec in &opts.operands {
                match self.env.process.jobs.resolve_job_spec(spec) {
                    Ok(id) => resolved.push(id),
                    Err(JobSpecError::Ambiguous) => {
                        let display = strip_job_spec_prefix(spec);
                        eprintln!("yosh: jobs: {}: ambiguous job spec", display);
                        exit_status = 1;
                    }
                    Err(_) => {
                        eprintln!("yosh: jobs: {}: no such job", spec);
                        exit_status = 1;
                    }
                }
            }
            resolved
        };

        for id in &job_ids {
            if opts.pgid_only {
                if let Some(job) = self.env.process.jobs.get(*id) {
                    println!("{}", job.pgid.as_raw());
                }
            } else if opts.long_format {
                if let Some(line) = self.env.process.jobs.format_job_long(*id) {
                    println!("{}", line);
                }
            } else if let Some(line) = self.env.process.jobs.format_job(*id) {
                println!("{}", line);
            }
        }

        // Mark done/terminated jobs as notified.
        let pending = self.env.process.jobs.pending_notifications();
        for id in pending {
            self.env.process.jobs.mark_notified(id);
        }

        Ok(exit_status)
    }

    pub(super) fn builtin_fg(&mut self, args: &[String]) -> Result<i32, ShellError> {
        if !self.env.mode.options.monitor {
            return Err(ShellError::runtime(
                RuntimeErrorKind::JobControlError,
                "fg: no job control".to_string(),
            ));
        }

        let job_id = if args.is_empty() {
            match self.env.process.jobs.current_id() {
                Some(id) => id,
                None => {
                    return Err(ShellError::runtime(
                        RuntimeErrorKind::JobControlError,
                        "fg: no current job".to_string(),
                    ));
                }
            }
        } else {
            match self.env.process.jobs.resolve_job_spec(&args[0]) {
                Ok(id) => id,
                Err(JobSpecError::Ambiguous) => {
                    let display = strip_job_spec_prefix(&args[0]);
                    return Err(ShellError::runtime(
                        RuntimeErrorKind::JobControlError,
                        format!("fg: {}: ambiguous job spec", display),
                    ));
                }
                Err(_) => {
                    return Err(ShellError::runtime(
                        RuntimeErrorKind::JobControlError,
                        format!("fg: {}: no such job", args[0]),
                    ));
                }
            }
        };

        let (pgid, command) = {
            let job = match self.env.process.jobs.get(job_id) {
                Some(j) => j,
                None => {
                    return Err(ShellError::runtime(
                        RuntimeErrorKind::JobControlError,
                        "fg: job not found".to_string(),
                    ));
                }
            };
            (job.pgid, job.command.clone())
        };

        // Print the command being foregrounded
        eprintln!("{}", command);

        // Update job state
        if let Some(job) = self.env.process.jobs.get_mut(job_id) {
            job.foreground = true;
            if matches!(job.status, JobStatus::Stopped(_)) {
                job.status = JobStatus::Running;
            }
        }

        // Restore the job's saved termios (if any) before handing the
        // terminal back. Falls back to the shell's snapshot so a job that
        // reaches fg without a stored termios (e.g. one that was never
        // stopped) at least lands in the shell's canonical mode.
        if self.env.mode.is_interactive && self.env.mode.options.monitor {
            let target = {
                let job_t = self
                    .env
                    .process
                    .jobs
                    .get(job_id)
                    .and_then(|j| j.saved_tmodes().cloned());
                job_t.or_else(|| self.env.process.jobs.shell_tmodes().cloned())
            };
            if let Some(t) = target {
                let _ = crate::exec::terminal_state::apply_tty_termios(&t);
            }
        }

        // Send SIGCONT to resume if stopped
        nix::sys::signal::killpg(pgid, nix::sys::signal::Signal::SIGCONT).ok();

        // Give terminal to the job
        jobs::give_terminal(pgid).ok();

        // Wait for the job
        let result = self.wait_for_foreground_job(job_id);
        let status = result.last_status;

        // Take terminal back
        jobs::take_terminal(self.env.process.shell_pgid).ok();

        // Restore shell termios after any foreground completion
        // (stopped or exited).
        self.restore_shell_termios_if_interactive();

        Ok(status)
    }

    pub(super) fn builtin_bg(&mut self, args: &[String]) -> Result<i32, ShellError> {
        if !self.env.mode.options.monitor {
            return Err(ShellError::runtime(
                RuntimeErrorKind::JobControlError,
                "bg: no job control".to_string(),
            ));
        }

        let job_id = if args.is_empty() {
            match self.env.process.jobs.current_id() {
                Some(id) => id,
                None => {
                    return Err(ShellError::runtime(
                        RuntimeErrorKind::JobControlError,
                        "bg: no current job".to_string(),
                    ));
                }
            }
        } else {
            match self.env.process.jobs.resolve_job_spec(&args[0]) {
                Ok(id) => id,
                Err(JobSpecError::Ambiguous) => {
                    let display = strip_job_spec_prefix(&args[0]);
                    return Err(ShellError::runtime(
                        RuntimeErrorKind::JobControlError,
                        format!("bg: {}: ambiguous job spec", display),
                    ));
                }
                Err(_) => {
                    return Err(ShellError::runtime(
                        RuntimeErrorKind::JobControlError,
                        format!("bg: {}: no such job", args[0]),
                    ));
                }
            }
        };

        let pgid = {
            let job = match self.env.process.jobs.get(job_id) {
                Some(j) => j,
                None => {
                    return Err(ShellError::runtime(
                        RuntimeErrorKind::JobControlError,
                        "bg: job not found".to_string(),
                    ));
                }
            };
            if !matches!(job.status, JobStatus::Stopped(_)) {
                return Err(ShellError::runtime(
                    RuntimeErrorKind::JobControlError,
                    format!("bg: job {} not stopped", job_id),
                ));
            }
            job.pgid
        };

        // Update job state
        if let Some(job) = self.env.process.jobs.get_mut(job_id) {
            job.status = JobStatus::Running;
            job.foreground = false;
            eprintln!("[{}]+ {} &", job.id, job.command);
        }

        // Send SIGCONT
        nix::sys::signal::killpg(pgid, nix::sys::signal::Signal::SIGCONT).ok();

        Ok(0)
    }

    /// Apply the shell's captured termios snapshot when in interactive
    /// + monitor mode. Best-effort; silent on failure or when the
    ///   snapshot is not set (non-interactive, non-monitor, or capture
    ///   failed at REPL startup).
    pub(super) fn restore_shell_termios_if_interactive(&self) {
        if self.env.mode.is_interactive
            && self.env.mode.options.monitor
            && let Some(shell_t) = self.env.process.jobs.shell_tmodes()
        {
            let _ = crate::exec::terminal_state::apply_tty_termios(shell_t);
        }
    }

    /// Apply the per-job state transition for `WaitStatus::Stopped`.
    ///
    /// Decides only on `(job_id, sig, captured)`: writes the Stopped
    /// status, resets the `notified` flag so the change is reported,
    /// clears the foreground flag, and stores the captured termios —
    /// including `None`, which intentionally clears any previously saved
    /// snapshot. Preserves glibc-manual semantics across mid-session
    /// `exec 0</dev/null`: a stale snapshot from a TTY the shell no
    /// longer drives must not survive into a later `fg`.
    ///
    /// Silently no-ops if `job_id` is no longer in the table; the caller
    /// (`wait_for_foreground_job`) already tolerates that race.
    fn record_stopped_state(
        &mut self,
        job_id: crate::env::jobs::JobId,
        sig: i32,
        captured: Option<nix::sys::termios::Termios>,
    ) {
        if let Some(job) = self.env.process.jobs.get_mut(job_id) {
            job.status = JobStatus::Stopped(sig);
            job.notified = false;
            job.foreground = false;
            job.set_saved_tmodes(captured);
        }
    }

    /// Wait for a foreground job to complete or stop.
    ///
    /// Returns a `ForegroundWaitResult` containing the last exit status,
    /// per-process statuses (for pipefail), and whether the job was stopped.
    ///
    /// Side effect: on `WaitStatus::Stopped`, captures the current TTY
    /// termios when in interactive + monitor mode and stdin is a TTY
    /// (otherwise `None`: the call-site guard short-circuits to `None`
    /// outside that mode, and `capture_tty_termios` itself returns
    /// `Ok(None)` when stdin is no longer a TTY). The result is handed to
    /// `record_stopped_state`, which writes it to `job.saved_tmodes` so a
    /// later `fg` can replay it. The capture is always written — including
    /// `None` overwrites — to avoid keeping a stale snapshot across
    /// `exec 0</dev/null` style redirections.
    pub(super) fn wait_for_foreground_job(
        &mut self,
        job_id: crate::env::jobs::JobId,
    ) -> ForegroundWaitResult {
        let (pgid, total_processes) = match self.env.process.jobs.get(job_id) {
            Some(j) => (j.pgid, j.pids.len()),
            None => {
                return ForegroundWaitResult {
                    last_status: 1,
                    process_statuses: Vec::new(),
                    stopped: false,
                };
            }
        };

        let mut last_status = 0;
        let mut process_statuses: Vec<(nix::unistd::Pid, i32)> = Vec::new();

        loop {
            if process_statuses.len() >= total_processes {
                self.env.process.jobs.mark_notified(job_id);
                self.env.process.jobs.remove_job(job_id);
                break;
            }

            match waitpid(
                nix::unistd::Pid::from_raw(-pgid.as_raw()),
                Some(WaitPidFlag::WUNTRACED),
            ) {
                Ok(WaitStatus::Exited(pid, code)) => {
                    self.env
                        .process
                        .jobs
                        .update_status(pid, JobStatus::Done(code));
                    last_status = code;
                    process_statuses.push((pid, code));
                }
                Ok(WaitStatus::Signaled(pid, sig, _)) => {
                    let code = 128 + sig as i32;
                    self.env
                        .process
                        .jobs
                        .update_status(pid, JobStatus::Terminated(sig as i32));
                    last_status = code;
                    process_statuses.push((pid, code));
                }
                Ok(WaitStatus::Stopped(_pid, sig)) => {
                    // Snapshot the terminal state the stopped child was
                    // using, so `fg` can replay it on resume. Must run
                    // before we print anything, since the print itself
                    // happens in whatever termios the child left behind.
                    let captured = if self.env.mode.is_interactive && self.env.mode.options.monitor
                    {
                        crate::exec::terminal_state::capture_tty_termios()
                            .ok()
                            .flatten()
                    } else {
                        None
                    };
                    self.record_stopped_state(job_id, sig as i32, captured);
                    if let Some(line) = self.env.process.jobs.format_job(job_id) {
                        eprintln!("{}", line);
                    }
                    last_status = 128 + sig as i32;
                    return ForegroundWaitResult {
                        last_status,
                        process_statuses,
                        stopped: true,
                    };
                }
                Err(nix::errno::Errno::ECHILD) => {
                    self.env.process.jobs.remove_job(job_id);
                    break;
                }
                Err(nix::errno::Errno::EINTR) => {
                    self.process_pending_signals();
                    continue;
                }
                _ => break,
            }
        }

        ForegroundWaitResult {
            last_status,
            process_statuses,
            stopped: false,
        }
    }

    /// Display pending job notifications and clean up completed jobs.
    pub fn display_job_notifications(&mut self) {
        let pending = self.env.process.jobs.pending_notifications();
        for id in &pending {
            if let Some(line) = self.env.process.jobs.format_job(*id) {
                eprintln!("{}", line);
            }
            self.env.process.jobs.mark_notified(*id);
        }
        self.env.process.jobs.cleanup_notified();
    }
}

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

    #[test]
    fn parse_options_recognizes_long_flag() {
        let args = vec!["-l".to_string()];
        let opts = parse_options(&args).unwrap();
        assert!(opts.long_format);
        assert!(!opts.pgid_only);
        assert_eq!(opts.operands, Vec::<String>::new());
    }

    #[test]
    fn parse_options_recognizes_pgid_flag() {
        let args = vec!["-p".to_string()];
        let opts = parse_options(&args).unwrap();
        assert!(!opts.long_format);
        assert!(opts.pgid_only);
    }

    #[test]
    fn parse_options_clustered_flags() {
        let args = vec!["-lp".to_string()];
        let opts = parse_options(&args).unwrap();
        assert!(opts.long_format);
        assert!(opts.pgid_only);
    }

    #[test]
    fn parse_options_double_dash_ends_flags() {
        let args = vec!["--".to_string(), "%1".to_string()];
        let opts = parse_options(&args).unwrap();
        assert_eq!(opts.operands, vec!["%1".to_string()]);
    }

    #[test]
    fn parse_options_rejects_unknown_flag() {
        let args = vec!["-x".to_string()];
        let err = parse_options(&args).unwrap_err();
        assert!(err.contains("jobs:") && err.contains("-x"));
    }

    #[test]
    fn parse_options_collects_operands_after_flags() {
        let args = vec!["-l".to_string(), "%1".to_string(), "%2".to_string()];
        let opts = parse_options(&args).unwrap();
        assert!(opts.long_format);
        assert_eq!(opts.operands, vec!["%1".to_string(), "%2".to_string()]);
    }

    #[test]
    fn record_stopped_state_clears_stale_saved_tmodes_on_none_capture() {
        use crate::env::jobs::JobStatus;
        use nix::unistd::Pid;
        let mut exec = Executor::new("yosh", vec![]);
        let pid = Pid::from_raw(12345);
        let id = exec
            .env
            .process
            .jobs
            .add_job(pid, vec![pid], "test-cmd", true);

        // Pre-populate saved_tmodes as if a previous stop captured a TTY snapshot.
        let zeroed: libc::termios = unsafe { std::mem::zeroed() };
        let t: nix::sys::termios::Termios = zeroed.into();
        exec.env
            .process
            .jobs
            .get_mut(id)
            .unwrap()
            .set_saved_tmodes(Some(t));
        assert!(
            exec.env
                .process
                .jobs
                .get(id)
                .unwrap()
                .saved_tmodes()
                .is_some(),
            "precondition: saved_tmodes should be populated before the simulated stop",
        );

        // Simulate the next stop where capture_tty_termios() returned Ok(None)
        // (e.g., after `exec 0</dev/null` redirected stdin away from the TTY).
        exec.record_stopped_state(id, libc::SIGTSTP, None);

        let job = exec
            .env
            .process
            .jobs
            .get(id)
            .expect("job should still be in table");
        assert!(
            job.saved_tmodes().is_none(),
            "stale termios must be cleared when capture returns None",
        );
        assert!(matches!(job.status, JobStatus::Stopped(_)));
        assert!(!job.foreground);
    }

    #[test]
    fn record_stopped_state_stores_some_capture() {
        use crate::env::jobs::JobStatus;
        use nix::unistd::Pid;
        let mut exec = Executor::new("yosh", vec![]);
        let pid = Pid::from_raw(12346);
        let id = exec
            .env
            .process
            .jobs
            .add_job(pid, vec![pid], "test-cmd", true);

        assert!(
            exec.env
                .process
                .jobs
                .get(id)
                .unwrap()
                .saved_tmodes()
                .is_none(),
            "precondition: saved_tmodes should start as None for a fresh job",
        );

        let zeroed: libc::termios = unsafe { std::mem::zeroed() };
        let t: nix::sys::termios::Termios = zeroed.into();

        exec.record_stopped_state(id, libc::SIGTSTP, Some(t));

        let job = exec
            .env
            .process
            .jobs
            .get(id)
            .expect("job should still be in table");
        assert!(job.saved_tmodes().is_some(), "Some capture must be stored");
        assert!(matches!(job.status, JobStatus::Stopped(_)));
        assert!(!job.foreground);
    }

    #[test]
    fn record_stopped_state_no_op_on_unknown_job() {
        let mut exec = Executor::new("yosh", vec![]);
        // job_id 9999 was never added; the helper must silently no-op
        // (the same race-tolerance the caller, `wait_for_foreground_job`,
        // already exhibits when a job is removed between waitpid and the
        // state-write).
        exec.record_stopped_state(9999, libc::SIGTSTP, None);
        assert!(exec.env.process.jobs.get(9999).is_none());
    }
}