Skip to main content

oxdock_core/
lib.rs

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