cyberbrain 0.4.0

Cited, trust-tiered, local-first memory for AI coding agents
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
//! A pseudo-terminal, on Windows and on Unix.
//!
//! Two implementations of four operations: start a program attached to a terminal, read what
//! it prints, write what the person types, and tell it the window changed size. Everything
//! above this module is platform-neutral.
//!
//! Both platforms are here on purpose rather than Windows alone. The desktop launcher is a
//! Windows program, but the machine this is written and tested on is not one, and a terminal
//! whose only implementation runs where nobody can try it is a terminal nobody has tried.
//! The Unix half is also useful in its own right: `cyberbrain serve` runs on a server.

use std::path::Path;

/// What a terminal session is asked to run.
pub struct Spawn<'a> {
    /// argv. Empty means the platform's default shell.
    pub command: &'a [String],
    pub cwd: &'a Path,
    pub cols: u16,
    pub rows: u16,
}

#[cfg(unix)]
pub use unix::Pty;
#[cfg(windows)]
pub use windows::Pty;

// ---------------------------------------------------------------------------------------

#[cfg(unix)]
mod unix {
    use super::{Spawn, default_shell};
    use std::io::{self, Read, Write};
    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
    use std::os::unix::process::CommandExt;
    use std::process::{Child, Command};

    pub struct Pty {
        master: OwnedFd,
        child: Child,
    }

    impl Pty {
        pub fn spawn(req: Spawn<'_>) -> io::Result<Pty> {
            // Safety: openpty fills two descriptors or returns non-zero; nothing else here
            // touches the values until it has said it succeeded.
            let (master, slave) = unsafe {
                let mut m: RawFd = -1;
                let mut s: RawFd = -1;
                // `mut`, and a raw `*mut` below, because glibc declares the last two
                // arguments `const` and Apple's libc does not. A `*mut` weakens to a
                // `*const` at the call, so this one spelling compiles on both; the other way
                // round it built here and failed on macOS, which is where CI found it. Raw
                // rather than `&mut`, because from where clippy stands — glibc — a mutable
                // reference is one the callee does not need, and that warning is an error.
                let mut size = libc::winsize {
                    ws_row: req.rows,
                    ws_col: req.cols,
                    ws_xpixel: 0,
                    ws_ypixel: 0,
                };
                if libc::openpty(
                    &mut m,
                    &mut s,
                    std::ptr::null_mut(),
                    std::ptr::null_mut(),
                    &raw mut size,
                ) != 0
                {
                    return Err(io::Error::last_os_error());
                }
                // Close-on-exec on the master, before anything is started through it.
                // Without it every program in the terminal — and everything it starts, to
                // any depth — inherits a writable handle on the terminal itself: enough to
                // forge output the page renders as the program's, and to read input meant
                // for something else. It also keeps the descriptor alive in every survivor.
                libc::fcntl(m, libc::F_SETFD, libc::FD_CLOEXEC);
                (OwnedFd::from_raw_fd(m), OwnedFd::from_raw_fd(s))
            };

            let argv = default_shell(req.command);
            let mut cmd = Command::new(&argv[0]);
            cmd.args(&argv[1..])
                .current_dir(req.cwd)
                // What a program looks at to decide whether it may use colour and cursor
                // movement. Without it many tools fall back to their dumbest output.
                .env("TERM", "xterm-256color");

            let slave_fd = slave.as_raw_fd();
            unsafe {
                cmd.pre_exec(move || {
                    // A session of its own, with the pty as its controlling terminal, or
                    // Ctrl-C reaches this process instead of the child's job.
                    if libc::setsid() < 0 {
                        return Err(io::Error::last_os_error());
                    }
                    if libc::ioctl(slave_fd, libc::TIOCSCTTY as _, 0) < 0 {
                        return Err(io::Error::last_os_error());
                    }
                    for target in [libc::STDIN_FILENO, libc::STDOUT_FILENO, libc::STDERR_FILENO] {
                        if libc::dup2(slave_fd, target) < 0 {
                            return Err(io::Error::last_os_error());
                        }
                    }
                    if slave_fd > libc::STDERR_FILENO {
                        libc::close(slave_fd);
                    }
                    Ok(())
                });
            }
            let child = cmd.spawn()?;
            // The parent has no use for the slave end, and holding it open would mean the
            // read below never sees end-of-file when the child exits.
            drop(slave);
            Ok(Pty { master, child })
        }

