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, StepKind, all_metadata, all_structural_metadata,
8    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::Symlink { .. } => exec::dispatch_symlink,
24    StepKind::Mkdir(..) => exec::dispatch_mkdir,
25    StepKind::Install { .. } => exec::dispatch_install,
26    StepKind::Ls(..) => exec::dispatch_ls,
27    StepKind::Cwd => exec::dispatch_cwd,
28    StepKind::Read(..) => exec::dispatch_read,
29    StepKind::ReadLine { .. } => exec::dispatch_read_line,
30    StepKind::Prompt { .. } => exec::dispatch_prompt,
31    StepKind::Write { .. } => exec::dispatch_write,
32    StepKind::Append { .. } => exec::dispatch_append,
33    StepKind::Remove { .. } => exec::dispatch_remove,
34    StepKind::Expand { .. } => exec::dispatch_expand,
35    StepKind::AssertEq { .. } => exec::dispatch_assert_eq,
36    StepKind::AssertContains { .. } => exec::dispatch_assert_contains,
37    StepKind::HashSha256 { .. } => exec::dispatch_hash_sha256,
38    StepKind::Exit(..) => exec::dispatch_exit,
39    StepKind::AssignAsync { .. } => exec::dispatch_assign_async_step,
40    StepKind::Set { .. } => exec::dispatch_set,
41    StepKind::Await { .. } => exec::dispatch_await_step,
42    StepKind::AssignCapture { .. } => exec::dispatch_assign_capture_step,
43    StepKind::AwaitCapture { .. } => exec::dispatch_await_capture_step,
44    StepKind::Cancel { .. } => exec::dispatch_cancel_step,
45    StepKind::Timeout { .. } => exec::dispatch_timeout_step,
46    StepKind::Sleep { .. } => exec::dispatch_sleep_step,
47    StepKind::ListAppend { .. } => exec::dispatch_push_into_step,
48    StepKind::FuncDef { .. } => exec::dispatch_func_def,
49    StepKind::Call { .. } => exec::dispatch_call,
50    StepKind::Return { .. } => exec::dispatch_return,
51    StepKind::While { .. } => exec::dispatch_while_loop,
52    StepKind::Break => exec::dispatch_break,
53    StepKind::Continue => exec::dispatch_continue,
54}
55
56/// Parse a script using the production `lower_command` dispatcher.
57/// The typed `ParseError` converts into `anyhow::Error` at this boundary
58/// with no intermediate `.context()` wrapping, so the message survives.
59/// Builtin function names seed the reserved set, so `FUNC` shadowing a
60/// native fails here; hosts unknown at parse time fall back to the runtime
61/// `define_func` guard.
62pub fn parse_script(input: &str) -> anyhow::Result<Vec<oxdock_parser::Step>> {
63    parse_script_with_modules(input, std_module_table())
64}
65
66/// Parse with a module provenance table so calls resolve statically:
67/// qualified `MODULE::NAME` checks membership, bare `NAME` resolves through
68/// `SCRIPT` definitions and `IMPORT`ed modules. Reserved covers builtins
69/// plus every table module, so `FUNC` shadowing any of them fails here;
70/// hosts unknown at parse time fall back to the runtime `define_func`
71/// guard.
72pub fn parse_script_with_modules(
73    input: &str,
74    modules: oxdock_parser::ModuleTable,
75) -> anyhow::Result<Vec<oxdock_parser::Step>> {
76    let mut reserved = builtin_function_names();
77    reserved.extend(modules.reserved_base_names());
78    Ok(oxdock_parser::parse_script_with_modules(
79        input,
80        lower_command,
81        reserved,
82        modules,
83    )?)
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89    use indoc::indoc;
90    use oxdock_fs::{
91        GuardedPath, GuardedTempDir, PathResolver, env as oxdock_env, to_forward_slashes,
92    };
93    use oxdock_parser::{Step, StepKind};
94    #[cfg(unix)]
95    use std::time::Instant;
96
97    fn guard_root(temp: &GuardedTempDir) -> GuardedPath {
98        temp.as_guarded_path().clone()
99    }
100
101    fn read_trimmed(path: &GuardedPath) -> String {
102        let resolver = PathResolver::new(path.root(), path.root()).unwrap();
103        resolver
104            .read_to_string(path)
105            .unwrap_or_default()
106            .trim()
107            .to_string()
108    }
109
110    fn create_dirs(path: &GuardedPath) {
111        let resolver = PathResolver::new(path.root(), path.root()).unwrap();
112        resolver.create_dir_all(path).unwrap();
113    }
114
115    fn exists(root: &GuardedPath, rel: &str) -> bool {
116        root.join(rel).map(|p| p.exists()).unwrap_or(false)
117    }
118
119    #[test]
120    fn run_isolates_cargo_target_dir_from_workspace() {
121        let temp = GuardedPath::tempdir().unwrap();
122        let root = guard_root(&temp);
123
124        #[allow(clippy::disallowed_macros)]
125        let cmd = if cfg!(windows) {
126            "echo %CARGO_TARGET_DIR% > seen.txt"
127        } else {
128            "printf %s \"$CARGO_TARGET_DIR\" > seen.txt"
129        };
130
131        let steps = vec![Step {
132            guard: None,
133            kind: StepKind::Run(cmd.to_string().into()),
134            scope_enter: 0,
135            scope_exit: 0,
136        }];
137
138        run_steps(&root, &steps).unwrap();
139
140        let seen = read_trimmed(&root.join("seen.txt").unwrap());
141        let legacy = root.join(".cargo-target").unwrap();
142
143        assert_ne!(
144            seen.trim(),
145            legacy.display().to_string(),
146            "CARGO_TARGET_DIR must not target the workspace tree"
147        );
148        assert!(
149            seen.trim().contains("oxdock-cargo-"),
150            "CARGO_TARGET_DIR must point at the isolated scratch location, got {seen:?}"
151        );
152    }
153
154    #[test]
155    fn lazy_snapshot_run_materializes_but_local_run_does_not() {
156        let temp = GuardedPath::tempdir().unwrap();
157        let root = guard_root(&temp);
158
159        // Snapshot-rooted RUN executes against the snapshot workdir.
160        let steps = parse_script("RUN echo hi").unwrap();
161        let output = run_steps_with_lazy_snapshot(&root, &steps, ExecIo::new()).unwrap();
162        assert!(
163            output.snapshot.is_materialized(),
164            "snapshot-rooted RUN must materialize the snapshot"
165        );
166
167        // LOCAL-rooted RUN executes against the live tree.
168        let steps = parse_script(indoc! {r#"
169            WORKSPACE LOCAL
170            RUN echo hi
171        "#})
172        .unwrap();
173        let output = run_steps_with_lazy_snapshot(&root, &steps, ExecIo::new()).unwrap();
174        assert!(
175            !output.snapshot.is_materialized(),
176            "LOCAL-rooted RUN must never materialize the snapshot"
177        );
178    }
179
180    #[test]
181    fn lazy_empty_run_creates_nothing() {
182        let temp = GuardedPath::tempdir().unwrap();
183        let root = guard_root(&temp);
184
185        let output = run_steps_with_lazy_snapshot(&root, &[], ExecIo::new()).unwrap();
186        assert!(!output.snapshot.is_materialized());
187        assert!(output.snapshot.get().is_none());
188    }
189
190    #[test]
191    fn lazy_local_echo_assert_failure_never_materializes_snapshot() {
192        let temp = GuardedPath::tempdir().unwrap();
193        let root = guard_root(&temp);
194
195        let script = indoc!(
196            r#"
197            WORKSPACE LOCAL
198            ECHO playground pid is 41067
199            ASSERT_CONTAINS stdout "playground pid i!!"
200            "#
201        );
202        let steps = parse_script(script).unwrap();
203
204        // Retain the snapshot handle across the failing run: the lazy
205        // convenience wrapper discards it on error, so drive the manager
206        // directly to pin the unmaterialized invariant (issue #131).
207        let mut resolver = PathResolver::new_lazy(root.clone()).unwrap();
208        resolver.set_workspace_root(root.clone());
209        let snapshot = resolver.snapshot_handle();
210        let fs: Box<dyn oxdock_fs::WorkspaceFs> = Box::new(resolver);
211        let result = run_steps_with_manager(
212            fs,
213            &steps,
214            oxdock_process::default_process_manager(),
215            ExecIo::new(),
216        );
217        assert!(result.is_err(), "mismatched ASSERT_CONTAINS must fail");
218        let err = result.err().unwrap();
219        assert!(!snapshot.is_materialized());
220        assert!(snapshot.get().is_none());
221
222        let enriched = enrich_lazy_error(&snapshot, &root, err);
223        let msg = enriched.to_string();
224        assert!(
225            msg.contains("did not contain 'playground pid i!!'"),
226            "{msg}"
227        );
228        assert!(msg.contains("never materialized"), "{msg}");
229        assert!(!msg.contains("filesystem snapshot (root"), "{msg}");
230    }
231
232    #[test]
233    fn lazy_local_echo_assert_success_leaves_snapshot_pending() {
234        let temp = GuardedPath::tempdir().unwrap();
235        let root = guard_root(&temp);
236
237        let script = indoc!(
238            r#"
239            WORKSPACE LOCAL
240            ECHO playground pid is 41067
241            ASSERT_CONTAINS stdout "playground pid is 41067"
242            "#
243        );
244        let steps = parse_script(script).unwrap();
245
246        let output = run_steps_with_lazy_snapshot(&root, &steps, ExecIo::new()).unwrap();
247        assert!(!output.snapshot.is_materialized());
248        assert!(output.snapshot.get().is_none());
249    }
250
251    #[test]
252    fn lazy_default_mode_echo_assert_failure_keeps_snapshot_pending() {
253        let temp = GuardedPath::tempdir().unwrap();
254        let root = guard_root(&temp);
255
256        // Same conditions as the LOCAL failure test, minus the WORKSPACE
257        // statement: the implicit default is snapshot mode, but the
258        // non-mutating steps must still leave it pending (issue #131).
259        let script = indoc!(
260            r#"
261            ECHO playground pid is 41067
262            ASSERT_CONTAINS stdout "playground pid i!!"
263            "#
264        );
265        let steps = parse_script(script).unwrap();
266
267        // Retain the snapshot handle across the failing run: the lazy
268        // convenience wrapper discards it on error, so drive the manager
269        // directly to pin the unmaterialized invariant (issue #131).
270        let mut resolver = PathResolver::new_lazy(root.clone()).unwrap();
271        resolver.set_workspace_root(root.clone());
272        let snapshot = resolver.snapshot_handle();
273        let fs: Box<dyn oxdock_fs::WorkspaceFs> = Box::new(resolver);
274        let result = run_steps_with_manager(
275            fs,
276            &steps,
277            oxdock_process::default_process_manager(),
278            ExecIo::new(),
279        );
280        assert!(result.is_err(), "mismatched ASSERT_CONTAINS must fail");
281        let err = result.err().unwrap();
282        assert!(!snapshot.is_materialized());
283        assert!(snapshot.get().is_none());
284
285        let enriched = enrich_lazy_error(&snapshot, &root, err);
286        let msg = enriched.to_string();
287        assert!(
288            msg.contains("did not contain 'playground pid i!!'"),
289            "{msg}"
290        );
291        assert!(msg.contains("never materialized"), "{msg}");
292        assert!(!msg.contains("filesystem snapshot (root"), "{msg}");
293    }
294
295    #[test]
296    fn lazy_default_mode_write_materializes_snapshot() {
297        let temp = GuardedPath::tempdir().unwrap();
298        let root = guard_root(&temp);
299
300        // No WORKSPACE statement: a snapshot-targeted WRITE must transition
301        // the lazy handle to materialized (issue #131).
302        let steps = parse_script("WRITE \"snap.txt\" \"snap\"").unwrap();
303
304        let output = run_steps_with_lazy_snapshot(&root, &steps, ExecIo::new()).unwrap();
305        assert!(output.snapshot.is_materialized());
306        let snapshot_root = output.snapshot.get().expect("snapshot must be published");
307        assert!(
308            exists(snapshot_root, "snap.txt"),
309            "WRITE must land inside the materialized snapshot"
310        );
311    }
312
313    #[test]
314    fn guard_skips_when_env_missing() {
315        let temp = GuardedPath::tempdir().unwrap();
316        let root = guard_root(&temp);
317
318        let guard_var = oxdock_env::GUARD_TEST_TOKEN_UNSET;
319        let script = format!(
320            indoc!(
321                r#"
322                [env:{guard}] WRITE "skipped.txt" "hi"
323                WRITE "kept.txt" "ok"
324                "#
325            ),
326            guard = guard_var
327        );
328        let steps = crate::parse_script(&script).unwrap();
329
330        run_steps(&root, &steps).unwrap();
331
332        assert!(
333            !exists(&root, "skipped.txt"),
334            "guarded WRITE should be skipped"
335        );
336        assert!(exists(&root, "kept.txt"), "unguarded WRITE should run");
337    }
338
339    #[test]
340    fn guard_sees_env_set_by_env_step() {
341        let temp = GuardedPath::tempdir().unwrap();
342        let root = guard_root(&temp);
343
344        let script = indoc!(
345            r#"
346            ENV FOO="1"
347            [env:FOO] WRITE "hit.txt" "yes"
348            WRITE "always.txt" "ok"
349            "#
350        );
351        let steps = crate::parse_script(script).unwrap();
352
353        run_steps(&root, &steps).unwrap();
354
355        assert!(
356            exists(&root, "hit.txt"),
357            "guarded WRITE should run after ENV sets variable"
358        );
359        assert!(exists(&root, "always.txt"), "unguarded WRITE should run");
360    }
361
362    #[test]
363    fn echo_runs_and_allows_subsequent_steps() {
364        let temp = GuardedPath::tempdir().unwrap();
365        let root = guard_root(&temp);
366
367        let script = indoc!(
368            r#"
369            ECHO "Hello, world"
370            WRITE "always.txt" "ok"
371            "#
372        );
373        let steps = crate::parse_script(script).unwrap();
374
375        run_steps(&root, &steps).unwrap();
376
377        assert!(exists(&root, "always.txt"), "WRITE after ECHO should run");
378    }
379
380    #[test]
381    fn guard_on_previous_line_applies_to_next_command() {
382        let temp = GuardedPath::tempdir().unwrap();
383        let root = guard_root(&temp);
384
385        let script = indoc!(
386            r#"
387            ENV FOO="1"
388            [env:FOO]
389            WRITE "hit.txt" "yes"
390            WRITE "always.txt" "ok"
391            "#
392        );
393        let steps = crate::parse_script(script).unwrap();
394
395        run_steps(&root, &steps).unwrap();
396
397        assert!(
398            exists(&root, "hit.txt"),
399            "guarded WRITE on next line should run"
400        );
401        assert!(exists(&root, "always.txt"), "unguarded WRITE should run");
402    }
403
404    #[test]
405    fn guard_respects_platform_negation() {
406        let temp = GuardedPath::tempdir().unwrap();
407        let root = guard_root(&temp);
408
409        let script = indoc!(
410            r#"
411            [not(family:unix)] WRITE "platform.txt" "hi"
412            WRITE "always.txt" "ok"
413            "#
414        );
415        let steps = crate::parse_script(script).unwrap();
416
417        run_steps(&root, &steps).unwrap();
418
419        #[allow(clippy::disallowed_macros)]
420        let expect_skipped = cfg!(unix);
421        assert_eq!(
422            exists(&root, "platform.txt"),
423            !expect_skipped,
424            "platform guard should skip on Unix and run elsewhere"
425        );
426        assert!(exists(&root, "always.txt"), "unguarded WRITE should run");
427    }
428
429    #[test]
430    fn guard_block_env_scope_restores_after_exit() {
431        let temp = GuardedPath::tempdir().unwrap();
432        let root = guard_root(&temp);
433
434        let script = indoc!(
435            r#"
436            ENV RUN="1"
437            [env:RUN] {
438                ENV INNER="1"
439                WRITE "scoped.txt" "hit"
440            }
441            [env:INNER] WRITE "leak.txt" "nope"
442            "#
443        );
444        let steps = crate::parse_script(script).unwrap();
445
446        run_steps(&root, &steps).unwrap();
447
448        assert!(exists(&root, "scoped.txt"), "block should run");
449        assert!(
450            !exists(&root, "leak.txt"),
451            "env set inside block must not leak outward"
452        );
453    }
454
455    #[test]
456    fn guard_block_workdir_scope_restores_after_exit() {
457        let temp = GuardedPath::tempdir().unwrap();
458        let root = guard_root(&temp);
459
460        let script = indoc!(
461            r#"
462            MKDIR "nested"
463            ENV RUN="1"
464            [env:RUN] {
465                WORKDIR "nested"
466                WRITE "inside.txt" "ok"
467            }
468            WRITE "outside.txt" "root"
469            "#
470        );
471        let steps = crate::parse_script(script).unwrap();
472
473        run_steps(&root, &steps).unwrap();
474
475        assert!(
476            exists(&root, "nested/inside.txt"),
477            "inside write should land in nested dir"
478        );
479        assert!(
480            exists(&root, "outside.txt"),
481            "workdir should reset after block exits"
482        );
483        assert!(
484            !exists(&root, "nested/outside.txt"),
485            "writes after block should not stay scoped"
486        );
487    }
488
489    #[test]
490    fn workspace_scope_restores_after_guard_block() {
491        let snapshot = GuardedPath::tempdir().unwrap();
492        let local = GuardedPath::tempdir().unwrap();
493        let snapshot_root = guard_root(&snapshot);
494        let local_root = guard_root(&local);
495
496        let script = indoc!(
497            r#"
498            ENV RUN="1"
499            [env:RUN] {
500                WORKSPACE LOCAL
501                WRITE "local_only.txt" "inside"
502            }
503            WRITE "snapshot_only.txt" "outside"
504            "#
505        );
506        let steps = crate::parse_script(script).unwrap();
507
508        run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
509
510        assert!(
511            local_root.join("local_only.txt").unwrap().exists(),
512            "workspace switch inside block should affect local root"
513        );
514        assert!(
515            snapshot_root.join("snapshot_only.txt").unwrap().exists(),
516            "writes after block must target snapshot again"
517        );
518        assert!(
519            !local_root.join("snapshot_only.txt").unwrap().exists(),
520            "workspace should reset after guard block exits"
521        );
522    }
523
524    #[test]
525    fn guard_matches_profile_env() {
526        // Set PROFILE via script ENV; guards now only see script-level env.
527        let temp = GuardedPath::tempdir().unwrap();
528        let root = guard_root(&temp);
529
530        let profile = std::env::var(oxdock_env::PROFILE).unwrap_or_else(|_| "debug".to_string());
531        let script = format!(
532            indoc!(
533                r#"
534                ENV PROFILE={0}
535                [eq(env:PROFILE, {0})] WRITE "hit.txt" "yes"
536                [ne(env:PROFILE, {0})] WRITE "miss.txt" "no"
537                "#
538            ),
539            profile
540        );
541
542        let steps = crate::parse_script(&script).unwrap();
543        run_steps(&root, &steps).unwrap();
544
545        assert!(
546            exists(&root, "hit.txt"),
547            "PROFILE-matching guard should run"
548        );
549        assert!(
550            !exists(&root, "miss.txt"),
551            "PROFILE inequality guard should skip for current profile"
552        );
553    }
554
555    #[test]
556    fn multiple_guards_all_must_pass() {
557        let temp = GuardedPath::tempdir().unwrap();
558        let root = guard_root(&temp);
559
560        let key = oxdock_env::MULTI_GUARD_TEST_PASS;
561
562        let script = format!(
563            indoc!(
564                r#"
565                ENV {k}=ok
566                [env:{k},eq(env:{k}, ok)] WRITE "hit.txt" "yes"
567                WRITE "always.txt" "ok"
568                "#
569            ),
570            k = key
571        );
572        let steps = crate::parse_script(&script).unwrap();
573        run_steps(&root, &steps).unwrap();
574
575        assert!(
576            exists(&root, "hit.txt"),
577            "guarded step should run when all guards pass"
578        );
579        assert!(exists(&root, "always.txt"), "unguarded step should run");
580    }
581
582    #[test]
583    fn multiple_guards_skip_when_one_fails() {
584        let temp = GuardedPath::tempdir().unwrap();
585        let root = guard_root(&temp);
586
587        let key = oxdock_env::MULTI_GUARD_TEST_FAIL;
588
589        let script = format!(
590            indoc!(
591                r#"
592                ENV {k}=ok
593                [env:{k},ne(env:{k}, ok)] WRITE "miss.txt" "yes"
594                WRITE "always.txt" "ok"
595                "#
596            ),
597            k = key
598        );
599        let steps = crate::parse_script(&script).unwrap();
600        run_steps(&root, &steps).unwrap();
601
602        assert!(
603            !exists(&root, "miss.txt"),
604            "guarded step should skip when any guard fails"
605        );
606        assert!(exists(&root, "always.txt"), "unguarded step should run");
607    }
608
609    #[cfg(unix)]
610    #[cfg_attr(
611        miri,
612        ignore = "stdout streaming not supported for background command under Miri"
613    )]
614    #[test]
615    fn async_exits_success_and_stops_pipeline() {
616        let temp = GuardedPath::tempdir().unwrap();
617        let root = guard_root(&temp);
618
619        // Background succeeds quickly; pipeline should complete without error.
620        let script = "ASYNC RUN \"sh -c 'sleep 0.05'\"";
621        let steps = crate::parse_script(script).unwrap();
622        let res = run_steps(&root, &steps);
623        assert!(res.is_ok(), "ASYNC success should allow clean exit");
624    }
625
626    #[cfg(unix)]
627    #[cfg_attr(
628        miri,
629        ignore = "stdout streaming not supported for background command under Miri"
630    )]
631    #[test]
632    fn async_failure_bubbles_status() {
633        let temp = GuardedPath::tempdir().unwrap();
634        let root = guard_root(&temp);
635
636        let script = "ASYNC RUN \"sh -c 'sleep 0.05; exit 7'\"";
637        let steps = crate::parse_script(script).unwrap();
638        let err = run_steps(&root, &steps).unwrap_err();
639        let msg = err.to_string();
640        assert!(
641            msg.contains("ASYNC process exited with status") || msg.contains("exit status: 7"),
642            "should surface failing ASYNC exit code"
643        );
644    }
645
646    #[cfg(unix)]
647    #[cfg_attr(
648        miri,
649        ignore = "timing-sensitive background process test is unreliable under Miri"
650    )]
651    #[test]
652    fn async_multiple_stops_on_first_exit_and_does_not_block_steps() {
653        let temp = GuardedPath::tempdir().unwrap();
654        let root = guard_root(&temp);
655
656        let script = indoc! {
657            r#"
658            ASYNC RUN "sh -c 'sleep 0.2; echo one > one.txt'"
659            ASYNC RUN "sh -c 'sleep 0.5; echo two > two.txt'"
660            WRITE "done.txt" "ok"
661            "#
662        };
663
664        let steps = crate::parse_script(script).unwrap();
665        let start = Instant::now();
666        let res = run_steps(&root, &steps);
667        let elapsed = start.elapsed();
668
669        assert!(res.is_ok(), "ASYNC success should allow clean exit");
670        assert!(
671            exists(&root, "done.txt"),
672            "foreground step should run after spawning backgrounds"
673        );
674        assert!(
675            exists(&root, "one.txt"),
676            "first background should finish and emit output"
677        );
678        // With the new poll-all model, both children run to completion.
679        // The second background (~0.5s) should also finish.
680        assert!(
681            exists(&root, "two.txt"),
682            "second background should finish (poll-all waits for all)"
683        );
684
685        let upper = 0.8;
686        assert!(
687            elapsed.as_secs_f32() < upper && elapsed.as_secs_f32() > 0.15,
688            "should wait for both backgrounds (~0.5s); got {elapsed:?}"
689        );
690    }
691
692    #[cfg(unix)]
693    #[cfg_attr(
694        miri,
695        ignore = "timing-sensitive background process test is unreliable under Miri"
696    )]
697    #[test]
698    fn background_killed_when_unrelated_step_fails() {
699        let temp = GuardedPath::tempdir().unwrap();
700        let root = guard_root(&temp);
701
702        let script = indoc! {
703            r#"
704            ASYNC RUN "sh -c 'sleep 1; echo late > late.txt'"
705            RUN "__oxdock_missing_command_xyz__"
706            "#
707        };
708
709        let steps = crate::parse_script(script).unwrap();
710        assert!(
711            run_steps(&root, &steps).is_err(),
712            "pipeline should fail on the missing command"
713        );
714        // The ASYNC handle is dropped mid-pipeline when the error propagates;
715        // its Drop safety net must kill the writer before it can emit the
716        // late artifact.
717        assert!(
718            !exists(&root, "late.txt"),
719            "abandoned background writer must be killed by Drop teardown"
720        );
721    }
722
723    #[cfg(unix)]
724    #[cfg_attr(
725        miri,
726        ignore = "stdout streaming not supported for background command under Miri"
727    )]
728    #[test]
729    fn exit_terminates_backgrounds_and_returns_code() {
730        let temp = GuardedPath::tempdir().unwrap();
731        let root = guard_root(&temp);
732
733        let script = indoc! {
734            r#"
735            ASYNC RUN "sh -c 'sleep 1; echo late > late.txt'"
736            EXIT 5
737            "#
738        };
739
740        let steps = crate::parse_script(script).unwrap();
741        let err = run_steps(&root, &steps).unwrap_err();
742        let msg = err.to_string();
743        assert!(msg.contains("EXIT requested with code 5"));
744        assert!(
745            !exists(&root, "late.txt"),
746            "background process should be killed when EXIT is hit"
747        );
748    }
749
750    #[test]
751    #[cfg_attr(
752        miri,
753        ignore = "EXIT joins real background threads; timing-sensitive under Miri"
754    )]
755    fn exit_inside_nested_block_reports_code_and_kills_backgrounds() {
756        let temp = GuardedPath::tempdir().unwrap();
757        let root = guard_root(&temp);
758
759        let script = indoc! {
760            r#"
761            ASYNC {
762                SLEEP 30s
763            }
764            [bool:true] {
765                EXIT 5
766            }
767            "#
768        };
769
770        let steps = crate::parse_script(script).unwrap();
771        let start = std::time::Instant::now();
772        let err = run_steps(&root, &steps).unwrap_err();
773        assert!(
774            err.to_string().contains("EXIT requested with code 5"),
775            "nested EXIT must report its code: {err}"
776        );
777        assert!(
778            start.elapsed() < std::time::Duration::from_secs(10),
779            "nested EXIT must kill the background SLEEP promptly"
780        );
781    }
782
783    #[cfg_attr(
784        miri,
785        ignore = "stdout streaming not supported for background command under Miri"
786    )]
787    #[test]
788    fn env_applies_to_run_and_background() {
789        let temp = GuardedPath::tempdir().unwrap();
790        let root = guard_root(&temp);
791
792        #[allow(clippy::disallowed_macros)]
793        let script = if cfg!(windows) {
794            indoc! {
795                r#"
796                ENV FOO="bar"
797                RUN "echo %FOO% > run.txt"
798                ASYNC RUN "echo %FOO% > bg.txt"
799                "#
800            }
801        } else {
802            indoc! {
803                r#"
804                ENV FOO="bar"
805                RUN "sh -c 'printf %s \"$FOO\" > run.txt'"
806                ASYNC RUN "sh -c 'printf %s \"$FOO\" > bg.txt'"
807                "#
808            }
809        };
810
811        let steps = crate::parse_script(script).unwrap();
812        run_steps(&root, &steps).unwrap();
813
814        assert_eq!(read_trimmed(&root.join("run.txt").unwrap()), "bar");
815        assert_eq!(read_trimmed(&root.join("bg.txt").unwrap()), "bar");
816    }
817
818    #[test]
819    fn workspace_switches_between_snapshot_and_local() {
820        let snapshot = GuardedPath::tempdir().unwrap();
821        let local = GuardedPath::tempdir().unwrap();
822        let snapshot_root = guard_root(&snapshot);
823        let local_root = guard_root(&local);
824
825        let script = indoc! {
826            r#"
827            WRITE "snap.txt" "snap"
828            WORKSPACE LOCAL
829            WRITE "local.txt" "local"
830            WORKSPACE SNAPSHOT
831            WRITE "snap2.txt" "again"
832            "#
833        };
834
835        let steps = crate::parse_script(script).unwrap();
836        run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
837
838        assert!(snapshot_root.join("snap.txt").unwrap().exists());
839        assert!(snapshot_root.join("snap2.txt").unwrap().exists());
840        assert!(local_root.join("local.txt").unwrap().exists());
841    }
842
843    #[test]
844    fn workspace_root_changes_where_slash_points() {
845        let snapshot = GuardedPath::tempdir().unwrap();
846        let local = GuardedPath::tempdir().unwrap();
847        let snapshot_root = guard_root(&snapshot);
848        let local_root = guard_root(&local);
849        let local_client = local_root.join("client").unwrap();
850        create_dirs(&local_client);
851
852        let script = indoc! {
853            r#"
854            WORKSPACE LOCAL
855            WORKDIR "/"
856            WRITE "localroot.txt" "one"
857            WORKDIR "client"
858            WRITE "client.txt" "two"
859            WORKSPACE SNAPSHOT
860            WORKDIR "/"
861            WRITE "snaproot.txt" "three"
862            "#
863        };
864
865        let steps = crate::parse_script(script).unwrap();
866        run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
867
868        assert!(local_root.join("localroot.txt").unwrap().exists());
869        assert!(local_client.join("client.txt").unwrap().exists());
870        assert!(snapshot_root.join("snaproot.txt").unwrap().exists());
871    }
872
873    /// Serialized cache-dir pin for hermetic tests. `OXDOCK_CACHE_DIR` is
874    /// process-global; the lock plus drop-restore keeps parallel tests
875    /// isolated (mirrors `SerialCargoEnv` in `oxdock-process`).
876    struct SerialCacheDir {
877        _lock: std::sync::MutexGuard<'static, ()>,
878        prev: Option<String>,
879    }
880
881    static CACHE_DIR_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
882
883    impl SerialCacheDir {
884        fn pin(dir: &GuardedPath) -> Self {
885            let lock = CACHE_DIR_LOCK
886                .lock()
887                .unwrap_or_else(|poisoned| poisoned.into_inner());
888            let prev = std::env::var(oxdock_env::CACHE_DIR).ok();
889            // SAFETY: serialized by `CACHE_DIR_LOCK`, restored on drop.
890            unsafe {
891                std::env::set_var(
892                    oxdock_env::CACHE_DIR,
893                    dir.as_path().to_string_lossy().into_owned(),
894                );
895            }
896            Self { _lock: lock, prev }
897        }
898    }
899
900    impl Drop for SerialCacheDir {
901        fn drop(&mut self) {
902            unsafe {
903                match &self.prev {
904                    Some(v) => std::env::set_var(oxdock_env::CACHE_DIR, v),
905                    None => std::env::remove_var(oxdock_env::CACHE_DIR),
906                }
907            }
908        }
909    }
910
911    #[test]
912    fn workspace_cache_persists_across_runs() {
913        let pin = GuardedPath::tempdir().unwrap();
914        let pin_root = guard_root(&pin);
915        let _env = SerialCacheDir::pin(&pin_root);
916
917        let snapshot = GuardedPath::tempdir().unwrap();
918        let local = GuardedPath::tempdir().unwrap();
919        let snapshot_root = guard_root(&snapshot);
920        let local_root = guard_root(&local);
921
922        // First run writes through CACHE, then hops roots to prove the
923        // entry does not land in snapshot or local.
924        let first = indoc! {
925            r#"
926            WRITE "snap.txt" "snap"
927            WORKSPACE LOCAL
928            WRITE "local.txt" "local"
929            WORKSPACE CACHE
930            WRITE "cached.txt" "persistent"
931            WORKSPACE SNAPSHOT
932            "#
933        };
934        let steps = crate::parse_script(first).unwrap();
935        run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
936
937        // Native only: the Miri synthetic backend keys all non-snapshot
938        // state by build root, so cross-root absence is vacuous there.
939        // Selection itself is covered by mock tests under Miri.
940        #[cfg(not(miri))]
941        assert!(!exists(&snapshot_root, "cached.txt"));
942        #[cfg(not(miri))]
943        assert!(!exists(&local_root, "cached.txt"));
944
945        // A fresh run with a fresh snapshot root still sees the entry:
946        // the cache survived while the snapshot did not. The Miri
947        // synthetic backend keys non-snapshot state by build root, so the
948        // second run reuses the local root there; natively it gets a
949        // fresh one.
950        let fresh_snapshot = GuardedPath::tempdir().unwrap();
951        let fresh_snapshot_root = guard_root(&fresh_snapshot);
952        #[cfg(not(miri))]
953        let fresh_local = GuardedPath::tempdir().unwrap();
954        #[cfg(not(miri))]
955        let fresh_local_root = guard_root(&fresh_local);
956        #[cfg(miri)]
957        let fresh_local_root = local_root.clone();
958
959        let second = indoc! {
960            r#"
961            WORKSPACE CACHE
962            LET $v: STRING = READ cached.txt
963            ASSERT_EQ $v "persistent"
964            "#
965        };
966        let steps = crate::parse_script(second).unwrap();
967        run_steps_with_context(&fresh_snapshot_root, &fresh_local_root, &steps).unwrap();
968    }
969
970    #[test]
971    fn workspace_cache_local_stays_in_project_tree() {
972        // Pin the OS cache aside: `--local` must never touch it.
973        let pin = GuardedPath::tempdir().unwrap();
974        let pin_root = guard_root(&pin);
975        let _env = SerialCacheDir::pin(&pin_root);
976
977        let snapshot = GuardedPath::tempdir().unwrap();
978        let local = GuardedPath::tempdir().unwrap();
979        let snapshot_root = guard_root(&snapshot);
980        let local_root = guard_root(&local);
981
982        let first = indoc! {
983            r#"
984            WORKSPACE CACHE --local
985            WRITE "local-cached.txt" "persistent"
986            LET $v: STRING = READ local-cached.txt
987            ASSERT_EQ $v "persistent"
988            "#
989        };
990        let steps = crate::parse_script(first).unwrap();
991        run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
992
993        // Native only (see above): the Miri synthetic backend shares one
994        // namespace per build root, so location assertions are vacuous.
995        #[cfg(not(miri))]
996        assert!(exists(&local_root, ".cache/workspace/local-cached.txt"));
997        #[cfg(not(miri))]
998        assert!(!exists(&pin_root, "workspace/local-cached.txt"));
999
1000        // A fresh snapshot against the same project tree reads it back:
1001        // the local cache outlives the ephemeral snapshot.
1002        let fresh_snapshot = GuardedPath::tempdir().unwrap();
1003        let fresh_snapshot_root = guard_root(&fresh_snapshot);
1004        let second = indoc! {
1005            r#"
1006            WORKSPACE CACHE --local
1007            LET $v: STRING = READ local-cached.txt
1008            ASSERT_EQ $v "persistent"
1009            "#
1010        };
1011        let steps = crate::parse_script(second).unwrap();
1012        run_steps_with_context(&fresh_snapshot_root, &local_root, &steps).unwrap();
1013
1014        // A fresh project tree does not: the local cache lives and dies
1015        // with the tree, unlike the OS-native flavor.
1016        let other_local = GuardedPath::tempdir().unwrap();
1017        let other_local_root = guard_root(&other_local);
1018        let steps = crate::parse_script(second).unwrap();
1019        assert!(
1020            run_steps_with_context(&fresh_snapshot_root, &other_local_root, &steps).is_err(),
1021            "local cache must not leak across project trees"
1022        );
1023    }
1024
1025    #[test]
1026    fn workspace_system_reaches_outside_roots() {
1027        let snapshot = GuardedPath::tempdir().unwrap();
1028        let local = GuardedPath::tempdir().unwrap();
1029        let snapshot_root = guard_root(&snapshot);
1030        let local_root = guard_root(&local);
1031        let outside = GuardedPath::tempdir().unwrap();
1032        let outside_root = guard_root(&outside);
1033
1034        // From a snapshot-selected start, SYSTEM writes an outside file by
1035        // absolute path, reads it back, and writes a sibling next to it.
1036        // Seeding from inside the script keeps every backend (including
1037        // the Miri synthetic one, which keys state by guard root) in one
1038        // namespace. Forward slashes throughout: a raw Windows path would
1039        // lose its backslashes to DSL string escapes (`C:\Users` parses
1040        // as `C:Users`).
1041        let script = format!(
1042            indoc! {r#"
1043                WORKSPACE SYSTEM
1044                WRITE "{secret}" outside
1045                LET $v: STRING = READ "{secret}"
1046                ASSERT_EQ $v outside
1047                WRITE "{sibling}" done
1048                WORKSPACE SNAPSHOT
1049            "#},
1050            secret = to_forward_slashes(
1051                &outside_root
1052                    .join("secret.txt")
1053                    .unwrap()
1054                    .as_path()
1055                    .to_string_lossy()
1056            ),
1057            sibling = to_forward_slashes(
1058                &outside_root
1059                    .join("sibling.txt")
1060                    .unwrap()
1061                    .as_path()
1062                    .to_string_lossy()
1063            ),
1064        );
1065        let steps = crate::parse_script(&script).unwrap();
1066        run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
1067
1068        // Native only (see above): Miri shares one namespace per build root,
1069        // while the in-script ASSERT_EQ already verifies content everywhere.
1070        #[cfg(not(miri))]
1071        assert!(exists(&outside_root, "sibling.txt"));
1072        // Native only (see above): Miri shares one namespace per build root.
1073        #[cfg(not(miri))]
1074        assert!(!exists(&snapshot_root, "sibling.txt"));
1075        #[cfg(not(miri))]
1076        assert!(!exists(&local_root, "sibling.txt"));
1077    }
1078
1079    #[test]
1080    fn copy_from_workspace_targets() {
1081        let pin = GuardedPath::tempdir().unwrap();
1082        let pin_root = guard_root(&pin);
1083        let _env = SerialCacheDir::pin(&pin_root);
1084
1085        let snapshot = GuardedPath::tempdir().unwrap();
1086        let local = GuardedPath::tempdir().unwrap();
1087        let snapshot_root = guard_root(&snapshot);
1088        let local_root = guard_root(&local);
1089        let outside = GuardedPath::tempdir().unwrap();
1090        let outside_root = guard_root(&outside);
1091
1092        // SNAPSHOT, CACHE, LOCAL, and SYSTEM sources each resolve against
1093        // their own root and land in the snapshot cwd. The SYSTEM source
1094        // is seeded from inside the script so every backend observes one
1095        // namespace. Forward slashes throughout: raw Windows backslashes
1096        // would be consumed by DSL string escapes.
1097        let script = format!(
1098            indoc! {r#"
1099                WRITE snap-src.txt from-snap
1100                WORKSPACE CACHE
1101                WRITE cache-src.txt from-cache
1102                WORKSPACE SYSTEM
1103                WRITE "{secret}" outside
1104                WORKSPACE SNAPSHOT
1105                COPY --from-workspace SNAPSHOT snap-src.txt snap-copy.txt
1106                COPY --from-workspace CACHE cache-src.txt cache-copy.txt
1107                COPY --from-workspace SYSTEM "{secret}" sys-copy.txt
1108                COPY --from-workspace LOCAL "{local_src}" local-copy.txt
1109            "#},
1110            secret = to_forward_slashes(
1111                &outside_root
1112                    .join("secret.txt")
1113                    .unwrap()
1114                    .as_path()
1115                    .to_string_lossy()
1116            ),
1117            local_src = to_forward_slashes(
1118                &local_root
1119                    .join("local-src.txt")
1120                    .unwrap()
1121                    .as_path()
1122                    .to_string_lossy()
1123            ),
1124        );
1125        // Seed the LOCAL source through the build context side.
1126        let local_seeder = PathResolver::new(local_root.as_path(), local_root.as_path()).unwrap();
1127        local_seeder
1128            .write_file(&local_root.join("local-src.txt").unwrap(), b"from-local")
1129            .unwrap();
1130
1131        let steps = crate::parse_script(&script).unwrap();
1132        run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
1133
1134        assert!(exists(&snapshot_root, "snap-copy.txt"));
1135        assert!(exists(&snapshot_root, "cache-copy.txt"));
1136        assert!(exists(&snapshot_root, "sys-copy.txt"));
1137        assert!(exists(&snapshot_root, "local-copy.txt"));
1138
1139        // A pending snapshot has no source to copy from.
1140        let pending = indoc! {r#"
1141            COPY --from-workspace SNAPSHOT missing.txt out.txt
1142        "#};
1143        let steps = crate::parse_script(pending).unwrap();
1144        let fresh_snapshot = GuardedPath::tempdir().unwrap();
1145        let fresh_local = GuardedPath::tempdir().unwrap();
1146        assert!(
1147            run_steps_with_context(
1148                &guard_root(&fresh_snapshot),
1149                &guard_root(&fresh_local),
1150                &steps
1151            )
1152            .is_err(),
1153            "COPY from a pending snapshot must fail"
1154        );
1155    }
1156
1157    #[test]
1158    fn copy_destinations_mirror_docker() {
1159        // Docker destination semantics: a file copied onto a directory
1160        // (`.`, an existing dir, or a trailing-slash spell) lands inside
1161        // it under its basename; a directory source copies its contents.
1162        // Covers the `COPY file .` escape-check failure under cache roots.
1163        let pin = GuardedPath::tempdir().unwrap();
1164        let pin_root = guard_root(&pin);
1165        let _env = SerialCacheDir::pin(&pin_root);
1166
1167        let snapshot = GuardedPath::tempdir().unwrap();
1168        let local = GuardedPath::tempdir().unwrap();
1169        let snapshot_root = guard_root(&snapshot);
1170        let local_root = guard_root(&local);
1171
1172        let seeder = PathResolver::new(local_root.as_path(), local_root.as_path()).unwrap();
1173        seeder
1174            .write_file(&local_root.join("cargo.toml").unwrap(), b"manifest")
1175            .unwrap();
1176        seeder
1177            .create_dir_all(&local_root.join("sub").unwrap())
1178            .unwrap();
1179        seeder
1180            .write_file(&local_root.join("sub/a.txt").unwrap(), b"a")
1181            .unwrap();
1182
1183        let script = indoc! {r#"
1184            WORKSPACE CACHE --local
1185            COPY --from-workspace LOCAL cargo.toml .
1186            LET $a: STRING = READ cargo.toml
1187            ASSERT_EQ $a manifest
1188            COPY --from-workspace LOCAL cargo.toml renamed.txt
1189            LET $b: STRING = READ renamed.txt
1190            ASSERT_EQ $b manifest
1191            MKDIR subdir
1192            COPY --from-workspace LOCAL cargo.toml subdir
1193            COPY --from-workspace LOCAL cargo.toml subdir/
1194            LET $c: STRING = READ subdir/cargo.toml
1195            ASSERT_EQ $c manifest
1196            COPY --from-workspace LOCAL sub .
1197            LET $d: STRING = READ a.txt
1198            ASSERT_EQ $d a
1199            WORKSPACE SNAPSHOT
1200            COPY --from-workspace LOCAL cargo.toml .
1201            LET $e: STRING = READ cargo.toml
1202            ASSERT_EQ $e manifest
1203        "#};
1204        let steps = crate::parse_script(script).unwrap();
1205        run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
1206
1207        // Native only: the Miri synthetic backend keys all non-snapshot
1208        // state by build root, so location assertions via `exists()` are
1209        // vacuous there. Content is verified in-script above on every
1210        // platform; selection itself is covered by mock tests under Miri.
1211        #[cfg(not(miri))]
1212        assert!(exists(&local_root, ".cache/workspace/cargo.toml"));
1213        #[cfg(not(miri))]
1214        assert!(exists(&local_root, ".cache/workspace/renamed.txt"));
1215        #[cfg(not(miri))]
1216        assert!(exists(&local_root, ".cache/workspace/subdir/cargo.toml"));
1217        #[cfg(not(miri))]
1218        assert!(exists(&local_root, ".cache/workspace/a.txt"));
1219        #[cfg(not(miri))]
1220        assert!(exists(&snapshot_root, "cargo.toml"));
1221    }
1222}