Skip to main content

kaish_kernel/scheduler/
scatter.rs

1//! Scatter/Gather — Parallel pipeline execution.
2//!
3//! Scatter splits input into items and runs the pipeline in parallel.
4//! Gather collects the parallel results.
5//!
6//! # Example
7//!
8//! ```text
9//! cat urls.txt | scatter | fetch url=${ITEM} | gather
10//! ```
11//!
12//! This reads URLs, then for each URL runs `fetch` in parallel,
13//! then collects all results.
14
15use std::sync::Arc;
16use std::sync::atomic::{AtomicBool, Ordering};
17use std::time::Duration;
18
19use tokio::sync::Semaphore;
20use tracing::Instrument;
21
22use crate::ast::{Command, Redirect, Value};
23use crate::dispatch::CommandDispatcher;
24use crate::duration::parse_duration;
25use crate::interpreter::ExecResult;
26use crate::tools::{ExecContext, ToolRegistry};
27
28use super::pipeline::{apply_redirects, PipelineRunner};
29
30/// Options for scatter operation.
31#[derive(Debug, Clone)]
32pub struct ScatterOptions {
33    /// Variable name to bind each item to (default: "ITEM").
34    pub var_name: String,
35    /// Maximum parallelism (default: 8).
36    pub limit: usize,
37    /// Per-worker timeout. When `Some`, each worker is cancelled after this
38    /// duration; the worker's external children get SIGTERM/SIGKILL and the
39    /// `ScatterResult.timed_out` flag is set.
40    pub timeout: Option<Duration>,
41}
42
43/// Options for gather operation.
44#[derive(Debug, Clone, Default)]
45pub struct GatherOptions {
46    /// `--lines`: emit each successful worker's raw `out` in item order instead
47    /// of JSONL rows — and HARD-ERROR (exit 123, no partial text) if any worker
48    /// failed, since bare lines cannot represent a failure. The text escape
49    /// hatch that keeps the old line mode's safety property.
50    pub lines: bool,
51    /// `--json` (the kernel-wide flag; scatter/gather own their output, so it
52    /// reaches the tool): render the result records as ONE JSON array instead
53    /// of JSONL rows. Same records, same `.data`.
54    pub json: bool,
55}
56
57impl Default for ScatterOptions {
58    fn default() -> Self {
59        Self {
60            var_name: "ITEM".to_string(),
61            limit: 8,
62            timeout: None,
63        }
64    }
65}
66
67/// One typed scatter item: the JSON element that fans out to a worker.
68///
69/// `json` is the source of truth — the worker binding derives from it via
70/// [`json_to_value_no_envelope`](crate::interpreter::json_to_value_no_envelope)
71/// (the exact conversion `for v in $(cmd)` uses), and the gather row's `item`
72/// field carries it typed. `label` is a char-safe truncated display form for
73/// spans and error messages.
74#[derive(Debug, Clone)]
75pub struct ScatterItem {
76    /// The element as JSON (string items are JSON strings).
77    pub json: serde_json::Value,
78    /// Compact display label for tracing and error text.
79    pub label: String,
80}
81
82impl ScatterItem {
83    fn new(json: serde_json::Value) -> Self {
84        let full = match &json {
85            serde_json::Value::String(s) => s.clone(),
86            other => other.to_string(),
87        };
88        // Char-safe truncation (a byte slice at 64 can split a UTF-8 char).
89        let label = if full.chars().count() > 64 {
90            let head: String = full.chars().take(64).collect();
91            format!("{head}...")
92        } else {
93            full
94        };
95        Self { json, label }
96    }
97
98    fn from_text_line(line: &str) -> Self {
99        Self::new(serde_json::Value::String(line.to_string()))
100    }
101}
102
103/// Result from a single scatter worker.
104#[derive(Debug, Clone)]
105pub struct ScatterResult {
106    /// The input item that was processed.
107    pub item: ScatterItem,
108    /// The execution result.
109    pub result: ExecResult,
110    /// Whether the worker was cancelled by the per-worker `--timeout`.
111    pub timed_out: bool,
112}
113
114/// Runs scatter/gather pipelines.
115///
116/// Uses a single dispatcher for sequential stages (pre_scatter, post_gather),
117/// and forks it per parallel worker via [`CommandDispatcher::fork`]. Each
118/// worker gets its own subkernel with snapshotted session state so they can
119/// run concurrently without racing on scope/cwd/aliases.
120pub struct ScatterGatherRunner {
121    tools: Arc<ToolRegistry>,
122    /// Full dispatch chain for sequential stages (pre_scatter, post_gather).
123    /// Parallel workers fork from this dispatcher.
124    sequential_dispatcher: Arc<dyn CommandDispatcher>,
125}
126
127impl ScatterGatherRunner {
128    /// Create a new scatter/gather runner.
129    ///
130    /// `dispatcher` drives sequential stages directly and serves as the fork
131    /// source for parallel workers.
132    pub fn new(
133        tools: Arc<ToolRegistry>,
134        dispatcher: Arc<dyn CommandDispatcher>,
135    ) -> Self {
136        Self { tools, sequential_dispatcher: dispatcher }
137    }
138
139    /// Execute a scatter/gather pipeline.
140    ///
141    /// The pipeline is split into three parts:
142    /// - pre_scatter: commands before scatter
143    /// - parallel: commands between scatter and gather
144    /// - post_gather: commands after gather
145    ///
146    /// Returns the final result after all stages complete.
147    #[tracing::instrument(level = "info", skip(self, pre_scatter, scatter_opts, parallel, gather_opts, post_gather, ctx), fields(item_count = tracing::field::Empty, parallelism = scatter_opts.limit))]
148    #[allow(clippy::too_many_arguments)]
149    pub async fn run(
150        &self,
151        pre_scatter: &[Command],
152        scatter_opts: ScatterOptions,
153        parallel: &[Command],
154        gather_opts: GatherOptions,
155        gather_redirects: &[Redirect],
156        post_gather: &[Command],
157        ctx: &mut ExecContext,
158    ) -> ExecResult {
159        let runner = PipelineRunner::new(self.tools.clone());
160
161        // Run pre-scatter commands to get input.
162        // Uses run_sequential to avoid async recursion (scatter → run → scatter).
163        let (text, data) = if pre_scatter.is_empty() {
164            // Use existing stdin — structured data, a String buffer, or a lazy
165            // `pipe_stdin` (a frontend-seeded process-stdin pipe). `take_stdin`
166            // alone would miss the pipe; `read_stdin_to_text` prefers it.
167            let data = ctx.take_stdin_data();
168            let text = match ctx.read_stdin_to_text().await {
169                Ok(s) => s.unwrap_or_default(),
170                Err(e) => return ExecResult::failure(2, format!("scatter: {e}")),
171            };
172            (text, data)
173        } else {
174            let result = runner.run_sequential(pre_scatter, ctx, &*self.sequential_dispatcher).await;
175            if !result.ok() {
176                return result;
177            }
178            (result.text_out().into_owned(), result.data)
179        };
180
181        // Extract items from structured data or text
182        let items = match extract_items(data.as_ref(), &text) {
183            Ok(items) => items,
184            Err(msg) => return ExecResult::failure(1, msg),
185        };
186        if items.is_empty() {
187            return ExecResult::success("");
188        }
189
190        tracing::Span::current().record("item_count", items.len());
191
192        // Run parallel stage
193        let results = self
194            .run_parallel(&items, &scatter_opts, parallel, ctx)
195            .await;
196
197        // Gather per the GH #73 contract: JSONL result records by default (one
198        // row per worker, failures included), or `--lines` raw text. Exit codes
199        // are A′: 0 all ok · 123 any worker failed · 2 usage (clap layer).
200        let gathered = gather_results(&results, &gather_opts);
201
202        // `gather`'s own trailing redirect (`… | gather > results.jsonl | …`)
203        // must apply to gather's OWN result before anything downstream sees
204        // it — matching shell semantics where a file redirect on a pipeline
205        // stage wins over the pipe (`cmd > file | next` sends cmd's real
206        // stdout to the file; `next` reads nothing from cmd). Applying it
207        // unconditionally (regardless of exit code) matches a redirect being
208        // a file-descriptor operation independent of the command's success —
209        // `false > file` still creates the file. Previously this only ran
210        // when gather was the pipeline's last command, so a trailing
211        // `gather > file | jq` silently skipped the file and let the
212        // unredirected rows flow to `jq` instead.
213        let gathered = apply_redirects(gathered, gather_redirects, ctx).await;
214
215        // Run post-gather commands if any. A failed gather short-circuits —
216        // feeding partial/failed output onward would propagate corruption.
217        if post_gather.is_empty() || gathered.code != 0 {
218            gathered
219        } else {
220            ctx.set_stdin_with_data(
221                gathered.text_out().into_owned(),
222                gathered.data.clone(),
223            );
224            runner.run_sequential(post_gather, ctx, &*self.sequential_dispatcher).await
225        }
226    }
227
228    /// Run the parallel stage for all items.
229    ///
230    /// Each worker gets its own forked dispatcher via
231    /// [`CommandDispatcher::fork`]. The fork snapshots per-session state
232    /// (scope, cwd, aliases, user tools) so workers can run concurrently
233    /// without racing. Forks are cheap (Scope is COW, plus a few Arc bumps),
234    /// and they unlock the full dispatch chain inside workers — user tools,
235    /// `.kai` scripts, and `$(...)` in args all work.
236    #[tracing::instrument(level = "debug", skip(self, items, opts, commands, base_ctx), fields(worker_count = items.len()))]
237    async fn run_parallel(
238        &self,
239        items: &[ScatterItem],
240        opts: &ScatterOptions,
241        commands: &[Command],
242        base_ctx: &ExecContext,
243    ) -> Vec<ScatterResult> {
244        let semaphore = Arc::new(Semaphore::new(opts.limit));
245        let tools = self.tools.clone();
246        let var_name = opts.var_name.clone();
247
248        // Spawn parallel tasks
249        let mut handles = Vec::with_capacity(items.len());
250
251        for item in items.iter().cloned() {
252            let permit = semaphore.clone().acquire_owned().await;
253            let tools = tools.clone();
254            // Fork attached: the worker's cancel token is a child of the
255            // parent kernel's, so a parent cancel (request timeout, embedder
256            // Kernel::cancel) cascades into the worker and kills its
257            // external children via the wait_or_kill discipline.
258            let worker_dispatcher = self.sequential_dispatcher.fork_attached().await;
259            let commands = commands.to_vec();
260            let parent_token = base_ctx.cancel.clone();
261            let worker_token = parent_token.child_token();
262
263            // Build the worker context FROM THE PARENT, not from scratch. A
264            // from-scratch `ExecContext::with_backend_and_scope` starts
265            // `watchdog = None`; `dispatch_command` then syncs that `None` INTO
266            // the subkernel (kernel.rs `ec.watchdog = ctx.watchdog.clone()`),
267            // clobbering the fork's inherited watchdog — so inside a worker the
268            // script clock is gone and any `ctx.patient` hold suspends a
269            // *missing* timer, yielding false-positive request timeouts that
270            // kill the worker. `child_for_pipeline` clones exactly what a worker
271            // needs in one shot — watchdog, vfs_budget, aliases, ignore_config,
272            // output_limit, allow_external_commands, backend, cwd, scope,
273            // dispatcher — replacing the manual field-copy that was easy to let
274            // drift (and that dropped the watchdog). `base_ctx` is a borrow (not
275            // `'static`), so the child MUST be built here and MOVED into the
276            // spawn — it cannot be constructed inside the closure.
277            let mut worker_ctx = base_ctx.child_for_pipeline();
278            // Per-worker TYPED binding — the same json→Value conversion the
279            // for-loop uses for `$(cmd)` items (GH #73), so a record element
280            // subscripts as `${ITEM[k]}`.
281            worker_ctx.scope.set(
282                &var_name,
283                crate::interpreter::json_to_value_no_envelope(item.json.clone()),
284            );
285            // Per-worker cancel token (a child of the parent's), so the timeout
286            // timer and a parent cancel both reach this worker's externals.
287            worker_ctx.cancel = worker_token.clone();
288
289            // Per-worker timeout: spawn a delay task that cancels the worker's
290            // child token after `opts.timeout`. The cancel cascades into the
291            // worker's externals via the fork's cancel link. `timed_out_flag`
292            // distinguishes timeout from explicit parent cancellation when
293            // tagging ScatterResult.
294            let timed_out_flag = Arc::new(AtomicBool::new(false));
295            let timer_handle: Option<tokio::task::JoinHandle<()>> = opts.timeout.map(|d| {
296                let cancel = worker_token.clone();
297                let flag = timed_out_flag.clone();
298                tokio::spawn(async move {
299                    tokio::time::sleep(d).await;
300                    flag.store(true, Ordering::SeqCst);
301                    cancel.cancel();
302                })
303            });
304            let timed_out_check = timed_out_flag.clone();
305
306            let worker_span = tracing::debug_span!("scatter_worker", item = %item.label);
307            // Propagate the embedder's trace context across the spawn boundary so
308            // each worker's spans stay in the same trace. `.instrument` below
309            // provides the tracing parent; this provides the OTel parent.
310            let handle = tokio::spawn(crate::telemetry::bind_current_context(async move {
311                let _permit = permit; // Hold permit until done
312                let mut worker_ctx = worker_ctx; // moved in; built from parent above
313
314                // Run through PipelineRunner + dispatcher (full resolution chain).
315                // Uses run_sequential to avoid async recursion and infinite future size.
316                let runner = PipelineRunner::new(tools);
317                let mut result =
318                    runner.run_sequential(&commands, &mut worker_ctx, &*worker_dispatcher).await;
319
320                // Per-worker spill boundary. `run_sequential` never reaches the
321                // kernel's top-level post-run spill check (kernel.rs:2704), so
322                // without this each worker holds its FULL output in memory —
323                // N concurrent workers × large output evades the sandbox
324                // `output_limit` (10 workers × 1 GB = 10 GB resident before
325                // anything spills). Cap here, where the N× multiplication lives;
326                // `child_for_pipeline` shares the parent's `output_limit`, so
327                // workers cap against the same budget.
328                if worker_ctx.output_limit.is_enabled() {
329                    let _ = crate::output_limit::spill_if_needed(
330                        &mut result,
331                        &worker_ctx.output_limit,
332                    )
333                    .await;
334                }
335
336                // Worker finished — abort the timer if still pending so it
337                // doesn't fire a now-pointless cancel and idle resources.
338                if let Some(h) = timer_handle {
339                    h.abort();
340                }
341
342                let timed_out = timed_out_check.load(Ordering::SeqCst);
343                ScatterResult { item, result, timed_out }
344            }.instrument(worker_span)));
345
346            handles.push(handle);
347        }
348
349        // Collect results
350        let mut results = Vec::with_capacity(handles.len());
351        for handle in handles {
352            match handle.await {
353                Ok(result) => results.push(result),
354                Err(e) => {
355                    results.push(ScatterResult {
356                        item: ScatterItem::new(serde_json::Value::String(
357                            "<worker panicked>".to_string(),
358                        )),
359                        result: ExecResult::failure(1, format!("Task panicked: {}", e)),
360                        timed_out: false,
361                    });
362                }
363            }
364        }
365
366        results
367    }
368}
369
370/// Extract typed items from structured data or text (GH #73 contract).
371///
372/// Structured `.data` wins and fans out TYPED: a JSON array yields one item per
373/// element with the element's real type (a record element subscripts as
374/// `${ITEM[k]}` in the worker; number `1` and string `"1"` stay distinct). A
375/// `null` element is a loud error — a worker silently running with a null
376/// binding is corruption. A single non-array OBJECT is a loud error with a
377/// select-the-array hint (one worker running on the `{"jobs":[…]}` envelope is
378/// never what was meant); a single scalar is one item. Binary data is a loud
379/// error.
380///
381/// Plain-text stdin is split on newlines only — one item per line, each a
382/// string — matching the for-loop `$(cmd)` contract: trailing newlines trimmed
383/// once, each line's trailing `\r` stripped, whitespace within a line never
384/// split. Blank lines are SKIPPED (panel-ratified: a worker spawned on `""` is
385/// silent corruption of the most common input shape). Empty input yields zero
386/// items (the caller exits 0 with no rows).
387pub fn extract_items(data: Option<&Value>, text: &str) -> Result<Vec<ScatterItem>, String> {
388    // 1. Structured data wins over text (arch_data_iteration contract).
389    match data {
390        // JSON array — fan out per element, typed (seq/split/glob/find/jq).
391        Some(Value::Json(serde_json::Value::Array(arr))) => {
392            let mut items = Vec::with_capacity(arr.len());
393            for (i, elem) in arr.iter().enumerate() {
394                if elem.is_null() {
395                    return Err(format!(
396                        "scatter: item {i} is null — refusing to bind a worker to null \
397                         (filter it out first, e.g. jq 'map(select(. != null))')"
398                    ));
399                }
400                items.push(ScatterItem::new(elem.clone()));
401            }
402            return Ok(items);
403        }
404        // Kaish scalars — one typed item each.
405        Some(Value::String(s)) => {
406            return Ok(vec![ScatterItem::new(serde_json::Value::String(s.clone()))])
407        }
408        Some(Value::Int(i)) => return Ok(vec![ScatterItem::new(serde_json::json!(i))]),
409        Some(Value::Float(f)) => return Ok(vec![ScatterItem::new(serde_json::json!(f))]),
410        Some(Value::Bool(b)) => return Ok(vec![ScatterItem::new(serde_json::json!(b))]),
411        Some(Value::Null) => {
412            return Err("scatter: input is null — nothing to fan out".to_string())
413        }
414        // A single JSON object is almost always the unselected envelope around
415        // the array the caller meant — loud, with the fix in the message.
416        Some(Value::Json(serde_json::Value::Object(map))) => {
417            let hint = map
418                .iter()
419                .find(|(_, v)| v.is_array())
420                .map(|(k, _)| format!(" (did you mean jq '.{k}'?)"))
421                .unwrap_or_default();
422            return Err(format!(
423                "scatter: input is a single object, not an array — select the array to \
424                 fan out over{hint}"
425            ));
426        }
427        Some(Value::Json(serde_json::Value::Null)) => {
428            return Err("scatter: input is null — nothing to fan out".to_string())
429        }
430        // Single JSON scalar — one typed item.
431        Some(Value::Json(json)) => return Ok(vec![ScatterItem::new(json.clone())]),
432        // Binary can't bind a worker variable meaningfully — loud, never a
433        // placeholder string item.
434        Some(Value::Bytes(b)) => {
435            return Err(format!(
436                "scatter: input is binary ({} bytes) — decode it to text or JSON first",
437                b.len()
438            ))
439        }
440        // No structured data — fall through to plain-text newline-split.
441        None => {}
442    }
443
444    // 2. Plain text — newline-split, mirroring kernel.rs for-loop $(cmd)
445    // semantics; every text item is a string.
446    let trimmed = text.trim_end_matches(['\n', '\r']);
447    if trimmed.is_empty() {
448        return Ok(vec![]);
449    }
450    Ok(trimmed
451        .split('\n')
452        .map(|line| line.trim_end_matches('\r'))
453        .filter(|line| !line.is_empty())
454        .map(ScatterItem::from_text_line)
455        .collect())
456}
457
458/// Strip exactly one trailing newline (`\n` or `\r\n`), leaving everything
459/// else raw — the GH #73 contract for the row's `out` and `err` fields.
460fn strip_one_trailing_newline(s: &str) -> &str {
461    let s = s.strip_suffix('\n').unwrap_or(s);
462    s.strip_suffix('\r').unwrap_or(s)
463}
464
465/// Build one JSONL result record for a worker (GH #73 row schema).
466///
467/// `{"i":N, "item":<typed>, "ok":bool, "code":N, "out":"…", "err":"…"}` plus
468/// `data` (the worker's structured output, typed) when present and
469/// `timed_out:true` when it was. `i`/`item`/`ok`/`code`/`out`/`err` are always
470/// present (`err` deliberately so — omit-empty on the most-read field would
471/// make `${r[err]}` a loud missing-key error on every successful row). A
472/// timed-out worker reports `code` 124 (the `timeout(1)` prior) and `ok` false.
473///
474/// # Binary-output hazard
475///
476/// A worker's `out` is a `text_out()`-shaped string field, but the worker's
477/// `ExecResult` payload can be `OutputPayload::Bytes` — several builtins
478/// already produce it (`cat`/`head`/`tail`/`base64 -d`/`xxd -r`/`dd`/`tee`/
479/// external commands via `env`/`spawn`), so a worker running e.g. `cat
480/// binary.file` is not a hypothetical, it is reachable today. `text_out()`
481/// would lossily replace invalid UTF-8 with U+FFFD — silent data corruption
482/// riding through the row as if it were the worker's real text output. Per
483/// "crash beats corrupt" we go loud at row granularity instead: `try_text_out`
484/// catches it, the row is forced `ok:false` with a clear `err` (never a
485/// lossily-decoded `out`), and the OTHER rows are unaffected — see
486/// `docs/binary-data.md` for the broader binary-data plan.
487fn result_row(i: usize, r: &ScatterResult) -> serde_json::Value {
488    let mut ok = r.result.ok() && !r.timed_out;
489    let mut code = if r.timed_out { 124 } else { r.result.code };
490
491    let (out_text, err_text) = match r.result.try_text_out() {
492        Ok(text) => (
493            strip_one_trailing_newline(&text).to_string(),
494            strip_one_trailing_newline(&r.result.err).to_string(),
495        ),
496        Err(e) => {
497            ok = false;
498            if code == 0 {
499                code = 1;
500            }
501            (
502                String::new(),
503                format!(
504                    "binary worker output not representable as text ({} bytes) — \
505                     encode it in the worker (base64/xxd)",
506                    e.len
507                ),
508            )
509        }
510    };
511
512    let mut row = serde_json::Map::new();
513    row.insert("i".into(), serde_json::json!(i));
514    row.insert("item".into(), r.item.json.clone());
515    row.insert("ok".into(), serde_json::json!(ok));
516    row.insert("code".into(), serde_json::json!(code));
517    row.insert("out".into(), serde_json::json!(out_text));
518    row.insert("err".into(), serde_json::json!(err_text));
519    if let Some(data) = &r.result.data {
520        row.insert("data".into(), kaish_types::value_to_json(data));
521    }
522    if r.timed_out {
523        row.insert("timed_out".into(), serde_json::json!(true));
524    }
525    serde_json::Value::Object(row)
526}
527
528/// Render gathered worker results as an [`ExecResult`] (GH #73 contract).
529///
530/// Default: JSONL — one compact result record per worker, in item order, EVERY
531/// worker including failures. One source, three views: the pipe text is the
532/// JSONL, `.data` is the typed record array (so `for r in $(… | gather)`
533/// iterates records and post-gather stages see typed stdin), and the kernel
534/// `--json` flag renders the same array as one JSON document via `rich_json`.
535///
536/// `--lines`: each successful worker's raw `out` in item order — and a HARD
537/// error (no partial text) if any worker failed, because bare lines cannot
538/// represent a failure (the old line mode's safety property, kept as a flag).
539///
540/// Exit codes (A′): `0` all workers ok · `123` any worker failed, partial or
541/// total (timeouts count) — partial-vs-total is distinguished in the rows.
542fn gather_results(results: &[ScatterResult], opts: &GatherOptions) -> ExecResult {
543    // A worker's binary stdout that can't decode as text is a failure for
544    // gather's purposes too — see `result_row`'s hazard doc. Folding it into
545    // `failed` here keeps the overall exit code (0 vs 123) honest: a `--lines`
546    // or JSONL caller checking `$?` must see non-zero, not a silent "0 all
547    // ok" while one row was actually corruption-guarded away.
548    let is_unrepresentable = |r: &ScatterResult| r.result.try_text_out().is_err();
549
550    let failed: Vec<&ScatterResult> = results
551        .iter()
552        .filter(|r| !r.result.ok() || r.timed_out || is_unrepresentable(r))
553        .collect();
554    let code = if failed.is_empty() { 0 } else { 123 };
555    let err = if failed.is_empty() {
556        String::new()
557    } else {
558        let names = failed
559            .iter()
560            .map(|r| {
561                if is_unrepresentable(r) {
562                    format!("{} (binary output not representable as text)", r.item.label)
563                } else {
564                    r.item.label.clone()
565                }
566            })
567            .collect::<Vec<_>>()
568            .join(", ");
569        format!("gather: {} of {} worker(s) failed: {names}", failed.len(), results.len())
570    };
571
572    if opts.lines {
573        // Bare lines can't carry a failure — refuse with no partial text
574        // rather than silently dropping rows. This also covers binary output
575        // (folded into `failed` above): `--lines` is a text-only escape
576        // hatch, and a U+FFFD-laden line would be exactly the silent
577        // corruption this hardening pass exists to prevent.
578        if !failed.is_empty() {
579            return ExecResult::failure(code, format!("{err} (drop --lines to get per-worker rows)"));
580        }
581        let text = results
582            .iter()
583            .map(|r| strip_one_trailing_newline(&r.result.text_out()).to_string())
584            .collect::<Vec<_>>()
585            .join("\n");
586        return ExecResult::success(text);
587    }
588
589    let rows: Vec<serde_json::Value> =
590        results.iter().enumerate().map(|(i, r)| result_row(i, r)).collect();
591    let text = if opts.json {
592        // `--json`: the same records as one JSON document.
593        serde_json::to_string_pretty(&rows).unwrap_or_default()
594    } else {
595        // Default: JSONL — one compact record per line.
596        rows.iter().map(|row| row.to_string()).collect::<Vec<_>>().join("\n")
597    };
598    let array = serde_json::Value::Array(rows);
599    ExecResult::from_parts(code, text, err, Some(Value::Json(array)))
600}
601
602/// Human-readable repr of a `Value` for a "wrong type" error message —
603/// deliberately not `Debug` (whose `String("five")` quoting/enum-tag noise
604/// reads badly to a user who just typed `--limit five`).
605fn describe_value(v: &Value) -> String {
606    match v {
607        Value::Null => "null".to_string(),
608        Value::Bool(b) => b.to_string(),
609        Value::Int(n) => n.to_string(),
610        Value::Float(f) => f.to_string(),
611        Value::String(s) => format!("{s:?}"),
612        Value::Json(j) => j.to_string(),
613        Value::Bytes(b) => format!("<{} bytes>", b.len()),
614    }
615}
616
617/// Parse scatter options from tool args.
618///
619/// A flag key *present* in `args.named` with a value of the wrong type is a
620/// loud `Err`, never a silent fall-back to the default — `scatter --limit
621/// five` must not quietly run at the default limit, and `scatter --as 42`
622/// must not quietly bind `$ITEM`. (An *absent* or unresolved flag falls back
623/// to a bare boolean earlier, at the pipeline arg-binding layer — that lenient
624/// path is unrelated and untouched here.)
625pub fn parse_scatter_options(args: &crate::tools::ToolArgs) -> Result<ScatterOptions, String> {
626    let mut opts = ScatterOptions::default();
627
628    match args.named.get("as") {
629        None => {}
630        Some(Value::String(name)) => opts.var_name = name.clone(),
631        Some(other) => {
632            return Err(format!(
633                "scatter --as: expected a variable name, got {}",
634                describe_value(other)
635            ))
636        }
637    }
638
639    match args.named.get("limit") {
640        None => {}
641        Some(Value::Int(n)) => opts.limit = clamp_scatter_limit(*n),
642        // Values from variables often stringify (`--limit "$n"`) — coerce a
643        // numeric string the same as an int.
644        Some(Value::String(s)) => match s.trim().parse::<i64>() {
645            Ok(n) => opts.limit = clamp_scatter_limit(n),
646            Err(_) => {
647                return Err(format!(
648                    "scatter --limit: expected a positive integer, got {}",
649                    describe_value(&Value::String(s.clone()))
650                ))
651            }
652        },
653        Some(other) => {
654            return Err(format!(
655                "scatter --limit: expected a positive integer, got {}",
656                describe_value(other)
657            ))
658        }
659    }
660
661    // --timeout DURATION: per-worker timeout. Accepts the same forms as the
662    // `timeout` builtin (30, 5s, 500ms, 2m, 1h). A present-but-invalid value
663    // is a loud Err — a typo here must not silently disable cancellation.
664    match args.named.get("timeout") {
665        None => {}
666        Some(Value::String(s)) => match parse_duration(s) {
667            Some(d) => opts.timeout = Some(d),
668            None => {
669                return Err(format!(
670                    "scatter --timeout: invalid duration {} (try: 30, 5s, 500ms, 2m, 1h)",
671                    describe_value(&Value::String(s.clone()))
672                ))
673            }
674        },
675        Some(Value::Int(n)) if *n >= 0 => opts.timeout = Some(Duration::from_secs(*n as u64)),
676        Some(other) => {
677            return Err(format!(
678                "scatter --timeout: expected a non-negative duration, got {}",
679                describe_value(other)
680            ))
681        }
682    }
683
684    Ok(opts)
685}
686
687/// Clamp a requested `--limit` to `[1, SCATTER_LIMIT_MAX]`, warning (not
688/// erroring) when the ceiling clamps a value down — this ceiling exists to
689/// protect the host, not to reject user input, so it stays a warn+clamp.
690fn clamp_scatter_limit(requested: i64) -> usize {
691    let clamped = requested.clamp(1, SCATTER_LIMIT_MAX as i64);
692    if requested > SCATTER_LIMIT_MAX as i64 {
693        tracing::warn!(
694            target: "kaish::scatter",
695            requested = requested,
696            ceiling = SCATTER_LIMIT_MAX,
697            "scatter limit clamped to ceiling"
698        );
699    }
700    clamped as usize
701}
702
703/// Upper bound on the concurrency `scatter --limit N` accepts. Users who
704/// ask for more get a `tracing::warn` and are clamped to this value —
705/// silent clamping would violate the "no silent fallbacks" rule.
706pub const SCATTER_LIMIT_MAX: usize = 10_000;
707
708/// Parse gather options from tool args.
709///
710/// Returns `Err` for a present-but-wrong-typed flag value, mirroring
711/// [`parse_scatter_options`]. Today gather's only value-carrying flags are
712/// boolean (`--lines`/`--json`), so this can't yet fail — the `Result` return
713/// keeps the signature symmetric with scatter's and ready for the next
714/// value-carrying gather flag.
715pub fn parse_gather_options(args: &crate::tools::ToolArgs) -> Result<GatherOptions, String> {
716    let mut opts = GatherOptions::default();
717
718    if args.has_flag("lines") {
719        opts.lines = true;
720    }
721
722    if args.has_flag("json") {
723        opts.json = true;
724    }
725
726    Ok(opts)
727}
728
729#[cfg(test)]
730mod tests {
731    use super::*;
732
733    fn labels(items: &[ScatterItem]) -> Vec<String> {
734        items.iter().map(|i| i.label.clone()).collect()
735    }
736
737    fn item(s: &str) -> ScatterItem {
738        ScatterItem::new(serde_json::Value::String(s.to_string()))
739    }
740
741    #[test]
742    fn test_extract_items_structured_json_array() {
743        let data = Value::Json(serde_json::json!(["a", "b", "c"]));
744        let items = extract_items(Some(&data), "").unwrap();
745        assert_eq!(labels(&items), vec!["a", "b", "c"]);
746    }
747
748    #[test]
749    fn test_extract_items_structured_mixed_types_stay_typed() {
750        // GH #73: number 1 and string "1" must remain distinct through the
751        // fan-out — the old Vec<String> path conflated them silently.
752        let data = Value::Json(serde_json::json!([1, "1", true, {"id": 7}]));
753        let items = extract_items(Some(&data), "").unwrap();
754        assert_eq!(items[0].json, serde_json::json!(1));
755        assert_eq!(items[1].json, serde_json::json!("1"));
756        assert_ne!(items[0].json, items[1].json, "1 and \"1\" must not conflate");
757        assert_eq!(items[2].json, serde_json::json!(true));
758        assert_eq!(items[3].json, serde_json::json!({"id": 7}));
759    }
760
761    #[test]
762    fn test_extract_items_null_element_is_loud() {
763        let data = Value::Json(serde_json::json!(["a", null, "c"]));
764        let err = extract_items(Some(&data), "").unwrap_err();
765        assert!(err.contains("null"), "should name the problem: {err}");
766        assert!(err.contains("item 1"), "should name the position: {err}");
767    }
768
769    #[test]
770    fn test_extract_items_single_object_is_loud_with_hint() {
771        let data = Value::Json(serde_json::json!({"jobs": [1, 2]}));
772        let err = extract_items(Some(&data), "").unwrap_err();
773        assert!(err.contains("single object"), "{err}");
774        assert!(err.contains("jq '.jobs'"), "should hint the array key: {err}");
775    }
776
777    #[test]
778    fn test_extract_items_binary_is_loud() {
779        let data = Value::Bytes(vec![0, 1, 2]);
780        let err = extract_items(Some(&data), "").unwrap_err();
781        assert!(err.contains("binary"), "{err}");
782    }
783
784    #[test]
785    fn test_extract_items_structured_string() {
786        let data = Value::String("single".into());
787        let items = extract_items(Some(&data), "").unwrap();
788        assert_eq!(labels(&items), vec!["single"]);
789    }
790
791    #[test]
792    fn test_extract_items_single_line_text() {
793        let items = extract_items(None, "hello").unwrap();
794        assert_eq!(labels(&items), vec!["hello"]);
795    }
796
797    #[test]
798    fn test_extract_items_empty() {
799        let items = extract_items(None, "").unwrap();
800        assert!(items.is_empty());
801    }
802
803    #[test]
804    fn test_extract_items_multiline_fans_out_per_line() {
805        let items = extract_items(None, "one\ntwo\nthree").unwrap();
806        assert_eq!(labels(&items), vec!["one", "two", "three"]);
807    }
808
809    #[test]
810    fn test_extract_items_trailing_newline_no_phantom_item() {
811        let items = extract_items(None, "one\ntwo\n").unwrap();
812        assert_eq!(labels(&items), vec!["one", "two"]);
813    }
814
815    #[test]
816    fn test_extract_items_crlf_per_line() {
817        let items = extract_items(None, "one\r\ntwo\r\n").unwrap();
818        assert_eq!(labels(&items), vec!["one", "two"]);
819    }
820
821    #[test]
822    fn test_extract_items_blank_lines_skipped() {
823        // GH #73 panel finding: a worker spawned on "" is silent corruption of
824        // the most common input shape — blank lines are skipped, not items.
825        let items = extract_items(None, "a\n\nb").unwrap();
826        assert_eq!(labels(&items), vec!["a", "b"]);
827    }
828
829    #[test]
830    fn test_extract_items_whitespace_within_line_not_split() {
831        let items = extract_items(None, "a b\nc d").unwrap();
832        assert_eq!(labels(&items), vec!["a b", "c d"]);
833    }
834
835    #[test]
836    fn test_extract_items_only_newlines_is_empty() {
837        let items = extract_items(None, "\n\n").unwrap();
838        assert!(items.is_empty());
839    }
840
841    #[test]
842    fn test_extract_items_structured_overrides_text() {
843        let data = Value::Json(serde_json::json!(["x", "y"]));
844        let items = extract_items(Some(&data), "ignored\ntext").unwrap();
845        assert_eq!(labels(&items), vec!["x", "y"]);
846    }
847
848    #[test]
849    fn test_item_label_truncates_on_char_boundary() {
850        // 100 multibyte chars — a byte-slice truncation would panic.
851        let long: String = "é".repeat(100);
852        let it = ScatterItem::new(serde_json::Value::String(long));
853        assert!(it.label.ends_with("..."));
854        assert_eq!(it.label.chars().count(), 67);
855    }
856
857    #[test]
858    fn test_gather_results_jsonl_rows_carry_everything() {
859        let results = vec![
860            ScatterResult {
861                item: item("a"),
862                result: ExecResult::success("result_a\n"),
863                timed_out: false,
864            },
865            ScatterResult {
866                item: item("b"),
867                result: ExecResult::failure(7, "boom\n"),
868                timed_out: false,
869            },
870        ];
871        let out = gather_results(&results, &GatherOptions::default());
872        assert_eq!(out.code, 123, "any failure → 123 (A′)");
873        let rows: Vec<serde_json::Value> = out
874            .text_out()
875            .lines()
876            .map(|l| serde_json::from_str(l).unwrap())
877            .collect();
878        assert_eq!(rows.len(), 2, "every worker gets a row, failures included");
879        assert_eq!(rows[0]["i"], 0);
880        assert_eq!(rows[0]["item"], "a");
881        assert_eq!(rows[0]["ok"], true);
882        assert_eq!(rows[0]["out"], "result_a", "trailing newline stripped");
883        assert_eq!(rows[0]["err"], "", "err always present");
884        assert!(rows[0].get("timed_out").is_none(), "omit-false");
885        assert!(rows[0].get("data").is_none(), "omit-empty");
886        assert_eq!(rows[1]["i"], 1);
887        assert_eq!(rows[1]["ok"], false);
888        assert_eq!(rows[1]["code"], 7);
889        assert_eq!(rows[1]["err"], "boom");
890        // .data carries the typed array for iteration / post-gather.
891        assert!(matches!(out.data, Some(Value::Json(serde_json::Value::Array(_)))));
892    }
893
894    #[test]
895    fn test_gather_results_all_ok_is_zero() {
896        let results = vec![ScatterResult {
897            item: item("a"),
898            result: ExecResult::success("x"),
899            timed_out: false,
900        }];
901        let out = gather_results(&results, &GatherOptions::default());
902        assert_eq!(out.code, 0);
903        assert!(out.err.is_empty());
904    }
905
906    #[test]
907    fn test_gather_results_timeout_row_is_124() {
908        let results = vec![ScatterResult {
909            item: item("slow"),
910            result: ExecResult::failure(1, "cancelled"),
911            timed_out: true,
912        }];
913        let out = gather_results(&results, &GatherOptions::default());
914        assert_eq!(out.code, 123);
915        let row: serde_json::Value = serde_json::from_str(out.text_out().lines().next().unwrap()).unwrap();
916        assert_eq!(row["code"], 124, "timeout reports the timeout(1) code");
917        assert_eq!(row["ok"], false);
918        assert_eq!(row["timed_out"], true);
919    }
920
921    #[test]
922    fn test_gather_results_typed_record_item_in_row() {
923        let results = vec![ScatterResult {
924            item: ScatterItem::new(serde_json::json!({"id": 3, "host": "web1"})),
925            result: ExecResult::success("ok"),
926            timed_out: false,
927        }];
928        let out = gather_results(&results, &GatherOptions::default());
929        let row: serde_json::Value = serde_json::from_str(out.text_out().lines().next().unwrap()).unwrap();
930        assert_eq!(row["item"]["id"], 3, "row item is the TYPED value, not a string");
931    }
932
933    #[test]
934    fn test_gather_results_worker_data_rides_the_row() {
935        let mut r = ExecResult::success("text");
936        r.data = Some(Value::Json(serde_json::json!({"k": 1})));
937        let results = vec![ScatterResult { item: item("a"), result: r, timed_out: false }];
938        let out = gather_results(&results, &GatherOptions::default());
939        let row: serde_json::Value = serde_json::from_str(out.text_out().lines().next().unwrap()).unwrap();
940        assert_eq!(row["data"]["k"], 1, "worker .data lands typed in the row");
941        assert_eq!(row["out"], "text", "out stays alongside data");
942    }
943
944    #[test]
945    fn test_gather_results_lines_happy_path() {
946        let results = vec![
947            ScatterResult { item: item("a"), result: ExecResult::success("result_a\n"), timed_out: false },
948            ScatterResult { item: item("b"), result: ExecResult::success("result_b"), timed_out: false },
949        ];
950        let out = gather_results(&results, &GatherOptions { lines: true, ..Default::default() });
951        assert_eq!(out.code, 0);
952        assert_eq!(&*out.text_out(), "result_a\nresult_b");
953    }
954
955    #[test]
956    fn test_gather_results_lines_hard_errors_on_any_failure() {
957        // Bare lines can't represent a failure — no partial text, loud 123.
958        let results = vec![
959            ScatterResult { item: item("a"), result: ExecResult::success("good"), timed_out: false },
960            ScatterResult { item: item("b"), result: ExecResult::failure(1, "boom"), timed_out: false },
961        ];
962        let out = gather_results(&results, &GatherOptions { lines: true, ..Default::default() });
963        assert_eq!(out.code, 123);
964        assert!(out.text_out().is_empty(), "no partial text on --lines failure");
965        assert!(out.err.contains("b"), "names the failed item: {}", out.err);
966    }
967
968    #[test]
969    fn test_parse_scatter_options() {
970        use crate::tools::ToolArgs;
971
972        let mut args = ToolArgs::new();
973        args.named.insert("as".to_string(), Value::String("URL".to_string()));
974        args.named.insert("limit".to_string(), Value::Int(4));
975
976        let opts = parse_scatter_options(&args).unwrap();
977        assert_eq!(opts.var_name, "URL");
978        assert_eq!(opts.limit, 4);
979    }
980
981    #[test]
982    fn test_parse_gather_options() {
983        use crate::tools::ToolArgs;
984
985        let mut args = ToolArgs::new();
986        args.flags.insert("lines".to_string());
987
988        let opts = parse_gather_options(&args).unwrap();
989        assert!(opts.lines);
990        assert!(!parse_gather_options(&ToolArgs::new()).unwrap().lines, "default is JSONL");
991    }
992
993    #[test]
994    fn scatter_limit_clamps_to_ceiling() {
995        use crate::tools::ToolArgs;
996
997        let mut args = ToolArgs::new();
998        args.named.insert("limit".to_string(), Value::Int(999_999));
999        let opts = parse_scatter_options(&args).unwrap();
1000        assert_eq!(opts.limit, SCATTER_LIMIT_MAX);
1001    }
1002
1003    #[test]
1004    fn scatter_limit_raises_zero_to_one() {
1005        use crate::tools::ToolArgs;
1006
1007        let mut args = ToolArgs::new();
1008        args.named.insert("limit".to_string(), Value::Int(0));
1009        let opts = parse_scatter_options(&args).unwrap();
1010        assert_eq!(opts.limit, 1);
1011    }
1012
1013    #[test]
1014    fn scatter_limit_raises_negative_to_one() {
1015        use crate::tools::ToolArgs;
1016
1017        let mut args = ToolArgs::new();
1018        args.named.insert("limit".to_string(), Value::Int(-42));
1019        let opts = parse_scatter_options(&args).unwrap();
1020        assert_eq!(opts.limit, 1);
1021    }
1022
1023    #[test]
1024    fn scatter_limit_preserves_valid_values() {
1025        use crate::tools::ToolArgs;
1026
1027        let mut args = ToolArgs::new();
1028        args.named.insert("limit".to_string(), Value::Int(500));
1029        let opts = parse_scatter_options(&args).unwrap();
1030        assert_eq!(opts.limit, 500);
1031    }
1032
1033    // ── FIX A: loud on present-but-wrong-typed flag values ──
1034
1035    #[test]
1036    fn scatter_limit_wrong_type_is_loud_error() {
1037        use crate::tools::ToolArgs;
1038
1039        let mut args = ToolArgs::new();
1040        args.named.insert("limit".to_string(), Value::String("five".to_string()));
1041        let err = parse_scatter_options(&args).unwrap_err();
1042        assert!(err.contains("--limit"), "{err}");
1043        assert!(err.contains("five"), "{err}");
1044    }
1045
1046    #[test]
1047    fn scatter_limit_bool_is_loud_error() {
1048        use crate::tools::ToolArgs;
1049
1050        let mut args = ToolArgs::new();
1051        args.named.insert("limit".to_string(), Value::Bool(true));
1052        let err = parse_scatter_options(&args).unwrap_err();
1053        assert!(err.contains("--limit"), "{err}");
1054    }
1055
1056    #[test]
1057    fn scatter_limit_numeric_string_coerces() {
1058        // Values from variables often stringify: `scatter --limit "$n"`.
1059        use crate::tools::ToolArgs;
1060
1061        let mut args = ToolArgs::new();
1062        args.named.insert("limit".to_string(), Value::String("5".to_string()));
1063        let opts = parse_scatter_options(&args).unwrap();
1064        assert_eq!(opts.limit, 5);
1065    }
1066
1067    #[test]
1068    fn scatter_as_wrong_type_is_loud_error() {
1069        use crate::tools::ToolArgs;
1070
1071        let mut args = ToolArgs::new();
1072        args.named.insert("as".to_string(), Value::Int(42));
1073        let err = parse_scatter_options(&args).unwrap_err();
1074        assert!(err.contains("--as"), "{err}");
1075        assert!(err.contains("42"), "{err}");
1076    }
1077
1078    #[test]
1079    fn scatter_timeout_negative_int_is_loud_error() {
1080        use crate::tools::ToolArgs;
1081
1082        let mut args = ToolArgs::new();
1083        args.named.insert("timeout".to_string(), Value::Int(-5));
1084        let err = parse_scatter_options(&args).unwrap_err();
1085        assert!(err.contains("--timeout"), "{err}");
1086    }
1087
1088    #[test]
1089    fn scatter_timeout_unparseable_string_is_loud_error() {
1090        use crate::tools::ToolArgs;
1091
1092        let mut args = ToolArgs::new();
1093        args.named.insert("timeout".to_string(), Value::String("banana".to_string()));
1094        let err = parse_scatter_options(&args).unwrap_err();
1095        assert!(err.contains("--timeout"), "{err}");
1096        assert!(err.contains("banana"), "{err}");
1097    }
1098
1099    #[test]
1100    fn scatter_timeout_valid_duration_string_parses() {
1101        use crate::tools::ToolArgs;
1102
1103        let mut args = ToolArgs::new();
1104        args.named.insert("timeout".to_string(), Value::String("5s".to_string()));
1105        let opts = parse_scatter_options(&args).unwrap();
1106        assert_eq!(opts.timeout, Some(Duration::from_secs(5)));
1107    }
1108
1109    #[test]
1110    fn scatter_timeout_nonnegative_int_is_seconds() {
1111        use crate::tools::ToolArgs;
1112
1113        let mut args = ToolArgs::new();
1114        args.named.insert("timeout".to_string(), Value::Int(30));
1115        let opts = parse_scatter_options(&args).unwrap();
1116        assert_eq!(opts.timeout, Some(Duration::from_secs(30)));
1117    }
1118
1119    // ── FIX C: binary worker output must not silently corrupt to U+FFFD ──
1120
1121    fn binary_result(invalid_utf8: Vec<u8>) -> ExecResult {
1122        ExecResult::success_bytes(invalid_utf8)
1123    }
1124
1125    #[test]
1126    fn gather_row_goes_loud_not_lossy_on_binary_out() {
1127        // 0xFF is never valid UTF-8 on its own — text_out() would replace it
1128        // with U+FFFD; try_text_out() must catch it instead.
1129        let results = vec![ScatterResult {
1130            item: item("bin"),
1131            result: binary_result(vec![0xFF, 0xFE, 0x00, 0x01]),
1132            timed_out: false,
1133        }];
1134        let out = gather_results(&results, &GatherOptions::default());
1135        assert_eq!(out.code, 123, "a binary row flips the overall exit code too");
1136        let row: serde_json::Value =
1137            serde_json::from_str(out.text_out().lines().next().unwrap()).unwrap();
1138        assert_eq!(row["ok"], false, "binary output must not be silently ok:true");
1139        assert_ne!(row["code"], 0, "must carry a nonzero code");
1140        assert!(row["out"].as_str().unwrap().is_empty(), "no lossy text in out");
1141        let err_text = row["err"].as_str().unwrap();
1142        assert!(err_text.contains("binary"), "{err_text}");
1143        assert!(!err_text.contains('\u{FFFD}'), "must not carry U+FFFD: {err_text}");
1144    }
1145
1146    #[test]
1147    fn gather_lines_hard_errors_on_binary_out() {
1148        // --lines is the raw-text escape hatch; binary must hard-error the
1149        // whole gather rather than emit a U+FFFD-laden line.
1150        let results = vec![
1151            ScatterResult { item: item("a"), result: ExecResult::success("good"), timed_out: false },
1152            ScatterResult {
1153                item: item("bin"),
1154                result: binary_result(vec![0xFF, 0xFE]),
1155                timed_out: false,
1156            },
1157        ];
1158        let out = gather_results(&results, &GatherOptions { lines: true, ..Default::default() });
1159        assert_eq!(out.code, 123);
1160        assert!(out.text_out().is_empty(), "no partial/lossy text on binary --lines failure");
1161        assert!(!out.err.contains('\u{FFFD}'), "must not carry U+FFFD: {}", out.err);
1162        assert!(out.err.contains("binary") || out.err.contains("bin"), "{}", out.err);
1163    }
1164
1165    // ── FIX D: workers must inherit the parent's watchdog ──
1166
1167    fn ctx_with_memory_fs() -> ExecContext {
1168        use crate::vfs::{MemoryFs, VfsRouter};
1169        use std::sync::Arc;
1170        let mut vfs = VfsRouter::new();
1171        vfs.mount("/", MemoryFs::new());
1172        ExecContext::new(Arc::new(vfs))
1173    }
1174
1175    #[test]
1176    fn worker_ctx_inherits_parent_watchdog() {
1177        use crate::watchdog::Watchdog;
1178        use std::sync::Arc;
1179
1180        let mut parent = ctx_with_memory_fs();
1181        parent.watchdog = Some(Arc::new(Watchdog::new(Duration::from_secs(30))));
1182
1183        // The fix: workers are built via `child_for_pipeline`, which clones the
1184        // parent's watchdog. The old from-scratch `with_backend_and_scope`
1185        // path (below) dropped it — this test would fail against that path.
1186        let worker_ctx = parent.child_for_pipeline();
1187        assert!(
1188            worker_ctx.watchdog.is_some(),
1189            "worker must carry the parent's script watchdog, not None"
1190        );
1191
1192        // Document the trap the fix closes: the old construction starts with a
1193        // None watchdog, which dispatch_command then syncs into the subkernel.
1194        let from_scratch =
1195            ExecContext::with_backend_and_scope(parent.backend.clone(), parent.scope.clone());
1196        assert!(
1197            from_scratch.watchdog.is_none(),
1198            "the abandoned from-scratch path is exactly why the worker lost its watchdog"
1199        );
1200    }
1201
1202    // ── FIX E: workers cap output against the shared spill budget ──
1203
1204    #[tokio::test]
1205    async fn worker_spills_over_the_shared_output_limit() {
1206        use crate::output_limit::{spill_if_needed, OutputLimitConfig};
1207
1208        // Small in-memory limit (no disk writes in tests — CLAUDE.md).
1209        let mut cfg = OutputLimitConfig::agent().in_memory();
1210        cfg.set_limit(Some(64));
1211
1212        let mut parent = ctx_with_memory_fs();
1213        parent.output_limit = cfg;
1214
1215        // `child_for_pipeline` shares the parent's output_limit, so the worker
1216        // caps against the same budget — this is exactly what the worker path
1217        // now reads (`worker_ctx.output_limit`) before building its
1218        // ScatterResult.
1219        let worker_ctx = parent.child_for_pipeline();
1220        assert!(worker_ctx.output_limit.is_enabled(), "budget must reach the worker");
1221
1222        // Mirror the worker sequence: a large result, then the per-worker spill.
1223        let mut result = ExecResult::success("x".repeat(4096));
1224        assert!(worker_ctx.output_limit.is_enabled());
1225        let _ = spill_if_needed(&mut result, &worker_ctx.output_limit).await;
1226
1227        assert!(result.did_spill, "worker output over the limit must spill, not stay resident");
1228        assert!(
1229            result.text_out().len() < 4096,
1230            "spilled output must be truncated, not the full payload: {} bytes",
1231            result.text_out().len()
1232        );
1233    }
1234}