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