Skip to main content

magi/
worktree_setup.rs

1//! `[worktree] setup`: what a fresh worktree needs beyond its tracked files.
2//!
3//! magi makes its worktrees with plain `git worktree add`, so a `.env` or a
4//! one-off bootstrap that `renri add` would have produced is missing. Each
5//! step runs in order, right after the worktree exists and before any agent
6//! or verify command touches it. A failing step fails that worktree with the
7//! step and its output; nothing here is ever swallowed.
8//!
9//! Three rules keep the competition honest:
10//!
11//! - **Blindness.** `MAGI_RUN` / `MAGI_NODE` are removed from a command's
12//!   environment, and nothing seat- or agent-shaped is exported.
13//! - **Products are not work.** Every path the steps leave untracked is
14//!   recorded in the worktree's own git dir ([`RECORD`]) and hidden from `git
15//!   add -A` by a per-worktree `core.excludesFile`; [`withheld_paths`] is the
16//!   second line, used by the rescue commits.
17//! - **Setup does not edit tracked files.** One that does fails the worktree,
18//!   which also stops a `kata apply`-shaped step: every candidate would carry
19//!   the same diff.
20
21use std::path::{Component, Path, PathBuf};
22use std::time::Duration;
23
24use anyhow::{Context, Result, bail};
25
26use crate::config::{Config, SetupStep};
27use crate::git;
28use crate::proc::Quiet as _;
29
30/// File in the worktree's git dir listing the setup products, NUL-separated.
31pub const RECORD: &str = "magi-setup-paths";
32/// Per-worktree exclude file `core.excludesFile` points at.
33const EXCLUDE: &str = "magi-setup-exclude";
34/// Output kept in an error message.
35const TAIL: usize = 4000;
36
37/// Run `cfg.worktree.setup` in `wt`, a worktree of `repo` (the primary checkout).
38///
39/// A no-op for the default empty list. Idempotent, since a reviewer's worktree
40/// is wiped and set up again every round.
41pub async fn prepare(cfg: &Config, repo: &Path, wt: &Path) -> Result<()> {
42    prepare_with(cfg, repo, wt, crate::build_target::Coordination::Acquire).await
43}
44
45pub(crate) async fn prepare_with(
46    cfg: &Config,
47    repo: &Path,
48    wt: &Path,
49    coordination: crate::build_target::Coordination<'_>,
50) -> Result<()> {
51    let steps = &cfg.worktree.setup;
52    if steps.is_empty() {
53        return Ok(());
54    }
55    let total = steps.len();
56    let shell = steps
57        .iter()
58        .any(|step| step.run.is_some())
59        .then(|| cfg.shell());
60    // Reserve once, before even a copy step. AdmissionDiskWait must prove
61    // that no setup step has run, so a caller can safely retry from scratch.
62    let build = if let Some(shell) = &shell
63        && crate::build_target::isolated(cfg)
64    {
65        crate::build_target::command::check_shell(shell)?;
66        // Every setup command must fit the isolated grammar, as each did at
67        // its own step before admission moved up here. Checked for all of
68        // them first, so an unsupported one stops setup before anything ran.
69        for (i, step) in steps.iter().enumerate() {
70            if let Some(command) = &step.run {
71                crate::build_target::command::normalize(command).with_context(|| {
72                    format!(
73                        "worktree setup step {}/{total} ({}) failed",
74                        i + 1,
75                        step.describe()
76                    )
77                })?;
78            }
79        }
80        let build = crate::build_target::Operation::admit(cfg, wt, "", "setup", coordination)
81            .await
82            .context("worktree setup admission")?;
83        Some(build)
84    } else {
85        None
86    };
87    let mut copied: Vec<String> = Vec::new();
88    for (i, step) in steps.iter().enumerate() {
89        let n = i + 1;
90        let what = step.describe();
91        match (&step.copy, &step.run) {
92            (Some(spec), None) => {
93                let made = copy_step(repo, wt, spec, step.optional)
94                    .await
95                    .with_context(|| format!("worktree setup step {n}/{total} ({what}) failed"))?;
96                copied.extend(made);
97            }
98            (None, Some(command)) => {
99                let secs = step
100                    .timeout_secs
101                    .unwrap_or_else(|| cfg.graph.verify_timeout());
102                let shell = shell.as_deref().expect("setup command has a shell");
103                let timeout = Duration::from_secs(secs);
104                let (lease, outputs, target) = if let Some(build) = &build {
105                    let mut outputs: Vec<_> = build
106                        .outputs
107                        .iter()
108                        .map(crate::retention::OutputLease::duplicate)
109                        .collect();
110                    outputs.extend(crate::retention::OutputLease::borrow(wt)?);
111                    (
112                        build
113                            .lease
114                            .as_ref()
115                            .map(crate::repo_lock::SeatLease::share_operation),
116                        outputs,
117                        Some((build.target.as_path(), cfg.disk.min_free_bytes)),
118                    )
119                } else {
120                    (None, Vec::new(), None)
121                };
122                let result =
123                    run_command(shell, command, wt, timeout, lease, outputs, false, target).await;
124                result
125                    .with_context(|| format!("worktree setup step {n}/{total} ({what}) failed"))?;
126            }
127            _ => bail!("worktree setup step {n}/{total} must set exactly one of copy / run"),
128        }
129    }
130    seal(wt, &copied).await.context("worktree setup")
131}
132
133/// `src -> dst`, or just `path` for the same path on both sides.
134fn split_copy(spec: &str) -> (&str, &str) {
135    match spec.split_once("->") {
136        Some((a, b)) => (a.trim(), b.trim()),
137        None => (spec.trim(), spec.trim()),
138    }
139}
140
141/// Is `p` a path that stays inside the worktree, and out of `.git`?
142pub fn valid_destination(p: &str) -> Result<()> {
143    if p.is_empty() {
144        bail!("destination is empty");
145    }
146    let path = Path::new(p);
147    if path.is_absolute() || p.starts_with('/') || p.starts_with('\\') || p.contains(':') {
148        bail!("destination `{p}` must be relative to the worktree");
149    }
150    let mut first = true;
151    for c in path.components() {
152        match c {
153            Component::Normal(s) => {
154                if first && s.eq_ignore_ascii_case(".git") {
155                    bail!("destination `{p}` is inside .git");
156                }
157                first = false;
158            }
159            Component::CurDir => {}
160            _ => bail!("destination `{p}` must not contain `..`"),
161        }
162    }
163    Ok(())
164}
165
166/// Validate a `copy` spec at load time.
167pub fn validate_copy(spec: &str) -> Result<()> {
168    let (src, dst) = split_copy(spec);
169    if src.is_empty() {
170        bail!("copy `{spec}` has no source");
171    }
172    valid_destination(dst)
173}
174
175/// Returns the destination when this call created it.
176async fn copy_step(repo: &Path, wt: &Path, spec: &str, optional: bool) -> Result<Option<String>> {
177    let (src, dst) = split_copy(spec);
178    validate_copy(spec)?;
179    let src_path = if Path::new(src).is_absolute() {
180        PathBuf::from(src)
181    } else {
182        repo.join(src)
183    };
184    let dst_path = wt.join(dst);
185    // A destination reached through a symlink could land outside the worktree.
186    let mut probe = wt.to_path_buf();
187    for c in Path::new(dst).components() {
188        if let Component::Normal(s) = c {
189            probe.push(s);
190            if let Ok(meta) = tokio::fs::symlink_metadata(&probe).await
191                && meta.file_type().is_symlink()
192            {
193                bail!("destination `{dst}` goes through a symlink");
194            }
195        }
196    }
197    let data = match tokio::fs::read(&src_path).await {
198        Ok(d) => d,
199        Err(e) if e.kind() == std::io::ErrorKind::NotFound && optional => return Ok(None),
200        Err(e) => bail!("cannot read source {}: {e}", src_path.display()),
201    };
202    if let Some(parent) = dst_path.parent() {
203        tokio::fs::create_dir_all(parent)
204            .await
205            .with_context(|| format!("create {}", parent.display()))?;
206    }
207    // `create_new`: an existing file in the worktree wins, never overwritten.
208    use tokio::io::AsyncWriteExt as _;
209    match tokio::fs::OpenOptions::new()
210        .write(true)
211        .create_new(true)
212        .open(&dst_path)
213        .await
214    {
215        Ok(mut f) => {
216            f.write_all(&data).await?;
217            f.flush().await?;
218            #[cfg(unix)]
219            if let Ok(meta) = tokio::fs::metadata(&src_path).await {
220                tokio::fs::set_permissions(&dst_path, meta.permissions())
221                    .await
222                    .ok();
223            }
224            Ok(Some(dst.trim_start_matches("./").to_owned()))
225        }
226        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(None),
227        Err(e) => bail!("cannot create {}: {e}", dst_path.display()),
228    }
229}
230
231fn tail(s: &str) -> &str {
232    let s = s.trim();
233    if s.len() <= TAIL {
234        return s;
235    }
236    let mut at = s.len() - TAIL;
237    while !s.is_char_boundary(at) {
238        at += 1;
239    }
240    &s[at..]
241}
242
243/// Shared contained shell runner for setup and pre-clean commands.
244#[allow(clippy::too_many_arguments)]
245pub(crate) async fn run_command(
246    shell: &[String],
247    command: &str,
248    wt: &Path,
249    timeout: Duration,
250    lease: Option<crate::repo_lock::SeatLease>,
251    outputs: Vec<crate::retention::OutputLease>,
252    pre_clean: bool,
253    target: Option<(&Path, u64)>,
254) -> Result<()> {
255    let script = target
256        .map(|_| crate::build_target::command::normalize(command))
257        .transpose()?
258        .unwrap_or(command);
259    static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
260    let log = std::env::temp_dir().join(format!(
261        "magi-setup-{}-{}.out",
262        std::process::id(),
263        SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
264    ));
265    if pre_clean {
266        tracing::info!(cwd = %wt.display(), output = %log.display(), command, "pre-clean command output (retained on interruption)");
267    }
268    let out = std::fs::File::create(&log).context("create output file")?;
269    let err = out.try_clone()?;
270    let mut cmd = tokio::process::Command::new(&shell[0]);
271    cmd.quiet();
272    cmd.args(&shell[1..])
273        .arg(script)
274        .current_dir(wt)
275        .env_remove("MAGI_RUN")
276        .env_remove("MAGI_NODE")
277        .stdin(std::process::Stdio::null())
278        .stdout(out)
279        .stderr(err)
280        .kill_on_drop(true);
281    crate::chat_control::bridge::clear_environment(&mut cmd);
282    if pre_clean {
283        cmd.env("MAGI_PRE_CLEAN_ACTIVE", "1");
284        for key in crate::worker::INVOCATION_ENV {
285            cmd.env_remove(key);
286        }
287    }
288    crate::incremental::configure(&mut cmd, wt)?;
289    let spawn = if let Some((target, _)) = target {
290        crate::build_target::command::configure(&mut cmd, target)?;
291        crate::seat_process::Running::spawn_build
292    } else {
293        crate::build_target::command::clear(&mut cmd)?;
294        crate::seat_process::Running::spawn_operation
295    };
296    let mut running = spawn(cmd, lease, outputs)
297        .with_context(|| format!("spawn `{}` for `{command}`", shell[0]))?;
298    let pressure = async {
299        match target {
300            Some((target, floor)) => {
301                crate::retention::emergency(vec![wt.to_owned(), target.to_owned()], floor, true)
302                    .await
303            }
304            None => std::future::pending().await,
305        }
306    };
307    let waited = tokio::select! {
308        waited = tokio::time::timeout(timeout, running.child().wait()) => waited,
309        reason = pressure => {
310            running.finish().await;
311            std::fs::remove_file(&log).ok();
312            return Err(crate::repo_lock::ResourceBlocked(reason).into());
313        }
314    };
315    // Compiler wrappers supervise their own process groups. Join cleanup of
316    // the entire setup tree before returning, on success as well as timeout.
317    // Cancellation transfers the same ownership to Running's cleanup thread.
318    running.finish().await;
319    let body = || {
320        use std::io::{Read, Seek, SeekFrom};
321        let mut bytes = Vec::new();
322        if let Ok(mut f) = std::fs::File::open(&log) {
323            let _ = f.seek(SeekFrom::End(-(TAIL as i64)));
324            let _ = f.take(TAIL as u64).read_to_end(&mut bytes);
325        }
326        tail(&String::from_utf8_lossy(&bytes)).to_owned()
327    };
328    let result = match waited {
329        Ok(Ok(status)) if status.success() => Ok(()),
330        Ok(Ok(status)) => Err(anyhow::anyhow!(
331            "`{command}` exited with {status}\n{}",
332            body()
333        )),
334        Ok(Err(e)) => Err(anyhow::anyhow!("`{command}` could not be awaited: {e}")),
335        Err(_) => Err(anyhow::anyhow!(
336            "`{command}` timed out after {}s\n{}",
337            timeout.as_secs(),
338            body()
339        )),
340    };
341    std::fs::remove_file(&log).ok();
342    result
343}
344
345async fn git_dir(wt: &Path) -> Result<PathBuf> {
346    Ok(PathBuf::from(
347        git::git(wt, &["rev-parse", "--absolute-git-dir"])
348            .await?
349            .trim(),
350    ))
351}
352
353/// Paths a worktree's setup recorded, relative to it. Empty when none.
354pub async fn withheld_paths(wt: &Path) -> Vec<String> {
355    let Ok(dir) = git_dir(wt).await else {
356        return Vec::new();
357    };
358    let Ok(raw) = tokio::fs::read(dir.join(RECORD)).await else {
359        return Vec::new();
360    };
361    raw.split(|b| *b == 0)
362        .filter(|p| !p.is_empty())
363        .map(|p| String::from_utf8_lossy(p).into_owned())
364        .collect()
365}
366
367/// Unstage whatever setup produced, so a rescue commit never carries it.
368pub async fn unstage_products(wt: &Path) -> Result<()> {
369    let paths = withheld_paths(wt).await;
370    if paths.is_empty() {
371        return Ok(());
372    }
373    let mut args = vec!["reset", "-q", "--"];
374    args.extend(paths.iter().map(String::as_str));
375    git::git(wt, &args).await.map(|_| ())
376}
377
378/// After the steps: refuse tracked edits, record the untracked products and
379/// hide them from `git add`.
380async fn seal(wt: &Path, copied: &[String]) -> Result<()> {
381    let tracked = git::git(wt, &["diff", "--name-only", "HEAD"]).await?;
382    if !tracked.trim().is_empty() {
383        bail!(
384            "setup must not change tracked files (every seat would carry the same diff), \
385             but it changed:\n{}",
386            tail(&tracked)
387        );
388    }
389    let out = git::git(wt, &["ls-files", "-z", "--others", "--exclude-standard"]).await?;
390    let mut paths: Vec<String> = withheld_paths(wt).await;
391    // Copied files are recorded even when `.gitignore` hides them from
392    // `--exclude-standard`: a later `git add -f` or an edited ignore rule must
393    // still not carry them into a commit.
394    for p in copied
395        .iter()
396        .map(String::as_str)
397        .chain(out.split('\0').filter(|p| !p.is_empty()))
398    {
399        if !paths.iter().any(|q| q == p) {
400            paths.push(p.to_owned());
401        }
402    }
403    if paths.is_empty() {
404        return Ok(());
405    }
406    let dir = git_dir(wt).await?;
407    let mut raw = Vec::new();
408    for p in &paths {
409        raw.extend_from_slice(p.as_bytes());
410        raw.push(0);
411    }
412    tokio::fs::write(dir.join(RECORD), raw).await?;
413    hide(wt, &dir, &paths).await
414}
415
416fn exclude_line(p: &str) -> String {
417    let mut s = String::from("/");
418    for c in p.chars() {
419        if matches!(c, '*' | '?' | '[' | ']' | '\\' | '#' | '!' | ' ') {
420            s.push('\\');
421        }
422        s.push(c);
423    }
424    s
425}
426
427/// Point this worktree's `core.excludesFile` at its products, keeping the
428/// user's own excludes. Needs `extensions.worktreeConfig`, which the caller
429/// takes with `git::acquire_worktree_config`; without it `--worktree` would
430/// write the shared config and change the operator's checkout, so that is a
431/// loud failure, never a fallback.
432async fn hide(wt: &Path, dir: &Path, paths: &[String]) -> Result<()> {
433    let ext = git::git_raw(wt, &["config", "--get", "extensions.worktreeConfig"]).await?;
434    if !(ext.ok() && ext.stdout.trim() == "true") {
435        bail!(
436            "setup left untracked files ({}) but extensions.worktreeConfig is off, so they \
437             cannot be hidden from `git add` per worktree",
438            paths.join(", ")
439        );
440    }
441    let file = dir.join(EXCLUDE);
442    let file_s = file.to_string_lossy().replace('\\', "/");
443    let current = git::git_raw(wt, &["config", "--get", "core.excludesFile"])
444        .await
445        .ok()
446        .filter(|o| o.ok())
447        .map(|o| o.stdout.trim().to_owned())
448        .filter(|s| !s.is_empty());
449    let mut body = match current {
450        Some(c) if c == file_s => std::fs::read_to_string(&file).unwrap_or_default(),
451        Some(c) => {
452            let c = match c.strip_prefix("~/") {
453                Some(rest) => std::env::var_os("HOME")
454                    .map(|h| PathBuf::from(h).join(rest))
455                    .unwrap_or_else(|| PathBuf::from(&c)),
456                None => PathBuf::from(&c),
457            };
458            std::fs::read_to_string(c).unwrap_or_default()
459        }
460        None => String::new(),
461    };
462    if !body.is_empty() && !body.ends_with('\n') {
463        body.push('\n');
464    }
465    for p in paths {
466        let line = exclude_line(p);
467        if !body.lines().any(|l| l == line) {
468            body.push_str(&line);
469            body.push('\n');
470        }
471    }
472    std::fs::write(&file, body).with_context(|| format!("write {}", file.display()))?;
473    git::git(wt, &["config", "--worktree", "core.excludesFile", &file_s])
474        .await
475        .map(|_| ())
476}
477
478impl SetupStep {
479    /// One-line description for errors.
480    pub fn describe(&self) -> String {
481        match (&self.copy, &self.run) {
482            (Some(c), _) => format!("copy {c}"),
483            (_, Some(r)) => format!("run {r}"),
484            _ => "empty".to_owned(),
485        }
486    }
487}
488
489#[cfg(test)]
490mod tests {
491    use super::*;
492    use crate::config::SetupStep;
493
494    fn copy(spec: &str) -> SetupStep {
495        SetupStep {
496            copy: Some(spec.to_owned()),
497            ..Default::default()
498        }
499    }
500
501    fn run(cmd: &str) -> SetupStep {
502        SetupStep {
503            run: Some(cmd.to_owned()),
504            ..Default::default()
505        }
506    }
507
508    fn cfg(steps: Vec<SetupStep>) -> Config {
509        let mut c = Config::default();
510        c.worktree.setup = steps;
511        c.verify.shell = Some(vec!["sh".to_owned(), "-c".to_owned()]);
512        c
513    }
514
515    /// A repository with one commit and a detached linked worktree.
516    async fn scratch() -> (tempfile::TempDir, PathBuf, PathBuf) {
517        let tmp = tempfile::tempdir().unwrap();
518        let repo = tmp.path().join("repo");
519        std::fs::create_dir_all(&repo).unwrap();
520        for args in [
521            vec!["init", "-b", "main"],
522            vec!["config", "user.name", "t"],
523            vec!["config", "user.email", "t@example.com"],
524        ] {
525            git::git(&repo, &args).await.unwrap();
526        }
527        std::fs::write(repo.join("a.txt"), "a\n").unwrap();
528        git::git(&repo, &["add", "-A"]).await.unwrap();
529        git::git(&repo, &["commit", "-m", "init"]).await.unwrap();
530        let wt = tmp.path().join("wt");
531        git::worktree_add_detached(&repo, &wt, "HEAD")
532            .await
533            .unwrap();
534        // What `prep` and the other callers take before setup runs.
535        git::acquire_worktree_config(&repo).await.unwrap();
536        (tmp, repo, wt)
537    }
538    #[cfg(unix)]
539    #[tokio::test]
540    async fn isolated_setup_runs_under_the_existing_repository_operation() {
541        crate::run::pin_test_home();
542        let (_tmp, repo, wt) = scratch().await;
543        let mut config = cfg(vec![run("touch setup-completed")]);
544        config.verify.build_cache = crate::config::BuildCache::Isolated;
545        config.disk.min_free_bytes = 0;
546        config.coordination = Some(crate::config::Coordination {
547            contract_file: "fixture-contract".into(),
548            contract_token: "fixture-v1".into(),
549            lock_file: "fixture-lock".into(),
550        });
551        std::fs::write(repo.join(".git/fixture-contract"), "fixture-v1").unwrap();
552        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(3), || false);
553        let repository =
554            crate::repo_lock::SeatLease::operation_with(&repo, config.coordination.as_ref(), &wait)
555                .await
556                .unwrap()
557                .unwrap();
558        tokio::time::timeout(
559            Duration::from_secs(10),
560            prepare_with(
561                &config,
562                &repo,
563                &wt,
564                crate::build_target::Coordination::Held(Some(&repository)),
565            ),
566        )
567        .await
568        .expect("setup must not wait for its own repository operation")
569        .unwrap();
570        assert!(wt.join("setup-completed").is_file());
571    }
572
573    #[tokio::test]
574    async fn isolated_setup_reports_disk_admission_without_starting_the_command() {
575        crate::run::pin_test_home();
576        let (_tmp, repo, wt) = scratch().await;
577        let mut config = cfg(vec![run("touch setup-completed")]);
578        config.verify.build_cache = crate::config::BuildCache::Isolated;
579        config.disk.min_free_bytes = u64::MAX;
580        let error = prepare(&config, &repo, &wt).await.unwrap_err();
581        assert!(
582            error.is::<crate::build_target::AdmissionDiskWait>(),
583            "{error:#}"
584        );
585        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
586        assert!(!wt.join("setup-completed").exists());
587    }
588
589    #[tokio::test]
590    async fn default_is_a_no_op() {
591        let (_t, repo, wt) = scratch().await;
592        prepare(&Config::default(), &repo, &wt).await.unwrap();
593        assert!(withheld_paths(&wt).await.is_empty());
594    }
595
596    #[tokio::test]
597    async fn copy_then_run_in_order() {
598        let (_t, repo, wt) = scratch().await;
599        std::fs::write(repo.join(".env.example"), "KEY=1\n").unwrap();
600        let c = cfg(vec![
601            copy(".env.example -> .env"),
602            run("cat .env > seen.txt && echo ran >> seen.txt"),
603        ]);
604        prepare(&c, &repo, &wt).await.unwrap();
605        assert_eq!(
606            std::fs::read_to_string(wt.join("seen.txt")).unwrap(),
607            "KEY=1\nran\n"
608        );
609        let mut got = withheld_paths(&wt).await;
610        got.sort();
611        assert_eq!(got, [".env", "seen.txt"]);
612    }
613
614    #[tokio::test]
615    async fn a_failing_step_stops_and_names_step_and_output() {
616        let (_t, repo, wt) = scratch().await;
617        let c = cfg(vec![run("echo boom >&2; exit 3"), run("touch after.txt")]);
618        let err = format!("{:#}", prepare(&c, &repo, &wt).await.unwrap_err());
619        assert!(err.contains("step 1/2"), "{err}");
620        assert!(err.contains("boom"), "{err}");
621        assert!(!wt.join("after.txt").exists());
622    }
623
624    #[tokio::test]
625    async fn a_timeout_keeps_the_partial_output() {
626        let (_t, repo, wt) = scratch().await;
627        let mut step = run("echo partial; sleep 30");
628        step.timeout_secs = Some(1);
629        let err = format!(
630            "{:#}",
631            prepare(&cfg(vec![step]), &repo, &wt).await.unwrap_err()
632        );
633        assert!(err.contains("timed out"), "{err}");
634        assert!(err.contains("partial"), "{err}");
635    }
636
637    #[tokio::test]
638    async fn copy_never_overwrites() {
639        let (_t, repo, wt) = scratch().await;
640        std::fs::write(repo.join("src.txt"), "new\n").unwrap();
641        std::fs::write(wt.join("dst.txt"), "mine\n").unwrap();
642        prepare(&cfg(vec![copy("src.txt -> dst.txt")]), &repo, &wt)
643            .await
644            .unwrap();
645        assert_eq!(
646            std::fs::read_to_string(wt.join("dst.txt")).unwrap(),
647            "mine\n"
648        );
649    }
650
651    #[tokio::test]
652    async fn a_missing_source_is_an_error_unless_optional() {
653        let (_t, repo, wt) = scratch().await;
654        let err = format!(
655            "{:#}",
656            prepare(&cfg(vec![copy("nope")]), &repo, &wt)
657                .await
658                .unwrap_err()
659        );
660        assert!(err.contains("step 1/1") && err.contains("nope"), "{err}");
661        let mut opt = copy("nope");
662        opt.optional = true;
663        prepare(&cfg(vec![opt]), &repo, &wt).await.unwrap();
664        assert!(!wt.join("nope").exists());
665    }
666
667    #[tokio::test]
668    async fn setup_may_not_edit_tracked_files() {
669        let (_t, repo, wt) = scratch().await;
670        let err = format!(
671            "{:#}",
672            prepare(&cfg(vec![run("echo x >> a.txt")]), &repo, &wt)
673                .await
674                .unwrap_err()
675        );
676        assert!(err.contains("tracked") && err.contains("a.txt"), "{err}");
677    }
678
679    #[tokio::test]
680    async fn the_command_does_not_see_the_run_identity() {
681        let (_t, repo, wt) = scratch().await;
682        // Safe in a unit test: only this process reads them, via the child.
683        unsafe {
684            std::env::set_var("MAGI_RUN", "r1");
685            std::env::set_var("MAGI_NODE", "n1");
686        }
687        prepare(
688            &cfg(vec![run("echo \"[$MAGI_RUN][$MAGI_NODE]\" > ids.txt")]),
689            &repo,
690            &wt,
691        )
692        .await
693        .unwrap();
694        assert_eq!(
695            std::fs::read_to_string(wt.join("ids.txt")).unwrap(),
696            "[][]\n"
697        );
698    }
699
700    #[tokio::test]
701    async fn products_are_kept_out_of_both_commit_paths() {
702        let (_t, repo, wt) = scratch().await;
703        std::fs::write(repo.join("secret"), "s\n").unwrap();
704        prepare(&cfg(vec![copy("secret")]), &repo, &wt)
705            .await
706            .unwrap();
707
708        // Hidden from the agent's own `git add -A` ...
709        git::git(&wt, &["add", "-A"]).await.unwrap();
710        assert!(
711            git::git(&wt, &["diff", "--cached", "--name-only"])
712                .await
713                .unwrap()
714                .is_empty()
715        );
716
717        // ... and a rescue with only the product commits nothing.
718        assert!(!git::commit_all(&wt, "rescue").await.unwrap());
719        let r = git::rescue_commit(&wt, "rescue").await.unwrap();
720        assert!(!r.committed);
721
722        // Real work beside it is committed, the product is not.
723        std::fs::write(wt.join("work.txt"), "w\n").unwrap();
724        assert!(git::commit_all(&wt, "rescue").await.unwrap());
725        let files = git::git(&wt, &["show", "--name-only", "--format=", "HEAD"])
726            .await
727            .unwrap();
728        assert_eq!(files.trim(), "work.txt");
729    }
730
731    #[tokio::test]
732    async fn products_without_worktree_config_fail_loudly_and_leave_shared_config_alone() {
733        let (_t, repo, wt) = scratch().await;
734        git::release_worktree_config(&repo).await.unwrap();
735        std::fs::write(repo.join("secret"), "s\n").unwrap();
736        let err = format!(
737            "{:#}",
738            prepare(&cfg(vec![copy("secret")]), &repo, &wt)
739                .await
740                .unwrap_err()
741        );
742        assert!(err.contains("worktreeConfig"), "{err}");
743        let shared = git::git_raw(&repo, &["config", "--get", "core.excludesFile"])
744            .await
745            .unwrap();
746        assert!(!shared.ok(), "shared config was written: {}", shared.stdout);
747    }
748
749    #[tokio::test]
750    async fn an_ignored_copy_is_still_withheld_from_commits() {
751        let (_t, repo, wt) = scratch().await;
752        std::fs::write(wt.join(".gitignore"), ".env\n").unwrap();
753        git::git(&wt, &["add", ".gitignore"]).await.unwrap();
754        git::git(&wt, &["commit", "-m", "ignore"]).await.unwrap();
755        std::fs::write(repo.join(".env"), "s\n").unwrap();
756        prepare(&cfg(vec![copy(".env")]), &repo, &wt).await.unwrap();
757        assert_eq!(withheld_paths(&wt).await, [".env"]);
758        // The agent force-adds it, then magi rescues.
759        git::git(&wt, &["add", "-f", ".env"]).await.unwrap();
760        std::fs::write(wt.join("work.txt"), "w\n").unwrap();
761        assert!(git::commit_all(&wt, "rescue").await.unwrap());
762        let files = git::git(&wt, &["show", "--name-only", "--format=", "HEAD"])
763            .await
764            .unwrap();
765        assert_eq!(files.trim(), "work.txt");
766    }
767
768    #[test]
769    fn destinations_must_stay_inside() {
770        for bad in ["/etc/x", "../x", "a/../../x", ".git/hooks/x", "C:/x", ""] {
771            assert!(valid_destination(bad).is_err(), "{bad}");
772        }
773        assert!(valid_destination("a/b.env").is_ok());
774    }
775}