Skip to main content

agentmux_bashwrap/
bash_wrap.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `exec` subcommand — runs the user's bash command and streams chunks.
5//!
6//! Invariants:
7//! - The user's command is decoded from `--b64-cmd` so quoting /
8//!   multi-line / shell-metachar content survives the rewrite.
9//! - The inner command runs under `bash -c` inside a PTY by default
10//!   (`run_via_pty`), with a pipe-stdio fallback (`run_via_pipes`)
11//!   if PTY allocation fails. The PTY path keeps glibc's stdout
12//!   line-buffered so partial chunks reach the overlay in real time;
13//!   ConPTY's startup DSR (`\x1b[6n`, Windows only) is satisfied by
14//!   pre-loading the master writer with `\x1b[1;1R`; the writer is held alive until
15//!   after child.wait() (dropping it earlier sends CTRL_C_EVENT on
16//!   Windows — ConPTY CONIN lifetime invariant, same as pair.master).
17//!   The command is wrapped in a brace group redirected from /dev/null
18//!   (`{ <cmd>; } </dev/null`) so stdin-reading children see EOF instead
19//!   of blocking on the live PTY slave. We must NOT use `exec </dev/null`
20//!   for this: running it inside bash closes the child's ConPTY console
21//!   input from the child side, which ConPTY reports as a CTRL_C_EVENT,
22//!   killing every command with exit 130 before it ran. The group
23//!   redirect points only the group's fd 0 at /dev/null while bash's own
24//!   console fd stays open, so children get EOF and ConPTY never fires.
25//!   The pipe path remains as a safety net and is the only path that
26//!   preserves the stdout/stderr split — PTY collapses both onto
27//!   one stream. See `docs/specs/SPEC_LIVE_LOG_PTY_REWORK_2026_05_16.md`.
28//! - Bash is located via `$AGENTMUX_BASH` → `$BASH` → PATH search →
29//!   well-known Windows locations (Git Bash). Fails loud if missing.
30//! - Each line is published as its own chunk with `kind` set to
31//!   `"stdout"` (PTY path always; pipe path for stdout reads) or
32//!   `"stderr"` (pipe path only — PTY merges both onto one stream).
33//!   Aggregated output (with stderr lines prefixed `[stderr] ` in the
34//!   pipe path) is captured into a buffer; on exit, a formatted summary
35//!   lands on this process's stdout for Claude's native Bash tool to
36//!   harvest as the `tool_result` content. Truncated head/tail at 50KB
37//!   each per `docs/specs/SPEC_STREAMING_BASH_RUNNER_2026_05_11.md` §4.5.
38//! - If MPS publish fails (missing env, sidecar down, etc.), the
39//!   command still runs to completion — output just doesn't stream.
40//!   The model-visible blob is unaffected. A `kind: "system"` chunk
41//!   announces the degradation at startup.
42
43#[cfg(windows)]
44use agentmux_common::win32::NoWindow;
45use anyhow::{Context, Result, anyhow};
46use portable_pty::{CommandBuilder, PtySize, native_pty_system};
47use std::path::PathBuf;
48use std::process::Stdio;
49use std::sync::Arc;
50use std::time::Duration;
51use tokio::io::AsyncReadExt;
52use tokio::process::Command;
53use tokio::sync::{Mutex, mpsc, oneshot};
54
55use crate::cwd_state::{append_cwd_capture, CwdState, CWD_STATE_ENV};
56use crate::mps_client::WpsClient;
57
58pub use crate::exec_args::Args;
59
60/// Cap the model-visible head/tail sections of the aggregated blob.
61const MODEL_BLOB_HEAD_BYTES: usize = 50_000;
62const MODEL_BLOB_TAIL_BYTES: usize = 50_000;
63
64/// Flush pending bytes to the publisher when buffered without a
65/// newline AND the buffer reaches this size — so long lines and
66/// newline-free output (minified JSON, CR-only progress bars) still
67/// stream live instead of accumulating in memory unbounded.
68const FLUSH_BYTES: usize = 4096;
69
70/// Size of the PTY commands run in. Wider than the classic 80 so that
71/// width-aware programs (tables, `--help`, `ls` columns) don't fold their
72/// output with hard line breaks; previews scroll long lines instead. Bash
73/// derives `COLUMNS` / `LINES` from it.
74const PTY_COLS: u16 = 200;
75const PTY_ROWS: u16 = 50;
76
77/// Flush pending bytes after this much idle time even if no newline /
78/// size threshold has been hit — keeps slow-trickle output visible
79/// without waiting for the next byte that would have triggered a
80/// natural flush.
81const FLUSH_QUIET_WINDOW: Duration = Duration::from_millis(50);
82
83/// If a wrapped command's PTY produces zero bytes of output for this long,
84/// assume it's blocked waiting for interactive input that will never come
85/// (e.g. `less`/`more` invoked as a pager, since the PTY deliberately makes
86/// the child see `isatty(stdout) == true` and this wrapper never writes to
87/// the PTY again after the startup DSR response) and forcibly kill it
88/// rather than leak this whole process forever. See
89/// docs/retro/RETRO_BASHWRAP_PAGER_HANG_LEAK_2026_07_14.md.
90///
91/// This is an IDLE timeout, not a total-runtime timeout: a command that's
92/// silent for under this long but runs far longer overall (e.g. a build
93/// with continuous compiler output over several minutes) is unaffected —
94/// only a command producing literally zero bytes for the full window trips
95/// it. Overridable via `AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS`.
96const DEFAULT_IDLE_KILL_TIMEOUT: Duration = Duration::from_secs(600);
97
98fn idle_kill_timeout() -> Duration {
99    std::env::var("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS")
100        .ok()
101        .and_then(|s| s.parse::<u64>().ok())
102        .map(Duration::from_secs)
103        .unwrap_or(DEFAULT_IDLE_KILL_TIMEOUT)
104}
105
106/// The idle-kill timeout to actually apply for this invocation. A
107/// declared-background call (`args.declared_background`, threaded from the
108/// CLI's own `run_in_background: true`) is exempt from the idle-kill safety
109/// net entirely — it may legitimately go silent forever (a GUI window, a dev
110/// server) without that being a stuck/pager-hung command. Everything else
111/// keeps the ordinary `idle_kill_timeout()`. See issue #2491.
112fn effective_idle_timeout(args: &Args) -> Duration {
113    if args.declared_background {
114        Duration::from_secs(u64::MAX)
115    } else {
116        idle_kill_timeout()
117    }
118}
119
120/// For a `--declared-background` invocation, detach this process into a
121/// brand-new session (`setsid()`) before doing anything else, so it has no
122/// controlling terminal at all.
123///
124/// Without this, this process (and anything it spawns — the wrapped
125/// command's own PTY-hosted child, e.g. `task dev`) stays in the SAME
126/// session as the `claude` CLI process that invoked it (an ordinary child
127/// inherits its parent's session/process group unless it explicitly
128/// detaches). Two independent POSIX mechanisms then both threaten it the
129/// moment that session's leader (`claude`) is killed for ANY reason,
130/// including a clean single-PID kill that never touches this process
131/// directly:
132/// 1. If `claude`'s own PTY master is closed (agentmux-srv's normal
133///    stop/replace path drops its input channel, which drops the PTY
134///    writer+master — see `blockcontroller/shell/lifecycle.rs`), the
135///    kernel hangs up the terminal, sending SIGHUP to the whole foreground
136///    process group of that terminal.
137/// 2. Independently of (1): POSIX also sends SIGHUP to a session's
138///    foreground process group when the session LEADER terminates — this
139///    fires purely from `claude` exiting, with no PTY-close step required
140///    at all.
141/// Either one, by default, terminates this process (SIGHUP's default
142/// disposition) — and if this process is what's directly holding open the
143/// wrapped command's own PTY master (the common case, via `run_via_pty`),
144/// this process dying closes that PTY too, cascading the exact same
145/// hangup one level deeper to the wrapped command itself. `setsid()`
146/// makes this process (and, transitively, anything it PTY-spawns
147/// afterward, which becomes associated with THIS new session rather than
148/// `claude`'s) immune to both — a session with no controlling terminal at
149/// all has no foreground process group for the kernel to signal. See
150/// docs/specs/SPEC_BACKGROUND_TASK_TEARDOWN_SURVIVAL_2026_08_20.md and the
151/// Codex finding on PR #2683 this was written to address.
152///
153/// A plain child (not already a process group leader — always true here,
154/// since this process was just `exec`'d as an ordinary child of `claude`)
155/// can always call `setsid()` successfully; a failure would be a genuine
156/// platform anomaly, logged but not fatal — worst case this invocation
157/// keeps the pre-existing (already-buggy, already being fixed elsewhere in
158/// this same PR) exposure, rather than losing the command's actual output.
159/// No-op on Windows (no session/controlling-terminal concept to detach
160/// from) and for an ordinary, non-backgrounded invocation.
161#[cfg(unix)]
162fn detach_declared_background_session(args: &Args) {
163    if !args.declared_background {
164        return;
165    }
166    // SAFETY: setsid() is a well-defined POSIX syscall; this process is
167    // not a process group leader (an ordinary freshly-exec'd child never
168    // is), so EPERM (the only failure mode) cannot occur in practice.
169    let rc = unsafe { libc::setsid() };
170    if rc == -1 {
171        tracing::warn!(
172            target: "bashwrap",
173            tool_id = %args.tool_id,
174            error = %std::io::Error::last_os_error(),
175            "setsid() failed for a declared-background invocation — this task remains exposed to SIGHUP if the owning agent session is torn down",
176        );
177    }
178}
179
180#[cfg(not(unix))]
181fn detach_declared_background_session(_args: &Args) {}
182
183/// Kill `pid` AND every descendant it spawned, not just the one process.
184/// Supplements `ChildKiller::kill()` (portable-pty's Windows impl is a bare
185/// `TerminateProcess` on a single handle, no job object — see the caller's
186/// comment) — without this, a wrapped command whose direct child forks
187/// further (a pipeline, or `git` spawning `less` as a child) can leave an
188/// orphaned grandchild running and still attached to the PTY slave after
189/// the "kill" (reagent P1, PR #2156).
190///
191/// `agentmux_common::process::force_kill_tree` does the killing, by PID only:
192///
193/// Windows: `taskkill /F /T /PID <pid>` (console flash suppressed) walks the
194/// OS-level parent-PID tree, independent of shell job control, and
195/// force-kills every process in it.
196///
197/// Unix: SIGKILL to the child's process group. portable-pty makes the PTY
198/// child a session and group leader (`setsid`), so its pgid is its pid and
199/// the group holds the command, its pipeline and what it backgrounded with
200/// `&`. portable-pty's own `ChildKiller` only SIGHUPs the one pid, which a
201/// `nohup`'d child ignores. A child that started its own session is out of
202/// reach here; the agent's process tracker ends it with the agent.
203fn kill_process_tree(pid: u32) {
204    match agentmux_common::process::force_kill_tree(pid) {
205        Ok(()) => tracing::info!(target: "bashwrap", pid, "kill_process_tree: tree killed"),
206        // Non-fatal: the direct-handle kill above may have already won the
207        // race (the tree is then "not found"), which is fine — best-effort
208        // supplemental cleanup either way.
209        Err(e) => tracing::warn!(target: "bashwrap", pid, error = %e, "kill_process_tree: kill did not report success"),
210    }
211}
212
213/// Internal channel payload: a single line tagged with its source.
214/// Bytes are raw — UTF-8 conversion is deferred to the publish /
215/// aggregation site so non-UTF-8 output (binary `cat`, Windows
216/// legacy-encoded tools) doesn't abort the reader.
217#[derive(Debug)]
218struct LineEvent {
219    kind: ToolChunkKind, // Stdout or Stderr
220    /// Raw bytes including the trailing `\n` if present. May be the
221    /// final fragment before EOF without a newline, in which case it
222    /// has no trailing delimiter.
223    bytes: Vec<u8>,
224}
225
226/// Returns the inner command's exit code so main.rs can mirror it as
227/// the wrapper's own process exit. Without this, Claude's native Bash
228/// tool would see success for every wrapped command regardless of the
229/// actual outcome.
230pub async fn run(args: Args) -> Result<i32> {
231    let command = decode_command(&args.b64_cmd)?;
232    run_command(args, command).await
233}
234
235pub(crate) async fn run_command(mut args: Args, command: String) -> Result<i32> {
236    detach_declared_background_session(&args);
237    log_relevant_env();
238
239    // `block_id` controls the MPS publish scope. Prefer the explicit
240    // CLI arg, but fall back to AGENTMUX_BLOCKID env (set by
241    // agentmux-srv when spawning Claude) so the hook doesn't have to
242    // pass it explicitly. Without a scope, the frontend's per-block
243    // subscription won't receive the events.
244    if args.block_id.as_deref().filter(|s| !s.is_empty()).is_none() {
245        if let Ok(v) = std::env::var("AGENTMUX_BLOCKID") {
246            if !v.is_empty() {
247                args.block_id = Some(v);
248            }
249        }
250    }
251
252    let mps = WpsClient::from_env();
253    let degraded = mps.is_none();
254
255    let buffered = Arc::new(Mutex::new(Vec::<u8>::with_capacity(64 * 1024)));
256
257    tracing::info!(
258        target: "bashwrap",
259        tool_id = %args.tool_id,
260        block_id = %args.block_id.as_deref().unwrap_or(""),
261        degraded,
262        command_len = command.len(),
263        "exec start"
264    );
265
266    // Join handle for the fire-and-forget pid publish below, if spawned.
267    // `main.rs` calls `std::process::exit()` immediately once `run()`
268    // returns — which tears down every still-in-flight spawned task with
269    // no Drop glue, silently. Every OTHER spawned task in this file
270    // (`idle_watcher`, `publisher_handle`, `wait_task`, the
271    // `kill_process_tree` spawn_blocking) is explicitly joined with a
272    // bounded timeout before `run()` returns for exactly this reason; this
273    // one must be too (reagentx P1, PR #2681) — joined below, after
274    // `run_proc` completes, so it still doesn't block a genuinely
275    // long-running declared-background command's own startup (by the time
276    // a long-running command's `run_proc` finally returns, this task has
277    // long since finished on its own — the join below is only ever a real
278    // wait in the narrow case `run_proc` returns quickly, e.g. the wrapped
279    // command fails fast).
280    let mut pid_publish: Option<tokio::task::JoinHandle<()>> = None;
281
282    if degraded {
283        // Surface degradation as a real chunk on stdout (we'll prefix
284        // it on the model side too) so the user sees a clear "no
285        // streaming this turn" message in the overlay. MPS publish
286        // would no-op, so we skip it.
287        let warn = b"[bashwrap] warning: streaming disabled (auth/url env missing); command output will only appear on completion\n";
288        buffered.lock().await.extend_from_slice(warn);
289    } else if let Some(client) = mps.as_ref() {
290        match publish_system(
291            client,
292            &args.tool_id,
293            args.block_id.as_deref(),
294            &format!("[bashwrap] starting: {} chars", command.len()),
295        )
296        .await
297        {
298            Ok(()) => tracing::info!(target: "bashwrap", tool_id = %args.tool_id, "initial publish ok"),
299            Err(e) => tracing::warn!(target: "bashwrap", tool_id = %args.tool_id, error = %e, "initial publish failed"),
300        }
301        if args.declared_background {
302            // Fire-and-forget, NOT awaited inline: publish_pid's own doc
303            // comment promises best-effort semantics, and awaiting it
304            // right here (as an earlier version of this code did) put its
305            // up-to-~10s worst case (two publish_chunk attempts, each up
306            // to the 5s WpsClient::from_env default, plus the retry's own
307            // 250ms sleep) directly on this declared-background command's
308            // startup path — measurably delaying the actual work (e.g.
309            // `task dev`) behind a degraded MPS endpoint, exactly what
310            // "best-effort" is supposed to avoid (reagentx P1, PR #2681).
311            // Still joined (bounded) below before `run()` returns, so a
312            // fast-exiting wrapped command can't silently abandon it.
313            let client = client.clone();
314            let tool_id = args.tool_id.clone();
315            let block_id = args.block_id.clone();
316            pid_publish = Some(tokio::spawn(async move {
317                publish_pid(&client, &tool_id, block_id.as_deref(), std::process::id()).await;
318            }));
319        }
320    }
321
322    let start = std::time::Instant::now();
323    // NOT `?` here — captured instead of propagated immediately. `run_proc`
324    // can fail fast (e.g. `locate_bash()`/PTY-or-pipe spawn failure) and an
325    // early `?`-return would skip the pid_publish join below entirely,
326    // reproducing the exact abandonment bug the join exists to prevent, just
327    // via the Err path instead of a fast Ok exit (reagentx P1, round 3 on
328    // this PR — the round-2 fix only covered the Ok(status) fast-exit case).
329    let run_result = run_proc(&args, &command, mps.as_ref(), buffered.clone()).await;
330    let elapsed = start.elapsed();
331
332    if let Some(handle) = pid_publish {
333        // Bound slightly above publish_pid's own worst case (~10.25s: two
334        // publish attempts at up to 5s each + the 250ms retry sleep) so
335        // this only ever cuts it short in a genuinely wedged case, not a
336        // normal slow-but-still-within-its-own-bounds one.
337        match tokio::time::timeout(Duration::from_secs(11), handle).await {
338            Ok(Ok(())) => {}
339            Ok(Err(join_err)) => {
340                tracing::warn!(target: "bashwrap", tool_id = %args.tool_id, error = %join_err, "pid publish task panicked");
341            }
342            Err(_elapsed) => {
343                tracing::warn!(target: "bashwrap", tool_id = %args.tool_id, "pid publish task still running after its own bound — abandoning rather than delaying exit further");
344            }
345        }
346    }
347
348    let status = run_result?;
349
350    if let Some(client) = mps.as_ref() {
351        let _ = client
352            .publish_chunk(
353                args.block_id.as_deref(),
354                &ToolChunk::Terminal {
355                    tool_id: args.tool_id.clone(),
356                    exit_code: status,
357                    timestamp: now_ms(),
358                },
359            )
360            .await;
361    }
362
363    let buf = buffered.lock().await;
364    let mut model_blob = format_model_blob(&buf, status, elapsed);
365    if let Some(hint) = access_denied_hint(&buf, status) {
366        model_blob.push_str(hint);
367    }
368    print!("{}", model_blob);
369    Ok(status)
370}
371
372fn decode_command(b64: &str) -> Result<String> {
373    use base64::Engine as _;
374    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
375    let bytes = URL_SAFE_NO_PAD
376        .decode(b64.as_bytes())
377        .context("decoding --b64-cmd")?;
378    Ok(String::from_utf8(bytes).context("--b64-cmd is not valid UTF-8")?)
379}
380
381use agentmux_common::client_events::{ToolChunk, ToolChunkKind};
382use agentmux_common::time::now_ms_u64 as now_ms;
383
384/// Log which streaming-relevant env vars the wrapper actually received,
385/// so the sidecar log tells us at a glance whether the env-propagation
386/// chain from agentmux-srv → claude → bash → hook → here is intact.
387/// Values are not logged (auth key is sensitive); presence/absence is
388/// the only signal we need to triage the propagation gap.
389fn log_relevant_env() {
390    let has = |k: &str| std::env::var(k).is_ok();
391    tracing::info!(
392        target: "bashwrap",
393        auth_key = has("AGENTMUX_AUTH_KEY"),
394        local_url = has("AGENTMUX_LOCAL_URL"),
395        agent_id = has("AGENTMUX_AGENT_ID"),
396        block_id = has("AGENTMUX_BLOCKID"),
397        bash = std::env::var("BASH").ok(),
398        agentmux_bash = std::env::var("AGENTMUX_BASH").ok(),
399        "bashwrap exec env snapshot"
400    );
401}
402
403async fn publish_system(
404    client: &WpsClient,
405    tool_id: &str,
406    block_id: Option<&str>,
407    msg: &str,
408) -> Result<()> {
409    client
410        .publish_chunk(
411            block_id,
412            &ToolChunk::Chunk {
413                tool_id: tool_id.to_string(),
414                kind: ToolChunkKind::System,
415                content: msg.to_string(),
416                timestamp: now_ms(),
417            },
418        )
419        .await
420}
421
422/// Publish this process's own pid, once, for a declared-background
423/// invocation. Called via `tokio::spawn` (never awaited inline) — see the
424/// call site's comment for why blocking startup on this was a real
425/// latency bug (reagentx P1, PR #2681).
426///
427/// The single retry here is insurance against a transient MPS/HTTP
428/// publish failure ONLY — it does not, and cannot, wait for
429/// `db_background_tasks`'s row to exist first (this function has no
430/// visibility into srv's database state). This publish routinely arrives
431/// at srv before that row exists at all (this call fires at process
432/// start, before the frontend has even seen an accepted-background tool
433/// result to create the row from) — that ordering race is handled
434/// entirely server-side, by stashing an early pid and applying it once
435/// the row is created (`pending_background_pids.rs`,
436/// `websocket.rs`'s `COMMAND_BACKGROUND_TASK_PID`/`COMMAND_DOCK_NODE_STATUS`
437/// handlers). An earlier version of this comment claimed this retry
438/// covered that race — it never did (Codex P1, reagentx P2, PR #2681).
439async fn publish_pid(client: &WpsClient, tool_id: &str, block_id: Option<&str>, pid: u32) {
440    let msg = ToolChunk::Pid {
441        tool_id: tool_id.to_string(),
442        pid,
443        timestamp: now_ms(),
444    };
445    if client.publish_chunk(block_id, &msg).await.is_ok() {
446        return;
447    }
448    tokio::time::sleep(Duration::from_millis(250)).await;
449    if let Err(e) = client.publish_chunk(block_id, &msg).await {
450        tracing::warn!(target: "bashwrap", tool_id, pid, error = %e, "pid publish failed after retry");
451    }
452}
453
454async fn publish_line(
455    client: &WpsClient,
456    tool_id: &str,
457    block_id: Option<&str>,
458    kind: ToolChunkKind,
459    line: &str,
460) -> Result<()> {
461    client
462        .publish_chunk(
463            block_id,
464            &ToolChunk::Chunk {
465                tool_id: tool_id.to_string(),
466                kind,
467                content: line.to_string(),
468                timestamp: now_ms(),
469            },
470        )
471        .await
472}
473
474/// Locate bash. Order:
475/// 1. `$AGENTMUX_BASH` — explicit override from agentmux-srv config.
476/// 2. `$BASH` — set by bash itself when it spawns a child; reliable
477///    inside Claude Code's hook context because Claude shells out to
478///    bash to run the hook.
479/// 3. `which bash` on PATH.
480/// 4. Well-known Windows paths (Git Bash, msys2). Skipped on Unix.
481///
482/// Fail-loud if not found — pass-through fallback would hide the issue.
483pub(crate) fn locate_bash() -> Result<PathBuf> {
484    if let Ok(p) = std::env::var("AGENTMUX_BASH") {
485        if !p.is_empty() {
486            return Ok(PathBuf::from(p));
487        }
488    }
489    if let Ok(p) = std::env::var("BASH") {
490        if !p.is_empty() && PathBuf::from(&p).exists() {
491            return Ok(PathBuf::from(p));
492        }
493    }
494    if let Ok(p) = which::which("bash") {
495        return Ok(p);
496    }
497    #[cfg(windows)]
498    {
499        for candidate in [
500            r"C:\Program Files\Git\bin\bash.exe",
501            r"C:\Program Files\Git\usr\bin\bash.exe",
502            r"C:\Program Files (x86)\Git\bin\bash.exe",
503            r"C:\msys64\usr\bin\bash.exe",
504            r"C:\msys2\usr\bin\bash.exe",
505        ] {
506            let p = PathBuf::from(candidate);
507            if p.exists() {
508                return Ok(p);
509            }
510        }
511    }
512    Err(anyhow!(
513        "bash not found — set AGENTMUX_BASH, install Git Bash, or add bash to PATH"
514    ))
515}
516
517/// Read raw bytes from a child stdio handle and forward chunks to
518/// the publisher with three flush triggers:
519///
520/// 1. **Newline.** As soon as a `\n` is in the buffer, drain everything
521///    up to and including that newline as one chunk. Loop, since a
522///    single read can contain multiple complete lines.
523/// 2. **Size threshold** (`FLUSH_BYTES`). If the buffer accumulates
524///    without a newline (minified JSON output, long progress lines,
525///    `printf` without `\n`), flush as soon as it exceeds the
526///    threshold. Prevents unbounded memory growth and keeps streaming
527///    live for newline-free output.
528/// 3. **Quiet-window** (`FLUSH_QUIET_WINDOW`). After this much idle
529///    time with non-empty pending bytes, flush. Surfaces slow-trickle
530///    output (one byte at a time) that would otherwise wait for the
531///    next byte to trigger a natural flush.
532async fn stream_reader<R>(
533    mut reader: R,
534    kind: ToolChunkKind,
535    tx: mpsc::Sender<LineEvent>,
536    last_activity: Arc<std::sync::Mutex<std::time::Instant>>,
537)
538where
539    R: tokio::io::AsyncRead + Unpin,
540{
541    let mut pending: Vec<u8> = Vec::with_capacity(8192);
542    let mut buf = [0u8; 8192];
543    // P1b: CR override slot — when the quiet window expires and `pending`
544    // starts with `\r`, hold it here rather than flushing immediately.
545    // The next read prepends it so collapse_cr can overwrite it with the
546    // new frame, collapsing throttled spinner frames (>50 ms apart) before
547    // they become separate LineEvents.
548    let mut pending_cr_override: Option<Vec<u8>> = None;
549    // A1: speculative one-tick hold for a pending line with no leading OR
550    // trailing `\r` yet. Mirrors the same slot in `pty_reader_loop`. See
551    // docs/specs/SPEC_TOOL_LOG_UNIVERSAL_ANIMATION_COLLAPSE_2026_07_27.md §A1.
552    let mut deferred_pending: Option<Vec<u8>> = None;
553    loop {
554        match tokio::time::timeout(FLUSH_QUIET_WINDOW, reader.read(&mut buf)).await {
555            Ok(Ok(0)) => {
556                // EOF: flush any held CR override or A1 deferred line, then
557                // drain remainder, stripping a dangling lone \r (stream
558                // ended mid-spinner or mid-CRLF pair).
559                if let Some(mut held) = pending_cr_override.take() {
560                    if held.last() == Some(&b'\r') {
561                        held.pop();
562                    }
563                    if !held.is_empty() {
564                        let _ = tx.send(LineEvent { kind, bytes: held }).await;
565                    }
566                }
567                if let Some(deferred) = deferred_pending.take() {
568                    let _ = tx.send(LineEvent { kind, bytes: deferred }).await;
569                }
570                if !pending.is_empty() {
571                    if pending.last() == Some(&b'\r') {
572                        pending.pop();
573                    }
574                    if !pending.is_empty() {
575                        let _ = tx
576                            .send(LineEvent { kind, bytes: std::mem::take(&mut pending) })
577                            .await;
578                    }
579                }
580                return;
581            }
582            Ok(Ok(n)) => {
583                // Idle-kill tracking (mirrors the PTY path's pty_reader_loop):
584                // reset on ANY bytes read, regardless of whether they become
585                // a published LineEvent — see run_via_pipes's idle watcher.
586                *last_activity.lock().unwrap_or_else(|e| e.into_inner()) = std::time::Instant::now();
587                // P1b: prepend any held CR override so collapse_cr can
588                // overwrite it with the new frame content.
589                if let Some(held) = pending_cr_override.take() {
590                    let mut combined = held;
591                    combined.extend_from_slice(&buf[..n]);
592                    pending.splice(0..0, combined);
593                } else if let Some(deferred) = deferred_pending.take() {
594                    // A1: resolve last tick's speculative hold. A leading
595                    // `\r` means this is the overwrite we were hoping for;
596                    // otherwise the deferred line was genuinely final and
597                    // unrelated — flush it on its own first.
598                    if buf[..n].first() == Some(&b'\r') {
599                        let mut combined = deferred;
600                        combined.extend_from_slice(&buf[..n]);
601                        pending.splice(0..0, combined);
602                    } else {
603                        if tx.send(LineEvent { kind, bytes: deferred }).await.is_err() {
604                            return;
605                        }
606                        pending.extend_from_slice(&buf[..n]);
607                    }
608                } else {
609                    pending.extend_from_slice(&buf[..n]);
610                }
611                collapse_cr(&mut pending);
612                // Drain every complete line.
613                while let Some(nl_pos) = pending.iter().position(|&b| b == b'\n') {
614                    let line: Vec<u8> = pending.drain(..=nl_pos).collect();
615                    if tx.send(LineEvent { kind, bytes: line }).await.is_err() {
616                        return;
617                    }
618                }
619                // P2a: newline-free residue past the size threshold — flush
620                // unconditionally to keep memory bounded. Prevents unbounded
621                // accumulation from a trailing-\r spinner that never emits \n.
622                if pending.len() >= FLUSH_BYTES {
623                    if tx
624                        .send(LineEvent { kind, bytes: std::mem::take(&mut pending) })
625                        .await
626                        .is_err()
627                    {
628                        return;
629                    }
630                }
631            }
632            Ok(Err(e)) => {
633                tracing::warn!(target: "bashwrap", error = %e, ?kind, "read error");
634                return;
635            }
636            Err(_elapsed) => {
637                // P1b/A1: quiet-window expiry.
638                //
639                // If a line was already speculatively deferred last tick
640                // (A1) and nothing new arrived since — deferred_pending
641                // being Some implies pending is empty, since any new data
642                // would have resolved it in the Ok(Ok(n)) branch above —
643                // give up waiting for a `\r`-prefixed overwrite and flush
644                // it now.
645                //
646                // If `pending` starts with `\r`, it is a leading-\r spinner
647                // frame. Stash it in the CR override slot so the next read
648                // prepends it and collapse_cr can overwrite it with the new
649                // frame.
650                //
651                // If `pending` ends with `\r` (but not starts), hold it —
652                // a following `\n` will form a complete CRLF.
653                //
654                // Otherwise (non-`\r` partial output, e.g. `printf
655                // 'Building...'`): first quiet window with this content —
656                // defer it one tick (A1) instead of flushing immediately,
657                // in case the very next read starts with `\r`. See
658                // docs/specs/SPEC_TOOL_LOG_UNIVERSAL_ANIMATION_COLLAPSE_2026_07_27.md §A1.
659                //
660                // Note: pending_cr_override / deferred_pending are always
661                // None here at this point (after the take() above). Each is
662                // set only by take(&mut pending), which empties pending; the
663                // only way to reach this branch with non-empty pending is
664                // after an Ok(Ok(n)) that already consumed and cleared both.
665                if let Some(deferred) = deferred_pending.take() {
666                    if tx.send(LineEvent { kind, bytes: deferred }).await.is_err() {
667                        return;
668                    }
669                }
670                if !pending.is_empty() {
671                    if pending.first() == Some(&b'\r') {
672                        pending_cr_override = Some(std::mem::take(&mut pending));
673                    } else if pending.last() != Some(&b'\r') {
674                        deferred_pending = Some(std::mem::take(&mut pending));
675                    }
676                    // else: trailing-\r hold — do nothing, next read resolves CRLF.
677                }
678            }
679        }
680    }
681}
682
683/// Spawn the bash child and stream its lines. PTY by default with a
684/// pipe fallback if PTY allocation fails (G6 in
685/// docs/specs/SPEC_LIVE_LOG_PTY_REWORK_2026_05_16.md).
686///
687/// Why PTY: when the child sees its stdout as a pipe, glibc switches
688/// libc stdio from line-buffered to block-buffered (~4 KB). External
689/// programs (grep, npm, cargo, python, ...) accumulate output in the
690/// stdio buffer until flush, defeating the live-log overlay's premise.
691/// PTY makes `isatty(STDOUT_FILENO) == 1` so glibc stays line-buffered.
692///
693/// CRITICAL ConPTY lifetime contract (Windows): `pair.master` MUST
694/// stay alive across `child.wait()`. Dropping master during child
695/// startup tears down the pseudoconsole anchor and produces
696/// `STATUS_DLL_INIT_FAILED` (the β.A wedge). See retro §4.2.
697///
698/// HEADLESS PTY contract (Windows): ConPTY queries the terminal at
699/// startup with `\x1b[6n` (DSR — request cursor position) and blocks
700/// waiting for a `\x1b[r;cR` response. A headless PTY (no real terminal
701/// behind it) never answers — the child never proceeds — so
702/// `child.wait()` would never return. We write a synthetic `\x1b[1;1R`
703/// response via the master writer, and the reader strips the query from
704/// the output. This is what xterm.js does for VS Code's agent-mode
705/// terminal; here we do the minimum subset for non-interactive `bash -c`.
706/// Verified via agentmux-pty-repro V2 before this landed.
707///
708/// Unix PTYs never ask (checked with `bash -c` 3.2 and 5.x on macOS: no
709/// `\x1b[6n` in the output, and the command exits without a reply). There
710/// the reply would only be echoed back by the line discipline as the
711/// printable text `^[[1;1R` at the start of every result, which no escape
712/// stripping can recognise, and left in the child's stdin. So it is sent on
713/// Windows only.
714///
715/// The PTY is [`PTY_COLS`] wide, not the classic 80: width-aware programs
716/// (tables, help text, column listings) fold their output at the terminal
717/// width with real line breaks, which no preview can undo.
718async fn run_proc(
719    args: &Args,
720    command: &str,
721    mps: Option<&WpsClient>,
722    buffered: Arc<Mutex<Vec<u8>>>,
723) -> Result<i32> {
724    let bash = locate_bash()?;
725    let pty_system = native_pty_system();
726    match pty_system.openpty(PtySize {
727        rows: PTY_ROWS,
728        cols: PTY_COLS,
729        pixel_width: 0,
730        pixel_height: 0,
731    }) {
732        Ok(pair) => {
733            tracing::info!(
734                target: "bashwrap",
735                bash = %bash.display(),
736                "spawning bash -c via PTY (live-buffered, headless DSR responder active)",
737            );
738            run_via_pty(args, command, mps, buffered, &bash, pair).await
739        }
740        Err(e) => {
741            tracing::warn!(
742                target: "bashwrap",
743                bash = %bash.display(),
744                error = %e,
745                "PTY allocation failed — falling back to pipes (output may buffer at child level)",
746            );
747            run_via_pipes(args, command, mps, buffered, &bash).await
748        }
749    }
750}
751
752/// PTY-backed run path. Holds master alive across child.wait() and
753/// answers DSR queries from bash at startup.
754pub(crate) async fn run_via_pty(
755    args: &Args,
756    command: &str,
757    mps: Option<&WpsClient>,
758    buffered: Arc<Mutex<Vec<u8>>>,
759    bash: &std::path::Path,
760    pair: portable_pty::PtyPair,
761) -> Result<i32> {
762    let mut cmd = CommandBuilder::new(bash.as_os_str());
763    // -c <cmd> for non-interactive run, WITHOUT -l. Login shell
764    // startup costs ~1 second (sources /etc/profile, /etc/bashrc,
765    // ~/.bash_profile, etc.) which the user sees as a "Running..."
766    // delay before any chunk arrives. We pre-prepend the MSYS2 bin
767    // dirs to PATH manually (see below) so external commands like
768    // `date`, `grep`, `awk` resolve without needing rc-script setup.
769    cmd.arg("-c");
770    // Give stdin-reading children (`cat`, `read`, prompted scripts) EOF
771    // instead of leaving them blocked on the live PTY slave, but do NOT use
772    // `exec </dev/null` — running that inside bash closes the child's ConPTY
773    // console-input handle from the child side, which ConPTY reports as a
774    // CTRL_C_EVENT and kills the command with exit 130 before it runs (the
775    // bug this wrapper exists to fix). A brace-group redirect points the
776    // group's fd 0 at /dev/null for the command's duration while bash's own
777    // fd 0 (the console) stays open, so children see EOF and ConPTY never
778    // fires ctrl-c. The leading newline terminates the group list cleanly
779    // regardless of how `command` ends (trailing comment, no newline, etc.).
780    let cwd_state = CwdState::for_call(args.agent.as_deref(), args.agent_unknown);
781    // Wrapped a second time by `append_cwd_capture` so the ending `$PWD`
782    // survives this disposable process — see the module doc of
783    // `cwd_state.rs` for why that's necessary.
784    cmd.arg(append_cwd_capture(&format!("{{\n{}\n}} </dev/null", command)));
785
786    // Disable pagers. The PTY above deliberately makes the child see
787    // `isatty(stdout) == true` so external tools stay line-buffered (see
788    // the module doc comment) — but that's exactly what `git`
789    // (diff/log/show/branch/...) uses to decide whether to auto-invoke
790    // `core.pager` (`less` by default). We never write to the PTY again
791    // after the startup DSR response below, so a pager waiting for a
792    // keystroke blocks forever and leaks this whole process. `cat` passes
793    // content straight through with no paging. See
794    // docs/retro/RETRO_BASHWRAP_PAGER_HANG_LEAK_2026_07_14.md.
795    cmd.env("GIT_PAGER", "cat");
796    cmd.env("PAGER", "cat");
797
798    // PATH fix-up: bashwrap is a Windows exe, so when MSYS2/Git Bash
799    // spawned us it converted PATH to Windows form, which has
800    // /c/Windows/system32, /c/Program Files/nodejs, etc. but NOT
801    // /usr/bin, /usr/local/bin, /mingw64/bin where coreutils lives.
802    // Without -l (above), the child bash inherits the Windows PATH
803    // and every external command becomes "command not found".
804    //
805    // Derive MSYS2 bin dirs from bash's own location — typically
806    // bash sits at `C:\Program Files\Git\usr\bin\bash.exe`, so the
807    // three dirs we need are reachable as siblings/cousins of that.
808    // Pre-pend them to the inherited PATH; the existing Windows
809    // entries stay so platform-specific tools (cmd, powershell, gh,
810    // ...) still resolve.
811    if let Some(usr_bin) = bash.parent() {
812        let mut prefix_dirs: Vec<std::ffi::OsString> = vec![usr_bin.to_path_buf().into()];
813        if let Some(usr) = usr_bin.parent() {
814            // /usr/local/bin sibling of /usr/bin.
815            let local_bin = usr.join("local").join("bin");
816            if local_bin.exists() {
817                prefix_dirs.push(local_bin.into());
818            }
819            // /mingw64/bin sibling of /usr (Git for Windows layout).
820            if let Some(git_root) = usr.parent() {
821                let mingw64_bin = git_root.join("mingw64").join("bin");
822                if mingw64_bin.exists() {
823                    prefix_dirs.push(mingw64_bin.into());
824                }
825            }
826        }
827        let existing_path = std::env::var_os("PATH").unwrap_or_default();
828        let mut all_dirs: Vec<std::path::PathBuf> =
829            prefix_dirs.iter().map(std::path::PathBuf::from).collect();
830        if !existing_path.is_empty() {
831            for p in std::env::split_paths(&existing_path) {
832                all_dirs.push(p);
833            }
834        }
835        let new_path = std::env::join_paths(&all_dirs)
836            .context("joining PATH entries for child bash")?;
837        cmd.env("PATH", &new_path);
838        tracing::info!(
839            target: "bashwrap",
840            prepended_dirs = ?prefix_dirs,
841            "PATH fix-up for child bash (no login-shell startup needed)",
842        );
843    }
844    if let Some(dir) = &cwd_state.start_dir {
845        cmd.cwd(dir);
846    }
847    if let Some(state_path) = &cwd_state.path {
848        cmd.env(CWD_STATE_ENV, state_path);
849    }
850
851    let child = pair
852        .slave
853        .spawn_command(cmd)
854        .with_context(|| format!("PTY spawn of bash at {}", bash.display()))?;
855
856    // Split out a killer before `child` moves into the wait task below, so
857    // an idle-timeout detected on the reader side (a different task) can
858    // still terminate it. See `ChildKiller::clone_killer`'s doc comment —
859    // this is exactly the "send it signals independently from a thread
860    // that may be blocked in `.wait`" case it exists for.
861    //
862    // `killer.kill()` alone only terminates THIS ONE process (portable-pty's
863    // Windows impl is a bare `TerminateProcess` on the direct handle, no
864    // job object) — it does not reach descendants bash forked (a pipeline,
865    // or `git` spawning `less` as a child). An orphaned grandchild can
866    // survive the kill, stay attached to the PTY slave, and keep blocking
867    // forever — reproducing this exact leak one process removed instead of
868    // eliminating it (reagent P1, PR #2156). `child_pid` + `kill_process_tree`
869    // below is the supplemental fix: a full tree-kill by PID.
870    let mut killer = child.clone_killer();
871    let child_pid = child.process_id();
872
873    let reader = pair.master.try_clone_reader().context("PTY try_clone_reader")?;
874
875    // Write the DSR response into the master writer (Windows), then hold
876    // the writer alive until after child.wait(). On Windows, closing the
877    // CONIN pipe write-end while the pseudoconsole is still attached
878    // sends CTRL_C_EVENT to the child (exit 130 / SIGINT). This is
879    // the same ConPTY-lifetime invariant as pair.master itself — both
880    // must outlive child.wait(). After the DSR response we never write
881    // again; the handle is kept open only to hold CONIN alive.
882    #[allow(unused_mut)]
883    let mut writer = pair.master.take_writer().context("PTY take_writer")?;
884    // ConPTY only: a Unix PTY never asks, and would echo this back into the
885    // output as `^[[1;1R` (see run_proc's doc comment).
886    #[cfg(windows)]
887    {
888        use std::io::Write as _;
889        let _ = writer.write_all(b"\x1b[1;1R");
890        let _ = writer.flush();
891    }
892
893    let (tx, rx) = mpsc::channel::<LineEvent>(1024);
894    let tx_reader = tx.clone();
895    let (idle_tx, idle_rx) = oneshot::channel::<()>();
896    let pty_idle_timeout = effective_idle_timeout(args);
897    tokio::task::spawn_blocking(move || {
898        pty_reader_loop(reader, tx_reader, idle_tx, pty_idle_timeout, child_pid);
899    });
900    drop(tx);
901
902    let publisher_handle = spawn_publisher_loop(args, mps.cloned(), buffered.clone(), rx);
903
904    // Move pair AND writer into the wait task — both must outlive
905    // child.wait() to satisfy the ConPTY lifetime contract on Windows.
906    let mut wait_task = tokio::task::spawn_blocking(move || -> Result<i32> {
907        let mut child = child;
908        let status = child.wait().context("PTY child wait")?;
909        let code = status.exit_code() as i32;
910        tracing::info!(target: "bashwrap", exit_code = code, "PTY child exited");
911        drop(writer);
912        drop(pair);
913        Ok(code)
914    });
915
916    // `idle_rx` resolves for TWO distinct reasons, and they must not be
917    // conflated (reagent P1, PR #2156): either `pty_reader_loop` really
918    // did send the idle-timeout signal (`Ok(())`), OR its `idle_tx` was
919    // simply DROPPED WITHOUT SENDING because the reader hit a normal EOF
920    // and returned — which is exactly what happens on ordinary, fast,
921    // successful command completion. A oneshot receiver's `.await`
922    // resolves (with `Err`) in that drop case too, and `wait_task`
923    // finishing is an independent race on a separate spawn_blocking
924    // thread — under scheduling variance (or blocking-pool contention from
925    // concurrent bashwrap invocations, common per this PR's own retro doc)
926    // the reader's drop can resolve first even for a command that ran to
927    // completion normally. Treating ANY `idle_rx` resolution as "idle
928    // timeout fired" would misclassify and kill perfectly successful fast
929    // commands. Only `Ok(())` is a real signal; `Err` just means "not an
930    // idle timeout, keep waiting on wait_task directly."
931    let mut idle_killed = false;
932    let exit_code = tokio::select! {
933        res = &mut wait_task => {
934            res.context("PTY wait task join")??
935        }
936        idle_signal = idle_rx => {
937            if idle_signal.is_err() {
938                // idle_tx dropped without sending — not a real timeout.
939                // idle_rx is now consumed either way, so just await the
940                // real completion directly instead of re-entering select.
941                wait_task.await.context("PTY wait task join")??
942            } else {
943                idle_killed = true;
944                tracing::warn!(
945                    target: "bashwrap",
946                    tool_id = %args.tool_id,
947                    idle_secs = idle_kill_timeout().as_secs(),
948                    "child produced no PTY output for the idle timeout — likely \
949                     blocked waiting for interactive input (e.g. a pager); killing",
950                );
951                // Tree-kill FIRST, `killer.kill()` second — order matters.
952                // `taskkill /T` walks descendants by their recorded parent PID,
953                // which only works while the root (bash) is still enumerable;
954                // killing bash first (via killer.kill()) and THEN tree-killing
955                // races taskkill against an already-dead root and can leave
956                // grandchildren behind (verified empirically: an earlier version
957                // of this fix that called killer.kill() first left 1 of 2
958                // backgrounded test children alive — the test below is what
959                // caught it). killer.kill() still runs afterward as a cheap,
960                // harmless belt-and-suspenders in case kill_process_tree itself
961                // didn't fully land (e.g. taskkill unavailable).
962                if let Some(pid) = child_pid {
963                    // spawn_blocking: kill_process_tree shells out synchronously
964                    // (std::process::Command::output()) — running it inline here
965                    // would block this tokio worker thread for the taskkill
966                    // round-trip. Bounded (reagent P1, PR #2156): `taskkill /T`
967                    // itself can hang (a documented Windows failure mode —
968                    // unresponsive process enumeration) — without this timeout,
969                    // an unresponsive taskkill reintroduces the exact unbounded
970                    // hang this whole fix exists to eliminate.
971                    let _ = tokio::time::timeout(
972                        Duration::from_secs(5),
973                        tokio::task::spawn_blocking(move || kill_process_tree(pid)),
974                    )
975                    .await;
976                }
977                let _ = killer.kill();
978                // Bounded grace period for the kill to actually land and for
979                // the wait task to finish (which drops writer/pair, releasing
980                // the PTY). If it still doesn't, abandon the wait rather than
981                // block forever — main()'s process::exit() tears down every
982                // thread in this process regardless, once run() returns.
983                match tokio::time::timeout(Duration::from_secs(5), &mut wait_task).await {
984                    Ok(Ok(Ok(code))) => code,
985                    _ => 124, // matches the conventional `timeout` command's exit code
986                }
987            }
988        }
989    };
990
991    // `buffered` (read by the caller for the model blob) is populated
992    // only by the publisher loop, so drain it BEFORE appending the
993    // idle-kill diagnostic (reagent P2, PR #2156) — otherwise genuine
994    // pre-kill output still queued in the channel could flush into
995    // `buffered` after the diagnostic note, interleaving it ahead of
996    // trailing real output instead of strictly after it. Bounded for the
997    // same reason as the wait task above: if a surviving grandchild still
998    // holds the PTY slave open after the kill, the reader thread's
999    // blocking read may never see EOF.
1000    if tokio::time::timeout(Duration::from_secs(5), publisher_handle)
1001        .await
1002        .is_err()
1003    {
1004        tracing::warn!(target: "bashwrap", tool_id = %args.tool_id, "publisher drain timed out — proceeding without it");
1005    }
1006
1007    if idle_killed {
1008        buffered.lock().await.extend_from_slice(
1009            b"\n[bashwrap] command produced no output for the idle timeout and was \
1010terminated automatically (likely blocked on a pager or other interactive \
1011prompt this wrapper can never answer, e.g. `git diff`/`log`/`show` auto- \
1012paging output that doesn't fit one screen). Try `git --no-pager <cmd>` or \
1013`| cat` on future invocations.\n",
1014        );
1015    }
1016
1017    Ok(exit_code)
1018}
1019
1020/// Pipe-backed run path. Safety net for environments where PTY
1021/// allocation fails (CI, sandboxes). Same byte semantics as the old
1022/// pipe-only wrapper.
1023pub(crate) async fn run_via_pipes(
1024    args: &Args,
1025    command: &str,
1026    mps: Option<&WpsClient>,
1027    buffered: Arc<Mutex<Vec<u8>>>,
1028    bash: &std::path::Path,
1029) -> Result<i32> {
1030    // Same cwd-persistence rationale as run_via_pty — see `cwd_state.rs`.
1031    let cwd_state = CwdState::for_call(args.agent.as_deref(), args.agent_unknown);
1032    let mut cmd = Command::new(bash);
1033    cmd.arg("-c")
1034        .arg(append_cwd_capture(command))
1035        .stdin(Stdio::null())
1036        .stdout(Stdio::piped())
1037        .stderr(Stdio::piped())
1038        .kill_on_drop(true)
1039        // Defense-in-depth, matching run_via_pty: stdout is a plain pipe
1040        // here (isatty == false), so git shouldn't auto-page in this path
1041        // at all — but set it anyway in case some tool pages on a
1042        // different heuristic. See
1043        // docs/retro/RETRO_BASHWRAP_PAGER_HANG_LEAK_2026_07_14.md.
1044        .env("GIT_PAGER", "cat")
1045        .env("PAGER", "cat");
1046    if let Some(dir) = &cwd_state.start_dir {
1047        cmd.current_dir(dir);
1048    }
1049    if let Some(state_path) = &cwd_state.path {
1050        cmd.env(CWD_STATE_ENV, state_path);
1051    }
1052    // Windows only: bash.exe is a console-subsystem binary, so spawning it
1053    // without CREATE_NO_WINDOW pops a new visible (and orphaned-looking)
1054    // console window for every fallback exec — this path only runs when
1055    // PTY allocation fails, which is why it slipped past
1056    // SPEC_ELIMINATE_BASHWRAP_CONSOLE_WINDOWS_2026_06_20's audit (that pass
1057    // covered bashwrap's own process subsystem and shell_node.rs, not this
1058    // rarely-exercised inner spawn). Same fix as shell_node.rs.
1059    #[cfg(windows)]
1060    {
1061        // `cmd` is `tokio::process::Command`; `NoWindow` covers both it and
1062        // `std::process::Command`, so no `CommandExt` import is needed.
1063        cmd.no_window();
1064    }
1065    let mut child = cmd
1066        .spawn()
1067        .with_context(|| format!("pipe spawn of bash at {}", bash.display()))?;
1068    // Captured before anything else can consume/reap the child — see the
1069    // idle-kill branch below for why this matters (reagent P1, PR #2156).
1070    let child_pid = child.id();
1071
1072    let stdout = child.stdout.take().ok_or_else(|| anyhow!("no stdout"))?;
1073    let stderr = child.stderr.take().ok_or_else(|| anyhow!("no stderr"))?;
1074
1075    // Idle-kill safety net (reagent P1, PR #2156): this path has no PTY, so
1076    // it can't hit the pager-hang mechanism specifically (isatty(stdout) ==
1077    // false here, the whole reason git wouldn't auto-page) — but nothing
1078    // else bounded child.wait() either, so ANY other hang cause still
1079    // leaked the wrapper forever, reproducing the root bug this PR exists
1080    // to fix. Mirrors run_via_pty's idle (not total-runtime) timeout: a
1081    // shared last-activity clock updated by both stdout/stderr readers on
1082    // every byte read, watched by a lightweight polling task.
1083    let last_activity = Arc::new(std::sync::Mutex::new(std::time::Instant::now()));
1084
1085    let (tx, rx) = mpsc::channel::<LineEvent>(1024);
1086    let stdout_reader = tokio::spawn(stream_reader(stdout, ToolChunkKind::Stdout, tx.clone(), last_activity.clone()));
1087    let stderr_reader = tokio::spawn(stream_reader(stderr, ToolChunkKind::Stderr, tx.clone(), last_activity.clone()));
1088    drop(tx);
1089
1090    let publisher_handle = spawn_publisher_loop(args, mps.cloned(), buffered.clone(), rx);
1091
1092    let (idle_tx, idle_rx) = oneshot::channel::<()>();
1093    let idle_timeout = effective_idle_timeout(args);
1094    // Silent is not stuck: a busy process tree restarts the clock (idle_gate.rs).
1095    let idle_watcher = tokio::spawn(crate::idle_gate::watch(last_activity.clone(), child_pid, idle_timeout, idle_tx));
1096
1097    // Same Ok/Err distinction as run_via_pty's select (reagent P1 follow-up):
1098    // idle_rx resolving with Err just means pty_reader_loop-equivalent
1099    // cleanup dropped it without signaling (not applicable on this path
1100    // directly, but kept for structural symmetry and defensiveness) — not
1101    // a real signal either way.
1102    let mut idle_killed = false;
1103    let exit_code: i32 = tokio::select! {
1104        res = child.wait() => {
1105            idle_watcher.abort();
1106            res.context("waiting for bash child")?.code().unwrap_or(-1)
1107        }
1108        idle_signal = idle_rx => {
1109            if idle_signal.is_err() {
1110                child.wait().await.context("waiting for bash child")?.code().unwrap_or(-1)
1111            } else {
1112                idle_killed = true;
1113                tracing::warn!(
1114                    target: "bashwrap",
1115                    tool_id = %args.tool_id,
1116                    idle_secs = idle_kill_timeout().as_secs(),
1117                    "child produced no output for the idle timeout (pipe path) — killing",
1118                );
1119                // Same tree-kill-first ordering and reasoning as run_via_pty
1120                // (reagent P1, PR #2156): child.start_kill() alone only
1121                // terminates the direct bash process, not descendants it
1122                // forked (a backgrounded `&` child, or a pipeline segment) —
1123                // those would otherwise survive, still attached to the
1124                // stdout/stderr pipes, leaving the reader tasks waiting for
1125                // an EOF that never comes. Bounded: taskkill /T can itself
1126                // hang (a documented Windows failure mode).
1127                if let Some(pid) = child_pid {
1128                    let _ = tokio::time::timeout(
1129                        Duration::from_secs(5),
1130                        tokio::task::spawn_blocking(move || kill_process_tree(pid)),
1131                    )
1132                    .await;
1133                }
1134                let _ = child.start_kill();
1135                match tokio::time::timeout(Duration::from_secs(5), child.wait()).await {
1136                    Ok(Ok(status)) => status.code().unwrap_or(-1),
1137                    _ => 124, // matches the conventional `timeout` command's exit code
1138                }
1139            }
1140        }
1141    };
1142
1143    // Reader tasks: bound-JOIN, never `.abort()`. Empirically, aborting a
1144    // task that's inside `tokio::time::timeout(_, AsyncRead::read(..))` on
1145    // a just-killed child's Windows pipe leaves something in a state that
1146    // hangs this whole test/runtime's shutdown — reproduced in isolation
1147    // while building this fix (a bare `.read().await` with no per-call
1148    // timeout wrapper was fine to abort; adding the 50ms quiet-window
1149    // timeout wrapper, matching `stream_reader`'s real structure, is what
1150    // triggered it). A `JoinHandle` that's simply *dropped* without abort,
1151    // by contrast, does not cancel the task — it keeps running fully
1152    // detached and harmlessly finishes reading to EOF on its own once the
1153    // pipe closes, which is exactly what timing out on the join and
1154    // moving on (rather than aborting) achieves here.
1155    if tokio::time::timeout(
1156        Duration::from_secs(5),
1157        async { let _ = tokio::join!(stdout_reader, stderr_reader); },
1158    )
1159    .await
1160    .is_err()
1161    {
1162        tracing::warn!(target: "bashwrap", tool_id = %args.tool_id, "reader tasks did not finish within the grace period — leaving them to finish in the background rather than aborting (see run_via_pipes's comment)");
1163    }
1164
1165    // Bounded for the same reason as run_via_pty: proceed rather than block
1166    // forever if a hung descendant somehow keeps a pipe end open.
1167    if tokio::time::timeout(Duration::from_secs(5), publisher_handle)
1168        .await
1169        .is_err()
1170    {
1171        tracing::warn!(target: "bashwrap", tool_id = %args.tool_id, "publisher drain timed out — proceeding without it");
1172    }
1173
1174    if idle_killed {
1175        buffered.lock().await.extend_from_slice(
1176            b"\n[bashwrap] command produced no output for the idle timeout and was \
1177terminated automatically.\n",
1178        );
1179    }
1180
1181    Ok(exit_code)
1182}
1183
1184/// PTY reader loop: drains bytes from the master, strips DSR / ANSI
1185/// control sequences, and forwards line-split chunks to the publisher.
1186///
1187/// Uses a thread-bridge + `recv_timeout` to add a quiet-window flush
1188/// identical to `stream_reader`'s `tokio::time::timeout` approach, but
1189/// for the blocking sync I/O that the PTY master reader requires.
1190///
1191/// **P1a — `collapse_cr`:** called on the `pending` accumulator after
1192/// each PTY read (after `strip_ansi`), collapsing mid-buffer lone-`\r`
1193/// overwrites (trailing-`\r` convention, e.g. `"frame\r"`) and embedded
1194/// multi-frame chunks (e.g. `printf 'f1\rf2\rfinal\n'`). Previously the
1195/// PTY path passed `\r` bytes intact and relied on `spawn_publisher_loop`'s
1196/// `pending_cr_line` slot; that slot only fires per-LineEvent so embedded
1197/// `\r`s in a single write survived uncollapsed.
1198///
1199/// **P1b — leading-`\r` spinner collapse:** throttled spinners (npm,
1200/// cargo, ora, tqdm at ~80-100 ms/frame, above the 50 ms quiet window)
1201/// arrive as separate reads. When the quiet window expires and `pending`
1202/// starts with `\r`, the frame is stashed in a `pending_cr_override` slot
1203/// rather than flushed. The next read prepends it so `collapse_cr`
1204/// overwrites it with the new frame. The slot is flushed when a
1205/// `\n`-terminated line arrives or at EOF.
1206///
1207/// **P2a — `FLUSH_BYTES` guard:** flushed unconditionally when accumulated
1208/// size exceeds `FLUSH_BYTES`, preventing unbounded accumulation from a
1209/// trailing-`\r` spinner that never emits `\n`.
1210fn pty_reader_loop(
1211    reader: Box<dyn std::io::Read + Send>,
1212    tx: mpsc::Sender<LineEvent>,
1213    idle_tx: oneshot::Sender<()>,
1214    idle_timeout: Duration,
1215    root_pid: Option<u32>,
1216) {
1217    use std::sync::mpsc as std_mpsc;
1218    // PTY collapses stdout + stderr onto one stream — the slave's
1219    // terminal device is a single FD shared by both. Chunks are
1220    // labelled "stdout" because there is no way to recover the
1221    // original FD distinction from the master read. The pipe path
1222    // (`run_via_pipes`) preserves the split.
1223    let kind = ToolChunkKind::Stdout;
1224
1225    // Offload the blocking read to a dedicated thread so the main
1226    // loop can use recv_timeout for the quiet-window flush. Bound the
1227    // channel (64 slots ≈ 512 KiB headroom) so a flooding child can't
1228    // grow it unbounded — the SyncSender blocks when full, propagating
1229    // backpressure to the PTY buffer and ultimately to the child process.
1230    let (data_tx, data_rx) = std_mpsc::sync_channel::<Option<Vec<u8>>>(64);
1231    std::thread::spawn(move || {
1232        use std::io::Read;
1233        let mut reader = reader;
1234        let mut buf = [0u8; 8192];
1235        loop {
1236            match reader.read(&mut buf) {
1237                Ok(0) => {
1238                    let _ = data_tx.send(None); // EOF sentinel
1239                    return;
1240                }
1241                Ok(n) => {
1242                    if data_tx.send(Some(buf[..n].to_vec())).is_err() {
1243                        return; // consumer gone
1244                    }
1245                }
1246                Err(e) => {
1247                    tracing::warn!(target: "bashwrap", error = %e, "PTY read error");
1248                    return;
1249                }
1250            }
1251        }
1252    });
1253
1254    let mut pending: Vec<u8> = Vec::with_capacity(8192);
1255    // P1b: CR override slot — mirrors the same slot in stream_reader.
1256    // When the quiet window expires and `pending` starts with `\r`, hold
1257    // it here so throttled spinner frames collapse before becoming separate
1258    // LineEvents.
1259    let mut pending_cr_override: Option<Vec<u8>> = None;
1260    // A1: speculative one-tick hold for a pending line that has NO leading
1261    // OR trailing `\r` yet (the overwhelmingly common real pattern: print a
1262    // static label once, then every subsequent update is `\r`-prefixed).
1263    // Distinct from `pending_cr_override` above — that slot only ever holds
1264    // content that already starts with `\r`. See
1265    // docs/specs/SPEC_TOOL_LOG_UNIVERSAL_ANIMATION_COLLAPSE_2026_07_27.md §A1.
1266    let mut deferred_pending: Option<Vec<u8>> = None;
1267    // A2: tracks whether this tool call's output has scrolled past its
1268    // first visual line yet — see `normalize_csi_overwrites`'s doc comment
1269    // for why CUP-to-home (`\x1b[H`) is only a `\r`-equivalent while this
1270    // is still true.
1271    let mut still_on_first_line = true;
1272    // A2: tracks whether the cursor is currently at column 0, across PTY
1273    // reads — see `normalize_csi_overwrites`'s doc comment for why a
1274    // standalone EL is only safe to treat as `\r` while this is true, and
1275    // why it must persist across calls rather than reset per-chunk.
1276    let mut at_col0 = true;
1277    // Idle-kill tracking: `last_activity` resets on every byte read from
1278    // the PTY (regardless of whether it becomes a published LineEvent —
1279    // even control-sequence-only output means the child is still doing
1280    // something). `idle_tx` fires exactly once, on the first quiet-window
1281    // timeout after `idle_kill_timeout()` has elapsed with zero activity.
1282    // See the constant's doc comment for why this is idle-based rather
1283    // than a total-runtime cap. `idle_timeout` is passed in by the caller
1284    // (`effective_idle_timeout`) rather than read here, so a declared-
1285    // background call's exemption applies without this loop needing its
1286    // own copy of `Args`.
1287    let mut last_activity = std::time::Instant::now();
1288    let mut idle_tx = Some(idle_tx);
1289    // Silent is not stuck: a busy process tree restarts the clock (idle_gate.rs).
1290    let mut gate = crate::idle_gate::IdleGate::new(root_pid, idle_timeout);
1291    loop {
1292        match data_rx.recv_timeout(FLUSH_QUIET_WINDOW) {
1293            Ok(Some(mut chunk)) => {
1294                last_activity = std::time::Instant::now();
1295                gate.reset();
1296                let raw_n = chunk.len();
1297                strip_dsr(&mut chunk);
1298                // Phase γ (partial): convert the CHA(col-1)/EL cursor-
1299                // repositioning idioms into `\r` bytes BEFORE strip_ansi
1300                // deletes them outright, so collapse_cr (below) can treat
1301                // CSI-based progress-bar redraws as overwrites the same way
1302                // it already does for bare `\r`. See
1303                // docs/specs/SPEC_TOOL_LOG_UNIVERSAL_ANIMATION_COLLAPSE_2026_07_27.md §A2.
1304                normalize_csi_overwrites(&mut chunk, &mut still_on_first_line, &mut at_col0);
1305                // Phase β: strip remaining ANSI control sequences so
1306                // the plain-text chunk list doesn't render them as
1307                // garbled literal characters. Bash emits terminal-
1308                // init bytes (`\x1b[m`, `\x1b]0;<title>\x07`,
1309                // `\x1b[?25h`) on every `-c` invocation through a
1310                // PTY; without this strip every chunk list starts
1311                // with garbage.
1312                strip_ansi(&mut chunk);
1313                tracing::debug!(target: "bashwrap", raw_bytes = raw_n, post_strip = chunk.len(), "PTY read");
1314                if chunk.is_empty() {
1315                    continue;
1316                }
1317                // P1b: prepend any held CR override so collapse_cr can
1318                // overwrite it with the new frame content.
1319                if let Some(held) = pending_cr_override.take() {
1320                    let mut combined = held;
1321                    combined.extend_from_slice(&chunk);
1322                    pending.splice(0..0, combined);
1323                } else if let Some(deferred) = deferred_pending.take() {
1324                    // A1: the new chunk resolves last tick's speculative
1325                    // hold. A leading `\r` means it's the overwrite we were
1326                    // hoping for — merge and let collapse_cr do the rest,
1327                    // same as the pending_cr_override case above. Anything
1328                    // else means the deferred line was genuinely final and
1329                    // unrelated to this new content — flush it as its own
1330                    // line first so the two are never wrongly concatenated.
1331                    if chunk.first() == Some(&b'\r') {
1332                        let mut combined = deferred;
1333                        combined.extend_from_slice(&chunk);
1334                        pending.splice(0..0, combined);
1335                    } else {
1336                        if tx.blocking_send(LineEvent { kind, bytes: deferred }).is_err() {
1337                            return;
1338                        }
1339                        pending.extend_from_slice(&chunk);
1340                    }
1341                } else {
1342                    pending.extend_from_slice(&chunk);
1343                }
1344                // P1a: collapse lone \r in the accumulated pending buffer,
1345                // normalising mid-buffer overwrites and embedded multi-frame
1346                // chunks identically to the pipe path.
1347                collapse_cr(&mut pending);
1348                // Any held CR override was already consumed and prepended into
1349                // `pending` above, so it never survives to this drain loop —
1350                // mirrors the pipe path in `stream_reader` which omits a
1351                // take() here for the same reason.
1352                while let Some(nl_pos) = pending.iter().position(|&b| b == b'\n') {
1353                    let line: Vec<u8> = pending.drain(..=nl_pos).collect();
1354                    if tx.blocking_send(LineEvent { kind, bytes: line }).is_err() {
1355                        return;
1356                    }
1357                }
1358                // P2a: size threshold — flush unconditionally to keep memory
1359                // bounded. Prevents unbounded accumulation from a trailing-\r
1360                // spinner that never emits \n.
1361                if pending.len() >= FLUSH_BYTES {
1362                    if tx.blocking_send(LineEvent {
1363                        kind,
1364                        bytes: std::mem::take(&mut pending),
1365                    }).is_err() {
1366                        return;
1367                    }
1368                }
1369            }
1370            Ok(None) => {
1371                // EOF: flush any held CR override or A1 deferred line first,
1372                // then drain remainder, stripping a dangling lone \r.
1373                if let Some(mut held) = pending_cr_override.take() {
1374                    if held.last() == Some(&b'\r') {
1375                        held.pop();
1376                    }
1377                    if !held.is_empty() {
1378                        let _ = tx.blocking_send(LineEvent { kind, bytes: held });
1379                    }
1380                }
1381                if let Some(deferred) = deferred_pending.take() {
1382                    let _ = tx.blocking_send(LineEvent { kind, bytes: deferred });
1383                }
1384                if !pending.is_empty() {
1385                    if pending.last() == Some(&b'\r') {
1386                        pending.pop();
1387                    }
1388                    if !pending.is_empty() {
1389                        let _ = tx.blocking_send(LineEvent {
1390                            kind,
1391                            bytes: std::mem::take(&mut pending),
1392                        });
1393                    }
1394                }
1395                return;
1396            }
1397            Err(std_mpsc::RecvTimeoutError::Timeout) => {
1398                if idle_tx.is_some() && last_activity.elapsed() >= idle_timeout {
1399                    // Fires once (idle_tx.take() leaves None behind), even
1400                    // though this branch keeps running every quiet-window
1401                    // tick after that — the async side kills the child on
1402                    // receipt, which will eventually produce real EOF/error
1403                    // here and end the loop normally.
1404                    if gate.stuck(&mut last_activity) {
1405                        if let Some(sender) = idle_tx.take() {
1406                            let _ = sender.send(());
1407                        }
1408                    }
1409                }
1410                // P1b/A1: quiet-window expiry.
1411                //
1412                // If a line was ALREADY speculatively deferred last tick
1413                // (A1) and nothing new has arrived since — deferred_pending
1414                // being Some implies pending is empty, since any new data
1415                // would have resolved it in the Ok(Some) branch above — give
1416                // up waiting for a `\r`-prefixed overwrite and flush it now.
1417                //
1418                // If `pending` starts with `\r`, it is a leading-\r spinner
1419                // frame. Stash it in the CR override slot so the next read
1420                // prepends it and collapse_cr overwrites it with the new frame.
1421                //
1422                // If `pending` ends with `\r` (but not starts), hold it —
1423                // a following `\n` can form a complete CRLF.
1424                //
1425                // Otherwise (non-`\r` partial output, e.g. `printf
1426                // 'Building...'`): this is the FIRST quiet window with this
1427                // content, so defer it one tick (A1) rather than flushing
1428                // immediately — in case the very next read starts with `\r`
1429                // and this was actually the first frame of an overwrite
1430                // sequence (the overwhelmingly common real pattern: print a
1431                // static label once, then every subsequent update is
1432                // `\r`-prefixed). See
1433                // docs/specs/SPEC_TOOL_LOG_UNIVERSAL_ANIMATION_COLLAPSE_2026_07_27.md §A1.
1434                if let Some(deferred) = deferred_pending.take() {
1435                    if tx.blocking_send(LineEvent { kind, bytes: deferred }).is_err() {
1436                        return;
1437                    }
1438                }
1439                if !pending.is_empty() {
1440                    if pending.first() == Some(&b'\r') {
1441                        // Leading-\r spinner frame: stash in the override slot so
1442                        // the next Ok(Some) prepends it and collapse_cr can overwrite
1443                        // it with the incoming frame.
1444                        //
1445                        // Note: pending_cr_override is always None here. The override
1446                        // is set only by take(&mut pending), which empties pending.
1447                        // The only way to reach this branch with non-empty pending is
1448                        // after an Ok(Some) that already consumed and cleared the
1449                        // override. No flush-prior is needed or reachable.
1450                        pending_cr_override = Some(std::mem::take(&mut pending));
1451                    } else if pending.last() != Some(&b'\r') {
1452                        // First quiet window with this non-\r content: defer
1453                        // instead of flushing (A1). deferred_pending is
1454                        // always None here for the same reason as above.
1455                        deferred_pending = Some(std::mem::take(&mut pending));
1456                    }
1457                    // else: trailing-\r hold — do nothing, next read resolves CRLF.
1458                }
1459            }
1460            Err(std_mpsc::RecvTimeoutError::Disconnected) => {
1461                // Reader thread died without EOF — flush CR override / A1
1462                // deferred line, then drain.
1463                if let Some(mut held) = pending_cr_override.take() {
1464                    if held.last() == Some(&b'\r') {
1465                        held.pop();
1466                    }
1467                    if !held.is_empty() {
1468                        let _ = tx.blocking_send(LineEvent { kind, bytes: held });
1469                    }
1470                }
1471                if let Some(deferred) = deferred_pending.take() {
1472                    let _ = tx.blocking_send(LineEvent { kind, bytes: deferred });
1473                }
1474                if !pending.is_empty() {
1475                    if pending.last() == Some(&b'\r') {
1476                        pending.pop();
1477                    }
1478                    if !pending.is_empty() {
1479                        let _ = tx.blocking_send(LineEvent {
1480                            kind,
1481                            bytes: std::mem::take(&mut pending),
1482                        });
1483                    }
1484                }
1485                return;
1486            }
1487        }
1488    }
1489}
1490
1491/// Normalize CSI cursor-repositioning idioms that map cleanly onto the
1492/// existing `\r`-based overwrite model, converting them to a literal `\r`
1493/// byte so `collapse_cr` (which already understands `\r`) collapses them
1494/// too, with no new cases needed there. Runs on the raw `chunk` BEFORE
1495/// `strip_ansi`, which otherwise deletes CSI sequences unconditionally with
1496/// no overwrite-awareness — the "Phase γ" gap `strip_ansi`'s own doc
1497/// comment flags ("Cursor positioning escapes within the same line").
1498/// See docs/specs/SPEC_TOOL_LOG_UNIVERSAL_ANIMATION_COLLAPSE_2026_07_27.md §A2.
1499///
1500/// `still_on_first_line` and `at_col0` are both caller-owned state that
1501/// persists across calls for the lifetime of one reader loop — this
1502/// function is invoked once per PTY read, and a chunk boundary is not a
1503/// terminal state boundary: a read ending mid-line (no trailing `\n`/`\r`)
1504/// must carry "cursor is NOT at column 0" into the next call, otherwise a
1505/// standalone EL split across two reads (`"prefix"` in one chunk,
1506/// `"\x1b[2Ksuffix"` in the next) would see a freshly-reset `at_col0 ==
1507/// true` and wrongly convert that EL to `\r`, reproducing the exact
1508/// mid-line truncation bug this function exists to prevent, just moved
1509/// from a mid-chunk split to a cross-chunk-read split (reagent P1, PR
1510/// #2330, caught after the first, chunk-internal-only version of this fix).
1511///
1512/// `still_on_first_line`: `true` until the first `\n` is
1513/// seen in this tool call's output, `false` forever after. Needed because
1514/// **Windows ConPTY re-serializes a literal `\r` as CUP-to-home
1515/// (`\x1b[H`)** rather than passing it through unchanged — verified
1516/// empirically via `a1_e2e_static_label_then_delayed_cr_overwrite_collapses_to_one_line`
1517/// capturing the raw PTY bytes: a child process writing `\rdone` produces
1518/// `\x1b[?25l\x1b[Hdone...\x1b[?25h` on the wire, not a literal `\r`. CUP
1519/// "home" (row 1, col 1) is unambiguous evidence of an overwrite ONLY when
1520/// nothing has scrolled the visual line off row 1 yet; once real multi-line
1521/// output exists, `\x1b[H` genuinely means "go back to the first of several
1522/// lines" (a multi-line redraw, spec §A3, deliberately out of scope) and
1523/// must NOT be treated as "restart the current line".
1524///
1525/// Cases handled, chosen because each means exactly "move to the start of
1526/// the (only) line so far" without needing true per-column tracking:
1527///   - CUP to row 1 col 1 (`\x1b[H`, `\x1b[1H`, `\x1b[1;1H`, and the
1528///     omitted-field variants of each), gated on `still_on_first_line` per
1529///     above — the ConPTY-observed idiom.
1530///   - CHA to column 1 (`\x1b[1G` / `\x1b[G`, "cursor to column 1") is
1531///     literally "move to start of line" — identical to `\r`. Unix PTYs
1532///     (and any tool not going through ConPTY's re-serialization) may use
1533///     this form directly.
1534///   - EL (`\x1b[2K` erase whole line, `\x1b[K`/`\x1b[0K` erase to end of
1535///     line) is treated as "reset to start of line" too, but ONLY when the
1536///     cursor is already known to be at column 0 (`*at_col0`) — i.e. the
1537///     dominant real-world `\r` + EL idiom (`\r\x1b[2K<text>`), where it's
1538///     genuinely redundant with the `\r` already just emitted. A
1539///     STANDALONE EL, mid-line (cursor NOT at column 0 — e.g.
1540///     `prefix\x1b[Ksuffix`), is a real, different case: EL only erases
1541///     from the cursor onward and never moves it, so collapsing it to `\r`
1542///     there would make `collapse_cr` truncate `prefix` even though EL
1543///     never asked for that. That standalone case is left unconverted
1544///     (falls through to the "unrecognized" branch below, so `strip_ansi`
1545///     removes the escape byte-for-byte without touching `prefix`) — a
1546///     bug reagent caught on this exact line (PR #2330): the prior,
1547///     unconditional version silently discarded `prefix` in
1548///     `prefix\x1b[Ksuffix\n`.
1549///
1550/// CUB (`\x1b[<n>D`, "cursor back n columns") is intentionally NOT handled
1551/// here — a faithful implementation needs true per-column tracking (a raw
1552/// byte position isn't a faithful proxy once `n` varies per frame), which
1553/// `collapse_cr`'s line-offset model doesn't have. Left as a documented
1554/// follow-up alongside CUU/multi-line redraw (spec §A3) rather than
1555/// guessed at with an approximation that could truncate the wrong amount.
1556fn normalize_csi_overwrites(chunk: &mut Vec<u8>, still_on_first_line: &mut bool, at_col0: &mut bool) {
1557    let mut out: Vec<u8> = Vec::with_capacity(chunk.len());
1558    let mut i = 0;
1559    while i < chunk.len() {
1560        let b = chunk[i];
1561        if b == b'\n' {
1562            *still_on_first_line = false;
1563        }
1564        if b == 0x1b && i + 1 < chunk.len() && chunk[i + 1] == b'[' {
1565            let mut j = i + 2;
1566            while j < chunk.len() && (0x30..=0x3F).contains(&chunk[j]) {
1567                j += 1;
1568            }
1569            if j < chunk.len() && (0x40..=0x7E).contains(&chunk[j]) {
1570                let params = &chunk[i + 2..j];
1571                let final_byte = chunk[j];
1572                let is_cha_col1 = final_byte == b'G' && (params.is_empty() || params == b"1");
1573                let is_el = final_byte == b'K' && *at_col0;
1574                let is_cup_home = *still_on_first_line
1575                    && final_byte == b'H'
1576                    && is_cup_row1_col1(params);
1577                if is_cha_col1 || is_el || is_cup_home {
1578                    out.push(b'\r');
1579                    *at_col0 = true;
1580                    i = j + 1;
1581                    continue;
1582                }
1583                // Unrecognized/CUB/mid-line-EL/out-of-scope CSI sequence:
1584                // fall through untouched, byte by byte, so strip_ansi
1585                // (which runs next) still recognizes and removes it as a
1586                // whole — this function only ever substitutes the matched
1587                // idioms above. Each of those bytes then runs through the
1588                // ordinary `*at_col0 = b == b'\n' || b == b'\r'` update
1589                // below like any other byte, which forces `at_col0` to
1590                // `false` (none of an escape sequence's bytes are `\n`/
1591                // `\r`) — conservative and safe (errs toward NOT
1592                // collapsing a subsequent EL), not "left as-is".
1593            }
1594        }
1595        out.push(b);
1596        *at_col0 = b == b'\n' || b == b'\r';
1597        i += 1;
1598    }
1599    *chunk = out;
1600}
1601
1602/// Does a CUP (`\x1b[<params>H`) params string address row 1, column 1
1603/// ("home")? Each field defaults to 1 when empty, per ECMA-48 — so `""`,
1604/// `"1"`, `"1;1"`, `";1"`, `"1;"`, and `";"` are all row-1-col-1.
1605fn is_cup_row1_col1(params: &[u8]) -> bool {
1606    let field_is_one_or_empty = |f: &[u8]| f.is_empty() || f == b"1";
1607    match params.iter().position(|&b| b == b';') {
1608        None => field_is_one_or_empty(params),
1609        Some(idx) => {
1610            field_is_one_or_empty(&params[..idx]) && field_is_one_or_empty(&params[idx + 1..])
1611        }
1612    }
1613}
1614
1615/// Scan `chunk` for DSR `\x1b[6n` sequences and remove them in place
1616/// so they don't leak into the model-visible blob or overlay log.
1617fn strip_dsr(chunk: &mut Vec<u8>) {
1618    const DSR: &[u8] = b"\x1b[6n";
1619    let mut i = 0;
1620    while i + DSR.len() <= chunk.len() {
1621        if &chunk[i..i + DSR.len()] == DSR {
1622            chunk.drain(i..i + DSR.len());
1623        } else {
1624            i += 1;
1625        }
1626    }
1627}
1628
1629/// Phase β (lite): strip ANSI control sequences from a PTY chunk so
1630/// the overlay's plain-text ChunkList doesn't render them as garbled
1631/// literal characters.
1632///
1633/// Three families to handle (everything bash emits during init and
1634/// most programs emit during normal output):
1635///
1636/// 1. **CSI sequences** — `ESC [ <params> <final>` where params are
1637///    `0x30..=0x3F` (digits, `;`, `?`, etc.) and final is
1638///    `0x40..=0x7E` (letters + punctuation). Covers `\x1b[m` (reset),
1639///    `\x1b[?25h/l` (cursor visibility), color codes, cursor moves.
1640///
1641/// 2. **OSC sequences** — `ESC ] <text> BEL` (or `ESC ] <text> ESC \`).
1642///    Covers `\x1b]0;<title>\x07` (set window title — emitted by
1643///    Git Bash on every command).
1644///
1645/// 3. **Lone control chars** — `\r` (carriage return without
1646///    newline), `\x07` (bell), `\x08` (backspace). CRLF → LF for
1647///    the chunk list. Lone `\r` passes through so `collapse_cr` can
1648///    operate on the `pending` buffer across PTY reads (see below).
1649///
1650/// Things we DON'T handle yet (Phase γ territory):
1651/// - Alt-screen apps (`\x1b[?1049h`) — left in the stream.
1652/// - Cursor positioning escapes within the same line.
1653/// - OSC 633 (shell integration markers).
1654fn strip_ansi(chunk: &mut Vec<u8>) {
1655    let mut out: Vec<u8> = Vec::with_capacity(chunk.len());
1656    let mut i = 0;
1657    while i < chunk.len() {
1658        let b = chunk[i];
1659        if b == 0x1b && i + 1 < chunk.len() {
1660            match chunk[i + 1] {
1661                b'[' => {
1662                    // CSI: scan params (0x30..=0x3F) then final (0x40..=0x7E).
1663                    let mut j = i + 2;
1664                    while j < chunk.len() && (0x30..=0x3F).contains(&chunk[j]) {
1665                        j += 1;
1666                    }
1667                    // Intermediate bytes (rare for our case).
1668                    while j < chunk.len() && (0x20..=0x2F).contains(&chunk[j]) {
1669                        j += 1;
1670                    }
1671                    if j < chunk.len() && (0x40..=0x7E).contains(&chunk[j]) {
1672                        // Consume the whole CSI sequence.
1673                        i = j + 1;
1674                        continue;
1675                    }
1676                    // Malformed — keep ESC, skip past.
1677                    out.push(b);
1678                    i += 1;
1679                    continue;
1680                }
1681                b']' => {
1682                    // OSC: scan until BEL (0x07) or ST (`ESC \`).
1683                    let mut j = i + 2;
1684                    while j < chunk.len() {
1685                        if chunk[j] == 0x07 {
1686                            i = j + 1;
1687                            break;
1688                        }
1689                        if chunk[j] == 0x1b && j + 1 < chunk.len() && chunk[j + 1] == b'\\' {
1690                            i = j + 2;
1691                            break;
1692                        }
1693                        j += 1;
1694                    }
1695                    if i <= j {
1696                        // Reached end of chunk without terminator —
1697                        // drop the rest as a partial OSC. (Next read
1698                        // will resume with the trailing bytes; if it
1699                        // doesn't start with the terminator we'll
1700                        // mis-render once, but that's better than
1701                        // emitting garbage.)
1702                        i = chunk.len();
1703                    }
1704                    continue;
1705                }
1706                _ => {
1707                    // ESC followed by some other byte (e.g. `ESC c` =
1708                    // reset). Consume both.
1709                    i += 2;
1710                    continue;
1711                }
1712            }
1713        }
1714        if b == 0x07 {
1715            // Bare BEL — drop.
1716            i += 1;
1717            continue;
1718        }
1719        if b == b'\r' && i + 1 < chunk.len() && chunk[i + 1] == b'\n' {
1720            // CRLF → LF: drop the \r, keep the \n on the next pass.
1721            i += 1;
1722            continue;
1723        }
1724        out.push(b);
1725        i += 1;
1726    }
1727    *chunk = out;
1728}
1729
1730/// Collapse lone carriage-returns in the `pending` byte buffer, simulating
1731/// terminal overwrite: each `\r` NOT followed by `\n` discards the current
1732/// visual line back to column 0.
1733///
1734/// **Why here and not in `strip_ansi`:** real spinner animations emit each
1735/// frame as a separate `write()` syscall, so the preceding frame content and
1736/// the overwriting `\r` arrive in different PTY reads. Running collapse on
1737/// the `pending` accumulator (which spans reads for the current visual line)
1738/// catches those cross-read overwrites.
1739///
1740/// **Leading `\r` is preserved — including through mid-buffer overwrites.**
1741/// When a lone `\r` appears at the very start of a visual line, it is emitted
1742/// as-is rather than discarded. When a subsequent lone `\r` overwrites a line
1743/// that *itself* started with `\r` (e.g. `"\rframe1\rframe2"`), the leading
1744/// `\r` is preserved in the result (`"\rframe2"`, not `"frame2"`). This lets
1745/// the caller's `pending_cr_override` slot chain-collapse throttled spinner
1746/// frames on successive reads: the collapsed result still starts with `\r`, so
1747/// the slot engages again on the next quiet-window expiry.
1748///
1749/// **Trailing `\r` is left in place.** A `\r` at the very end of `pending`
1750/// might be the first byte of a CRLF pair split across reads. Collapsing it
1751/// immediately would discard the line's content before the `\n` arrives,
1752/// causing silent data loss. The caller suppresses the eager partial-line
1753/// flush when `pending` ends with `\r` so the next read can disambiguate.
1754fn collapse_cr(pending: &mut Vec<u8>) {
1755    if !pending.contains(&b'\r') {
1756        return; // fast-path: no CR at all
1757    }
1758    let mut out: Vec<u8> = Vec::with_capacity(pending.len());
1759    let mut line_start = 0usize;
1760    let mut i = 0;
1761    while i < pending.len() {
1762        let b = pending[i];
1763        if b == b'\n' {
1764            out.push(b);
1765            line_start = out.len();
1766            i += 1;
1767        } else if b == b'\r' {
1768            if i + 1 < pending.len() {
1769                if pending[i + 1] == b'\n' {
1770                    // CRLF → LF (strip_ansi already handles this for
1771                    // within-chunk pairs, but CRLF can straddle reads).
1772                    out.push(b'\n');
1773                    line_start = out.len();
1774                    i += 2;
1775                } else if out.len() == line_start {
1776                    // Leading \r: nothing to overwrite on this line.
1777                    // Preserve it so the caller's pending_cr_override slot
1778                    // can recognise and hold leading-\r spinner frames
1779                    // ("\rframe", npm/ora/tqdm style).
1780                    out.push(b);
1781                    i += 1;
1782                } else {
1783                    // Lone \r mid-buffer: discard current line back to column 0.
1784                    // If the line opened with a leading \r (spinner convention),
1785                    // preserve that leading \r so the pending_cr_override slot in
1786                    // the reader can still recognise the result as a spinner frame
1787                    // after collapsing "\rframe1\rframe2" → "\rframe2".
1788                    let keep =
1789                        usize::from(out.len() > line_start && out[line_start] == b'\r');
1790                    out.truncate(line_start + keep);
1791                    i += 1;
1792                }
1793            } else {
1794                // Trailing \r — can't disambiguate yet; leave for next read.
1795                out.push(b);
1796                i += 1;
1797            }
1798        } else {
1799            out.push(b);
1800            i += 1;
1801        }
1802    }
1803    *pending = out;
1804}
1805
1806/// Shared publisher loop — drains the LineEvent channel, aggregates
1807/// into the model-visible buffer, and publishes each line via MPS.
1808///
1809/// **Leading-`\r` spinner handling:** throttled spinner frames (npm, cargo,
1810/// ora, tqdm at >50 ms/frame) are collapsed upstream — in the
1811/// `pending_cr_override` slot inside `stream_reader` (pipe path) and
1812/// `pty_reader_loop` (PTY path) — before reaching this loop. The
1813/// `pending_cr_line` slot here remains as a secondary layer: when a frame
1814/// arrives with a leading `\r`, the prior stored frame is published first
1815/// (so no frame is silently dropped), then the new frame is stored and
1816/// flushed at the next non-`\r` line or EOF. Consecutive spinner frames
1817/// therefore appear as sequential published chunks in the live log.
1818///
1819/// The model-visible buffer (`buffered`) receives the post-collapse LineEvent
1820/// bytes. Intermediate spinner frames collapsed by `pending_cr_override` never
1821/// become LineEvents and are not present in `buffered`; the model sees only the
1822/// surviving final frame for each overwrite sequence.
1823fn spawn_publisher_loop(
1824    args: &Args,
1825    mps: Option<WpsClient>,
1826    buffered: Arc<Mutex<Vec<u8>>>,
1827    mut rx: mpsc::Receiver<LineEvent>,
1828) -> tokio::task::JoinHandle<()> {
1829    let tool_id = args.tool_id.clone();
1830    let block_id = args.block_id.clone();
1831    tokio::spawn(async move {
1832        let mut chunks_published = 0u64;
1833        let mut chunks_failed = 0u64;
1834
1835        // Pending leading-\r spinner frame: holds (content_after_cr, kind).
1836        // Flushed on the next non-\r line or at EOF.
1837        let mut pending_cr_line: Option<(String, ToolChunkKind)> = None;
1838
1839        while let Some(event) = rx.recv().await {
1840            {
1841                let mut buf = buffered.lock().await;
1842                if event.kind == ToolChunkKind::Stderr {
1843                    buf.extend_from_slice(b"[stderr] ");
1844                }
1845                // Strip a single leading `\r` carried by a collapsed leading-\r
1846                // spinner frame (e.g. a final "\r✔ done\n"), matching the MPS
1847                // live path's `strip_prefix('\r')` below, so the model-visible
1848                // blob and the live log agree byte-for-byte. The trailing `\n`
1849                // is preserved here — it separates lines in the blob.
1850                let body: &[u8] = match event.bytes.first() {
1851                    Some(&b'\r') => &event.bytes[1..],
1852                    _ => &event.bytes,
1853                };
1854                buf.extend_from_slice(body);
1855            }
1856            if let Some(client) = mps.as_ref() {
1857                let mut line_bytes: &[u8] = &event.bytes;
1858                if line_bytes.last() == Some(&b'\n') {
1859                    line_bytes = &line_bytes[..line_bytes.len() - 1];
1860                }
1861                let line_str = String::from_utf8_lossy(line_bytes);
1862
1863                if let Some(stripped) = line_str.strip_prefix('\r') {
1864                    // Leading-\r spinner frame: publish any prior pending frame
1865                    // before storing the new one, so consecutive \r-prefixed
1866                    // lines are not silently dropped from the live MPS log.
1867                    // (This pending slot only affects the live MPS log; the
1868                    // model-visible blob already received this frame's bytes
1869                    // above, with the leading \r stripped to match.)
1870                    if let Some((prior_text, prior_kind)) = pending_cr_line.take() {
1871                        match publish_line(
1872                            client,
1873                            &tool_id,
1874                            block_id.as_deref(),
1875                            prior_kind,
1876                            &prior_text,
1877                        )
1878                        .await
1879                        {
1880                            Ok(()) => chunks_published += 1,
1881                            Err(e) => {
1882                                chunks_failed += 1;
1883                                tracing::warn!(
1884                                    target: "bashwrap",
1885                                    tool_id = %tool_id,
1886                                    error = %e,
1887                                    "MPS publish failed (prior pending_cr_line)"
1888                                );
1889                            }
1890                        }
1891                    }
1892                    pending_cr_line = Some((stripped.to_owned(), event.kind));
1893                } else {
1894                    // Non-\r line: flush any pending spinner frame first.
1895                    if let Some((cr_text, cr_kind)) = pending_cr_line.take() {
1896                        match publish_line(
1897                            client,
1898                            &tool_id,
1899                            block_id.as_deref(),
1900                            cr_kind,
1901                            &cr_text,
1902                        )
1903                        .await
1904                        {
1905                            Ok(()) => chunks_published += 1,
1906                            Err(e) => {
1907                                chunks_failed += 1;
1908                                tracing::warn!(
1909                                    target: "bashwrap",
1910                                    tool_id = %tool_id,
1911                                    error = %e,
1912                                    "MPS publish failed"
1913                                );
1914                            }
1915                        }
1916                    }
1917                    match publish_line(
1918                        client,
1919                        &tool_id,
1920                        block_id.as_deref(),
1921                        event.kind,
1922                        &line_str,
1923                    )
1924                    .await
1925                    {
1926                        Ok(()) => chunks_published += 1,
1927                        Err(e) => {
1928                            chunks_failed += 1;
1929                            tracing::warn!(
1930                                target: "bashwrap",
1931                                tool_id = %tool_id,
1932                                error = %e,
1933                                "MPS publish failed"
1934                            );
1935                        }
1936                    }
1937                }
1938            }
1939        }
1940
1941        // EOF: flush any remaining pending spinner frame.
1942        if let Some((cr_text, cr_kind)) = pending_cr_line.take() {
1943            if let Some(client) = mps.as_ref() {
1944                match publish_line(client, &tool_id, block_id.as_deref(), cr_kind, &cr_text).await
1945                {
1946                    Ok(()) => chunks_published += 1,
1947                    Err(e) => {
1948                        chunks_failed += 1;
1949                        tracing::warn!(
1950                            target: "bashwrap",
1951                            tool_id = %tool_id,
1952                            error = %e,
1953                            "MPS publish failed (EOF flush)"
1954                        );
1955                    }
1956                }
1957            }
1958        }
1959
1960        tracing::info!(
1961            target: "bashwrap",
1962            tool_id = %tool_id,
1963            chunks_published,
1964            chunks_failed,
1965            "publisher done"
1966        );
1967    })
1968}
1969
1970/// Snap `idx` down to the nearest UTF-8 character boundary (or 0).
1971/// A byte is a UTF-8 char boundary iff it's either ASCII (< 0x80) or
1972/// a leading byte (>= 0xC0). Continuation bytes are in 0x80..=0xBF.
1973/// `idx == buf.len()` is always a valid boundary (one past the end).
1974fn snap_to_char_boundary_floor(buf: &[u8], idx: usize) -> usize {
1975    let mut i = idx.min(buf.len());
1976    while i > 0 && i < buf.len() && (buf[i] & 0xC0) == 0x80 {
1977        i -= 1;
1978    }
1979    i
1980}
1981
1982/// Snap `idx` up to the nearest UTF-8 character boundary (or buf.len()).
1983fn snap_to_char_boundary_ceil(buf: &[u8], idx: usize) -> usize {
1984    let mut i = idx.min(buf.len());
1985    while i < buf.len() && (buf[i] & 0xC0) == 0x80 {
1986        i += 1;
1987    }
1988    i
1989}
1990
1991/// Build the aggregated, model-visible blob from the captured bytes.
1992/// Truncates with head/tail markers if it exceeds 100KB.
1993///
1994/// **UTF-8 safety**: head/tail slice boundaries are snapped to the
1995/// nearest UTF-8 character boundary so non-ASCII output (emoji,
1996/// accented characters, CJK) doesn't get corrupted into `�`
1997/// replacement characters at the cut point — naive fixed-byte slicing
1998/// splits multi-byte sequences and the lossy decode emits replacement
1999/// chars.
2000pub(crate) fn format_model_blob(
2001    buf: &[u8],
2002    exit_code: i32,
2003    elapsed: std::time::Duration,
2004) -> String {
2005    let body = if buf.len() <= MODEL_BLOB_HEAD_BYTES + MODEL_BLOB_TAIL_BYTES {
2006        String::from_utf8_lossy(buf).into_owned()
2007    } else {
2008        let head_end = snap_to_char_boundary_floor(buf, MODEL_BLOB_HEAD_BYTES);
2009        let tail_start = snap_to_char_boundary_ceil(buf, buf.len() - MODEL_BLOB_TAIL_BYTES);
2010        let head = String::from_utf8_lossy(&buf[..head_end]);
2011        let tail = String::from_utf8_lossy(&buf[tail_start..]);
2012        let elided = tail_start - head_end;
2013        format!(
2014            "{}\n... [{} bytes elided — see streaming log for full output] ...\n{}",
2015            head, elided, tail
2016        )
2017    };
2018    format!(
2019        "<exited {} in {:.2}s>\n{}",
2020        exit_code,
2021        elapsed.as_secs_f64(),
2022        body
2023    )
2024}
2025
2026/// Output fragments that mean an API refused the caller rather than the
2027/// command being wrong: AWS (`AccessDenied`, `AccessDeniedException`,
2028/// `... is not authorized to perform: ...`, EC2's `UnauthorizedOperation`)
2029/// and the GitHub API as an App (`Resource not accessible by integration`).
2030const ACCESS_DENIED_MARKERS: &[&str] = &[
2031    "AccessDenied",
2032    "is not authorized to perform",
2033    "UnauthorizedOperation",
2034    "Resource not accessible by integration",
2035];
2036
2037/// Appended after a failed command whose output shows an access denial.
2038/// Generic on purpose: how to escalate differs per deployment. Conditional
2039/// on purpose: in a compound command or a test suite the denial text may
2040/// come from a step that isn't the one that failed.
2041pub(crate) const ACCESS_DENIED_HINT: &str = "\n[agentmux] The output above includes an access denial. If that denial \
2042is why the command failed, don't work around it with another credential or by skipping the step: use this \
2043environment's documented escalation path (check your Global Memory and CLAUDE.md) with a stated reason, or ask the \
2044human operator if there is none.\n";
2045
2046/// The hint for the model, if the command failed and its output shows an
2047/// access denial. The whole buffer is searched, including any part the
2048/// model blob elides. A successful command never gets the hint, so a `grep`
2049/// or a log that merely mentions `AccessDenied` stays untouched.
2050pub(crate) fn access_denied_hint(buf: &[u8], exit_code: i32) -> Option<&'static str> {
2051    if exit_code == 0 {
2052        return None;
2053    }
2054    let denied = ACCESS_DENIED_MARKERS.iter().any(|marker| {
2055        let needle = marker.as_bytes();
2056        buf.windows(needle.len()).any(|window| window == needle)
2057    });
2058    denied.then_some(ACCESS_DENIED_HINT)
2059}
2060
2061#[cfg(test)]
2062mod tests {
2063    use super::*;
2064    use crate::cwd_state::CWD_STATE_FILE_OVERRIDE_ENV;
2065    use crate::test_env_lock::{unique_temp_dir, EnvVarGuard, ENV_LOCK};
2066
2067    // Env-touching tests share the crate-wide lock (`test_env_lock`): the
2068    // cwd-state tests in `cwd_state.rs` set the same variables.
2069
2070    #[test]
2071    fn decodes_b64_command() {
2072        // base64("echo hi") = ZWNobyBoaQ (no padding, url-safe)
2073        let s = decode_command("ZWNobyBoaQ").unwrap();
2074        assert_eq!(s, "echo hi");
2075    }
2076
2077    #[test]
2078    fn decodes_multi_line_with_quotes() {
2079        use base64::Engine as _;
2080        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
2081        let original = "echo \"line one\"\necho 'line two'";
2082        let b64 = URL_SAFE_NO_PAD.encode(original.as_bytes());
2083        let s = decode_command(&b64).unwrap();
2084        assert_eq!(s, original);
2085    }
2086
2087    #[test]
2088    fn rejects_malformed_b64() {
2089        assert!(decode_command("not-valid-base64===").is_err());
2090    }
2091
2092    /// reagentx P2 on this PR: a fixed (non-unique) temp filename meant two
2093    /// concurrent Bash tool calls for the same instance could both write to
2094    /// the *same* temp file before either renamed it, corrupting the
2095    /// persisted cwd with interleaved bytes. Proves two real, genuinely
2096    /// concurrent writers (via `$$`, each process's own PID) never
2097    /// interleave — the file always ends up as one writer's complete,
2098    /// valid output, never a mix of both.
2099    #[tokio::test]
2100    async fn run_via_pipes_concurrent_writers_never_corrupt_state_file() {
2101        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2102        let scratch = unique_temp_dir("e2e-concurrent");
2103        let state_file = scratch.join("state.cwd");
2104        let dir_a = scratch.join("dir-a");
2105        let dir_b = scratch.join("dir-b");
2106        std::fs::create_dir_all(&dir_a).unwrap();
2107        std::fs::create_dir_all(&dir_b).unwrap();
2108
2109        let _override =
2110            EnvVarGuard::set(CWD_STATE_FILE_OVERRIDE_ENV, state_file.to_str().unwrap());
2111
2112        let bash = locate_bash().expect("locate_bash for test — same dependency the whole binary needs");
2113        let args_a = Args {
2114            tool_id: "test-concurrent-a".to_string(),
2115            b64_cmd: String::new(),
2116            block_id: None,
2117            declared_background: false,
2118            agent: None,
2119            agent_unknown: false,
2120        };
2121        let args_b = Args {
2122            tool_id: "test-concurrent-b".to_string(),
2123            b64_cmd: String::new(),
2124            block_id: None,
2125            declared_background: false,
2126            agent: None,
2127            agent_unknown: false,
2128        };
2129        let cd_a = format!("cd \"{}\"", dir_a.display());
2130        let cd_b = format!("cd \"{}\"", dir_b.display());
2131        let buffered_a = Arc::new(tokio::sync::Mutex::new(Vec::<u8>::new()));
2132        let buffered_b = Arc::new(tokio::sync::Mutex::new(Vec::<u8>::new()));
2133
2134        let (status_a, status_b) = tokio::join!(
2135            run_via_pipes(&args_a, &cd_a, None, buffered_a, &bash),
2136            run_via_pipes(&args_b, &cd_b, None, buffered_b, &bash),
2137        );
2138        assert_eq!(status_a.unwrap(), 0);
2139        assert_eq!(status_b.unwrap(), 0);
2140
2141        // Whichever writer's rename landed last, the file must contain
2142        // exactly ONE valid, complete directory path — never a truncated
2143        // or interleaved mix of both writers' output.
2144        let final_contents = std::fs::read_to_string(&state_file).unwrap();
2145        let trimmed = final_contents.trim();
2146        let a_str = dir_a.to_string_lossy();
2147        let b_str = dir_b.to_string_lossy();
2148        assert!(
2149            trimmed.ends_with(dir_a.file_name().unwrap().to_str().unwrap())
2150                || trimmed.ends_with(dir_b.file_name().unwrap().to_str().unwrap()),
2151            "expected a clean write of either {a_str:?} or {b_str:?}, got {trimmed:?}"
2152        );
2153        assert!(
2154            !trimmed.contains('\n'),
2155            "a corrupted/interleaved write would likely contain embedded newlines: {trimmed:?}"
2156        );
2157
2158        let _ = std::fs::remove_dir_all(&scratch);
2159    }
2160
2161    /// End-to-end proof of the actual fix: running a `cd` in one `exec`
2162    /// invocation must change the starting directory of the *next*
2163    /// invocation, via the persisted state file — not just leave a
2164    /// same-process illusion of persistence.
2165    #[tokio::test]
2166    async fn run_via_pipes_persists_cwd_across_invocations() {
2167        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2168        let scratch = unique_temp_dir("e2e-pipes");
2169        let state_file = scratch.join("state.cwd");
2170        let target_dir = scratch.join("moved-here");
2171        std::fs::create_dir_all(&target_dir).unwrap();
2172
2173        let prev = std::env::var(CWD_STATE_FILE_OVERRIDE_ENV).ok();
2174        unsafe {
2175            std::env::set_var(CWD_STATE_FILE_OVERRIDE_ENV, &state_file);
2176        }
2177
2178        let bash = locate_bash().expect("locate_bash for test — same dependency the whole binary needs");
2179        let args = Args {
2180            tool_id: "test-cwd-persist".to_string(),
2181            b64_cmd: String::new(),
2182            block_id: None,
2183            declared_background: false,
2184            agent: None,
2185            agent_unknown: false,
2186        };
2187
2188        // Call 1: cd into target_dir. Nothing about this process's own env
2189        // changes — the fix must work purely through the state file.
2190        let cd_cmd = format!("cd \"{}\"", target_dir.display());
2191        let buffered1 = Arc::new(tokio::sync::Mutex::new(Vec::<u8>::new()));
2192        let status1 = run_via_pipes(&args, &cd_cmd, None, buffered1, &bash)
2193            .await
2194            .expect("call 1 should succeed");
2195        assert_eq!(status1, 0, "cd should succeed");
2196
2197        // Call 2: a fresh, unrelated invocation with no cd of its own —
2198        // `pwd` should report target_dir, proving the restored starting
2199        // directory came from call 1's persisted state, not from this
2200        // process's own (unchanged) cwd.
2201        let buffered2 = Arc::new(tokio::sync::Mutex::new(Vec::<u8>::new()));
2202        let status2 = run_via_pipes(&args, "pwd", None, buffered2.clone(), &bash)
2203            .await
2204            .expect("call 2 should succeed");
2205        assert_eq!(status2, 0);
2206
2207        unsafe {
2208            match prev {
2209                Some(v) => std::env::set_var(CWD_STATE_FILE_OVERRIDE_ENV, v),
2210                None => std::env::remove_var(CWD_STATE_FILE_OVERRIDE_ENV),
2211            }
2212        }
2213
2214        let pwd_output = String::from_utf8_lossy(&buffered2.lock().await).trim().to_string();
2215        let expected_name = target_dir
2216            .file_name()
2217            .and_then(|n| n.to_str())
2218            .unwrap()
2219            .to_string();
2220        let _ = std::fs::remove_dir_all(&scratch);
2221
2222        // Compare by trailing path component only — Windows `pwd` under Git
2223        // Bash reports an MSYS-style path (`/c/...`), not the Windows-style
2224        // path this test constructed the `cd` from.
2225        assert!(
2226            pwd_output.ends_with(&expected_name),
2227            "expected pwd output to end in {expected_name:?}, got {pwd_output:?}"
2228        );
2229    }
2230
2231    #[test]
2232    fn format_model_blob_under_cap_passes_body_through() {
2233        let body = b"hello world\n";
2234        let out = format_model_blob(body, 0, std::time::Duration::from_millis(123));
2235        assert!(out.starts_with("<exited 0 in 0.12s>\n"));
2236        assert!(out.contains("hello world"));
2237    }
2238
2239    #[test]
2240    fn access_denied_hint_on_failed_denials() {
2241        // Real outputs: the AWS CLI, CDK, EC2 and the GitHub API as an App.
2242        for output in [
2243            "An error occurred (AccessDeniedException) when calling the GetCostAndUsage operation: User: arn:aws:sts::1:assumed-role/R/s is not authorized to perform: ce:GetCostAndUsage",
2244            "User: arn:aws:sts::1:assumed-role/R/s is not authorized to perform: cloudformation:DescribeStacks on resource: arn:aws:cloudformation:us-east-1:1:stack/x/y",
2245            "An error occurred (UnauthorizedOperation) when calling the DescribeInstances operation",
2246            "An error occurred (AccessDenied) when calling the ListBuckets operation: Access Denied",
2247            "gh: Resource not accessible by integration (HTTP 403)",
2248        ] {
2249            assert_eq!(access_denied_hint(output.as_bytes(), 254), Some(ACCESS_DENIED_HINT), "{output}");
2250        }
2251    }
2252
2253    #[test]
2254    fn access_denied_hint_not_on_success_or_other_failures() {
2255        // Exit 0: a grep or a log that only mentions a denial.
2256        assert_eq!(access_denied_hint(b"docs/x.md:12: AccessDenied means escalate", 0), None);
2257        // Failed, but not a denial.
2258        assert_eq!(access_denied_hint(b"error: could not compile `x`", 101), None);
2259        assert_eq!(access_denied_hint(b"", 1), None);
2260    }
2261
2262    #[test]
2263    fn access_denied_hint_searches_output_the_blob_elides() {
2264        // The denial sits in the middle of output over the model blob's cap.
2265        let mut buf = vec![b'x'; MODEL_BLOB_HEAD_BYTES + 10];
2266        buf.extend_from_slice(b" is not authorized to perform: s3:PutObject ");
2267        buf.extend(vec![b'y'; MODEL_BLOB_TAIL_BYTES + 10]);
2268        let blob = format_model_blob(&buf, 1, std::time::Duration::from_millis(1));
2269        assert!(!blob.contains("is not authorized"), "precondition: the blob elides the denial");
2270        assert_eq!(access_denied_hint(&buf, 1), Some(ACCESS_DENIED_HINT));
2271    }
2272
2273    #[test]
2274    fn access_denied_hint_is_generic_and_says_not_to_work_around() {
2275        // AgentMux ships to every deployment: no deployment's own commands.
2276        for specific in ["secrets escalate", "gh-agent", "a5af"] {
2277            assert!(!ACCESS_DENIED_HINT.contains(specific), "{specific}");
2278        }
2279        assert!(ACCESS_DENIED_HINT.contains("don't work around it"));
2280        assert!(ACCESS_DENIED_HINT.contains("ask the human operator"));
2281        // The denial may come from an earlier step than the one that failed.
2282        assert!(ACCESS_DENIED_HINT.contains("If that denial is why the command failed"));
2283    }
2284
2285    #[test]
2286    fn format_model_blob_truncates_over_cap_at_char_boundary() {
2287        // 200KB of '🌟' (4-byte emoji) > 100KB cap → truncates.
2288        let s = "🌟".repeat(50_000);
2289        let bytes = s.as_bytes();
2290        let out = format_model_blob(bytes, 0, std::time::Duration::from_secs(1));
2291        // No replacement char `�` (U+FFFD) — boundary snap must keep
2292        // multi-byte sequences whole at the cut point.
2293        assert!(
2294            !out.contains('\u{FFFD}'),
2295            "found replacement char (lossy decode at boundary)"
2296        );
2297        assert!(out.contains("bytes elided"));
2298    }
2299
2300    #[test]
2301    fn snap_floor_is_idempotent_at_ascii() {
2302        let buf = b"abcdef";
2303        assert_eq!(snap_to_char_boundary_floor(buf, 3), 3);
2304        assert_eq!(snap_to_char_boundary_floor(buf, 0), 0);
2305        assert_eq!(snap_to_char_boundary_floor(buf, 6), 6);
2306    }
2307
2308    #[test]
2309    fn snap_floor_steps_back_off_continuation_bytes() {
2310        // "é" = [0xC3, 0xA9]; index 1 is a continuation byte.
2311        let buf = b"\xc3\xa9x";
2312        assert_eq!(snap_to_char_boundary_floor(buf, 1), 0);
2313    }
2314
2315    // ── collapse_cr tests ────────────────────────────────────────────────────
2316
2317    fn cr(input: &[u8]) -> Vec<u8> {
2318        let mut v = input.to_vec();
2319        collapse_cr(&mut v);
2320        v
2321    }
2322
2323    #[test]
2324    fn collapse_cr_no_cr_is_noop() {
2325        assert_eq!(cr(b"hello\nworld\n"), b"hello\nworld\n");
2326    }
2327
2328    #[test]
2329    fn collapse_cr_trailing_cr_preserved() {
2330        // Trailing \r must not be collapsed — may be first byte of CRLF split
2331        // across reads. The caller suppresses the partial flush in this case.
2332        assert_eq!(cr(b"frame1\r"), b"frame1\r");
2333    }
2334
2335    #[test]
2336    fn collapse_cr_crlf_within_buffer_becomes_lf() {
2337        assert_eq!(cr(b"line\r\n"), b"line\n");
2338    }
2339
2340    #[test]
2341    fn collapse_cr_crlf_straddle_resolved_on_second_call() {
2342        // Simulate two reads: first leaves trailing \r, second sees \n next.
2343        // collapse_cr is called after each extend.
2344        let mut pending = b"line1\r".to_vec();
2345        collapse_cr(&mut pending);
2346        assert_eq!(pending, b"line1\r"); // trailing \r preserved
2347        pending.extend_from_slice(b"\nmore");
2348        collapse_cr(&mut pending);
2349        assert_eq!(pending, b"line1\nmore"); // CRLF resolved, "more" accumulated
2350    }
2351
2352    #[test]
2353    fn collapse_cr_trailing_spinner_frames_collapse() {
2354        // Trailing-\r convention: "frame\r" per write, accumulated before \n.
2355        let mut pending = b"frame1\r".to_vec();
2356        collapse_cr(&mut pending);
2357        // trailing \r kept, frame1 still present
2358        assert_eq!(pending, b"frame1\r");
2359        pending.extend_from_slice(b"frame2\r");
2360        collapse_cr(&mut pending);
2361        // \r mid-buffer (pos 6, followed by 'f'): frame1 collapsed, trailing \r kept
2362        assert_eq!(pending, b"frame2\r");
2363        pending.extend_from_slice(b"done\n");
2364        collapse_cr(&mut pending);
2365        // \r mid-buffer (followed by 'd'): frame2 collapsed, done\n remains
2366        assert_eq!(pending, b"done\n");
2367    }
2368
2369    #[test]
2370    fn collapse_cr_leading_spinner_frames_collapse() {
2371        // Leading-\r convention: "\rframe" per write (npm/ora/gh style).
2372        // Case 1: non-\r line overwritten by \r-prefixed content (normal path).
2373        let mut pending = b"frame1".to_vec();
2374        collapse_cr(&mut pending);
2375        assert_eq!(pending, b"frame1"); // no \r, unchanged
2376        pending.extend_from_slice(b"\rframe2");
2377        collapse_cr(&mut pending);
2378        // "frame1\rframe2": \r at pos 6 overwrites non-\r line → "frame2"
2379        assert_eq!(pending, b"frame2");
2380        pending.extend_from_slice(b"\rdone\n");
2381        collapse_cr(&mut pending);
2382        // "frame2\rdone\n": \r at pos 6 overwrites non-\r line, done\n remains
2383        assert_eq!(pending, b"done\n");
2384    }
2385
2386    #[test]
2387    fn collapse_cr_leading_cr_multi_frame_preserves_leading_cr() {
2388        // Case 2: \r-prefixed line overwritten by another \r-prefixed line.
2389        // "\rframe1\rframe2" must collapse to "\rframe2", NOT "frame2".
2390        // Without the leading-\r preservation, the mid-buffer \r at pos 7
2391        // would truncate to line_start=0, discarding the leading \r, and
2392        // pending_cr_override can no longer detect the result as a spinner.
2393        assert_eq!(cr(b"\rframe1\rframe2"), b"\rframe2");
2394        // Three frames: only last survives, leading \r preserved.
2395        assert_eq!(cr(b"\rframe1\rframe2\rframe3"), b"\rframe3");
2396        // Normal (non-leading-\r) line overwritten: no leading \r in result.
2397        assert_eq!(cr(b"frame1\rframe2"), b"frame2");
2398    }
2399
2400    #[test]
2401    fn collapse_cr_preserves_prior_lines() {
2402        // \r only rewinds to the start of the current visual line, not past \n.
2403        assert_eq!(cr(b"line1\npartial\rreplace\n"), b"line1\nreplace\n");
2404    }
2405
2406    // ── normalize_csi_overwrites tests (spec §A2) ──────────────────────────
2407
2408    fn csi(input: &[u8]) -> Vec<u8> {
2409        let mut v = input.to_vec();
2410        let mut still_on_first_line = true;
2411        let mut at_col0 = true;
2412        normalize_csi_overwrites(&mut v, &mut still_on_first_line, &mut at_col0);
2413        v
2414    }
2415
2416    #[test]
2417    fn normalize_csi_cha_col1_becomes_cr() {
2418        assert_eq!(csi(b"progress\x1b[1Gdone"), b"progress\rdone");
2419        // Bare \x1b[G (no param) means column 1 too, per ECMA-48 default.
2420        assert_eq!(csi(b"progress\x1b[Gdone"), b"progress\rdone");
2421    }
2422
2423    #[test]
2424    fn normalize_csi_cha_other_column_left_untouched() {
2425        // Only column 1 maps cleanly onto "\r" (start of line); other
2426        // columns are intentionally out of scope (need true column
2427        // tracking) and must survive unmangled for strip_ansi to remove.
2428        let out = csi(b"progress\x1b[10Gdone");
2429        assert!(!out.contains(&b'\r'), "unrelated CHA column must not synthesize a \\r");
2430        assert_eq!(out, b"progress\x1b[10Gdone");
2431    }
2432
2433    #[test]
2434    fn normalize_csi_el_at_line_start_becomes_cr() {
2435        // EL at the very start of a chunk (nothing written on this line
2436        // yet) is safe: there's nothing to lose by treating it as \r.
2437        assert_eq!(csi(b"\x1b[2Kfresh"), b"\rfresh");
2438        assert_eq!(csi(b"\x1b[Kfresh"), b"\rfresh");
2439        assert_eq!(csi(b"\x1b[0Kfresh"), b"\rfresh");
2440        // Same, after a real newline -- also column 0.
2441        assert_eq!(csi(b"line1\n\x1b[2Kfresh"), b"line1\n\rfresh");
2442    }
2443
2444    #[test]
2445    fn normalize_csi_standalone_mid_line_el_is_left_untouched_not_synthesized_to_cr() {
2446        // reagent P1, PR #2330: EL only erases from the cursor onward and
2447        // never moves it -- it is NOT equivalent to \r when real content
2448        // ("stale") already precedes it on the line. The previous,
2449        // unconditional version turned this into "stale\rfresh", which
2450        // collapse_cr then truncated to just "fresh", silently discarding
2451        // "stale" even though EL never asked for that. Leaving it
2452        // unconverted here means strip_ansi removes only the escape bytes
2453        // afterward, preserving "stale" + "fresh" concatenated.
2454        let out = csi(b"stale\x1b[2Kfresh");
2455        assert!(!out.contains(&b'\r'), "mid-line EL must not synthesize a \\r: {out:?}");
2456        assert_eq!(out, b"stale\x1b[2Kfresh");
2457
2458        let out_k = csi(b"stale\x1b[Kfresh");
2459        assert!(!out_k.contains(&b'\r'));
2460        assert_eq!(out_k, b"stale\x1b[Kfresh");
2461    }
2462
2463    #[test]
2464    fn normalize_csi_at_col0_persists_across_calls_mid_line_el_split_across_reads_stays_untouched() {
2465        // reagent P1, PR #2330 (round 2): normalize_csi_overwrites is called
2466        // once per PTY read in the real reader loop, with at_col0 threaded
2467        // in by &mut reference across calls -- NOT reset per call. A prior
2468        // version of this fix declared at_col0 as a local reset to `true`
2469        // on every call, so a standalone EL split across two PTY reads
2470        // ("prefix" in one read, "\x1b[2Ksuffix" in the next) would see a
2471        // freshly-true at_col0 on the second call and wrongly convert the
2472        // EL to \r, reproducing the exact mid-line truncation bug the first
2473        // round of this fix addressed -- just moved from a mid-chunk split
2474        // to a cross-chunk-read split.
2475        let mut still_on_first_line = true;
2476        let mut at_col0 = true;
2477
2478        let mut first_read = b"prefix".to_vec();
2479        normalize_csi_overwrites(&mut first_read, &mut still_on_first_line, &mut at_col0);
2480        assert_eq!(first_read, b"prefix");
2481        assert!(!at_col0, "cursor is mid-line after a read with no trailing \\n/\\r");
2482
2483        let mut second_read = b"\x1b[2Ksuffix".to_vec();
2484        normalize_csi_overwrites(&mut second_read, &mut still_on_first_line, &mut at_col0);
2485        assert!(
2486            !second_read.contains(&b'\r'),
2487            "EL split across a PTY-read boundary, still mid-line, must not synthesize a \\r: {second_read:?}"
2488        );
2489        assert_eq!(second_read, b"\x1b[2Ksuffix");
2490
2491        // Simulate the reader loop's actual buffering: both reads accumulate
2492        // into one pending buffer before collapse_cr/strip_ansi run on it.
2493        let mut pending = first_read;
2494        pending.extend_from_slice(&second_read);
2495        assert_eq!(pending, b"prefix\x1b[2Ksuffix");
2496    }
2497
2498    #[test]
2499    fn normalize_csi_at_col0_persists_across_calls_leading_cr_read_then_bare_el_read_becomes_cr() {
2500        // Complement of the above: a read ending in \r (cursor genuinely at
2501        // column 0) followed by a read that STARTS with EL must still
2502        // convert -- persisted state must correctly stay `true` too, not
2503        // just correctly go false.
2504        let mut still_on_first_line = true;
2505        let mut at_col0 = true;
2506
2507        let mut first_read = b"frame1\r".to_vec();
2508        normalize_csi_overwrites(&mut first_read, &mut still_on_first_line, &mut at_col0);
2509        assert!(at_col0, "trailing \\r puts the cursor back at column 0");
2510
2511        let mut second_read = b"\x1b[2Kframe2".to_vec();
2512        normalize_csi_overwrites(&mut second_read, &mut still_on_first_line, &mut at_col0);
2513        assert_eq!(second_read, b"\rframe2");
2514    }
2515
2516    #[test]
2517    fn normalize_csi_el_immediately_after_real_cr_still_becomes_cr() {
2518        // The dominant real-world idiom (\r\x1b[2K<text>): the \r already
2519        // puts the cursor at column 0, so a following EL is genuinely
2520        // redundant and safe to also represent as \r.
2521        assert_eq!(csi(b"\r\x1b[2Kfresh"), b"\r\rfresh");
2522    }
2523
2524    #[test]
2525    fn normalize_csi_cup_home_becomes_cr_on_first_line() {
2526        // Windows ConPTY re-serializes a literal \r as CUP-to-home rather
2527        // than passing it through -- verified empirically via the e2e test
2528        // below. All the omitted-field variants mean row 1, col 1.
2529        assert_eq!(csi(b"progress\x1b[Hdone"), b"progress\rdone");
2530        assert_eq!(csi(b"progress\x1b[1Hdone"), b"progress\rdone");
2531        assert_eq!(csi(b"progress\x1b[1;1Hdone"), b"progress\rdone");
2532        assert_eq!(csi(b"progress\x1b[;1Hdone"), b"progress\rdone");
2533        assert_eq!(csi(b"progress\x1b[1;Hdone"), b"progress\rdone");
2534    }
2535
2536    #[test]
2537    fn normalize_csi_cup_other_position_left_untouched() {
2538        // Row/col other than 1,1 isn't "start of line" and must survive
2539        // unmangled.
2540        let out = csi(b"progress\x1b[2;1Hdone");
2541        assert!(!out.contains(&b'\r'));
2542        assert_eq!(out, b"progress\x1b[2;1Hdone");
2543    }
2544
2545    #[test]
2546    fn normalize_csi_cup_home_ignored_once_output_has_scrolled_past_first_line() {
2547        // Once real multi-line output exists, \x1b[H means "go back to the
2548        // FIRST of several lines" (a multi-line redraw, spec §A3,
2549        // deliberately out of scope) -- must NOT be treated as "restart
2550        // the current line", which would corrupt the multi-line content.
2551        let mut v = b"line1\nline2\n\x1b[Hline1-updated".to_vec();
2552        let mut still_on_first_line = true;
2553        let mut at_col0 = true;
2554        normalize_csi_overwrites(&mut v, &mut still_on_first_line, &mut at_col0);
2555        assert!(!still_on_first_line, "must flip false after the first \\n");
2556        assert!(
2557            !v.contains(&b'\r'),
2558            "CUP-home after multi-line output must not synthesize a \\r: {:?}",
2559            String::from_utf8_lossy(&v)
2560        );
2561        assert_eq!(v, b"line1\nline2\n\x1b[Hline1-updated");
2562    }
2563
2564    #[test]
2565    fn normalize_csi_cub_left_untouched() {
2566        // CUB (cursor-back N) is documented out-of-scope for this pass
2567        // (spec §A2) -- needs true per-column tracking. Must survive
2568        // unmangled here so strip_ansi still strips it as a whole sequence
2569        // afterward (not left as garbage).
2570        let out = csi(b"progress\x1b[5Ddone");
2571        assert!(!out.contains(&b'\r'));
2572        assert_eq!(out, b"progress\x1b[5Ddone");
2573    }
2574
2575    #[test]
2576    fn normalize_csi_dominant_cr_plus_el_idiom_is_redundant_but_correct() {
2577        // The overwhelmingly common real-world idiom: \r\x1b[2K<text>. The
2578        // \r is already present; normalize_csi_overwrites additionally
2579        // turning \x1b[2K into a second \r is harmless -- collapse_cr
2580        // treats consecutive \r as idempotent resets to the same line
2581        // start.
2582        let normalized = csi(b"\r\x1b[2Knew frame");
2583        let mut pending = normalized;
2584        collapse_cr(&mut pending);
2585        assert_eq!(pending, b"\rnew frame");
2586    }
2587
2588    #[test]
2589    fn normalize_csi_composes_with_collapse_cr_for_a_full_overwrite() {
2590        // End-to-end of the two functions together, as the reader loop
2591        // actually calls them: a progress line first written plainly, then
2592        // rewritten via CHA(1) on the next PTY read, must collapse exactly
2593        // like a \r-based rewrite would.
2594        let mut pending = b"Downloading 10%".to_vec();
2595        collapse_cr(&mut pending); // no-op, no \r yet
2596
2597        let mut next_chunk = b"\x1b[1GDownloading 45%".to_vec();
2598        let mut still_on_first_line = true;
2599        let mut at_col0 = true;
2600        normalize_csi_overwrites(&mut next_chunk, &mut still_on_first_line, &mut at_col0);
2601        pending.extend_from_slice(&next_chunk);
2602        collapse_cr(&mut pending);
2603
2604        assert_eq!(pending, b"Downloading 45%");
2605    }
2606
2607    /// Verify that the quiet-window semantics are: hold when pending ends
2608    /// with \r; flush when it doesn't. These are unit tests of the policy
2609    /// (not of the reader loop directly) — they encode the contract so a
2610    /// future refactor can't accidentally revert to pop-and-flush.
2611    #[test]
2612    fn quiet_window_holds_when_trailing_cr() {
2613        // A spinner frame "⠋ Loading...\r" should NOT be flushed by the
2614        // quiet-window — the \r signals that the next frame will overwrite.
2615        let pending = b"Loading...\r".to_vec();
2616        assert!(
2617            pending.last() == Some(&b'\r'),
2618            "quiet-window must hold pending ending with \\r"
2619        );
2620        // Simulate what collapse_cr does when the next frame arrives.
2621        let mut combined = pending.clone();
2622        combined.extend_from_slice(b"Done!\n");
2623        collapse_cr(&mut combined);
2624        assert_eq!(combined, b"Done!\n");
2625    }
2626
2627    #[test]
2628    fn quiet_window_defers_once_when_no_leading_or_trailing_cr() {
2629        // "Building..." (no \r at either end) is a candidate for A1's
2630        // one-tick speculative defer, not an immediate flush — see
2631        // docs/specs/SPEC_TOOL_LOG_UNIVERSAL_ANIMATION_COLLAPSE_2026_07_27.md §A1.
2632        let pending = b"Building...".to_vec();
2633        assert!(
2634            pending.first() != Some(&b'\r') && pending.last() != Some(&b'\r'),
2635            "quiet-window must defer (not flush) pending with no leading/trailing \\r"
2636        );
2637    }
2638
2639    /// A1: the exact real-world bug this closes — a static label is
2640    /// printed once with no `\r`, THEN (after the label has already been
2641    /// speculatively deferred) a `\r`-prefixed overwrite arrives. Before
2642    /// A1, the label would already have been flushed as its own permanent
2643    /// LineEvent by the time the overwrite showed up, producing two lines
2644    /// instead of one settled line.
2645    #[test]
2646    fn a1_deferred_line_merges_with_a_following_cr_prefixed_overwrite() {
2647        // What deferred_pending holds after tick 1 (no \r either end).
2648        let deferred = b"Installing deps...".to_vec();
2649        // What arrives on the next read: a \r-prefixed overwrite.
2650        let next_chunk = b"\rInstalling deps... done\n".to_vec();
2651        // Mirrors the reader's merge step: prepend deferred, let
2652        // collapse_cr do the rest.
2653        let mut combined = deferred;
2654        combined.extend_from_slice(&next_chunk);
2655        collapse_cr(&mut combined);
2656        assert_eq!(
2657            combined, b"Installing deps... done\n",
2658            "deferred label + \\r-overwrite must collapse to ONE line, not two"
2659        );
2660    }
2661
2662    /// A1: the deferred line must NOT be merged with unrelated content
2663    /// that arrives without a leading `\r` — that's two genuinely
2664    /// different lines and must stay two LineEvents.
2665    #[test]
2666    fn a1_deferred_line_is_not_merged_with_unrelated_non_cr_content() {
2667        let deferred = b"Installing deps...".to_vec();
2668        let next_chunk = b"Running tests...\n".to_vec();
2669        // Mirrors the reader's policy: no leading \r on the new chunk means
2670        // flush `deferred` as its own event, then start fresh with the new
2671        // chunk (never concatenate the two).
2672        assert_ne!(next_chunk.first(), Some(&b'\r'));
2673        let mut fresh = Vec::new();
2674        fresh.extend_from_slice(&next_chunk);
2675        collapse_cr(&mut fresh);
2676        assert_eq!(fresh, b"Running tests...\n");
2677        // The deferred line, flushed separately, is untouched by the above.
2678        assert_eq!(deferred, b"Installing deps...");
2679    }
2680
2681    #[test]
2682    fn eof_strips_trailing_cr() {
2683        // At EOF, a dangling \r (stream ended mid-spinner or mid-CRLF) is
2684        // stripped before the final flush so the rendered chunk is clean.
2685        let mut pending = b"partial\r".to_vec();
2686        if pending.last() == Some(&b'\r') {
2687            pending.pop();
2688        }
2689        assert_eq!(pending, b"partial");
2690    }
2691
2692    #[test]
2693    fn locate_bash_via_explicit_env() {
2694        // Use the binary that runs the test as a stand-in for "bash"
2695        // — we only assert that the override is honored, not that the
2696        // path is a real bash. ENV_LOCK serializes against any future
2697        // env-touching test (and against `BASH` reads in the same fn).
2698        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2699        let exe = std::env::current_exe().expect("current_exe");
2700        let prev_agentmux_bash = std::env::var("AGENTMUX_BASH").ok();
2701        let prev_bash = std::env::var("BASH").ok();
2702        // Clear BASH so the override path is the one being asserted.
2703        unsafe {
2704            std::env::set_var("AGENTMUX_BASH", &exe);
2705            std::env::remove_var("BASH");
2706        }
2707        let found = locate_bash().expect("locate_bash with override");
2708        assert_eq!(found, exe);
2709        unsafe {
2710            match prev_agentmux_bash {
2711                Some(v) => std::env::set_var("AGENTMUX_BASH", v),
2712                None => std::env::remove_var("AGENTMUX_BASH"),
2713            }
2714            if let Some(v) = prev_bash {
2715                std::env::set_var("BASH", v);
2716            }
2717        }
2718    }
2719
2720    // ── idle_kill_timeout tests ─────────────────────────────────────────────
2721    // RETRO_BASHWRAP_PAGER_HANG_LEAK_2026_07_14.md: these cover the env-var
2722    // override for the idle-kill timeout. The kill/PTY behavior itself isn't
2723    // unit-testable without a real PTY (see the retro's verification section
2724    // for the manual repro this was checked against instead).
2725
2726    #[test]
2727    fn idle_kill_timeout_defaults_when_unset() {
2728        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2729        let prev = std::env::var("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS").ok();
2730        unsafe {
2731            std::env::remove_var("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS");
2732        }
2733        assert_eq!(idle_kill_timeout(), DEFAULT_IDLE_KILL_TIMEOUT);
2734        unsafe {
2735            if let Some(v) = prev {
2736                std::env::set_var("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS", v);
2737            }
2738        }
2739    }
2740
2741    #[test]
2742    fn idle_kill_timeout_honors_env_override() {
2743        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2744        let prev = std::env::var("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS").ok();
2745        unsafe {
2746            std::env::set_var("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS", "5");
2747        }
2748        assert_eq!(idle_kill_timeout(), Duration::from_secs(5));
2749        unsafe {
2750            match prev {
2751                Some(v) => std::env::set_var("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS", v),
2752                None => std::env::remove_var("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS"),
2753            }
2754        }
2755    }
2756
2757    #[test]
2758    fn idle_kill_timeout_falls_back_on_unparseable_value() {
2759        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2760        let prev = std::env::var("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS").ok();
2761        unsafe {
2762            std::env::set_var("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS", "not-a-number");
2763        }
2764        assert_eq!(idle_kill_timeout(), DEFAULT_IDLE_KILL_TIMEOUT);
2765        unsafe {
2766            match prev {
2767                Some(v) => std::env::set_var("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS", v),
2768                None => std::env::remove_var("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS"),
2769            }
2770        }
2771    }
2772
2773    /// End-to-end proof that the idle-kill mechanism actually fires AND
2774    /// reaches the whole process tree, not just the direct PTY child.
2775    ///
2776    /// Uses two backgrounded `sleep` grandchildren (`bash -c '{ sleep
2777    /// <marker>1 & sleep <marker>2 & wait; } </dev/null'`) rather than a
2778    /// single-process command: killing only the direct `bash` child (what
2779    /// `ChildKiller::kill()` alone does — see `kill_process_tree`'s doc
2780    /// comment) would leave these two running as orphans, exactly
2781    /// reproducing the leak one process removed instead of fixing it
2782    /// (reagent P1, PR #2156). The marker values are unique per test run
2783    /// (derived from the current PID) so a leftover orphan from a
2784    /// *previous* failed run of this same test, or an unrelated `sleep`
2785    /// elsewhere on a shared dev machine, can't produce a false pass.
2786    ///
2787    /// The `sleep <marker>` argument doubles as the zero-PTY-output
2788    /// condition this exists to catch (a clean, portable stand-in for "any
2789    /// command silently blocked forever," the same shape as the pager hang
2790    /// — see docs/retro/RETRO_BASHWRAP_PAGER_HANG_LEAK_2026_07_14.md).
2791    /// Without the fix, this test would hang until the outer
2792    /// `tokio::time::timeout` fires and fails it.
2793    #[tokio::test]
2794    async fn run_via_pty_kills_idle_child_and_returns_promptly() {
2795        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2796        let prev = std::env::var("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS").ok();
2797        unsafe {
2798            std::env::set_var("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS", "1");
2799        }
2800
2801        let bash = locate_bash().expect("locate_bash for test — same dependency the whole binary needs");
2802        let pty_system = native_pty_system();
2803        let pair = match pty_system.openpty(PtySize {
2804            rows: 24,
2805            cols: 80,
2806            pixel_width: 0,
2807            pixel_height: 0,
2808        }) {
2809            Ok(p) => p,
2810            Err(e) => {
2811                unsafe {
2812                    match prev {
2813                        Some(v) => std::env::set_var("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS", v),
2814                        None => std::env::remove_var("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS"),
2815                    }
2816                }
2817                eprintln!("skipping: PTY unavailable in this environment: {e}");
2818                return;
2819            }
2820        };
2821
2822        let args = Args {
2823            tool_id: "test-idle-kill".to_string(),
2824            b64_cmd: String::new(),
2825            block_id: None,
2826            declared_background: false,
2827            agent: None,
2828            agent_unknown: false,
2829        };
2830        // `Mutex` in this module scope resolves to `std::sync::Mutex`
2831        // (shadowed for `ENV_LOCK` above) — `run_via_pty` needs the async
2832        // `tokio::sync::Mutex` its `buffered: Arc<Mutex<Vec<u8>>>` param
2833        // expects, so spell it out.
2834        let buffered = Arc::new(tokio::sync::Mutex::new(Vec::<u8>::new()));
2835
2836        // Unique-per-run, but still a valid numeric duration for `sleep`
2837        // (GNU coreutils sleep accepts fractional seconds and arbitrarily
2838        // large values). A non-numeric marker string would make `sleep`
2839        // error out instantly instead of blocking — caught by this test's
2840        // own first run failing with exit code 0 (~0.1s elapsed) instead
2841        // of the expected kill.
2842        //
2843        // The `100` tag (vs. `bashwrap_binary_idle_kill_cleans_up_full_process_tree`'s
2844        // `300`) is NOT cosmetic: `std::process::id()` is the SAME across
2845        // every test in this binary (they're threads in one process, not
2846        // separate processes), and Rust's test harness runs tests in
2847        // parallel by default — so a bare `pid.to_string()` marker would
2848        // let this test's sleep processes get miscounted as "survivors" by
2849        // that other test's WMI substring search (and vice versa) if both
2850        // happen to overlap in time. Found this the hard way: the other
2851        // test failed with "3 survivors" once this test's marker collided
2852        // with its own. The tag makes the two tests' marker strings
2853        // non-overlapping substrings of each other.
2854        let pid = std::process::id();
2855        let marker = format!("{pid}100");
2856        let command = format!("sleep {marker}.001 & sleep {marker}.002 & wait");
2857
2858        let start = std::time::Instant::now();
2859        let result = tokio::time::timeout(
2860            Duration::from_secs(20),
2861            run_via_pty(&args, &command, None, buffered.clone(), &bash, pair),
2862        )
2863        .await
2864        .expect("run_via_pty must not hang past the outer test timeout — idle-kill should have fired well before this")
2865        .expect("run_via_pty should return Ok even when it had to kill the child");
2866
2867        // The exact code is platform/kill-mechanism-specific (portable-pty's
2868        // Windows ChildKiller calls TerminateProcess with code 127, but the
2869        // wrapping `bash -c` process's own reported code after being killed
2870        // is what we actually observe here, not necessarily 127 — verified
2871        // empirically as 1 on this Windows dev machine). `124` is only the
2872        // fallback sentinel used if the wait task doesn't resolve within
2873        // the post-kill grace period at all. What actually matters: it's
2874        // never the clean-success `0`, and (checked below) it returns
2875        // promptly instead of hanging.
2876        assert_ne!(
2877            result, 0,
2878            "an idle-killed child must not report a clean success exit code"
2879        );
2880        assert!(
2881            start.elapsed() < Duration::from_secs(15),
2882            "should return well within the 1s idle timeout + grace periods, not the 20s outer bound — got {:?}",
2883            start.elapsed()
2884        );
2885
2886        let blob = buffered.lock().await;
2887        assert!(
2888            String::from_utf8_lossy(&blob).contains("terminated automatically"),
2889            "model-visible blob should explain why the command was cut short, got: {:?}",
2890            String::from_utf8_lossy(&blob)
2891        );
2892        drop(blob);
2893
2894        // NOTE on what this test does NOT prove: calling `run_via_pty`
2895        // in-process (as a library function inside `cargo test`'s own
2896        // process) returning does not, by itself, guarantee every
2897        // descendant is gone yet — see
2898        // `bashwrap_binary_idle_kill_cleans_up_full_process_tree` below for
2899        // why, and for the test that actually proves full-tree cleanup.
2900        let _ = &marker; // used by the binary-level test below, not here
2901
2902        unsafe {
2903            match prev {
2904                Some(v) => std::env::set_var("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS", v),
2905                None => std::env::remove_var("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS"),
2906            }
2907        }
2908    }
2909
2910    /// Reagent P1 follow-up, PR #2156: `idle_rx` resolves (with `Err`) not
2911    /// only when `pty_reader_loop` really signals an idle timeout, but also
2912    /// whenever it returns normally (EOF on a fast, successful command) and
2913    /// drops the still-unused `idle_tx`. The original `tokio::select! { _ =
2914    /// idle_rx => {...} }` treated BOTH cases identically, so a fast
2915    /// command completing could race `wait_task` and get spuriously
2916    /// killed + tagged "terminated automatically" even though it ran to
2917    /// completion normally. Fixed by branching on `idle_signal.is_err()`
2918    /// inside that arm instead of ignoring the value.
2919    ///
2920    /// A single run of a fast command isn't a reliable regression test for
2921    /// a race in general, so this runs `echo` 30 times with a very short
2922    /// idle timeout to widen the chance of catching it.
2923    ///
2924    /// Honesty check performed while writing this test: temporarily forced
2925    /// the OLD (buggy) unconditional-kill behavior back in and re-ran this
2926    /// exact test — it still passed 30/30. On this machine, `wait_task`
2927    /// (`child.wait()` resolving) appears to reliably win the race against
2928    /// `pty_reader_loop`'s EOF-then-drop for a trivially fast command like
2929    /// `echo hello`, so this test does NOT reliably fail on the unfixed
2930    /// code and can't be trusted as sole proof the bug is gone. muxreview's
2931    /// code-level analysis of the race is still correct — a oneshot
2932    /// receiver genuinely does resolve identically for "sent" and
2933    /// "dropped without sending," and the fix (branching on
2934    /// `idle_signal.is_err()`) is the structurally correct response
2935    /// regardless of whether this specific test can force the window open.
2936    /// The scenario muxreview named as the realistic trigger — blocking
2937    /// thread-pool contention from concurrent bashwrap invocations —
2938    /// wasn't reproduced here; doing so reliably would need deliberately
2939    /// saturating tokio's blocking pool, not attempted given time spent on
2940    /// this investigation already. This test is kept as basic coverage of
2941    /// the fast-success path (asserts real output, exit 0, no spurious
2942    /// diagnostic) — a real regression guard for *some* bugs in this area,
2943    /// just not proven to be one for this exact race.
2944    #[tokio::test]
2945    async fn run_via_pty_does_not_misclassify_fast_success_as_idle_timeout() {
2946        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2947        // reagentx P2 on PR #2569 (re-review): a manual save-now/restore-
2948        // at-the-end dance doesn't run on an early exit — the `panic!`s in
2949        // the loop below (via `unwrap_or_else`) and the `assert_eq!`/
2950        // `assert!` calls can all unwind straight past the restore code
2951        // that used to sit at the bottom of this function, leaking this env
2952        // var's override to every subsequent test in the process. Same bug
2953        // class already fixed via `EnvVarGuard` (defined above, used
2954        // elsewhere in this file for exactly this reason) for the
2955        // neighboring `a1_e2e` test — applied here too.
2956        //
2957        // 1s was tight enough that a loaded CI runner's PTY-reader-thread
2958        // scheduling delay alone could exceed it before `echo hello` ever
2959        // produced output — a genuine idle-kill by the test's own
2960        // (deliberately short) timeout, not the idle_rx/wait_task
2961        // misclassification race this test exists to catch. 3s keeps the
2962        // race window this test targets while giving scheduling enough
2963        // slack not to trip the timeout on its own.
2964        let _idle_timeout_guard = EnvVarGuard::set("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS", "3");
2965
2966        let bash = locate_bash().expect("locate_bash for test — same dependency the whole binary needs");
2967
2968        for i in 0..30 {
2969            let pty_system = native_pty_system();
2970            let pair = match pty_system.openpty(PtySize {
2971                rows: 24,
2972                cols: 80,
2973                pixel_width: 0,
2974                pixel_height: 0,
2975            }) {
2976                Ok(p) => p,
2977                Err(e) => {
2978                    eprintln!("skipping: PTY unavailable in this environment: {e}");
2979                    break;
2980                }
2981            };
2982            let args = Args {
2983                tool_id: format!("test-fast-success-{i}"),
2984                b64_cmd: String::new(),
2985                block_id: None,
2986                declared_background: false,
2987                agent: None,
2988                agent_unknown: false,
2989            };
2990            let buffered = Arc::new(tokio::sync::Mutex::new(Vec::<u8>::new()));
2991
2992            let result = tokio::time::timeout(
2993                Duration::from_secs(10),
2994                run_via_pty(&args, "echo hello", None, buffered.clone(), &bash, pair),
2995            )
2996            .await
2997            .unwrap_or_else(|_| panic!("iteration {i}: run_via_pty must not hang on a trivial fast command"))
2998            .unwrap_or_else(|e| panic!("iteration {i}: run_via_pty errored: {e}"));
2999
3000            assert_eq!(
3001                result, 0,
3002                "iteration {i}: a fast, genuinely successful `echo` must report clean exit 0, \
3003                 not get spuriously classified as idle-killed by the idle_rx/wait_task race"
3004            );
3005            let blob = String::from_utf8_lossy(&buffered.lock().await).into_owned();
3006            assert!(
3007                !blob.contains("terminated automatically"),
3008                "iteration {i}: fast successful command must not carry the idle-kill \
3009                 diagnostic — got blob: {blob:?}"
3010            );
3011            assert!(
3012                blob.contains("hello"),
3013                "iteration {i}: expected the command's real output in the blob, got: {blob:?}"
3014            );
3015        }
3016    }
3017
3018    /// Issue #2491: a declared-background call (`declared_background:
3019    /// true`, threaded from the CLI's own `run_in_background: true`) must
3020    /// be exempt from the idle-kill safety net — it may legitimately go
3021    /// silent past the timeout window (a GUI window, a dev server) without
3022    /// that meaning it's stuck. Uses a 1s idle timeout and a command silent
3023    /// for 3s (3x the timeout) so a non-exempt call would provably be
3024    /// killed well before this test's own bound — proves the exemption is
3025    /// doing something, not merely that idle-kill didn't happen to fire.
3026    #[tokio::test]
3027    async fn run_via_pty_skips_idle_kill_when_declared_background() {
3028        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
3029        let _idle_timeout_guard = EnvVarGuard::set("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS", "1");
3030
3031        let bash = locate_bash().expect("locate_bash for test — same dependency the whole binary needs");
3032        let pty_system = native_pty_system();
3033        let pair = match pty_system.openpty(PtySize {
3034            rows: 24,
3035            cols: 80,
3036            pixel_width: 0,
3037            pixel_height: 0,
3038        }) {
3039            Ok(p) => p,
3040            Err(e) => {
3041                eprintln!("skipping: PTY unavailable in this environment: {e}");
3042                return;
3043            }
3044        };
3045        let args = Args {
3046            tool_id: "test-declared-background".to_string(),
3047            b64_cmd: String::new(),
3048            block_id: None,
3049            declared_background: true,
3050            agent: None,
3051            agent_unknown: false,
3052        };
3053        let buffered = Arc::new(tokio::sync::Mutex::new(Vec::<u8>::new()));
3054
3055        let result = tokio::time::timeout(
3056            Duration::from_secs(10),
3057            run_via_pty(&args, "sleep 3 && echo done", None, buffered.clone(), &bash, pair),
3058        )
3059        .await
3060        .expect("a declared-background call must not hang past the outer test timeout")
3061        .expect("run_via_pty should return Ok");
3062
3063        assert_eq!(
3064            result, 0,
3065            "a declared-background command silent past the idle-timeout window must still run \
3066             to completion, not get idle-killed — exit code was {result}"
3067        );
3068        let blob = String::from_utf8_lossy(&buffered.lock().await).into_owned();
3069        assert!(
3070            blob.contains("done"),
3071            "expected the command's real output after surviving the idle window, got: {blob:?}"
3072        );
3073        assert!(
3074            !blob.contains("terminated automatically"),
3075            "declared-background call must never carry the idle-kill diagnostic — got: {blob:?}"
3076        );
3077    }
3078
3079    /// End-to-end proof of A1 against a REAL PTY + bash, reproducing the
3080    /// exact bug SPEC_TOOL_LOG_UNIVERSAL_ANIMATION_COLLAPSE_2026_07_27.md
3081    /// closes: a static label printed with no `\r`, a pause past the
3082    /// quiet-window, then a `\r`-prefixed overwrite. Before A1, the label
3083    /// was already flushed as its own permanent LineEvent by the time the
3084    /// overwrite arrived, so the model-visible blob contained the label
3085    /// TWICE ("Installing deps..." followed by "Installing deps... done").
3086    ///
3087    /// The pause is deliberately tuned to land INSIDE A1's one-extra-tick
3088    /// window: greater than one `FLUSH_QUIET_WINDOW` (50ms, so the label is
3089    /// actually deferred rather than merged inline on the same read) but
3090    /// less than two (100ms, the point at which A1 gives up waiting and
3091    /// flushes the deferred line anyway per the spec's own "no added
3092    /// latency beyond one extra tick" scope). 70ms centers comfortably
3093    /// inside that ~50ms window in isolation, but real OS thread scheduling
3094    /// still occasionally pushes either boundary under load (observed: this
3095    /// test flaked ~1 run in 6 in the full-suite parallel run, though never
3096    /// in isolation) — `FLUSH_QUIET_WINDOW` is a hardcoded const with no
3097    /// test-only override, so retrying the wall-clock scenario a few times
3098    /// (same "widen the chance" philosophy already used by
3099    /// `run_via_pty_does_not_misclassify_fast_success_as_idle_timeout`
3100    /// above, just applied to reliably demonstrate a real behavior instead
3101    /// of reliably catching a rare regression) is more honest than either a
3102    /// single flaky assertion or silently loosening what's being proven.
3103    #[tokio::test]
3104    async fn a1_e2e_static_label_then_delayed_cr_overwrite_collapses_to_one_line() {
3105        let bash = locate_bash().expect("locate_bash for test — same dependency the whole binary needs");
3106        let command = "printf 'Installing deps...'; sleep 0.07; printf '\\rInstalling deps... done\\n'";
3107
3108        // reagentx P2 on PR #2569: a hung/slow attempt used to be retried by
3109        // wrapping `run_via_pty` in an EXTERNAL `tokio::time::timeout` and
3110        // `continue`ing past the deadline. That leaked a process: dropping
3111        // the outer future does NOT abort `wait_task`/`pty_reader_loop`
3112        // (independent `spawn_blocking` tasks already running by the time
3113        // the timeout could preempt anything), so the underlying bash/PTY
3114        // child from the timed-out attempt kept running detached — up to
3115        // MAX_ATTEMPTS - 1 of them per flaky run, none ever cleaned up.
3116        //
3117        // `run_via_pty` already has a CORRECT internal kill path for exactly
3118        // "this attempt is stuck": its idle-timeout branch tree-kills the
3119        // child (via `kill_process_tree` + `clone_killer`) and returns exit
3120        // code 124 BEFORE returning at all. Rather than fight that with a
3121        // second, incomplete external timeout, lower its threshold for this
3122        // test (well above what this ~70ms command legitimately needs, but
3123        // short enough to bound a genuinely stuck attempt) and let
3124        // `run_via_pty` clean up after itself before this test ever sees
3125        // control back — no external timeout, no orphan.
3126        let _env_guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
3127        // reagentx P2 on PR #2569 (re-review): a manual save-now/restore-
3128        // at-the-end dance doesn't run on an early exit — `Err(e) =>
3129        // panic!(...)` and the `assert_eq!` below can both unwind straight
3130        // out of the loop, skipping the restore and leaving this env var
3131        // permanently set to "15" for the rest of the test binary process.
3132        // `EnvVarGuard` (used elsewhere in this file for exactly this
3133        // reason) restores it in `Drop`, which runs on every exit path
3134        // including a panic unwind.
3135        let _idle_timeout_guard = EnvVarGuard::set("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS", "15");
3136
3137        const MAX_ATTEMPTS: u32 = 5;
3138        // reagentx P2 on PR #2559 (re-review): must be updated on EVERY
3139        // retry path, not just the occurrence-mismatch one — the idle-kill
3140        // branch below used to leave this at its initial empty value, so if
3141        // every attempt got idle-killed the final panic misleadingly
3142        // reported an empty blob instead of indicating a timeout occurred.
3143        let mut last_outcome = String::new();
3144        let mut collapsed = false;
3145        let mut skipped = false;
3146        for attempt in 1..=MAX_ATTEMPTS {
3147            let pty_system = native_pty_system();
3148            let pair = match pty_system.openpty(PtySize {
3149                rows: 24,
3150                cols: 80,
3151                pixel_width: 0,
3152                pixel_height: 0,
3153            }) {
3154                Ok(p) => p,
3155                Err(e) => {
3156                    eprintln!("skipping: PTY unavailable in this environment: {e}");
3157                    skipped = true;
3158                    break;
3159                }
3160            };
3161            let args = Args {
3162                tool_id: format!("test-a1-e2e-{attempt}"),
3163                b64_cmd: String::new(),
3164                block_id: None,
3165                declared_background: false,
3166                agent: None,
3167                agent_unknown: false,
3168            };
3169            let buffered = Arc::new(tokio::sync::Mutex::new(Vec::<u8>::new()));
3170
3171            let result = match run_via_pty(&args, command, None, buffered.clone(), &bash, pair).await {
3172                Ok(r) => r,
3173                Err(e) => panic!("run_via_pty should return Ok, got: {e}"),
3174            };
3175            if result == 124 {
3176                // Idle-killed by run_via_pty's own internal mechanism — the
3177                // process tree is already cleaned up by the time this
3178                // returns, nothing left behind to leak.
3179                last_outcome = format!("attempt {attempt}/{MAX_ATTEMPTS}: idle-killed by run_via_pty \
3180                    (likely a loaded CI runner delaying process spawn/scheduling), no output captured");
3181                eprintln!(
3182                    "{last_outcome} — retrying, already cleaned up"
3183                );
3184                continue;
3185            }
3186            if result != 0 {
3187                // Retried for the same reason 124 is, immediately above: on a
3188                // loaded runner bash can fail to start cleanly, and from here
3189                // that is indistinguishable from being idle-killed.
3190                //
3191                // This was `assert_eq!(result, 0, "command should exit cleanly")`,
3192                // which failed the whole test on attempt 1 and bypassed
3193                // MAX_ATTEMPTS entirely. The retry loop existed but covered only
3194                // two of the three flaky outcomes, and the one it missed is the
3195                // one that fired — exit 1, failing a docs-only PR that touched
3196                // no Rust at all (issue #2916). A retry loop that does not cover
3197                // the case that actually happens is decoration.
3198                //
3199                // A genuinely broken build still fails: every one of
3200                // MAX_ATTEMPTS must exit nonzero, and the panic below reports
3201                // the last outcome, which a bare assert_eq! never did.
3202                last_outcome = format!(
3203                    "attempt {attempt}/{MAX_ATTEMPTS}: command exited {result}, expected 0 \
3204                     (likely a loaded CI runner failing to spawn bash cleanly)"
3205                );
3206                eprintln!("{last_outcome} — retrying");
3207                continue;
3208            }
3209
3210            let blob = String::from_utf8_lossy(&buffered.lock().await).into_owned();
3211            let occurrences = blob.matches("Installing deps").count();
3212            if occurrences == 1 && blob.contains("Installing deps... done") {
3213                collapsed = true; // demonstrated: the collapse happened as designed
3214                break;
3215            }
3216            last_outcome = format!(
3217                "attempt {attempt}/{MAX_ATTEMPTS}: expected 1 occurrence + the settled frame, \
3218                 got {occurrences} occurrence(s) — blob: {blob:?}"
3219            );
3220            eprintln!(
3221                "{last_outcome} (retrying: real OS scheduling can occasionally push the 70ms \
3222                 pause outside A1's ~50-100ms defer window)"
3223            );
3224        }
3225
3226        if skipped || collapsed {
3227            return;
3228        }
3229        panic!(
3230            "the static label + its delayed \\r-overwrite must collapse to ONE occurrence across \
3231             {MAX_ATTEMPTS} attempts — last outcome: {last_outcome}"
3232        );
3233    }
3234}