        pub fn reader(&self) -> io::Result<Box<dyn Read + Send>> {
            Ok(Box::new(std::fs::File::from(self.master.try_clone()?)))
        }

        pub fn writer(&self) -> io::Result<Box<dyn Write + Send>> {
            Ok(Box::new(std::fs::File::from(self.master.try_clone()?)))
        }

        pub fn resize(&self, cols: u16, rows: u16) -> io::Result<()> {
            let size = libc::winsize {
                ws_row: rows,
                ws_col: cols,
                ws_xpixel: 0,
                ws_ypixel: 0,
            };
            // Safety: a valid descriptor and a filled struct; the kernel copies it out.
            if unsafe { libc::ioctl(self.master.as_raw_fd(), libc::TIOCSWINSZ, &size) } < 0 {
                return Err(io::Error::last_os_error());
            }
            Ok(())
        }

        /// End the session, not just the shell.
        ///
        /// `pre_exec` calls `setsid`, so the child leads its own process group and its group
        /// id is its process id. Killing only the child left everything it had started
        /// running — and those survivors hold the slave open, so the master never reports
        /// end of file, so the reader thread waits for ever holding a thread and two
        /// descriptors. One closed browser tab, one leaked thread, for the life of the
        /// process.
        ///
        /// A grandchild that calls `setsid` for itself still escapes, and that is correct:
        /// `nohup` and `tmux` exist to survive their terminal.
        pub fn kill(&mut self) {
            // Safety: the pid is the group id because of `setsid`, and a negative pid is
            // how `kill` addresses a group.
            unsafe {
                libc::kill(-(self.child.id() as libc::pid_t), libc::SIGKILL);
            }
            let _ = self.child.kill();
            let _ = self.child.wait();
        }

        pub fn exited(&mut self) -> Option<i32> {
            self.child
                .try_wait()
                .ok()
                .flatten()
                .map(|s| s.code().unwrap_or(-1))
        }
    }
}

// ---------------------------------------------------------------------------------------

#[cfg(windows)]
mod windows {
    use super::{Spawn, default_shell};
    use std::io::{self, Read, Write};
    use std::os::windows::io::{FromRawHandle, OwnedHandle};
    use std::ptr;
    use windows_sys::Win32::Foundation::{
        CloseHandle, HANDLE, INVALID_HANDLE_VALUE, WAIT_OBJECT_0,
    };
    use windows_sys::Win32::System::Console::{
        COORD, ClosePseudoConsole, CreatePseudoConsole, HPCON, ResizePseudoConsole,
    };
    use windows_sys::Win32::System::Pipes::CreatePipe;
    use windows_sys::Win32::System::Threading::{
        CreateProcessW, DeleteProcThreadAttributeList, EXTENDED_STARTUPINFO_PRESENT,
        GetExitCodeProcess, InitializeProcThreadAttributeList, LPPROC_THREAD_ATTRIBUTE_LIST,
        PROCESS_INFORMATION, STARTUPINFOEXW, TerminateProcess, UpdateProcThreadAttribute,
        WaitForSingleObject,
    };

    /// Documented in the ConPTY samples and not exported by windows-sys.
    const PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE: usize = 0x0002_0016;

    pub struct Pty {
        pc: HPCON,
        /// What we write into: the terminal's input.
        input: OwnedHandle,
        /// What we read from: the terminal's output.
        output: OwnedHandle,
        process: OwnedHandle,
        thread: OwnedHandle,
    }

