pub mod system;
use std::path::PathBuf;
use crate::engine::note::ProcessRef;
use crate::engine::rules::Liveness;
const START_TOLERANCE_MS: u64 = 2_000;
const MAX_DEPTH: usize = 32;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProcInfo {
pub pid: u32,
pub parent: Option<u32>,
pub name: String,
pub exe: Option<PathBuf>,
pub started_ms: Option<u64>,
pub command_line: Option<String>,
pub arguments: Vec<String>,
pub cwd: Option<PathBuf>,
}
impl ProcInfo {
pub fn to_ref(&self) -> Option<ProcessRef> {
Some(ProcessRef {
pid: self.pid,
started_ms: self.started_ms?,
})
}
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)
}
}
pub trait ProcessTable {
fn get(&self, pid: u32) -> Option<ProcInfo>;
}
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
}
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
}
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..]
}
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,
Some(_) => Liveness::Gone,
}
}
#[cfg(test)]
pub(crate) mod fake {
use std::collections::HashMap;
use super::{ProcInfo, ProcessTable};
pub(crate) struct FakeTable(HashMap<u32, ProcInfo>);
impl FakeTable {
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(),
)
}
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
}
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
}
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
}
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
}
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() {
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);
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() {
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
}));
}
}