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