    // The handles are owned by this struct and only touched through it.
    unsafe impl Send for Pty {}

    impl Pty {
        pub fn spawn(req: Spawn<'_>) -> io::Result<Pty> {
            unsafe {
                // Two pipes, crossed: the console reads what we write, and writes what we
                // read. Both ends of each are created, and the two the console keeps are
                // closed here once it has them.
                let (mut in_read, mut in_write) = (INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE);
                let (mut out_read, mut out_write) = (INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE);
                if CreatePipe(&mut in_read, &mut in_write, ptr::null(), 0) == 0 {
                    return Err(io::Error::last_os_error());
                }
                if CreatePipe(&mut out_read, &mut out_write, ptr::null(), 0) == 0 {
                    // The first pair was made and nobody owns it yet.
                    let e = io::Error::last_os_error();
                    CloseHandle(in_read);
                    CloseHandle(in_write);
                    return Err(e);
                }

                // `HPCON` is an integer handle in windows-sys, not a pointer.
                let mut pc: HPCON = 0;
                let size = COORD {
                    X: req.cols.max(1) as i16,
                    Y: req.rows.max(1) as i16,
                };
                let hr = CreatePseudoConsole(size, in_read, out_write, 0, &mut pc);
                // The console holds its own references now.
                CloseHandle(in_read);
                CloseHandle(out_write);
                if hr != 0 {
                    CloseHandle(in_write);
                    CloseHandle(out_read);
                    return Err(io::Error::from_raw_os_error(hr));
                }

                // The attribute list is what ties the new process to the console. Sized by
                // asking, because the size is not ours to assume.
                let mut bytes: usize = 0;
                InitializeProcThreadAttributeList(ptr::null_mut(), 1, 0, &mut bytes);
                let mut attrs = vec![0u8; bytes];
                let list = attrs.as_mut_ptr() as LPPROC_THREAD_ATTRIBUTE_LIST;
                if InitializeProcThreadAttributeList(list, 1, 0, &mut bytes) == 0 {
                    let e = io::Error::last_os_error();
                    ClosePseudoConsole(pc);
                    CloseHandle(in_write);
                    CloseHandle(out_read);
                    return Err(e);
                }
                if UpdateProcThreadAttribute(
                    list,
                    0,
                    PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
                    pc as *const std::ffi::c_void,
                    size_of::<HPCON>(),
                    ptr::null_mut(),
                    ptr::null(),
                ) == 0
                {
                    // The list was initialised, so it has allocations of its own to give
                    // back — a failure here is not a reason to keep them.
                    let e = io::Error::last_os_error();
                    DeleteProcThreadAttributeList(list);
                    ClosePseudoConsole(pc);
                    CloseHandle(in_write);
                    CloseHandle(out_read);
                    return Err(e);
                }

                let mut si: STARTUPINFOEXW = std::mem::zeroed();
                si.StartupInfo.cb = size_of::<STARTUPINFOEXW>() as u32;
                si.lpAttributeList = list;
                let mut pi: PROCESS_INFORMATION = std::mem::zeroed();

                let mut line = wide(&super::command_line(&default_shell(req.command)));
                let cwd = wide(&req.cwd.display().to_string());
                let ok = CreateProcessW(
                    ptr::null(),
                    line.as_mut_ptr(),
                    ptr::null(),
                    ptr::null(),
                    0,
                    EXTENDED_STARTUPINFO_PRESENT,
                    ptr::null(),
                    cwd.as_ptr(),
                    &si.StartupInfo,
                    &mut pi,
                );
                DeleteProcThreadAttributeList(list);
                if ok == 0 {
                    // Every failed start used to cost two kernel handles, in a process that
                    // runs for days: a profile pointing at a program that is not installed
                    // is one click, and people click it more than once.
                    let e = io::Error::last_os_error();
                    ClosePseudoConsole(pc);
                    CloseHandle(in_write);
                    CloseHandle(out_read);
                    return Err(e);
                }

                Ok(Pty {
                    pc,
                    input: OwnedHandle::from_raw_handle(in_write as _),
                    output: OwnedHandle::from_raw_handle(out_read as _),
                    process: OwnedHandle::from_raw_handle(pi.hProcess as _),
                    thread: OwnedHandle::from_raw_handle(pi.hThread as _),
                })
            }
        }

