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