kaeru 0.1.9

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! Process information.
//!
//! Everything above this module works on the [`ProcessTable`] trait, so that
//! the logic can be tested with a fake table. [`system::SystemTable`] is the
//! real one, read from the OS.

pub mod system;

use std::path::PathBuf;

use crate::engine::note::ProcessRef;
use crate::engine::rules::Liveness;

/// How far apart two start times of the same process can be. Different OS
/// APIs round start times differently.
pub const START_TOLERANCE_MS: u64 = 2_000;

/// How many processes `lineage` walks at most. Real process trees are
/// shallow; the limit guards against loops in bad data.
const MAX_DEPTH: usize = 32;

/// What kaeru knows about one running process.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProcInfo {
    pub pid: u32,
    /// The parent's process id, if the process has a parent.
    pub parent: Option<u32>,
    /// The executable's file name, such as `WindowsTerminal.exe` or `zsh`.
    pub name: String,
    /// The executable's full path, if it can be read.
    pub exe: Option<PathBuf>,
    /// The start time, in milliseconds since the Unix epoch, or `None` when
    /// the process can't be inspected.
    pub started_ms: Option<u64>,
    /// The command line, with its arguments joined by spaces, if it can be
    /// read.
    pub command_line: Option<String>,
    /// The command line's arguments, the program first, as the OS keeps
    /// them, so that an argument with spaces in it stays one argument. Empty
    /// when they can't be read.
    pub arguments: Vec<String>,
    /// The folder the process works in, if it can be read.
    pub cwd: Option<PathBuf>,
}

impl ProcInfo {
    /// Returns this process as a [`ProcessRef`] for a note, or `None` when
    /// its start time is unknown.
    pub fn to_ref(&self) -> Option<ProcessRef> {
        Some(ProcessRef {
            pid: self.pid,
            started_ms: self.started_ms?,
        })
    }

    /// Returns whether this is the process that a note names: the same id,
    /// started at the same time, give or take how start times are rounded.
    pub fn is(&self, process: &ProcessRef) -> bool {
        self.pid == process.pid
            && self
                .started_ms
                .is_some_and(|started| started.abs_diff(process.started_ms) <= START_TOLERANCE_MS)
    }
}

/// A source of process information: the OS, or a fixed table in tests.
pub trait ProcessTable {
    /// Returns the process with this id, if there is one.
    fn get(&self, pid: u32) -> Option<ProcInfo>;
}

/// Returns the process and its ancestors, nearest first.
///
/// The walk stops when a "parent" started after its child, because then the
/// real parent has ended and an unrelated process reused its id.
pub fn lineage(table: &dyn ProcessTable, pid: u32) -> Vec<ProcInfo> {
    let mut chain: Vec<ProcInfo> = Vec::new();
    let mut next = Some(pid);
    while let Some(id) = next {
        if chain.len() >= MAX_DEPTH || chain.iter().any(|p| p.pid == id) {
            break;
        }
        let Some(info) = table.get(id) else { break };
        let child_start = chain.last().and_then(|child| child.started_ms);
        if let (Some(child), Some(parent)) = (child_start, info.started_ms)
            && parent > child.saturating_add(START_TOLERANCE_MS)
        {
            break;
        }
        next = info.parent;
        chain.push(info);
    }
    chain
}

/// Returns a shell's lineage with its parent's lineage after the shell, for
/// a shell whose real parent the OS doesn't record, as in Git Bash, where
/// mintty starts bash through an MSYS fork. When the parent started after
/// the shell, it is an unrelated process that reused the id, and the
/// shell's own lineage comes back.
pub fn with_parent(shell: Vec<ProcInfo>, parent: Vec<ProcInfo>) -> Vec<ProcInfo> {
    let (Some(first), Some(above)) = (shell.first(), parent.first()) else {
        return shell;
    };
    if let (Some(child), Some(started)) = (first.started_ms, above.started_ms)
        && started > child.saturating_add(START_TOLERANCE_MS)
    {
        return shell;
    }
    let mut chain = vec![first.clone()];
    chain.extend(parent.into_iter().take(MAX_DEPTH - 1));
    chain
}