        pub fn reader(&self) -> io::Result<Box<dyn Read + Send>> {
            Ok(Box::new(std::fs::File::from(self.output.try_clone()?)))
        }

        pub fn writer(&self) -> io::Result<Box<dyn Write + Send>> {
            Ok(Box::new(std::fs::File::from(self.input.try_clone()?)))
        }

        pub fn resize(&self, cols: u16, rows: u16) -> io::Result<()> {
            let size = COORD {
                X: cols.max(1) as i16,
                Y: rows.max(1) as i16,
            };
            let hr = unsafe { ResizePseudoConsole(self.pc, size) };
            if hr != 0 {
                return Err(io::Error::from_raw_os_error(hr));
            }
            Ok(())
        }

        pub fn kill(&mut self) {
            unsafe {
                TerminateProcess(handle(&self.process), 1);
                WaitForSingleObject(handle(&self.process), 2000);
            }
        }

        /// Whether the program has ended, and with what.
        ///
        /// The liveness question goes to `WaitForSingleObject`, not to the exit code. The
        /// obvious version compares the code against `STILL_ACTIVE`, which is 259 — and a
        /// program that legitimately exits with 259 then counts as running for ever, so the
        /// page never hears that it stopped and the pane simply goes quiet. The wait answers
        /// the question that was actually asked; the code is read only once it has.
        pub fn exited(&mut self) -> Option<i32> {
            if unsafe { WaitForSingleObject(handle(&self.process), 0) } != WAIT_OBJECT_0 {
                return None;
            }
            let mut code: u32 = 0;
            if unsafe { GetExitCodeProcess(handle(&self.process), &mut code) } == 0 {
                return Some(-1);
            }
            Some(code as i32)
        }
    }

    impl Drop for Pty {
        fn drop(&mut self) {
            // The console before the handles: closing it is what tells the child its
            // terminal is gone, and a child holding a pipe nobody reads never exits.
            unsafe { ClosePseudoConsole(self.pc) };
            let _ = &self.thread;
        }
    }

    fn handle(h: &OwnedHandle) -> HANDLE {
        use std::os::windows::io::AsRawHandle;
        h.as_raw_handle() as HANDLE
    }

    fn wide(s: &str) -> Vec<u16> {
        use std::ffi::OsStr;
        use std::os::windows::ffi::OsStrExt;
        OsStr::new(s).encode_wide().chain(Some(0)).collect()
    }
}

// ---------------------------------------------------------------------------------------

