Skip to main content

oxdock_core/exec/
mod.rs

1mod args;
2mod capture;
3#[cfg(any(test, feature = "test-harness"))]
4pub mod conformance;
5mod engine;
6mod exit;
7mod fs_ops;
8mod handlers;
9mod import;
10mod io;
11pub mod mcp;
12mod native;
13pub mod remote;
14mod state;
15mod static_check;
16mod steps;
17#[cfg(test)]
18mod tests;
19mod typing;
20
21pub use self::remote::{
22    RemoteRequest, RemoteResponse, RemoteRunner, TransferStage, apply_push_dir, apply_push_file,
23    apply_push_symlink,
24};
25
26pub use self::args::{json_to_value, json_to_value_typed, value_to_json, value_to_json_typed};
27#[cfg(any(test, feature = "test-harness"))]
28pub use self::conformance::assert_module_returns_conformance;
29pub use self::engine::{Engine, EngineOutput};
30pub use self::exit::{ExitRequest, exit_code_of};
31pub(crate) use self::handlers::{
32    dispatch_append, dispatch_archive, dispatch_assert_contains, dispatch_assert_eq,
33    dispatch_assign, dispatch_assign_async_step, dispatch_assign_capture_step,
34    dispatch_async_block, dispatch_await_capture_step, dispatch_await_step, dispatch_break,
35    dispatch_call, dispatch_cancel_step, dispatch_continue, dispatch_copy, dispatch_copy_git,
36    dispatch_echo, dispatch_env, dispatch_exit, dispatch_expand, dispatch_for_loop,
37    dispatch_func_def, dispatch_if_then, dispatch_import_file, dispatch_import_funcs,
38    dispatch_inherit_env, dispatch_install, dispatch_isolated_inherit_env, dispatch_isolated_step,
39    dispatch_ls, dispatch_mkdir, dispatch_prompt, dispatch_push_into_step, dispatch_read,
40    dispatch_read_line, dispatch_remote, dispatch_remove, dispatch_return, dispatch_run,
41    dispatch_run_exec, dispatch_set, dispatch_sleep_step, dispatch_symlink, dispatch_timeout_step,
42    dispatch_unarchive, dispatch_while_loop, dispatch_with_io, dispatch_with_io_block,
43    dispatch_workdir, dispatch_workspace, dispatch_write,
44};
45pub use self::import::{DryRunStep, dry_run_closure};
46pub use self::io::ExecIo;
47pub use self::io::PipeStream;
48pub use self::io::PushManifestSink;
49pub use self::io::{StreamChunk, StreamHook, TeeStream};
50pub use self::mcp::{McpCallOutput, McpSession};
51pub use self::native::{
52    FuncKind, FuncMeta, FuncParam, FunctionRegistry, HostModule, HostRegistration, NativeFn,
53    OxDockFn, ParamOption, PreRunCheck, PureFn, PureTable, RecordSchema, builtin_function_metas,
54    builtin_function_names, fill_optional_args, required_arity, std_module_table,
55};
56pub use self::state::ExecState;
57pub use self::state::MAX_RUNNING_TASKS;
58pub use self::steps::StepCtx;
59pub use self::typing::{
60    Field, LIST_TAG, MAP_TAG, OxDockType, TypeDescriptor, TypeTag, Value, ValuePayload,
61    check_options, check_value, check_value_at, clone_boxed, clone_copy, clone_shared, drop_boxed,
62    drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed, fmt_inline, fmt_shared,
63    load_inline, startup_descriptors, store_inline, type_anchor, unshare_boxed, unshare_inline,
64    unshare_shared,
65};
66
67use anyhow::Result;
68use oxdock_fs::{
69    GuardedPath, LazyGuardedTempDir, PathResolver, WorkspaceFs, reserve_cargo_scratch,
70};
71use oxdock_parser::Step;
72use oxdock_process::{
73    BuiltinEnv, DefaultProcessManager, ProcessManager, SharedInput, SharedOutput,
74    default_process_manager,
75};
76
77use std::collections::BTreeMap;
78use std::sync::Arc;
79
80use self::fs_ops::describe_dir;
81use self::io::{StreamHandle, assemble_default_io, teed_stderr, teed_stdout};
82use self::steps::execute_steps;
83
84/// Display text emitted by `CWD` while the snapshot root is selected but not
85/// yet materialized (issue #131). Single source of truth: the `cwd` handler
86/// prints this value, and the logic-test harness resolves the same value
87/// from `@SNAPSHOT_PENDING@` fixture tokens.
88pub const SNAPSHOT_PENDING_DISPLAY: &str = "<snapshot:pending>";
89
90/// Fallback tree body used when a materialized snapshot cannot be described
91/// while composing a run error (issue #131). Single source of truth for the
92/// lazy error path.
93pub const SNAPSHOT_TREE_UNAVAILABLE: &str = "<unavailable>";
94
95pub fn run_steps(fs_root: &GuardedPath, steps: &[Step]) -> Result<()> {
96    run_steps_with_context(fs_root, fs_root, steps)
97}
98
99pub fn run_steps_with_context(
100    fs_root: &GuardedPath,
101    build_context: &GuardedPath,
102    steps: &[Step],
103) -> Result<()> {
104    run_steps_with_context_result(fs_root, build_context, steps, None, None).map(|_| ())
105}
106
107/// Execute the DSL and return the final working directory after all steps.
108pub fn run_steps_with_context_result(
109    fs_root: &GuardedPath,
110    build_context: &GuardedPath,
111    steps: &[Step],
112    stdin: Option<SharedInput>,
113    stdout: Option<SharedOutput>,
114) -> Result<GuardedPath> {
115    let io = assemble_default_io(stdin, stdout);
116    run_steps_with_context_result_with_io(fs_root, build_context, steps, io)
117}
118
119pub fn run_steps_with_context_result_with_io(
120    fs_root: &GuardedPath,
121    build_context: &GuardedPath,
122    steps: &[Step],
123    io: ExecIo,
124) -> Result<GuardedPath> {
125    match run_steps_inner(fs_root, build_context, steps, io) {
126        Ok(final_cwd) => Ok(final_cwd),
127        Err(err) => {
128            let fs = PathResolver::new(fs_root.as_path(), build_context.as_path())?;
129            let tree = describe_dir(&fs, fs_root, 2, 24);
130            let snapshot = format!(
131                "filesystem snapshot (root {}):\n{}",
132                fs_root.display(),
133                tree
134            );
135            Err(compose_error_with_snapshot(err, snapshot))
136        }
137    }
138}
139
140/// Compose a single error message with the top cause plus a caller-provided
141/// filesystem-snapshot section. Shared by the eager and lazy runners so both
142/// render identical chains and only differ in the snapshot section.
143fn compose_error_with_snapshot(err: anyhow::Error, snapshot_section: String) -> anyhow::Error {
144    // Compose a single error message with the top cause plus a compact fs snapshot.
145    let chain = err.chain().map(|e| e.to_string()).collect::<Vec<_>>();
146    let mut primary = chain
147        .first()
148        .cloned()
149        .unwrap_or_else(|| "unknown error".into());
150    let rest = if chain.len() > 1 {
151        let first_cause = chain[1].clone();
152        primary = format!("{primary} ({first_cause})");
153        if chain.len() > 2 {
154            let causes = chain
155                .iter()
156                .skip(2)
157                .map(|s| s.as_str())
158                .collect::<Vec<_>>()
159                .join("\n  ");
160            format!("\ncauses:\n  {}", causes)
161        } else {
162            String::new()
163        }
164    } else {
165        String::new()
166    };
167    let msg = format!("{}{}\n{}", primary, rest, snapshot_section);
168    // The snapshot composer flattens the chain into one message for CLI
169    // rendering. Re-attach a relayed EXIT code as the inner error under
170    // that message: the text stays byte-identical while the code stays
171    // machine readable (context values are invisible to chain traversal,
172    // so the typed request must ride as a real error, not as context).
173    match exit::exit_code_of(&err) {
174        Some(code) => anyhow::Error::new(exit::ExitRequest(code)).context(msg),
175        None => anyhow::anyhow!(msg),
176    }
177}
178
179fn run_steps_inner(
180    fs_root: &GuardedPath,
181    build_context: &GuardedPath,
182    steps: &[Step],
183    io: ExecIo,
184) -> Result<GuardedPath> {
185    let mut resolver = PathResolver::new_guarded(fs_root.clone(), build_context.clone())?;
186    resolver.set_workspace_root(build_context.clone());
187    run_steps_with_fs_with_io(Box::new(resolver), steps, io)
188}
189
190/// Output of a lazily-executed run (issue #131): the final working directory
191/// (concretized as of return), shared ownership of the snapshot backing dir,
192/// and the filesystem handle for post-hoc convergence (e.g. concretizing the
193/// cwd after shell-entry materialization).
194pub struct LazyRunOutput {
195    pub final_cwd: GuardedPath,
196    pub snapshot: Arc<LazyGuardedTempDir>,
197    pub fs: Box<dyn WorkspaceFs>,
198    /// Top-level script variable bindings captured at `Flow::Done`, keyed by
199    /// variable name with deterministic ordering. Read-only introspection for
200    /// hosts that assert on in-memory evaluation without file round trips.
201    /// Ephemeral block scopes are excluded; see `run_steps_with_manager`.
202    pub bindings: BTreeMap<String, Value>,
203}
204
205/// Execute the DSL against a lazily-created snapshot: no temporary directory
206/// exists until the first snapshot-targeted resolution. The snapshot handle
207/// is shared with the resolver, so all clones observe the same directory.
208pub fn run_steps_with_lazy_snapshot(
209    build_context: &GuardedPath,
210    steps: &[Step],
211    io: ExecIo,
212) -> Result<LazyRunOutput> {
213    run_steps_with_lazy_snapshot_and_modules(build_context, steps, io, Vec::new(), Vec::new())
214}
215
216/// Same as [`run_steps_with_lazy_snapshot`], plus host modules and types
217/// (see [`run_steps_with_manager_with_modules`]). Lets binary hosts that
218/// run on the lazy snapshot path expose plugin surface without changing
219/// CLI semantics.
220pub fn run_steps_with_lazy_snapshot_and_modules(
221    build_context: &GuardedPath,
222    steps: &[Step],
223    io: ExecIo,
224    modules: Vec<HostModule<DefaultProcessManager>>,
225    types: Vec<&'static TypeDescriptor>,
226) -> Result<LazyRunOutput> {
227    run_steps_with_lazy_snapshot_and_modules_and_entry(
228        build_context,
229        steps,
230        io,
231        modules,
232        types,
233        None,
234    )
235}
236
237/// Same as [`run_steps_with_lazy_snapshot_and_modules`], plus the entry
238/// script file (#115): top-level relative `IMPORT` paths resolve against
239/// its parent directory.
240pub fn run_steps_with_lazy_snapshot_and_modules_and_entry(
241    build_context: &GuardedPath,
242    steps: &[Step],
243    io: ExecIo,
244    modules: Vec<HostModule<DefaultProcessManager>>,
245    types: Vec<&'static TypeDescriptor>,
246    entry_file: Option<GuardedPath>,
247) -> Result<LazyRunOutput> {
248    let mut resolver = PathResolver::new_lazy(build_context.clone())?;
249    resolver.set_workspace_root(build_context.clone());
250    let snapshot = resolver.snapshot_handle();
251    let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
252    match run_steps_with_manager_with_modules_and_entry(
253        fs,
254        steps,
255        default_process_manager(),
256        io,
257        modules,
258        types,
259        entry_file,
260    ) {
261        Ok((final_cwd, fs, bindings)) => Ok(LazyRunOutput {
262            final_cwd,
263            snapshot,
264            fs,
265            bindings,
266        }),
267        Err(err) => Err(enrich_lazy_error(&snapshot, build_context, err)),
268    }
269}
270
271/// Error enrichment for lazy runs: a materialized snapshot gets the same
272/// filesystem-snapshot treatment as eager runs; a pending one reports that
273/// no snapshot directory was ever created instead of describing a tree.
274/// Chain rendering is identical to the eager path (shared composer).
275pub fn enrich_lazy_error(
276    snapshot: &Arc<LazyGuardedTempDir>,
277    build_context: &GuardedPath,
278    err: anyhow::Error,
279) -> anyhow::Error {
280    match snapshot.get() {
281        Some(concrete) => {
282            let tree = match PathResolver::new(concrete.as_path(), build_context.as_path()) {
283                Ok(describe_fs) => describe_dir(&describe_fs, concrete, 2, 24),
284                Err(_) => String::from(SNAPSHOT_TREE_UNAVAILABLE),
285            };
286            let snapshot_msg = format!(
287                "filesystem snapshot (root {}):\n{}",
288                concrete.display(),
289                tree
290            );
291            compose_error_with_snapshot(err, snapshot_msg)
292        }
293        None => compose_error_with_snapshot(
294            err,
295            String::from(
296                "filesystem snapshot: never materialized (no snapshot directory was created)",
297            ),
298        ),
299    }
300}
301
302pub fn run_steps_with_fs(
303    fs: Box<dyn WorkspaceFs>,
304    steps: &[Step],
305    stdin: Option<SharedInput>,
306    stdout: Option<SharedOutput>,
307) -> Result<GuardedPath> {
308    let io = assemble_default_io(stdin, stdout);
309    run_steps_with_fs_with_io(fs, steps, io)
310}
311
312pub fn run_steps_with_fs_with_io(
313    fs: Box<dyn WorkspaceFs>,
314    steps: &[Step],
315    io: ExecIo,
316) -> Result<GuardedPath> {
317    run_steps_with_manager(fs, steps, default_process_manager(), io).map(|(cwd, _, _)| cwd)
318}
319
320/// Base name of a qualified `MODULE::NAME` reference for human-facing
321/// errors. Single source lives in `oxdock-parser`; listings (`FUNCTIONS()`,
322/// `DESCRIBE`) keep the qualified form while step errors name the callable
323/// as written.
324pub(crate) use oxdock_parser::base_name;
325
326/// Host introspection entry point: execute the DSL against a caller-provided
327/// filesystem and return the final working directory, the filesystem handle,
328/// and the top-level script variable bindings captured at `Flow::Done`.
329/// Bindings are read from the root variable scope only, so ephemeral
330/// variables from `FUNC` bodies, `FOR`/`WHILE` iterations, and `ASYNC` blocks
331/// are excluded. On script failure the scope is discarded with the error and
332/// no bindings are returned.
333#[allow(clippy::type_complexity)]
334pub fn run_steps_with_manager<P: ProcessManager>(
335    fs: Box<dyn WorkspaceFs>,
336    steps: &[Step],
337    process: P,
338    io: ExecIo,
339) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
340    run_steps_with_manager_with_modules(fs, steps, process, io, Vec::new(), Vec::new())
341}
342
343/// Same as [`run_steps_with_manager`], plus host modules and types. Each
344/// module's functions become callable as `MODULE::NAME` with full step
345/// context; each type descriptor becomes visible to `TYPES()` and valid for
346/// `LET $x: NAME` declarations carrying same-named opaque payloads.
347/// Authors should derive entries with `#[oxdock_func]` / `#[oxdock_type]`
348/// (see `oxdock-func-macro`) and group them into [`HostModule`] instead of
349/// hand-writing metadata and glue.
350#[allow(clippy::type_complexity)]
351pub fn run_steps_with_manager_with_modules<P: ProcessManager>(
352    fs: Box<dyn WorkspaceFs>,
353    steps: &[Step],
354    process: P,
355    io: ExecIo,
356    modules: Vec<HostModule<P>>,
357    types: Vec<&'static self::typing::TypeDescriptor>,
358) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
359    run_steps_with_manager_with_modules_and_entry(fs, steps, process, io, modules, types, None)
360}
361
362/// Same as [`run_steps_with_manager_with_modules`], plus the entry script
363/// file (#115): top-level relative `IMPORT` paths resolve against its
364/// parent directory. `None` resolves imports against the workspace root.
365#[allow(clippy::type_complexity)]
366#[allow(clippy::too_many_arguments)]
367pub fn run_steps_with_manager_with_modules_and_entry<P: ProcessManager>(
368    fs: Box<dyn WorkspaceFs>,
369    steps: &[Step],
370    process: P,
371    io: ExecIo,
372    modules: Vec<HostModule<P>>,
373    types: Vec<&'static self::typing::TypeDescriptor>,
374    entry_file: Option<GuardedPath>,
375) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
376    let mut state = new_state(fs, io)?;
377    state.entry_file = entry_file;
378    state.module_table = build_module_table(&modules);
379    for module in &modules {
380        // Pre-run checks first: unmapped services fail here, before the
381        // first step executes and with zero side effects.
382        module.check_pre_run(steps)?;
383    }
384    for module in modules {
385        state.register_module(module);
386    }
387    for descriptor in types {
388        state.register_type(descriptor);
389    }
390    finish_run(state, process, steps)
391}
392
393pub(crate) fn new_state<P: ProcessManager>(
394    fs: Box<dyn WorkspaceFs>,
395    io: ExecIo,
396) -> Result<ExecState<P>> {
397    let cwd = fs.root().clone();
398    let build_context = fs.build_context().clone();
399    let cargo_scratch = reserve_cargo_scratch()?;
400    // Seeded script environment: sandbox defaults first, then explicit
401    // layers win (BuiltinEnv sanctions, `io` overrides route host
402    // entries). The pure seed is stored alongside for `ISOLATED`
403    // resets and transport sanitize.
404    let seed = Arc::new(oxdock_process::seed_defaults(
405        &cargo_scratch.tmp_seed_display(),
406        &cargo_scratch.target_seed_display(),
407    ));
408    let mut envs = (*seed).clone();
409    envs.extend(BuiltinEnv::collect(&build_context).into_envs());
410    for (key, value) in io.inherit_env_overrides() {
411        envs.insert(key.clone(), value.clone());
412    }
413    let envs = Arc::new(envs);
414    let assert_windows = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
415    let assert_windows_stderr = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
416    let exact_stdout = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
417    // Run-scoped worker telemetry: the root hub adopts the staged
418    // counter so every pump worker this run spawns attributes to it.
419    let worker_counter = io.worker_counter();
420    let mut state = ExecState {
421        fs,
422        cargo_scratch,
423        seed,
424        cwd: cwd.clone(),
425        initial_root: cwd,
426        envs,
427        bg_children: Vec::new(),
428        scope_stack: Vec::new(),
429        isolated_stack: Vec::new(),
430        io,
431        assert_windows: assert_windows.clone(),
432        assert_windows_stderr: assert_windows_stderr.clone(),
433        exact_stdout: exact_stdout.clone(),
434        var_scopes: Vec::new(),
435        cancel_token: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
436        cancel_hub: std::sync::Arc::new(oxdock_process::CancelHub::with_counter(worker_counter)),
437        active_process: std::sync::Arc::new(std::sync::Mutex::new(None)),
438        named_tasks: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
439        next_task_id: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1)),
440        live_tasks: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
441        inside_async: false,
442        keeper_expiry: None,
443        cancellable: false,
444        reap_floor: None,
445        functions: self::native::FunctionRegistry::with_builtins(),
446        entry_file: None,
447        import_stack: Vec::new(),
448        import_alias_frame: None,
449        modules: std::collections::HashMap::new(),
450        module_stack: Vec::new(),
451        module_table: self::native::std_module_table(),
452        types: self::typing::startup_type_map(),
453        record_schemas: std::collections::HashMap::new(),
454        module_states: std::collections::HashMap::new(),
455        type_aliases: std::collections::HashMap::new(),
456        call_depth: 0,
457        // Root flow is task 0; worker ids start at 1 (see next_task_id).
458        task_id: 0,
459        push_manifest: Vec::new(),
460        _marker: std::marker::PhantomData,
461    };
462
463    // Push a global variable scope so top-level LET assignments are captured.
464    state.push_var_scope();
465
466    Ok(state)
467}
468
469/// Parse-time module table for `state`: stock `STD` builtins plus every
470/// staged host module, mirroring [`Engine::module_table`]. Imported files
471/// (#115) parse with this table so their `IMPORT [STD]` and qualified
472/// calls resolve exactly like the entry script's.
473fn build_module_table<P: ProcessManager>(
474    modules: &[self::native::HostModule<P>],
475) -> oxdock_parser::ModuleTable {
476    let mut table = self::native::std_module_table();
477    for module in modules {
478        let mut func_names = std::collections::HashSet::new();
479        for registration in &module.funcs {
480            let name = match registration {
481                self::native::HostRegistration::Stateful { name, .. } => name,
482                self::native::HostRegistration::Pure { name, .. } => name,
483                self::native::HostRegistration::Both { name, .. } => name,
484            };
485            func_names.insert(name.clone());
486        }
487        table.modules.insert(
488            module.name.clone(),
489            Some(oxdock_parser::ModuleFuncs { func_names }),
490        );
491    }
492    table
493}
494
495#[allow(clippy::type_complexity)]
496fn finish_run<P: ProcessManager>(
497    mut state: ExecState<P>,
498    process: P,
499    steps: &[Step],
500) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
501    // Execution boundary: every run entry point funnels through here, so
502    // typo'd param and return type tags fail before any step runs. A bad
503    // label is a programmer error, never a runtime value.
504    state.type_aliases = self::typing::collect_type_aliases(steps, &state)?;
505    state.validate_function_type_tags()?;
506    // Script-side counterpart: terminal unification, MissingReturn,
507    // undeclared variables, and ungated ANY flow fail here too,
508    // before any step runs. The closure pass covers the entry script
509    // plus every transitively imported file (#115): cross-file calls
510    // typecheck against the collected signatures, so no nested file
511    // can smuggle a type error past the entry gate.
512    let saved_aliases = state.type_aliases.clone();
513    let closure = self::import::expand_import_closure(&mut state, steps)?;
514    for file in &closure {
515        let aliases = self::typing::collect_type_aliases(&file.steps, &state)?;
516        // Validation is permissive (global) for v1: all file aliases
517        // merge bare, like host types. Runtime persistence stays strict
518        // (only exported + imported persist); static gating for
519        // harvests (unexported fails) lives in `collect_site`.
520        for (name, target) in &aliases {
521            state.type_aliases.insert(name.clone(), target.clone());
522        }
523    }
524    static_check::validate_script_closure(steps, &closure, &state)?;
525    state.type_aliases = saved_aliases;
526    let assert_windows = Arc::clone(&state.assert_windows);
527    let assert_windows_stderr = Arc::clone(&state.assert_windows_stderr);
528    let exact_stdout = Arc::clone(&state.exact_stdout);
529    let _default_stdout = std::io::stdout();
530    let stdin = state.io.stdin().into();
531    // Every emitted byte flows through the tee so stream assertions see both
532    // interpreter output and streamed child output, even when no capture
533    // sink was configured (forwarding to real stdout in that case).
534    let stdout = Some(StreamHandle::Stream(teed_stdout(
535        state.io.stdout(),
536        assert_windows,
537        exact_stdout,
538        None,
539    )));
540    let stderr = state
541        .io
542        .stderr()
543        .map(|sink| StreamHandle::Stream(teed_stderr(Some(sink), assert_windows_stderr, None)));
544    let mut proc_mgr = process;
545    let flow = execute_steps(
546        &mut state,
547        &mut proc_mgr,
548        steps,
549        stdin,
550        false,
551        stdout,
552        stderr,
553        None,
554        None,
555        true,
556    )?;
557    match flow {
558        // Concretize on the way out so a bare pending anchor never escapes as
559        // the reported final directory (shell entry / OUT_DIR sync need real
560        // paths; a pending run reports the local root or concretizes after
561        // shell-entry materialization through the returned fs handle).
562        self::steps::Flow::Done => {
563            // Root-scope isolation: at Done all blocks have popped, so the
564            // first scope is the global one. Read it explicitly (rather than
565            // a flattened all-scopes view) and strip declared types so hosts
566            // see plain values.
567            let bindings: BTreeMap<String, Value> = state
568                .var_scopes
569                .first()
570                .map(|scope| {
571                    scope
572                        .iter()
573                        .map(|(k, (_, v))| (k.clone(), v.clone()))
574                        .collect()
575                })
576                .unwrap_or_default();
577            Ok((state.fs.concretize_cwd(&state.cwd), state.fs, bindings))
578        }
579        self::steps::Flow::Break { idx } => {
580            anyhow::bail!("step {}: BREAK outside loop", idx + 1)
581        }
582        self::steps::Flow::Continue { idx } => {
583            anyhow::bail!("step {}: CONTINUE outside loop", idx + 1)
584        }
585        self::steps::Flow::Return { idx, .. } => {
586            // Values only cross a boundary: a function call, an ASYNC
587            // task, or an inline LET block. With none enclosing, the
588            // pipeline top rejects it like any other escaped flow.
589            anyhow::bail!(
590                "step {}: RETURN outside function, ASYNC task, or LET block",
591                idx + 1
592            )
593        }
594    }
595}