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