/// argv joined the way `CreateProcessW` parses it back apart.
///
/// Quoted when a piece contains a space, because the person typing
/// `ssh root@host "cd /srv && ls"` means one argument and not three.
///
/// The backslash rule is the fiddly half, and doubling every one of them — which is what
/// this did first — is wrong. `CommandLineToArgvW` treats a backslash as special *only*
/// in a run immediately before a quote: there, `2n` backslashes plus `"` open or close
/// quoting, `2n+1` produce `n` backslashes and a literal quote, and anywhere else a
/// backslash is itself. Doubling them all turned
/// `C:\Program Files\Git\bin\bash.exe` into a path with doubled separators. It was
/// invisible while `tokenise` was eating backslashes before they ever reached here.
/// Only Windows calls this, and every platform tests it. That is the point of it being
/// here rather than inside `mod windows`: the rule it implements is string handling, the
/// mistake in it was string handling, and a rule that can only be checked where nobody can
/// run the checks is a rule nobody checks.
#[cfg_attr(not(windows), allow(dead_code))]
pub(super) fn command_line(argv: &[String]) -> String {
    let mut line = String::new();
    for (i, part) in argv.iter().enumerate() {
        if i > 0 {
            line.push(' ');
        }
        if !part.is_empty() && !part.contains([' ', '\t', '"']) {
            line.push_str(part);
            continue;
        }
        line.push('"');
        let mut backslashes = 0usize;
        for c in part.chars() {
            match c {
                '\\' => {
                    backslashes += 1;
                }
                '"' => {
                    // The run before a quote is doubled, then the quote is escaped.
                    line.extend(std::iter::repeat_n('\\', backslashes * 2 + 1));
                    backslashes = 0;
                    line.push('"');
                }
                other => {
                    line.extend(std::iter::repeat_n('\\', backslashes));
                    backslashes = 0;
                    line.push(other);
                }
            }
        }
        // The closing quote is a quote too: the run before it doubles.
        line.extend(std::iter::repeat_n('\\', backslashes * 2));
        line.push('"');
    }
    line
}

