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