Skip to main content

agentmux_common/
build_slot.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Puts the build slot where agents' shells find it, so only one heavy build or test runs
5//! at a time on a machine: `docs/specs/SPEC_BUILD_SLOT_ENFORCEMENT_2026_10_20.md`.
6//!
7//! Two kinds of file are installed, both taken from `scripts/build-slot/`:
8//!
9//! - `~/.agentmux/shared/locks/build-slot.sh`, the lock itself. Every AgentMux channel on the
10//!   machine shares it, so it is only replaced by a newer version (`# build-slot-version: N`),
11//!   never by an older channel's copy.
12//! - A shim per heavy tool (`cargo`, `task`, `npm`, `npx`, `docker`, each with a `.cmd` twin) in
13//!   `~/.agentmux/tools/bin`, the user tools directory that agents' shells put ahead of the system
14//!   PATH (`tool_store::tools_path`). All are the same two files under different names; they send
15//!   the tool's heavy subcommands through the lock. A file at that path that does not carry the
16//!   shim's marker is somebody's own and is left alone.
17//!
18//! Installing never fails startup: the caller logs an error and goes on. The shims fail open
19//! too, so a missing or broken lock script costs nothing but the protection.
20
21use std::io;
22use std::path::{Path, PathBuf};
23
24const SCRIPT: &str = include_str!("../../../scripts/build-slot/build-slot.sh");
25const SHIM_SH: &str = include_str!("../../../scripts/build-slot/shim");
26const SHIM_CMD: &str = include_str!("../../../scripts/build-slot/shim.cmd");
27
28/// The tools that get a shim, by the name the shim is installed under.
29const SHIMMED_TOOLS: [&str; 5] = ["cargo", "task", "npm", "npx", "docker"];
30
31const VERSION_PREFIX: &str = "# build-slot-version:";
32/// Both shims carry this text; a file without it is not ours to overwrite.
33const SHIM_MARKER: &str = "agentmux-build-slot-shim";
34
35/// `~/.agentmux/shared/locks/build-slot.sh` under `home`.
36pub fn script_path(home: &Path) -> PathBuf {
37    home.join(".agentmux").join("shared").join("locks").join("build-slot.sh")
38}
39
40/// `~/.agentmux/tools/bin` under `home`: the shims' directory.
41pub fn shim_dir(home: &Path) -> PathBuf {
42    home.join(".agentmux").join("tools").join("bin")
43}
44
45/// A slot with no heartbeat for this long belongs to a dead holder (the script's own rule).
46const STALE_SECS: u64 = 90;
47
48/// Who holds the build slot right now, read from the lock's owner file.
49#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
50pub struct SlotHolder {
51    /// The holder's `AGENTMUX_AGENT_ID` (else its user name), as the script recorded it.
52    pub agent: String,
53    /// When it took the slot, in epoch milliseconds.
54    pub since_ms: u64,
55    /// Why: the shim's reason (`cargo test`), else the command line.
56    pub reason: String,
57    /// The command line it runs, cut to 120 characters: a background subagent's build holds the slot under its leader's id, and this says what is really running.
58    pub command: String,
59    /// The run's own token: tells this holder's slot from one a later holder made.
60    #[serde(default)]
61    pub token: String,
62    /// The pid the script saw for itself. A real one on Linux and macOS; on Windows a Git Bash
63    /// pid, which no native tool can use (see `winpid`).
64    #[serde(default)]
65    pub pid: Option<u32>,
66    /// The script's Windows process id (Git Bash only): the root of the holder's process tree.
67    #[serde(default)]
68    pub winpid: Option<u32>,
69}
70
71impl SlotHolder {
72    /// The operating system's id for the script's process, the root of the holder's process
73    /// tree: the Windows id on Windows (none for a script older than version 9, which did not
74    /// record it), the pid elsewhere.
75    pub fn process_id(&self) -> Option<u32> {
76        if cfg!(windows) { self.winpid } else { self.pid }.filter(|p| *p > 1)
77    }
78}
79
80/// `~/.agentmux/shared/locks/build`, the lock's own folder, or `AGENTMUX_BUILD_SLOT_DIR` when
81/// that is set (the script honours it too).
82pub fn lock_dir() -> Option<PathBuf> {
83    match std::env::var_os("AGENTMUX_BUILD_SLOT_DIR").filter(|d| !d.is_empty()) {
84        Some(dir) => Some(PathBuf::from(dir)),
85        None => dirs::home_dir().map(|h| h.join(".agentmux").join("shared").join("locks").join("build")),
86    }
87}
88
89/// The current holder of this machine's build slot, if there is a live one.
90pub fn holder() -> Option<SlotHolder> {
91    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok()?.as_secs();
92    read_holder(&lock_dir()?, now)
93}
94
95/// The holder recorded under `root` at `now_secs`: none when the slot is free, when its owner
96/// file is not written yet, or when nobody has kept it alive for `STALE_SECS` (a dead holder).
97pub fn read_holder(root: &Path, now_secs: u64) -> Option<SlotHolder> {
98    let slot = root.join("slot");
99    let text = std::fs::read_to_string(slot.join("owner")).ok()?;
100    let alive_at = [slot.join("heartbeat"), slot.clone()]
101        .iter()
102        .find_map(|p| std::fs::metadata(p).ok()?.modified().ok())?
103        .duration_since(std::time::UNIX_EPOCH)
104        .ok()?
105        .as_secs();
106    if now_secs.saturating_sub(alive_at) > STALE_SECS {
107        return None;
108    }
109    let field = |key: &str| text.lines().find_map(|l| l.strip_prefix(key)?.strip_prefix('=')).map(str::trim);
110    let agent = field("agent").filter(|a| !a.is_empty())?.to_string();
111    let start: u64 = field("start")?.parse().ok()?;
112    let reason = field("reason").filter(|r| !r.is_empty()).or_else(|| field("cmd")).unwrap_or_default().to_string();
113    let command: String = field("cmd").unwrap_or_default().chars().take(120).collect();
114    let number = |key: &str| field(key).and_then(|v| v.parse::<u32>().ok());
115    Some(SlotHolder {
116        agent,
117        since_ms: start.saturating_mul(1000),
118        reason,
119        command,
120        token: field("token").unwrap_or_default().to_string(),
121        pid: number("pid"),
122        winpid: number("winpid"),
123    })
124}
125
126/// The file srv writes into the held slot once the holder's process tree has used no CPU for a
127/// while; `build-slot status` prints it (`idle_note` in the script).
128fn idle_path(root: &Path) -> PathBuf {
129    root.join("slot").join("idle")
130}
131
132/// Records that the holder with `token` has been idle since `since_secs` (epoch seconds). Does
133/// nothing when the slot now belongs to another holder: a note about the last run must never
134/// land on the next one.
135pub fn write_idle(root: &Path, token: &str, since_secs: u64) -> io::Result<()> {
136    let owner = std::fs::read_to_string(root.join("slot").join("owner")).unwrap_or_default();
137    if !owner.lines().any(|l| l.strip_prefix("token=").is_some_and(|t| t.trim() == token)) {
138        return Ok(());
139    }
140    std::fs::write(idle_path(root), format!("token={token}\nidle_since={since_secs}\n"))
141}
142
143/// Removes the idle note: the holder is busy again, or gone.
144pub fn clear_idle(root: &Path) {
145    let _ = std::fs::remove_file(idle_path(root));
146}
147
148/// Environment variables that make a bash started with them define `cargo`, `task`, `npm`, `npx`
149/// and `docker` as functions calling the shims under `home` (`BASH_FUNC_cargo%%` and so on: bash
150/// imports an exported function from its environment).
151///
152/// A function wins over any PATH lookup, so the shim is reached whatever order a shell profile
153/// left the PATH in. On Windows, Git Bash's profile puts `~/bin` first, and a `cargo.exe` there
154/// (a rustup proxy) made every agent's `cargo` skip the slot: five srv compiles ran at once
155/// (2026-10-25). The shims put their own directory back first for the tools they run, which
156/// covers what those start (`task` -> `cargo`).
157///
158/// Nothing for a tool whose shim is not installed (or is somebody's own), nor when the slot is
159/// switched off (`off`, from `AGENTMUX_BUILD_SLOT_OFF`).
160pub fn shim_function_env(home: &Path, off: bool) -> Vec<(String, String)> {
161    if off {
162        return Vec::new();
163    }
164    let dir = shim_dir(home).to_string_lossy().replace('\\', "/");
165    // The path goes between double quotes in the function body.
166    if dir.chars().any(|c| matches!(c, '"' | '$' | '`' | '\\' | '\n' | '\r')) {
167        return Vec::new();
168    }
169    SHIMMED_TOOLS
170        .iter()
171        .filter(|tool| std::fs::read_to_string(shim_dir(home).join(tool)).is_ok_and(|t| t.contains(SHIM_MARKER)))
172        .map(|tool| (format!("BASH_FUNC_{tool}%%"), format!("() {{  \"{dir}/{tool}\" \"$@\"\n}}")))
173        .collect()
174}
175
176/// [`shim_function_env`] for the current user's home, with the slot's off switch read from the
177/// environment.
178pub fn shim_function_env_for_current_user() -> Vec<(String, String)> {
179    let off = std::env::var_os("AGENTMUX_BUILD_SLOT_OFF").is_some_and(|v| !v.is_empty());
180    dirs::home_dir().map(|h| shim_function_env(&h, off)).unwrap_or_default()
181}
182
183/// What one `install` call did.
184#[derive(Debug, Default, PartialEq, Eq)]
185pub struct Installed {
186    /// Files written, by name.
187    pub written: Vec<String>,
188    /// Files left alone because they are not ours, by name.
189    pub foreign: Vec<String>,
190}
191
192/// Installs for the current user's home directory. `Ok` with nothing written when there is none,
193/// and when this AgentMux is isolated (`AGENTMUX_HOME_OVERRIDE`): the lock and the shims are shared
194/// by every AgentMux on the machine, so a test or capture instance must not change them.
195pub fn install_for_current_user() -> io::Result<Installed> {
196    let isolated = std::env::var_os("AGENTMUX_HOME_OVERRIDE").is_some_and(|v| !v.is_empty());
197    install_unless_isolated(isolated, dirs::home_dir().as_deref())
198}
199
200/// [`install`] into `home`, unless `isolated`: then nothing is written, so the start of a test or
201/// capture instance leaves the real home as it was.
202fn install_unless_isolated(isolated: bool, home: Option<&Path>) -> io::Result<Installed> {
203    match home {
204        Some(home) if !isolated => install(home),
205        _ => Ok(Installed::default()),
206    }
207}
208
209/// Installs the lock script and both shims under `home`, writing only what is missing or older.
210pub fn install(home: &Path) -> io::Result<Installed> {
211    let mut done = Installed::default();
212
213    let script = lf(SCRIPT);
214    let script_dest = script_path(home);
215    let installed_version = std::fs::read_to_string(&script_dest).ok().and_then(|t| version_of(&t));
216    let embedded_version = version_of(&script);
217    if !script_dest.exists() || installed_version.is_none() || embedded_version > installed_version {
218        write_executable(&script_dest, &script)?;
219        done.written.push("build-slot.sh".to_string());
220    }
221
222    let dir = shim_dir(home);
223    let (sh, cmd) = (lf(SHIM_SH), crlf(SHIM_CMD));
224    let files = SHIMMED_TOOLS.iter().flat_map(|t| [(t.to_string(), &sh), (format!("{t}.cmd"), &cmd)]);
225    for (name, text) in files {
226        let text = text.as_str();
227        let dest = dir.join(&name);
228        match std::fs::read_to_string(&dest) {
229            Ok(existing) if existing == text => {}
230            Ok(existing) if existing.contains(SHIM_MARKER) => {
231                write_executable(&dest, text)?;
232                done.written.push(name.clone());
233            }
234            Ok(_) => done.foreign.push(name.clone()),
235            Err(e) if e.kind() == io::ErrorKind::NotFound => {
236                write_executable(&dest, text)?;
237                done.written.push(name.clone());
238            }
239            // Not valid UTF-8 (a real binary named `cargo`): somebody else's.
240            Err(e) if e.kind() == io::ErrorKind::InvalidData => done.foreign.push(name.clone()),
241            Err(e) => return Err(e),
242        }
243    }
244    Ok(done)
245}
246
247/// The `# build-slot-version: N` line's number.
248fn version_of(text: &str) -> Option<u32> {
249    text.lines()
250        .find_map(|l| l.strip_prefix(VERSION_PREFIX))
251        .and_then(|v| v.trim().parse().ok())
252}
253
254/// A shell script must be LF whatever the checkout's line endings were.
255fn lf(text: &str) -> String {
256    text.replace("\r\n", "\n")
257}
258
259/// A batch file is CRLF whatever the checkout's line endings were.
260fn crlf(text: &str) -> String {
261    lf(text).replace('\n', "\r\n")
262}
263
264/// Writes through a temporary name in the same directory, then renames over `dest`, so a
265/// shell starting a shim at that moment sees the old file or the new one, never half of one.
266fn write_executable(dest: &Path, text: &str) -> io::Result<()> {
267    let dir = dest.parent().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "no parent"))?;
268    std::fs::create_dir_all(dir)?;
269    let tmp = dir.join(format!(".{}.{}.tmp", dest.file_name().and_then(|n| n.to_str()).unwrap_or("f"), std::process::id()));
270    std::fs::write(&tmp, text)?;
271    #[cfg(unix)]
272    {
273        use std::os::unix::fs::PermissionsExt;
274        std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755))?;
275    }
276    std::fs::rename(&tmp, dest).inspect_err(|_| {
277        let _ = std::fs::remove_file(&tmp);
278    })
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284
285    fn home() -> tempfile::TempDir {
286        tempfile::tempdir().unwrap()
287    }
288
289    fn write_slot(root: &Path, owner: &str, heartbeat: bool) {
290        let slot = root.join("slot");
291        std::fs::create_dir_all(&slot).unwrap();
292        std::fs::write(slot.join("owner"), owner).unwrap();
293        if heartbeat {
294            std::fs::write(slot.join("heartbeat"), "").unwrap();
295        }
296    }
297
298    fn now_secs() -> u64 {
299        std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs()
300    }
301
302    #[test]
303    fn the_holder_is_read_from_the_owner_file_and_a_dead_one_is_not_a_holder() {
304        let h = home();
305        let root = h.path();
306        assert_eq!(read_holder(root, now_secs()), None, "no slot: free");
307        write_slot(root, "agent=Lazo\npid=1\ntoken=t\nstart=1792830000\ncwd=/x\ncmd=/c/bin/cargo test -p x\nreason=cargo test\n", true);
308        assert_eq!(
309            read_holder(root, now_secs()),
310            Some(SlotHolder {
311                agent: "Lazo".into(),
312                since_ms: 1_792_830_000_000,
313                reason: "cargo test".into(),
314                command: "/c/bin/cargo test -p x".into(),
315                token: "t".into(),
316                pid: Some(1),
317                winpid: None,
318            })
319        );
320        write_slot(root, "agent=Lazo\npid=77\nwinpid=4242\ntoken=t\nstart=1792830000\ncmd=x\n", true);
321        let holder = read_holder(root, now_secs()).unwrap();
322        assert_eq!((holder.pid, holder.winpid), (Some(77), Some(4242)));
323        let expected = if cfg!(windows) { Some(4242) } else { Some(77) };
324        assert_eq!(holder.process_id(), expected, "the Windows id on Windows, the pid elsewhere");
325        write_slot(root, "agent=Lazo\npid=1\ntoken=t\nstart=1792830000\ncmd=x\n", true);
326        assert_eq!(read_holder(root, now_secs()).unwrap().process_id(), None, "a pid of 1 is no process of ours");
327        assert_eq!(read_holder(root, now_secs() + 10 * 60), None, "no heartbeat for minutes: its holder died");
328        write_slot(root, "agent=Manoz\nstart=1792830001\ncmd=npm run build\n", true);
329        assert_eq!(read_holder(root, now_secs()).unwrap().reason, "npm run build", "no reason: the command line");
330        write_slot(root, "agent=Manoz\n", true);
331        assert_eq!(read_holder(root, now_secs()), None, "an owner file still being written names no start");
332        write_slot(root, "", false);
333        assert_eq!(read_holder(root, now_secs()), None);
334    }
335
336    #[test]
337    fn the_embedded_files_are_what_the_installer_expects() {
338        assert!(version_of(SCRIPT).is_some(), "build-slot.sh needs a `# build-slot-version: N` line");
339        assert!(SHIM_SH.contains(SHIM_MARKER), "the cargo shim must carry its marker");
340        assert!(SHIM_CMD.contains(SHIM_MARKER), "the cargo.cmd shim must carry its marker");
341        assert!(!lf(SCRIPT).contains('\r') && !lf(SHIM_SH).contains('\r'));
342        // One function, called on the last line: bash reads a script a piece at a time, so a
343        // wait still running an older copy would break mid-line when the file is replaced.
344        let lines: Vec<&str> = SCRIPT.lines().filter(|l| !l.trim().is_empty()).collect();
345        assert_eq!(lines.last().copied(), Some("main \"$@\"; exit $?"), "the script must end by calling main");
346        assert!(lines.contains(&"main() {"), "the script body must be one function");
347        assert!(crlf(SHIM_CMD).contains("\r\n") && !crlf(SHIM_CMD).replace("\r\n", "").contains('\n'));
348    }
349
350    /// An isolated instance (a test or capture run with `AGENTMUX_HOME_OVERRIDE`) leaves the real
351    /// home alone: the lock and the shims are shared by every AgentMux on the machine.
352    #[test]
353    fn an_isolated_instance_installs_nothing_in_the_real_home() {
354        let real = home();
355        assert_eq!(install_unless_isolated(true, Some(real.path())).unwrap(), Installed::default());
356        assert!(!real.path().join(".agentmux").exists(), "nothing at all was created under the home");
357        assert_eq!(install_unless_isolated(false, None).unwrap(), Installed::default(), "no home: nothing to install into");
358        let done = install_unless_isolated(false, Some(real.path())).unwrap();
359        assert!(done.written.contains(&"build-slot.sh".to_string()) && done.written.contains(&"npm".to_string()));
360        assert!(script_path(real.path()).exists(), "a normal instance still installs");
361    }
362
363    #[test]
364    fn an_empty_home_gets_the_script_and_both_shims_once() {
365        let h = home();
366        let first = install(h.path()).unwrap();
367        assert_eq!(
368            first.written,
369            vec!["build-slot.sh", "cargo", "cargo.cmd", "task", "task.cmd", "npm", "npm.cmd", "npx", "npx.cmd", "docker", "docker.cmd"]
370        );
371        assert!(first.foreign.is_empty());
372        assert_eq!(install(h.path()).unwrap(), Installed::default(), "the second call finds nothing to do");
373        assert_eq!(std::fs::read_to_string(shim_dir(h.path()).join("cargo.cmd")).unwrap(), crlf(SHIM_CMD));
374    }
375
376    #[test]
377    fn a_cargo_that_is_not_the_shim_is_left_alone() {
378        let h = home();
379        let dir = shim_dir(h.path());
380        std::fs::create_dir_all(&dir).unwrap();
381        std::fs::write(dir.join("cargo"), "#!/bin/sh\necho mine\n").unwrap();
382        let done = install(h.path()).unwrap();
383        assert_eq!(done.foreign, vec!["cargo"]);
384        assert_eq!(std::fs::read_to_string(dir.join("cargo")).unwrap(), "#!/bin/sh\necho mine\n");
385        assert!(done.written.contains(&"cargo.cmd".to_string()), "the other shims are still installed");
386        assert!(done.written.contains(&"task".to_string()), "the other tools' shims are still installed");
387    }
388
389    #[test]
390    fn an_older_shim_is_replaced_and_a_newer_script_is_kept() {
391        let h = home();
392        install(h.path()).unwrap();
393        let dir = shim_dir(h.path());
394        std::fs::write(dir.join("cargo"), "#!/bin/sh\n# agentmux-build-slot-shim v0\n").unwrap();
395        let newer = "#!/bin/bash\n# build-slot-version: 999\necho newer channel\n";
396        std::fs::write(script_path(h.path()), newer).unwrap();
397        let done = install(h.path()).unwrap();
398        assert_eq!(done.written, vec!["cargo"]);
399        assert_eq!(std::fs::read_to_string(script_path(h.path())).unwrap(), newer, "no downgrade");
400    }
401
402    #[test]
403    fn an_unversioned_or_older_script_is_replaced() {
404        let h = home();
405        install(h.path()).unwrap();
406        std::fs::write(script_path(h.path()), "#!/bin/bash\n# written by hand, no version\n").unwrap();
407        assert_eq!(install(h.path()).unwrap().written, vec!["build-slot.sh"]);
408        std::fs::write(script_path(h.path()), "#!/bin/bash\n# build-slot-version: 0\n").unwrap();
409        assert_eq!(install(h.path()).unwrap().written, vec!["build-slot.sh"]);
410    }
411
412    // The shim's own behaviour, run with a stand-in cargo and a stand-in lock script.
413    // Skipped where there is no bash (a Windows machine without Git for Windows).
414    fn bash() -> Option<PathBuf> {
415        if cfg!(windows) {
416            let git = std::env::var_os("ProgramFiles").map(|p| PathBuf::from(p).join("Git").join("bin").join("bash.exe"))?;
417            git.exists().then_some(git)
418        } else {
419            Some(PathBuf::from("bash"))
420        }
421    }
422
423    /// What the `tool` shim ran, given `args`, for a home with or without the lock script.
424    fn run_tool_env(tool: &str, with_slot: bool, off: bool, args: &[&str], env: &[(&str, &str)]) -> Option<String> {
425        // In a project with a package.json beside a Cargo.toml: what npm and npx are queued for.
426        run_tool_in(tool, with_slot, off, args, env, &["proj/package.json", "proj/Cargo.toml"], "proj").map(|(out, _)| out)
427    }
428
429    /// [`run_tool_env`] with the files of a project laid out under the home (`files`, paths from
430    /// it) and the shim run from `cwd` (a folder in it). Also returns the home, so a test can
431    /// read what the shim wrote there.
432    fn run_tool_in(
433        tool: &str,
434        with_slot: bool,
435        off: bool,
436        args: &[&str],
437        env: &[(&str, &str)],
438        files: &[&str],
439        cwd: &str,
440    ) -> Option<(String, tempfile::TempDir)> {
441        let bash = bash()?;
442        let h = home();
443        for f in files {
444            let path = h.path().join(f);
445            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
446            std::fs::write(&path, "{}").unwrap();
447        }
448        let cwd = h.path().join(cwd);
449        std::fs::create_dir_all(&cwd).unwrap();
450        let real_dir = h.path().join("real");
451        let shim = shim_dir(h.path());
452        std::fs::create_dir_all(&real_dir).unwrap();
453        std::fs::create_dir_all(&shim).unwrap();
454        let real = real_dir.join(tool);
455        std::fs::write(&real, "#!/usr/bin/env bash\necho \"REAL $*\"\n").unwrap();
456        std::fs::write(shim.join(tool), lf(SHIM_SH)).unwrap();
457        if with_slot {
458            std::fs::create_dir_all(script_path(h.path()).parent().unwrap()).unwrap();
459            std::fs::write(script_path(h.path()), "#!/usr/bin/env bash\necho \"SLOT $*\"\n").unwrap();
460        }
461        #[cfg(unix)]
462        {
463            use std::os::unix::fs::PermissionsExt;
464            std::fs::set_permissions(&real, std::fs::Permissions::from_mode(0o755)).unwrap();
465        }
466        let sep = if cfg!(windows) { ";" } else { ":" };
467        let path = format!("{}{sep}{}{sep}{}", shim.display(), real_dir.display(), std::env::var("PATH").unwrap_or_default());
468        let mut cmd = std::process::Command::new(bash);
469        cmd.arg(shim.join(tool)).args(args).env("PATH", path).env("HOME", h.path()).env_remove("AGENTMUX_BUILD_SLOT_DIR").current_dir(&cwd);
470        if off {
471            cmd.env("AGENTMUX_BUILD_SLOT_OFF", "1");
472        }
473        cmd.envs(env.iter().copied());
474        #[cfg(windows)]
475        {
476            use crate::win32::NoWindow;
477            cmd.no_window();
478        }
479        let out = cmd.output().unwrap();
480        Some((String::from_utf8_lossy(&out.stdout).replace("\r\n", "\n").trim().to_string(), h))
481    }
482
483    fn run_tool(tool: &str, with_slot: bool, off: bool, args: &[&str]) -> Option<String> {
484        run_tool_env(tool, with_slot, off, args, &[])
485    }
486
487    fn run_shim(with_slot: bool, off: bool, args: &[&str]) -> Option<String> {
488        run_tool("cargo", with_slot, off, args)
489    }
490
491    fn contains_all(out: &str, parts: &[&str]) -> bool {
492        parts.iter().all(|p| out.contains(p))
493    }
494
495    #[test]
496    fn a_heavy_subcommand_goes_through_the_slot_and_a_light_one_does_not() {
497        let Some(test) = run_shim(true, false, &["test", "-p", "x"]) else { return };
498        assert!(test.starts_with("SLOT --reason cargo test -- "), "got {test:?}");
499        assert!(contains_all(&test, &["real", "cargo test -p x"]), "got {test:?}");
500        let nightly = run_shim(true, false, &["+nightly", "--locked", "check"]).unwrap();
501        assert!(nightly.starts_with("SLOT --reason cargo check -- "), "got {nightly:?}");
502        for args in [
503            &["-C", "dir", "test"][..],
504            &["-Z", "unstable-options", "test"][..],
505            &["--config", "build.jobs=2", "test"][..],
506            &["--color", "never", "test"][..],
507            &["--config=build.jobs=2", "-Zunstable-options", "test"][..],
508        ] {
509            let out = run_shim(true, false, args).unwrap();
510            assert!(out.starts_with("SLOT --reason cargo test -- "), "{args:?} should be slotted, got {out:?}");
511        }
512        assert_eq!(run_shim(true, false, &["metadata"]).unwrap(), "REAL metadata");
513        assert_eq!(run_shim(true, false, &["-C", "dir", "metadata"]).unwrap(), "REAL -C dir metadata");
514        assert_eq!(run_shim(true, false, &["run", "-p", "srv"]).unwrap(), "REAL run -p srv", "run keeps running, so it is not slotted");
515        assert_eq!(run_shim(true, false, &[]).unwrap(), "REAL");
516    }
517
518    /// Whether the `tool` shim sent `args` through the slot (the stand-in lock script says so).
519    fn slotted(tool: &str, args: &[&str]) -> Option<bool> {
520        run_tool(tool, true, false, args).map(|out| out.starts_with("SLOT "))
521    }
522
523    #[test]
524    fn task_npm_npx_and_docker_slot_their_heavy_commands_only() {
525        if bash().is_none() {
526            return;
527        }
528        let heavy: &[(&str, &[&str])] = &[
529            ("task", &["package"]),
530            ("task", &["package:portable"]),
531            ("task", &["--verbose", "build:backend"]),
532            ("task", &["-d", "x", "bundle:windows"]),
533            ("task", &["check:doc-status", "package"]),
534            ("npm", &["run", "build"]),
535            ("npm", &["run", "--silent", "package:portable"]),
536            ("npm", &["run", "test:e2e"]),
537            ("npm", &["test"]),
538            ("npm", &["run", "coverage"]),
539            ("npm", &["run", "--workspace", "child", "coverage"]),
540            ("npm", &["run", "--prefix", "/p", "build"]),
541            ("npm", &["--workspace", "child", "run", "-w", "x", "package"]),
542            ("npx", &["vite", "build"]),
543            ("npx", &["vitest", "run", "x.test.ts"]),
544            ("npx", &["vitest"]),
545            ("docker", &["build", "-t", "x", "."]),
546            ("docker", &["buildx", "build", "."]),
547            ("docker", &["compose", "up", "--build"]),
548            ("docker", &["--context", "c", "build", "."]),
549        ];
550        for (tool, args) in heavy {
551            assert_eq!(slotted(tool, args), Some(true), "{tool} {args:?} should be slotted");
552        }
553        let light: &[(&str, &[&str])] = &[
554            ("task", &["dev"]),
555            ("task", &["run"]),
556            ("task", &["check:doc-status"]),
557            ("task", &["changeset", "--", "patch", "package"]),
558            ("task", &[]),
559            ("npm", &["install"]),
560            ("npm", &["ci"]),
561            ("npm", &["run", "lint:scss"]),
562            ("npm", &["run", "dev"]),
563            ("npm", &["run", "--workspace", "build", "lint:scss"]),
564            ("npm", &[]),
565            ("npx", &["tsc", "--noEmit"]),
566            ("npx", &["vite"]),
567            ("docker", &["run", "--rm", "x"]),
568            ("docker", &["ps"]),
569            ("docker", &["compose", "up"]),
570            ("docker", &["--version"]),
571        ];
572        for (tool, args) in light {
573            assert_eq!(slotted(tool, args), Some(false), "{tool} {args:?} should run directly");
574        }
575        // The reason names the command, and the real tool gets the original arguments.
576        let out = run_tool("task", true, false, &["package", "--force"]).unwrap();
577        assert!(out.starts_with("SLOT --reason task package -- "), "got {out:?}");
578        assert!(contains_all(&out, &["real", "task package --force"]), "got {out:?}");
579        assert_eq!(run_tool("npm", true, true, &["run", "build"]).unwrap(), "REAL run build", "the opt-out works for every tool");
580        assert_eq!(run_tool("docker", false, false, &["build", "."]).unwrap(), "REAL build .", "no lock script: docker still runs");
581    }
582
583    /// With a terminal, a bare vitest watches and keeps running, so it is not slotted unless the
584    /// arguments ask for a single run (`npm test -- --run`, #5379).
585    #[test]
586    fn with_a_terminal_only_a_one_shot_test_run_is_slotted() {
587        if bash().is_none() {
588            return;
589        }
590        let with_tty = |tool: &str, args: &[&str]| {
591            run_tool_env(tool, true, false, args, &[("BUILD_SLOT_ASSUME_TTY", "1")]).map(|o| o.starts_with("SLOT "))
592        };
593        for (tool, args) in [
594            ("npm", &["test", "--", "--run"][..]),
595            ("npm", &["run", "test", "--", "--run"][..]),
596            ("npx", &["vitest", "--run"][..]),
597            ("npx", &["vitest", "run"][..]),
598            ("npm", &["run", "build"][..]),
599        ] {
600            assert_eq!(with_tty(tool, args), Some(true), "{tool} {args:?} should be slotted with a terminal");
601        }
602        for (tool, args) in [
603            ("npm", &["test"][..]),
604            ("npm", &["run", "test"][..]),
605            ("npx", &["vitest"][..]),
606            ("npm", &["test", "--", "--coverage"][..]),
607            ("npx", &["vitest", "--coverage"][..]),
608        ] {
609            assert_eq!(with_tty(tool, args), Some(false), "{tool} {args:?} watches with a terminal, so it is not slotted");
610        }
611    }
612
613    /// What npm and npx do in a folder laid out as `files` (paths under the home), run from `cwd`:
614    /// whether the command went through the slot, and the text of the lock folder's unqueued.log.
615    fn npm_in(files: &[&str], cwd: &str, tool: &str, args: &[&str]) -> Option<(bool, String)> {
616        let (out, home) = run_tool_in(tool, true, false, args, &[], files, cwd)?;
617        let log = std::fs::read_to_string(home.path().join(".agentmux/shared/locks/build/unqueued.log")).unwrap_or_default();
618        Some((out.starts_with("SLOT "), log))
619    }
620
621    /// The slot is for Rust and agentmux-frontend builds: an npm or npx build in a site-style repo
622    /// (a package.json with no Cargo.toml above it) runs at once, and says so in the lock folder's
623    /// log. A package in or below a Rust tree is still queued.
624    #[test]
625    fn npm_and_npx_queue_only_in_a_tree_with_a_cargo_toml() {
626        if bash().is_none() {
627            return;
628        }
629        let rust = &["agentmux/package.json", "agentmux/Cargo.toml"][..];
630        let site = &["site/package.json"][..];
631        for (tool, args) in [("npm", &["run", "build"][..]), ("npx", &["vite", "build"][..]), ("npm", &["test"][..])] {
632            let (slotted, log) = npm_in(rust, "agentmux", tool, args).unwrap();
633            assert!(slotted && log.is_empty(), "{tool} {args:?} beside a Cargo.toml queues, and says nothing: {log:?}");
634            let (slotted, log) = npm_in(site, "site", tool, args).unwrap();
635            assert!(!slotted, "{tool} {args:?} in a site repo runs at once");
636            assert!(log.trim_end().ends_with("not queued: no Cargo.toml") && log.contains(&format!("{tool}")), "one line for it: {log:?}");
637            assert_eq!(log.lines().count(), 1, "{log:?}");
638        }
639        // The line carries epoch, agent, command and folder, tab-separated.
640        let (_, log) = npm_in(site, "site", "npm", &["run", "build"]).unwrap();
641        let fields: Vec<&str> = log.trim_end().split('\t').collect();
642        assert_eq!(fields.len(), 5, "{log:?}");
643        assert!(fields[0].parse::<u64>().is_ok() && fields[2] == "npm run build" && fields[3].ends_with("/site"), "{fields:?}");
644        // A package nested in a Rust tree: the nearest package.json has no Cargo.toml beside it, but
645        // one sits above it, so it builds in that tree and is queued.
646        let nested = &["agentmux/Cargo.toml", "agentmux/widgets/clock/package.json"][..];
647        assert_eq!(npm_in(nested, "agentmux/widgets/clock", "npm", &["run", "build"]).unwrap().0, true, "nested in the tree: queued");
648        // A folder inside a site, below its package.json, is the site's.
649        assert_eq!(npm_in(site, "site", "npm", &["run", "build"]).unwrap().0, false);
650        let deep = &["site/package.json", "site/src/deep/x.ts"][..];
651        assert_eq!(npm_in(deep, "site/src/deep", "npm", &["run", "build"]).unwrap().0, false, "the nearest package.json is found from a subfolder");
652        // `--prefix` names the project, wherever the command is run from.
653        let both = &["agentmux/package.json", "agentmux/Cargo.toml", "site/package.json"][..];
654        assert_eq!(npm_in(both, "agentmux", "npm", &["run", "build", "--prefix", "../site"]).unwrap().0, false, "--prefix to a site");
655        assert_eq!(npm_in(both, "site", "npm", &["--prefix=../agentmux", "run", "build"]).unwrap().0, true, "--prefix=dir to the Rust tree");
656        // No package.json anywhere: not known to be a site, so it queues as before.
657        assert_eq!(npm_in(&[], "nowhere", "npx", &["vite", "build"]).unwrap().0, true);
658        // Light commands are never queued and never noted; cargo is unchanged.
659        let (slotted, log) = npm_in(site, "site", "npm", &["install"]).unwrap();
660        assert!(!slotted && log.is_empty(), "a light command is not a skipped queue: {log:?}");
661        let (out, home) = run_tool_in("cargo", true, false, &["test"], &[], site, "site").unwrap();
662        assert!(out.starts_with("SLOT "), "cargo queues wherever it is run: {out}");
663        assert!(!home.path().join(".agentmux/shared/locks/build/unqueued.log").exists());
664    }
665
666    /// Runs the lock script under bash with its slot directory at `root`, as a fresh top-level call.
667    fn run_slot(bash: &Path, script: &Path, root: &Path, args: &[&str]) -> std::process::Output {
668        let mut cmd = std::process::Command::new(bash);
669        cmd.arg(script).args(args).env("AGENTMUX_BUILD_SLOT_DIR", root).env_remove("BUILD_SLOT_HELD").env("BUILD_SLOT_POLL", "1");
670        #[cfg(windows)]
671        {
672            use crate::win32::NoWindow;
673            cmd.no_window();
674        }
675        cmd.output().unwrap()
676    }
677
678    /// Every run leaves one line in the history, and `history` summarises them by reason.
679    #[test]
680    fn a_run_is_recorded_in_the_history_and_summarised() {
681        let Some(bash) = bash() else { return };
682        let h = home();
683        let script = h.path().join("build-slot.sh");
684        std::fs::write(&script, lf(SCRIPT)).unwrap();
685        let root = h.path().join("slot dir");
686        let run = |args: &[&str]| run_slot(&bash, &script, &root, args);
687        assert_eq!(run(&["--reason", "cargo test", "--", "true"]).status.code(), Some(0));
688        assert_eq!(run(&["--reason", "task package", "--", "sh", "-c", "exit 3"]).status.code(), Some(3));
689        let log = std::fs::read_to_string(root.join("history.log")).unwrap();
690        let rows: Vec<Vec<&str>> = log.lines().map(|l| l.split('\t').collect()).collect();
691        assert_eq!(rows.len(), 2, "one line per run: {log:?}");
692        assert!(rows.iter().all(|r| r.len() == 6), "epoch, agent, reason, waited, held, exit: {log:?}");
693        assert_eq!((rows[0][2], rows[0][5]), ("cargo test", "0"));
694        assert_eq!((rows[1][2], rows[1][5]), ("task package", "3"), "the wrapped command's exit code is recorded");
695        let summary = String::from_utf8_lossy(&run(&["history"]).stdout).to_string();
696        assert!(summary.starts_with("runs: 2,"), "got {summary:?}");
697        assert!(contains_all(&summary, &["cargo test", "task package"]), "got {summary:?}");
698    }
699
700    /// A run cut short by a signal is still recorded (once, exit 130), and the log rotates
701    /// to `history.log.1` instead of being rewritten once it is long.
702    #[test]
703    fn an_interrupted_run_is_recorded_and_a_long_log_rotates() {
704        let Some(bash) = bash() else { return };
705        let h = home();
706        let script = h.path().join("build-slot.sh");
707        std::fs::write(&script, lf(SCRIPT)).unwrap();
708        let root = h.path().join("slot dir");
709        let run = |args: &[&str]| run_slot(&bash, &script, &root, args);
710        // The wrapped command signals its parent, the wrapper, and then ends.
711        let out = run(&["--reason", "cargo test", "--", "bash", "-c", "kill -TERM $PPID; sleep 1"]);
712        assert_eq!(out.status.code(), Some(130));
713        let log = std::fs::read_to_string(root.join("history.log")).unwrap();
714        let rows: Vec<Vec<&str>> = log.lines().map(|l| l.split('\t').collect()).collect();
715        assert_eq!(rows.len(), 1, "recorded once, not twice: {log:?}");
716        assert_eq!((rows[0][2], rows[0][5]), ("cargo test", "130"));
717        assert!(!root.join("slot").exists(), "the slot is freed");
718
719        let filler = "1\tx\told\t0\t0\t0\n".repeat(2001);
720        std::fs::write(root.join("history.log"), filler).unwrap();
721        assert_eq!(run(&["--reason", "task package", "--", "true"]).status.code(), Some(0));
722        assert!(root.join("history.log.1").exists(), "past 2000 lines the log is renamed aside");
723        assert!(!root.join("history.log").exists(), "and the next append starts a new file");
724        let summary = String::from_utf8_lossy(&run(&["history"]).stdout).to_string();
725        assert!(summary.starts_with("runs: 2002,"), "history reads both generations: {summary:?}");
726    }
727
728    #[test]
729    fn shim_functions_are_offered_for_every_installed_shim_and_nothing_else() {
730        let h = home();
731        assert!(shim_function_env(h.path(), false).is_empty(), "no shims installed: no functions");
732        install(h.path()).unwrap();
733        let env = shim_function_env(h.path(), false);
734        let names: Vec<&str> = env.iter().map(|(k, _)| k.as_str()).collect();
735        assert_eq!(names, ["BASH_FUNC_cargo%%", "BASH_FUNC_task%%", "BASH_FUNC_npm%%", "BASH_FUNC_npx%%", "BASH_FUNC_docker%%"]);
736        let dir = shim_dir(h.path()).to_string_lossy().replace('\\', "/");
737        assert_eq!(env[0].1, format!("() {{  \"{dir}/cargo\" \"$@\"\n}}"));
738        assert!(shim_function_env(h.path(), true).is_empty(), "the opt-out switches them off");
739        // A `cargo` that is somebody's own is not ours to put a function in front of.
740        std::fs::write(shim_dir(h.path()).join("cargo"), "#!/bin/sh\necho mine\n").unwrap();
741        let env = shim_function_env(h.path(), false);
742        assert!(env.iter().all(|(k, _)| k != "BASH_FUNC_cargo%%") && env.len() == 4);
743    }
744
745    /// The bug of 2026-10-25: a `cargo` earlier on the PATH than the shims' directory (Git Bash's
746    /// profile puts `~/bin` first) skipped the slot. With the functions in the environment the shim
747    /// is reached anyway; without them it is not.
748    #[test]
749    fn a_cargo_earlier_on_the_path_still_goes_through_the_slot_with_the_functions() {
750        let Some(bash) = bash() else { return };
751        let h = home();
752        install(h.path()).unwrap();
753        // Stand-ins: a lock script that says it ran, a "user bin" cargo that is first on the PATH,
754        // and the real cargo after the shims.
755        std::fs::write(script_path(h.path()), "#!/usr/bin/env bash\necho \"SLOT $*\"\n").unwrap();
756        let (user_bin, real_dir) = (h.path().join("userbin"), h.path().join("real"));
757        for (dir, text) in [(&user_bin, "BYPASS"), (&real_dir, "REAL")] {
758            std::fs::create_dir_all(dir).unwrap();
759            std::fs::write(dir.join("cargo"), format!("#!/usr/bin/env bash\necho {text}\n")).unwrap();
760            #[cfg(unix)]
761            {
762                use std::os::unix::fs::PermissionsExt;
763                std::fs::set_permissions(dir.join("cargo"), std::fs::Permissions::from_mode(0o755)).unwrap();
764            }
765        }
766        let sep = if cfg!(windows) { ";" } else { ":" };
767        let path = format!("{}{sep}{}{sep}{}{sep}{}", user_bin.display(), shim_dir(h.path()).display(), real_dir.display(), std::env::var("PATH").unwrap_or_default());
768        let run = |with_functions: bool| {
769            let mut cmd = std::process::Command::new(&bash);
770            cmd.args(["-c", "cargo test -p x"]).env("PATH", &path).env("HOME", h.path()).env_remove("BUILD_SLOT_HELD").env_remove("AGENTMUX_BUILD_SLOT_OFF");
771            if with_functions {
772                cmd.envs(shim_function_env(h.path(), false));
773            }
774            #[cfg(windows)]
775            {
776                use crate::win32::NoWindow;
777                cmd.no_window();
778            }
779            String::from_utf8_lossy(&cmd.output().unwrap().stdout).replace("\r\n", "\n").trim().to_string()
780        };
781        assert_eq!(run(false), "BYPASS", "without the functions the earlier cargo wins, which is the bug");
782        let out = run(true);
783        assert!(out.starts_with("SLOT --reason cargo test -- "), "got {out:?}");
784        assert!(out.contains("userbin") && out.ends_with("cargo test -p x"), "the slot runs the cargo the shell would have found, the one in the user's bin: {out:?}");
785    }
786
787    /// What the shim runs starts with the shims' directory first on the PATH, so `task` ->
788    /// `cargo` and `npm run build` -> `cargo` are slotted too.
789    #[test]
790    fn the_tool_a_shim_runs_finds_the_shims_first() {
791        let Some(bash) = bash() else { return };
792        let h = home();
793        let (shim, real_dir) = (shim_dir(h.path()), h.path().join("real"));
794        std::fs::create_dir_all(&shim).unwrap();
795        std::fs::create_dir_all(&real_dir).unwrap();
796        std::fs::write(shim.join("task"), lf(SHIM_SH)).unwrap();
797        std::fs::write(real_dir.join("task"), "#!/usr/bin/env bash\necho \"FIRST ${PATH%%:*}\"\n").unwrap();
798        #[cfg(unix)]
799        {
800            use std::os::unix::fs::PermissionsExt;
801            std::fs::set_permissions(real_dir.join("task"), std::fs::Permissions::from_mode(0o755)).unwrap();
802        }
803        let sep = if cfg!(windows) { ";" } else { ":" };
804        // The shims' directory is NOT first.
805        let path = format!("{}{sep}{}{sep}{}", real_dir.display(), shim.display(), std::env::var("PATH").unwrap_or_default());
806        let mut cmd = std::process::Command::new(bash);
807        cmd.arg(shim.join("task")).arg("dev").env("PATH", path).env("HOME", h.path()).env("AGENTMUX_BUILD_SLOT_OFF", "1");
808        #[cfg(windows)]
809        {
810            use crate::win32::NoWindow;
811            cmd.no_window();
812        }
813        let out = String::from_utf8_lossy(&cmd.output().unwrap().stdout).replace("\r\n", "\n").trim().to_string();
814        assert!(out.starts_with("FIRST ") && out.ends_with(".agentmux/tools/bin"), "got {out:?}");
815    }
816
817    fn spawn_slot(bash: &Path, script: &Path, root: &Path, limit: Option<&str>, args: &[&str]) -> std::process::Child {
818        let env: Vec<(&str, &str)> = limit.map(|n| ("BUILD_SLOT_MAX", n)).into_iter().collect();
819        spawn_slot_env(bash, script, root, &env, args)
820    }
821
822    /// One run at a time by default; with a limit of two, two hold a slot at once and a third waits,
823    /// saying how long it has waited and who holds the slot.
824    #[test]
825    fn a_limit_of_two_lets_two_runs_hold_a_slot_and_a_third_waits() {
826        let Some(bash) = bash() else { return };
827        let h = home();
828        let script = h.path().join("build-slot.sh");
829        std::fs::write(&script, lf(SCRIPT)).unwrap();
830        let root = h.path().join("locks");
831        let status = |limit: Option<&str>| {
832            let out = spawn_slot(&bash, &script, &root, limit, &["status"]).wait_with_output().unwrap();
833            String::from_utf8_lossy(&out.stdout).replace("\r\n", "\n")
834        };
835
836        // Waits (up to 30 s) for the status to say `want`: process start-up is slow under load.
837        let until = |limit: Option<&str>, want: &[&str]| {
838            let mut last = String::new();
839            for _ in 0..60 {
840                last = status(limit);
841                if contains_all(&last, want) {
842                    return last;
843                }
844                std::thread::sleep(std::time::Duration::from_millis(500));
845            }
846            panic!("never saw {want:?} in the status; the last was {last:?}");
847        };
848
849        // Default limit: the second run queues behind the first.
850        let first = spawn_slot(&bash, &script, &root, None, &["--", "sleep", "10"]);
851        until(None, &["slot: HELD"]);
852        let second = spawn_slot(&bash, &script, &root, None, &["--", "true"]);
853        let s = until(None, &["slot: HELD", "queued #1"]);
854        assert!(!s.contains("slot-2"), "one slot: the second waits, it does not take another: {s:?}");
855        let second = second.wait_with_output().unwrap();
856        assert_eq!(second.status.code(), Some(0));
857        let waited = String::from_utf8_lossy(&second.stderr).to_string();
858        assert!(contains_all(&waited, &["waiting for the build slot", "has waited", "slot: HELD by"]), "got {waited:?}");
859        first.wait_with_output().unwrap();
860
861        // A limit of two, from the limit file: two hold at once, the third waits.
862        std::fs::write(root.join("limit"), "2\n").unwrap();
863        let a = spawn_slot(&bash, &script, &root, None, &["--", "sleep", "10"]);
864        until(None, &["slots: 1 of 2 in use"]);
865        let b = spawn_slot(&bash, &script, &root, None, &["--", "sleep", "10"]);
866        until(None, &["slot: HELD", "slot-2: HELD", "slots: 2 of 2 in use"]);
867        let c = spawn_slot(&bash, &script, &root, None, &["--", "true"]);
868        until(None, &["slots: 2 of 2 in use", "queued #1"]);
869        assert_eq!(c.wait_with_output().unwrap().status.code(), Some(0), "the third runs once one is released");
870        a.wait_with_output().unwrap();
871        b.wait_with_output().unwrap();
872    }
873
874    /// A call from a process that already holds a slot (task -> cargo, a build script running
875    /// cargo) goes straight through: it never waits for the slot it is inside.
876    #[test]
877    fn a_nested_call_inside_a_held_slot_does_not_wait_for_itself() {
878        let Some(bash) = bash() else { return };
879        let h = home();
880        let script = h.path().join("build-slot.sh");
881        std::fs::write(&script, lf(SCRIPT)).unwrap();
882        let root = h.path().join("locks");
883        let outer = format!("bash '{}' -- echo inner", script.to_string_lossy().replace('\\', "/"));
884        let out = spawn_slot(&bash, &script, &root, None, &["--", "bash", "-c", &outer]);
885        let started = std::time::Instant::now();
886        let out = out.wait_with_output().unwrap();
887        assert!(started.elapsed() < std::time::Duration::from_secs(20), "the nested call waited for its own slot");
888        assert_eq!(out.status.code(), Some(0));
889        assert!(String::from_utf8_lossy(&out.stdout).contains("inner"));
890        // And it passes straight through even while somebody else holds the only slot.
891        let holder = spawn_slot(&bash, &script, &root, None, &["--", "sleep", "4"]);
892        std::thread::sleep(std::time::Duration::from_millis(1500));
893        let mut nested = std::process::Command::new(&bash);
894        nested.arg(&script).args(["--", "echo", "ran"]).env("AGENTMUX_BUILD_SLOT_DIR", &root).env("BUILD_SLOT_HELD", "1");
895        #[cfg(windows)]
896        {
897            use crate::win32::NoWindow;
898            nested.no_window();
899        }
900        let started = std::time::Instant::now();
901        let out = nested.output().unwrap();
902        assert!(started.elapsed() < std::time::Duration::from_secs(3), "a nested call queued behind another holder");
903        assert!(String::from_utf8_lossy(&out.stdout).contains("ran"));
904        holder.wait_with_output().unwrap();
905    }
906
907    /// A lock folder that can't be made or written never stops the build: the command runs, with a warning.
908    #[test]
909    fn an_unusable_lock_folder_runs_the_command_with_a_warning() {
910        let Some(bash) = bash() else { return };
911        let h = home();
912        let script = h.path().join("build-slot.sh");
913        std::fs::write(&script, lf(SCRIPT)).unwrap();
914        // A file where the folder's parent should be: mkdir -p can't succeed.
915        let blocker = h.path().join("not-a-folder");
916        std::fs::write(&blocker, "x").unwrap();
917        let root = blocker.join("locks");
918        let started = std::time::Instant::now();
919        let out = spawn_slot(&bash, &script, &root, None, &["--", "sh", "-c", "echo ran; exit 7"]).wait_with_output().unwrap();
920        assert!(started.elapsed() < std::time::Duration::from_secs(10), "it must not wait for a lock it can't take");
921        assert_eq!(out.status.code(), Some(7), "the command's own exit code");
922        assert!(String::from_utf8_lossy(&out.stdout).contains("ran"));
923        assert!(String::from_utf8_lossy(&out.stderr).contains("running without the build slot"), "{:?}", String::from_utf8_lossy(&out.stderr));
924    }
925
926    #[test]
927    fn the_shim_fails_open() {
928        if bash().is_none() {
929            return;
930        }
931        assert_eq!(run_shim(false, false, &["test"]).unwrap(), "REAL test", "no lock script: cargo still runs");
932        assert_eq!(run_shim(true, true, &["test"]).unwrap(), "REAL test", "AGENTMUX_BUILD_SLOT_OFF skips the slot");
933    }
934
935    /// A wait started by a native program (this test binary; on Windows also `cmd.exe` and
936    /// `task.exe`, which is how the `cargo` shim usually reaches the script) is not an orphan.
937    /// Git Bash reports pid 1 as the parent of such a wait; the script used to read that as
938    /// "the process that started this wait is gone" and leave the queue with exit 129, so a
939    /// `cargo build` that had to wait for the slot failed instead of waiting.
940    #[test]
941    fn a_wait_started_by_a_native_parent_waits_instead_of_leaving() {
942        let Some(bash) = bash() else { return };
943        let h = home();
944        let script = h.path().join("build-slot.sh");
945        std::fs::write(&script, lf(SCRIPT)).unwrap();
946        // A slot held by someone else, with a heartbeat from just now.
947        let root = h.path().join("slots");
948        let slot = root.join("slot");
949        std::fs::create_dir_all(&slot).unwrap();
950        std::fs::write(slot.join("owner"), "agent=other\ntoken=t\nstart=1\ncwd=/\ncmd=cargo test\n").unwrap();
951        std::fs::write(slot.join("heartbeat"), "").unwrap();
952        let mut cmd = std::process::Command::new(bash);
953        cmd.arg(&script)
954            .args(["--", "echo", "never"])
955            .env("AGENTMUX_BUILD_SLOT_DIR", &root)
956            // A test run inside the slot (build-slot.sh -- cargo test) inherits this, and a
957            // script that finds it set runs its command without waiting.
958            .env_remove("BUILD_SLOT_HELD")
959            .env("BUILD_SLOT_POLL", "1")
960            .env("BUILD_SLOT_MAX_WAIT", "3");
961        #[cfg(windows)]
962        {
963            use crate::win32::NoWindow;
964            cmd.no_window();
965        }
966        let out = cmd.output().unwrap();
967        let err = String::from_utf8_lossy(&out.stderr);
968        assert!(!err.contains("is gone"), "the wait took its parent for gone: {err}");
969        assert_eq!(out.status.code(), Some(75), "it should wait out BUILD_SLOT_MAX_WAIT and give up: {err}");
970        assert!(!String::from_utf8_lossy(&out.stdout).contains("never"), "the command must not run while the slot is held");
971    }
972
973    /// `spawn_slot` with more environment (a slower poll, a shorter ticket limit).
974    fn spawn_slot_env(bash: &Path, script: &Path, root: &Path, env: &[(&str, &str)], args: &[&str]) -> std::process::Child {
975        let mut cmd = std::process::Command::new(bash);
976        cmd.arg(script)
977            .args(args)
978            .env("AGENTMUX_BUILD_SLOT_DIR", root)
979            .env_remove("BUILD_SLOT_HELD")
980            .env_remove("BUILD_SLOT_MAX")
981            .env("BUILD_SLOT_POLL", "1")
982            .envs(env.iter().copied())
983            .stdin(std::process::Stdio::null())
984            .stdout(std::process::Stdio::piped())
985            .stderr(std::process::Stdio::piped());
986        #[cfg(windows)]
987        {
988            use crate::win32::NoWindow;
989            cmd.no_window();
990        }
991        cmd.spawn().unwrap()
992    }
993
994    fn queue_tickets(root: &Path) -> Vec<(String, String)> {
995        let mut tickets: Vec<(String, String)> = std::fs::read_dir(root.join("queue"))
996            .map(|d| {
997                d.filter_map(|e| e.ok())
998                    .filter(|e| !e.file_name().to_string_lossy().starts_with('.'))
999                    .map(|e| (e.file_name().to_string_lossy().to_string(), std::fs::read_to_string(e.path()).unwrap_or_default()))
1000                    .collect()
1001            })
1002            .unwrap_or_default();
1003        tickets.sort();
1004        tickets
1005    }
1006
1007    /// Polls `ok` for up to 30 s (process start-up is slow under load).
1008    fn wait_for(what: &str, mut ok: impl FnMut() -> bool) {
1009        for _ in 0..120 {
1010            if ok() {
1011                return;
1012            }
1013            std::thread::sleep(std::time::Duration::from_millis(250));
1014        }
1015        panic!("never saw {what}");
1016    }
1017
1018    /// The owner file carries what srv needs to watch the holder, and `status` says when srv found
1019    /// it idle: only for the run that srv named, and never for a run it has not flagged.
1020    #[test]
1021    fn status_says_a_holder_is_idle_only_when_srv_flagged_that_run() {
1022        let Some(bash) = bash() else { return };
1023        let h = home();
1024        let script = h.path().join("build-slot.sh");
1025        std::fs::write(&script, lf(SCRIPT)).unwrap();
1026        let root = h.path().join("locks");
1027        let status = || {
1028            let out = spawn_slot(&bash, &script, &root, None, &["status"]).wait_with_output().unwrap();
1029            String::from_utf8_lossy(&out.stdout).replace("\r\n", "\n")
1030        };
1031        let mut holder = spawn_slot(&bash, &script, &root, None, &["--", "sleep", "90"]);
1032        wait_for("the holder", || read_holder(&root, now_secs()).is_some());
1033        let held = read_holder(&root, now_secs()).expect("a live holder");
1034        assert!(held.pid.is_some_and(|p| p > 1), "the owner file names the script's pid: {held:?}");
1035        if cfg!(windows) {
1036            assert!(held.winpid.is_some_and(|p| p > 1), "Git Bash records its Windows process id: {held:?}");
1037        }
1038        let busy = status();
1039        assert!(busy.contains("HELD by") && !busy.contains("idle"), "a holder srv has not flagged is not idle: {busy}");
1040
1041        write_idle(&root, "some-other-run", now_secs() - 5 * 60).unwrap();
1042        assert!(!root.join("slot").join("idle").exists(), "a note for another run is not written onto this one");
1043        std::fs::write(root.join("slot").join("idle"), format!("token=an-earlier-run\nidle_since={}\n", now_secs() - 5 * 60)).unwrap();
1044        assert!(!status().contains("idle"), "a note an earlier holder left is not this holder's");
1045
1046        write_idle(&root, &held.token, now_secs() - 12 * 60).unwrap();
1047        let idle = status();
1048        assert!(
1049            idle.contains("idle for 12 min, no CPU") && idle.contains("not stopped"),
1050            "got {idle}; owner {:?}; idle file {:?}",
1051            std::fs::read_to_string(root.join("slot").join("owner")),
1052            std::fs::read_to_string(root.join("slot").join("idle"))
1053        );
1054        clear_idle(&root);
1055        assert!(!status().contains("idle"), "work removes the note");
1056        let _ = holder.kill();
1057        let _ = holder.wait();
1058    }
1059
1060    /// A waiter that a loaded host makes slow (more than the ticket limit between two touches of
1061    /// its ticket) still goes in the order it arrived. The script used to delete any other
1062    /// waiter's ticket older than 30 s, so a later arrival that was quicker took the slot first.
1063    /// Here the ticket limit is 2 s and the first waiter polls every 4 s, which is the same thing
1064    /// at test speed.
1065    #[test]
1066    fn a_slow_waiter_keeps_its_place_in_the_line() {
1067        let Some(bash) = bash() else { return };
1068        let h = home();
1069        let script = h.path().join("build-slot.sh");
1070        std::fs::write(&script, lf(SCRIPT)).unwrap();
1071        let root = h.path().join("locks");
1072        let order = h.path().join("order.txt");
1073        let append = |who: &str| format!("echo {who} >> \"{}\"", order.to_string_lossy().replace('\\', "/"));
1074
1075        let holder = spawn_slot(&bash, &script, &root, None, &["--", "sleep", "8"]);
1076        wait_for("the holder", || root.join("slot").join("owner").exists());
1077        wait_for("the holder's ticket to go", || queue_tickets(&root).is_empty());
1078        let limit = [("BUILD_SLOT_TICKET_STALE_SECS", "2")];
1079        let slow = [("BUILD_SLOT_TICKET_STALE_SECS", "2"), ("BUILD_SLOT_POLL", "4")];
1080        let a = spawn_slot_env(&bash, &script, &root, &slow, &["--", "bash", "-c", &append("A")]);
1081        wait_for("A's ticket", || queue_tickets(&root).len() == 1);
1082        // B arrives in a later second than A, so its ticket sorts after A's.
1083        std::thread::sleep(std::time::Duration::from_millis(2200));
1084        let b = spawn_slot_env(&bash, &script, &root, &limit, &["--", "bash", "-c", &append("B")]);
1085        assert_eq!(a.wait_with_output().unwrap().status.code(), Some(0));
1086        assert_eq!(b.wait_with_output().unwrap().status.code(), Some(0));
1087        holder.wait_with_output().unwrap();
1088        let ran = std::fs::read_to_string(&order).unwrap().replace("\r\n", "\n");
1089        assert_eq!(ran, "A\nB\n", "A arrived first and must run first, even though its loop is slow");
1090    }
1091
1092    /// A ticket whose waiter is gone is dropped once it is stale, so a dead waiter never holds up
1093    /// the line; this is what the 30 s rule was for, and it still works.
1094    #[test]
1095    fn the_ticket_of_a_waiter_that_is_gone_is_dropped() {
1096        let Some(bash) = bash() else { return };
1097        let h = home();
1098        let script = h.path().join("build-slot.sh");
1099        std::fs::write(&script, lf(SCRIPT)).unwrap();
1100        let root = h.path().join("locks");
1101        std::fs::create_dir_all(root.join("queue")).unwrap();
1102        let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
1103        // Arrived five minutes ago, untouched for two, and no process has this pid.
1104        let ticket = root.join("queue").join(format!("{}-2147483000", now - 300));
1105        std::fs::write(&ticket, "gone: cargo test\n").unwrap();
1106        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
1107        std::fs::File::options().write(true).open(&ticket).unwrap().set_modified(old).unwrap();
1108        // The dead waiter's ticket is first in line, so a run that gives up (exit 75) or has to wait
1109        // out the ticket's age (the limit is 300 s) shows the ticket held the line.
1110        let out = spawn_slot_env(&bash, &script, &root, &[("BUILD_SLOT_MAX_WAIT", "150")], &["--", "echo", "ran"])
1111            .wait_with_output()
1112            .unwrap();
1113        assert_eq!(out.status.code(), Some(0), "{}", String::from_utf8_lossy(&out.stderr));
1114        assert!(String::from_utf8_lossy(&out.stdout).contains("ran"));
1115        assert!(!ticket.exists(), "the dead waiter's ticket is removed");
1116    }
1117
1118    /// A waiter whose ticket was removed writes it again under the same name (the same place in
1119    /// the line), with its text.
1120    #[test]
1121    fn a_ticket_that_goes_missing_comes_back_in_the_same_place() {
1122        let Some(bash) = bash() else { return };
1123        let h = home();
1124        let script = h.path().join("build-slot.sh");
1125        std::fs::write(&script, lf(SCRIPT)).unwrap();
1126        let root = h.path().join("locks");
1127        let holder = spawn_slot(&bash, &script, &root, None, &["--", "sleep", "9"]);
1128        wait_for("the holder", || root.join("slot").join("owner").exists());
1129        // The holder takes its own ticket out of the queue just after it writes the owner file.
1130        wait_for("the holder's ticket to go", || queue_tickets(&root).is_empty());
1131        let waiter = spawn_slot(&bash, &script, &root, None, &["--", "true"]);
1132        wait_for("the waiter's ticket", || {
1133            let t = queue_tickets(&root);
1134            t.len() == 1 && !t[0].1.is_empty()
1135        });
1136        let (name, text) = queue_tickets(&root).remove(0);
1137        assert!(text.contains("true"), "the ticket says who waits and for what: {text:?}");
1138        std::fs::remove_file(root.join("queue").join(&name)).unwrap();
1139        wait_for("the ticket again", || !queue_tickets(&root).is_empty());
1140        assert_eq!(queue_tickets(&root), vec![(name, text)], "back under its own name, with its text");
1141        assert_eq!(waiter.wait_with_output().unwrap().status.code(), Some(0));
1142        holder.wait_with_output().unwrap();
1143    }
1144
1145    /// `status` names every live waiter, in line; a ticket still being written is shown by its pid.
1146    #[test]
1147    fn status_lists_the_waiters_in_line_and_never_an_empty_entry() {
1148        let Some(bash) = bash() else { return };
1149        let h = home();
1150        let script = h.path().join("build-slot.sh");
1151        std::fs::write(&script, lf(SCRIPT)).unwrap();
1152        let root = h.path().join("locks");
1153        std::fs::create_dir_all(root.join("queue")).unwrap();
1154        let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
1155        std::fs::write(root.join("queue").join(format!("{}-4242", now - 5)), "lazo: cargo test\n").unwrap();
1156        std::fs::write(root.join("queue").join(format!("{}-4343", now - 4)), "").unwrap();
1157        let out = spawn_slot(&bash, &script, &root, None, &["status"]).wait_with_output().unwrap();
1158        let text = String::from_utf8_lossy(&out.stdout).replace("\r\n", "\n");
1159        assert!(text.contains("queued #1: lazo: cargo test"), "got {text:?}");
1160        assert!(text.contains("queued #2: (waiter pid 4343)"), "got {text:?}");
1161    }
1162}