Skip to main content

magi/
proc.rs

1//! Spawning child processes without putting a window on the operator's screen.
2//!
3//! Every external program magi runs - the agent CLIs, `git`, `gh`, the
4//! configured verification commands - is a console application. What happens
5//! when one is spawned depends on whether the *parent* has a console, and
6//! magi has two kinds of parent:
7//!
8//! - `magi run` / `magi review` in a terminal. The child inherits that
9//!   console, writes nowhere visible because its pipes are redirected, and
10//!   nothing appears.
11//! - `magi web`, which serves the deck. Its successor is spawned
12//!   `DETACHED_PROCESS` on purpose (see [`crate::web`]): it has to outlive the
13//!   process that started it and must not hold a pipe a terminal is waiting
14//!   on. **That process has no console at all**, so Windows allocates a brand
15//!   new one for each console child - and draws it. An implement wave is
16//!   three agents, so three black windows opened over whatever the operator
17//!   was doing, in front of the browser they were reading the deck in.
18//!
19//! `CREATE_NO_WINDOW` is the answer to exactly that: the child still gets a
20//! console for its standard handles, and that console is never shown. It is
21//! not the same as `DETACHED_PROCESS`, which gives the child no console and
22//! would make a grandchild pop a window of its own for the same reason.
23//!
24//! Nothing here is conditional on how magi was started. A hidden console is
25//! correct in a terminal too: the pipes are redirected either way, so there
26//! was never anything to look at.
27
28/// `CREATE_NO_WINDOW` - run the child's console, but never draw it.
29///
30/// From `processthreadsapi.h`. Spelled out rather than pulled in from a
31/// bindings crate: it is one number that has been stable since Windows 2000,
32/// and the alternative is a dependency for it.
33#[cfg(windows)]
34const CREATE_NO_WINDOW: u32 = 0x0800_0000;
35
36/// Spawn without a visible console window.
37///
38/// Implemented for both `Command` types magi uses - `std` for the few
39/// synchronous calls, `tokio` for everything else - so a call site does not
40/// have to know which one it is holding, and so no call site has to repeat a
41/// `#[cfg(windows)]` block to get it.
42///
43/// A no-op off Windows, where a spawned process has no window to begin with.
44pub trait Quiet {
45    /// Apply it, and hand the command back for further building.
46    fn quiet(&mut self) -> &mut Self;
47}
48
49impl Quiet for std::process::Command {
50    fn quiet(&mut self) -> &mut Self {
51        #[cfg(windows)]
52        {
53            use std::os::windows::process::CommandExt as _;
54            self.creation_flags(CREATE_NO_WINDOW);
55        }
56        self
57    }
58}
59
60impl Quiet for tokio::process::Command {
61    fn quiet(&mut self) -> &mut Self {
62        #[cfg(windows)]
63        {
64            self.creation_flags(CREATE_NO_WINDOW);
65        }
66        self
67    }
68}
69
70/// Best-effort liveness check for a process id, with no dependency beyond
71/// what the platform ships.
72///
73/// There is no portable way in the standard library to ask "is this pid
74/// alive" - no `libc`, no `sysinfo`, nothing magi already depends on binds
75/// the signals API - so this shells out to whatever each platform already
76/// provides: `kill -0` on Unix, `tasklist` on Windows. Both are read-only:
77/// `kill -0` sends no signal, it only checks whether one *could* be sent.
78///
79/// Every uncertain outcome reads as alive, on purpose. This exists so
80/// [`crate::daemon::sweep_stale_claims`] can reclaim a lock faster than its
81/// age-based fallback when the owning process is verifiably gone; the risk
82/// on the other side - reclaiming a lock a live process still holds - lets a
83/// second daemon start a second run on the same task, which costs far more
84/// than leaving one lock alone a little longer. So a helper program that is
85/// missing, output that cannot be parsed, or a permission error that merely
86/// proves the pid exists under another account, all count as "alive" rather
87/// than as license to reclaim.
88#[must_use]
89pub fn pid_alive(pid: u32) -> bool {
90    pid_alive_with(pid, platform_pid_alive)
91}
92
93/// Apply the conservative policy to one platform liveness query.
94///
95/// Kept separate from the OS command so queue and daemon tests can exercise
96/// dead, live, and unavailable answers without requiring permission to list
97/// the machine's processes.
98fn pid_alive_with<F>(pid: u32, query: F) -> bool
99where
100    F: FnOnce(u32) -> std::io::Result<bool>,
101{
102    match query(pid) {
103        Ok(alive) => alive,
104        Err(error) => {
105            // Sweeping is a poll-loop operation, so state the environment
106            // problem at the default log level without repeating it for every
107            // protected lock on every poll.
108            static REPORTED: std::sync::Once = std::sync::Once::new();
109            REPORTED.call_once(|| {
110                tracing::warn!(
111                    %pid,
112                    %error,
113                    "process liveness query unavailable; keeping locks rather than treating processes as dead"
114                );
115            });
116            true
117        }
118    }
119}
120
121/// A three-valued liveness read, for a caller that *displays* whether a
122/// process is running rather than deciding whether it is safe to reclaim a
123/// lock. [`pid_alive`]'s Err-means-alive policy exists to protect a lock a
124/// live process still holds — the wrong bias for a report that must never
125/// tell an operator a process is confirmed dead just because this build
126/// could not ask the platform. `None` here is the honest "could not tell",
127/// left for the caller to render as its own "unknown" rather than folded
128/// into either `Some` answer.
129#[must_use]
130pub fn pid_status(pid: u32) -> Option<bool> {
131    pid_status_with(pid, platform_pid_alive)
132}
133
134/// [`pid_status`] with its process-liveness query supplied by the caller —
135/// see [`pid_alive_with`] for why this split exists.
136fn pid_status_with<F>(pid: u32, query: F) -> Option<bool>
137where
138    F: FnOnce(u32) -> std::io::Result<bool>,
139{
140    query(pid).ok()
141}
142
143/// An opaque marker identifying *which* process currently holds `pid`, not
144/// merely whether the number is in use — the OS-reported moment it started.
145/// Compared only for equality by the caller, never parsed as a timestamp:
146/// the two platform formats are not on the same scale, and nothing here
147/// needs to be.
148///
149/// A live pid alone never proves it is the process a caller thinks it is —
150/// pids get reused, sometimes within minutes on a busy machine — so
151/// [`crate::run::RunState::liveness`] uses this to corroborate a `driver_pid`
152/// that answered `pid_status(..) == Some(true)`: it records this marker
153/// alongside the pid, and a later mismatch means a *different* process now
154/// answers to that number, not that the original one is somehow still
155/// running under it. `None` when the platform could not say — a caller must
156/// treat that exactly like an unavailable [`pid_status`] query, not as
157/// either a match or a mismatch.
158#[must_use]
159pub fn process_started_at(pid: u32) -> Option<String> {
160    platform_process_started_at(pid).ok()
161}
162
163// `lstart` is `ps`'s own fixed-format wall-clock start time — POSIX portable
164// (unlike `/proc`, which does not exist on macOS/BSD), and a process never
165// reports a different one across its own lifetime, so two queries of the
166// same still-running process always agree byte for byte.
167fn platform_process_started_at(pid: u32) -> std::io::Result<String> {
168    #[cfg(unix)]
169    {
170        let out = std::process::Command::new("ps")
171            .args(["-o", "lstart=", "-p", &pid.to_string()])
172            .output()?;
173        if !out.status.success() {
174            return Err(std::io::Error::other(format!(
175                "ps exited with {}",
176                out.status
177            )));
178        }
179        let text = String::from_utf8_lossy(&out.stdout).trim().to_owned();
180        if text.is_empty() {
181            return Err(std::io::Error::other("ps reported no such process"));
182        }
183        Ok(text)
184    }
185    #[cfg(windows)]
186    {
187        // Round-trip ("o") format: sub-millisecond precision, so two
188        // processes started in the same second (`lstart`'s own granularity
189        // on the Unix side above) still do not collide here.
190        let script = format!("(Get-Process -Id {pid} -ErrorAction Stop).StartTime.ToString('o')");
191        let out = std::process::Command::new("powershell")
192            .args(["-NoProfile", "-NonInteractive", "-Command", &script])
193            .quiet()
194            .output()?;
195        if !out.status.success() {
196            return Err(std::io::Error::other(format!(
197                "PowerShell exited with {}: {}",
198                out.status,
199                String::from_utf8_lossy(&out.stderr).trim()
200            )));
201        }
202        let text = String::from_utf8_lossy(&out.stdout).trim().to_owned();
203        if text.is_empty() {
204            return Err(std::io::Error::other("PowerShell reported no start time"));
205        }
206        Ok(text)
207    }
208    #[cfg(not(any(unix, windows)))]
209    {
210        let _ = pid;
211        Err(std::io::Error::other(
212            "process start time is unavailable on this platform",
213        ))
214    }
215}
216
217fn platform_pid_alive(pid: u32) -> std::io::Result<bool> {
218    #[cfg(unix)]
219    {
220        match std::process::Command::new("kill")
221            .arg("-0")
222            .arg(pid.to_string())
223            .output()
224        {
225            Ok(o) => Ok(parse_unix_kill_output(o.status.success(), &o.stderr)),
226            Err(error) => Err(error),
227        }
228    }
229    #[cfg(windows)]
230    {
231        let out = std::process::Command::new("tasklist")
232            .quiet()
233            .args(["/FI", &format!("PID eq {pid}"), "/NH", "/FO", "CSV"])
234            .output();
235        match out {
236            Ok(o) => tasklist_result(
237                pid,
238                o.status.success(),
239                &o.stdout,
240                &o.stderr,
241                &o.status.to_string(),
242            ),
243            Err(error) => Err(error),
244        }
245    }
246    #[cfg(not(any(unix, windows)))]
247    {
248        let _ = pid;
249        Ok(true)
250    }
251}
252
253/// 数値の PID から推測せず、`kill -0` の終了状態と診断を解釈する。
254/// 明示的な "no such process" 診断だけを死亡の証拠とする。
255#[cfg(any(unix, test))]
256fn parse_unix_kill_output(success: bool, stderr: &[u8]) -> bool {
257    if success {
258        return true;
259    }
260    !String::from_utf8_lossy(stderr)
261        .to_lowercase()
262        .contains("no such process")
263}
264
265/// `tasklist /FO CSV` の出力を解釈する。一致しない場合、要求した PID の
266/// フィールドを持つ行は存在しない。
267#[cfg(any(windows, test))]
268fn parse_windows_tasklist_output(pid: u32, stdout: &[u8]) -> std::io::Result<bool> {
269    if stdout.iter().all(u8::is_ascii_whitespace) {
270        return Err(std::io::Error::other("tasklist produced no output"));
271    }
272    let expected = pid.to_string();
273    let rows = String::from_utf8_lossy(stdout)
274        .lines()
275        .map(tasklist_csv_fields)
276        .collect::<Option<Vec<_>>>()
277        .ok_or_else(|| std::io::Error::other("could not parse tasklist CSV output"))?;
278    Ok(rows
279        .into_iter()
280        .any(|fields| fields.get(1).is_some_and(|field| field == &expected)))
281}
282
283/// `tasklist` が出す、二重引用符と `""` エスケープを持つ CSV の一行を分ける。
284/// 壊れた CSV は呼び出し側が利用不能として保持できるよう `None` を返す。
285#[cfg(any(windows, test))]
286fn tasklist_csv_fields(line: &str) -> Option<Vec<String>> {
287    let mut fields = Vec::new();
288    let mut field = String::new();
289    let mut quoted = false;
290    let mut chars = line.chars().peekable();
291
292    while let Some(ch) = chars.next() {
293        match ch {
294            '"' if quoted && chars.peek() == Some(&'"') => {
295                field.push('"');
296                chars.next();
297            }
298            '"' => quoted = !quoted,
299            ',' if !quoted => fields.push(std::mem::take(&mut field)),
300            _ => field.push(ch),
301        }
302    }
303    (!quoted).then(|| {
304        fields.push(field);
305        fields
306    })
307}
308
309/// `tasklist` の失敗を、利用不能な問い合わせとして保持する。
310#[cfg(any(windows, test))]
311fn tasklist_result(
312    pid: u32,
313    success: bool,
314    stdout: &[u8],
315    stderr: &[u8],
316    status: &str,
317) -> std::io::Result<bool> {
318    if success {
319        parse_windows_tasklist_output(pid, stdout)
320    } else {
321        Err(std::io::Error::other(format!(
322            "tasklist exited {status}: {}",
323            String::from_utf8_lossy(stderr).trim()
324        )))
325    }
326}
327
328#[cfg(test)]
329mod tests {
330    use super::*;
331
332    /// The flag is the one Windows documents, and not one of the two it is
333    /// easily confused with.
334    ///
335    /// `DETACHED_PROCESS` (0x8) is what leaves a process without a console -
336    /// which is what caused the windows this module exists to stop, because a
337    /// child of such a process gets a fresh console *with* a window.
338    /// `CREATE_NEW_CONSOLE` (0x10) asks for the window outright.
339    #[cfg(windows)]
340    #[test]
341    fn the_flag_hides_a_console_rather_than_removing_or_creating_one() {
342        assert_eq!(CREATE_NO_WINDOW, 0x0800_0000);
343        assert_ne!(CREATE_NO_WINDOW, 0x0000_0008, "DETACHED_PROCESS");
344        assert_ne!(CREATE_NO_WINDOW, 0x0000_0010, "CREATE_NEW_CONSOLE");
345    }
346
347    /// Applying it does not disturb the command being built.
348    ///
349    /// The trait returns `&mut Self` so it can sit in the middle of a builder
350    /// chain, and a call site that put it there must not lose its program or
351    /// arguments to it.
352    #[test]
353    fn quiet_leaves_the_command_it_was_handed_intact() {
354        let mut cmd = tokio::process::Command::new("git");
355        cmd.args(["status", "--short"]).quiet();
356        let built = cmd.as_std();
357        assert_eq!(built.get_program(), "git");
358        let args: Vec<_> = built.get_args().collect();
359        assert_eq!(args, ["status", "--short"]);
360    }
361
362    /// Every `Command::new` in this crate's own sources is either quieted or
363    /// carries one of the two exemptions this module's doc explains.
364    ///
365    /// A textual scan, not a lint: nothing in `cargo clippy` knows that a
366    /// console-app child of a console-less parent gets a window, so nothing
367    /// catches a spawn that forgot `.quiet()` short of a human reading every
368    /// call site - which is exactly how `disk.rs`'s PowerShell probe and
369    /// `graph.rs`'s `gh pr create` went unquieted despite every neighbouring
370    /// spawn getting it right. Each `Command::new` is checked against the
371    /// text between it and the next one in the same file (or end of file),
372    /// which is always enough to cover its own builder chain and never
373    /// bleeds into an unrelated spawn's exemption.
374    #[test]
375    fn every_spawn_in_the_crate_is_quiet_or_documented_as_exempt() {
376        let src_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
377        let mut offenders = Vec::new();
378        for entry in std::fs::read_dir(&src_dir).expect("read src dir") {
379            let path = entry.expect("dir entry").path();
380            if path.extension().and_then(|e| e.to_str()) != Some("rs") {
381                continue;
382            }
383            let file_name = path
384                .file_name()
385                .and_then(|n| n.to_str())
386                .unwrap_or("")
387                .to_owned();
388            if file_name == "tui.rs" {
389                // explorer / open / xdg-open: GUI launchers, not console
390                // children - out of scope by design (see AGENTS.md).
391                continue;
392            }
393            let text = std::fs::read_to_string(&path).expect("read source file");
394            let lines: Vec<&str> = text.lines().collect();
395            let spawn_at: Vec<usize> = lines
396                .iter()
397                .enumerate()
398                .filter(|(_, l)| l.contains("Command::new("))
399                .map(|(i, _)| i)
400                .collect();
401            for (pos, &start) in spawn_at.iter().enumerate() {
402                let end = spawn_at.get(pos + 1).copied().unwrap_or(lines.len());
403                let block = lines[start..end].join("\n");
404                if block.contains(".quiet()") {
405                    continue;
406                }
407                // `spawn_successor`'s DETACHED_PROCESS successor has no
408                // console to inherit in the first place; see its doc comment
409                // in `web.rs`.
410                if block.contains("DETACHED_PROCESS") {
411                    continue;
412                }
413                // A spawn guarded by `#[cfg(unix)]` a few lines above cannot
414                // hit the Windows console bug at all.
415                let preceding = lines[start.saturating_sub(5)..start].join("\n");
416                if preceding.contains("#[cfg(unix)]") {
417                    continue;
418                }
419                offenders.push(format!("{file_name}:{}", start + 1));
420            }
421        }
422        assert!(
423            offenders.is_empty(),
424            "Command::new without .quiet() and no documented exemption: {offenders:?}"
425        );
426    }
427
428    #[test]
429    fn pid_liveness_policy_is_deterministic_without_an_os_process_query() {
430        assert!(pid_alive_with(42, |_| Ok(true)));
431        assert!(!pid_alive_with(42, |_| Ok(false)));
432    }
433
434    #[test]
435    fn an_unavailable_process_query_is_never_mistaken_for_a_dead_process() {
436        assert!(pid_alive_with(42, |_| Err(std::io::Error::other(
437            "access denied"
438        ))));
439    }
440
441    /// Unlike [`pid_alive_with`]'s Err-means-alive bias, the three-valued read
442    /// leaves an unavailable query as `None` rather than inventing either
443    /// answer — a display that guessed "dead" here would be exactly the wrong
444    /// kind of confidence this exists to avoid.
445    #[test]
446    fn pid_status_reports_alive_dead_and_unknown_as_three_distinct_answers() {
447        assert_eq!(pid_status_with(42, |_| Ok(true)), Some(true));
448        assert_eq!(pid_status_with(42, |_| Ok(false)), Some(false));
449        assert_eq!(
450            pid_status_with(42, |_| Err(std::io::Error::other("access denied"))),
451            None
452        );
453    }
454
455    /// 本番パーサー用のコマンド出力フィクスチャであり、特定 PID の OS 上の
456    /// 死亡状態を主張するものではない。
457    #[test]
458    fn unix_kill_output_only_marks_no_such_process_as_dead() {
459        assert!(parse_unix_kill_output(true, b""));
460        assert!(!parse_unix_kill_output(
461            false,
462            b"kill: (12345) - No such process\n"
463        ));
464        assert!(parse_unix_kill_output(
465            false,
466            b"kill: (12345) - Operation not permitted\n"
467        ));
468    }
469
470    /// 本番パーサー用のコマンド出力フィクスチャであり、OS の生存照会ではない。
471    /// 失敗した `tasklist` は死亡ではなく利用不能のままとする。
472    #[test]
473    fn windows_tasklist_csv_parsing_handles_match_no_match_and_error() {
474        let pid = 12345;
475        assert!(
476            parse_windows_tasklist_output(
477                pid,
478                b"\"magi.exe\",\"12345\",\"Console\",\"1\",\"10 K\"\r\n"
479            )
480            .expect("整形式 CSV の一致行は生存を示す")
481        );
482        assert!(
483            parse_windows_tasklist_output(
484                pid,
485                b"\"magi,worker.exe\",\"12345\",\"Console\",\"1\",\"10 K\"\r\n"
486            )
487            .expect("カンマ入りイメージ名でも PID 列を読む")
488        );
489        assert!(
490            !parse_windows_tasklist_output(
491                pid,
492                b"INFO: No tasks are running which match the specified criteria.\r\n"
493            )
494            .expect("tasklist の no-match 出力は整形式である")
495        );
496        assert!(
497            parse_windows_tasklist_output(pid, b"\"magi.exe\",\"12345").is_err(),
498            "壊れた CSV は死亡ではなく利用不能である"
499        );
500        assert!(
501            parse_windows_tasklist_output(pid, b"").is_err(),
502            "空出力は死亡ではなく利用不能である"
503        );
504        assert!(
505            parse_windows_tasklist_output(pid, b"\r\n").is_err(),
506            "空白だけの出力は死亡ではなく利用不能である"
507        );
508        assert!(
509            tasklist_result(
510                pid,
511                true,
512                b"\"magi.exe\",\"12345\",\"Console\",\"1\",\"10 K\"\r\n",
513                b"",
514                "exit status: 0",
515            )
516            .expect("CSV の一致行は生存を示す")
517        );
518
519        let error = tasklist_result(pid, false, b"", b"Access is denied.\r\n", "exit status: 1")
520            .expect_err("tasklist の失敗は死亡ではなく利用不能である");
521        assert!(error.to_string().contains("Access is denied."));
522    }
523
524    /// このテスト自身の PID を OS に問い合わせるスモーク診断。
525    ///
526    /// CI では実際のコマンド実行と成功出力の解析を必須にする。制限された
527    /// 対話席で問い合わせ自体が使えない場合は、その事実を出力して成功結果や
528    /// 死んだプロセスと取り違えない。実行中の PID を dead と報告した場合と、
529    /// CI で問い合わせが利用不能な場合は失敗にする。
530    #[test]
531    fn platform_query_reports_this_running_process_as_alive_or_unavailable() {
532        let pid = std::process::id();
533        match platform_pid_alive(pid) {
534            Ok(true) => {}
535            Ok(false) => {
536                panic!("OS の PID 問い合わせが実行中のテストプロセス {pid} を dead と報告した")
537            }
538            Err(error) if std::env::var_os("CI").is_some() => {
539                panic!("CI で OS の PID 問い合わせを実行できない(テストプロセス {pid}): {error}")
540            }
541            Err(error) => {
542                eprintln!("OS の PID 問い合わせは利用できません(テストプロセス {pid}): {error}")
543            }
544        }
545    }
546
547    /// 同じスモーク診断を `process_started_at` にも適用する: 実行中の
548    /// このテストプロセス自身に対して呼ぶと、利用可能な環境では必ず何か
549    /// 返り、そして二回呼んでも同じ値を返す — 同一プロセスの起動時刻が
550    /// 問い合わせのたびにずれては、pid 再利用との判別に使えない。
551    #[test]
552    fn platform_query_reports_this_running_process_start_time_consistently_or_unavailable() {
553        let pid = std::process::id();
554        match (
555            platform_process_started_at(pid),
556            platform_process_started_at(pid),
557        ) {
558            (Ok(first), Ok(second)) => assert_eq!(
559                first, second,
560                "同一の生存プロセスへの二回の問い合わせが食い違った"
561            ),
562            (Err(error), _) | (_, Err(error)) if std::env::var_os("CI").is_some() => {
563                panic!("CI で起動時刻の問い合わせを実行できない(テストプロセス {pid}): {error}")
564            }
565            _ => eprintln!("起動時刻の問い合わせは利用できません(テストプロセス {pid})"),
566        }
567    }
568}