/// The command to run, or the platform's usual shell when none was named.
fn default_shell(command: &[String]) -> Vec<String> {
    if !command.is_empty() {
        return command.to_vec();
    }
    if cfg!(windows) {
        vec![std::env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".to_string())]
    } else {
        vec![std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string())]
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(unix)]
    use std::io::{self, Read};

    /// A terminal is not a pipe, and the difference is what these check: the child gets a
    /// device it believes is a terminal, and what it prints comes back with the line endings
    /// a terminal produces.
    #[cfg(unix)]
    #[test]
    fn a_program_runs_in_it_and_its_output_comes_back() {
        let dir = tempfile::tempdir().unwrap();
        let mut pty = Pty::spawn(Spawn {
            command: &[
                "/bin/sh".into(),
                "-c".into(),
                "printf 'hello-from-pty'".into(),
            ],
            cwd: dir.path(),
            cols: 80,
            rows: 24,
        })
        .unwrap();
        let mut out = pty.reader().unwrap();
        let mut buf = Vec::new();
        // Read to end: the master reports EOF once the child is gone and the slave is
        // closed, which is the contract the session loop above depends on.
        let _ = out.read_to_end(&mut buf);
        let text = String::from_utf8_lossy(&buf);
        assert!(text.contains("hello-from-pty"), "{text:?}");
        pty.kill();
    }

    #[cfg(unix)]
    #[test]
    fn the_child_is_told_it_is_a_terminal() {
        let dir = tempfile::tempdir().unwrap();
        // `test -t 0` is the question itself: a pipe answers no, a terminal answers yes.
        let mut pty = Pty::spawn(Spawn {
            command: &[
                "/bin/sh".into(),
                "-c".into(),
                "test -t 0 && printf yes || printf no".into(),
            ],
            cwd: dir.path(),
            cols: 80,
            rows: 24,
        })
        .unwrap();
        let mut buf = Vec::new();
        let _ = pty.reader().unwrap().read_to_end(&mut buf);
        assert_eq!(String::from_utf8_lossy(&buf).trim(), "yes");
        pty.kill();
    }

    /// The size is not decoration: a full-screen program draws to it, and one that thinks
    /// the window is 80x24 when it is not paints over itself.
    #[cfg(unix)]
    #[test]
    fn the_size_is_the_one_asked_for_and_a_resize_reaches_the_child() {
        let dir = tempfile::tempdir().unwrap();
        let mut pty = Pty::spawn(Spawn {
            command: &[
                "/bin/sh".into(),
                "-c".into(),
                // Report on every window change, so the second line is the resize.
                "trap 'stty size' WINCH; stty size; sleep 2".into(),
            ],
            cwd: dir.path(),
            cols: 120,
            rows: 40,
        })
        .unwrap();
        let mut out = pty.reader().unwrap();
        let first = read_until(&mut out, "40 120");
        assert!(first.contains("40 120"), "{first:?}");

        pty.resize(100, 30).unwrap();
        let second = read_until(&mut out, "30 100");
        assert!(
            second.contains("30 100"),
            "the resize did not reach the child: {second:?}"
        );
        pty.kill();
    }

    /// One `read` is one chunk the kernel had ready, not one line. Reading once and
    /// asserting on it passed here for as long as the terminal has existed and came back
    /// with `"\r\n"` on a CI machine — the tail of the previous line, arriving on its own.
    /// So this reads until the answer is among what has arrived, or the child is gone.
    #[cfg(unix)]
    fn read_until(out: &mut impl Read, needle: &str) -> String {
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        let mut seen = String::new();
        let mut buf = [0u8; 256];
        while std::time::Instant::now() < deadline {
            match out.read(&mut buf) {
                Ok(0) | Err(_) => break,
                Ok(n) => {
                    seen.push_str(&String::from_utf8_lossy(&buf[..n]));
                    if seen.contains(needle) {
                        break;
                    }
                }
            }
        }
        seen
    }

    /// The reader above, against the shape that broke the test: the first chunk is a bare
    /// line ending and the answer arrives split across the two after it.
    #[cfg(unix)]
    #[test]
    fn an_answer_split_across_reads_is_still_found() {
        struct Chunks(Vec<&'static [u8]>);
        impl Read for Chunks {
            fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
                if self.0.is_empty() {
                    return Ok(0);
                }
                let c = self.0.remove(0);
                buf[..c.len()].copy_from_slice(c);
                Ok(c.len())
            }
        }
        let mut chunks = Chunks(vec![b"\r\n", b"30 1", b"00\r\n"]);
        assert_eq!(read_until(&mut chunks, "30 100"), "\r\n30 100\r\n");
        // And an answer that never comes ends with the child, not with a hang.
        let mut none = Chunks(vec![b"\r\n"]);
        assert_eq!(read_until(&mut none, "30 100"), "\r\n");
    }

    #[cfg(unix)]
    #[test]
    fn what_is_typed_reaches_the_program() {
        let dir = tempfile::tempdir().unwrap();
        let mut pty = Pty::spawn(Spawn {
            command: &[
                "/bin/sh".into(),
                "-c".into(),
                "read line; printf \"got:%s\" \"$line\"".into(),
            ],
            cwd: dir.path(),
            cols: 80,
            rows: 24,
        })
        .unwrap();
        pty.writer().unwrap().write_all(b"typed-this\n").unwrap();
        let mut buf = Vec::new();
        let _ = pty.reader().unwrap().read_to_end(&mut buf);
        assert!(
            String::from_utf8_lossy(&buf).contains("got:typed-this"),
            "{:?}",
            String::from_utf8_lossy(&buf)
        );
        pty.kill();
    }

    /// The rule `CommandLineToArgvW` actually applies, which is not "escape every
    /// backslash". Checked on every platform, because the mistake is in string handling and
    /// not in Win32 — and because it was invisible for as long as the splitter upstream was
    /// eating backslashes before they ever arrived here.
    #[test]
    fn a_windows_command_line_escapes_the_way_windows_parses() {
        let line =
            |argv: &[&str]| command_line(&argv.iter().map(|s| s.to_string()).collect::<Vec<_>>());

        // No space: nothing to do, and above all no doubling of the separators.
        assert_eq!(line(&[r"C:\Users\me\tool.exe"]), r"C:\Users\me\tool.exe");
        // A space means quotes, and the backslashes inside stay as they are.
        assert_eq!(
            line(&[r"C:\Program Files\Git\bin\bash.exe"]),
            r#""C:\Program Files\Git\bin\bash.exe""#
        );
        // A trailing backslash before the closing quote doubles, or the quote is escaped by
        // it and the argument runs on.
        assert_eq!(line(&[r"C:\Program Files\"]), r#""C:\Program Files\\""#);
        // A run before a literal quote doubles, and the quote itself is escaped.
        assert_eq!(line(&[r#"a\"b c"#]), r#""a\\\"b c""#);
        // Several parts, joined by a single space.
        assert_eq!(
            line(&["ssh", "-i", r"C:\keys\id_rsa", "root@host"]),
            r"ssh -i C:\keys\id_rsa root@host"
        );
        // An empty argument is an argument.
        assert_eq!(line(&["x", ""]), r#"x """#);
    }

    /// The master must not travel into the terminal it belongs to.
    ///
    /// Everything started in a terminal inherited a writable handle on that terminal:
    /// enough to forge output the page renders as the program's own, and to read input meant
    /// for something else. It also kept the descriptor alive in every survivor, so nothing
    /// ever saw end of file.
    #[cfg(unix)]
    #[test]
    fn a_program_in_the_terminal_does_not_inherit_the_terminal_itself() {
        use std::io::Read;
        let dir = tempfile::tempdir().unwrap();
        let mut pty = Pty::spawn(Spawn {
            command: &[
                "/bin/sh".into(),
                "-c".into(),
                "ls -l /proc/self/fd; exit".into(),
            ],
            cwd: dir.path(),
            cols: 80,
            rows: 24,
        })
        .unwrap();
        let mut out = Vec::new();
        let _ = pty.reader().unwrap().read_to_end(&mut out);
        let listing = String::from_utf8_lossy(&out);
        assert!(
            !listing.contains("ptmx"),
            "the child inherited the master side of its own terminal:\n{listing}"
        );
        pty.kill();
    }

    /// The comment on the session loop says "the program goes with the window". That has to
    /// be true of what the program started, not only of the program: a shell is a thing
    /// people start other things from, and killing the shell alone leaves those running
    /// where nobody can see or stop them.
    ///
    /// A grandchild that calls `setsid` for itself still escapes, and that is correct —
    /// `nohup` and `tmux` exist to survive their terminal. This is about the ones that did
    /// not ask to.
    #[cfg(unix)]
    #[test]
    fn killing_a_session_ends_what_it_started() {
        use std::io::Read;
        let dir = tempfile::tempdir().unwrap();
        let mut pty = Pty::spawn(Spawn {
            command: &[
                "/bin/sh".into(),
                "-c".into(),
                // Ignores the hangup the kernel sends when the session leader dies, so only
                // an explicit kill of the group reaches it.
                "trap '' HUP; sleep 60 & echo $!; wait".into(),
            ],
            cwd: dir.path(),
            cols: 80,
            rows: 24,
        })
        .unwrap();
        let mut buf = [0u8; 64];
        let n = pty.reader().unwrap().read(&mut buf).unwrap();
        let pid: i32 = String::from_utf8_lossy(&buf[..n])
            .trim()
            .parse()
            .expect("the shell printed the background pid");
        assert!(alive(pid), "the background program should be running");

        pty.kill();
        // Signals are delivered promptly, but not instantly.
        for _ in 0..50 {
            if !alive(pid) {
                return;
            }
            std::thread::sleep(std::time::Duration::from_millis(20));
        }
        // Do not leave it behind if the assertion is about to fail.
        unsafe { libc::kill(pid, libc::SIGKILL) };
        panic!("{pid} outlived the terminal it was started in");
    }

    #[cfg(unix)]
    fn alive(pid: i32) -> bool {
        // Signal 0 asks without sending: it succeeds while the process exists.
        unsafe { libc::kill(pid, 0) == 0 }
    }

    #[test]
    fn a_named_command_wins_over_the_default_shell() {
        let named = vec!["ssh".to_string(), "root@example".to_string()];
        assert_eq!(default_shell(&named), named);
        assert_eq!(default_shell(&[]).len(), 1);
    }
}