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::plan(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 plan = target
256        .map(|_| crate::build_target::command::plan(command))
257        .transpose()?;
258    let script = plan.as_ref().map_or(command, |plan| plan.script);
259    let dir = match plan.as_ref().and_then(|plan| plan.dir.as_deref()) {
260        Some(dir) => crate::build_target::command::resolve_dir(wt, dir)?,
261        None => wt.to_owned(),
262    };
263    static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
264    let log = std::env::temp_dir().join(format!(
265        "magi-setup-{}-{}.out",
266        std::process::id(),
267        SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
268    ));
269    if pre_clean {
270        tracing::info!(cwd = %wt.display(), output = %log.display(), command, "pre-clean command output (retained on interruption)");
271    }
272    let out = std::fs::File::create(&log).context("create output file")?;
273    let err = out.try_clone()?;
274    let mut cmd = tokio::process::Command::new(&shell[0]);
275    cmd.quiet();
276    cmd.args(&shell[1..])
277        .arg(script)
278        .current_dir(&dir)
279        .env_remove("MAGI_RUN")
280        .env_remove("MAGI_NODE")
281        .env_remove(crate::build_id::EXPECT_ENV)
282        .stdin(std::process::Stdio::null())
283        .stdout(out)
284        .stderr(err)
285        .kill_on_drop(true);
286    crate::chat_control::bridge::clear_environment(&mut cmd);
287    if pre_clean {
288        cmd.env("MAGI_PRE_CLEAN_ACTIVE", "1");
289        for key in crate::worker::INVOCATION_ENV {
290            cmd.env_remove(key);
291        }
292    }
293    crate::incremental::configure(&mut cmd, wt)?;
294    let spawn = if let Some((target, _)) = target {
295        crate::build_target::command::configure(&mut cmd, target)?;
296        crate::seat_process::Running::spawn_build
297    } else {
298        crate::build_target::command::clear(&mut cmd)?;
299        crate::seat_process::Running::spawn_operation
300    };
301    let mut running = spawn(cmd, lease, outputs)
302        .with_context(|| format!("spawn `{}` for `{command}`", shell[0]))?;
303    let pressure = async {
304        match target {
305            Some((target, floor)) => {
306                crate::retention::emergency(vec![wt.to_owned(), target.to_owned()], floor, true)
307                    .await
308            }
309            None => std::future::pending().await,
310        }
311    };
312    let waited = tokio::select! {
313        waited = tokio::time::timeout(timeout, running.child().wait()) => waited,
314        reason = pressure => {
315            running.finish().await;
316            std::fs::remove_file(&log).ok();
317            return Err(crate::repo_lock::ResourceBlocked(reason).into());
318        }
319    };
320    // Compiler wrappers supervise their own process groups. Join cleanup of
321    // the entire setup tree before returning, on success as well as timeout.
322    // Cancellation transfers the same ownership to Running's cleanup thread.
323    running.finish().await;
324    let body = || {
325        use std::io::{Read, Seek, SeekFrom};
326        let mut bytes = Vec::new();
327        if let Ok(mut f) = std::fs::File::open(&log) {
328            let _ = f.seek(SeekFrom::End(-(TAIL as i64)));
329            let _ = f.take(TAIL as u64).read_to_end(&mut bytes);
330        }
331        tail(&String::from_utf8_lossy(&bytes)).to_owned()
332    };
333    let result = match waited {
334        Ok(Ok(status)) if status.success() => Ok(()),
335        Ok(Ok(status)) => Err(anyhow::anyhow!(
336            "`{command}` exited with {status}\n{}",
337            body()
338        )),
339        Ok(Err(e)) => Err(anyhow::anyhow!("`{command}` could not be awaited: {e}")),
340        Err(_) => Err(anyhow::anyhow!(
341            "`{command}` timed out after {}s\n{}",
342            timeout.as_secs(),
343            body()
344        )),
345    };
346    std::fs::remove_file(&log).ok();
347    result
348}
349
350async fn git_dir(wt: &Path) -> Result<PathBuf> {
351    Ok(PathBuf::from(
352        git::git(wt, &["rev-parse", "--absolute-git-dir"])
353            .await?
354            .trim(),
355    ))
356}
357
358/// Paths a worktree's setup recorded, relative to it. Empty when none.
359pub async fn withheld_paths(wt: &Path) -> Vec<String> {
360    let Ok(dir) = git_dir(wt).await else {
361        return Vec::new();
362    };
363    let Ok(raw) = tokio::fs::read(dir.join(RECORD)).await else {
364        return Vec::new();
365    };
366    raw.split(|b| *b == 0)
367        .filter(|p| !p.is_empty())
368        .map(|p| String::from_utf8_lossy(p).into_owned())
369        .collect()
370}
371
372/// Unstage whatever setup produced, so a rescue commit never carries it.
373pub async fn unstage_products(wt: &Path) -> Result<()> {
374    let paths = withheld_paths(wt).await;
375    if paths.is_empty() {
376        return Ok(());
377    }
378    let mut args = vec!["reset", "-q", "--"];
379    args.extend(paths.iter().map(String::as_str));
380    git::git(wt, &args).await.map(|_| ())
381}
382
383/// After the steps: refuse tracked edits, record the untracked products and
384/// hide them from `git add`.
385async fn seal(wt: &Path, copied: &[String]) -> Result<()> {
386    let tracked = git::git(wt, &["diff", "--name-only", "HEAD"]).await?;
387    if !tracked.trim().is_empty() {
388        bail!(
389            "setup must not change tracked files (every seat would carry the same diff), \
390             but it changed:\n{}",
391            tail(&tracked)
392        );
393    }
394    let out = git::git(wt, &["ls-files", "-z", "--others", "--exclude-standard"]).await?;
395    let mut paths: Vec<String> = withheld_paths(wt).await;
396    // Copied files are recorded even when `.gitignore` hides them from
397    // `--exclude-standard`: a later `git add -f` or an edited ignore rule must
398    // still not carry them into a commit.
399    for p in copied
400        .iter()
401        .map(String::as_str)
402        .chain(out.split('\0').filter(|p| !p.is_empty()))
403    {
404        if !paths.iter().any(|q| q == p) {
405            paths.push(p.to_owned());
406        }
407    }
408    if paths.is_empty() {
409        return Ok(());
410    }
411    let dir = git_dir(wt).await?;
412    let mut raw = Vec::new();
413    for p in &paths {
414        raw.extend_from_slice(p.as_bytes());
415        raw.push(0);
416    }
417    tokio::fs::write(dir.join(RECORD), raw).await?;
418    hide(wt, &dir, &paths).await
419}
420
421fn exclude_line(p: &str) -> String {
422    let mut s = String::from("/");
423    for c in p.chars() {
424        if matches!(c, '*' | '?' | '[' | ']' | '\\' | '#' | '!' | ' ') {
425            s.push('\\');
426        }
427        s.push(c);
428    }
429    s
430}
431
432/// Point this worktree's `core.excludesFile` at its products, keeping the
433/// user's own excludes. Needs `extensions.worktreeConfig`, which the caller
434/// takes with `git::acquire_worktree_config`; without it `--worktree` would
435/// write the shared config and change the operator's checkout, so that is a
436/// loud failure, never a fallback.
437async fn hide(wt: &Path, dir: &Path, paths: &[String]) -> Result<()> {
438    let ext = git::git_raw(wt, &["config", "--get", "extensions.worktreeConfig"]).await?;
439    if !(ext.ok() && ext.stdout.trim() == "true") {
440        bail!(
441            "setup left untracked files ({}) but extensions.worktreeConfig is off, so they \
442             cannot be hidden from `git add` per worktree",
443            paths.join(", ")
444        );
445    }
446    let file = dir.join(EXCLUDE);
447    let file_s = file.to_string_lossy().replace('\\', "/");
448    let current = git::git_raw(wt, &["config", "--get", "core.excludesFile"])
449        .await
450        .ok()
451        .filter(|o| o.ok())
452        .map(|o| o.stdout.trim().to_owned())
453        .filter(|s| !s.is_empty());
454    let mut body = match current {
455        Some(c) if c == file_s => std::fs::read_to_string(&file).unwrap_or_default(),
456        Some(c) => {
457            let c = match c.strip_prefix("~/") {
458                Some(rest) => std::env::var_os("HOME")
459                    .map(|h| PathBuf::from(h).join(rest))
460                    .unwrap_or_else(|| PathBuf::from(&c)),
461                None => PathBuf::from(&c),
462            };
463            std::fs::read_to_string(c).unwrap_or_default()
464        }
465        None => String::new(),
466    };
467    if !body.is_empty() && !body.ends_with('\n') {
468        body.push('\n');
469    }
470    for p in paths {
471        let line = exclude_line(p);
472        if !body.lines().any(|l| l == line) {
473            body.push_str(&line);
474            body.push('\n');
475        }
476    }
477    std::fs::write(&file, body).with_context(|| format!("write {}", file.display()))?;
478    git::git(wt, &["config", "--worktree", "core.excludesFile", &file_s])
479        .await
480        .map(|_| ())
481}
482
483impl SetupStep {
484    /// One-line description for errors.
485    pub fn describe(&self) -> String {
486        match (&self.copy, &self.run) {
487            (Some(c), _) => format!("copy {c}"),
488            (_, Some(r)) => format!("run {r}"),
489            _ => "empty".to_owned(),
490        }
491    }
492}
493
494#[cfg(test)]
495mod tests {
496    use super::*;
497    use crate::config::SetupStep;
498
499    fn copy(spec: &str) -> SetupStep {
500        SetupStep {
501            copy: Some(spec.to_owned()),
502            ..Default::default()
503        }
504    }
505
506    fn run(cmd: &str) -> SetupStep {
507        SetupStep {
508            run: Some(cmd.to_owned()),
509            ..Default::default()
510        }
511    }
512
513    fn cfg(steps: Vec<SetupStep>) -> Config {
514        let mut c = Config::default();
515        c.worktree.setup = steps;
516        c.verify.shell = Some(vec!["sh".to_owned(), "-c".to_owned()]);
517        c
518    }
519
520    /// A repository with one commit and a detached linked worktree.
521    async fn scratch() -> (tempfile::TempDir, PathBuf, PathBuf) {
522        let tmp = tempfile::tempdir().unwrap();
523        let repo = tmp.path().join("repo");
524        std::fs::create_dir_all(&repo).unwrap();
525        for args in [
526            vec!["init", "-b", "main"],
527            vec!["config", "user.name", "t"],
528            vec!["config", "user.email", "t@example.com"],
529        ] {
530            git::git(&repo, &args).await.unwrap();
531        }
532        std::fs::write(repo.join("a.txt"), "a\n").unwrap();
533        git::git(&repo, &["add", "-A"]).await.unwrap();
534        git::git(&repo, &["commit", "-m", "init"]).await.unwrap();
535        let wt = tmp.path().join("wt");
536        git::worktree_add_detached(&repo, &wt, "HEAD")
537            .await
538            .unwrap();
539        // What `prep` and the other callers take before setup runs.
540        git::acquire_worktree_config(&repo).await.unwrap();
541        (tmp, repo, wt)
542    }
543    #[cfg(unix)]
544    #[tokio::test]
545    async fn isolated_setup_runs_under_the_existing_repository_operation() {
546        crate::run::pin_test_home();
547        let (_tmp, repo, wt) = scratch().await;
548        let mut config = cfg(vec![run("touch setup-completed")]);
549        config.verify.build_cache = crate::config::BuildCache::Isolated;
550        config.disk.min_free_bytes = 0;
551        config.coordination = Some(crate::config::Coordination {
552            contract_file: "fixture-contract".into(),
553            contract_token: "fixture-v1".into(),
554            lock_file: "fixture-lock".into(),
555        });
556        std::fs::write(repo.join(".git/fixture-contract"), "fixture-v1").unwrap();
557        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(3), || false);
558        let repository =
559            crate::repo_lock::SeatLease::operation_with(&repo, config.coordination.as_ref(), &wait)
560                .await
561                .unwrap()
562                .unwrap();
563        tokio::time::timeout(
564            Duration::from_secs(10),
565            prepare_with(
566                &config,
567                &repo,
568                &wt,
569                crate::build_target::Coordination::Held(Some(&repository)),
570            ),
571        )
572        .await
573        .expect("setup must not wait for its own repository operation")
574        .unwrap();
575        assert!(wt.join("setup-completed").is_file());
576    }
577
578    #[tokio::test]
579    async fn isolated_setup_reports_disk_admission_without_starting_the_command() {
580        crate::run::pin_test_home();
581        let (_tmp, repo, wt) = scratch().await;
582        let mut config = cfg(vec![run("touch setup-completed")]);
583        config.verify.build_cache = crate::config::BuildCache::Isolated;
584        config.disk.min_free_bytes = u64::MAX;
585        let error = prepare(&config, &repo, &wt).await.unwrap_err();
586        assert!(
587            error.is::<crate::build_target::AdmissionDiskWait>(),
588            "{error:#}"
589        );
590        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
591        assert!(!wt.join("setup-completed").exists());
592    }
593
594    #[tokio::test]
595    async fn default_is_a_no_op() {
596        let (_t, repo, wt) = scratch().await;
597        prepare(&Config::default(), &repo, &wt).await.unwrap();
598        assert!(withheld_paths(&wt).await.is_empty());
599    }
600
601    #[tokio::test]
602    async fn copy_then_run_in_order() {
603        let (_t, repo, wt) = scratch().await;
604        std::fs::write(repo.join(".env.example"), "KEY=1\n").unwrap();
605        let c = cfg(vec![
606            copy(".env.example -> .env"),
607            run("cat .env > seen.txt && echo ran >> seen.txt"),
608        ]);
609        prepare(&c, &repo, &wt).await.unwrap();
610        assert_eq!(
611            std::fs::read_to_string(wt.join("seen.txt")).unwrap(),
612            "KEY=1\nran\n"
613        );
614        let mut got = withheld_paths(&wt).await;
615        got.sort();
616        assert_eq!(got, [".env", "seen.txt"]);
617    }
618
619    #[tokio::test]
620    async fn a_failing_step_stops_and_names_step_and_output() {
621        let (_t, repo, wt) = scratch().await;
622        let c = cfg(vec![run("echo boom >&2; exit 3"), run("touch after.txt")]);
623        let err = format!("{:#}", prepare(&c, &repo, &wt).await.unwrap_err());
624        assert!(err.contains("step 1/2"), "{err}");
625        assert!(err.contains("boom"), "{err}");
626        assert!(!wt.join("after.txt").exists());
627    }
628
629    #[tokio::test]
630    async fn a_timeout_keeps_the_partial_output() {
631        let (_t, repo, wt) = scratch().await;
632        let mut step = run("echo partial; sleep 30");
633        step.timeout_secs = Some(1);
634        let err = format!(
635            "{:#}",
636            prepare(&cfg(vec![step]), &repo, &wt).await.unwrap_err()
637        );
638        assert!(err.contains("timed out"), "{err}");
639        assert!(err.contains("partial"), "{err}");
640    }
641
642    #[tokio::test]
643    async fn copy_never_overwrites() {
644        let (_t, repo, wt) = scratch().await;
645        std::fs::write(repo.join("src.txt"), "new\n").unwrap();
646        std::fs::write(wt.join("dst.txt"), "mine\n").unwrap();
647        prepare(&cfg(vec![copy("src.txt -> dst.txt")]), &repo, &wt)
648            .await
649            .unwrap();
650        assert_eq!(
651            std::fs::read_to_string(wt.join("dst.txt")).unwrap(),
652            "mine\n"
653        );
654    }
655
656    #[tokio::test]
657    async fn a_missing_source_is_an_error_unless_optional() {
658        let (_t, repo, wt) = scratch().await;
659        let err = format!(
660            "{:#}",
661            prepare(&cfg(vec![copy("nope")]), &repo, &wt)
662                .await
663                .unwrap_err()
664        );
665        assert!(err.contains("step 1/1") && err.contains("nope"), "{err}");
666        let mut opt = copy("nope");
667        opt.optional = true;
668        prepare(&cfg(vec![opt]), &repo, &wt).await.unwrap();
669        assert!(!wt.join("nope").exists());
670    }
671
672    #[tokio::test]
673    async fn setup_may_not_edit_tracked_files() {
674        let (_t, repo, wt) = scratch().await;
675        let err = format!(
676            "{:#}",
677            prepare(&cfg(vec![run("echo x >> a.txt")]), &repo, &wt)
678                .await
679                .unwrap_err()
680        );
681        assert!(err.contains("tracked") && err.contains("a.txt"), "{err}");
682    }
683
684    #[tokio::test]
685    async fn the_command_does_not_see_the_run_identity() {
686        let (_t, repo, wt) = scratch().await;
687        // Safe in a unit test: only this process reads them, via the child.
688        unsafe {
689            std::env::set_var("MAGI_RUN", "r1");
690            std::env::set_var("MAGI_NODE", "n1");
691        }
692        prepare(
693            &cfg(vec![run("echo \"[$MAGI_RUN][$MAGI_NODE]\" > ids.txt")]),
694            &repo,
695            &wt,
696        )
697        .await
698        .unwrap();
699        assert_eq!(
700            std::fs::read_to_string(wt.join("ids.txt")).unwrap(),
701            "[][]\n"
702        );
703    }
704
705    #[tokio::test]
706    async fn products_are_kept_out_of_both_commit_paths() {
707        let (_t, repo, wt) = scratch().await;
708        std::fs::write(repo.join("secret"), "s\n").unwrap();
709        prepare(&cfg(vec![copy("secret")]), &repo, &wt)
710            .await
711            .unwrap();
712
713        // Hidden from the agent's own `git add -A` ...
714        git::git(&wt, &["add", "-A"]).await.unwrap();
715        assert!(
716            git::git(&wt, &["diff", "--cached", "--name-only"])
717                .await
718                .unwrap()
719                .is_empty()
720        );
721
722        // ... and a rescue with only the product commits nothing.
723        assert!(!git::commit_all(&wt, "rescue").await.unwrap());
724        let r = git::rescue_commit(&wt, "rescue").await.unwrap();
725        assert!(!r.committed);
726
727        // Real work beside it is committed, the product is not.
728        std::fs::write(wt.join("work.txt"), "w\n").unwrap();
729        assert!(git::commit_all(&wt, "rescue").await.unwrap());
730        let files = git::git(&wt, &["show", "--name-only", "--format=", "HEAD"])
731            .await
732            .unwrap();
733        assert_eq!(files.trim(), "work.txt");
734    }
735
736    #[tokio::test]
737    async fn products_without_worktree_config_fail_loudly_and_leave_shared_config_alone() {
738        let (_t, repo, wt) = scratch().await;
739        git::release_worktree_config(&repo).await.unwrap();
740        std::fs::write(repo.join("secret"), "s\n").unwrap();
741        let err = format!(
742            "{:#}",
743            prepare(&cfg(vec![copy("secret")]), &repo, &wt)
744                .await
745                .unwrap_err()
746        );
747        assert!(err.contains("worktreeConfig"), "{err}");
748        let shared = git::git_raw(&repo, &["config", "--get", "core.excludesFile"])
749            .await
750            .unwrap();
751        assert!(!shared.ok(), "shared config was written: {}", shared.stdout);
752    }
753
754    #[tokio::test]
755    async fn an_ignored_copy_is_still_withheld_from_commits() {
756        let (_t, repo, wt) = scratch().await;
757        std::fs::write(wt.join(".gitignore"), ".env\n").unwrap();
758        git::git(&wt, &["add", ".gitignore"]).await.unwrap();
759        git::git(&wt, &["commit", "-m", "ignore"]).await.unwrap();
760        std::fs::write(repo.join(".env"), "s\n").unwrap();
761        prepare(&cfg(vec![copy(".env")]), &repo, &wt).await.unwrap();
762        assert_eq!(withheld_paths(&wt).await, [".env"]);
763        // The agent force-adds it, then magi rescues.
764        git::git(&wt, &["add", "-f", ".env"]).await.unwrap();
765        std::fs::write(wt.join("work.txt"), "w\n").unwrap();
766        assert!(git::commit_all(&wt, "rescue").await.unwrap());
767        let files = git::git(&wt, &["show", "--name-only", "--format=", "HEAD"])
768            .await
769            .unwrap();
770        assert_eq!(files.trim(), "work.txt");
771    }
772
773    #[test]
774    fn destinations_must_stay_inside() {
775        for bad in ["/etc/x", "../x", "a/../../x", ".git/hooks/x", "C:/x", ""] {
776            assert!(valid_destination(bad).is_err(), "{bad}");
777        }
778        assert!(valid_destination("a/b.env").is_ok());
779    }
780}