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