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