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