/// Returns the lineage without the forked copies of a shell at its start.
/// An MSYS shell, such as Git Bash's bash, starts a program by forking
/// itself first, so the program's parent is a copy of the shell, with the
/// same command line, whose parent is the shell itself.
pub fn without_forks(lineage: &[ProcInfo]) -> &[ProcInfo] {
    let mut start = 0;
    while let (Some(process), Some(parent)) = (lineage.get(start), lineage.get(start + 1)) {
        let forked = process.name == parent.name
            && process.command_line.is_some()
            && process.command_line == parent.command_line;
        if !forked {
            break;
        }
        start += 1;
    }
    &lineage[start..]
}

/// Returns whether the process in a note is still the same running process.
pub fn liveness(table: &dyn ProcessTable, process: &ProcessRef) -> Liveness {
    match table.get(process.pid) {
        None => Liveness::Gone,
        Some(ProcInfo {
            started_ms: None, ..
        }) => Liveness::Unknown,
        Some(ProcInfo {
            started_ms: Some(started),
            ..
        }) if started.abs_diff(process.started_ms) <= START_TOLERANCE_MS => Liveness::Running,
        // Same id, different start time: another process reused the id.
        Some(_) => Liveness::Gone,
    }
}

#[cfg(test)]
pub(crate) mod fake {
    use std::collections::HashMap;

    use super::{ProcInfo, ProcessTable};

    /// A fixed process table for tests, built from
    /// `(pid, parent, name, started_ms)` tuples.
    pub(crate) struct FakeTable(HashMap<u32, ProcInfo>);

    impl FakeTable {
        /// Returns a table that holds these processes.
        pub(crate) fn new(entries: &[(u32, Option<u32>, &str, Option<u64>)]) -> Self {
            FakeTable(
                entries
                    .iter()
                    .map(|&(pid, parent, name, started_ms)| {
                        let info = ProcInfo {
                            pid,
                            parent,
                            name: name.into(),
                            exe: None,
                            started_ms,
                            command_line: None,
                            arguments: Vec::new(),
                            cwd: None,
                        };
                        (pid, info)
                    })
                    .collect(),
            )
        }

        /// Returns the table with a command line for one of its processes,
        /// whose arguments are the command line's words.
        pub(crate) fn with_command_line(mut self, pid: u32, command_line: &str) -> Self {
            if let Some(info) = self.0.get_mut(&pid) {
                info.command_line = Some(command_line.into());
                info.arguments = command_line.split_whitespace().map(String::from).collect();
            }
            self
        }

        /// Returns the table with the arguments of one of its processes,
        /// which may have spaces in them.
        pub(crate) fn with_arguments(mut self, pid: u32, arguments: &[&str]) -> Self {
            if let Some(info) = self.0.get_mut(&pid) {
                info.command_line = Some(arguments.join(" "));
                info.arguments = arguments.iter().map(|&argument| argument.into()).collect();
            }
            self
        }

        /// Returns the table with the folder that one of its processes works
        /// in.
        pub(crate) fn with_cwd(mut self, pid: u32, cwd: &str) -> Self {
            if let Some(info) = self.0.get_mut(&pid) {
                info.cwd = Some(cwd.into());
            }
            self
        }

        /// Returns the processes in the table.
        pub(crate) fn processes(&self) -> Vec<ProcInfo> {
            let mut processes: Vec<ProcInfo> = self.0.values().cloned().collect();
            processes.sort_by_key(|process| process.pid);
            processes
        }

        /// Returns the table with an executable path for one of its
        /// processes.
        pub(crate) fn with_exe(mut self, pid: u32, exe: &str) -> Self {
            if let Some(info) = self.0.get_mut(&pid) {
                info.exe = Some(exe.into());
            }
            self
        }
    }

