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