Skip to main content

oxdock_core/
lib.rs

1extern crate self as oxdock_core;
2
3pub mod exec;
4pub mod pipeline;
5pub use exec::*;
6pub use oxdock_parser::{
7    Arg, ArgType, CommandMeta, CommandSpec, Example, StepKind, all_metadata,
8    all_structural_metadata, lower_command,
9};
10pub use oxdock_process::ProcessManager;
11
12define_pipeline! {
13    StepKind::Run(..) => exec::dispatch_run,
14    StepKind::RunExec { .. } => exec::dispatch_run_exec,
15    StepKind::AsyncBlock { .. } => exec::dispatch_async_block,
16    StepKind::Echo(..) => exec::dispatch_echo,
17    StepKind::Workdir(..) => exec::dispatch_workdir,
18    StepKind::Workspace(..) => exec::dispatch_workspace,
19    StepKind::RemoteBlock { .. } => exec::dispatch_remote,
20    StepKind::Env { .. } => exec::dispatch_env,
21    StepKind::Copy { .. } => exec::dispatch_copy,
22    StepKind::CopyGit { .. } => exec::dispatch_copy_git,
23    StepKind::Archive { .. } => exec::dispatch_archive,
24    StepKind::Unarchive { .. } => exec::dispatch_unarchive,
25    StepKind::Symlink { .. } => exec::dispatch_symlink,
26    StepKind::Mkdir(..) => exec::dispatch_mkdir,
27    StepKind::Install { .. } => exec::dispatch_install,
28    StepKind::Ls(..) => exec::dispatch_ls,
29    StepKind::Cwd => exec::dispatch_cwd,
30    StepKind::Read(..) => exec::dispatch_read,
31    StepKind::ReadLine { .. } => exec::dispatch_read_line,
32    StepKind::Prompt { .. } => exec::dispatch_prompt,
33    StepKind::Write { .. } => exec::dispatch_write,
34    StepKind::Append { .. } => exec::dispatch_append,
35    StepKind::Remove { .. } => exec::dispatch_remove,
36    StepKind::Expand { .. } => exec::dispatch_expand,
37    StepKind::AssertEq { .. } => exec::dispatch_assert_eq,
38    StepKind::AssertContains { .. } => exec::dispatch_assert_contains,
39    StepKind::HashSha256 { .. } => exec::dispatch_hash_sha256,
40    StepKind::Exit(..) => exec::dispatch_exit,
41    StepKind::AssignAsync { .. } => exec::dispatch_assign_async_step,
42    StepKind::Set { .. } => exec::dispatch_set,
43    StepKind::Await { .. } => exec::dispatch_await_step,
44    StepKind::AssignCapture { .. } => exec::dispatch_assign_capture_step,
45    StepKind::AwaitCapture { .. } => exec::dispatch_await_capture_step,
46    StepKind::Cancel { .. } => exec::dispatch_cancel_step,
47    StepKind::Timeout { .. } => exec::dispatch_timeout_step,
48    StepKind::Isolated { .. } => exec::dispatch_isolated_step,
49    StepKind::IsolatedInheritEnv { .. } => exec::dispatch_isolated_inherit_env,
50    StepKind::Sleep { .. } => exec::dispatch_sleep_step,
51    StepKind::ListAppend { .. } => exec::dispatch_push_into_step,
52    StepKind::FuncDef { .. } => exec::dispatch_func_def,
53    StepKind::Call { .. } => exec::dispatch_call,
54    StepKind::Return { .. } => exec::dispatch_return,
55    StepKind::While { .. } => exec::dispatch_while_loop,
56    StepKind::Break => exec::dispatch_break,
57    StepKind::Continue => exec::dispatch_continue,
58}
59
60/// Parse a script using the production `lower_command` dispatcher.
61/// The typed `ParseError` converts into `anyhow::Error` at this boundary
62/// with no intermediate `.context()` wrapping, so the message survives.
63/// Builtin function names seed the reserved set, so `FUNC` shadowing a
64/// native fails here; hosts unknown at parse time fall back to the runtime
65/// `define_func` guard.
66pub fn parse_script(input: &str) -> anyhow::Result<Vec<oxdock_parser::Step>> {
67    parse_script_with_modules(input, std_module_table())
68}
69
70/// Parse with a module provenance table so calls resolve statically:
71/// qualified `MODULE::NAME` checks membership, bare `NAME` resolves through
72/// `SCRIPT` definitions and `IMPORT`ed modules. Reserved covers builtins
73/// plus every table module, so `FUNC` shadowing any of them fails here;
74/// hosts unknown at parse time fall back to the runtime `define_func`
75/// guard.
76pub fn parse_script_with_modules(
77    input: &str,
78    modules: oxdock_parser::ModuleTable,
79) -> anyhow::Result<Vec<oxdock_parser::Step>> {
80    let mut reserved = builtin_function_names();
81    reserved.extend(modules.reserved_base_names());
82    Ok(oxdock_parser::parse_script_with_modules(
83        input,
84        lower_command,
85        reserved,
86        modules,
87    )?)
88}
89
90/// Parse with modules plus single-file `EXPORT` metadata and `#` docs.
91/// Used by the MCP host; the linear runner ignores the extra fields.
92pub fn parse_script_with_modules_and_exports(
93    input: &str,
94    modules: oxdock_parser::ModuleTable,
95) -> anyhow::Result<oxdock_parser::ParsedScript> {
96    let mut reserved = builtin_function_names();
97    reserved.extend(modules.reserved_base_names());
98    Ok(oxdock_parser::parse_script_with_modules_and_exports(
99        input,
100        lower_command,
101        reserved,
102        modules,
103    )?)
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109    use indoc::indoc;
110    use oxdock_fs::{
111        GuardedPath, GuardedTempDir, PathResolver, env as oxdock_env, to_forward_slashes,
112    };
113    use std::time::Instant;
114
115    fn guard_root(temp: &GuardedTempDir) -> GuardedPath {
116        temp.as_guarded_path().clone()
117    }
118
119    fn read_trimmed(path: &GuardedPath) -> String {
120        let resolver = PathResolver::new(path.root(), path.root()).unwrap();
121        resolver
122            .read_to_string(path)
123            .unwrap_or_default()
124            .trim()
125            .to_string()
126    }
127
128    fn create_dirs(path: &GuardedPath) {
129        let resolver = PathResolver::new(path.root(), path.root()).unwrap();
130        resolver.create_dir_all(path).unwrap();
131    }
132
133    fn exists(root: &GuardedPath, rel: &str) -> bool {
134        root.join(rel).map(|p| p.exists()).unwrap_or(false)
135    }
136
137    #[test]
138    fn run_isolates_cargo_target_dir_from_workspace() {
139        let temp = GuardedPath::tempdir().unwrap();
140        let root = guard_root(&temp);
141
142        #[allow(clippy::disallowed_macros)]
143        let cmd = if cfg!(windows) {
144            "echo %CARGO_TARGET_DIR% > seen.txt"
145        } else {
146            "printf %s \"$CARGO_TARGET_DIR\" > seen.txt"
147        };
148
149        let steps = parse_script(&format!("RUN {cmd}")).unwrap();
150
151        run_steps(&root, &steps).unwrap();
152
153        let seen = read_trimmed(&root.join("seen.txt").unwrap());
154        let legacy = root.join(".cargo-target").unwrap();
155
156        assert_ne!(
157            seen.trim(),
158            legacy.display().to_string(),
159            "CARGO_TARGET_DIR must not target the workspace tree"
160        );
161        let normalized = seen.trim().replace('\\', "/");
162        assert!(
163            normalized.ends_with("/target") && normalized.contains("oxdock-"),
164            "CARGO_TARGET_DIR must point at the isolated scratch target dir, got {seen:?}"
165        );
166    }
167
168    #[test]
169    fn lazy_snapshot_run_materializes_but_local_run_does_not() {
170        let temp = GuardedPath::tempdir().unwrap();
171        let root = guard_root(&temp);
172
173        // Snapshot-rooted RUN executes against the snapshot workdir.
174        // The seeded host PATH resolves the shell with no allowlist.
175        let steps = parse_script("RUN echo hi").unwrap();
176        let output = run_steps_with_lazy_snapshot(&root, &steps, ExecIo::new()).unwrap();
177        assert!(
178            output.snapshot.is_materialized(),
179            "snapshot-rooted RUN must materialize the snapshot"
180        );
181
182        // LOCAL-rooted RUN executes against the live tree.
183        let steps = parse_script(indoc! {r#"
184            WORKSPACE LOCAL
185            RUN echo hi
186        "#})
187        .unwrap();
188        let output = run_steps_with_lazy_snapshot(&root, &steps, ExecIo::new()).unwrap();
189        assert!(
190            !output.snapshot.is_materialized(),
191            "LOCAL-rooted RUN must never materialize the snapshot"
192        );
193    }
194
195    #[test]
196    fn lazy_empty_run_creates_nothing() {
197        let temp = GuardedPath::tempdir().unwrap();
198        let root = guard_root(&temp);
199
200        let output = run_steps_with_lazy_snapshot(&root, &[], ExecIo::new()).unwrap();
201        assert!(!output.snapshot.is_materialized());
202        assert!(output.snapshot.get().is_none());
203    }
204
205    #[test]
206    fn lazy_local_echo_assert_failure_never_materializes_snapshot() {
207        let temp = GuardedPath::tempdir().unwrap();
208        let root = guard_root(&temp);
209
210        let script = indoc!(
211            r#"
212            WORKSPACE LOCAL
213            ECHO playground pid is 41067
214            ASSERT_CONTAINS stdout "playground pid i!!"
215            "#
216        );
217        let steps = parse_script(script).unwrap();
218
219        // Retain the snapshot handle across the failing run: the lazy
220        // convenience wrapper discards it on error, so drive the manager
221        // directly to pin the unmaterialized invariant (issue #131).
222        let mut resolver = PathResolver::new_lazy(root.clone()).unwrap();
223        resolver.set_workspace_root(root.clone());
224        let snapshot = resolver.snapshot_handle();
225        let fs: Box<dyn oxdock_fs::WorkspaceFs> = Box::new(resolver);
226        let result = run_steps_with_manager(
227            fs,
228            &steps,
229            oxdock_process::default_process_manager(),
230            ExecIo::new(),
231        );
232        assert!(result.is_err(), "mismatched ASSERT_CONTAINS must fail");
233        let err = result.err().unwrap();
234        assert!(!snapshot.is_materialized());
235        assert!(snapshot.get().is_none());
236
237        let enriched = enrich_lazy_error(&snapshot, &root, err);
238        let msg = enriched.to_string();
239        assert!(
240            msg.contains("did not contain 'playground pid i!!'"),
241            "{msg}"
242        );
243        assert!(msg.contains("never materialized"), "{msg}");
244        assert!(!msg.contains("filesystem snapshot (root"), "{msg}");
245    }
246
247    #[test]
248    fn lazy_local_echo_assert_success_leaves_snapshot_pending() {
249        let temp = GuardedPath::tempdir().unwrap();
250        let root = guard_root(&temp);
251
252        let script = indoc!(
253            r#"
254            WORKSPACE LOCAL
255            ECHO playground pid is 41067
256            ASSERT_CONTAINS stdout "playground pid is 41067"
257            "#
258        );
259        let steps = parse_script(script).unwrap();
260
261        let output = run_steps_with_lazy_snapshot(&root, &steps, ExecIo::new()).unwrap();
262        assert!(!output.snapshot.is_materialized());
263        assert!(output.snapshot.get().is_none());
264    }
265
266    #[test]
267    fn lazy_default_mode_echo_assert_failure_keeps_snapshot_pending() {
268        let temp = GuardedPath::tempdir().unwrap();
269        let root = guard_root(&temp);
270
271        // Same conditions as the LOCAL failure test, minus the WORKSPACE
272        // statement: the implicit default is snapshot mode, but the
273        // non-mutating steps must still leave it pending (issue #131).
274        let script = indoc!(
275            r#"
276            ECHO playground pid is 41067
277            ASSERT_CONTAINS stdout "playground pid i!!"
278            "#
279        );
280        let steps = parse_script(script).unwrap();
281
282        // Retain the snapshot handle across the failing run: the lazy
283        // convenience wrapper discards it on error, so drive the manager
284        // directly to pin the unmaterialized invariant (issue #131).
285        let mut resolver = PathResolver::new_lazy(root.clone()).unwrap();
286        resolver.set_workspace_root(root.clone());
287        let snapshot = resolver.snapshot_handle();
288        let fs: Box<dyn oxdock_fs::WorkspaceFs> = Box::new(resolver);
289        let result = run_steps_with_manager(
290            fs,
291            &steps,
292            oxdock_process::default_process_manager(),
293            ExecIo::new(),
294        );
295        assert!(result.is_err(), "mismatched ASSERT_CONTAINS must fail");
296        let err = result.err().unwrap();
297        assert!(!snapshot.is_materialized());
298        assert!(snapshot.get().is_none());
299
300        let enriched = enrich_lazy_error(&snapshot, &root, err);
301        let msg = enriched.to_string();
302        assert!(
303            msg.contains("did not contain 'playground pid i!!'"),
304            "{msg}"
305        );
306        assert!(msg.contains("never materialized"), "{msg}");
307        assert!(!msg.contains("filesystem snapshot (root"), "{msg}");
308    }
309
310    #[test]
311    fn lazy_default_mode_write_materializes_snapshot() {
312        let temp = GuardedPath::tempdir().unwrap();
313        let root = guard_root(&temp);
314
315        // No WORKSPACE statement: a snapshot-targeted WRITE must transition
316        // the lazy handle to materialized (issue #131).
317        let steps = parse_script("WRITE \"snap.txt\" \"snap\"").unwrap();
318
319        let output = run_steps_with_lazy_snapshot(&root, &steps, ExecIo::new()).unwrap();
320        assert!(output.snapshot.is_materialized());
321        let snapshot_root = output.snapshot.get().expect("snapshot must be published");
322        assert!(
323            exists(snapshot_root, "snap.txt"),
324            "WRITE must land inside the materialized snapshot"
325        );
326    }
327
328    #[test]
329    fn guard_skips_when_env_missing() {
330        let temp = GuardedPath::tempdir().unwrap();
331        let root = guard_root(&temp);
332
333        let guard_var = oxdock_env::oxdock::GUARD_TEST_TOKEN_UNSET;
334        let script = format!(
335            indoc!(
336                r#"
337                [env:{guard}] WRITE "skipped.txt" "hi"
338                WRITE "kept.txt" "ok"
339                "#
340            ),
341            guard = guard_var
342        );
343        let steps = crate::parse_script(&script).unwrap();
344
345        run_steps(&root, &steps).unwrap();
346
347        assert!(
348            !exists(&root, "skipped.txt"),
349            "guarded WRITE should be skipped"
350        );
351        assert!(exists(&root, "kept.txt"), "unguarded WRITE should run");
352    }
353
354    #[test]
355    fn guard_sees_env_set_by_env_step() {
356        let temp = GuardedPath::tempdir().unwrap();
357        let root = guard_root(&temp);
358
359        let script = indoc!(
360            r#"
361            ENV FOO="1"
362            [env:FOO] WRITE "hit.txt" "yes"
363            WRITE "always.txt" "ok"
364            "#
365        );
366        let steps = crate::parse_script(script).unwrap();
367
368        run_steps(&root, &steps).unwrap();
369
370        assert!(
371            exists(&root, "hit.txt"),
372            "guarded WRITE should run after ENV sets variable"
373        );
374        assert!(exists(&root, "always.txt"), "unguarded WRITE should run");
375    }
376
377    #[test]
378    fn echo_runs_and_allows_subsequent_steps() {
379        let temp = GuardedPath::tempdir().unwrap();
380        let root = guard_root(&temp);
381
382        let script = indoc!(
383            r#"
384            ECHO "Hello, world"
385            WRITE "always.txt" "ok"
386            "#
387        );
388        let steps = crate::parse_script(script).unwrap();
389
390        run_steps(&root, &steps).unwrap();
391
392        assert!(exists(&root, "always.txt"), "WRITE after ECHO should run");
393    }
394
395    #[test]
396    fn guard_on_previous_line_applies_to_next_command() {
397        let temp = GuardedPath::tempdir().unwrap();
398        let root = guard_root(&temp);
399
400        let script = indoc!(
401            r#"
402            ENV FOO="1"
403            [env:FOO]
404            WRITE "hit.txt" "yes"
405            WRITE "always.txt" "ok"
406            "#
407        );
408        let steps = crate::parse_script(script).unwrap();
409
410        run_steps(&root, &steps).unwrap();
411
412        assert!(
413            exists(&root, "hit.txt"),
414            "guarded WRITE on next line should run"
415        );
416        assert!(exists(&root, "always.txt"), "unguarded WRITE should run");
417    }
418
419    #[test]
420    fn guard_respects_platform_negation() {
421        let temp = GuardedPath::tempdir().unwrap();
422        let root = guard_root(&temp);
423
424        let script = indoc!(
425            r#"
426            [not(family:unix)] WRITE "platform.txt" "hi"
427            WRITE "always.txt" "ok"
428            "#
429        );
430        let steps = crate::parse_script(script).unwrap();
431
432        run_steps(&root, &steps).unwrap();
433
434        #[allow(clippy::disallowed_macros)]
435        let expect_skipped = cfg!(unix);
436        assert_eq!(
437            exists(&root, "platform.txt"),
438            !expect_skipped,
439            "platform guard should skip on Unix and run elsewhere"
440        );
441        assert!(exists(&root, "always.txt"), "unguarded WRITE should run");
442    }
443
444    #[test]
445    fn guard_block_env_scope_restores_after_exit() {
446        let temp = GuardedPath::tempdir().unwrap();
447        let root = guard_root(&temp);
448
449        let script = indoc!(
450            r#"
451            ENV RUN="1"
452            [env:RUN] {
453                ENV INNER="1"
454                WRITE "scoped.txt" "hit"
455            }
456            [env:INNER] WRITE "leak.txt" "nope"
457            "#
458        );
459        let steps = crate::parse_script(script).unwrap();
460
461        run_steps(&root, &steps).unwrap();
462
463        assert!(exists(&root, "scoped.txt"), "block should run");
464        assert!(
465            !exists(&root, "leak.txt"),
466            "env set inside block must not leak outward"
467        );
468    }
469
470    #[test]
471    fn guard_block_workdir_scope_restores_after_exit() {
472        let temp = GuardedPath::tempdir().unwrap();
473        let root = guard_root(&temp);
474
475        let script = indoc!(
476            r#"
477            MKDIR "nested"
478            ENV RUN="1"
479            [env:RUN] {
480                WORKDIR "nested"
481                WRITE "inside.txt" "ok"
482            }
483            WRITE "outside.txt" "root"
484            "#
485        );
486        let steps = crate::parse_script(script).unwrap();
487
488        run_steps(&root, &steps).unwrap();
489
490        assert!(
491            exists(&root, "nested/inside.txt"),
492            "inside write should land in nested dir"
493        );
494        assert!(
495            exists(&root, "outside.txt"),
496            "workdir should reset after block exits"
497        );
498        assert!(
499            !exists(&root, "nested/outside.txt"),
500            "writes after block should not stay scoped"
501        );
502    }
503
504    #[test]
505    fn workspace_scope_restores_after_guard_block() {
506        let snapshot = GuardedPath::tempdir().unwrap();
507        let local = GuardedPath::tempdir().unwrap();
508        let snapshot_root = guard_root(&snapshot);
509        let local_root = guard_root(&local);
510
511        let script = indoc!(
512            r#"
513            ENV RUN="1"
514            [env:RUN] {
515                WORKSPACE LOCAL
516                WRITE "local_only.txt" "inside"
517            }
518            WRITE "snapshot_only.txt" "outside"
519            "#
520        );
521        let steps = crate::parse_script(script).unwrap();
522
523        run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
524
525        assert!(
526            local_root.join("local_only.txt").unwrap().exists(),
527            "workspace switch inside block should affect local root"
528        );
529        assert!(
530            snapshot_root.join("snapshot_only.txt").unwrap().exists(),
531            "writes after block must target snapshot again"
532        );
533        assert!(
534            !local_root.join("snapshot_only.txt").unwrap().exists(),
535            "workspace should reset after guard block exits"
536        );
537    }
538
539    #[test]
540    fn guard_matches_profile_env() {
541        // Set PROFILE via script ENV; guards now only see script-level env.
542        let temp = GuardedPath::tempdir().unwrap();
543        let root = guard_root(&temp);
544
545        let profile = std::env::var(oxdock_env::cargo::build::PROFILE)
546            .unwrap_or_else(|_| "debug".to_string());
547        let script = format!(
548            indoc!(
549                r#"
550                ENV PROFILE={0}
551                [eq(env:PROFILE, {0})] WRITE "hit.txt" "yes"
552                [ne(env:PROFILE, {0})] WRITE "miss.txt" "no"
553                "#
554            ),
555            profile
556        );
557
558        let steps = crate::parse_script(&script).unwrap();
559        run_steps(&root, &steps).unwrap();
560
561        assert!(
562            exists(&root, "hit.txt"),
563            "PROFILE-matching guard should run"
564        );
565        assert!(
566            !exists(&root, "miss.txt"),
567            "PROFILE inequality guard should skip for current profile"
568        );
569    }
570
571    #[test]
572    fn multiple_guards_all_must_pass() {
573        let temp = GuardedPath::tempdir().unwrap();
574        let root = guard_root(&temp);
575
576        let key = oxdock_env::oxdock::MULTI_GUARD_TEST_PASS;
577
578        let script = format!(
579            indoc!(
580                r#"
581                ENV {k}=ok
582                [env:{k},eq(env:{k}, ok)] WRITE "hit.txt" "yes"
583                WRITE "always.txt" "ok"
584                "#
585            ),
586            k = key
587        );
588        let steps = crate::parse_script(&script).unwrap();
589        run_steps(&root, &steps).unwrap();
590
591        assert!(
592            exists(&root, "hit.txt"),
593            "guarded step should run when all guards pass"
594        );
595        assert!(exists(&root, "always.txt"), "unguarded step should run");
596    }
597
598    #[test]
599    fn multiple_guards_skip_when_one_fails() {
600        let temp = GuardedPath::tempdir().unwrap();
601        let root = guard_root(&temp);
602
603        let key = oxdock_env::oxdock::MULTI_GUARD_TEST_FAIL;
604
605        let script = format!(
606            indoc!(
607                r#"
608                ENV {k}=ok
609                [env:{k},ne(env:{k}, ok)] WRITE "miss.txt" "yes"
610                WRITE "always.txt" "ok"
611                "#
612            ),
613            k = key
614        );
615        let steps = crate::parse_script(&script).unwrap();
616        run_steps(&root, &steps).unwrap();
617
618        assert!(
619            !exists(&root, "miss.txt"),
620            "guarded step should skip when any guard fails"
621        );
622        assert!(exists(&root, "always.txt"), "unguarded step should run");
623    }
624
625    #[cfg_attr(
626        miri,
627        ignore = "stdout streaming not supported for background command under Miri"
628    )]
629    #[test]
630    fn async_exits_success_and_stops_pipeline() {
631        let temp = GuardedPath::tempdir().unwrap();
632        let root = guard_root(&temp);
633
634        // Background succeeds quickly; pipeline should complete without error.
635        let script = indoc! {
636            r#"
637            [family:unix] ASYNC RUN "sleep 0.05"
638            [family:windows] ASYNC RUN "ping -n 1 127.0.0.1"
639            "#
640        };
641        let steps = crate::parse_script(script).unwrap();
642        let res = run_steps(&root, &steps);
643        assert!(res.is_ok(), "ASYNC success should allow clean exit");
644    }
645
646    #[cfg_attr(
647        miri,
648        ignore = "stdout streaming not supported for background command under Miri"
649    )]
650    #[test]
651    fn async_failure_bubbles_status() {
652        let temp = GuardedPath::tempdir().unwrap();
653        let root = guard_root(&temp);
654
655        let script = indoc! {
656            r#"
657            [family:unix] ASYNC RUN "sleep 0.05; exit 7"
658            [family:windows] ASYNC RUN "exit 7"
659            "#
660        };
661        let steps = crate::parse_script(script).unwrap();
662        let err = run_steps(&root, &steps).unwrap_err();
663        let msg = err.to_string();
664        assert!(
665            msg.contains("ASYNC process exited with status")
666                || msg.contains("exit status: 7")
667                || msg.contains("exit code: 7"),
668            "should surface failing ASYNC exit code"
669        );
670    }
671
672    #[cfg_attr(
673        miri,
674        ignore = "timing-sensitive background process test is unreliable under Miri"
675    )]
676    #[test]
677    fn async_multiple_stops_on_first_exit_and_does_not_block_steps() {
678        let temp = GuardedPath::tempdir().unwrap();
679        let root = guard_root(&temp);
680
681        let script = indoc! {
682            r#"
683            [family:unix] ASYNC RUN "sleep 0.2; echo one > one.txt"
684            [family:windows] ASYNC RUN "ping -n 2 127.0.0.1 > NUL & echo one > one.txt"
685            [family:unix] ASYNC RUN "sleep 0.5; echo two > two.txt"
686            [family:windows] ASYNC RUN "ping -n 3 127.0.0.1 > NUL & echo two > two.txt"
687            WRITE "done.txt" "ok"
688            "#
689        };
690
691        let steps = crate::parse_script(script).unwrap();
692        let start = Instant::now();
693        let res = run_steps(&root, &steps);
694        let elapsed = start.elapsed();
695
696        assert!(res.is_ok(), "ASYNC success should allow clean exit");
697        assert!(
698            exists(&root, "done.txt"),
699            "foreground step should run after spawning backgrounds"
700        );
701        assert!(
702            exists(&root, "one.txt"),
703            "first background should finish and emit output"
704        );
705        // With the new poll-all model, both children run to completion.
706        // The second background should also finish.
707        assert!(
708            exists(&root, "two.txt"),
709            "second background should finish (poll-all waits for all)"
710        );
711
712        // Shell sleep granularity differs per platform (`sleep` seconds
713        // against `ping` whole seconds), so only the bounds branch.
714        #[allow(clippy::disallowed_macros)]
715        let (lower, upper) = if cfg!(windows) {
716            (0.9, 3.0)
717        } else {
718            (0.15, 0.8)
719        };
720        assert!(
721            elapsed.as_secs_f32() < upper && elapsed.as_secs_f32() > lower,
722            "should wait for both backgrounds; got {elapsed:?}"
723        );
724    }
725
726    #[cfg_attr(
727        miri,
728        ignore = "timing-sensitive background process test is unreliable under Miri"
729    )]
730    #[test]
731    fn background_killed_when_unrelated_step_fails() {
732        let temp = GuardedPath::tempdir().unwrap();
733        let root = guard_root(&temp);
734
735        let script = indoc! {
736            r#"
737            [family:unix] ASYNC RUN "sleep 30; echo late > late.txt"
738            [family:windows] ASYNC RUN "ping -n 31 127.0.0.1 > NUL & echo late > late.txt"
739            RUN "__oxdock_missing_command_xyz__"
740            "#
741        };
742
743        let steps = crate::parse_script(script).unwrap();
744        let start = Instant::now();
745        assert!(
746            run_steps(&root, &steps).is_err(),
747            "pipeline should fail on the missing command"
748        );
749        // The ASYNC handle is dropped mid-pipeline when the error propagates;
750        // its Drop safety net must kill the writer before it can emit the
751        // late artifact. The sleep is generous on purpose: it bounds the
752        // kill timeliness on loaded runners without slowing the test,
753        // which still fails fast on the missing command. No rendezvous
754        // step: the RUN pre-spawn cancellation check closes the worker
755        // startup race, so a polling TIMEOUT only adds shared cancel
756        // state that outlives its step. No INHERIT_ENV either: the
757        // session seed already carries the host `PATH` (and `SystemRoot`
758        // on Windows), so plain `RUN` resolves without boilerplate. One
759        // shell level only: the engine already wraps the script, so each
760        // line spells its sleep-then-write chain directly and the tree
761        // under test is identical on both platforms.
762        assert!(
763            !exists(&root, "late.txt"),
764            "abandoned background writer must be killed by Drop teardown"
765        );
766        // A direct-child-only kill passes the assertion above but stalls
767        // pump EOF on the orphaned sleeper for the full 30s: bound the
768        // whole run so that regression fails loud instead of slow.
769        assert!(
770            start.elapsed() < std::time::Duration::from_secs(25),
771            "teardown must end the tree promptly, took {:?}",
772            start.elapsed()
773        );
774    }
775
776    #[cfg_attr(
777        miri,
778        ignore = "stdout streaming not supported for background command under Miri"
779    )]
780    #[test]
781    fn exit_terminates_backgrounds_and_returns_code() {
782        let temp = GuardedPath::tempdir().unwrap();
783        let root = guard_root(&temp);
784
785        let script = indoc! {
786            r#"
787            [family:unix] ASYNC RUN "sleep 30; echo late > late.txt"
788            [family:windows] ASYNC RUN "ping -n 31 127.0.0.1 > NUL & echo late > late.txt"
789            EXIT 5
790            "#
791        };
792
793        let steps = crate::parse_script(script).unwrap();
794        let err = run_steps(&root, &steps).unwrap_err();
795        let msg = err.to_string();
796        assert!(msg.contains("EXIT requested with code 5"));
797        assert!(
798            !exists(&root, "late.txt"),
799            "background process should be killed when EXIT is hit"
800        );
801    }
802
803    #[test]
804    #[cfg_attr(
805        miri,
806        ignore = "EXIT joins real background threads; timing-sensitive under Miri"
807    )]
808    fn exit_inside_nested_block_reports_code_and_kills_backgrounds() {
809        let temp = GuardedPath::tempdir().unwrap();
810        let root = guard_root(&temp);
811
812        let script = indoc! {
813            r#"
814            ASYNC {
815                SLEEP 30s
816            }
817            [bool:true] {
818                EXIT 5
819            }
820            "#
821        };
822
823        let steps = crate::parse_script(script).unwrap();
824        let start = std::time::Instant::now();
825        let err = run_steps(&root, &steps).unwrap_err();
826        assert!(
827            err.to_string().contains("EXIT requested with code 5"),
828            "nested EXIT must report its code: {err}"
829        );
830        assert!(
831            start.elapsed() < std::time::Duration::from_secs(10),
832            "nested EXIT must kill the background SLEEP promptly"
833        );
834    }
835
836    #[cfg_attr(
837        miri,
838        ignore = "stdout streaming not supported for background command under Miri"
839    )]
840    #[test]
841    fn env_applies_to_run_and_background() {
842        let temp = GuardedPath::tempdir().unwrap();
843        let root = guard_root(&temp);
844
845        let script = indoc! {
846            r#"
847            ENV FOO="bar"
848            [family:windows] RUN "echo %FOO% > run.txt"
849            [family:unix] RUN "printf %s \"$FOO\" > run.txt"
850            [family:windows] ASYNC RUN "echo %FOO% > bg.txt"
851            [family:unix] ASYNC RUN "printf %s \"$FOO\" > bg.txt"
852            "#
853        };
854
855        let steps = crate::parse_script(script).unwrap();
856        run_steps(&root, &steps).unwrap();
857
858        assert_eq!(read_trimmed(&root.join("run.txt").unwrap()), "bar");
859        assert_eq!(read_trimmed(&root.join("bg.txt").unwrap()), "bar");
860    }
861
862    #[test]
863    fn workspace_switches_between_snapshot_and_local() {
864        let snapshot = GuardedPath::tempdir().unwrap();
865        let local = GuardedPath::tempdir().unwrap();
866        let snapshot_root = guard_root(&snapshot);
867        let local_root = guard_root(&local);
868
869        let script = indoc! {
870            r#"
871            WRITE "snap.txt" "snap"
872            WORKSPACE LOCAL
873            WRITE "local.txt" "local"
874            WORKSPACE SNAPSHOT
875            WRITE "snap2.txt" "again"
876            "#
877        };
878
879        let steps = crate::parse_script(script).unwrap();
880        run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
881
882        assert!(snapshot_root.join("snap.txt").unwrap().exists());
883        assert!(snapshot_root.join("snap2.txt").unwrap().exists());
884        assert!(local_root.join("local.txt").unwrap().exists());
885    }
886
887    #[test]
888    fn workspace_root_changes_where_slash_points() {
889        let snapshot = GuardedPath::tempdir().unwrap();
890        let local = GuardedPath::tempdir().unwrap();
891        let snapshot_root = guard_root(&snapshot);
892        let local_root = guard_root(&local);
893        let local_client = local_root.join("client").unwrap();
894        create_dirs(&local_client);
895
896        let script = indoc! {
897            r#"
898            WORKSPACE LOCAL
899            WORKDIR "/"
900            WRITE "localroot.txt" "one"
901            WORKDIR "client"
902            WRITE "client.txt" "two"
903            WORKSPACE SNAPSHOT
904            WORKDIR "/"
905            WRITE "snaproot.txt" "three"
906            "#
907        };
908
909        let steps = crate::parse_script(script).unwrap();
910        run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
911
912        assert!(local_root.join("localroot.txt").unwrap().exists());
913        assert!(local_client.join("client.txt").unwrap().exists());
914        assert!(snapshot_root.join("snaproot.txt").unwrap().exists());
915    }
916
917    /// Serialized cache-dir pin for hermetic tests. `OXDOCK_CACHE_DIR` is
918    /// process-global; the lock plus drop-restore keeps parallel tests
919    /// isolated (mirrors `SerialCargoEnv` in `oxdock-process`).
920    struct SerialCacheDir {
921        _lock: std::sync::MutexGuard<'static, ()>,
922        prev: Option<String>,
923    }
924
925    static CACHE_DIR_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
926
927    impl SerialCacheDir {
928        fn pin(dir: &GuardedPath) -> Self {
929            let lock = CACHE_DIR_LOCK
930                .lock()
931                .unwrap_or_else(|poisoned| poisoned.into_inner());
932            let prev = std::env::var(oxdock_env::oxdock::CACHE_DIR).ok();
933            // SAFETY: serialized by `CACHE_DIR_LOCK`, restored on drop.
934            unsafe {
935                std::env::set_var(
936                    oxdock_env::oxdock::CACHE_DIR,
937                    dir.as_path().to_string_lossy().into_owned(),
938                );
939            }
940            Self { _lock: lock, prev }
941        }
942    }
943
944    impl Drop for SerialCacheDir {
945        fn drop(&mut self) {
946            unsafe {
947                match &self.prev {
948                    Some(v) => std::env::set_var(oxdock_env::oxdock::CACHE_DIR, v),
949                    None => std::env::remove_var(oxdock_env::oxdock::CACHE_DIR),
950                }
951            }
952        }
953    }
954
955    #[test]
956    fn workspace_cache_persists_across_runs() {
957        let pin = GuardedPath::tempdir().unwrap();
958        let pin_root = guard_root(&pin);
959        let _env = SerialCacheDir::pin(&pin_root);
960
961        let snapshot = GuardedPath::tempdir().unwrap();
962        let local = GuardedPath::tempdir().unwrap();
963        let snapshot_root = guard_root(&snapshot);
964        let local_root = guard_root(&local);
965
966        // First run writes through CACHE, then hops roots to prove the
967        // entry does not land in snapshot or local.
968        let first = indoc! {
969            r#"
970            WRITE "snap.txt" "snap"
971            WORKSPACE LOCAL
972            WRITE "local.txt" "local"
973            WORKSPACE CACHE
974            WRITE "cached.txt" "persistent"
975            WORKSPACE SNAPSHOT
976            "#
977        };
978        let steps = crate::parse_script(first).unwrap();
979        run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
980
981        // Native only: the Miri synthetic backend keys all non-snapshot
982        // state by build root, so cross-root absence is vacuous there.
983        // Selection itself is covered by mock tests under Miri.
984        #[cfg(not(miri))]
985        assert!(!exists(&snapshot_root, "cached.txt"));
986        #[cfg(not(miri))]
987        assert!(!exists(&local_root, "cached.txt"));
988
989        // A fresh run with a fresh snapshot root still sees the entry:
990        // the cache survived while the snapshot did not. The Miri
991        // synthetic backend keys non-snapshot state by build root, so the
992        // second run reuses the local root there; natively it gets a
993        // fresh one.
994        let fresh_snapshot = GuardedPath::tempdir().unwrap();
995        let fresh_snapshot_root = guard_root(&fresh_snapshot);
996        #[cfg(not(miri))]
997        let fresh_local = GuardedPath::tempdir().unwrap();
998        #[cfg(not(miri))]
999        let fresh_local_root = guard_root(&fresh_local);
1000        #[cfg(miri)]
1001        let fresh_local_root = local_root.clone();
1002
1003        let second = indoc! {
1004            r#"
1005            WORKSPACE CACHE
1006            LET $v: STRING = READ cached.txt
1007            ASSERT_EQ $v "persistent"
1008            "#
1009        };
1010        let steps = crate::parse_script(second).unwrap();
1011        run_steps_with_context(&fresh_snapshot_root, &fresh_local_root, &steps).unwrap();
1012    }
1013
1014    #[test]
1015    fn workspace_cache_local_stays_in_project_tree() {
1016        // Pin the OS cache aside: `--local` must never touch it.
1017        let pin = GuardedPath::tempdir().unwrap();
1018        let pin_root = guard_root(&pin);
1019        let _env = SerialCacheDir::pin(&pin_root);
1020
1021        let snapshot = GuardedPath::tempdir().unwrap();
1022        let local = GuardedPath::tempdir().unwrap();
1023        let snapshot_root = guard_root(&snapshot);
1024        let local_root = guard_root(&local);
1025
1026        let first = indoc! {
1027            r#"
1028            WORKSPACE CACHE --local
1029            WRITE "local-cached.txt" "persistent"
1030            LET $v: STRING = READ local-cached.txt
1031            ASSERT_EQ $v "persistent"
1032            "#
1033        };
1034        let steps = crate::parse_script(first).unwrap();
1035        run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
1036
1037        // Native only (see above): the Miri synthetic backend shares one
1038        // namespace per build root, so location assertions are vacuous.
1039        #[cfg(not(miri))]
1040        assert!(exists(&local_root, ".cache/workspace/local-cached.txt"));
1041        #[cfg(not(miri))]
1042        assert!(!exists(&pin_root, "workspace/local-cached.txt"));
1043
1044        // A fresh snapshot against the same project tree reads it back:
1045        // the local cache outlives the ephemeral snapshot.
1046        let fresh_snapshot = GuardedPath::tempdir().unwrap();
1047        let fresh_snapshot_root = guard_root(&fresh_snapshot);
1048        let second = indoc! {
1049            r#"
1050            WORKSPACE CACHE --local
1051            LET $v: STRING = READ local-cached.txt
1052            ASSERT_EQ $v "persistent"
1053            "#
1054        };
1055        let steps = crate::parse_script(second).unwrap();
1056        run_steps_with_context(&fresh_snapshot_root, &local_root, &steps).unwrap();
1057
1058        // A fresh project tree does not: the local cache lives and dies
1059        // with the tree, unlike the OS-native flavor.
1060        let other_local = GuardedPath::tempdir().unwrap();
1061        let other_local_root = guard_root(&other_local);
1062        let steps = crate::parse_script(second).unwrap();
1063        assert!(
1064            run_steps_with_context(&fresh_snapshot_root, &other_local_root, &steps).is_err(),
1065            "local cache must not leak across project trees"
1066        );
1067    }
1068
1069    #[test]
1070    fn workspace_system_reaches_outside_roots() {
1071        let snapshot = GuardedPath::tempdir().unwrap();
1072        let local = GuardedPath::tempdir().unwrap();
1073        let snapshot_root = guard_root(&snapshot);
1074        let local_root = guard_root(&local);
1075        let outside = GuardedPath::tempdir().unwrap();
1076        let outside_root = guard_root(&outside);
1077
1078        // From a snapshot-selected start, SYSTEM writes an outside file by
1079        // absolute path, reads it back, and writes a sibling next to it.
1080        // Seeding from inside the script keeps every backend (including
1081        // the Miri synthetic one, which keys state by guard root) in one
1082        // namespace. Forward slashes throughout: a raw Windows path would
1083        // lose its backslashes to DSL string escapes (`C:\Users` parses
1084        // as `C:Users`).
1085        let script = format!(
1086            indoc! {r#"
1087                WORKSPACE SYSTEM
1088                WRITE "{secret}" outside
1089                LET $v: STRING = READ "{secret}"
1090                ASSERT_EQ $v outside
1091                WRITE "{sibling}" done
1092                WORKSPACE SNAPSHOT
1093            "#},
1094            secret = to_forward_slashes(
1095                &outside_root
1096                    .join("secret.txt")
1097                    .unwrap()
1098                    .as_path()
1099                    .to_string_lossy()
1100            ),
1101            sibling = to_forward_slashes(
1102                &outside_root
1103                    .join("sibling.txt")
1104                    .unwrap()
1105                    .as_path()
1106                    .to_string_lossy()
1107            ),
1108        );
1109        let steps = crate::parse_script(&script).unwrap();
1110        run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
1111
1112        // Native only (see above): Miri shares one namespace per build root,
1113        // while the in-script ASSERT_EQ already verifies content everywhere.
1114        #[cfg(not(miri))]
1115        assert!(exists(&outside_root, "sibling.txt"));
1116        // Native only (see above): Miri shares one namespace per build root.
1117        #[cfg(not(miri))]
1118        assert!(!exists(&snapshot_root, "sibling.txt"));
1119        #[cfg(not(miri))]
1120        assert!(!exists(&local_root, "sibling.txt"));
1121    }
1122
1123    #[test]
1124    fn copy_from_workspace_targets() {
1125        let pin = GuardedPath::tempdir().unwrap();
1126        let pin_root = guard_root(&pin);
1127        let _env = SerialCacheDir::pin(&pin_root);
1128
1129        let snapshot = GuardedPath::tempdir().unwrap();
1130        let local = GuardedPath::tempdir().unwrap();
1131        let snapshot_root = guard_root(&snapshot);
1132        let local_root = guard_root(&local);
1133        let outside = GuardedPath::tempdir().unwrap();
1134        let outside_root = guard_root(&outside);
1135
1136        // SNAPSHOT, CACHE, LOCAL, and SYSTEM sources each resolve against
1137        // their own root and land in the snapshot cwd. The SYSTEM source
1138        // is seeded from inside the script so every backend observes one
1139        // namespace. Forward slashes throughout: raw Windows backslashes
1140        // would be consumed by DSL string escapes.
1141        let script = format!(
1142            indoc! {r#"
1143                WRITE snap-src.txt from-snap
1144                WORKSPACE CACHE
1145                WRITE cache-src.txt from-cache
1146                WORKSPACE SYSTEM
1147                WRITE "{secret}" outside
1148                WORKSPACE SNAPSHOT
1149                COPY --from-workspace SNAPSHOT snap-src.txt snap-copy.txt
1150                COPY --from-workspace CACHE cache-src.txt cache-copy.txt
1151                COPY --from-workspace SYSTEM "{secret}" sys-copy.txt
1152                COPY --from-workspace LOCAL "{local_src}" local-copy.txt
1153            "#},
1154            secret = to_forward_slashes(
1155                &outside_root
1156                    .join("secret.txt")
1157                    .unwrap()
1158                    .as_path()
1159                    .to_string_lossy()
1160            ),
1161            local_src = to_forward_slashes(
1162                &local_root
1163                    .join("local-src.txt")
1164                    .unwrap()
1165                    .as_path()
1166                    .to_string_lossy()
1167            ),
1168        );
1169        // Seed the LOCAL source through the build context side.
1170        let local_seeder = PathResolver::new(local_root.as_path(), local_root.as_path()).unwrap();
1171        local_seeder
1172            .write_file(&local_root.join("local-src.txt").unwrap(), b"from-local")
1173            .unwrap();
1174
1175        let steps = crate::parse_script(&script).unwrap();
1176        run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
1177
1178        assert!(exists(&snapshot_root, "snap-copy.txt"));
1179        assert!(exists(&snapshot_root, "cache-copy.txt"));
1180        assert!(exists(&snapshot_root, "sys-copy.txt"));
1181        assert!(exists(&snapshot_root, "local-copy.txt"));
1182
1183        // A pending snapshot has no source to copy from.
1184        let pending = indoc! {r#"
1185            COPY --from-workspace SNAPSHOT missing.txt out.txt
1186        "#};
1187        let steps = crate::parse_script(pending).unwrap();
1188        let fresh_snapshot = GuardedPath::tempdir().unwrap();
1189        let fresh_local = GuardedPath::tempdir().unwrap();
1190        assert!(
1191            run_steps_with_context(
1192                &guard_root(&fresh_snapshot),
1193                &guard_root(&fresh_local),
1194                &steps
1195            )
1196            .is_err(),
1197            "COPY from a pending snapshot must fail"
1198        );
1199    }
1200
1201    #[test]
1202    fn copy_destinations_mirror_docker() {
1203        // Docker destination semantics: a file copied onto a directory
1204        // (`.`, an existing dir, or a trailing-slash spell) lands inside
1205        // it under its basename; a directory source copies its contents.
1206        // Covers the `COPY file .` escape-check failure under cache roots.
1207        let pin = GuardedPath::tempdir().unwrap();
1208        let pin_root = guard_root(&pin);
1209        let _env = SerialCacheDir::pin(&pin_root);
1210
1211        let snapshot = GuardedPath::tempdir().unwrap();
1212        let local = GuardedPath::tempdir().unwrap();
1213        let snapshot_root = guard_root(&snapshot);
1214        let local_root = guard_root(&local);
1215
1216        let seeder = PathResolver::new(local_root.as_path(), local_root.as_path()).unwrap();
1217        seeder
1218            .write_file(&local_root.join("cargo.toml").unwrap(), b"manifest")
1219            .unwrap();
1220        seeder
1221            .create_dir_all(&local_root.join("sub").unwrap())
1222            .unwrap();
1223        seeder
1224            .write_file(&local_root.join("sub/a.txt").unwrap(), b"a")
1225            .unwrap();
1226
1227        let script = indoc! {r#"
1228            WORKSPACE CACHE --local
1229            COPY --from-workspace LOCAL cargo.toml .
1230            LET $a: STRING = READ cargo.toml
1231            ASSERT_EQ $a manifest
1232            COPY --from-workspace LOCAL cargo.toml renamed.txt
1233            LET $b: STRING = READ renamed.txt
1234            ASSERT_EQ $b manifest
1235            MKDIR subdir
1236            COPY --from-workspace LOCAL cargo.toml subdir
1237            COPY --from-workspace LOCAL cargo.toml subdir/
1238            LET $c: STRING = READ subdir/cargo.toml
1239            ASSERT_EQ $c manifest
1240            COPY --from-workspace LOCAL sub .
1241            LET $d: STRING = READ a.txt
1242            ASSERT_EQ $d a
1243            WORKSPACE SNAPSHOT
1244            COPY --from-workspace LOCAL cargo.toml .
1245            LET $e: STRING = READ cargo.toml
1246            ASSERT_EQ $e manifest
1247        "#};
1248        let steps = crate::parse_script(script).unwrap();
1249        run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
1250
1251        // Native only: the Miri synthetic backend keys all non-snapshot
1252        // state by build root, so location assertions via `exists()` are
1253        // vacuous there. Content is verified in-script above on every
1254        // platform; selection itself is covered by mock tests under Miri.
1255        #[cfg(not(miri))]
1256        assert!(exists(&local_root, ".cache/workspace/cargo.toml"));
1257        #[cfg(not(miri))]
1258        assert!(exists(&local_root, ".cache/workspace/renamed.txt"));
1259        #[cfg(not(miri))]
1260        assert!(exists(&local_root, ".cache/workspace/subdir/cargo.toml"));
1261        #[cfg(not(miri))]
1262        assert!(exists(&local_root, ".cache/workspace/a.txt"));
1263        #[cfg(not(miri))]
1264        assert!(exists(&snapshot_root, "cargo.toml"));
1265    }
1266
1267    /// The isolation discriminator: real children on both sides of the
1268    /// boundary. A plain `RUN` sees the outer var; the identical `RUN`
1269    /// inside `ISOLATED` does not. Mock-recorded envs cannot prove this
1270    /// (they assert staged maps, never spawned children); only executed
1271    /// processes distinguish a scrub from generic block scoping. One
1272    /// script with platform guards, no `$` spellings anywhere, so
1273    /// DSL-level dollar expansion cannot confound what the child itself
1274    /// observes.
1275    #[test]
1276    #[cfg_attr(
1277        miri,
1278        ignore = "spawns real child processes; Miri does not support process execution"
1279    )]
1280    fn isolated_hides_outer_env_from_real_children() {
1281        let temp = GuardedPath::tempdir().unwrap();
1282        let root = guard_root(&temp);
1283
1284        // One unguarded allowlist per scope: absent names skip silently.
1285        // The seed already provides PATH at every reseed, so the lists
1286        // only route OUTER: its omission inside is the assertion.
1287        // Writes stay inside the scopes that bind their variables:
1288        // block-local `$boxed` does not leak outward by design.
1289        let script = indoc!(
1290            r#"
1291            ENV OUTER=outer-val
1292            [family:unix] LET $plain: STRING = RUN ["sh", "-c", "printenv OUTER || echo absent"]
1293            [family:windows] LET $plain: STRING = RUN ["cmd", "/c", "if defined OUTER (echo outer-val) else (echo absent)"]
1294            WRITE plain.txt "{{ $plain }}"
1295            ISOLATED {
1296                [family:unix] LET $boxed: STRING = RUN ["sh", "-c", "printenv OUTER || echo absent"]
1297                [family:windows] LET $boxed: STRING = RUN ["cmd", "/c", "if defined OUTER (echo outer-val) else (echo absent)"]
1298                WRITE boxed.txt "{{ $boxed }}"
1299            }
1300            "#
1301        );
1302        let steps = crate::parse_script(script).unwrap();
1303        run_steps(&root, &steps).unwrap();
1304
1305        assert_eq!(
1306            read_trimmed(&root.join("plain.txt").unwrap()),
1307            "outer-val",
1308            "plain RUN must see the outer var"
1309        );
1310        assert_eq!(
1311            read_trimmed(&root.join("boxed.txt").unwrap()),
1312            "absent",
1313            "ISOLATED RUN must not see the outer var"
1314        );
1315    }
1316
1317    /// Exact-set child env audit: one `FUNC` dumps the child environment it
1318    /// observes, called from three isolation depths. Each dump must contain exactly the expected names with the expected values
1319    /// and nothing else; a host-only sentinel set in the test process
1320    /// must be absent at every depth. This is the end-to-end closedness
1321    /// proof: recorded maps cannot show what a real child observes.
1322    #[test]
1323    #[cfg_attr(
1324        miri,
1325        ignore = "spawns real child processes; Miri does not support process execution"
1326    )]
1327    fn child_env_matches_allowlist_at_every_depth() {
1328        fn env_map(text: &str) -> std::collections::BTreeMap<String, String> {
1329            text.lines()
1330                .filter_map(|line| {
1331                    line.split_once('=')
1332                        .map(|(k, v)| (k.to_string(), v.to_string()))
1333                })
1334                .collect()
1335        }
1336
1337        // Host-only sentinel: never routed anywhere, must appear in no dump.
1338        // RAII-guarded so a mid-test failure still restores process env.
1339        let _probe_guard = oxdock_process::TestEnvGuard::set("OXDOCK_ENV_AUDIT_PROBE", "host-only");
1340        let temp = GuardedPath::tempdir().unwrap();
1341        let root = guard_root(&temp);
1342
1343        // The mid level re-adds OUTER; the deep level drops it again, so
1344        // the three dumps prove pass-through, re-adding, and narrowing.
1345        // PATH needs no allowlist: the seed provides it at every level.
1346        let script = indoc!(
1347            r#"
1348            ENV OUTER=outer-val
1349            FUNC DUMPENV() {
1350                [family:unix] LET $o: STRING = RUN ["sh", "-c", "env"]
1351                [family:windows] LET $o: STRING = RUN ["cmd", "/c", "set"]
1352                RETURN $o
1353            }
1354            LET $top: STRING = DUMPENV()
1355            WRITE top.txt "{{ $top }}"
1356            ISOLATED {
1357                INHERIT_ENV [OUTER]
1358                LET $mid: STRING = DUMPENV()
1359                WRITE mid.txt "{{ $mid }}"
1360                ISOLATED {
1361                    LET $deep: STRING = DUMPENV()
1362                    WRITE deep.txt "{{ $deep }}"
1363                }
1364            }
1365            "#
1366        );
1367        let steps = crate::parse_script(script).unwrap();
1368        run_steps(&root, &steps).unwrap();
1369
1370        let read_env = |name: &str| {
1371            let body = read_trimmed(&root.join(name).unwrap());
1372            env_map(&body)
1373        };
1374        let top = read_env("top.txt");
1375        let mid = read_env("mid.txt");
1376        let deep = read_env("deep.txt");
1377
1378        // Expected names per depth, derived from the seed declaration
1379        // (not hardcoded). `OUTER` rides top and mid after
1380        // the allowlist re-adds it; deep narrows it out. The seed rides
1381        // every spawn (top, mid after reseed, deep after reseed). The
1382        // shell itself adds a few names (`PWD` everywhere, plus `SHLVL`
1383        // and `_` under bash but not dash) that no allowlist routes:
1384        // shells disagree, so the assertion below is two-sided instead
1385        // of exact equality.
1386        #[allow(clippy::disallowed_macros)]
1387        let shell_added: &[&str] = if cfg!(windows) {
1388            // `cmd.exe` injects `PROMPT=$P$G` when unset, like unix
1389            // shells add `PWD`.
1390            &["PROMPT"]
1391        } else {
1392            &["PWD", "SHLVL", "_"]
1393        };
1394        // Seed-derived key set: mirror rows count only when the host
1395        // defines them; the engine-owned row always seeds. The child
1396        // reads the same process env, so host presence is the exact
1397        // oracle. Adding a seed row needs no edit here.
1398        let mut seed_names: Vec<&str> = Vec::new();
1399        for entry in oxdock_process::env_policy::current_platform_seed() {
1400            if entry.name == oxdock_env::cargo::TARGET_DIR || std::env::var(entry.name).is_ok() {
1401                seed_names.push(entry.name);
1402            }
1403        }
1404        let mut expect_top: Vec<&str> = vec!["OUTER"];
1405        expect_top.extend(seed_names.iter().copied());
1406        let expect_mid = expect_top.clone();
1407        let expect_deep: Vec<&str> = seed_names;
1408        for (label, got, mut want) in [
1409            ("top", &top, expect_top),
1410            ("mid", &mid, expect_mid),
1411            ("deep", &deep, expect_deep),
1412        ] {
1413            want.extend(shell_added);
1414            // Two-sided: every routed name must appear, and every
1415            // appearing name must be routed or shell-known. A newcomer
1416            // outside both lists still fails with its name shown.
1417            for name in &want {
1418                if shell_added.contains(name) {
1419                    continue;
1420                }
1421                assert!(
1422                    got.contains_key(*name),
1423                    "{label} dump lacks routed name {name}: {got:?}"
1424                );
1425            }
1426            for key in got.keys() {
1427                assert!(
1428                    want.contains(&key.as_str()),
1429                    "{label} dump carries unexpected name {key}: {got:?}"
1430                );
1431            }
1432        }
1433        assert_eq!(top.get("OUTER").map(String::as_str), Some("outer-val"));
1434        assert_eq!(mid.get("OUTER").map(String::as_str), Some("outer-val"));
1435        assert!(
1436            !deep.contains_key("OUTER"),
1437            "narrowed level must drop OUTER: {deep:?}"
1438        );
1439        for (label, got) in [("top", &top), ("mid", &mid), ("deep", &deep)] {
1440            assert!(
1441                !got.contains_key("OXDOCK_ENV_AUDIT_PROBE"),
1442                "{label} dump leaked a host-only var: {got:?}"
1443            );
1444        }
1445    }
1446}