    impl ProcessTable for FakeTable {
        fn get(&self, pid: u32) -> Option<ProcInfo> {
            self.0.get(&pid).cloned()
        }
    }
}

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

    #[test]
    fn a_shell_s_lineage_continues_with_the_parent_it_was_given() {
        // Windows recorded a parent that is gone; the real one is 10.
        let table = FakeTable::new(&[
            (20, Some(15), "bash.exe", Some(2_000)),
            (10, Some(5), "mintty.exe", Some(1_000)),
            (5, None, "explorer.exe", Some(500)),
        ]);
        let chain = with_parent(lineage(&table, 20), lineage(&table, 10));
        let pids: Vec<u32> = chain.iter().map(|process| process.pid).collect();
        assert_eq!(pids, [20, 10, 5]);
    }

    #[test]
    fn forked_copies_of_a_shell_are_skipped() {
        let table = FakeTable::new(&[
            (30, Some(20), "bash.exe", Some(3_000)),
            (20, Some(10), "bash.exe", Some(2_000)),
            (10, None, "mintty.exe", Some(1_000)),
        ])
        .with_command_line(30, "bash.exe -i -l")
        .with_command_line(20, "bash.exe -i -l");
        let chain = lineage(&table, 30);
        assert_eq!(without_forks(&chain)[0].pid, 20);
        // A bash started inside a bash has a command line of its own.
        let table = FakeTable::new(&[
            (30, Some(20), "bash.exe", Some(3_000)),
            (20, None, "bash.exe", Some(2_000)),
        ])
        .with_command_line(30, "bash")
        .with_command_line(20, "bash.exe -i -l");
        let chain = lineage(&table, 30);
        assert_eq!(without_forks(&chain)[0].pid, 30);
    }

    #[test]
    fn a_parent_that_started_after_the_shell_is_ignored() {
        let table = FakeTable::new(&[
            (20, None, "bash.exe", Some(2_000)),
            (10, None, "mintty.exe", Some(9_000)),
        ]);
        let chain = with_parent(lineage(&table, 20), lineage(&table, 10));
        assert_eq!(chain.len(), 1);
    }

    fn names(chain: &[ProcInfo]) -> Vec<&str> {
        chain.iter().map(|p| p.name.as_str()).collect()
    }

    #[test]
    fn lineage_walks_up_to_the_terminal() {
        let table = FakeTable::new(&[
            (40, Some(30), "kaeru.exe", Some(400)),
            (30, Some(20), "claude.exe", Some(300)),
            (20, Some(10), "powershell.exe", Some(200)),
            (10, Some(1), "WindowsTerminal.exe", Some(100)),
        ]);
        assert_eq!(
            names(&lineage(&table, 40)),
            [
                "kaeru.exe",
                "claude.exe",
                "powershell.exe",
                "WindowsTerminal.exe"
            ]
        );
    }

    #[test]
    fn lineage_stops_at_a_reused_parent_id() {
        // The shell's real parent ended; its id 10 now belongs to a newer
        // process.
        let table = FakeTable::new(&[
            (20, Some(10), "bash", Some(200_000)),
            (10, Some(1), "unrelated", Some(900_000)),
        ]);
        assert_eq!(names(&lineage(&table, 20)), ["bash"]);
    }

    #[test]
    fn lineage_survives_a_loop() {
        let table = FakeTable::new(&[(1, Some(2), "a", Some(1)), (2, Some(1), "b", Some(1))]);
        assert_eq!(names(&lineage(&table, 1)), ["a", "b"]);
    }

    #[test]
    fn liveness_compares_start_times() {
        let table = FakeTable::new(&[(7, None, "zsh", Some(10_000)), (8, None, "x", None)]);
        let at = |pid, started_ms| liveness(&table, &ProcessRef { pid, started_ms });
        assert_eq!(at(7, 10_000), Liveness::Running);
        assert_eq!(
            at(7, 11_500),
            Liveness::Running,
            "within rounding tolerance"
        );
        assert_eq!(
            at(7, 50_000),
            Liveness::Gone,
            "id reused by a newer process"
        );
        assert_eq!(at(9, 10_000), Liveness::Gone, "no such process");
        assert_eq!(at(8, 10_000), Liveness::Unknown, "can't be inspected");
    }

    #[test]
    fn a_process_is_the_one_a_note_names() {
        let table = FakeTable::new(&[(7, None, "zsh", Some(10_000)), (8, None, "x", None)]);
        let zsh = table.get(7).unwrap();
        assert!(zsh.is(&ProcessRef {
            pid: 7,
            started_ms: 11_000
        }));
        assert!(!zsh.is(&ProcessRef {
            pid: 7,
            started_ms: 50_000
        }));
        assert!(!zsh.is(&ProcessRef {
            pid: 9,
            started_ms: 10_000
        }));
        assert!(!table.get(8).unwrap().is(&ProcessRef {
            pid: 8,
            started_ms: 0
        }));
    }
}