Skip to main content

agentmux_srv_core/agents/
runner.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Unified agent runner — one-shot Claude Code spawn for the
5//! drone Agent block.
6//!
7//! Spawns `claude --print --output-format=stream-json` as a non-
8//! interactive subprocess, drains its stdout through
9//! `ClaudeTranslator`, forwards each `AgentEvent` on the caller's
10//! `tx`, and resolves the handle's `final_result` with the
11//! structured `AgentRunResult` once the stream emits `Done`.
12//!
13//! Headless and one-shot by design — the drone Agent block's
14//! contract is "send task, wait for done, return result." The
15//! interactive agent pane has its own PTY-based controller in
16//! `blockcontroller/shell/lifecycle.rs`; that path is NOT routed
17//! through this runner's spawn — what's shared is the translator +
18//! event shape, not the spawn function. (This used to cite a
19//! `SPEC_UNIFIED_AGENT_TYPES` spec that no longer exists anywhere in
20//! `docs/`; the pointer was dropped rather than replaced — see
21//! `scripts/check-spec-citations.sh`.)
22//! It DOES reuse this module's commit-aware admission gate
23//! (`admit_spawn` / `agent_commit_reserve_gb`, `pub(crate)`) — see
24//! `blockcontroller::shell::lifecycle::ShellController::start`,
25//! which calls them right before spawning a `claude`/`codex`/
26//! `gemini`/`qwen` interactive pane, mirroring this file's
27//! `run_agent` gate.
28
29#[cfg(windows)]
30use agentmux_common::win32::NoWindow;
31use std::path::PathBuf;
32use std::process::Stdio;
33
34use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
35use tokio::process::Command;
36use tokio::sync::{mpsc, oneshot};
37
38use super::failure::classify;
39use super::translator::claude::ClaudeTranslator;
40use super::translator::Translator as _;
41use super::types::{AgentEvent, AgentRef, AgentRunResult, AgentTask};
42
43/// Override the default `claude` binary name. Set to a full path
44/// (or a different binary) for testing or non-PATH installs.
45const ENV_CLAUDE_BIN: &str = "AGENTMUX_CLAUDE_BIN";
46
47const DEFAULT_CLAUDE_BIN: &str = "claude";
48
49/// Handle returned by `run_agent`. The caller already holds the
50/// `mpsc::UnboundedReceiver<AgentEvent>` they paired with the `tx`
51/// passed into `run_agent`; this handle adds the structured terminal
52/// value via `final_result` (drone Agent block's downstream
53/// output).
54///
55/// Dropping the caller's receiver implicitly cancels the run only if
56/// the runner observes the send error — Phase 2 adds an explicit
57/// `AbortHandle`.
58pub struct AgentRunHandle {
59    pub final_result: oneshot::Receiver<Result<AgentRunResult, String>>,
60}
61
62/// Error returned by the runner.
63#[derive(Debug, thiserror::Error)]
64pub enum AgentError {
65    #[error("agent runner: spawn failed: {0}")]
66    Spawn(String),
67    /// A container agent can write the folder the agent would start in, or has run in it
68    /// (`mcp_folder_rule::workflow_refusal`): nothing is started there.
69    #[error("agent runner: {0}")]
70    FolderRule(String),
71    /// System commit headroom is below the reserve required to safely start
72    /// another agent. Refusing here prevents a new `claude.exe` from tipping the
73    /// system commit charge into its limit, where a failed allocation aborts the
74    /// CEF host (Chromium OOM, `0xE0000008`). Callers should surface a transient
75    /// "memory full — try again when memory frees" rather than a hard failure.
76    /// Pillar 3 (`SPEC_WIN10_PAGEFILE_OOM_CRASH` / `SPEC_ARCHITECTURE_HEALTH_AND_REFACTOR`).
77    #[error("agent runner: insufficient memory to start agent ({avail_gb:.1} GB commit free, need {reserve_gb:.1} GB headroom)")]
78    CommitPressure { avail_gb: f64, reserve_gb: f64 },
79}
80
81/// Minimum free system commit (GB) required to admit a new agent spawn. Below
82/// this, launching another `claude.exe` risks pushing the system commit charge
83/// to its limit, where a failed allocation aborts the CEF host (Chromium OOM).
84///
85/// SPEC_WIN10_PAGEFILE_OOM_CRASH_2026_06_29's original P0 called for
86/// re-deriving this reserve from real per-agent `PrivateUsage`, not
87/// `VirtualMemorySize64` — the 6/26 estimate (`SPEC_MEMORY_ANALYSIS_2026_06_26`)
88/// had mistakenly attributed ~10.5 GB of commit to each `claude.exe`, read off
89/// `VirtualMemorySize64` (reserved address space, not commit charge). That
90/// number was never wired into this constant — this file has measured
91/// `2.0 GB` since Pillar 3 shipped (#1853) — but the measurement trail behind
92/// it is worth stating explicitly now that it exists:
93/// `SPEC_MEMORY_COMMIT_ATTRIBUTION_CORRECTION_2026_07_02.md` re-measured a
94/// live `claude.exe`'s actual `PrivateUsage` (Windows' real per-process commit
95/// counter) at ~1.05 GB, corroborated independently by
96/// Resource-Exhaustion-Detector telemetry (0.49–0.67 GB) in the 6/29 spec.
97/// `2.0` GB is ~2x that per-agent figure, a reasonable safety margin for one
98/// additional spawn — no VirtualMemorySize64-derived inflation to correct.
99/// Overridable via `AGENTMUX_AGENT_COMMIT_RESERVE_GB` (e.g. 0 disables the
100/// gate on a host with a huge page file; higher on a constrained box).
101const DEFAULT_AGENT_COMMIT_RESERVE_GB: f64 = 2.0;
102
103pub(crate) fn agent_commit_reserve_gb() -> f64 {
104    std::env::var("AGENTMUX_AGENT_COMMIT_RESERVE_GB")
105        .ok()
106        .and_then(|s| s.parse::<f64>().ok())
107        .filter(|v| *v >= 0.0)
108        .unwrap_or(DEFAULT_AGENT_COMMIT_RESERVE_GB)
109}
110
111/// Pure admission decision: is there enough free system commit to spawn another
112/// agent? `None` available (non-Windows, or the read failed) ⇒ admit — there's no
113/// cheap commit limit to enforce. Strict `<` so a value exactly at the reserve is
114/// admitted. CEF-free / OS-free so it is fully unit-testable.
115pub(crate) fn admit_spawn(avail_commit_gb: Option<f64>, reserve_gb: f64) -> Result<(), AgentError> {
116    match avail_commit_gb {
117        Some(avail) if avail < reserve_gb => {
118            Err(AgentError::CommitPressure { avail_gb: avail, reserve_gb })
119        }
120        _ => Ok(()),
121    }
122}
123
124/// Spawn `claude --print --output-format=stream-json` per the given
125/// `AgentTask` and `AgentRef`, drain its stdout through the shared
126/// `ClaudeTranslator`, forward each `AgentEvent` on `tx`, and
127/// resolve the returned handle's `final_result` with an
128/// `AgentRunResult` constructed from the terminal Cost + Done events.
129///
130/// Working directory resolution:
131///   - `agent_ref.working_directory` if non-empty
132///   - else the current process working directory
133///
134/// Account and bundle resolution, and named-agent continuation
135/// are NOT plumbed in Phase 1.5 PR 2 — the drone Agent block
136/// always spawns fresh (per spec §8 "drone runs always allocate
137/// fresh instance_name"). The bundles can be added in a follow-up
138/// once the drone inspector (PR 3) needs to surface them.
139pub async fn run_agent(
140    agent_ref: AgentRef,
141    task: AgentTask,
142    tx: mpsc::UnboundedSender<AgentEvent>,
143) -> Result<AgentRunHandle, AgentError> {
144    // Pillar 3 — commit-aware admission control. Refuse to spawn another agent
145    // when system commit headroom is below the reserve, rather than letting the
146    // new claude.exe push the box into an OOM abort. Gated here (the production
147    // entry) not in `run_agent_with_bin`, so the unit tests that inject a binary
148    // path bypass the gate and stay deterministic across hosts.
149    admit_spawn(
150        crate::backend::sysinfo::available_commit_gb(),
151        agent_commit_reserve_gb(),
152    )?;
153    let bin = std::env::var(ENV_CLAUDE_BIN)
154        .unwrap_or_else(|_| DEFAULT_CLAUDE_BIN.to_string());
155    run_agent_with_bin(&bin, agent_ref, task, tx).await
156}
157
158/// The folder a step starts in: the one it names, made absolute against srv's own folder when it is relative;
159/// srv's own folder when it names none.
160fn resolved_folder(named: &str) -> std::io::Result<PathBuf> {
161    if !named.is_empty() && std::path::Path::new(named).is_absolute() {
162        return Ok(PathBuf::from(named));
163    }
164    std::env::current_dir().map(|own| resolved_in(named, &own))
165}
166
167fn resolved_in(named: &str, own: &std::path::Path) -> PathBuf {
168    if named.is_empty() {
169        own.to_path_buf()
170    } else {
171        own.join(named)
172    }
173}
174
175/// The one question asked of every start of a harness on this computer in a folder: where a container agent can
176/// write or has run, nothing of the folder may run, and this start has no flags to keep the CLI to AgentMux's
177/// config. Asked of the folder the CLI really starts in (srv's own, when the step names none). The check reads
178/// the disk and the store, so it runs off the async workers.
179async fn refuse_in_a_container_agents_folder(working_dir: &std::path::Path) -> Result<(), AgentError> {
180    let asked = working_dir.to_path_buf();
181    let refusal = tokio::task::spawn_blocking(move || crate::backend::mcp_folder_rule::workflow_refusal(&asked))
182        .await
183        .unwrap_or_else(|_| Some(crate::backend::mcp_folder_rule::WORKFLOW_REFUSAL.to_string()));
184    refusal.map_or(Ok(()), |why| Err(AgentError::FolderRule(why)))
185}
186
187/// Internal entry point — same as `run_agent` but takes the `claude`
188/// binary path explicitly. Lets tests inject a known-nonexistent
189/// path to exercise the spawn-failure path without touching env vars
190/// (Rust 1.81+ flags `std::env::set_var` as unsound under concurrent
191/// test execution). The public `run_agent` is a thin shim that
192/// resolves the binary from `$AGENTMUX_CLAUDE_BIN` or the default.
193pub(crate) async fn run_agent_with_bin(
194    bin: &str,
195    agent_ref: AgentRef,
196    task: AgentTask,
197    tx: mpsc::UnboundedSender<AgentEvent>,
198) -> Result<AgentRunHandle, AgentError> {
199    let working_dir = resolved_folder(&agent_ref.working_directory).map_err(|e| AgentError::Spawn(format!("cwd: {e}")))?;
200    refuse_in_a_container_agents_folder(&working_dir).await?;
201
202    // `claude --print` runs in non-interactive mode and exits when
203    // done. `--output-format=stream-json` emits one JSON object per
204    // line, the format ClaudeTranslator consumes. `--verbose` is
205    // required alongside stream-json (the CLI rejects stream-json
206    // without it). `--include-partial-messages` gives us the
207    // streaming text_deltas — the translator skips the resulting
208    // `partial: true` snapshots when building the transcript.
209    let mut cmd = Command::new(bin);
210    // The drone one-shot agent spawn — sibling of the interactive agent pane in
211    // blockcontroller. `tokio::process::Command` inherits the parent environment
212    // wholesale, so without this every drone-launched CLI (and everything it
213    // shells out to) receives this instance's channel, data dir and cache dir.
214    // Same policy as the agent pane: the CLI is one of ours and may use the
215    // in-pane helpers, so the keep-set applies. (ReAgent P0, round 3, on #3326.)
216    crate::backend::pane_env::sanitize_process_command(&mut cmd);
217    cmd.args(task.tools.args()).arg("--print") // tool flags take lists: first, so a flag follows them and the prompt is not read as a tool
218        .arg("--output-format=stream-json")
219        .arg("--verbose")
220        .arg("--include-partial-messages")
221        // Moves per-machine sections (cwd, env info, memory paths, git status)
222        // out of the system prompt into the first user message, matching the
223        // persistent-controller launch args in providers.rs. This spawn path
224        // builds its own args independent of ProviderConfig, so the flag has
225        // to be added here too — reagent P1 on PR #1964.
226        .arg("--exclude-dynamic-system-prompt-sections");
227    // Forward the configured turn cap so the CLI enforces it.
228    // Previously stored on AgentTask but never passed to the
229    // subprocess — silently ignored. Reagent P1 + codex P2 on
230    // PR #834.
231    if let Some(n) = task.max_turns {
232        cmd.arg("--max-turns").arg(n.to_string());
233    }
234    // On Windows: suppress console-window allocation. Spawned from the windowless
235    // srv without CREATE_NO_WINDOW, this one-shot task-agent CLI opens a Windows
236    // Terminal window per run (Win11 default-terminal handler). stdio is piped, so
237    // no console is needed. See docs/retro/retro-windows-terminal-window-leak-2026-06-21.md.
238    #[cfg(windows)]
239    {
240        cmd.no_window();
241    }
242    crate::backend::process_tracker::registry::own_process_group(&mut cmd);
243    let mut child = agentmux_common::process::KillGroupOnDrop(cmd
244        .arg(&task.prompt)
245        .current_dir(&working_dir)
246        .stdin(Stdio::null())
247        .stdout(Stdio::piped())
248        .stderr(Stdio::piped())
249        .kill_on_drop(true)
250        .spawn()
251        .map_err(|e| AgentError::Spawn(format!("spawn `{bin}`: {e}")))?);
252    crate::backend::process_tracker::registry::record_untracked_cli(child.id());
253
254    let stdout = child
255        .stdout
256        .take()
257        .ok_or_else(|| AgentError::Spawn("claude stdout pipe missing".to_string()))?;
258    let stderr = child
259        .stderr
260        .take()
261        .ok_or_else(|| AgentError::Spawn("claude stderr pipe missing".to_string()))?;
262
263    let (result_tx, result_rx) = oneshot::channel();
264    // Hand the captured stderr back to `drain_and_collect` so a failed
265    // run reports the real cause (rate-limit / auth / OOM) instead of a
266    // bare exit code. See
267    // `docs/specs/SPEC_AGENT_FAILURE_DIAGNOSTICS_2026_06_11.md`.
268    let (stderr_tx, stderr_rx) = oneshot::channel::<Vec<u8>>();
269
270    // Drain stderr to EOF in the background so the child's pipe never
271    // fills (a half-drained pipe blocks the child on stderr writes and
272    // can stall the whole run). We keep a rolling *tail* — the last
273    // STDERR_TAIL_CAP bytes — because the CLI's terminal error line
274    // (rate-limit / auth / OOM) lands at the END of stderr; a capped
275    // prefix would drop exactly the line the classifier needs. On EOF
276    // the tail is handed to the collector via `stderr_tx`.
277    // (codex P2 on #1353: keep the tail, not a prefix.)
278    tokio::spawn(async move {
279        const STDERR_TAIL_CAP: usize = 64 * 1024;
280        let mut buf: Vec<u8> = Vec::with_capacity(8192);
281        let mut reader = BufReader::new(stderr);
282        let mut sink = [0u8; 8192];
283        loop {
284            match reader.read(&mut sink).await {
285                Ok(0) => break,
286                Ok(n) => append_capped_tail(&mut buf, &sink[..n], STDERR_TAIL_CAP),
287                Err(_) => break,
288            }
289        }
290        // Trim to exactly the last CAP bytes. If the receiver is gone
291        // (run succeeded — nobody needs stderr), the send just drops.
292        trim_to_tail(&mut buf, STDERR_TAIL_CAP);
293        let _ = stderr_tx.send(buf);
294    });
295
296    tokio::spawn(finish_or_abandon(result_tx, async move { drain_and_collect(stdout, &tx, &mut child, stderr_rx).await }));
297
298    Ok(AgentRunHandle {
299        final_result: result_rx,
300    })
301}
302
303/// Run `work` and send its result, unless the caller drops `final_result` first
304/// (a drone run cancelled or timed out): then `work` is dropped where it stands,
305/// and the child it owns is killed with it (`KillGroupOnDrop`).
306async fn finish_or_abandon<T>(mut result_tx: oneshot::Sender<T>, work: impl std::future::Future<Output = T>) {
307    tokio::select! {
308        result = work => {
309            let _ = result_tx.send(result);
310        }
311        () = result_tx.closed() => {}
312    }
313}
314
315/// Drain `stdout` line-by-line through `ClaudeTranslator`, forward
316/// every emitted event on `tx`, accumulate the terminal `Cost` /
317/// `Done` event payloads into an `AgentRunResult`, wait for the
318/// child to exit, and return the result.
319///
320/// Split out from `run_agent`; its parsing core, `drain_async_reader`,
321/// takes any async reader, so the unit tests below exercise it against
322/// in-memory pipes without spawning a real subprocess.
323async fn drain_and_collect(
324    stdout: tokio::process::ChildStdout,
325    tx: &mpsc::UnboundedSender<AgentEvent>,
326    child: &mut tokio::process::Child,
327    stderr_rx: oneshot::Receiver<Vec<u8>>,
328) -> Result<AgentRunResult, String> {
329    let result = drain_async_reader(BufReader::new(stdout), tx).await;
330
331    // Wait for child to exit so the OS reaps it cleanly.
332    let exit = child.wait().await.map_err(|e| format!("wait: {e}"))?;
333
334    match result {
335        Ok(mut accumulated) => {
336            // A run is a failure if the process exited non-zero OR claude
337            // reported an error on stdout (a terminal error `result`
338            // frame) even while exiting 0 — otherwise downstream blocks
339            // could treat a failed run as successful. (codex P1 #1353.)
340            let reported_error = accumulated.error_frame.take();
341            if exit.success() && reported_error.is_none() {
342                // Genuine success — but a stream that produced nothing is
343                // itself a (classified) failure, not a silent empty result.
344                if accumulated.response.is_empty() && accumulated.transcript.is_empty() {
345                    return Err(
346                        explain_failure(exit.code(), exit_signal(&exit), None, stderr_rx).await,
347                    );
348                }
349                accumulated.transcript.shrink_to_fit();
350                return Ok(accumulated);
351            }
352            // Non-zero exit, or a stdout-reported error on exit 0: classify
353            // from the exit status + result frame + captured stderr so the
354            // caller sees a real cause, not "exited with status N".
355            Err(explain_failure(exit.code(), exit_signal(&exit), reported_error, stderr_rx).await)
356        }
357        // Stream read error: still enrich with the exit/stderr cause.
358        Err(e) => {
359            let cause = explain_failure(exit.code(), exit_signal(&exit), None, stderr_rx).await;
360            Err(format!("{cause}\n(stream read: {e})"))
361        }
362    }
363}
364
365/// Await the captured stderr, classify the exit, log a warning, and
366/// render the human-readable explanation that becomes the run's
367/// terminal error string. See
368/// `docs/specs/SPEC_AGENT_FAILURE_DIAGNOSTICS_2026_06_11.md`.
369async fn explain_failure(
370    exit_code: Option<i32>,
371    signal: Option<i32>,
372    result_frame: Option<serde_json::Value>,
373    stderr_rx: oneshot::Receiver<Vec<u8>>,
374) -> String {
375    let bytes = stderr_rx.await.unwrap_or_default();
376    let stderr = String::from_utf8_lossy(&bytes);
377    let failure = classify(exit_code, signal, &stderr, result_frame.as_ref());
378    tracing::warn!(
379        code = ?failure.code,
380        exit_code = ?exit_code,
381        signal = ?signal,
382        retryable = failure.retryable,
383        "agent run failed: {}",
384        failure.title,
385    );
386    failure.explain()
387}
388
389/// Extract the terminating signal (Unix only). On non-Unix there is no
390/// signal concept, so this is always `None`.
391#[cfg(unix)]
392fn exit_signal(status: &std::process::ExitStatus) -> Option<i32> {
393    use std::os::unix::process::ExitStatusExt;
394    status.signal()
395}
396
397#[cfg(not(unix))]
398fn exit_signal(_status: &std::process::ExitStatus) -> Option<i32> {
399    None
400}
401
402/// Append `chunk` to a rolling tail buffer, compacting to the last
403/// `cap` bytes whenever it grows past `2 * cap` (amortized O(1)). The
404/// exact final trim happens at EOF via [`trim_to_tail`]. Keeping the
405/// *tail* (not a prefix) matters because the CLI's terminal error line
406/// is at the end of stderr.
407fn append_capped_tail(buf: &mut Vec<u8>, chunk: &[u8], cap: usize) {
408    buf.extend_from_slice(chunk);
409    if buf.len() > cap.saturating_mul(2) {
410        trim_to_tail(buf, cap);
411    }
412}
413
414/// Drop all but the last `cap` bytes of `buf`.
415fn trim_to_tail(buf: &mut Vec<u8>, cap: usize) {
416    if buf.len() > cap {
417        let excess = buf.len() - cap;
418        buf.drain(0..excess);
419    }
420}
421
422/// Drain an arbitrary async reader of newline-delimited stream-json
423/// frames, forward every emitted `AgentEvent` on `tx`, and return
424/// an accumulator capturing the terminal `Cost` and `Done` values.
425///
426/// Pure async helper — no subprocess, no broker. Unit-tested with
427/// `tokio::io::duplex` in-memory pipes.
428pub(crate) async fn drain_async_reader<R: tokio::io::AsyncBufRead + Unpin>(
429    mut reader: R,
430    tx: &mpsc::UnboundedSender<AgentEvent>,
431) -> Result<AgentRunResult, String> {
432    let mut translator = ClaudeTranslator::new();
433    let mut accumulated = AgentRunResult::default();
434    let mut line = String::new();
435    loop {
436        line.clear();
437        let n = reader
438            .read_line(&mut line)
439            .await
440            .map_err(|e| format!("stdout read: {e}"))?;
441        if n == 0 {
442            break; // EOF
443        }
444        let trimmed = line.trim_end_matches(['\n', '\r']);
445        if !trimmed.starts_with('{') {
446            continue;
447        }
448        let Ok(frame) = serde_json::from_str::<serde_json::Value>(trimmed) else {
449            continue;
450        };
451        // Capture a terminal *error* result frame so the collector can
452        // fail the run even when claude reports the error on stdout and
453        // exits 0 (the translator still emits a hollow `Done`).
454        // codex P1 on #1353.
455        if frame.get("type").and_then(|v| v.as_str()) == Some("result")
456            && super::failure::is_error_result_frame(&frame)
457        {
458            accumulated.error_frame = Some(frame.clone());
459        }
460        for event in translator.translate(frame) {
461            // Capture terminal values before forwarding so a closed
462            // receiver doesn't lose the accumulated result.
463            match &event {
464                AgentEvent::Cost { cost_usd, tokens } => {
465                    accumulated.cost_usd = *cost_usd;
466                    accumulated.tokens = tokens.clone();
467                }
468                AgentEvent::Done {
469                    response,
470                    transcript,
471                } => {
472                    accumulated.response = response.clone();
473                    accumulated.transcript = transcript.clone();
474                }
475                _ => {}
476            }
477            // Forward — if the receiver is dropped, just stop
478            // sending (the drain still continues to capture the
479            // accumulated result).
480            let _ = tx.send(event);
481        }
482    }
483    Ok(accumulated)
484}
485
486#[cfg(test)]
487mod tests {
488    use super::*;
489    use serde_json::json;
490    use tokio::io::AsyncWriteExt;
491
492    /// Build a stream-json byte sequence simulating a complete
493    /// short claude run: streamed text + cost + result.
494    fn synthetic_stream(prompt_reply: &str, cost: f64) -> Vec<u8> {
495        let mut s = String::new();
496        for ch in prompt_reply.chars() {
497            s.push_str(&format!(
498                r#"{{"type":"stream_event","event":{{"type":"content_block_delta","delta":{{"type":"text_delta","text":"{ch}"}}}}}}"#,
499            ));
500            s.push('\n');
501        }
502        s.push_str(&format!(
503            r#"{{"type":"assistant","message":{{"content":[{{"type":"text","text":"{prompt_reply}"}}]}}}}
504"#
505        ));
506        s.push_str(&format!(
507            r#"{{"type":"result","cost_usd":{cost},"usage":{{"input_tokens":10,"output_tokens":5,"cache_creation_input_tokens":0,"cache_read_input_tokens":0}},"result":"{prompt_reply}"}}
508"#
509        ));
510        s.into_bytes()
511    }
512
513    // ── Pillar 3 — commit-aware admission control (pure decision) ──────────────
514
515    #[test]
516    fn admit_spawn_allows_when_headroom_at_or_above_reserve() {
517        assert!(admit_spawn(Some(8.0), 2.0).is_ok());
518        // Exactly at the reserve admits (strict `<`).
519        assert!(admit_spawn(Some(2.0), 2.0).is_ok());
520    }
521
522    #[test]
523    fn admit_spawn_refuses_below_reserve() {
524        match admit_spawn(Some(1.0), 2.0) {
525            Err(AgentError::CommitPressure { avail_gb, reserve_gb }) => {
526                assert_eq!(avail_gb, 1.0);
527                assert_eq!(reserve_gb, 2.0);
528            }
529            other => panic!("expected CommitPressure, got {other:?}"),
530        }
531    }
532
533    #[test]
534    fn admit_spawn_admits_when_commit_unknown() {
535        // None (non-Windows / read failure) ⇒ no cheap limit to enforce ⇒ admit.
536        assert!(admit_spawn(None, 2.0).is_ok());
537    }
538
539    #[test]
540    fn agent_commit_reserve_defaults_when_env_absent_or_invalid() {
541        // Not asserting on the env var (tests share a process); just verify the
542        // default is the documented conservative floor and is non-negative.
543        assert_eq!(DEFAULT_AGENT_COMMIT_RESERVE_GB, 2.0);
544        assert!(DEFAULT_AGENT_COMMIT_RESERVE_GB >= 0.0);
545    }
546
547    #[tokio::test]
548    async fn drain_async_reader_accumulates_cost_and_done() {
549        let bytes = synthetic_stream("hello", 0.001);
550        let (mut w, r) = tokio::io::duplex(4096);
551        tokio::spawn(async move {
552            w.write_all(&bytes).await.unwrap();
553            w.shutdown().await.unwrap();
554        });
555
556        let (tx, mut rx) = mpsc::unbounded_channel();
557        let result = drain_async_reader(BufReader::new(r), &tx)
558            .await
559            .expect("drain ok");
560
561        assert_eq!(result.response, "hello");
562        assert_eq!(result.cost_usd, 0.001);
563        assert_eq!(result.tokens.input, 10);
564        assert_eq!(result.tokens.output, 5);
565        // Transcript contains the assistant turn.
566        assert_eq!(result.transcript.len(), 1);
567
568        // Events forwarded: 5 AssistantText (one per char) + Cost + Done.
569        drop(tx);
570        let mut evs = Vec::new();
571        while let Some(e) = rx.recv().await {
572            evs.push(e);
573        }
574        assert_eq!(evs.len(), 7, "got events: {evs:?}");
575        match &evs[evs.len() - 1] {
576            AgentEvent::Done { .. } => {}
577            other => panic!("expected last event Done, got {other:?}"),
578        }
579    }
580
581    #[tokio::test]
582    async fn drain_async_reader_skips_non_json_lines() {
583        // claude --verbose sometimes emits informational lines on
584        // stdout that aren't stream-json (rare but possible). Those
585        // must not break the drain.
586        let mut bytes: Vec<u8> = b"Reading config...\n".to_vec();
587        bytes.extend_from_slice(&synthetic_stream("ok", 0.0));
588        bytes.extend_from_slice(b"\n");
589
590        let (mut w, r) = tokio::io::duplex(4096);
591        tokio::spawn(async move {
592            w.write_all(&bytes).await.unwrap();
593            w.shutdown().await.unwrap();
594        });
595
596        let (tx, _rx) = mpsc::unbounded_channel();
597        let result = drain_async_reader(BufReader::new(r), &tx)
598            .await
599            .expect("drain ok");
600        assert_eq!(result.response, "ok");
601    }
602
603    #[tokio::test]
604    async fn drain_async_reader_returns_empty_on_no_stream() {
605        let (mut w, r) = tokio::io::duplex(4096);
606        tokio::spawn(async move {
607            // Just close — no output at all.
608            w.shutdown().await.unwrap();
609        });
610
611        let (tx, _rx) = mpsc::unbounded_channel();
612        let result = drain_async_reader(BufReader::new(r), &tx)
613            .await
614            .expect("drain ok");
615        // Default-empty result — the drain itself succeeds; the
616        // caller (drain_and_collect) is responsible for surfacing
617        // the "no Done event" as an error since it depends on
618        // exit status semantics.
619        assert!(result.response.is_empty());
620        assert_eq!(result.cost_usd, 0.0);
621    }
622
623    #[tokio::test]
624    async fn drain_async_reader_handles_multi_line_chunks() {
625        // BufReader's read_line is well-defined; this just guards
626        // against future regressions where someone might switch to a
627        // chunked reader.
628        let bytes = synthetic_stream("multi", 0.01);
629        let (mut w, r) = tokio::io::duplex(4096);
630        tokio::spawn(async move {
631            // Write in small chunks to exercise the read path.
632            for chunk in bytes.chunks(7) {
633                w.write_all(chunk).await.unwrap();
634            }
635            w.shutdown().await.unwrap();
636        });
637
638        let (tx, _rx) = mpsc::unbounded_channel();
639        let result = drain_async_reader(BufReader::new(r), &tx)
640            .await
641            .expect("drain ok");
642        assert_eq!(result.response, "multi");
643    }
644
645    #[tokio::test]
646    async fn drain_handles_malformed_json_gracefully() {
647        let mut bytes: Vec<u8> =
648            b"{this is not valid json\n{\"type\":\"unknown\"}\n".to_vec();
649        bytes.extend_from_slice(&synthetic_stream("recovered", 0.0));
650
651        let (mut w, r) = tokio::io::duplex(4096);
652        tokio::spawn(async move {
653            w.write_all(&bytes).await.unwrap();
654            w.shutdown().await.unwrap();
655        });
656
657        let (tx, _rx) = mpsc::unbounded_channel();
658        let result = drain_async_reader(BufReader::new(r), &tx)
659            .await
660            .expect("drain ok");
661        assert_eq!(result.response, "recovered");
662    }
663
664    #[tokio::test]
665    #[ignore = "requires `claude` CLI on PATH; run manually for end-to-end"]
666    async fn run_agent_end_to_end_with_real_claude() {
667        // Manual smoke: AGENTMUX_CLAUDE_BIN=/path/to/claude
668        // cargo test -p agentmux-srv-core -- --ignored
669        //     run_agent_end_to_end_with_real_claude
670        let (tx, mut rx) = mpsc::unbounded_channel();
671        let handle = run_agent(
672            AgentRef::default(),
673            AgentTask {
674                prompt: "What is 2+2? Respond with just the number.".to_string(),
675                context: serde_json::Map::new(),
676                max_turns: None,
677                tools: Default::default(),
678            },
679            tx,
680        )
681        .await
682        .expect("spawn ok");
683
684        // Drain events until done.
685        while let Some(_ev) = rx.recv().await {}
686
687        let result = handle
688            .final_result
689            .await
690            .expect("oneshot ok")
691            .expect("agent run ok");
692        assert!(result.response.contains('4'), "got: {}", result.response);
693        assert!(result.cost_usd > 0.0);
694    }
695
696    #[tokio::test]
697    async fn a_run_whose_caller_gave_up_is_dropped_with_what_it_owns() {
698        struct Owned(Option<oneshot::Sender<()>>);
699        impl Drop for Owned {
700            fn drop(&mut self) {
701                let _ = self.0.take().unwrap().send(());
702            }
703        }
704        let (result_tx, result_rx) = oneshot::channel::<u32>();
705        let (dropped_tx, dropped_rx) = oneshot::channel();
706        let task = tokio::spawn(finish_or_abandon(result_tx, async move {
707            let _owned = Owned(Some(dropped_tx));
708            std::future::pending::<u32>().await
709        }));
710        tokio::task::yield_now().await;
711        drop(result_rx);
712        tokio::time::timeout(std::time::Duration::from_secs(5), dropped_rx).await.expect("the work was dropped").unwrap();
713        task.await.unwrap();
714    }
715
716    #[tokio::test]
717    async fn a_finished_run_sends_its_result() {
718        let (result_tx, result_rx) = oneshot::channel::<u32>();
719        tokio::spawn(finish_or_abandon(result_tx, async { 7 }));
720        assert_eq!(result_rx.await.unwrap(), 7);
721    }
722
723    /// A step in a folder a container agent can write starts nothing: the answer is the rule's, not the spawn's,
724    /// even for a program that does not exist (which would otherwise be a spawn failure). A folder no container
725    /// agent has to do with goes on to the spawn.
726    #[tokio::test]
727    async fn a_step_in_a_container_agents_folder_starts_nothing() {
728        let (bound, own) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
729        crate::backend::fs_ops::container_folders::add_for_test(bound.path(), "agentmux-runner-rule", "/workspace");
730        let run = |dir: &std::path::Path| {
731            let (tx, _rx) = mpsc::unbounded_channel();
732            let agent = AgentRef { working_directory: dir.to_string_lossy().into_owned(), ..AgentRef::default() };
733            let task = AgentTask { prompt: "hi".to_string(), context: serde_json::Map::new(), max_turns: None, tools: Default::default() };
734            async move { run_agent_with_bin("/definitely/does/not/exist/claude-xyz-test", agent, task, tx).await }
735        };
736        match run(bound.path()).await {
737            Err(AgentError::FolderRule(why)) => assert_eq!(why, crate::backend::mcp_folder_rule::WORKFLOW_REFUSAL),
738            other => panic!("expected the rule's refusal, got {:?}", other.err()),
739        }
740        assert!(matches!(run(&bound.path().join("inside")).await, Err(AgentError::FolderRule(_))), "a folder in it");
741        assert!(matches!(run(own.path()).await, Err(AgentError::Spawn(_))), "any other folder goes on to the spawn");
742    }
743
744    /// The rule is asked of the folder the process really starts in: a relative folder is taken against srv's own
745    /// folder, and a link to a folder is the folder it leads to.
746    #[test]
747    fn the_rule_is_asked_of_where_a_relative_or_linked_folder_resolves() {
748        let (parent, own) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
749        let bound = parent.path().join("agent");
750        std::fs::create_dir_all(bound.join("inside")).unwrap();
751        crate::backend::fs_ops::container_folders::add_for_test(&bound, "agentmux-runner-rule-resolved", "/workspace");
752        let rule = |dir: &std::path::Path| crate::backend::mcp_folder_rule::workflow_refusal(dir).is_some();
753
754        assert_eq!(resolved_in("", own.path()), own.path(), "no folder named: srv's own");
755        assert_eq!(resolved_in("sub", own.path()), own.path().join("sub"));
756        // Relative to srv's own folder, the path leads out of it into the agent's.
757        let relative = format!("../{}/agent/inside", parent.path().file_name().unwrap().to_string_lossy());
758        assert!(!rule(own.path()));
759        assert!(rule(&resolved_in(&relative, own.path())), "a relative folder is asked where it leads");
760        assert!(!rule(&resolved_in("elsewhere", own.path())), "and a relative folder that leads nowhere near it is not refused");
761
762        // A link, from a folder of the person's, to the agent's folder.
763        let link = own.path().join("link");
764        #[cfg(unix)]
765        let linked = std::os::unix::fs::symlink(&bound, &link).is_ok();
766        #[cfg(windows)]
767        let linked = std::os::windows::fs::symlink_dir(&bound, &link).is_ok();
768        if linked {
769            assert!(rule(&link), "a link to the agent's folder is the agent's folder");
770            assert!(rule(&link.join("inside")), "and so is a folder in it");
771        } else {
772            eprintln!("no link could be made here: a linked folder is not tried");
773        }
774    }
775
776    #[tokio::test]
777    async fn run_agent_with_bin_surfaces_spawn_failure() {
778        // Inject a known-nonexistent binary path so the spawn fails
779        // deterministically. Verifies the AgentError::Spawn path
780        // without touching env vars (set_var is unsound under
781        // concurrent test execution in Rust 1.81+).
782        let (tx, _rx) = mpsc::unbounded_channel();
783        let result = run_agent_with_bin(
784            "/definitely/does/not/exist/claude-xyz-test",
785            AgentRef::default(),
786            AgentTask {
787                prompt: "hi".to_string(),
788                context: serde_json::Map::new(),
789                max_turns: None,
790                tools: Default::default(),
791            },
792            tx,
793        )
794        .await;
795        match result {
796            Err(AgentError::Spawn(msg)) => {
797                assert!(
798                    msg.contains("spawn") || msg.contains("does/not/exist"),
799                    "spawn error message should reference the failure; got: {msg}"
800                );
801            }
802            Err(other) => panic!("expected Spawn error, got: {other}"),
803            Ok(_) => panic!("expected Spawn error, got Ok(handle)"),
804        }
805    }
806
807    /// End-to-end (Unix): a stub binary that writes a rate-limit line to
808    /// stderr and exits 1 must produce a *classified* failure naming the
809    /// cause and including the stderr tail — not a bare "exit 1".
810    /// Exercises G1 (stderr retained) + G2 (classify) of
811    /// SPEC_AGENT_FAILURE_DIAGNOSTICS.
812    #[cfg(unix)]
813    #[tokio::test]
814    async fn classified_failure_surfaces_cause_and_stderr() {
815
816        let path = std::env::temp_dir()
817            .join(format!("amux-stub-claude-{}.sh", uuid::Uuid::new_v4()));
818        write_stub_script(
819            &path,
820            &[
821                "echo 'API Error: Server is temporarily limiting requests (not your usage limit) · Rate limited' >&2",
822                "exit 1",
823            ],
824        );
825
826        let (tx, _rx) = mpsc::unbounded_channel();
827        let handle = run_stub(
828            &path,
829            AgentTask {
830                prompt: "hi".to_string(),
831                context: serde_json::Map::new(),
832                max_turns: None,
833                tools: Default::default(),
834            },
835            tx,
836        )
837        .await
838        .expect("spawn ok");
839
840        let err = handle
841            .final_result
842            .await
843            .expect("oneshot ok")
844            .expect_err("run should fail");
845
846        assert!(
847            err.contains("Rate-limited"),
848            "explanation should name the class; got: {err}"
849        );
850        assert!(
851            err.to_lowercase().contains("rate limited"),
852            "stderr tail should be included; got: {err}"
853        );
854        assert!(
855            err.contains("retryable"),
856            "rate-limit is retryable; got: {err}"
857        );
858
859        let _ = std::fs::remove_file(&path);
860    }
861
862    /// End-to-end (Unix): stderr larger than the tail cap with the real
863    /// error on the LAST line must still classify correctly — the
864    /// rolling tail keeps the end, not a prefix. Regression test for
865    /// codex P2 on #1353.
866    #[cfg(unix)]
867    #[tokio::test]
868    async fn classified_failure_reads_error_past_stderr_cap() {
869
870        let path = std::env::temp_dir()
871            .join(format!("amux-stub-claude-big-{}.sh", uuid::Uuid::new_v4()));
872        write_stub_script(
873            &path,
874            &[
875                // ~70 KiB of filler (> 64 KiB tail cap), THEN the real error.
876                "head -c 70000 /dev/zero | tr '\\0' x >&2",
877                "printf '\\nAPI Error: Server is temporarily limiting requests (not your usage limit) Rate limited\\n' >&2",
878                "exit 1",
879            ],
880        );
881
882        let (tx, _rx) = mpsc::unbounded_channel();
883        let handle = run_stub(
884            &path,
885            AgentTask {
886                prompt: "hi".to_string(),
887                context: serde_json::Map::new(),
888                max_turns: None,
889                tools: Default::default(),
890            },
891            tx,
892        )
893        .await
894        .expect("spawn ok");
895
896        let err = handle
897            .final_result
898            .await
899            .expect("oneshot ok")
900            .expect_err("run should fail");
901
902        assert!(
903            err.contains("Rate-limited"),
904            "must classify from the tail past the cap; got: {}",
905            err.chars().take(160).collect::<String>()
906        );
907
908        let _ = std::fs::remove_file(&path);
909    }
910
911    #[test]
912    fn rolling_tail_keeps_last_bytes_past_cap() {
913        let cap = 8;
914        let mut buf = Vec::new();
915        for i in 0..100u8 {
916            append_capped_tail(&mut buf, &[i], cap);
917            assert!(buf.len() <= cap * 2, "rolling buffer must stay bounded");
918        }
919        trim_to_tail(&mut buf, cap);
920        assert_eq!(buf, vec![92, 93, 94, 95, 96, 97, 98, 99]);
921    }
922
923    #[test]
924    fn rolling_tail_single_large_chunk() {
925        let cap = 4;
926        let mut buf = Vec::new();
927        append_capped_tail(&mut buf, b"abcdefghij", cap);
928        trim_to_tail(&mut buf, cap);
929        assert_eq!(&buf, b"ghij");
930    }
931
932    #[tokio::test]
933    async fn drain_captures_error_result_frame() {
934        // An error result frame on stdout must be captured so the
935        // collector can fail the run even on exit 0. codex P1 #1353.
936        let bytes =
937            b"{\"type\":\"result\",\"is_error\":true,\"subtype\":\"error_during_execution\",\"error\":{\"message\":\"overloaded_error\"}}\n"
938                .to_vec();
939        let (mut w, r) = tokio::io::duplex(4096);
940        tokio::spawn(async move {
941            w.write_all(&bytes).await.unwrap();
942            w.shutdown().await.unwrap();
943        });
944        let (tx, _rx) = mpsc::unbounded_channel();
945        let result = drain_async_reader(BufReader::new(r), &tx)
946            .await
947            .expect("drain ok");
948        assert!(
949            result.error_frame.is_some(),
950            "error result frame should be captured"
951        );
952    }
953
954    /// Write an executable `/bin/sh` stub at `path`, atomically.
955    ///
956    /// Built at a sibling temp name and renamed into place, rather than created
957    /// directly at `path`. Creating it at its final path races every other test
958    /// that spawns a subprocess: between `File::create` and the handle being
959    /// dropped, another thread's `fork()` inherits the still-writable fd, and
960    /// the child holds it open until it execs — so exec'ing that same path here
961    /// fails with `ETXTBSY` ("Text file busy"). `CLOEXEC`, which Rust sets by
962    /// default, does not help: it closes on *exec*, and the window is between
963    /// fork and exec.
964    ///
965    /// Observed ~1 run in 3 of the parallel suite (`spawn ok: Spawn("spawn
966    /// /tmp/amux-stub-claude-okerr-….sh: Text file busy (os error 26)")`). CI
967    /// runs `--test-threads=1`, which is why it never fired there and sat
968    /// unexplained locally.
969    ///
970    /// `rename(2)` is atomic and the final path is never open for writing, so
971    /// no forked child can hold a write fd to it.
972    #[cfg(unix)]
973    fn write_stub_script(path: &std::path::Path, lines: &[&str]) {
974        use std::io::Write as _;
975        use std::os::unix::fs::PermissionsExt as _;
976        let tmp = path.with_extension("sh.partial");
977        {
978            let mut f = std::fs::File::create(&tmp).unwrap();
979            writeln!(f, "#!/bin/sh").unwrap();
980            for l in lines {
981                writeln!(f, "{l}").unwrap();
982            }
983            f.flush().unwrap();
984        }
985        let mut perms = std::fs::metadata(&tmp).unwrap().permissions();
986        perms.set_mode(0o755);
987        std::fs::set_permissions(&tmp, perms).unwrap();
988        std::fs::rename(&tmp, path).unwrap();
989    }
990
991    /// [`run_agent_with_bin`] on a stub from [`write_stub_script`], retrying
992    /// while the stub is "Text file busy". ETXTBSY is about the file, not its
993    /// path: a child forked by another test while the stub was open for
994    /// writing holds that write fd until it execs, and the rename above keeps
995    /// the same file — so the race it was meant to close stays open under the
996    /// parallel suite. It is always transient.
997    #[cfg(unix)]
998    async fn run_stub(
999        path: &std::path::Path,
1000        task: AgentTask,
1001        tx: mpsc::UnboundedSender<AgentEvent>,
1002    ) -> Result<AgentRunHandle, AgentError> {
1003        let mut attempt = 0;
1004        loop {
1005            match run_agent_with_bin(path.to_str().unwrap(), AgentRef::default(), task.clone(), tx.clone()).await {
1006                Err(e) if attempt < 20 && format!("{e:?}").contains("Text file busy") => {
1007                    attempt += 1;
1008                    tokio::time::sleep(std::time::Duration::from_millis(25)).await;
1009                }
1010                r => return r,
1011            }
1012        }
1013    }
1014
1015    /// The CLI is started with the block's tool limit as flags: reading tools and no MCP server for a block with no
1016    /// commands, `Bash` for exactly its command lines, and no flag at all for `allow_commands: true`.
1017    #[cfg(unix)]
1018    #[tokio::test]
1019    async fn the_cli_is_started_with_the_blocks_tool_limit() {
1020        use super::super::tool_limit::ToolLimit;
1021        let dir = tempfile::tempdir().unwrap();
1022        let argv_of = |tools: ToolLimit| {
1023            let (stub, out) = (dir.path().join(format!("stub-{}.sh", uuid::Uuid::new_v4())), dir.path().join(format!("argv-{}.txt", uuid::Uuid::new_v4())));
1024            write_stub_script(&stub, &[&format!("printf '%s\\n' \"$@\" > '{}'", out.display()), "exit 1"]);
1025            async move {
1026                let (tx, _rx) = mpsc::unbounded_channel();
1027                let task = AgentTask { prompt: "hi".to_string(), context: serde_json::Map::new(), max_turns: None, tools };
1028                let handle = run_stub(&stub, task, tx).await.expect("spawn ok");
1029                let _ = handle.final_result.await;
1030                std::fs::read_to_string(out).unwrap().lines().map(str::to_string).collect::<Vec<_>>()
1031            }
1032        };
1033        let value_after = |argv: &[String], flag: &str| argv.iter().position(|a| a == flag).map(|i| argv[i + 1].clone());
1034
1035        let reading = argv_of(ToolLimit::default()).await;
1036        assert_eq!(value_after(&reading, "--tools").as_deref(), Some("Read,Grep,Glob"), "{reading:?}");
1037        assert!(reading.iter().any(|a| a == "--strict-mcp-config"), "{reading:?}");
1038        assert_eq!(value_after(&reading, "--permission-mode").as_deref(), Some("dontAsk"), "{reading:?}");
1039        assert!(!reading.iter().any(|a| a == "--allowedTools" || a.contains("Bash")), "no command may run: {reading:?}");
1040
1041        let some = argv_of(ToolLimit::Limited { commands: vec!["git status".to_string()] }).await;
1042        assert_eq!(value_after(&some, "--tools").as_deref(), Some("Read,Grep,Glob,Bash"), "{some:?}");
1043        assert_eq!(value_after(&some, "--allowedTools").as_deref(), Some("Bash(git status)"), "{some:?}");
1044        assert_eq!(value_after(&some, "--setting-sources").as_deref(), Some(""), "no settings file adds to the list: {some:?}");
1045
1046        // A tool flag takes a list: the prompt is the last argument and never one of its values.
1047        for argv in [&reading, &some] {
1048            assert_eq!(argv.last().map(String::as_str), Some("hi"), "{argv:?}");
1049            for flag in ["--tools", "--allowedTools"] {
1050                let Some(at) = argv.iter().position(|a| a == flag) else { continue };
1051                let values = argv[at + 1..].iter().take_while(|a| !a.starts_with("--"));
1052                assert!(!values.clone().any(|v| v == "hi"), "{flag} reads the prompt as a value: {argv:?}");
1053            }
1054        }
1055
1056        let free = argv_of(ToolLimit::Unlimited).await;
1057        assert!(!free.iter().any(|a| a == "--tools" || a == "--strict-mcp-config"), "{free:?}");
1058    }
1059
1060    /// End-to-end (Unix): claude can report an error on stdout and still
1061    /// exit 0; the runner must NOT treat that as success. codex P1 #1353.
1062    #[cfg(unix)]
1063    #[tokio::test]
1064    async fn stdout_error_result_with_exit_zero_is_a_failure() {
1065        let path = std::env::temp_dir()
1066            .join(format!("amux-stub-claude-okerr-{}.sh", uuid::Uuid::new_v4()));
1067        // Emit an error result frame on stdout, then exit 0. The JSON lives in
1068        // a `let` so its braces are data, not format placeholders.
1069        let frame = r#"{"type":"result","is_error":true,"subtype":"error_during_execution","error":{"message":"overloaded_error: upstream busy"}}"#;
1070        write_stub_script(&path, &[&format!("echo '{frame}'"), "exit 0"]);
1071
1072        let (tx, _rx) = mpsc::unbounded_channel();
1073        let handle = run_stub(
1074            &path,
1075            AgentTask {
1076                prompt: "hi".to_string(),
1077                context: serde_json::Map::new(),
1078                max_turns: None,
1079                tools: Default::default(),
1080            },
1081            tx,
1082        )
1083        .await
1084        .expect("spawn ok");
1085
1086        let err = handle
1087            .final_result
1088            .await
1089            .expect("oneshot ok")
1090            .expect_err("stdout-reported error with exit 0 must fail");
1091        assert!(
1092            err.to_lowercase().contains("overloaded"),
1093            "should classify the stdout error; got: {err}"
1094        );
1095
1096        let _ = std::fs::remove_file(&path);
1097    }
1098
1099    /// The Drone task CLI leads its own process group (like an agent pane's),
1100    /// so a signal to its group can't reach srv and its helpers die with it.
1101    #[cfg(unix)]
1102    #[tokio::test]
1103    async fn the_task_cli_leads_its_own_process_group() {
1104        let dir = std::env::temp_dir().join(format!("amux-runner-group-{}", uuid::Uuid::new_v4()));
1105        std::fs::create_dir_all(&dir).unwrap();
1106        let report = dir.join("report");
1107        let stub = dir.join("claude-stub.sh");
1108        write_stub_script(
1109            &stub,
1110            &[&format!(
1111                "echo \"$$ $(ps -o pgid= -p $$ | tr -d ' ')\" > {r}.tmp && mv {r}.tmp {r}",
1112                r = report.display()
1113            )],
1114        );
1115        let (tx, _rx) = mpsc::unbounded_channel();
1116        let task = AgentTask { prompt: "hi".to_string(), context: serde_json::Map::new(), max_turns: None, tools: Default::default() };
1117        let handle = run_stub(&stub, task, tx).await.expect("spawn ok");
1118        let _ = handle.final_result.await;
1119        let text = std::fs::read_to_string(&report).expect("the stub reported");
1120        let fields: Vec<u32> = text.split_whitespace().filter_map(|f| f.parse().ok()).collect();
1121        assert_eq!(fields.len(), 2, "{text:?}");
1122        assert_eq!(fields[0], fields[1], "the CLI leads its own process group");
1123        assert_ne!(fields[1] as i32, unsafe { libc::getpgid(0) }, "not srv's group");
1124        let _ = std::fs::remove_dir_all(&dir);
1125    }
1126
1127    #[test]
1128    fn agent_task_max_turns_field_round_trips() {
1129        // Reagent P1 + codex P2 on PR #834: the max_turns field is
1130        // forwarded to the subprocess via `--max-turns N`. We can't
1131        // assert the actual CLI argument here without spawning, but
1132        // we can verify the field flows through AgentTask's
1133        // serde + Clone path without loss — the subprocess wiring
1134        // is exercised by the end-to-end test.
1135        let task = AgentTask {
1136            prompt: "x".into(),
1137            context: serde_json::Map::new(),
1138            max_turns: Some(7),
1139            tools: Default::default(),
1140        };
1141        let v = serde_json::to_value(&task).unwrap();
1142        assert_eq!(v["maxTurns"], json!(7));
1143        let back: AgentTask = serde_json::from_value(v).unwrap();
1144        assert_eq!(back.max_turns, Some(7));
1145    }
1146
1147    #[test]
1148    fn agent_run_result_has_sensible_defaults() {
1149        let r = AgentRunResult::default();
1150        assert_eq!(r.response, "");
1151        assert_eq!(r.cost_usd, 0.0);
1152        assert!(r.transcript.is_empty());
1153        let _ = json!(r); // serializes without panic
1154    }
1155}