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