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