Skip to main content

kaish_kernel/
dispatch.rs

1//! Command dispatch — the single execution path for all commands.
2//!
3//! The `CommandDispatcher` trait defines how a single command is resolved and
4//! executed. The Kernel implements this trait with the full dispatch chain:
5//! user tools → builtins → .kai scripts → external commands → backend tools.
6//!
7//! `PipelineRunner` calls `dispatcher.dispatch()` for each command in a
8//! pipeline, handling I/O routing (stdin piping, redirects) around each call.
9//!
10//! ```text
11//! Stmt::Command ──┐
12//!                  ├──▶ execute_pipeline() ──▶ PipelineRunner::run(dispatcher, commands, ctx)
13//! Stmt::Pipeline ──┘                                  │
14//!                                               for each command:
15//!                                                 dispatcher.dispatch(cmd, ctx)
16//!                                                     │
17//!                                               ┌─────┼──────────────┐
18//!                                               │     │              │
19//!                                          user_tools builtins  .kai scripts
20//!                                                                external cmds
21//!                                                                backend tools
22//! ```
23
24use std::sync::Arc;
25
26use anyhow::Result;
27use async_trait::async_trait;
28
29use crate::ast::{Command, Expr, Stmt, Value};
30use crate::interpreter::ExecResult;
31use crate::tools::ExecContext;
32#[cfg(test)]
33use crate::tools::{
34    external_commands_unavailable_error, ExternalCommandOutcome, ExternalCommandsUnavailable,
35};
36
37// The following imports are only used by the test-only `BackendDispatcher`.
38#[cfg(test)]
39use crate::ast::Arg;
40#[cfg(test)]
41use crate::backend::BackendError;
42#[cfg(test)]
43use crate::interpreter::apply_output_format;
44#[cfg(test)]
45use crate::scheduler::build_tool_args;
46#[cfg(test)]
47use crate::tools::{GlobalFlags, ToolRegistry};
48#[cfg(all(test, feature = "subprocess"))]
49use crate::tools::{resolve_in_path, virtual_cwd_error};
50
51/// Arm `PR_SET_PDEATHSIG(SIGKILL)` in a freshly forked child, so the OS kills
52/// it the moment `parent_pid` dies — for any reason, including `kill -9`, a
53/// segfault, or an OOM kill, none of which let the parent run a single
54/// instruction of cleanup. This is the one orphan guard that does not depend
55/// on `setpgid` + a pidfd kill, `kill_on_drop`, or any other code of ours
56/// getting to run.
57///
58/// **Call only between fork and exec.** `prctl` and `getppid` are both
59/// async-signal-safe per POSIX, which is what makes that legal.
60///
61/// The `getppid` check closes `PR_SET_PDEATHSIG`'s documented race: if the
62/// parent dies in the window between `fork` and the `prctl` above, the signal
63/// is armed against a parent that is already gone and will never be delivered
64/// — the exact orphan the flag exists to prevent, in the exact window it is
65/// hardest to notice. Comparing against the pid the parent captured *before*
66/// forking detects it, and failing the `pre_exec` fails the spawn loudly
67/// rather than exec'ing a process nothing will ever reap.
68///
69/// Linux only. macOS has no equivalent that works without a live watcher
70/// process, so this is compiled out there rather than faked with something
71/// weaker — see `KernelConfig::kill_children_on_parent_death`.
72#[cfg(all(unix, feature = "subprocess"))]
73pub(crate) fn arm_parent_death_signal(parent_pid: u32) -> std::io::Result<()> {
74    #[cfg(target_os = "linux")]
75    {
76        nix::sys::prctl::set_pdeathsig(nix::sys::signal::Signal::SIGKILL)
77            .map_err(|e| std::io::Error::from_raw_os_error(e as i32))?;
78
79        if nix::unistd::getppid().as_raw() as u32 != parent_pid {
80            return Err(std::io::Error::other(
81                "parent died before the parent-death signal was armed",
82            ));
83        }
84    }
85    #[cfg(not(target_os = "linux"))]
86    let _ = parent_pid;
87    Ok(())
88}
89
90/// Position of a command within a pipeline.
91///
92/// Used by external command execution to decide stdio inheritance:
93/// - `Only` or `Last` in interactive mode → inherit terminal
94/// - `First` or `Middle` → always capture
95///
96/// Not `#[non_exhaustive]`, deliberately: kaish pipelines are a strictly
97/// linear chain of stages, so these four variants exhaust every position a
98/// stage can occupy. A fifth would mean pipelines stopped being linear — a
99/// grammar change, not a variant this enum grows on its own.
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
101pub enum PipelinePosition {
102    /// Single command, no pipe.
103    #[default]
104    Only,
105    /// First command in a pipeline (no stdin from pipe).
106    First,
107    /// Middle of a pipeline (piped stdin, piped stdout).
108    Middle,
109    /// Last command in a pipeline (piped stdin, final output).
110    Last,
111}
112
113/// Trait for dispatching a single command through the full resolution chain.
114///
115/// Implementations handle argument parsing, tool lookup, and execution.
116/// The pipeline runner handles I/O routing (stdin, redirects, piping).
117#[async_trait]
118pub trait CommandDispatcher: Send + Sync {
119    /// Dispatch a single command for execution.
120    ///
121    /// The `ctx` provides stdin (from pipe or redirect), scope, and backend.
122    /// Implementations should handle schema-aware argument parsing and
123    /// output format extraction internally.
124    async fn dispatch(&self, cmd: &Command, ctx: &mut ExecContext) -> Result<ExecResult>;
125
126    /// Dispatch a compound statement (`if`, `for`, `while`, `case`) that sits
127    /// in a pipeline stage.
128    ///
129    /// The statement runs to completion and its whole output comes back in the
130    /// `ExecResult`; `PipelineRunner` then writes those bytes to the pipe. So
131    /// `ctx.pipe_stdout` must stay with the runner — hand it to the statement
132    /// and the first nested command inside it would take the writer and the
133    /// rest of the loop would write nowhere.
134    ///
135    /// The default rejects the form. Only a dispatcher that can execute a
136    /// whole statement (the `Kernel`) overrides it; a dispatcher that resolves
137    /// one command at a time has nothing to run a loop body with, and saying
138    /// so beats returning empty output at exit 0.
139    async fn dispatch_stmt(&self, _stmt: &Stmt, _ctx: &mut ExecContext) -> Result<ExecResult> {
140        anyhow::bail!("this dispatcher cannot run a compound statement in a pipeline stage")
141    }
142
143    /// Evaluate an expression through the full async chain.
144    ///
145    /// Unlike the runner's sync `eval_simple_expr`, this can run command
146    /// substitution (`$(...)`) because it has access to pipeline execution.
147    /// Used for redirect targets and heredoc bodies so `cat < $(cmd)`,
148    /// `echo x > $(cmd)`, and `$(...)` inside heredoc bodies work. The `ctx`
149    /// carries scope/cwd/backend for dispatchers that evaluate against it;
150    /// stateful dispatchers (Kernel) snapshot their own session state and
151    /// only let command output escape (side effects like `cd` do not).
152    async fn eval_expr(&self, expr: &Expr, ctx: &ExecContext) -> Result<Value>;
153
154    /// Fork the dispatcher for concurrent execution (detached).
155    ///
156    /// Returns a subsidiary dispatcher with independent mutable state, safe
157    /// to run concurrently with the parent and other forks without data
158    /// races on shared scope/cwd/aliases. Used by background `&` jobs,
159    /// where the fork must survive parent cancellation.
160    ///
161    /// For stateful dispatchers (e.g. Kernel) this snapshots per-session
162    /// state into a fresh instance. Stateless dispatchers may clone.
163    async fn fork(&self) -> Arc<dyn CommandDispatcher>;
164
165    /// Fork the dispatcher for concurrent execution (attached to parent cancel).
166    ///
167    /// Like [`Self::fork`] but the fork's cancellation token is a *child* of
168    /// the parent's. Cancelling the parent (timeout, Ctrl-C, embedder
169    /// `Kernel::cancel`) cascades into the fork, which then kills its own
170    /// external children via the usual SIGTERM/SIGKILL discipline.
171    ///
172    /// Used for foreground concurrency: scatter workers, concurrent pipeline
173    /// stages, command substitution. Default implementation delegates to
174    /// [`Self::fork`] for stateless dispatchers that don't track cancellation.
175    async fn fork_attached(&self) -> Arc<dyn CommandDispatcher> {
176        self.fork().await
177    }
178}
179
180/// Minimal stateless dispatcher used by pipeline/runner unit tests.
181///
182/// Production code uses `Kernel` (via `Kernel::fork` for concurrent contexts).
183/// This test-only dispatcher routes directly through `backend.call_tool()` so
184/// the pipeline runner can be exercised without spinning up a full Kernel.
185///
186/// Limitations (intentional — these are test-only constraints):
187/// - No user-defined tools
188/// - No .kai script resolution
189/// - No async argument evaluation (command substitution in args won't work)
190#[cfg(test)]
191pub(crate) struct BackendDispatcher {
192    tools: Arc<ToolRegistry>,
193}
194
195#[cfg(test)]
196impl BackendDispatcher {
197    /// Create a new backend dispatcher with the given tool registry.
198    pub(crate) fn new(tools: Arc<ToolRegistry>) -> Self {
199        Self { tools }
200    }
201
202    /// Try to execute an external command (PATH lookup + process spawn).
203    ///
204    /// Used as fallback when no builtin/backend tool matches. `Unavailable`
205    /// if kaish will not attempt this at all (kept in sync with
206    /// kernel.rs::try_execute_external — see `ExternalCommandOutcome`).
207    /// Always captures stdout/stderr (never inherits terminal — pipeline
208    /// stages don't need interactive I/O).
209    #[cfg(not(feature = "subprocess"))]
210    async fn try_external(
211        &self,
212        _name: &str,
213        _args: &[Arg],
214        _ctx: &mut ExecContext,
215    ) -> ExternalCommandOutcome {
216        ExternalCommandOutcome::Unavailable(ExternalCommandsUnavailable::NotCompiled)
217    }
218
219    /// Try to execute an external command (PATH lookup + process spawn).
220    #[cfg(feature = "subprocess")]
221    async fn try_external(
222        &self,
223        name: &str,
224        args: &[Arg],
225        ctx: &mut ExecContext,
226    ) -> ExternalCommandOutcome {
227        if !ctx.allow_external_commands {
228            return ExternalCommandOutcome::Unavailable(ExternalCommandsUnavailable::ConfiguredOff);
229        }
230        match self.try_external_on_path(name, args, ctx).await {
231            Some(result) => ExternalCommandOutcome::Ran(Box::new(result)),
232            None => ExternalCommandOutcome::NotFound,
233        }
234    }
235
236    /// The actual PATH lookup + spawn, once the caller has confirmed
237    /// external commands are allowed at all — kept in sync with
238    /// kernel.rs::try_execute_external_on_path.
239    #[cfg(feature = "subprocess")]
240    async fn try_external_on_path(
241        &self,
242        name: &str,
243        args: &[Arg],
244        ctx: &mut ExecContext,
245    ) -> Option<ExecResult> {
246        // Real filesystem location of the shell's cwd, if any. A `None` real
247        // path means the cwd is virtual (a CoW overlay, an in-memory VFS
248        // mount, …) — there's nowhere for a child OS process to run. Don't
249        // bail out here: a bare command name that isn't in PATH at all is a
250        // genuine "not found" regardless of cwd. Once the command actually
251        // resolves, `real_cwd` is checked again below and the honest reason
252        // is given then — kept in sync with kernel.rs::try_execute_external
253        // (issue #181).
254        let real_cwd = ctx.backend.resolve_real_path(&ctx.cwd);
255
256        // Resolve command: absolute/relative path or PATH lookup
257        let executable = if name.contains('/') {
258            // Resolve relative paths (./script, ../bin/tool) against the shell's cwd
259            let resolved = if std::path::Path::new(name).is_absolute() {
260                std::path::PathBuf::from(name)
261            } else {
262                match &real_cwd {
263                    Some(real_cwd) => real_cwd.join(name),
264                    // Can't resolve a relative path without a real cwd to
265                    // join against, so we can't even tell whether it would
266                    // exist — name the actual blocker.
267                    None => return Some(virtual_cwd_error(name, &ctx.cwd)),
268                }
269            };
270            // Kept in sync with kernel.rs::try_execute_external (issue
271            // #229): `exists()` alone isn't enough — a directory or a
272            // non-executable file both "exist" but must fail with the
273            // clean, documented exit-126 class instead of falling through
274            // to `Command::spawn()` and leaking whatever raw OS error comes
275            // back (e.g. "Permission denied (os error 13)" under exit 127).
276            if !resolved.exists() {
277                return Some(ExecResult::failure(127, format!("{}: No such file or directory", name)));
278            }
279            if !resolved.is_file() {
280                return Some(ExecResult::failure(126, format!("{}: Is a directory", name)));
281            }
282            #[cfg(unix)]
283            {
284                use std::os::unix::fs::PermissionsExt;
285                let mode = std::fs::metadata(&resolved)
286                    .map(|m| m.permissions().mode())
287                    .unwrap_or(0);
288                if mode & 0o111 == 0 {
289                    return Some(ExecResult::failure(126, format!("{}: Permission denied", name)));
290                }
291            }
292            resolved.to_string_lossy().into_owned()
293        } else {
294            // PATH from scope only — never OS env (keeps this test-only spawn
295            // site in sync with kernel.rs::try_execute_external).
296            let path_var = ctx.scope.get("PATH")
297                .map(crate::interpreter::value_to_string)
298                .unwrap_or_default();
299            resolve_in_path(name, &path_var)?
300        };
301
302        // The executable resolved — found in PATH, or a path that exists —
303        // but there's still nowhere to run it without a real cwd.
304        let real_cwd = match real_cwd {
305            Some(p) => p,
306            None => return Some(virtual_cwd_error(name, &ctx.cwd)),
307        };
308
309        // Build flat argv from args. A for-loop (not filter_map) so the
310        // Decision D collection-argv guard can short-circuit the whole spawn
311        // — kept in sync with the production build in kernel.rs::build_args_flat.
312        let mut argv: Vec<String> = Vec::new();
313        for arg in args {
314            match arg {
315                Arg::Positional(expr) => match expr {
316                    Expr::Literal(Value::String(s)) => argv.push(s.clone()),
317                    Expr::Literal(Value::Int(i)) => argv.push(i.to_string()),
318                    Expr::Literal(Value::Float(f)) => argv.push(f.to_string()),
319                    Expr::VarRef(path) => {
320                        if let Ok(v) = ctx.scope.resolve_path(path) {
321                            if let Some(msg) = crate::interpreter::structured_boundary_error("a command argument", &v) {
322                                return Some(ExecResult::failure(1, msg));
323                            }
324                            // Text sink: binary goes loud (kept in sync with
325                            // kernel.rs::build_args_flat).
326                            match crate::interpreter::value_to_text_sink(&v) {
327                                Ok(s) => argv.push(s),
328                                Err(e) => return Some(ExecResult::failure(1, e.to_string())),
329                            }
330                        }
331                    }
332                    // Remaining literal types (Bool/Json/Null/Bytes) — kept in
333                    // sync with the production build_args_flat, which resolves
334                    // every positional through value_to_text_sink (binary loud).
335                    Expr::Literal(other) => match crate::interpreter::value_to_text_sink(other) {
336                        Ok(s) => argv.push(s),
337                        Err(e) => return Some(ExecResult::failure(1, e.to_string())),
338                    },
339                    _ => {}
340                },
341                Arg::ShortFlag(f) => argv.push(format!("-{f}")),
342                Arg::LongFlag(f) => argv.push(format!("--{f}")),
343                Arg::Named { key, value } => match value {
344                    Expr::Literal(Value::String(s)) => argv.push(format!("--{key}={s}")),
345                    _ => argv.push(format!("--{key}=")),
346                },
347                Arg::WordAssign { key, value } => match value {
348                    Expr::Literal(Value::String(s)) => argv.push(format!("{key}={s}")),
349                    _ => argv.push(format!("{key}=")),
350                },
351                Arg::DoubleDash => argv.push("--".to_string()),
352            }
353        }
354
355        // Check for streaming pipes
356        let has_pipe_stdin = ctx.pipe_stdin.is_some();
357        let has_buffered_stdin = ctx.stdin.is_some();
358
359        // Spawn process
360        use tokio::process::Command;
361        use tokio::io::{AsyncReadExt, AsyncWriteExt};
362
363        let mut cmd = Command::new(&executable);
364        cmd.args(&argv);
365        cmd.current_dir(&real_cwd);
366        cmd.kill_on_drop(true);
367
368        // Hermetic env: child sees only kaish's exported vars, not the kaish
369        // process's OS env. Frontends that want OS-env passthrough (REPL, MCP)
370        // populate it via KernelConfig::initial_vars at construction.
371        cmd.env_clear();
372        let exported = ctx.scope.exported_vars();
373        // A structured value can't cross the process boundary; refuse rather than
374        // silently JSON-serialize it into the child's environment. Kept in sync
375        // with the production spawn site in kernel.rs::try_execute_external.
376        if let Some(msg) = crate::interpreter::structured_export_error(&exported) {
377            return Some(ExecResult::failure(1, msg));
378        }
379        for (var_name, value) in exported {
380            // Binary can't cross the process boundary as an env var value
381            // either — loud, not the `[binary: N bytes]` placeholder (kept in
382            // sync with the production spawn site).
383            match crate::interpreter::value_to_text_sink_named(
384                &value,
385                "an exported environment variable value",
386            ) {
387                Ok(s) => {
388                    cmd.env(var_name, s);
389                }
390                Err(e) => return Some(ExecResult::failure(1, e.to_string())),
391            }
392        }
393
394        // Stdin: pipe_stdin or buffered bytes or inherit (interactive) or null
395        cmd.stdin(if has_pipe_stdin || has_buffered_stdin {
396            std::process::Stdio::piped()
397        } else if ctx.interactive && matches!(ctx.pipeline_position, PipelinePosition::First | PipelinePosition::Only) {
398            std::process::Stdio::inherit()
399        } else {
400            std::process::Stdio::null()
401        });
402        cmd.stdout(std::process::Stdio::piped());
403        cmd.stderr(std::process::Stdio::piped());
404
405        // On Unix, always put the child in its own process group so a
406        // cancel can `killpg` the whole tree (the child plus any
407        // grandchildren) — matching the production spawn site
408        // (kernel.rs::try_execute_external) exactly. Without this, `killpg`
409        // targets a group nobody is actually in (an ESRCH no-op), and a
410        // grandchild spawned by the child survives cancellation — the exact
411        // gap GH #133 item 4 closes. This dispatcher has no job-control
412        // terminal integration (no `terminal_state`), so unlike production
413        // there is no signal-handler restoration to gate here.
414        #[cfg(unix)]
415        {
416            let kill_on_parent_death = ctx.kill_children_on_parent_death;
417            let parent_pid = std::process::id();
418            // SAFETY: setpgid, prctl, and getppid are async-signal-safe per
419            // POSIX; safe to call between fork and exec.
420            #[allow(unsafe_code)]
421            unsafe {
422                cmd.pre_exec(move || {
423                    nix::unistd::setpgid(nix::unistd::Pid::from_raw(0), nix::unistd::Pid::from_raw(0))
424                        .map_err(|e| std::io::Error::from_raw_os_error(e as i32))?;
425                    if kill_on_parent_death {
426                        arm_parent_death_signal(parent_pid)?;
427                    }
428                    Ok(())
429                });
430            }
431        }
432
433        let mut child = match cmd.spawn() {
434            Ok(c) => c,
435            Err(e) => return Some(ExecResult::failure(127, format!("{}: {}", name, e))),
436        };
437        // Open a pidfd (Linux) for race-free direct-child kill via wait_or_kill.
438        let kill_target = crate::pidfd::KillTarget::from_child(&child);
439
440        // Stream stdin: copy pipe_stdin → child stdin in chunks (bounded memory)
441        let stdin_task: Option<tokio::task::JoinHandle<()>> = if let Some(mut pipe_in) = ctx.pipe_stdin.take() {
442            let prefix = ctx.stdin.take();
443            child.stdin.take().map(|mut child_stdin| {
444                tokio::spawn(async move {
445                    // A buffered prefix and a live pipe are one stream, not two
446                    // candidates — see the same reasoning in
447                    // `kernel.rs::try_execute_external`, which this twin mirrors.
448                    if let Some(data) = prefix
449                        && child_stdin.write_all(&data).await.is_err()
450                    {
451                        return; // child closed stdin; drop signals EOF
452                    }
453                    let mut buf = [0u8; 8192];
454                    loop {
455                        match pipe_in.read(&mut buf).await {
456                            Ok(0) => break, // EOF
457                            Ok(n) => {
458                                if child_stdin.write_all(&buf[..n]).await.is_err() {
459                                    break; // child closed stdin
460                                }
461                            }
462                            Err(_) => break,
463                        }
464                    }
465                    // Drop child_stdin signals EOF to child
466                })
467            })
468        } else if let Some(data) = ctx.stdin.take() {
469            // Buffered stdin bytes written from a DETACHED task, not inline:
470            // an inline write deadlocks once the stdin pipe fills before the
471            // output drain below has spawned (mirrors the kernel.rs fix; keeps
472            // the two spawn sites in sync). Drop signals EOF; a broken pipe
473            // (child closed stdin early) is fine.
474            child.stdin.take().map(|mut child_stdin| {
475                tokio::spawn(async move {
476                    let _ = child_stdin.write_all(&data).await;
477                })
478            })
479        } else {
480            None
481        };
482
483        // Capture stdout via the spill-aware collector, regardless of whether
484        // this is a pipeline stage (`ctx.pipe_stdout` set) or the last/only
485        // stage. This intentionally does NOT special-case `ctx.pipe_stdout`
486        // — production's `try_execute_external` never touches that field at
487        // all; a middle/first pipeline stage's forwarding to the next stage
488        // is entirely `PipelineRunner::run_pipeline`'s job (pipeline.rs),
489        // which reads `stage_ctx.pipe_stdout` (still `Some`, untouched here)
490        // after `dispatch()` returns and forwards `result.out` itself.
491        //
492        // Before this fix, this dispatcher special-cased `pipe_stdout` and
493        // streamed the child's stdout straight through in 8KB chunks — full
494        // fidelity, no cap. Production has no such fast path: every external
495        // stage's stdout is captured here first, then forwarded by the
496        // runner, so a >10MB intermediate stage silently loses its head in
497        // production (the runner's forward goes through the SAME capture,
498        // still true after this fix — see GH #133 item 2 for the capture
499        // primitive itself). Losing the pipe_stdout special case is what lets
500        // a test reproduce that production bug class at all (GH #133 item 3).
501        let Some(child_stdout) = child.stdout.take() else {
502            return Some(ExecResult::failure(1, "internal: stdout not available"));
503        };
504        let Some(mut child_stderr) = child.stderr.take() else {
505            return Some(ExecResult::failure(1, "internal: stderr not available"));
506        };
507
508        // Capture stdout into a fixed 10MB tail-evicting ring (`BoundedStream`
509        // + `drain_to_stream`) — the SAME capture primitive the production
510        // spawn site uses (kernel.rs::try_execute_external), not the
511        // limit-aware `spill_aware_collect` this used to call. Production
512        // does not spill-check an external command's own capture inline
513        // against `ctx.output_limit`; the pipeline-level post-hoc
514        // `spill_if_needed` (`Kernel::execute_pipeline`) is what applies that
515        // afterward, and `did_spill` is left `false` here for THAT reason — a
516        // caller wanting the limit-aware post-hoc behavior applies it
517        // separately, same as the real pipeline path (GH #133 item 2).
518        // Independently, `did_spill` CAN still end up `true` below: if the
519        // ring itself overflows (unconditionally, regardless of
520        // `ctx.output_limit`), that's the GH #191 loud-overflow signal, not
521        // the limit-aware spill this comment is about.
522        let stdout_stream = Arc::new(crate::scheduler::BoundedStream::new(
523            crate::scheduler::DEFAULT_STREAM_MAX_SIZE,
524        ));
525        let stdout_clone = stdout_stream.clone();
526        let stdout_task = tokio::spawn(async move {
527            crate::scheduler::drain_to_stream(child_stdout, stdout_clone).await;
528        });
529
530        // Stderr streaming is intentionally left as-is (live to
531        // `ctx.stderr` when present, else buffered) — production instead
532        // caps stderr into its own 10MB ring with no live streaming. That
533        // divergence is out of scope for this PR; see GH #133 follow-ups.
534        let stderr_stream_handle = ctx.stderr.clone();
535        let stderr_task = tokio::spawn(async move {
536            let mut buf = Vec::new();
537            let mut chunk = [0u8; 8192];
538            loop {
539                match child_stderr.read(&mut chunk).await {
540                    Ok(0) => break,
541                    Ok(n) => {
542                        if let Some(ref stream) = stderr_stream_handle {
543                            stream.write(&chunk[..n]);
544                        } else {
545                            buf.extend_from_slice(&chunk[..n]);
546                        }
547                    }
548                    Err(_) => break,
549                }
550            }
551            if stderr_stream_handle.is_some() {
552                String::new()
553            } else {
554                String::from_utf8_lossy(&buf).into_owned()
555            }
556        });
557
558        let cancel = ctx.cancel.clone();
559        // Mirror production's cancel-aware drain handling: spawn the
560        // drains concurrently with the wait (not after collection
561        // completes) so a cancel can actually interrupt a still-running,
562        // still-silent child instead of blocking until it produces EOF.
563        let cancelled_before_wait = cancel.is_cancelled();
564        let status = crate::kernel::wait_or_kill(
565            &mut child,
566            kill_target.as_ref(),
567            &cancel,
568            std::time::Duration::from_secs(2),
569        ).await;
570        if let Some(task) = stdin_task { task.abort(); }
571        let mut stderr = if cancelled_before_wait || cancel.is_cancelled() {
572            // The child's pipes are gone; late output is lost but
573            // predictable death beats partial capture (same tradeoff
574            // production makes).
575            stdout_task.abort();
576            stderr_task.abort();
577            String::new()
578        } else {
579            let _ = stdout_task.await;
580            stderr_task.await.unwrap_or_default()
581        };
582
583        // Signal-death mapping (128+signal, e.g. SIGKILL→137) must match
584        // the production spawn site exactly — kept in sync via the shared
585        // `exit_code_from_status` helper (GH #133 item 1). A `wait_or_kill`
586        // I/O error (not a signal death) falls back to 1, same as before.
587        let code = match status {
588            Ok(s) => crate::kernel::exit_code_from_status(&s),
589            Err(_) => 1,
590        };
591        let stdout = stdout_stream.read().await;
592        // stdout came back as raw bytes: text if valid UTF-8, else a Bytes
593        // result (so `curl url`, `curl url > file.bin`, etc. keep binary intact).
594        let mut result = ExecResult::success_text_or_bytes(stdout).with_code(code);
595
596        // Mirror production's overflow signaling (GH #191) for the piece this
597        // twin actually shares with `kernel.rs::try_execute_external`: the
598        // stdout `BoundedStream` ring. Stderr here is captured differently
599        // from production (live-streamed to `ctx.stderr` when set, else an
600        // unbounded `Vec` — see the comment above `stderr_stream_handle`,
601        // GH #133 follow-up), so there is no stderr `BoundedStream` overflow
602        // to mirror; only the stdout side applies. `did_spill` stays `false`
603        // otherwise, matching `output_limit_is_not_applied_inline_matching_production`
604        // below — this is the fixed-ring overflow signal, not the
605        // limit-aware post-hoc spill Kernel::execute_pipeline applies.
606        if stdout_stream.has_overflowed().await {
607            let stats = stdout_stream.stats().await;
608            stderr = format!("{}{stderr}", stats.overflow_marker("stdout"));
609            result.did_spill = true;
610        }
611        result.err = stderr;
612        Some(result)
613    }
614}
615
616#[cfg(test)]
617#[async_trait]
618impl CommandDispatcher for BackendDispatcher {
619    async fn dispatch(&self, cmd: &Command, ctx: &mut ExecContext) -> Result<ExecResult> {
620        // Handle built-in true/false/: (`:` is another spelling of `true`)
621        match cmd.name.as_str() {
622            "true" | ":" => return Ok(ExecResult::success("")),
623            "false" => return Ok(ExecResult::failure(1, "")),
624            _ => {}
625        }
626
627        // Build tool args through the reduced sync evaluator (no command
628        // substitution) — see `SyncEvalSource` in `scheduler::pipeline`.
629        // A bad/subscripted collection access is a genuine PathError here too —
630        // propagate it via `?` rather than swallowing, same as the production
631        // Kernel::dispatch_command's `execute_command(..).await?`.
632        let schema = self.tools.get(&cmd.name).map(|t| t.schema());
633        let tool_args = build_tool_args(&cmd.args, ctx, schema.as_ref())
634            .await
635            .map_err(|e| anyhow::anyhow!(e))?;
636
637        // Honor --json before the tool runs so a parse failure inside the
638        // builtin doesn't drop the format on the floor. See kernel.rs for the
639        // matching call in the production path.
640        let raw_argv = schema.as_ref().is_some_and(|s| s.raw_argv);
641        GlobalFlags::apply_from_args(&tool_args, raw_argv, ctx);
642
643        // Execute via backend
644        let backend = ctx.backend.clone();
645        let result = match backend.call_tool(&cmd.name, tool_args, ctx).await {
646            // Route through the same `From<ToolResult> for ExecResult` the
647            // production dispatch path uses (kernel.rs) rather than
648            // hand-rolling the field-by-field copy: the old inline version
649            // wrapped `data` unconditionally as `Value::Json`, which skipped
650            // `json_to_value_no_envelope`'s scalar-unwrap (`Value::Int`/
651            // `Value::String`/…) and silently dropped `did_spill`/
652            // `original_code` — a divergence this test-only dispatcher must
653            // not have from the real path (GH #93 item 4).
654            Ok(tool_result) => ExecResult::from(tool_result),
655            Err(BackendError::ToolNotFound(_)) => {
656                // Fall back to external command execution. The backend
657                // registry already had its chance above, so — unlike the
658                // production path in kernel.rs, which tries external first —
659                // `Unavailable` is a final answer here, not something that
660                // needs to survive a later backend lookup.
661                match self.try_external(&cmd.name, &cmd.args, ctx).await {
662                    ExternalCommandOutcome::Ran(result) => *result,
663                    ExternalCommandOutcome::NotFound => {
664                        ExecResult::failure(127, format!("command not found: {}", cmd.name))
665                    }
666                    ExternalCommandOutcome::Unavailable(reason) => {
667                        external_commands_unavailable_error(&cmd.name, reason)
668                    }
669                }
670            }
671            Err(e) => ExecResult::failure(127, e.to_string()),
672        };
673
674        // Migrated builtins parse --json via the GlobalFlags flatten and
675        // write ctx.output_format. The kernel just applies it.
676        let result = match ctx.output_format {
677            Some(format) => apply_output_format(result, format),
678            None => result,
679        };
680
681        Ok(result)
682    }
683
684    /// Sync-only evaluation (no command substitution) — matches this
685    /// test dispatcher's documented "no async argument evaluation" limit.
686    async fn eval_expr(&self, expr: &Expr, ctx: &ExecContext) -> Result<Value> {
687        crate::scheduler::pipeline::eval_simple_expr(expr, ctx)
688            .map_err(|e| anyhow::anyhow!(e))?
689            .ok_or_else(|| anyhow::anyhow!("cannot evaluate expression in test dispatcher"))
690    }
691
692    /// BackendDispatcher is stateless, so a fork is just a clone.
693    async fn fork(&self) -> Arc<dyn CommandDispatcher> {
694        Arc::new(Self { tools: Arc::clone(&self.tools) })
695    }
696}
697
698/// Tests that spawn real external processes through `try_external`, to catch
699/// behavioral drift from the production spawn site (`kernel.rs::try_execute_external`)
700/// — GH #133. Unlike the `BackendDispatcher` tests in `scheduler::pipeline`,
701/// which exercise builtins over a `MemoryFs` (virtual cwd, so `try_external`
702/// never spawns), these give the dispatcher a real tempdir cwd + PATH so the
703/// external fallback actually runs a child process.
704#[cfg(all(test, feature = "subprocess"))]
705mod external_process_tests {
706    // Test-fixture helpers (not `#[test]` bodies themselves), so the
707    // workspace's usual allow-in-tests clippy.toml carve-out doesn't cover
708    // them — see CLAUDE.md's "clap builtin gotchas" / test-code conventions.
709    #![allow(clippy::unwrap_used, clippy::expect_used)]
710    use super::*;
711    use crate::ast::{Arg, Command, Expr, Value};
712    use crate::tools::{ExecContext, ToolRegistry};
713    use crate::vfs::{LocalFs, VfsRouter};
714
715    /// A `BackendDispatcher` + `ExecContext` rooted at a real tempdir, with an
716    /// empty tool registry (every command name falls through to
717    /// `try_external`, exactly like a real external command with no matching
718    /// builtin/user tool) and PATH seeded from the test process's own OS env.
719    /// Reading OS env here is fixture code, not kaish's hermetic runtime — see
720    /// CLAUDE.md and `external_command_tests.rs::repl_kernel`.
721    fn real_cwd_dispatcher() -> (BackendDispatcher, ExecContext, tempfile::TempDir) {
722        let dir = tempfile::tempdir().expect("tempdir");
723        let mut vfs = VfsRouter::new();
724        vfs.mount("/", LocalFs::new(dir.path().to_path_buf()));
725        let tools = Arc::new(ToolRegistry::new());
726        let mut ctx = ExecContext::with_vfs_and_tools(Arc::new(vfs), tools.clone());
727        // Exported (not just set): try_external's own PATH lookup reads
728        // ctx.scope directly, but the CHILD process only inherits exported
729        // vars (cmd.env_clear() + exported_vars()) — a script that shells
730        // out further (`sh -c "yes | head"`) needs PATH in ITS env too,
731        // not just kaish's resolver.
732        ctx.scope.set_exported(
733            "PATH",
734            Value::String(std::env::var("PATH").unwrap_or_default()),
735        );
736        let dispatcher = BackendDispatcher::new(tools);
737        (dispatcher, ctx, dir)
738    }
739
740    /// `sh -c <script>` as a `Command`, matching how the parser would build it
741    /// from `sh -c 'script'` (a short flag, then a positional literal).
742    fn sh_cmd(script: &str) -> Command {
743        Command {
744            name: "sh".to_string(),
745            args: vec![
746                Arg::ShortFlag("c".to_string()),
747                Arg::Positional(Expr::Literal(Value::String(script.to_string()))),
748            ],
749            redirects: vec![],
750        }
751    }
752
753    /// GH #133 item 1: production maps a signal-killed child to `128 + signal`
754    /// (SIGKILL -> 137); the twin used to hardcode `code().unwrap_or(1)` -> 1,
755    /// so a cancel/timeout test run through this dispatcher observed an exit
756    /// code production never actually produces. Fails at `code == 1` pre-fix.
757    #[tokio::test]
758    async fn signal_killed_child_maps_to_128_plus_signal() {
759        let (dispatcher, mut ctx, _dir) = real_cwd_dispatcher();
760        let cmd = sh_cmd("kill -KILL $$");
761        let result = dispatcher.dispatch(&cmd, &mut ctx).await.expect("dispatch");
762        assert_eq!(
763            result.code, 137,
764            "SIGKILL should map to 128+9=137 (production's mapping), got {}",
765            result.code
766        );
767    }
768
769    /// GH #133 item 2: the twin used to call the limit-aware
770    /// `spill_aware_collect` in its non-pipe capture branch, applying
771    /// `ctx.output_limit` inline and setting `did_spill` itself. Production's
772    /// `try_execute_external` never spill-checks its own capture that way —
773    /// spill is a pipeline-level, post-hoc step (`Kernel::execute_pipeline`
774    /// calls `spill_if_needed` AFTER the dispatcher returns). So even with a
775    /// tiny `output_limit` configured, `try_external` itself must return the
776    /// full (up to the 10MB ring) captured output with `did_spill == false`.
777    /// Pre-fix, the twin truncated inline and set `did_spill = true` here.
778    #[tokio::test]
779    async fn output_limit_is_not_applied_inline_matching_production() {
780        let (dispatcher, mut ctx, _dir) = real_cwd_dispatcher();
781        // A tiny in-memory limit (no disk spill file — CLAUDE.md: no real
782        // system paths in tests) — if try_external still spill-checked
783        // inline (the bug), this would trigger truncation right here.
784        ctx.output_limit = crate::output_limit::OutputLimitConfig::agent().in_memory();
785        ctx.output_limit.set_limit(Some(64));
786
787        let cmd = sh_cmd("yes x | head -c 1000");
788        let result = dispatcher.dispatch(&cmd, &mut ctx).await.expect("dispatch");
789
790        assert_eq!(result.code, 0, "err: {}", result.err);
791        assert_eq!(
792            result.text_out().len(),
793            1000,
794            "try_external must return the full captured output — production \
795             defers spill to the post-hoc pipeline step, not its own capture; \
796             got {} bytes: {:?}",
797            result.text_out().len(),
798            result.text_out()
799        );
800        assert!(
801            !result.did_spill,
802            "try_external itself must not set did_spill — that's \
803             Kernel::execute_pipeline's post-hoc spill_if_needed's job, \
804             matching production"
805        );
806    }
807
808    /// GH #133 item 3: before this fix, `try_external` special-cased
809    /// `ctx.pipe_stdout` — taking it out of the context and hand-streaming
810    /// the child's stdout straight into it in 8KB chunks, bypassing the
811    /// capture logic a non-pipeline external goes through, and always
812    /// returning an empty `result.out` ("output was streamed to pipe").
813    /// Production's `try_execute_external` has no such special case: it never
814    /// reads or writes `ctx.pipe_stdout` at all — `PipelineRunner::run_pipeline`
815    /// (pipeline.rs) is solely responsible for reading a stage's captured
816    /// `result.out` back out and forwarding it to the next stage.
817    #[tokio::test]
818    async fn pipeline_stage_leaves_pipe_stdout_for_the_runner_to_forward() {
819        let (dispatcher, mut ctx, _dir) = real_cwd_dispatcher();
820
821        // Simulate what PipelineRunner::run_pipeline wires onto a first/middle
822        // stage's ctx before calling dispatch(): a pipe_stdout the runner
823        // expects to read back out afterward.
824        let (writer, reader) = crate::scheduler::pipe_stream_default();
825        ctx.pipe_stdout = Some(writer);
826
827        // Drain the reader concurrently — a full-fidelity writer (the old
828        // special case) would otherwise still work here for a small payload,
829        // but this also lets the pipe close out cleanly either way.
830        let drain = tokio::spawn(async move {
831            use tokio::io::AsyncReadExt;
832            let mut reader = reader;
833            let mut buf = Vec::new();
834            let _ = reader.read_to_end(&mut buf).await;
835            buf
836        });
837
838        let cmd = sh_cmd("echo hello");
839        // A generous but bounded timeout: a real hang here (e.g. an
840        // accidental deadlock reintroduced by a future edit) should fail
841        // loud and fast in CI, not stall the suite indefinitely.
842        let result = tokio::time::timeout(
843            std::time::Duration::from_secs(15),
844            dispatcher.dispatch(&cmd, &mut ctx),
845        )
846        .await
847        .expect("dispatch timed out")
848        .expect("dispatch");
849
850        assert!(
851            ctx.pipe_stdout.is_some(),
852            "try_external must leave ctx.pipe_stdout untouched — forwarding \
853             to the next stage is PipelineRunner's job, matching production, \
854             which never reads or writes this field at all"
855        );
856
857        // Drop the writer now (the runner would take it back out and, after
858        // forwarding, let it go) so the reader sees EOF and `drain` actually
859        // completes — nothing else in this test closes the pipe, since
860        // try_external no longer touches it at all post-fix.
861        drop(ctx.pipe_stdout.take());
862        let _ = drain.await;
863
864        assert!(
865            result.text_out().contains("hello"),
866            "try_external must capture and return stdout the same way for a \
867             pipeline stage as a non-pipeline call (not force it empty \
868             because a pipe was attached) — got: {:?}",
869            result.text_out()
870        );
871    }
872
873    /// GH #133 item 3, large-payload consequence: before this fix, a pipeline
874    /// stage's stdout went through the hand-rolled full-fidelity streamer,
875    /// which ignored any size cap entirely and forwarded byte-for-byte no
876    /// matter the size — an intermediate stage had NO cap at all, of any
877    /// kind. Post-fix, every stage (pipe or not) goes through the same
878    /// capture path a non-pipeline external uses.
879    ///
880    /// Updated for GH #133 item 2 (landed since this test was written): the
881    /// shared capture path now caps via an *unconditional* ~10MB
882    /// `BoundedStream` ring regardless of `ctx.output_limit` configuration —
883    /// production never spill-checks its own capture inline against
884    /// `ctx.output_limit`, deferring THAT to the pipeline-level, post-hoc
885    /// `spill_if_needed`. So `ctx.output_limit` is configured below only to
886    /// prove it's inert here (matching item 2's contract) — it plays no part
887    /// in why this payload gets capped.
888    ///
889    /// Updated again for GH #191: the fixed ring overflowing IS now loud on
890    /// its own terms, independent of `ctx.output_limit`. `did_spill` flips to
891    /// `true` (this dispatcher calling `dispatch()` directly, not through
892    /// `Kernel::execute_pipeline`, is exactly why `code` stays `0` here — the
893    /// exit-3 remap lives in that caller, not in `try_external` itself), and
894    /// stderr carries a truncation marker. Stdout still comes back as a
895    /// clean, marker-free tail — the marker is never prepended into stdout
896    /// (which may be binary), only into stderr. This test still pins the
897    /// piece item 3 alone is responsible for: a pipeline stage is no longer
898    /// special-cased into a no-cap-of-any-kind fast path.
899    #[tokio::test]
900    async fn oversized_pipeline_stage_output_is_no_longer_forwarded_losslessly() {
901        let (dispatcher, mut ctx, _dir) = real_cwd_dispatcher();
902
903        ctx.output_limit = crate::output_limit::OutputLimitConfig::agent().in_memory();
904        ctx.output_limit.set_limit(Some(1024)); // tiny vs. the >10MB payload below
905
906        let (writer, reader) = crate::scheduler::pipe_stream_default();
907        ctx.pipe_stdout = Some(writer);
908
909        // Drain the pipe concurrently — a full-fidelity writer would
910        // otherwise block on the 64KB pipe capacity well before finishing an
911        // 11MB write, deadlocking the test.
912        let drain = tokio::spawn(async move {
913            use tokio::io::AsyncReadExt;
914            let mut reader = reader;
915            let mut buf = Vec::new();
916            let _ = reader.read_to_end(&mut buf).await;
917            buf
918        });
919
920        let cmd = sh_cmd("yes x | head -c 11000000");
921        // A generous but bounded timeout: a real hang here should fail loud
922        // and fast in CI, not stall the suite indefinitely.
923        let result = tokio::time::timeout(
924            std::time::Duration::from_secs(15),
925            dispatcher.dispatch(&cmd, &mut ctx),
926        )
927        .await
928        .expect("dispatch timed out")
929        .expect("dispatch");
930
931        // Drop the writer (try_external no longer touches it post-fix, so
932        // nothing else will) so the reader sees EOF and `drain` completes.
933        drop(ctx.pipe_stdout.take());
934        let _ = drain.await;
935
936        // The exit-3 remap lives in `Kernel::execute_pipeline` (`if
937        // result.did_spill { code = 3 }`), which this test never calls —
938        // it drives `dispatcher.dispatch()` directly. So `code` stays the
939        // child's own exit status (0) even though `did_spill` is now `true`.
940        assert_eq!(result.code, 0, "err: {}", result.err);
941        assert!(
942            result.text_out().len() < 11_000_000,
943            "an oversized (~11MB) pipeline stage's output must now be capped, \
944             not forwarded byte-for-byte losslessly — the pre-fix special \
945             case ignored any cap entirely; post-fix it goes through the same \
946             capped capture (the unconditional ~10MB ring) a non-pipeline \
947             external uses. got {} bytes",
948            result.text_out().len()
949        );
950        assert!(
951            !result.text_out().contains("truncated"),
952            "the loud-overflow marker (GH #191) must never contaminate stdout \
953             — it belongs in stderr only, since stdout may be binary: got {:?}",
954            &result.text_out()[..result.text_out().len().min(80)]
955        );
956        assert!(
957            result.did_spill,
958            "the fixed ~10MB ring overflowing must set did_spill (GH #191) so \
959             a real `Kernel::execute_pipeline` caller remaps to exit 3 — this \
960             is independent of ctx.output_limit's own spill_if_needed, which \
961             stays out of scope for try_external as before"
962        );
963        assert!(
964            result.err.contains("stdout truncated"),
965            "stderr must carry the loud overflow marker (GH #191): {}",
966            result.err
967        );
968    }
969
970    /// GH #133 item 4: production always puts the spawned child in its own
971    /// process group (`setpgid(0,0)` in `pre_exec`) so a cancel's `killpg`
972    /// reaches the whole tree — the direct child AND any grandchildren it
973    /// spawns. Pre-fix, this dispatcher never called `setpgid`, so `killpg`
974    /// targeted a process group nobody was actually in (an ESRCH no-op): a
975    /// grandchild survived cancellation even though the direct child died.
976    /// Any existing test asserting "grandchild cleanup" against this
977    /// dispatcher was passing trivially, verifying nothing real.
978    ///
979    /// # Why this test checks the structural fact, not an end-to-end kill
980    ///
981    /// The most faithful reproduction of the issue would background a
982    /// grandchild (`sleep N &`), cancel mid-flight, and assert the
983    /// grandchild dies too — pinning the exact "existing test passes
984    /// trivially" symptom. That reproduction turned out to be **blocked by a
985    /// separate, pre-existing ordering issue** in this dispatcher, not
986    /// introduced by this PR: `try_external`'s output collection used to run
987    /// to completion BEFORE `wait_or_kill` was even called, so cancellation
988    /// had no observable effect until the child's stdout closed on its own —
989    /// which, for a `sh -c '... & wait'` script producing no stdout, only
990    /// happened once the whole script finished naturally. GH #133 item 2 (PR
991    /// #152, already landed on main alongside this fix) restructured
992    /// collection to run *concurrently* with `wait_or_kill`, matching
993    /// production — an end-to-end grandchild-kill test is now meaningful and
994    /// fast, and remains a natural follow-up. Until then, this test pins the
995    /// concrete, fast, unconfounded consequence of *this* PR's diff: the
996    /// spawned child's own pgid equals its own pid, i.e. `setpgid(0, 0)` in
997    /// `pre_exec` actually took effect. `ps -p $$` runs and exits almost
998    /// immediately, producing no stdout for kaish to block draining — so the
999    /// ordering issue above never enters into it either way.
1000    #[cfg(unix)]
1001    #[tokio::test]
1002    async fn spawned_child_becomes_its_own_process_group_leader() {
1003        let tmp = tempfile::tempdir().expect("tempdir");
1004        let out_file = tmp.path().join("pgid_info");
1005
1006        let (dispatcher, mut ctx, _dir) = real_cwd_dispatcher();
1007
1008        // `$$` is the running shell's own PID; `ps -o pid=,pgid= -p $$`
1009        // reports that shell's pid and process-group id. If setpgid(0,0)
1010        // took effect in pre_exec (before `ps` even execs), the two must be
1011        // equal. Redirected straight to a file — sh's own captured stdout
1012        // (what kaish pipes) stays empty, so collection returns immediately.
1013        let script = format!("ps -o pid=,pgid= -p $$ > {}", out_file.display());
1014        let cmd = sh_cmd(&script);
1015
1016        let result = tokio::time::timeout(
1017            std::time::Duration::from_secs(10),
1018            dispatcher.dispatch(&cmd, &mut ctx),
1019        )
1020        .await
1021        .expect("dispatch timed out")
1022        .expect("dispatch");
1023        assert_eq!(result.code, 0, "err: {}", result.err);
1024
1025        let contents = std::fs::read_to_string(&out_file).expect("read pgid info");
1026        let mut fields = contents.split_whitespace();
1027        let pid: i32 = fields.next().expect("pid field").parse().expect("pid parse");
1028        let pgid: i32 = fields.next().expect("pgid field").parse().expect("pgid parse");
1029
1030        assert_eq!(
1031            pid, pgid,
1032            "the spawned child's pgid must equal its own pid — setpgid(0,0) \
1033             in pre_exec should make it its own process-group leader (so a \
1034             later killpg reaches it and any of its own children), matching \
1035             production (kernel.rs::try_execute_external); got pid={pid} \
1036             pgid={pgid}"
1037        );
1038    }
1039
1040    /// GH #229: `try_external`'s path-with-slash branch checked only
1041    /// `resolved.exists()` before spawning, diverging from production
1042    /// (`kernel.rs::try_execute_external`), which additionally checks
1043    /// `is_file()` (exit 126 "Is a directory") and the Unix executable bit
1044    /// (exit 126 "Permission denied"). Spawning a directory through this
1045    /// test-only dispatcher used to fall through to `Command::spawn()`,
1046    /// which fails with a raw OS error (mapped to exit 127 here, "{name}:
1047    /// {e}") instead of the clean, documented exit-126 class production
1048    /// gives every `kernel.execute()` test.
1049    #[tokio::test]
1050    async fn path_with_slash_to_a_directory_is_126_not_a_leaked_os_error() {
1051        let (dispatcher, mut ctx, dir) = real_cwd_dispatcher();
1052        std::fs::create_dir(dir.path().join("adir")).expect("mkdir");
1053
1054        let cmd = Command { name: "./adir".to_string(), args: vec![], redirects: vec![] };
1055        let result = dispatcher.dispatch(&cmd, &mut ctx).await.expect("dispatch");
1056
1057        assert_eq!(
1058            result.code, 126,
1059            "spawning a directory must report the clean 'Is a directory' class \
1060             (matching kernel.rs::try_execute_external), not leak whatever raw \
1061             OS spawn error Command::spawn() happens to produce: {:?}",
1062            result
1063        );
1064        assert!(
1065            result.err.contains("Is a directory"),
1066            "err should name the reason: {}",
1067            result.err
1068        );
1069    }
1070
1071    /// GH #229 companion: a resolved-but-non-executable regular file must
1072    /// report exit 126 "Permission denied", matching production's Unix mode
1073    /// check. Pre-fix, this dispatcher had no mode check at all and fell
1074    /// through to `Command::spawn()`, leaking whatever raw OS error resulted
1075    /// instead of the clean exit-126 class. The mode check reads the file's
1076    /// own permission bits directly (not an effective-permission check via
1077    /// the OS), so this is deterministic even when the test runs as root.
1078    #[cfg(unix)]
1079    #[tokio::test]
1080    async fn path_with_slash_to_a_non_executable_file_is_126_not_a_leaked_os_error() {
1081        use std::os::unix::fs::PermissionsExt;
1082
1083        let (dispatcher, mut ctx, dir) = real_cwd_dispatcher();
1084        let file_path = dir.path().join("not_executable");
1085        std::fs::write(&file_path, b"#!/bin/sh\necho hi\n").expect("write file");
1086        let mut perms = std::fs::metadata(&file_path).expect("metadata").permissions();
1087        perms.set_mode(0o644); // no exec bits, regardless of effective uid
1088        std::fs::set_permissions(&file_path, perms).expect("chmod");
1089
1090        let cmd = Command { name: "./not_executable".to_string(), args: vec![], redirects: vec![] };
1091        let result = dispatcher.dispatch(&cmd, &mut ctx).await.expect("dispatch");
1092
1093        assert_eq!(
1094            result.code, 126,
1095            "a non-executable file must report the clean 'Permission denied' \
1096             class (matching kernel.rs::try_execute_external), not leak a raw \
1097             OS spawn error: {:?}",
1098            result
1099        );
1100        assert!(
1101            result.err.contains("Permission denied"),
1102            "err should name the reason: {}",
1103            result.err
1104        );
1105    }
1106}