Skip to main content

supercov_engine/
workspace.rs

1//! Isolated project snapshots and crash-recoverable stable build cache.
2
3use std::{
4    collections::{BTreeMap, BTreeSet},
5    fs::{self, OpenOptions},
6    io::{self, Write},
7    path::{Component, Path, PathBuf},
8    sync::atomic::{AtomicU64, Ordering},
9    time::{SystemTime, UNIX_EPOCH},
10};
11
12use serde::Serialize;
13use sha2::{Digest, Sha256};
14
15use crate::lifecycle::{LifecycleError, ProjectLock, atomic_rename, remove_stored_tree_deferred};
16
17const WORKSPACE_MARKER: &str = ".supercov-workspace-store";
18const WORKSPACE_MARKER_CONTENTS: &[u8] = b"Supercov instrumented workspace. Safe to delete.\n";
19const ROOT_EXCLUSIONS: &[&str] = &[
20    ".cache",
21    ".git",
22    ".supercov",
23    ".mcdc-pool",
24    "node_modules",
25    "build",
26    "dist",
27    ".next",
28    ".nuxt",
29    ".output",
30    "coverage",
31    "playwright-report",
32    "test-results",
33    "target",
34];
35const NESTED_EXCLUSIONS: &[&str] = &[".supercov", ".mcdc-pool"];
36
37/// Whether the copy uses a virtual environment of the project's own, linked
38/// in rather than copied: what the command does to it, it does to the
39/// project's. Read to the depth a project keeps one at -- `.venv`, or a
40/// service's `api/.venv`.
41pub fn links_a_virtual_environment(workspace: &Path) -> bool {
42    fn search(directory: &Path, depth: usize) -> bool {
43        let Ok(entries) = fs::read_dir(directory) else {
44            return false;
45        };
46        entries.filter_map(Result::ok).any(|entry| {
47            let path = entry.path();
48            let name = entry.file_name();
49            let Ok(metadata) = fs::symlink_metadata(&path) else {
50                return false;
51            };
52            if metadata.file_type().is_symlink() {
53                return path.join("pyvenv.cfg").is_file();
54            }
55            depth > 0
56                && metadata.is_dir()
57                && name != "node_modules"
58                && name != ".supercov"
59                && name != ".git"
60                && search(&path, depth - 1)
61        })
62    }
63    search(workspace, 2)
64}
65static UNIQUE: AtomicU64 = AtomicU64::new(0);
66
67#[derive(Debug)]
68pub enum WorkspaceError {
69    Io { path: PathBuf, source: io::Error },
70    UnsafePath(PathBuf),
71    UnsupportedEntry(PathBuf),
72    MissingLock,
73    Lifecycle(LifecycleError),
74    UnsupportedPlatform(&'static str),
75}
76
77impl std::fmt::Display for WorkspaceError {
78    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        match self {
80            Self::Io { path, source } => write!(formatter, "{}: {source}", path.display()),
81            Self::UnsafePath(path) => {
82                write!(formatter, "unsafe workspace path: {}", path.display())
83            }
84            Self::UnsupportedEntry(path) => {
85                write!(
86                    formatter,
87                    "unsupported filesystem entry in isolated project: {}",
88                    path.display()
89                )
90            }
91            Self::MissingLock => write!(
92                formatter,
93                "isolated workspace preparation requires the active project lock"
94            ),
95            Self::Lifecycle(error) => write!(formatter, "{error}"),
96            Self::UnsupportedPlatform(reason) => {
97                write!(formatter, "unsupported workspace platform: {reason}")
98            }
99        }
100    }
101}
102
103impl std::error::Error for WorkspaceError {}
104
105impl From<LifecycleError> for WorkspaceError {
106    fn from(value: LifecycleError) -> Self {
107        Self::Lifecycle(value)
108    }
109}
110
111/// Leftover tool state -- a Chrome test profile linking into /tmp was the
112/// field case -- must not abort measurement. The mirror omits the entry:
113/// nothing outside the project is ever followed, and a test that truly needs
114/// the link fails visibly inside the workspace with this line as the cause.
115fn omit_escaping_link(path: &Path, target: &Path) {
116    eprintln!(
117        "[supercov] omitting symlink outside the isolated project: {} -> {}",
118        path.display(),
119        target.display()
120    );
121}
122
123/// `fs::canonicalize` on Windows returns a verbatim path -- `\\?\C:\...` or
124/// `\\?\UNC\server\share\...` -- and that prefix does not survive contact with
125/// anything else: Node's pathToFileURL reads `?` as a UNC host, `Path::starts_with`
126/// treats `\\?\C:\` and `C:\` as different prefixes so containment checks
127/// misjudge every link, and the prefix shows up in every diagnostic. Canonical
128/// paths are simplified back to the ordinary form at the one place they are
129/// made, so nothing downstream ever sees the verbatim spelling.
130pub(crate) fn canonicalize_simplified<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
131    fs::canonicalize(path).map(simplified)
132}
133
134#[cfg(windows)]
135pub(crate) fn simplified(path: PathBuf) -> PathBuf {
136    match path.to_str().and_then(strip_verbatim) {
137        Some(plain) => PathBuf::from(plain),
138        None => path,
139    }
140}
141
142#[cfg(not(windows))]
143pub(crate) fn simplified(path: PathBuf) -> PathBuf {
144    path
145}
146
147/// The pure string half, kept host-independent so it can be tested anywhere:
148/// `\\?\C:\a` -> `C:\a`, `\\?\UNC\srv\share\a` -> `\\srv\share\a`, and `None`
149/// for a path that carries no verbatim prefix.
150#[cfg_attr(not(windows), allow(dead_code))]
151pub(crate) fn strip_verbatim(path: &str) -> Option<String> {
152    let rest = path.strip_prefix(r"\\?\")?;
153    if let Some(unc) = rest.strip_prefix(r"UNC\") {
154        return Some(format!(r"\\{unc}"));
155    }
156    let mut chars = rest.chars();
157    let drive = chars.next()?;
158    if drive.is_ascii_alphabetic() && chars.next() == Some(':') {
159        return Some(rest.to_owned());
160    }
161    None
162}
163
164/// The `file://` URL for an absolute path, the way Node's `pathToFileURL`
165/// derives it. Node takes a bare `--import=C:\...` for a URL with scheme `c:`
166/// and refuses it -- ERR_UNSUPPORTED_ESM_URL_SCHEME -- while `/abs/path` has no
167/// colon and passes, which is why every POSIX run worked and every Windows run
168/// died in the first Node child. Windows paths reach here already simplified
169/// (no `\\?\`); `\` becomes `/`, a drive path becomes `file:///C:/...`, a UNC
170/// path `file://server/share/...`, and every byte outside the URL-safe set is
171/// percent-encoded so a space or a `#` in a temp directory cannot break it.
172pub(crate) fn file_url(path: &Path) -> String {
173    let text = path.to_string_lossy();
174    #[cfg(windows)]
175    let text = text.replace('\\', "/");
176    file_url_from_slash_path(&text)
177}
178
179/// The pure half: `slash_path` uses `/` separators on every host.
180pub(crate) fn file_url_from_slash_path(slash_path: &str) -> String {
181    let mut url = String::from("file://");
182    let mut rest = slash_path;
183    if let Some(unc) = rest.strip_prefix("//") {
184        // `//server/share/dir` -> `file://server/share/dir`: the host is the server.
185        let (host, tail) = unc.split_once('/').unwrap_or((unc, ""));
186        url.push_str(host);
187        rest = tail;
188        url.push('/');
189    } else if !rest.starts_with('/') {
190        // A drive path such as `C:/dir`.
191        url.push('/');
192    }
193    for byte in rest.bytes() {
194        let keep =
195            byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~' | b'/' | b':');
196        if keep {
197            url.push(byte as char);
198        } else {
199            url.push_str(&format!("%{byte:02X}"));
200        }
201    }
202    url
203}
204
205fn io_error(path: &Path, source: io::Error) -> WorkspaceError {
206    WorkspaceError::Io {
207        path: path.to_owned(),
208        source,
209    }
210}
211
212fn unique() -> String {
213    let nanos = SystemTime::now()
214        .duration_since(UNIX_EPOCH)
215        .unwrap_or_default()
216        .as_nanos();
217    format!(
218        "{}-{nanos}-{}",
219        std::process::id(),
220        UNIQUE.fetch_add(1, Ordering::Relaxed)
221    )
222}
223
224fn project_name(root: &Path) -> Result<&std::ffi::OsStr, WorkspaceError> {
225    root.file_name()
226        .ok_or_else(|| WorkspaceError::UnsafePath(root.into()))
227}
228
229/// The git repository a project is a directory of, when it is not the
230/// repository itself: a package in a monorepo. None for a project inside one
231/// of Supercov's own copies, which is never laid out again.
232fn enclosing_repository(root: &Path) -> Option<&Path> {
233    let repository = root
234        .ancestors()
235        .skip(1)
236        .find(|directory| directory.join(".git").exists())?;
237    let relative = root.strip_prefix(repository).ok()?;
238    if relative
239        .components()
240        .any(|component| component.as_os_str() == ".supercov")
241    {
242        return None;
243    }
244    Some(repository)
245}
246
247/// Where in a copy directory the project's copy sits: under its own name, or,
248/// for a package of a repository, at its path in the repository, so that
249/// what its suite reaches as `../` is where it is in the checkout.
250fn copy_layout(root: &Path) -> Result<PathBuf, WorkspaceError> {
251    let Some(repository) = enclosing_repository(root) else {
252        return Ok(PathBuf::from(project_name(root)?));
253    };
254    let name = repository
255        .file_name()
256        .ok_or_else(|| WorkspaceError::UnsafePath(repository.into()))?;
257    let relative = root
258        .strip_prefix(repository)
259        .map_err(|_| WorkspaceError::UnsafePath(root.into()))?;
260    Ok(Path::new(name).join(relative))
261}
262
263/// Around a package's copy, the rest of its repository: each directory on
264/// the way up holds links to its entries in the checkout. A Playwright
265/// `webServer` running `go run ../cmd/testserver`, or a tsconfig extending
266/// `../../tsconfig.base.json`, found nothing beside a copy of the package
267/// alone. Only the package is copied: what lies outside it is the checkout's,
268/// as when the suite runs there, and `.git` is never shared. Best effort.
269fn link_repository_around(root: &Path, workspace: &Path) {
270    let Some(repository) = enclosing_repository(root) else {
271        return;
272    };
273    let (mut real, mut copy) = (root, workspace);
274    while real != repository {
275        let (Some(real_parent), Some(copy_parent)) = (real.parent(), copy.parent()) else {
276            return;
277        };
278        let Ok(entries) = fs::read_dir(real_parent) else {
279            return;
280        };
281        for entry in entries.filter_map(Result::ok) {
282            let name = entry.file_name();
283            // A lockfile is never reached as `../`, and a tool that takes the
284            // topmost one as the root (Next.js) found the repository's twice,
285            // beside the copy and in the checkout above `.supercov`, and
286            // warned of a second lockfile the run alone had.
287            if Some(name.as_os_str()) == real.file_name()
288                || matches!(
289                    name.to_str(),
290                    Some(
291                        ".git"
292                            | ".supercov"
293                            | "package-lock.json"
294                            | "npm-shrinkwrap.json"
295                            | "yarn.lock"
296                            | "pnpm-lock.yaml"
297                            | "bun.lock"
298                            | "bun.lockb"
299                    )
300                )
301            {
302                continue;
303            }
304            let destination = copy_parent.join(&name);
305            if fs::symlink_metadata(&destination).is_ok() {
306                continue;
307            }
308            let target = entry.path();
309            let directory = fs::metadata(&target).is_ok_and(|metadata| metadata.is_dir());
310            // Windows: a file link needs a privilege a junction does not.
311            if create_link(&target, &destination, directory).is_err() && !directory {
312                let _ = fs::copy(&target, &destination);
313            }
314        }
315        (real, copy) = (real_parent, copy_parent);
316    }
317}
318
319pub fn workspace_container(root: &Path) -> PathBuf {
320    // Everything Supercov keeps in a project lives under .supercov: one
321    // directory to gitignore, one directory to delete. Users interact with
322    // their real files and the CLI; command outputs sync back after every
323    // run, so nothing in the container is ever theirs to fetch.
324    let preferred = root.join(".supercov/workspaces");
325    if fs::symlink_metadata(&preferred).is_err() || owned_workspace_path(&preferred) {
326        return preferred;
327    }
328    let digest = format!("{:x}", Sha256::digest(root.as_os_str().as_encoded_bytes()));
329    for sequence in 0..1_024usize {
330        let name = if sequence == 0 {
331            format!(".supercov/workspaces-{}", &digest[..16])
332        } else {
333            format!(".supercov/workspaces-{}-{sequence}", &digest[..16])
334        };
335        let candidate = root.join(name);
336        if fs::symlink_metadata(&candidate).is_err() || owned_workspace_path(&candidate) {
337            return candidate;
338        }
339    }
340    root.join(format!(".supercov/workspaces-{}-overflow", &digest[..16]))
341}
342
343/// A Cargo configuration in one of Supercov's own directories above the
344/// isolated copy of `root`. Cargo reads `.cargo/config.toml` from every
345/// ancestor of where it builds, so one there would change how the copy
346/// builds -- `[env]`, a runner, an alias -- while the project's own `cargo
347/// test` never sees it. The project's own `.cargo`, and those above the
348/// project, apply to both and are not Supercov's to judge.
349pub fn planted_cargo_configuration(root: &Path, workspace: &Path) -> Option<PathBuf> {
350    if !workspace.starts_with(root) {
351        return None;
352    }
353    // A repository's own, linked around a package's copy, applies to the
354    // checkout too.
355    let repository = enclosing_repository(root).and_then(|path| canonicalize_simplified(path).ok());
356    workspace
357        .ancestors()
358        .skip(1)
359        .take_while(|directory| *directory != root)
360        .map(|directory| directory.join(".cargo"))
361        .filter(|path| fs::symlink_metadata(path).is_ok())
362        .find(|path| {
363            repository.as_ref().is_none_or(|repository| {
364                !canonicalize_simplified(path).is_ok_and(|real| real.starts_with(repository))
365            })
366        })
367}
368
369/// The directory, in the container, that holds a copy of the project:
370/// `workspace` for the first, the one a run alone takes, and `workspace-2`
371/// for the one a run takes while the first is in use.
372fn copy_directory_name(copy: usize) -> String {
373    if copy <= 1 {
374        "workspace".into()
375    } else {
376        format!("workspace-{copy}")
377    }
378}
379
380/// Everything in the container that belongs to one copy: the copy, and the
381/// view of the author's source kept beside it.
382pub(crate) fn copy_directories(container: &Path, copy: usize) -> [PathBuf; 2] {
383    let name = copy_directory_name(copy);
384    [
385        container.join(&name),
386        container.join(name.replacen("workspace", "source", 1)),
387    ]
388}
389
390/// Where the copy a run holds is.
391pub fn cached_workspace_path(root: &Path, lock: &ProjectLock) -> Result<PathBuf, WorkspaceError> {
392    copy_path(root, lock.copy())
393}
394
395/// Where one of the project's copies is, by its number.
396pub fn copy_path(root: &Path, copy: usize) -> Result<PathBuf, WorkspaceError> {
397    Ok(workspace_container(root)
398        .join(copy_directory_name(copy))
399        .join(copy_layout(root)?))
400}
401
402pub fn isolated_workspace_path(root: &Path, run_id: &str) -> Result<PathBuf, WorkspaceError> {
403    if run_id.is_empty()
404        || run_id == "."
405        || run_id == ".."
406        || run_id
407            .chars()
408            .any(|character| matches!(character, '/' | '\\' | '\0') || character.is_control())
409    {
410        return Err(WorkspaceError::UnsafePath(PathBuf::from(run_id)));
411    }
412    Ok(workspace_container(root)
413        .join("work")
414        .join(run_id)
415        .join(copy_layout(root)?))
416}
417
418pub(crate) fn owned_workspace_path(path: &Path) -> bool {
419    fs::symlink_metadata(path).is_ok_and(|metadata| metadata.file_type().is_dir())
420        && fs::symlink_metadata(path.join(WORKSPACE_MARKER))
421            .is_ok_and(|metadata| metadata.file_type().is_file())
422        && fs::read(path.join(WORKSPACE_MARKER))
423            .is_ok_and(|contents| contents == WORKSPACE_MARKER_CONTENTS)
424}
425
426fn ensure_container(root: &Path) -> Result<PathBuf, WorkspaceError> {
427    let container = workspace_container(root);
428    let mut created = false;
429    match fs::symlink_metadata(&container) {
430        Ok(metadata) if !metadata.file_type().is_dir() => {
431            return Err(WorkspaceError::UnsafePath(container));
432        }
433        Ok(_) => {}
434        Err(error) if error.kind() == io::ErrorKind::NotFound => {
435            let store = container.parent().expect("container parent");
436            fs::create_dir_all(store).map_err(|source| io_error(store, source))?;
437            // One directory covers everything Supercov writes; make Git
438            // ignore it without the user touching their own .gitignore.
439            let store_ignore = root.join(".supercov/.gitignore");
440            if fs::symlink_metadata(&store_ignore).is_err() {
441                let _ = fs::write(&store_ignore, b"*\n");
442            }
443            // Made complete and then named, in one step. A run starting at
444            // the same moment took a container that existed and did not yet
445            // hold its marker for someone else's directory, kept its copy in
446            // another, and then could not find it.
447            let made = store.join(format!(".workspaces-{}", unique()));
448            fs::create_dir(&made).map_err(|source| io_error(&made, source))?;
449            fs::write(made.join(WORKSPACE_MARKER), WORKSPACE_MARKER_CONTENTS)
450                .map_err(|source| io_error(&made, source))?;
451            match fs::rename(&made, &container) {
452                Ok(()) => created = true,
453                // Another run named its own first.
454                Err(_) => {
455                    let _ = fs::remove_dir_all(&made);
456                }
457            }
458        }
459        Err(source) => return Err(io_error(&container, source)),
460    }
461    let result = (|| {
462        if !created && !owned_workspace_path(&container) {
463            return Err(WorkspaceError::UnsafePath(container.clone()));
464        }
465        for (name, contents) in [
466            (".gitignore", b"*\n".as_slice()),
467            (WORKSPACE_MARKER, WORKSPACE_MARKER_CONTENTS),
468        ] {
469            let path = container.join(name);
470            match OpenOptions::new().write(true).create_new(true).open(&path) {
471                Ok(mut file) => file
472                    .write_all(contents)
473                    .and_then(|_| file.sync_all())
474                    .map_err(|source| io_error(&path, source))?,
475                Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
476                    if !fs::symlink_metadata(&path)
477                        .is_ok_and(|metadata| metadata.file_type().is_file())
478                    {
479                        return Err(WorkspaceError::UnsafePath(path));
480                    }
481                    if name == WORKSPACE_MARKER
482                        && !fs::read(&path)
483                            .is_ok_and(|contents| contents == WORKSPACE_MARKER_CONTENTS)
484                    {
485                        return Err(WorkspaceError::UnsafePath(path));
486                    }
487                }
488                Err(source) => return Err(io_error(&path, source)),
489            }
490        }
491        Ok(container.clone())
492    })();
493    if result.is_err() && created {
494        let _ = fs::remove_dir_all(&container);
495    }
496    result
497}
498
499fn lexical_normalize(path: &Path) -> Option<PathBuf> {
500    let mut normalized = PathBuf::new();
501    for component in path.components() {
502        match component {
503            Component::Prefix(prefix) => normalized.push(prefix.as_os_str()),
504            Component::RootDir => normalized.push(component.as_os_str()),
505            Component::CurDir => {}
506            Component::ParentDir => {
507                if !normalized.pop() {
508                    return None;
509                }
510            }
511            Component::Normal(value) => normalized.push(value),
512        }
513    }
514    Some(normalized)
515}
516
517fn inside(root: &Path, path: &Path) -> bool {
518    path == root
519        || path.strip_prefix(root).is_ok_and(|local| {
520            !local.as_os_str().is_empty()
521                && local
522                    .components()
523                    .all(|component| matches!(component, Component::Normal(_)))
524        })
525}
526
527trait WorkspaceOperations {
528    fn copy_file(&mut self, source: &Path, destination: &Path) -> Result<(), WorkspaceError>;
529    fn rename(&mut self, source: &Path, destination: &Path) -> Result<(), WorkspaceError>;
530}
531
532struct SystemWorkspaceOperations;
533
534impl WorkspaceOperations for SystemWorkspaceOperations {
535    fn copy_file(&mut self, source: &Path, destination: &Path) -> Result<(), WorkspaceError> {
536        // Per-file APFS clonefile calls can cost tens of milliseconds for tiny
537        // files—far more than copying their bytes. Preserve CoW for genuinely
538        // large artifacts, while ordinary source/config files take the fast
539        // portable path.
540        const REFLINK_MINIMUM_BYTES: u64 = 1024 * 1024;
541        let bytes = fs::symlink_metadata(source)
542            .map_err(|source_error| io_error(source, source_error))?
543            .len();
544        if bytes < REFLINK_MINIMUM_BYTES {
545            fs::copy(source, destination)
546                .map(|_| ())
547                .map_err(|source_error| io_error(destination, source_error))
548        } else {
549            reflink_copy::reflink_or_copy(source, destination)
550                .map(|_| ())
551                .map_err(|source_error| io_error(destination, source_error))
552        }
553    }
554
555    fn rename(&mut self, source: &Path, destination: &Path) -> Result<(), WorkspaceError> {
556        atomic_rename(source, destination).map_err(WorkspaceError::from)
557    }
558}
559
560#[cfg(unix)]
561pub(crate) fn create_link(target: &Path, destination: &Path, _directory: bool) -> io::Result<()> {
562    std::os::unix::fs::symlink(target, destination)
563}
564
565#[cfg(windows)]
566pub(crate) fn create_link(target: &Path, destination: &Path, directory: bool) -> io::Result<()> {
567    if directory {
568        // Junctions work on ordinary NTFS installations without requiring
569        // Developer Mode or SeCreateSymbolicLinkPrivilege. This is the common
570        // path for dependency mounts and internal directory links. A project
571        // may still live on a non-NTFS/network filesystem where junctions are
572        // unavailable but unprivileged symlinks are enabled, so preserve that
573        // valid fallback instead of assuming one Windows filesystem.
574        match junction::create(target, destination) {
575            Ok(()) => Ok(()),
576            Err(junction_error) => {
577                let _ = fs::remove_dir(destination);
578                std::os::windows::fs::symlink_dir(target, destination).map_err(
579                    |symlink_error| {
580                        io::Error::new(
581                            symlink_error.kind(),
582                            format!(
583                                "junction creation failed ({junction_error}); directory symlink fallback failed ({symlink_error})"
584                            ),
585                        )
586                    },
587                )
588            }
589        }
590    } else {
591        // A project that already contains a file symlink necessarily runs in
592        // an environment capable of creating one. Do not silently copy it:
593        // that can change Node realpath/module-identity semantics.
594        std::os::windows::fs::symlink_file(target, destination)
595    }
596}
597
598/// Clone a directory copy-on-write. `false` means the platform or filesystem
599/// cannot (Linux has no directory reflink; APFS refuses across volumes and for
600/// trees holding entries a clone cannot carry), and the caller falls back to
601/// entry links. Any partial destination is removed first so the fallback
602/// starts from a clean slate.
603#[cfg(target_os = "macos")]
604fn clone_directory(source: &Path, destination: &Path) -> bool {
605    use std::{ffi::CString, os::unix::ffi::OsStrExt};
606
607    let (Ok(source_c), Ok(destination_c)) = (
608        CString::new(source.as_os_str().as_bytes()),
609        CString::new(destination.as_os_str().as_bytes()),
610    ) else {
611        return false;
612    };
613    // SAFETY: both arguments are valid NUL-terminated paths that outlive the
614    // call, and clonefile touches nothing else.
615    let status = unsafe { libc::clonefile(source_c.as_ptr(), destination_c.as_ptr(), 0) };
616    if status == 0 {
617        return true;
618    }
619    let _ = fs::remove_dir_all(destination);
620    false
621}
622
623#[cfg(all(unix, not(target_os = "macos")))]
624fn clone_directory(_source: &Path, _destination: &Path) -> bool {
625    false
626}
627
628/// Materialise `source` at `destination` without copying bytes: real
629/// directories, one hard link per file, symlinks recreated verbatim. This is
630/// the mount-safe form where a directory cannot be cloned (Linux has no
631/// directory reflink): a container or VM that mounts the workspace sees real
632/// dependency files where entry links would dangle. Hard links share inodes
633/// with the originals, so an in-place write still reaches the user's tree --
634/// the caveat entry links already carry -- but replacing an entry, which is
635/// what npm does, only unlinks the workspace's name. `false` means the tree
636/// could not be linked (another volume, protected files, an entry that is
637/// neither file, directory nor symlink) and the caller falls back to entry
638/// links after the partial destination is removed.
639#[cfg(unix)]
640fn hard_link_tree(source: &Path, destination: &Path) -> bool {
641    fn link(source: &Path, destination: &Path) -> io::Result<()> {
642        fs::create_dir(destination)?;
643        for entry in fs::read_dir(source)? {
644            let entry = entry?;
645            let from = entry.path();
646            let to = destination.join(entry.file_name());
647            let file_type = entry.file_type()?;
648            if file_type.is_dir() {
649                link(&from, &to)?;
650            } else if file_type.is_symlink() {
651                std::os::unix::fs::symlink(fs::read_link(&from)?, &to)?;
652            } else if file_type.is_file() {
653                fs::hard_link(&from, &to)?;
654            } else {
655                return Err(io::Error::new(
656                    io::ErrorKind::Unsupported,
657                    "entry is neither a file, a directory nor a symlink",
658                ));
659            }
660        }
661        Ok(())
662    }
663    if link(source, destination).is_ok() {
664        return true;
665    }
666    let _ = fs::remove_dir_all(destination);
667    false
668}
669
670#[derive(Clone, Copy)]
671struct CopyRoots<'a> {
672    source: &'a Path,
673    destination: &'a Path,
674    final_destination: &'a Path,
675    canonical_source: &'a Path,
676}
677
678fn copy_tree<Operations: WorkspaceOperations>(
679    source: &Path,
680    destination: &Path,
681    roots: CopyRoots<'_>,
682    root_level: bool,
683    operations: &mut Operations,
684) -> Result<(), WorkspaceError> {
685    fs::create_dir_all(destination).map_err(|source| io_error(destination, source))?;
686    let mut entries = fs::read_dir(source)
687        .map_err(|error| io_error(source, error))?
688        .collect::<Result<Vec<_>, _>>()
689        .map_err(|error| io_error(source, error))?;
690    entries.sort_by_key(fs::DirEntry::file_name);
691    for entry in entries {
692        let name = entry.file_name();
693        let name_text = name
694            .to_str()
695            .ok_or_else(|| WorkspaceError::UnsafePath(entry.path()))?;
696        if (root_level && ROOT_EXCLUSIONS.contains(&name_text))
697            || NESTED_EXCLUSIONS.contains(&name_text)
698        {
699            continue;
700        }
701        let from = entry.path();
702        let metadata = fs::symlink_metadata(&from).map_err(|error| io_error(&from, error))?;
703        if metadata.file_type().is_dir() && owned_workspace_path(&from) {
704            continue;
705        }
706        let to = destination.join(&name);
707        // A Python virtual environment is never instrumented, and copied it
708        // loses its interpreter: `bin/python` links outside the project, and
709        // such links are left out, so a server started as `.venv/bin/python`
710        // did not start at all. The copy uses the environment itself.
711        if metadata.file_type().is_dir() && from.join("pyvenv.cfg").is_file() {
712            create_link(&from, &to, true).map_err(|error| io_error(&to, error))?;
713            continue;
714        }
715        if metadata.file_type().is_dir() {
716            // Nested node_modules are never instrumented, so they are not
717            // mirrored file by file: on a real monorepo (many packages and
718            // examples, each with node_modules) the deep copy was 43-52
719            // seconds of every run's startup.
720            //
721            // Preferred: a copy-on-write clone of the whole directory. It is
722            // one call on APFS (85k files in ~1.2s, no bytes duplicated until
723            // written) and leaves the workspace self-contained -- a suite that
724            // mounts the workspace into a VM or container sees real dependency
725            // trees, and writes stay in the workspace instead of passing
726            // through to the user's tree.
727            //
728            // Next best, where directories cannot be cloned (Linux): the same
729            // tree as hard links -- real directories inside a mount, no bytes
730            // copied, one link call per file.
731            //
732            // Last resort: one symlink per package pointing at the original
733            // tree, the same semantics the root has. The directory itself is
734            // real, so tools creating NEW entries (vite's .cache) still write
735            // into the workspace, but the links dangle wherever the original
736            // path is not visible (a mounted VM), and npm then treats them as
737            // broken installs and fails to re-link them across the mount.
738            #[cfg(unix)]
739            if name_text == "node_modules" && !root_level {
740                if clone_directory(&from, &to) || hard_link_tree(&from, &to) {
741                    // A workspace package's own tools are started from its
742                    // own `.bin`, which comes before the root's on PATH.
743                    crate::source_tools::place_launchers(&from.join(".bin"), &to.join(".bin"))
744                        .map_err(|error| io_error(&to, error))?;
745                    continue;
746                }
747                fs::create_dir_all(&to).map_err(|error| io_error(&to, error))?;
748                let mut packages = fs::read_dir(&from)
749                    .map_err(|error| io_error(&from, error))?
750                    .collect::<Result<Vec<_>, _>>()
751                    .map_err(|error| io_error(&from, error))?;
752                packages.sort_by_key(fs::DirEntry::file_name);
753                for package in packages {
754                    let link_destination = to.join(package.file_name());
755                    if package.file_name() == ".bin" && package.path().is_dir() {
756                        link_tools(&package.path(), &link_destination, operations)?;
757                        continue;
758                    }
759                    create_link(&package.path(), &link_destination, false)
760                        .map_err(|error| io_error(&link_destination, error))?;
761                }
762                continue;
763            }
764            copy_tree(&from, &to, roots, false, operations)?;
765            if name_text == "node_modules" && !root_level {
766                crate::source_tools::place_launchers(&from.join(".bin"), &to.join(".bin"))
767                    .map_err(|error| io_error(&to, error))?;
768            }
769        } else if metadata.file_type().is_symlink() {
770            let link = fs::read_link(&from).map_err(|error| io_error(&from, error))?;
771            let unresolved_target = if link.is_absolute() {
772                link.clone()
773            } else {
774                from.parent().expect("entry parent").join(&link)
775            };
776            let Some(lexical_target) = lexical_normalize(&unresolved_target) else {
777                omit_escaping_link(&from, &link);
778                continue;
779            };
780            // A dangling symlink is a fact of the user's tree that their own
781            // tooling tolerates: npm and pnpm workspaces routinely leave links
782            // to packages that are not installed, and plain `npm test` never
783            // resolves them. Refusing to mirror the project over one broke a
784            // real monorepo on first touch. It resolves to nothing, so it can
785            // leak nothing; the LEXICAL containment check still applies, and
786            // the link is preserved as-is so the workspace matches the source.
787            let canonical_target = match canonicalize_simplified(&from) {
788                Ok(target) => Some(target),
789                Err(error) if error.kind() == io::ErrorKind::NotFound => None,
790                Err(error) => return Err(io_error(&from, error)),
791            };
792            let escapes = !inside(roots.source, &lexical_target)
793                || canonical_target
794                    .as_deref()
795                    .is_some_and(|target| !inside(roots.canonical_source, target));
796            if escapes {
797                omit_escaping_link(&from, &link);
798                continue;
799            }
800            let local_target = lexical_target
801                .strip_prefix(roots.source)
802                .map_err(|_| WorkspaceError::UnsafePath(lexical_target.clone()))?;
803            let relocated = roots.destination.join(local_target);
804            let Some(canonical_target) = canonical_target else {
805                if cfg!(windows) {
806                    // Windows link creation needs the target's type, which a
807                    // dangling link cannot provide; the entry resolves to
808                    // nothing either way.
809                    continue;
810                }
811                let isolated_link = if link.is_absolute() {
812                    pathdiff(&to, &relocated)?
813                } else {
814                    link
815                };
816                create_link(&isolated_link, &to, false).map_err(|error| io_error(&to, error))?;
817                continue;
818            };
819            let target_metadata = fs::metadata(&canonical_target)
820                .map_err(|error| io_error(&canonical_target, error))?;
821            let isolated_link = if cfg!(windows) && target_metadata.is_dir() {
822                roots.final_destination.join(local_target)
823            } else if link.is_absolute() {
824                pathdiff(&to, &relocated)?
825            } else {
826                link
827            };
828            create_link(&isolated_link, &to, target_metadata.is_dir())
829                .map_err(|error| io_error(&to, error))?;
830        } else if metadata.file_type().is_file() {
831            operations.copy_file(&from, &to)?;
832        }
833        // A socket or FIFO -- a dev server's `tmp/puma.sock`, a database
834        // socket kept under the project -- cannot be copied and holds no
835        // source. Refusing it stopped the run over a file no test reads by
836        // copy.
837    }
838    Ok(())
839}
840
841fn pathdiff(from: &Path, to: &Path) -> Result<PathBuf, WorkspaceError> {
842    let from = from
843        .parent()
844        .ok_or_else(|| WorkspaceError::UnsafePath(from.into()))?;
845    let from_components = from.components().collect::<Vec<_>>();
846    let to_components = to.components().collect::<Vec<_>>();
847    let common = from_components
848        .iter()
849        .zip(&to_components)
850        .take_while(|(left, right)| left == right)
851        .count();
852    if common == 0 {
853        return Err(WorkspaceError::UnsafePath(to.into()));
854    }
855    let mut relative = PathBuf::new();
856    for _ in common..from_components.len() {
857        relative.push("..");
858    }
859    for component in &to_components[common..] {
860        relative.push(component.as_os_str());
861    }
862    Ok(relative)
863}
864
865/// One entry of the root `node_modules`. A package of the project's own
866/// workspaces -- `node_modules/money` linked to `../packages/money` by npm,
867/// pnpm or Yarn -- links to its copy in the workspace, which is the
868/// instrumented one: linked to the project's entry it resolved to the
869/// original, so another package's tests ran its code unmeasured and a change
870/// to it never named them. Everything else links to the project's entry. A
871/// scope directory (`@acme/`) is mirrored and its packages linked the same
872/// way. Links to a copy are relative, so they hold when the staged workspace
873/// is moved into place.
874#[cfg(unix)]
875fn link_package(
876    root: &Path,
877    workspace: &Path,
878    target: &Path,
879    to: &Path,
880) -> Result<(), WorkspaceError> {
881    let metadata = fs::symlink_metadata(target).map_err(|error| io_error(target, error))?;
882    let scope = target
883        .file_name()
884        .and_then(|name| name.to_str())
885        .is_some_and(|name| name.starts_with('@'));
886    if scope && metadata.file_type().is_dir() {
887        fs::create_dir_all(to).map_err(|error| io_error(to, error))?;
888        let mut packages = fs::read_dir(target)
889            .map_err(|error| io_error(target, error))?
890            .collect::<Result<Vec<_>, _>>()
891            .map_err(|error| io_error(target, error))?;
892        packages.sort_by_key(fs::DirEntry::file_name);
893        for package in packages {
894            link_package(
895                root,
896                workspace,
897                &package.path(),
898                &to.join(package.file_name()),
899            )?;
900        }
901        return Ok(());
902    }
903    if metadata.file_type().is_symlink()
904        && let (Ok(resolved), Ok(canonical_root)) = (
905            canonicalize_simplified(target),
906            canonicalize_simplified(root),
907        )
908        && let Ok(local) = resolved.strip_prefix(&canonical_root)
909        && !local.as_os_str().is_empty()
910        && !local.components().any(|part| {
911            matches!(
912                part.as_os_str().to_str(),
913                Some("node_modules" | ".supercov")
914            )
915        })
916    {
917        let copy = workspace.join(local);
918        if fs::symlink_metadata(&copy).is_ok() {
919            return create_link(&pathdiff(to, &copy)?, to, true)
920                .map_err(|error| io_error(to, error));
921        }
922    }
923    create_link(target, to, false).map_err(|error| io_error(to, error))
924}
925
926/// The workspace's own `node_modules/.bin`: every tool of the project's, and
927/// in place of each that judges source as text a launcher that runs it on
928/// the source as it was written (see `source_tools`). Package managers put
929/// this directory first on a script's PATH, so nothing else decides what
930/// `biome` in a test script is.
931fn link_tools<Operations: WorkspaceOperations>(
932    tools: &Path,
933    to: &Path,
934    operations: &mut Operations,
935) -> Result<(), WorkspaceError> {
936    #[cfg(unix)]
937    let _ = &operations;
938    fs::create_dir_all(to).map_err(|error| io_error(to, error))?;
939    let judges = crate::source_tools::source_tools();
940    let binary = crate::source_tools::launching_binary();
941    let mut entries = fs::read_dir(tools)
942        .map_err(|error| io_error(tools, error))?
943        .collect::<Result<Vec<_>, _>>()
944        .map_err(|error| io_error(tools, error))?;
945    entries.sort_by_key(fs::DirEntry::file_name);
946    for entry in entries {
947        let (tool, link) = (entry.path(), to.join(entry.file_name()));
948        let launcher = binary.as_deref().and_then(|binary| {
949            crate::source_tools::launcher_for(&judges, binary, tools, &entry.file_name())
950        });
951        if let Some(launcher) = launcher {
952            crate::source_tools::write_launcher(&link, &launcher)
953                .map_err(|error| io_error(&link, error))?;
954            continue;
955        }
956        // A link, where one needs no privilege. On Windows the shims are
957        // small files that find their package from where they are, which
958        // the workspace's `node_modules` has a link for.
959        #[cfg(unix)]
960        create_link(&tool, &link, false).map_err(|error| io_error(&link, error))?;
961        #[cfg(windows)]
962        if fs::metadata(&tool).is_ok_and(|metadata| metadata.is_file()) {
963            operations.copy_file(&tool, &link)?;
964        }
965    }
966    Ok(())
967}
968
969fn link_node_modules<Operations: WorkspaceOperations>(
970    root: &Path,
971    workspace: &Path,
972    operations: &mut Operations,
973) -> Result<(), WorkspaceError> {
974    #[cfg(unix)]
975    let _ = &operations;
976    let source = root.join("node_modules");
977    let source_metadata = match fs::symlink_metadata(&source) {
978        Ok(metadata) => metadata,
979        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
980        Err(error) => return Err(io_error(&source, error)),
981    };
982    // pnpm setups routinely make the root node_modules itself a symlink into a
983    // store elsewhere. The mirror links each entry to its absolute target
984    // anyway, so following the root link loses no isolation -- refusing it
985    // forced one user to materialise a 3.7 GB tree by hand.
986    let source = if source_metadata.file_type().is_symlink() {
987        let resolved =
988            canonicalize_simplified(&source).map_err(|error| io_error(&source, error))?;
989        if !fs::symlink_metadata(&resolved)
990            .map_err(|error| io_error(&resolved, error))?
991            .file_type()
992            .is_dir()
993        {
994            return Err(WorkspaceError::UnsafePath(source));
995        }
996        resolved
997    } else if source_metadata.file_type().is_dir() {
998        source
999    } else {
1000        return Err(WorkspaceError::UnsafePath(source));
1001    };
1002    let destination = workspace.join("node_modules");
1003    fs::create_dir_all(&destination).map_err(|error| io_error(&destination, error))?;
1004    let mut entries = fs::read_dir(&source)
1005        .map_err(|error| io_error(&source, error))?
1006        .collect::<Result<Vec<_>, _>>()
1007        .map_err(|error| io_error(&source, error))?;
1008    entries.sort_by_key(fs::DirEntry::file_name);
1009    for entry in entries {
1010        let target = entry.path();
1011        let to = destination.join(entry.file_name());
1012        if entry.file_name() == ".bin"
1013            && fs::metadata(&target).is_ok_and(|metadata| metadata.is_dir())
1014        {
1015            link_tools(&target, &to, operations)?;
1016            continue;
1017        }
1018        #[cfg(unix)]
1019        link_package(root, workspace, &target, &to)?;
1020        #[cfg(windows)]
1021        {
1022            let file_type = entry
1023                .file_type()
1024                .map_err(|error| io_error(&target, error))?;
1025            let resolved = if file_type.is_symlink() {
1026                canonicalize_simplified(&target).map_err(|error| io_error(&target, error))?
1027            } else {
1028                target.clone()
1029            };
1030            let metadata = fs::metadata(&resolved).map_err(|error| io_error(&resolved, error))?;
1031            if metadata.is_dir() {
1032                create_link(&resolved, &to, true).map_err(|error| io_error(&to, error))?;
1033            } else if metadata.is_file() {
1034                // Top-level node_modules metadata files are cheap to copy and a
1035                // link would unnecessarily require Windows symlink privileges.
1036                operations.copy_file(&resolved, &to)?;
1037            } else {
1038                return Err(WorkspaceError::UnsupportedEntry(target));
1039            }
1040        }
1041    }
1042    Ok(())
1043}
1044
1045fn require_lock(root: &Path, lock: &ProjectLock) -> Result<(), WorkspaceError> {
1046    if lock.protects(root) {
1047        Ok(())
1048    } else {
1049        Err(WorkspaceError::MissingLock)
1050    }
1051}
1052
1053pub fn prepare_isolated_workspace(
1054    root: &Path,
1055    run_id: &str,
1056    lock: &ProjectLock,
1057) -> Result<PathBuf, WorkspaceError> {
1058    require_lock(root, lock)?;
1059    ensure_container(root)?;
1060    let mut operations = SystemWorkspaceOperations;
1061    let workspace = isolated_workspace_path(root, run_id)?;
1062    remove_stored_tree_deferred(root, &workspace)?;
1063    let canonical_root = canonicalize_simplified(root).map_err(|error| io_error(root, error))?;
1064    copy_tree(
1065        root,
1066        &workspace,
1067        CopyRoots {
1068            source: root,
1069            destination: &workspace,
1070            final_destination: &workspace,
1071            canonical_source: &canonical_root,
1072        },
1073        true,
1074        &mut operations,
1075    )?;
1076    link_node_modules(root, &workspace, &mut operations)?;
1077    link_repository_around(root, &workspace);
1078    Ok(workspace)
1079}
1080
1081fn transaction_prefix(root: &Path, kind: &str) -> Result<String, WorkspaceError> {
1082    Ok(format!(
1083        ".{}.{}-",
1084        project_name(root)?.to_string_lossy(),
1085        kind
1086    ))
1087}
1088
1089fn transaction_path(
1090    root: &Path,
1091    lock: &ProjectLock,
1092    kind: &str,
1093) -> Result<PathBuf, WorkspaceError> {
1094    let workspace = cached_workspace_path(root, lock)?;
1095    Ok(workspace.parent().expect("workspace parent").join(format!(
1096        "{}{}",
1097        transaction_prefix(root, kind)?,
1098        unique()
1099    )))
1100}
1101
1102#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1103#[serde(rename_all = "camelCase")]
1104pub struct CacheRecoveryResult {
1105    pub restored_previous: bool,
1106    pub removed_staging: usize,
1107    pub removed_previous: usize,
1108}
1109
1110pub fn recover_cached_workspace(
1111    root: &Path,
1112    lock: &ProjectLock,
1113) -> Result<CacheRecoveryResult, WorkspaceError> {
1114    require_lock(root, lock)?;
1115    let workspace = cached_workspace_path(root, lock)?;
1116    let parent = workspace.parent().expect("workspace parent");
1117    let entries = match fs::read_dir(parent) {
1118        Ok(entries) => entries,
1119        Err(error) if error.kind() == io::ErrorKind::NotFound => {
1120            return Ok(CacheRecoveryResult {
1121                restored_previous: false,
1122                removed_staging: 0,
1123                removed_previous: 0,
1124            });
1125        }
1126        Err(error) => return Err(io_error(parent, error)),
1127    };
1128    let staging_prefix = transaction_prefix(root, "staging")?;
1129    let previous_prefix = transaction_prefix(root, "previous")?;
1130    let mut staging = Vec::new();
1131    let mut previous = Vec::new();
1132    let mut invalid_previous = Vec::new();
1133    for entry in entries {
1134        let entry = entry.map_err(|error| io_error(parent, error))?;
1135        let name = entry.file_name().to_string_lossy().into_owned();
1136        if name.starts_with(&staging_prefix) {
1137            staging.push(entry.path());
1138        } else if name.starts_with(&previous_prefix) {
1139            let metadata = entry
1140                .file_type()
1141                .map_err(|error| io_error(&entry.path(), error))?;
1142            if metadata.is_dir() {
1143                let modified = entry
1144                    .metadata()
1145                    .and_then(|metadata| metadata.modified())
1146                    .unwrap_or(UNIX_EPOCH);
1147                previous.push((modified, entry.path()));
1148            } else {
1149                invalid_previous.push(entry.path());
1150            }
1151        }
1152    }
1153    previous.sort_by_key(|entry| std::cmp::Reverse(entry.0));
1154    let mut restored = false;
1155    if fs::symlink_metadata(&workspace).is_err()
1156        && let Some((_, newest)) = previous.first()
1157    {
1158        atomic_rename(newest, &workspace)?;
1159        previous.remove(0);
1160        restored = true;
1161    }
1162    let removed_staging = staging.len();
1163    let removed_previous = previous.len() + invalid_previous.len();
1164    for path in staging
1165        .into_iter()
1166        .chain(previous.into_iter().map(|(_, path)| path))
1167        .chain(invalid_previous)
1168    {
1169        remove_stored_tree_deferred(root, &path)?;
1170    }
1171    Ok(CacheRecoveryResult {
1172        restored_previous: restored,
1173        removed_staging,
1174        removed_previous,
1175    })
1176}
1177
1178fn checked_reuse_path(workspace: &Path, requested: &Path) -> Result<PathBuf, WorkspaceError> {
1179    if requested.is_absolute()
1180        || requested
1181            .components()
1182            .any(|component| !matches!(component, Component::Normal(_)))
1183    {
1184        return Err(WorkspaceError::UnsafePath(requested.into()));
1185    }
1186    let path = workspace.join(requested);
1187    if path == workspace || fs::symlink_metadata(&path).is_err() {
1188        return Err(WorkspaceError::UnsafePath(requested.into()));
1189    }
1190    Ok(path)
1191}
1192
1193pub fn prepare_cached_workspace(
1194    root: &Path,
1195    lock: &ProjectLock,
1196    reuse_paths: &[PathBuf],
1197) -> Result<PathBuf, WorkspaceError> {
1198    let mut operations = SystemWorkspaceOperations;
1199    prepare_cached_workspace_with_operations(root, lock, reuse_paths, &mut operations)
1200}
1201
1202fn prepare_cached_workspace_with_operations<Operations: WorkspaceOperations>(
1203    root: &Path,
1204    lock: &ProjectLock,
1205    reuse_paths: &[PathBuf],
1206    operations: &mut Operations,
1207) -> Result<PathBuf, WorkspaceError> {
1208    require_lock(root, lock)?;
1209    ensure_container(root)?;
1210    recover_cached_workspace(root, lock)?;
1211    let workspace = cached_workspace_path(root, lock)?;
1212    let staging = transaction_path(root, lock, "staging")?;
1213    let previous = transaction_path(root, lock, "previous")?;
1214    let result = (|| {
1215        let canonical_root =
1216            canonicalize_simplified(root).map_err(|error| io_error(root, error))?;
1217        copy_tree(
1218            root,
1219            &staging,
1220            CopyRoots {
1221                source: root,
1222                destination: &staging,
1223                final_destination: &workspace,
1224                canonical_source: &canonical_root,
1225            },
1226            true,
1227            operations,
1228        )?;
1229        link_node_modules(root, &staging, operations)?;
1230        for requested in reuse_paths {
1231            let from = checked_reuse_path(&workspace, requested)?;
1232            let to = staging.join(requested);
1233            // Output directories are excluded from the mirror only at the
1234            // root, so the staging tree may already hold a stale source copy
1235            // of a nested artifact. The cached artifact is the exact
1236            // post-build state and replaces it wholesale.
1237            match fs::symlink_metadata(&to) {
1238                Ok(existing) if existing.file_type().is_dir() => {
1239                    fs::remove_dir_all(&to).map_err(|error| io_error(&to, error))?;
1240                }
1241                Ok(_) => {
1242                    fs::remove_file(&to).map_err(|error| io_error(&to, error))?;
1243                }
1244                Err(_) => {}
1245            }
1246            let metadata = fs::symlink_metadata(&from).map_err(|error| io_error(&from, error))?;
1247            if metadata.file_type().is_dir() {
1248                let canonical_workspace = canonicalize_simplified(&workspace)
1249                    .map_err(|error| io_error(&workspace, error))?;
1250                copy_tree(
1251                    &from,
1252                    &to,
1253                    CopyRoots {
1254                        source: &workspace,
1255                        destination: &staging,
1256                        final_destination: &workspace,
1257                        canonical_source: &canonical_workspace,
1258                    },
1259                    false,
1260                    operations,
1261                )?;
1262            } else if metadata.file_type().is_file() {
1263                fs::create_dir_all(to.parent().expect("reuse parent"))
1264                    .map_err(|error| io_error(&to, error))?;
1265                operations.copy_file(&from, &to)?;
1266            } else {
1267                return Err(WorkspaceError::UnsupportedEntry(from));
1268            }
1269        }
1270        let mut moved_previous = false;
1271        if fs::symlink_metadata(&workspace).is_ok() {
1272            operations.rename(&workspace, &previous)?;
1273            moved_previous = true;
1274        }
1275        if let Err(error) = operations.rename(&staging, &workspace) {
1276            if moved_previous && fs::symlink_metadata(&workspace).is_err() {
1277                let _ = operations.rename(&previous, &workspace);
1278            }
1279            return Err(error);
1280        }
1281        if fs::symlink_metadata(&previous).is_ok() {
1282            remove_stored_tree_deferred(root, &previous)?;
1283        }
1284        link_repository_around(root, &workspace);
1285        Ok(workspace.clone())
1286    })();
1287    if fs::symlink_metadata(&staging).is_ok() {
1288        remove_stored_tree_deferred(root, &staging)?;
1289    }
1290    result
1291}
1292
1293/// The state of every regular file in the mirror the moment before the
1294/// wrapped command starts: relative path to (length, modified time). Cheap to
1295/// take (stat only) and precise enough to attribute changes to the command.
1296pub struct WorkspaceOutputBaseline {
1297    entries: BTreeMap<PathBuf, (u64, SystemTime)>,
1298}
1299
1300/// What flowed back to the real project after the wrapped command finished.
1301#[derive(Debug, Default, PartialEq, Eq)]
1302pub struct CommandOutputSync {
1303    pub synced: usize,
1304    /// Where the synced files went, for the line that reports them.
1305    pub synced_paths: Vec<PathBuf>,
1306    /// Source files the command modified inside the workspace. Their mirror
1307    /// copies are instrumented, so copying them back would inject probes into
1308    /// the user's repository; they are reported instead.
1309    pub skipped_instrumented: Vec<PathBuf>,
1310    /// Files the command deleted inside the workspace. Deletions are reported
1311    /// rather than propagated: a defect here would destroy user data.
1312    pub deleted_in_workspace: Vec<PathBuf>,
1313}
1314
1315fn walk_output_files(
1316    workspace: &Path,
1317    directory: &Path,
1318    entries: &mut BTreeMap<PathBuf, (u64, SystemTime)>,
1319) -> Result<(), WorkspaceError> {
1320    for entry in fs::read_dir(directory)
1321        .map_err(|error| io_error(directory, error))?
1322        .collect::<Result<Vec<_>, _>>()
1323        .map_err(|error| io_error(directory, error))?
1324    {
1325        let path = entry.path();
1326        let name = entry.file_name();
1327        let relative = path
1328            .strip_prefix(workspace)
1329            .map_err(|_| WorkspaceError::UnsafePath(path.clone()))?
1330            .to_owned();
1331        // Supercov's generated state never flows back, `.git` is not a
1332        // command output, and symlinks (the node_modules link above all) point
1333        // at the real project already.
1334        if relative.components().count() == 1
1335            && matches!(name.to_str(), Some(".supercov") | Some(".git"))
1336        {
1337            continue;
1338        }
1339        let metadata = entry.metadata().map_err(|error| io_error(&path, error))?;
1340        // Dependencies are never command outputs. Nested node_modules may be
1341        // materialised clones (see copy_tree), and a tool's cache inside any
1342        // node_modules must not flow back into the project's dependency tree.
1343        if metadata.is_dir() && name.to_str() == Some("node_modules") {
1344            continue;
1345        }
1346        if fs::symlink_metadata(&path)
1347            .map_err(|error| io_error(&path, error))?
1348            .file_type()
1349            .is_symlink()
1350        {
1351            continue;
1352        }
1353        if metadata.is_dir() {
1354            walk_output_files(workspace, &path, entries)?;
1355        } else if metadata.is_file() {
1356            let modified = metadata
1357                .modified()
1358                .map_err(|error| io_error(&path, error))?;
1359            entries.insert(relative, (metadata.len(), modified));
1360        }
1361    }
1362    Ok(())
1363}
1364
1365pub fn workspace_output_baseline(
1366    workspace: &Path,
1367) -> Result<WorkspaceOutputBaseline, WorkspaceError> {
1368    let mut entries = BTreeMap::new();
1369    walk_output_files(workspace, workspace, &mut entries)?;
1370    Ok(WorkspaceOutputBaseline { entries })
1371}
1372
1373/// Refuse to copy through any pre-existing symlink component under the
1374/// project root, so a command output can never be redirected outside it.
1375fn validate_writeback_destination(root: &Path, relative: &Path) -> Result<(), WorkspaceError> {
1376    if relative.as_os_str().is_empty()
1377        || relative
1378            .components()
1379            .any(|component| !matches!(component, Component::Normal(_)))
1380    {
1381        return Err(WorkspaceError::UnsafePath(relative.into()));
1382    }
1383    let mut current = root.to_owned();
1384    for component in relative.components() {
1385        current.push(component.as_os_str());
1386        match fs::symlink_metadata(&current) {
1387            Ok(metadata) if metadata.file_type().is_symlink() => {
1388                return Err(WorkspaceError::UnsafePath(current));
1389            }
1390            Ok(_) => {}
1391            Err(error) if error.kind() == io::ErrorKind::NotFound => break,
1392            Err(error) => return Err(io_error(&current, error)),
1393        }
1394    }
1395    Ok(())
1396}
1397
1398/// Paths by the place a reader would look for them: each top-level directory
1399/// with how many of the files it holds, the largest first, and files at the
1400/// root by name. "synced 2553 file(s)" named none of them, and 2,547 were a
1401/// build nobody expected in the checkout.
1402pub fn summarize_paths(paths: &[PathBuf]) -> String {
1403    const SHOWN: usize = 4;
1404    let mut places = BTreeMap::<String, usize>::new();
1405    for path in paths {
1406        let mut components = path.components();
1407        let first = components
1408            .next()
1409            .map(|component| component.as_os_str().to_string_lossy().into_owned())
1410            .unwrap_or_default();
1411        let place = if components.next().is_some() {
1412            format!("{first}/")
1413        } else {
1414            first
1415        };
1416        *places.entry(place).or_default() += 1;
1417    }
1418    let mut places = places.into_iter().collect::<Vec<_>>();
1419    places.sort_by(|left, right| right.1.cmp(&left.1).then_with(|| left.0.cmp(&right.0)));
1420    let mut shown = places
1421        .iter()
1422        .take(SHOWN)
1423        .map(|(place, count)| {
1424            if place.ends_with('/') {
1425                format!("{place} {count}")
1426            } else {
1427                place.clone()
1428            }
1429        })
1430        .collect::<Vec<_>>();
1431    if places.len() > SHOWN {
1432        let rest = places[SHOWN..]
1433            .iter()
1434            .map(|(_, count)| count)
1435            .sum::<usize>();
1436        shown.push(format!("{rest} elsewhere"));
1437    }
1438    shown.join(", ")
1439}
1440
1441/// The build output directories of files built from instrumented source.
1442///
1443/// Such a directory is the outermost one holding the file that the project
1444/// either ignores in git or does not have: `.next`, `dist`, `build`. A
1445/// directory the project tracks is not one, so a generated file next to
1446/// updated snapshots withholds only itself.
1447struct BuiltDirectories<'a> {
1448    root: &'a Path,
1449    judged: BTreeMap<PathBuf, bool>,
1450    directories: BTreeSet<PathBuf>,
1451}
1452
1453impl<'a> BuiltDirectories<'a> {
1454    fn new(root: &'a Path) -> Self {
1455        Self {
1456            root,
1457            judged: BTreeMap::new(),
1458            directories: BTreeSet::new(),
1459        }
1460    }
1461
1462    fn add(&mut self, relative: &Path) {
1463        let mut directory = PathBuf::new();
1464        let Some(parent) = relative.parent() else {
1465            return;
1466        };
1467        for component in parent.components() {
1468            directory.push(component);
1469            let root = self.root;
1470            let output = *self
1471                .judged
1472                .entry(directory.clone())
1473                .or_insert_with(|| is_build_output(root, &directory));
1474            if output {
1475                self.directories.insert(directory);
1476                return;
1477            }
1478        }
1479    }
1480
1481    fn holds(&self, relative: &Path) -> bool {
1482        relative
1483            .ancestors()
1484            .skip(1)
1485            .any(|directory| self.directories.contains(directory))
1486    }
1487}
1488
1489/// A bundle, a module or the source map of one.
1490fn compiled_javascript(path: &Path) -> bool {
1491    path.extension()
1492        .and_then(|extension| extension.to_str())
1493        .is_some_and(|extension| matches!(extension, "js" | "mjs" | "cjs" | "map"))
1494}
1495
1496fn is_build_output(root: &Path, directory: &Path) -> bool {
1497    if fs::symlink_metadata(root.join(directory)).is_err() {
1498        return true;
1499    }
1500    std::process::Command::new("git")
1501        .arg("-C")
1502        .arg(root)
1503        .args(["check-ignore", "-q", "--"])
1504        .arg(directory)
1505        .env("GIT_TERMINAL_PROMPT", "0")
1506        .stdin(std::process::Stdio::null())
1507        .stdout(std::process::Stdio::null())
1508        .stderr(std::process::Stdio::null())
1509        .status()
1510        .is_ok_and(|status| status.code() == Some(0))
1511}
1512
1513/// A text file larger than this is copied as it is.
1514const NAMED_FILE_LIMIT: u64 = 16 << 20;
1515
1516/// The spellings of the copy's directory a file can hold, each with the
1517/// project's directory spelled the same way: as the path is, as JSON writes
1518/// a Windows path (`C:\\project`), and as a URL writes one (`C:/project`).
1519fn copy_and_project(root: &Path, workspace: &Path) -> Vec<(String, String)> {
1520    let mut places = Vec::new();
1521    let mut add = |copy: &Path, project: &Path| {
1522        let (copy, project) = (copy.to_string_lossy(), project.to_string_lossy());
1523        for (from, to) in [("\\", "\\"), ("\\", "\\\\"), ("\\", "/")] {
1524            let pair = (copy.replace(from, to), project.replace(from, to));
1525            if !pair.0.is_empty() && pair.0 != pair.1 && !places.contains(&pair) {
1526                places.push(pair);
1527            }
1528        }
1529    };
1530    add(workspace, root);
1531    if let (Ok(copy), Ok(project)) = (
1532        canonicalize_simplified(workspace),
1533        canonicalize_simplified(root),
1534    ) {
1535        add(&copy, &project);
1536    }
1537    // The longest first, so one spelling inside another is not cut short.
1538    places.sort_by_key(|(copy, _)| std::cmp::Reverse(copy.len()));
1539    places
1540}
1541
1542/// The text of a file the command wrote, with the copy's directory replaced
1543/// by the project's, when the file is text that names the copy.
1544///
1545/// The command ran in the copy, so anything that wrote where it was wrote
1546/// the copy's path: a coverage report's `coverage-final.json` keyed every
1547/// file by it, `clover.xml` and a Cobertura report's `<source>` named it, and
1548/// a snapshot of a working directory holds it. Run without Supercov the same
1549/// files name the project, and a file that flows back to the project is to
1550/// be the file the command alone would have left there.
1551fn naming_the_project(
1552    file: &Path,
1553    places: &[(String, String)],
1554) -> Result<Option<String>, WorkspaceError> {
1555    let metadata = fs::metadata(file).map_err(|error| io_error(file, error))?;
1556    if !metadata.is_file() || metadata.len() > NAMED_FILE_LIMIT {
1557        return Ok(None);
1558    }
1559    let bytes = fs::read(file).map_err(|error| io_error(file, error))?;
1560    if bytes.contains(&0) {
1561        return Ok(None);
1562    }
1563    let Ok(text) = String::from_utf8(bytes) else {
1564        return Ok(None);
1565    };
1566    Ok(project_named(&text, places))
1567}
1568
1569/// What a Go or JVM command prints, passed on with the copy named as the
1570/// project. Maven ends a failed run with "Please refer to
1571/// <copy>/target/surefire-reports", Gradle with a `file://` address of its
1572/// report in the copy, and Go names a file in a compile error from where it
1573/// runs: `../../../../crypto.go:9:2` for `./crypto.go:9:2`.
1574pub fn console_names(root: &Path, workspace: &Path) -> crate::process_supervision::ConsoleNames {
1575    let up = workspace
1576        .strip_prefix(root)
1577        .ok()
1578        .map(|inside| inside.components().count())
1579        .filter(|levels| *levels > 0)
1580        .map(|levels| "../".repeat(levels));
1581    crate::process_supervision::ConsoleNames {
1582        places: copy_and_project(root, workspace),
1583        up_to_the_project: up,
1584    }
1585}
1586
1587/// `text` with each spelling of the copy's directory replaced by the
1588/// project's, when it holds one.
1589pub(crate) fn project_named(text: &str, places: &[(String, String)]) -> Option<String> {
1590    if !places.iter().any(|(copy, _)| text.contains(copy.as_str())) {
1591        return None;
1592    }
1593    let mut out = String::with_capacity(text.len());
1594    let mut rest = text;
1595    // The next place the copy is named, the longest spelling where two start
1596    // together (`places` is sorted so).
1597    while let Some((at, copy, project)) = places
1598        .iter()
1599        .filter_map(|(copy, project)| Some((rest.find(copy.as_str())?, copy, project)))
1600        .min_by_key(|(at, _, _)| *at)
1601    {
1602        out.push_str(&rest[..at]);
1603        let after = &rest[at + copy.len()..];
1604        // The directory itself, not a neighbour whose name begins with it
1605        // (`app` beside `app-old`).
1606        let continues = after
1607            .chars()
1608            .next()
1609            .is_some_and(|next| next.is_alphanumeric() || matches!(next, '-' | '_'));
1610        if continues {
1611            let first = rest[at..].chars().next().expect("a match is not empty");
1612            out.push(first);
1613            rest = &rest[at + first.len_utf8()..];
1614        } else {
1615            out.push_str(project);
1616            rest = after;
1617        }
1618    }
1619    out.push_str(rest);
1620    (out != text).then_some(out)
1621}
1622
1623/// Copy files the wrapped command created or changed in the mirror back to
1624/// the real project, so `supercov -- <command>` leaves the working tree in
1625/// the same state `<command>` alone would have: updated snapshots, generated
1626/// fixtures, and reports land in the repository, not in a cache directory.
1627/// `protected` names relative paths whose mirror copies are instrumented and
1628/// must never flow back.
1629pub fn sync_command_outputs(
1630    root: &Path,
1631    workspace: &Path,
1632    baseline: &WorkspaceOutputBaseline,
1633    protected: &BTreeSet<PathBuf>,
1634) -> Result<CommandOutputSync, WorkspaceError> {
1635    sync_outputs_of(
1636        CommandOutputs::JavaScript,
1637        root,
1638        workspace,
1639        baseline,
1640        protected,
1641    )
1642}
1643
1644/// Whose command ran in the copy, for what of its output is the copy's own.
1645///
1646/// A JavaScript build carries the instrumentation in what it compiles, and
1647/// is recognised by the runtime it imports. Go builds nothing into the tree
1648/// unless asked, and what it is asked to build holds the runtime's package.
1649/// Maven and Gradle compile into the tree, `target/` and `build/`, and what
1650/// they compile there is the copy's: only the reports they write beside it
1651/// are the command's own. Cargo builds outside the copy.
1652#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1653pub enum CommandOutputs {
1654    JavaScript,
1655    Go,
1656    Jvm,
1657    Rust,
1658}
1659
1660/// A Go binary built in the copy: it links the runtime, whose package path
1661/// is in it.
1662fn links_the_go_runtime(path: &Path) -> Result<bool, WorkspaceError> {
1663    const MARKER: &[u8] = b"_supercov_runtime";
1664    let bytes = fs::read(path).map_err(|error| io_error(path, error))?;
1665    Ok(bytes.contains(&0) && bytes.windows(MARKER.len()).any(|window| window == MARKER))
1666}
1667
1668/// The directories a JVM build writes its reports to, inside its output.
1669const JVM_REPORTS: &[&str] = &[
1670    "surefire-reports",
1671    "failsafe-reports",
1672    "test-results",
1673    "reports",
1674    "site",
1675];
1676
1677/// Whether a file a JVM build wrote is the build's own state or what it
1678/// compiled, rather than a report: anything in Gradle's own directory, and
1679/// anything in a module's output directory outside the report directories.
1680/// An output directory is `target` beside a `pom.xml` and `build` beside a
1681/// Gradle build file, so a package named `build` is not one.
1682fn jvm_build_state(workspace: &Path, relative: &Path) -> bool {
1683    let parts = relative
1684        .components()
1685        .map(|part| part.as_os_str().to_string_lossy().into_owned())
1686        .collect::<Vec<_>>();
1687    if parts.first().is_some_and(|first| first == ".gradle") {
1688        return true;
1689    }
1690    // The copy's build files carry what Supercov added to them.
1691    if parts.last().is_some_and(|name| {
1692        matches!(
1693            name.as_str(),
1694            "pom.xml"
1695                | "build.gradle"
1696                | "build.gradle.kts"
1697                | "settings.gradle"
1698                | "settings.gradle.kts"
1699        )
1700    }) {
1701        return true;
1702    }
1703    if relative
1704        .extension()
1705        .is_some_and(|extension| extension == "class" || extension == "jar")
1706    {
1707        return true;
1708    }
1709    let mut module = workspace.to_path_buf();
1710    for (index, part) in parts.iter().enumerate() {
1711        let output = match part.as_str() {
1712            "target" => module.join("pom.xml").is_file(),
1713            "build" => [
1714                "build.gradle",
1715                "build.gradle.kts",
1716                "settings.gradle",
1717                "settings.gradle.kts",
1718            ]
1719            .iter()
1720            .any(|file| module.join(file).is_file()),
1721            _ => false,
1722        };
1723        if output {
1724            return !parts[index + 1..]
1725                .iter()
1726                .any(|inside| JVM_REPORTS.contains(&inside.as_str()));
1727        }
1728        module.push(part);
1729    }
1730    false
1731}
1732
1733/// `sync_command_outputs` for a command of any of the languages that run in
1734/// a copy.
1735pub fn sync_outputs_of(
1736    kind: CommandOutputs,
1737    root: &Path,
1738    workspace: &Path,
1739    baseline: &WorkspaceOutputBaseline,
1740    protected: &BTreeSet<PathBuf>,
1741) -> Result<CommandOutputSync, WorkspaceError> {
1742    let mut current = BTreeMap::new();
1743    walk_output_files(workspace, workspace, &mut current)?;
1744    let mut sync = CommandOutputSync::default();
1745    // A file the command built FROM an instrumented source carries the
1746    // instrumentation with it. Copying that into the project would leave
1747    // probes and a workspace-only runtime import in the application's own
1748    // build output, which is the one thing isolation promises never
1749    // happens. The generated runtime lives only inside a workspace, so a
1750    // reference to it is proof the file is not the command's own output.
1751    //
1752    // Nor is the rest of the build it belongs to. `next build` wrote 2,547
1753    // files of which a handful imported the runtime; the others (chunks with
1754    // probes, manifests naming workspace paths) were copied, and a later
1755    // `next start` in the project would have served an instrumented build.
1756    let places = copy_and_project(root, workspace);
1757    let mut changed = Vec::new();
1758    let mut built = BTreeSet::new();
1759    let mut built_directories = BuiltDirectories::new(root);
1760    for (relative, state) in &current {
1761        if baseline.entries.get(relative) == Some(state) {
1762            continue;
1763        }
1764        if !protected.contains(relative) {
1765            match kind {
1766                CommandOutputs::JavaScript => {
1767                    // Compiled code marks a build. A report that quotes a
1768                    // stack frame of the runtime does not: the screenshots
1769                    // and traces beside a failed Playwright test's
1770                    // `error-context.md` are the command's own output.
1771                    let compiled = compiled_javascript(relative);
1772                    if built_from_instrumented_source(&workspace.join(relative), compiled)? {
1773                        built.insert(relative.clone());
1774                        if compiled {
1775                            built_directories.add(relative);
1776                        }
1777                    }
1778                }
1779                CommandOutputs::Go => {
1780                    if links_the_go_runtime(&workspace.join(relative))? {
1781                        built.insert(relative.clone());
1782                    }
1783                }
1784                CommandOutputs::Jvm => {
1785                    if jvm_build_state(workspace, relative) {
1786                        built.insert(relative.clone());
1787                    }
1788                }
1789                // Any Rust file in the copy may have been rewritten, the
1790                // tests among them for their assertions. And the lockfile
1791                // Cargo writes when a project has none is what the run's
1792                // dependencies are read from: returned, it made the run
1793                // that wrote it stale the moment it ended, and every test
1794                // affected by a change to one line.
1795                CommandOutputs::Rust => {
1796                    if relative
1797                        .extension()
1798                        .is_some_and(|extension| extension == "rs")
1799                        || relative
1800                            .file_name()
1801                            .is_some_and(|name| name == "Cargo.lock")
1802                    {
1803                        built.insert(relative.clone());
1804                    }
1805                }
1806            }
1807        }
1808        changed.push(relative);
1809    }
1810    for relative in changed {
1811        if protected.contains(relative)
1812            || built.contains(relative)
1813            || built_directories.holds(relative)
1814        {
1815            sync.skipped_instrumented.push(relative.clone());
1816            continue;
1817        }
1818        let from = workspace.join(relative);
1819        if unaccompanied_install_manifest(root, workspace, relative) {
1820            continue;
1821        }
1822        validate_writeback_destination(root, relative)?;
1823        let to = root.join(relative);
1824        if let Some(parent) = to.parent() {
1825            fs::create_dir_all(parent).map_err(|error| io_error(parent, error))?;
1826        }
1827        match naming_the_project(&from, &places)? {
1828            Some(text) => {
1829                fs::write(&to, text).map_err(|error| io_error(&to, error))?;
1830                if let Ok(metadata) = fs::metadata(&from) {
1831                    let _ = fs::set_permissions(&to, metadata.permissions());
1832                }
1833            }
1834            None => {
1835                fs::copy(&from, &to).map_err(|error| io_error(&to, error))?;
1836            }
1837        }
1838        sync.synced += 1;
1839        sync.synced_paths.push(relative.clone());
1840    }
1841    for relative in baseline.entries.keys() {
1842        // Only what the project still has is worth a line: a rebuilt `.next`
1843        // that never left the workspace "deleted" files nobody can find.
1844        if !current.contains_key(relative) && fs::symlink_metadata(root.join(relative)).is_ok() {
1845            sync.deleted_in_workspace.push(relative.clone());
1846        }
1847    }
1848    Ok(sync)
1849}
1850
1851/// What flowed back and what stayed, as the lines a run prints about it.
1852pub fn describe_command_outputs(outputs: &CommandOutputSync) -> Vec<String> {
1853    let mut lines = Vec::new();
1854    if outputs.synced > 0 {
1855        lines.push(format!(
1856            "[supercov] synced {} file(s) the command created or changed back to the project: {}",
1857            outputs.synced,
1858            summarize_paths(&outputs.synced_paths)
1859        ));
1860    }
1861    if !outputs.skipped_instrumented.is_empty() {
1862        lines.push(format!(
1863            "[supercov] {} file(s) stayed in the isolated workspace: they are instrumented copies, or were built from them, and must not overwrite your project: {}",
1864            outputs.skipped_instrumented.len(),
1865            summarize_paths(&outputs.skipped_instrumented)
1866        ));
1867    }
1868    if !outputs.deleted_in_workspace.is_empty() {
1869        lines.push(format!(
1870            "[supercov] the command deleted {} file(s) in the isolated workspace; deletions are not propagated to the project: {}",
1871            outputs.deleted_in_workspace.len(),
1872            summarize_paths(&outputs.deleted_in_workspace)
1873        ));
1874    }
1875    lines
1876}
1877
1878/// Give the workspace a git repository of its own, as the project has one.
1879///
1880/// Tools in a test command read git: npm's template-oss-check derives the
1881/// repository and release branches it expects from it, and semver's posttest
1882/// failed without one ("\"repository\" ... expected to be removed"). The
1883/// project's own .git is never shared -- a test's `git add` or `commit`
1884/// would then change the user's index and refs -- so this is a clone that
1885/// borrows the project's objects and has its own refs, index and config: the
1886/// project's HEAD, remotes and remote branches, and an index read from HEAD.
1887/// Best effort: without git, or on any failure, the workspace has no .git.
1888pub fn mirror_git_repository(root: &Path, workspace: &Path) -> Result<(), String> {
1889    if fs::symlink_metadata(root.join(".git")).is_err() {
1890        return Ok(());
1891    }
1892    let target = workspace.join(".git");
1893    let git = |directory: &Path, arguments: &[&str]| -> Result<String, String> {
1894        let output = std::process::Command::new("git")
1895            .arg("-C")
1896            .arg(directory)
1897            .args(arguments)
1898            .env("GIT_TERMINAL_PROMPT", "0")
1899            .stdin(std::process::Stdio::null())
1900            .output()
1901            .map_err(|error| format!("git {}: {error}", arguments.join(" ")))?;
1902        if output.status.success() {
1903            Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
1904        } else {
1905            Err(format!(
1906                "git {}: {}",
1907                arguments.join(" "),
1908                String::from_utf8_lossy(&output.stderr).trim()
1909            ))
1910        }
1911    };
1912    let result = (|| {
1913        if fs::symlink_metadata(&target).is_ok() {
1914            fs::remove_dir_all(&target).map_err(|error| error.to_string())?;
1915        }
1916        let source = root.to_string_lossy();
1917        let destination = target.to_string_lossy();
1918        git(
1919            workspace,
1920            &[
1921                "clone",
1922                "--quiet",
1923                "--shared",
1924                "--bare",
1925                &source,
1926                &destination,
1927            ],
1928        )?;
1929        git(workspace, &["config", "core.bare", "false"])?;
1930        match git(root, &["symbolic-ref", "-q", "HEAD"]) {
1931            Ok(branch) => git(workspace, &["symbolic-ref", "HEAD", &branch])?,
1932            Err(_) => {
1933                let commit = git(root, &["rev-parse", "HEAD"])?;
1934                git(workspace, &["update-ref", "--no-deref", "HEAD", &commit])?
1935            }
1936        };
1937        git(workspace, &["remote", "remove", "origin"])?;
1938        let remotes = git(root, &["remote"])?;
1939        for name in remotes.lines().filter(|name| !name.is_empty()) {
1940            // As configured: get-url applies the user's insteadOf rewrites,
1941            // which the clone's own reads apply again.
1942            let url = git(root, &["config", "--get", &format!("remote.{name}.url")])?;
1943            git(workspace, &["remote", "add", name, &url])?;
1944        }
1945        git(
1946            workspace,
1947            &[
1948                "fetch",
1949                "--quiet",
1950                "--no-tags",
1951                &source,
1952                "+refs/remotes/*:refs/remotes/*",
1953            ],
1954        )?;
1955        git(workspace, &["read-tree", "HEAD"])?;
1956        // Supercov's own directories are not the command's untracked files.
1957        let exclude = target.join("info/exclude");
1958        fs::create_dir_all(target.join("info")).map_err(|error| error.to_string())?;
1959        let mut patterns = fs::read_to_string(&exclude).unwrap_or_default();
1960        patterns.push_str("\n.supercov/\n");
1961        fs::write(&exclude, patterns).map_err(|error| error.to_string())?;
1962        Ok(())
1963    })();
1964    if result.is_err() {
1965        let _ = fs::remove_dir_all(&target);
1966    }
1967    result
1968}
1969
1970/// Keep the files Supercov rewrote out of the workspace repository's status:
1971/// natively they are unmodified, and a test that checks for a clean tree must
1972/// find one. Best effort, as the repository is.
1973pub fn hide_rewritten_files(workspace: &Path, files: &[String]) {
1974    if files.is_empty() || !workspace.join(".git").is_dir() {
1975        return;
1976    }
1977    let run = |arguments: &[&str], input: &str| {
1978        let mut child = std::process::Command::new("git")
1979            .arg("-C")
1980            .arg(workspace)
1981            .args(arguments)
1982            .stdin(std::process::Stdio::piped())
1983            .stdout(std::process::Stdio::piped())
1984            .stderr(std::process::Stdio::null())
1985            .spawn()
1986            .ok()?;
1987        child.stdin.take()?.write_all(input.as_bytes()).ok()?;
1988        let output = child.wait_with_output().ok()?;
1989        output
1990            .status
1991            .success()
1992            .then(|| String::from_utf8_lossy(&output.stdout).into_owned())
1993    };
1994    // Only tracked files carry the bit; git refuses the rest.
1995    let Some(listed) = run(&["ls-files", "-z"], "") else {
1996        return;
1997    };
1998    let tracked = listed.split('\0').collect::<BTreeSet<_>>();
1999    let hidden = files
2000        .iter()
2001        .filter(|file| tracked.contains(file.as_str()))
2002        .map(String::as_str)
2003        .collect::<Vec<_>>();
2004    if !hidden.is_empty() {
2005        let _ = run(
2006            &["update-index", "--skip-worktree", "--stdin"],
2007            &hidden.join("\n"),
2008        );
2009    }
2010}
2011
2012/// Whether `relative` is the manifest or lockfile of an install the command
2013/// made in the workspace alone. node_modules never flows back, so copying
2014/// these would leave the project claiming an install it does not have: tap
2015/// installs its plugins into .tap/plugins, found package.json and a lockfile
2016/// there on the next run without Supercov, and failed to import them. Left
2017/// out, the tool installs them again as it would the first time.
2018fn unaccompanied_install_manifest(root: &Path, workspace: &Path, relative: &Path) -> bool {
2019    let manifest = relative
2020        .file_name()
2021        .and_then(|name| name.to_str())
2022        .is_some_and(|name| {
2023            matches!(
2024                name,
2025                "package.json"
2026                    | "package-lock.json"
2027                    | "npm-shrinkwrap.json"
2028                    | "yarn.lock"
2029                    | "pnpm-lock.yaml"
2030                    | "bun.lock"
2031                    | "bun.lockb"
2032            )
2033        });
2034    let Some(directory) = relative.parent() else {
2035        return false;
2036    };
2037    manifest
2038        && workspace.join(directory).join("node_modules").is_dir()
2039        && !root.join(directory).join("node_modules").exists()
2040}
2041
2042/// Whether `path` mentions the generated runtime module, which exists only
2043/// inside an instrumented workspace. Read as bytes: build output can be
2044/// minified, source-mapped or not valid UTF-8, and the marker is ASCII.
2045/// Whether a file the command wrote came out of instrumented source: it
2046/// names the generated runtime, which lives only inside a workspace, or it is
2047/// compiled code that calls the probes. A bundler that inlines the runtime
2048/// leaves no path to it in a chunk (Turbopack's name it only in their source
2049/// maps), but the probe calls are still there. A minifier renames the
2050/// probes' local names and cannot rename the global they are read from: a
2051/// Vite production build of the instrumented copy held none of the first
2052/// two, and was synced over the project's `dist/`.
2053fn built_from_instrumented_source(path: &Path, compiled: bool) -> Result<bool, WorkspaceError> {
2054    const RUNTIME: &[u8] = b".supercov/node_modules/";
2055    const PROBE: &[u8] = b"__supercov";
2056    const GLOBAL: &[u8] = b"__SUPERCOV_DIRECT_RUNTIME__";
2057    let contents = match fs::read(path) {
2058        Ok(contents) => contents,
2059        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
2060        Err(error) => return Err(io_error(path, error)),
2061    };
2062    let holds = |marker: &[u8]| {
2063        contents
2064            .windows(marker.len())
2065            .any(|window| window == marker)
2066    };
2067    Ok(holds(RUNTIME) || (compiled && (holds(PROBE) || holds(GLOBAL))))
2068}
2069
2070pub fn prune_cached_workspace_sources(
2071    root: &Path,
2072    lock: &ProjectLock,
2073) -> Result<Vec<String>, WorkspaceError> {
2074    require_lock(root, lock)?;
2075    let workspace = cached_workspace_path(root, lock)?;
2076    if fs::symlink_metadata(&workspace).is_err() {
2077        return Ok(Vec::new());
2078    }
2079    let keep = BTreeSet::from(["node_modules".to_owned(), ".supercov".to_owned()]);
2080    let mut removed = Vec::new();
2081    for entry in fs::read_dir(&workspace).map_err(|error| io_error(&workspace, error))? {
2082        let entry = entry.map_err(|error| io_error(&workspace, error))?;
2083        let name = entry
2084            .file_name()
2085            .into_string()
2086            .map_err(|_| WorkspaceError::UnsafePath(entry.path()))?;
2087        if keep.contains(&name) {
2088            continue;
2089        }
2090        remove_stored_tree_deferred(root, &entry.path())?;
2091        removed.push(name);
2092    }
2093    removed.sort();
2094    Ok(removed)
2095}
2096
2097#[cfg(test)]
2098mod tests {
2099    #[test]
2100    fn file_urls_match_what_node_derives_for_every_path_shape() {
2101        use super::file_url_from_slash_path;
2102        assert_eq!(
2103            file_url_from_slash_path("C:/Users/runner/AppData/Local/Temp/x/register.mjs"),
2104            "file:///C:/Users/runner/AppData/Local/Temp/x/register.mjs"
2105        );
2106        assert_eq!(
2107            file_url_from_slash_path("C:/Users/a b/#1/register.mjs"),
2108            "file:///C:/Users/a%20b/%231/register.mjs"
2109        );
2110        assert_eq!(
2111            file_url_from_slash_path("//server/share/dir/register.mjs"),
2112            "file://server/share/dir/register.mjs"
2113        );
2114        assert_eq!(
2115            file_url_from_slash_path("/w/p/register.mjs"),
2116            "file:///w/p/register.mjs"
2117        );
2118        assert_eq!(
2119            file_url_from_slash_path("/w/p x?q/ü.mjs"),
2120            "file:///w/p%20x%3Fq/%C3%BC.mjs"
2121        );
2122    }
2123
2124    #[test]
2125    fn verbatim_prefixes_are_stripped_and_plain_paths_left_alone() {
2126        use super::strip_verbatim;
2127        assert_eq!(strip_verbatim(r"\\?\C:\a\b").as_deref(), Some(r"C:\a\b"));
2128        assert_eq!(strip_verbatim(r"\\?\d:\x").as_deref(), Some(r"d:\x"));
2129        assert_eq!(
2130            strip_verbatim(r"\\?\UNC\server\share\dir").as_deref(),
2131            Some(r"\\server\share\dir")
2132        );
2133        assert_eq!(strip_verbatim(r"C:\a\b"), None);
2134        assert_eq!(strip_verbatim("/w/project"), None);
2135        assert_eq!(strip_verbatim(r"\\server\share"), None);
2136        assert_eq!(strip_verbatim(r"\\?\"), None);
2137    }
2138
2139    use super::*;
2140
2141    fn writeback_fixture(name: &str) -> (PathBuf, PathBuf) {
2142        let base =
2143            std::env::temp_dir().join(format!("supercov-writeback-{}-{name}", std::process::id()));
2144        if base.exists() {
2145            fs::remove_dir_all(&base).unwrap();
2146        }
2147        let root = base.join("project");
2148        let workspace = base.join("workspace");
2149        fs::create_dir_all(root.join("src")).unwrap();
2150        fs::create_dir_all(workspace.join("src")).unwrap();
2151        fs::create_dir_all(workspace.join(".supercov")).unwrap();
2152        fs::write(root.join("src/app.ts"), "original\n").unwrap();
2153        fs::write(workspace.join("src/app.ts"), "instrumented\n").unwrap();
2154        fs::write(workspace.join(".supercov/state.json"), "{}").unwrap();
2155        (root, workspace)
2156    }
2157
2158    #[test]
2159    fn the_workspace_has_a_repository_of_its_own_that_reads_like_the_project() {
2160        let (root, workspace) = writeback_fixture("git-mirror");
2161        let git = |directory: &Path, arguments: &[&str]| {
2162            let output = std::process::Command::new("git")
2163                .arg("-C")
2164                .arg(directory)
2165                .args(arguments)
2166                .output()
2167                .unwrap();
2168            assert!(output.status.success(), "git {arguments:?}: {output:?}");
2169            String::from_utf8(output.stdout).unwrap().trim().to_owned()
2170        };
2171        git(&root, &["init", "--quiet", "--initial-branch=release/v2"]);
2172        git(&root, &["config", "user.email", "test@example.com"]);
2173        git(&root, &["config", "user.name", "Test"]);
2174        git(
2175            &root,
2176            &[
2177                "remote",
2178                "add",
2179                "origin",
2180                "https://github.com/example/app.git",
2181            ],
2182        );
2183        git(&root, &["add", "src/app.ts"]);
2184        git(&root, &["commit", "--quiet", "-m", "first"]);
2185        let head = git(&root, &["rev-parse", "HEAD"]);
2186
2187        mirror_git_repository(&root, &workspace).unwrap();
2188        assert_eq!(git(&workspace, &["rev-parse", "HEAD"]), head);
2189        assert_eq!(
2190            git(&workspace, &["symbolic-ref", "HEAD"]),
2191            "refs/heads/release/v2"
2192        );
2193        assert_eq!(
2194            git(&workspace, &["config", "--get", "remote.origin.url"]),
2195            "https://github.com/example/app.git"
2196        );
2197        // The workspace copy is instrumented and .supercov is Supercov's.
2198        hide_rewritten_files(&workspace, &["src/app.ts".to_owned()]);
2199        assert_eq!(git(&workspace, &["status", "--porcelain"]), "");
2200
2201        // A commit a test makes stays in the workspace's own repository.
2202        fs::write(workspace.join("new.txt"), "new\n").unwrap();
2203        git(&workspace, &["add", "new.txt"]);
2204        git(
2205            &workspace,
2206            &[
2207                "-c",
2208                "user.email=t@example.com",
2209                "-c",
2210                "user.name=T",
2211                "commit",
2212                "--quiet",
2213                "-m",
2214                "second",
2215            ],
2216        );
2217        assert_eq!(git(&root, &["rev-parse", "HEAD"]), head);
2218        assert_eq!(git(&root, &["status", "--porcelain"]), "");
2219        fs::remove_dir_all(root.parent().unwrap()).unwrap();
2220    }
2221
2222    #[test]
2223    fn an_install_the_command_made_does_not_flow_back_without_its_dependencies() {
2224        let (root, workspace) = writeback_fixture("tool-install");
2225        fs::write(workspace.join("package.json"), "{}").unwrap();
2226        fs::write(root.join("package.json"), "{}").unwrap();
2227        fs::create_dir_all(workspace.join("node_modules")).unwrap();
2228        fs::create_dir_all(root.join("node_modules")).unwrap();
2229        let baseline = workspace_output_baseline(&workspace).unwrap();
2230        // tap installs the plugins its config names into .tap/plugins.
2231        fs::create_dir_all(workspace.join(".tap/plugins/node_modules/@tapjs/clock")).unwrap();
2232        fs::write(workspace.join(".tap/plugins/package.json"), "{}").unwrap();
2233        fs::write(workspace.join(".tap/plugins/package-lock.json"), "{}").unwrap();
2234        fs::create_dir_all(workspace.join(".tap/test-results")).unwrap();
2235        fs::write(workspace.join(".tap/test-results/basic.tap"), "ok").unwrap();
2236        // The project's own manifest still flows back beside its own install.
2237        fs::write(workspace.join("package.json"), "{\"version\":\"2\"}").unwrap();
2238        let sync = sync_command_outputs(&root, &workspace, &baseline, &BTreeSet::new()).unwrap();
2239        assert!(!root.join(".tap/plugins/package.json").exists());
2240        assert!(!root.join(".tap/plugins/package-lock.json").exists());
2241        assert!(root.join(".tap/test-results/basic.tap").is_file());
2242        assert_eq!(
2243            fs::read_to_string(root.join("package.json")).unwrap(),
2244            "{\"version\":\"2\"}"
2245        );
2246        assert_eq!(sync.synced, 2);
2247        fs::remove_dir_all(root.parent().unwrap()).unwrap();
2248    }
2249
2250    #[test]
2251    fn a_file_that_flows_back_names_the_project_and_not_the_copy() {
2252        // Vitest's coverage report, written by a command that ran in the copy:
2253        // `coverage-final.json` keyed every file by the copy's path, where the
2254        // same command without Supercov keys it by the project's.
2255        let (root, workspace) = writeback_fixture("names");
2256        let baseline = workspace_output_baseline(&workspace).unwrap();
2257        let (copy, project) = (workspace.display().to_string(), root.display().to_string());
2258        fs::create_dir_all(workspace.join("coverage")).unwrap();
2259        fs::write(
2260            workspace.join("coverage/coverage-final.json"),
2261            format!("{{\"{copy}/src/fee.js\": {{\"path\": \"{copy}/src/fee.js\"}}}}"),
2262        )
2263        .unwrap();
2264        fs::write(
2265            workspace.join("coverage/cobertura.xml"),
2266            format!("<sources><source>{copy}</source></sources>"),
2267        )
2268        .unwrap();
2269        // A neighbour whose name only begins with the copy's is not the copy.
2270        fs::write(
2271            workspace.join("coverage/neighbour.txt"),
2272            format!("{copy}-old/file and {copy}"),
2273        )
2274        .unwrap();
2275        // Bytes that are not text are copied as they are.
2276        let mut binary = copy.clone().into_bytes();
2277        binary.push(0);
2278        fs::write(workspace.join("coverage/cache.bin"), &binary).unwrap();
2279        fs::write(workspace.join("coverage/plain.txt"), "nothing to name").unwrap();
2280        let sync = sync_command_outputs(&root, &workspace, &baseline, &BTreeSet::new()).unwrap();
2281        assert_eq!(sync.synced, 5);
2282        assert_eq!(
2283            fs::read_to_string(root.join("coverage/coverage-final.json")).unwrap(),
2284            format!("{{\"{project}/src/fee.js\": {{\"path\": \"{project}/src/fee.js\"}}}}")
2285        );
2286        assert_eq!(
2287            fs::read_to_string(root.join("coverage/cobertura.xml")).unwrap(),
2288            format!("<sources><source>{project}</source></sources>")
2289        );
2290        assert_eq!(
2291            fs::read_to_string(root.join("coverage/neighbour.txt")).unwrap(),
2292            format!("{copy}-old/file and {project}")
2293        );
2294        assert_eq!(fs::read(root.join("coverage/cache.bin")).unwrap(), binary);
2295        assert_eq!(
2296            fs::read_to_string(root.join("coverage/plain.txt")).unwrap(),
2297            "nothing to name"
2298        );
2299        // The copy keeps what the command wrote.
2300        assert!(
2301            fs::read_to_string(workspace.join("coverage/cobertura.xml"))
2302                .unwrap()
2303                .contains(&copy)
2304        );
2305        fs::remove_dir_all(root.parent().unwrap()).unwrap();
2306    }
2307
2308    #[test]
2309    fn what_a_go_jvm_or_rust_command_writes_flows_back_and_what_it_builds_stays() {
2310        // Only JavaScript's command had its files returned. `go test
2311        // -coverprofile=cover.out` left no `cover.out` in the project, `mvn
2312        // test` no `target/surefire-reports`, and a snapshot a Rust test
2313        // accepted stayed in the copy.
2314        let write = |workspace: &Path, file: &str, contents: &[u8]| {
2315            let path = workspace.join(file);
2316            fs::create_dir_all(path.parent().unwrap()).unwrap();
2317            fs::write(path, contents).unwrap();
2318        };
2319        let flows = |kind: CommandOutputs, name: &str, files: &[(&str, &[u8])]| {
2320            let (root, workspace) = writeback_fixture(name);
2321            // The build files are the copy's before the command runs.
2322            write(&workspace, "pom.xml", b"<project/>");
2323            write(&workspace, "app/build.gradle.kts", b"plugins {}");
2324            let baseline = workspace_output_baseline(&workspace).unwrap();
2325            for (file, contents) in files {
2326                write(&workspace, file, contents);
2327            }
2328            let sync =
2329                sync_outputs_of(kind, &root, &workspace, &baseline, &BTreeSet::new()).unwrap();
2330            let synced = files
2331                .iter()
2332                .filter(|(file, _)| root.join(file).is_file())
2333                .map(|(file, _)| (*file).to_owned())
2334                .collect::<Vec<_>>();
2335            assert_eq!(sync.synced, synced.len(), "{sync:?}");
2336            fs::remove_dir_all(root.parent().unwrap()).unwrap();
2337            synced
2338        };
2339        let mut binary = b"\x7fELF\0\0example.com/shop/_supercov_runtime\0".to_vec();
2340        binary.extend([0u8; 16]);
2341        assert_eq!(
2342            flows(
2343                CommandOutputs::Go,
2344                "go",
2345                &[
2346                    ("cover.out", b"mode: set\n"),
2347                    ("testdata/golden.png", b"\x89PNG\0\0"),
2348                    ("shop.test", &binary),
2349                ]
2350            ),
2351            ["cover.out", "testdata/golden.png"]
2352        );
2353        assert_eq!(
2354            flows(
2355                CommandOutputs::Jvm,
2356                "jvm",
2357                &[
2358                    (
2359                        "target/surefire-reports/TEST-shop.CryptoTest.xml",
2360                        b"<testsuite/>"
2361                    ),
2362                    ("target/site/jacoco/index.html", b"<html/>"),
2363                    ("app/build/test-results/test/TEST-a.xml", b"<testsuite/>"),
2364                    ("app/build/reports/tests/test/index.html", b"<html/>"),
2365                    ("src/test/resources/approved/output.txt", b"approved"),
2366                    // What the build compiled, and its own state.
2367                    ("target/classes/shop/Crypto.class", b"\xca\xfe\xba\xbe"),
2368                    (
2369                        "target/maven-status/compile/createdFiles.lst",
2370                        b"shop/Crypto.class"
2371                    ),
2372                    ("app/build/classes/kotlin/main/A.class", b"\xca\xfe\xba\xbe"),
2373                    ("app/build/tmp/compileKotlin/cache.txt", b"state"),
2374                    (".gradle/8.10/fileHashes/fileHashes.lock", b"lock"),
2375                    ("pom.xml", b"<project><!-- changed --></project>"),
2376                    // A package named `build` is not a build's output.
2377                    ("src/build/notes.txt", b"kept"),
2378                ]
2379            ),
2380            [
2381                "target/surefire-reports/TEST-shop.CryptoTest.xml",
2382                "target/site/jacoco/index.html",
2383                "app/build/test-results/test/TEST-a.xml",
2384                "app/build/reports/tests/test/index.html",
2385                "src/test/resources/approved/output.txt",
2386                "src/build/notes.txt",
2387            ]
2388        );
2389        assert_eq!(
2390            flows(
2391                CommandOutputs::Rust,
2392                "rust",
2393                &[
2394                    ("src/snapshots/sealed.snap", b"SNAP"),
2395                    ("report.json", b"{}"),
2396                    ("Cargo.lock", b"# lock"),
2397                    ("src/generated.rs", b"pub fn made() {}"),
2398                ]
2399            ),
2400            ["src/snapshots/sealed.snap", "report.json"]
2401        );
2402    }
2403
2404    #[test]
2405    fn dependency_trees_never_flow_back() {
2406        // Nested node_modules may be materialised clones, and any node_modules
2407        // can hold a tool's cache: neither is a command output.
2408        let (root, workspace) = writeback_fixture("dependencies");
2409        let baseline = workspace_output_baseline(&workspace).unwrap();
2410        fs::create_dir_all(workspace.join("node_modules/.vite")).unwrap();
2411        fs::write(workspace.join("node_modules/.vite/deps.json"), "{}").unwrap();
2412        fs::create_dir_all(workspace.join("packages/app/node_modules/dep")).unwrap();
2413        fs::write(
2414            workspace.join("packages/app/node_modules/dep/index.js"),
2415            "dep",
2416        )
2417        .unwrap();
2418        let sync = sync_command_outputs(&root, &workspace, &baseline, &BTreeSet::new()).unwrap();
2419        assert_eq!(sync.synced, 0);
2420        assert!(sync.deleted_in_workspace.is_empty());
2421        assert!(!root.join("node_modules").exists());
2422        assert!(!root.join("packages").exists());
2423        fs::remove_dir_all(root.parent().unwrap()).unwrap();
2424    }
2425
2426    #[test]
2427    fn output_built_from_instrumented_sources_never_flows_back() {
2428        // A build the command runs inside the workspace compiles the
2429        // instrumented copies, so its output carries probes and an import of a
2430        // runtime that exists only in the workspace. Writing that into the
2431        // project would leave the application's own build output instrumented
2432        // after the run, which isolation promises never happens.
2433        let (root, workspace) = writeback_fixture("built-output");
2434        let baseline = workspace_output_baseline(&workspace).unwrap();
2435        fs::create_dir_all(workspace.join("dist")).unwrap();
2436        fs::write(
2437            workspace.join("dist/app.js"),
2438            "import { coverageHit } from \"./.supercov/node_modules/runtime.mjs\";\ncoverageHit(0);\n",
2439        )
2440        .unwrap();
2441        fs::write(
2442            workspace.join("dist/app.d.ts"),
2443            "export declare const a: number;\n",
2444        )
2445        .unwrap();
2446
2447        let sync = sync_command_outputs(&root, &workspace, &baseline, &BTreeSet::new()).unwrap();
2448
2449        // The declarations beside it were inferred from the instrumented
2450        // copies too, so the whole build stays behind, not a part of it.
2451        assert_eq!(
2452            sync.skipped_instrumented,
2453            vec![PathBuf::from("dist/app.d.ts"), PathBuf::from("dist/app.js")],
2454            "the instrumented build is reported, not copied"
2455        );
2456        assert_eq!(sync.synced, 0);
2457        assert!(!root.join("dist").exists());
2458        fs::remove_dir_all(root.parent().unwrap()).unwrap();
2459    }
2460
2461    #[test]
2462    fn a_built_file_in_a_directory_the_project_keeps_withholds_only_itself() {
2463        // `src` is the project's own directory, not a build's: the snapshot a
2464        // test updated next to a generated bundle still belongs to the project.
2465        let (root, workspace) = writeback_fixture("built-beside-outputs");
2466        let baseline = workspace_output_baseline(&workspace).unwrap();
2467        fs::write(
2468            workspace.join("src/bundle.js"),
2469            "import \"../.supercov/node_modules/runtime.mjs\";\n",
2470        )
2471        .unwrap();
2472        fs::write(workspace.join("src/app.snap"), "updated\n").unwrap();
2473
2474        let sync = sync_command_outputs(&root, &workspace, &baseline, &BTreeSet::new()).unwrap();
2475
2476        assert_eq!(
2477            sync.skipped_instrumented,
2478            vec![PathBuf::from("src/bundle.js")]
2479        );
2480        assert_eq!(sync.synced, 1);
2481        assert_eq!(
2482            fs::read_to_string(root.join("src/app.snap")).unwrap(),
2483            "updated\n"
2484        );
2485        fs::remove_dir_all(root.parent().unwrap()).unwrap();
2486    }
2487
2488    #[test]
2489    fn paths_are_summarized_by_where_they_are() {
2490        let paths = [
2491            ".next/BUILD_ID",
2492            ".next/server/app.js",
2493            ".next/server/chunks/a.js",
2494            "tests/e2e/runs/1/report.json",
2495            "coverage/report.json",
2496            "playwright-report/index.html",
2497            "notes.txt",
2498            "out/a.txt",
2499        ]
2500        .map(PathBuf::from);
2501        assert_eq!(
2502            summarize_paths(&paths),
2503            ".next/ 3, coverage/ 1, notes.txt, out/ 1, 2 elsewhere"
2504        );
2505        assert_eq!(summarize_paths(&paths[..1]), ".next/ 1");
2506    }
2507
2508    #[test]
2509    fn a_report_that_quotes_the_runtime_does_not_make_its_directory_a_build() {
2510        // A failed Playwright test writes its stack, runtime frames included,
2511        // next to the screenshot and trace a developer opens to debug it.
2512        let (root, workspace) = writeback_fixture("report-quotes-runtime");
2513        let baseline = workspace_output_baseline(&workspace).unwrap();
2514        fs::create_dir_all(workspace.join("test-results/adds-an-item")).unwrap();
2515        fs::write(
2516            workspace.join("test-results/adds-an-item/error-context.md"),
2517            "at launch (/w/.supercov/node_modules/playwright.mjs:907:44)\n",
2518        )
2519        .unwrap();
2520        fs::write(
2521            workspace.join("test-results/adds-an-item/trace.zip"),
2522            "trace",
2523        )
2524        .unwrap();
2525
2526        let sync = sync_command_outputs(&root, &workspace, &baseline, &BTreeSet::new()).unwrap();
2527
2528        assert_eq!(
2529            sync.skipped_instrumented,
2530            vec![PathBuf::from("test-results/adds-an-item/error-context.md")]
2531        );
2532        assert_eq!(sync.synced, 1);
2533        assert!(root.join("test-results/adds-an-item/trace.zip").exists());
2534        fs::remove_dir_all(root.parent().unwrap()).unwrap();
2535    }
2536
2537    #[test]
2538    fn a_build_directory_git_ignores_stays_behind_even_when_the_project_has_one() {
2539        let (root, workspace) = writeback_fixture("built-ignored");
2540        let git = |arguments: &[&str]| {
2541            std::process::Command::new("git")
2542                .arg("-C")
2543                .arg(&root)
2544                .args(arguments)
2545                .output()
2546                .unwrap()
2547        };
2548        if !git(&["init", "-q"]).status.success() {
2549            fs::remove_dir_all(root.parent().unwrap()).unwrap();
2550            return;
2551        }
2552        fs::write(root.join(".gitignore"), ".next\n").unwrap();
2553        fs::create_dir_all(root.join(".next")).unwrap();
2554        fs::write(root.join(".next/BUILD_ID"), "mine\n").unwrap();
2555        let baseline = workspace_output_baseline(&workspace).unwrap();
2556        fs::create_dir_all(workspace.join(".next/server")).unwrap();
2557        fs::write(
2558            workspace.join(".next/server/chunk.js"),
2559            // Turbopack inlines the runtime: a chunk holds probe calls and
2560            // no path to it.
2561            "__supercovCoverageHitV3(__supercovProbeFileV2, 0);\n",
2562        )
2563        .unwrap();
2564        fs::write(workspace.join(".next/BUILD_ID"), "instrumented\n").unwrap();
2565
2566        let sync = sync_command_outputs(&root, &workspace, &baseline, &BTreeSet::new()).unwrap();
2567
2568        assert_eq!(sync.synced, 0);
2569        assert_eq!(sync.skipped_instrumented.len(), 2);
2570        assert_eq!(
2571            fs::read_to_string(root.join(".next/BUILD_ID")).unwrap(),
2572            "mine\n"
2573        );
2574        fs::remove_dir_all(root.parent().unwrap()).unwrap();
2575    }
2576
2577    #[test]
2578    fn a_minified_build_of_the_instrumented_copy_stays_in_the_workspace() {
2579        let (root, workspace) = writeback_fixture("built-minified");
2580        let initialized = std::process::Command::new("git")
2581            .arg("-C")
2582            .arg(&root)
2583            .args(["init", "-q"])
2584            .output()
2585            .unwrap();
2586        if !initialized.status.success() {
2587            fs::remove_dir_all(root.parent().unwrap()).unwrap();
2588            return;
2589        }
2590        fs::write(root.join(".gitignore"), "dist\n").unwrap();
2591        fs::create_dir_all(root.join("dist")).unwrap();
2592        fs::write(root.join("dist/index.html"), "mine\n").unwrap();
2593        let baseline = workspace_output_baseline(&workspace).unwrap();
2594        fs::create_dir_all(workspace.join("dist/assets")).unwrap();
2595        fs::write(
2596            workspace.join("dist/assets/index-DzZxFCVp.js"),
2597            // A minifier renames each probe's local name. The global they
2598            // are read from is a property name, which it leaves.
2599            "const e=globalThis.__SUPERCOV_DIRECT_RUNTIME__.coverageHitV2;e(t,0);\n",
2600        )
2601        .unwrap();
2602        fs::write(workspace.join("dist/index.html"), "instrumented\n").unwrap();
2603
2604        let sync = sync_command_outputs(&root, &workspace, &baseline, &BTreeSet::new()).unwrap();
2605
2606        assert_eq!(sync.synced, 0);
2607        assert_eq!(sync.skipped_instrumented.len(), 2);
2608        assert_eq!(
2609            fs::read_to_string(root.join("dist/index.html")).unwrap(),
2610            "mine\n"
2611        );
2612        fs::remove_dir_all(root.parent().unwrap()).unwrap();
2613    }
2614
2615    #[test]
2616    fn command_outputs_flow_back_to_the_project() {
2617        let (root, workspace) = writeback_fixture("outputs");
2618        let baseline = workspace_output_baseline(&workspace).unwrap();
2619        fs::create_dir_all(workspace.join("src/__snapshots__")).unwrap();
2620        fs::write(
2621            workspace.join("src/__snapshots__/app.snap"),
2622            "updated snapshot\n",
2623        )
2624        .unwrap();
2625        fs::write(workspace.join(".supercov/state.json"), "{\"changed\":1}").unwrap();
2626        let sync = sync_command_outputs(&root, &workspace, &baseline, &BTreeSet::new()).unwrap();
2627        assert_eq!(sync.synced, 1);
2628        assert_eq!(
2629            fs::read_to_string(root.join("src/__snapshots__/app.snap")).unwrap(),
2630            "updated snapshot\n"
2631        );
2632        assert!(!root.join(".supercov/state.json").exists());
2633        fs::remove_dir_all(root.parent().unwrap()).unwrap();
2634    }
2635
2636    #[test]
2637    fn instrumented_sources_never_flow_back() {
2638        let (root, workspace) = writeback_fixture("protected");
2639        let baseline = workspace_output_baseline(&workspace).unwrap();
2640        // A formatter run by the command rewrites the instrumented copy; the
2641        // real source must keep its original bytes.
2642        fs::write(workspace.join("src/app.ts"), "instrumented, reformatted\n").unwrap();
2643        let protected = BTreeSet::from([PathBuf::from("src/app.ts")]);
2644        let sync = sync_command_outputs(&root, &workspace, &baseline, &protected).unwrap();
2645        assert_eq!(sync.synced, 0);
2646        assert_eq!(sync.skipped_instrumented, [PathBuf::from("src/app.ts")]);
2647        assert_eq!(
2648            fs::read_to_string(root.join("src/app.ts")).unwrap(),
2649            "original\n"
2650        );
2651        fs::remove_dir_all(root.parent().unwrap()).unwrap();
2652    }
2653
2654    #[test]
2655    fn workspace_deletions_are_reported_but_never_propagated() {
2656        let (root, workspace) = writeback_fixture("deletions");
2657        fs::write(workspace.join("stale.txt"), "old\n").unwrap();
2658        fs::write(root.join("stale.txt"), "old\n").unwrap();
2659        // Gone from the workspace only: the project never had it.
2660        fs::write(workspace.join("built.txt"), "old\n").unwrap();
2661        let baseline = workspace_output_baseline(&workspace).unwrap();
2662        fs::remove_file(workspace.join("stale.txt")).unwrap();
2663        fs::remove_file(workspace.join("built.txt")).unwrap();
2664        let sync = sync_command_outputs(&root, &workspace, &baseline, &BTreeSet::new()).unwrap();
2665        assert_eq!(sync.deleted_in_workspace, [PathBuf::from("stale.txt")]);
2666        assert!(root.join("stale.txt").exists());
2667        fs::remove_dir_all(root.parent().unwrap()).unwrap();
2668    }
2669
2670    #[cfg(unix)]
2671    #[test]
2672    fn writeback_refuses_a_symlinked_destination() {
2673        let (root, workspace) = writeback_fixture("symlink");
2674        let outside = root.parent().unwrap().join("outside");
2675        fs::create_dir_all(&outside).unwrap();
2676        std::os::unix::fs::symlink(&outside, root.join("reports")).unwrap();
2677        let baseline = workspace_output_baseline(&workspace).unwrap();
2678        fs::create_dir_all(workspace.join("reports")).unwrap();
2679        fs::write(workspace.join("reports/result.txt"), "output\n").unwrap();
2680        let error =
2681            sync_command_outputs(&root, &workspace, &baseline, &BTreeSet::new()).unwrap_err();
2682        assert!(matches!(error, WorkspaceError::UnsafePath(_)));
2683        assert!(!outside.join("result.txt").exists());
2684        fs::remove_dir_all(root.parent().unwrap()).unwrap();
2685    }
2686
2687    struct OrdinaryCopyOperations;
2688
2689    impl WorkspaceOperations for OrdinaryCopyOperations {
2690        fn copy_file(&mut self, source: &Path, destination: &Path) -> Result<(), WorkspaceError> {
2691            fs::copy(source, destination)
2692                .map(|_| ())
2693                .map_err(|error| io_error(destination, error))
2694        }
2695
2696        fn rename(&mut self, source: &Path, destination: &Path) -> Result<(), WorkspaceError> {
2697            atomic_rename(source, destination).map_err(WorkspaceError::from)
2698        }
2699    }
2700
2701    struct FaultOperations {
2702        copy_count: usize,
2703        fail_copy_at: Option<usize>,
2704        rename_count: usize,
2705        fail_rename_at: Option<usize>,
2706    }
2707
2708    impl WorkspaceOperations for FaultOperations {
2709        fn copy_file(&mut self, source: &Path, destination: &Path) -> Result<(), WorkspaceError> {
2710            self.copy_count += 1;
2711            if self.fail_copy_at == Some(self.copy_count) {
2712                return Err(io_error(
2713                    destination,
2714                    io::Error::new(io::ErrorKind::StorageFull, "injected disk full"),
2715                ));
2716            }
2717            SystemWorkspaceOperations.copy_file(source, destination)
2718        }
2719
2720        fn rename(&mut self, source: &Path, destination: &Path) -> Result<(), WorkspaceError> {
2721            self.rename_count += 1;
2722            if self.fail_rename_at == Some(self.rename_count) {
2723                return Err(io_error(
2724                    destination,
2725                    io::Error::other("injected publication rename failure"),
2726                ));
2727            }
2728            SystemWorkspaceOperations.rename(source, destination)
2729        }
2730    }
2731
2732    fn transaction_debris(root: &Path) -> Vec<String> {
2733        let workspace = copy_path(root, 1).unwrap();
2734        let prefix = format!(".{}.", project_name(root).unwrap().to_string_lossy());
2735        fs::read_dir(workspace.parent().unwrap())
2736            .unwrap()
2737            .filter_map(Result::ok)
2738            .map(|entry| entry.file_name().to_string_lossy().into_owned())
2739            .filter(|name| name.starts_with(&prefix))
2740            .collect()
2741    }
2742
2743    fn project() -> PathBuf {
2744        let root = std::env::temp_dir().join(format!("supercov-workspace-rust-{}", unique()));
2745        fs::create_dir_all(root.join("src")).unwrap();
2746        fs::write(root.join("src/index.js"), "one").unwrap();
2747        fs::write(root.join("package.json"), "{}").unwrap();
2748        root
2749    }
2750
2751    #[test]
2752    #[cfg(unix)]
2753    fn root_node_modules_symlink_is_followed() {
2754        // pnpm layouts often make the project's node_modules a symlink into an
2755        // external store. Refusing it forced a 3.7 GB manual materialisation;
2756        // entries are linked to absolute targets regardless, so following the
2757        // root link is isolation-neutral.
2758        let root = project();
2759        let store = std::env::temp_dir().join(format!("supercov-store-{}", unique()));
2760        fs::create_dir_all(store.join("left-pad")).unwrap();
2761        fs::write(store.join("left-pad/package.json"), "{}").unwrap();
2762        std::os::unix::fs::symlink(&store, root.join("node_modules")).unwrap();
2763        let mut lock = ProjectLock::acquire(&root, "run", "now").unwrap();
2764        let workspace = prepare_isolated_workspace(&root, "run", &lock).unwrap();
2765        assert!(
2766            fs::symlink_metadata(workspace.join("node_modules/left-pad"))
2767                .unwrap()
2768                .file_type()
2769                .is_symlink()
2770        );
2771        lock.release().unwrap();
2772        fs::remove_dir_all(root).unwrap();
2773        fs::remove_dir_all(store).unwrap();
2774    }
2775
2776    #[test]
2777    fn a_package_copy_sits_where_the_package_is_in_its_repository() {
2778        // skyhook-io/radar's Playwright config in web/ starts its server with
2779        // `go run ../cmd/testserver`, which a copy of web/ alone did not have.
2780        let repository = project();
2781        fs::create_dir_all(repository.join(".git")).unwrap();
2782        fs::create_dir_all(repository.join("cmd/testserver")).unwrap();
2783        fs::write(repository.join("cmd/testserver/main.go"), "package main\n").unwrap();
2784        fs::write(repository.join("tsconfig.base.json"), "{}").unwrap();
2785        fs::write(repository.join("package-lock.json"), "{}").unwrap();
2786        let root = repository.join("packages/web");
2787        fs::create_dir_all(root.join("src")).unwrap();
2788        fs::write(root.join("src/app.js"), "export {};\n").unwrap();
2789        fs::create_dir_all(repository.join("packages/ui")).unwrap();
2790        let mut lock = ProjectLock::acquire(&root, "run", "now").unwrap();
2791        let workspace = prepare_isolated_workspace(&root, "run", &lock).unwrap();
2792        let name = repository.file_name().unwrap();
2793        assert!(workspace.ends_with(Path::new(name).join("packages/web")));
2794        assert!(workspace.join("src/app.js").is_file());
2795        assert_eq!(
2796            fs::read_to_string(workspace.join("../../cmd/testserver/main.go")).unwrap(),
2797            "package main\n"
2798        );
2799        assert!(workspace.join("../../tsconfig.base.json").is_file());
2800        assert!(workspace.join("../ui").is_dir());
2801        // The repository's .git is never shared with a test, and its
2802        // lockfile is not there to be found twice.
2803        assert!(fs::symlink_metadata(workspace.join("../../.git")).is_err());
2804        assert!(fs::symlink_metadata(workspace.join("../../package-lock.json")).is_err());
2805        lock.release().unwrap();
2806        fs::remove_dir_all(repository).unwrap();
2807    }
2808
2809    #[test]
2810    #[cfg(unix)]
2811    fn dangling_symlinks_are_preserved_and_escaping_ones_still_refused() {
2812        // npm and pnpm workspaces routinely leave symlinks to packages that
2813        // are not installed. superinterface's examples/*/node_modules carried
2814        // one, plain `npm test` never resolves it, and the mirror died on
2815        // `canonicalize` with ENOENT before any test ran. A dangling link
2816        // resolves to nothing, so it can leak nothing: it is preserved as-is,
2817        // while the lexical containment check still applies.
2818        let root = project();
2819        let nested = root.join("examples/app/node_modules/@scope");
2820        fs::create_dir_all(&nested).unwrap();
2821        std::os::unix::fs::symlink(
2822            "../../../../packages/react/node_modules/@scope/pkg",
2823            nested.join("pkg"),
2824        )
2825        .unwrap();
2826        let mut lock = ProjectLock::acquire(&root, "run", "now").unwrap();
2827        let workspace = prepare_isolated_workspace(&root, "run", &lock).unwrap();
2828        let mirrored = workspace.join("examples/app/node_modules/@scope/pkg");
2829        let metadata = fs::symlink_metadata(&mirrored).unwrap();
2830        assert!(metadata.file_type().is_symlink());
2831        assert_eq!(
2832            fs::read_link(&mirrored).unwrap(),
2833            PathBuf::from("../../../../packages/react/node_modules/@scope/pkg")
2834        );
2835        lock.release().unwrap();
2836        fs::remove_dir_all(root).unwrap();
2837    }
2838
2839    #[test]
2840    #[cfg(target_os = "macos")]
2841    fn nested_node_modules_are_cloned_not_linked() {
2842        // A suite that mounts the workspace into a VM sees no host paths, so
2843        // entry links into the original tree dangle there and npm fails to
2844        // re-link them across the mount. APFS clones the directory instead:
2845        // real files, relative links inside kept verbatim, and writes staying
2846        // in the workspace.
2847        let root = project();
2848        let nested = root.join("packages/app/node_modules");
2849        fs::create_dir_all(nested.join("dep")).unwrap();
2850        fs::create_dir_all(nested.join(".bin")).unwrap();
2851        fs::write(nested.join("dep/index.js"), "dep").unwrap();
2852        std::os::unix::fs::symlink("../dep/index.js", nested.join(".bin/dep")).unwrap();
2853        let mut lock = ProjectLock::acquire(&root, "run", "now").unwrap();
2854        let workspace = prepare_isolated_workspace(&root, "run", &lock).unwrap();
2855        let mirrored = workspace.join("packages/app/node_modules");
2856        assert!(
2857            fs::symlink_metadata(mirrored.join("dep"))
2858                .unwrap()
2859                .file_type()
2860                .is_dir()
2861        );
2862        assert_eq!(
2863            fs::read_to_string(mirrored.join("dep/index.js")).unwrap(),
2864            "dep"
2865        );
2866        assert_eq!(
2867            fs::read_link(mirrored.join(".bin/dep")).unwrap(),
2868            PathBuf::from("../dep/index.js")
2869        );
2870        fs::write(mirrored.join("dep/index.js"), "changed in the workspace").unwrap();
2871        assert_eq!(
2872            fs::read_to_string(nested.join("dep/index.js")).unwrap(),
2873            "dep"
2874        );
2875        lock.release().unwrap();
2876        fs::remove_dir_all(root).unwrap();
2877    }
2878
2879    #[test]
2880    #[cfg(unix)]
2881    fn hard_linked_dependency_tree_is_real_and_replaceable() {
2882        // The Linux materialisation: files share inodes with the originals,
2883        // symlinks are carried verbatim, and replacing an entry in the
2884        // workspace (npm's reify) leaves the user's tree untouched.
2885        use std::os::unix::fs::MetadataExt;
2886        let base = std::env::temp_dir().join(format!("supercov-hardlink-{}", unique()));
2887        let source = base.join("node_modules");
2888        fs::create_dir_all(source.join("dep")).unwrap();
2889        fs::create_dir_all(source.join(".bin")).unwrap();
2890        fs::write(source.join("dep/index.js"), "dep").unwrap();
2891        std::os::unix::fs::symlink("../dep/index.js", source.join(".bin/dep")).unwrap();
2892        let destination = base.join("workspace/node_modules");
2893        fs::create_dir_all(destination.parent().unwrap()).unwrap();
2894        assert!(hard_link_tree(&source, &destination));
2895        assert_eq!(
2896            fs::metadata(destination.join("dep/index.js"))
2897                .unwrap()
2898                .ino(),
2899            fs::metadata(source.join("dep/index.js")).unwrap().ino()
2900        );
2901        assert_eq!(
2902            fs::read_link(destination.join(".bin/dep")).unwrap(),
2903            PathBuf::from("../dep/index.js")
2904        );
2905        fs::remove_dir_all(destination.join("dep")).unwrap();
2906        fs::create_dir_all(destination.join("dep")).unwrap();
2907        fs::write(destination.join("dep/index.js"), "replaced").unwrap();
2908        assert_eq!(
2909            fs::read_to_string(source.join("dep/index.js")).unwrap(),
2910            "dep"
2911        );
2912        fs::remove_dir_all(base).unwrap();
2913    }
2914
2915    #[test]
2916    #[cfg(unix)]
2917    fn symlink_escaping_the_project_is_omitted_from_the_mirror() {
2918        // The escape check guards the MIRRORED source tree. node_modules (root
2919        // and nested) are linked or cloned from the user's originals instead,
2920        // so the escaping fixture lives outside node_modules here.
2921        // Leftover tool state (a Chrome test profile linking into /tmp) must
2922        // not abort measurement: the entry is omitted and the run proceeds.
2923        let root = project();
2924        let nested = root.join("examples/app/lib");
2925        fs::create_dir_all(&nested).unwrap();
2926        std::os::unix::fs::symlink("../../../../../outside-the-project/pkg", nested.join("pkg"))
2927            .unwrap();
2928        let mut lock = ProjectLock::acquire(&root, "run", "now").unwrap();
2929        let workspace = prepare_isolated_workspace(&root, "run", &lock).unwrap();
2930        assert!(fs::symlink_metadata(workspace.join("examples/app/lib/pkg")).is_err());
2931        assert!(workspace.join("src/index.js").exists());
2932        lock.release().unwrap();
2933        fs::remove_dir_all(root).unwrap();
2934    }
2935
2936    #[test]
2937    fn isolated_copy_never_changes_source_and_requires_the_lock() {
2938        let root = project();
2939        let mut lock = ProjectLock::acquire(&root, "run", "now").unwrap();
2940        let workspace = prepare_isolated_workspace(&root, "run", &lock).unwrap();
2941        fs::write(workspace.join("src/index.js"), "instrumented").unwrap();
2942        assert_eq!(
2943            fs::read_to_string(root.join("src/index.js")).unwrap(),
2944            "one"
2945        );
2946        lock.release().unwrap();
2947        assert!(matches!(
2948            prepare_isolated_workspace(&root, "other", &lock),
2949            Err(WorkspaceError::MissingLock)
2950        ));
2951        fs::remove_dir_all(root).unwrap();
2952    }
2953
2954    #[test]
2955    fn everything_supercov_writes_lives_under_the_store() {
2956        let root = project();
2957        assert_eq!(
2958            workspace_container(&root),
2959            root.join(".supercov/workspaces")
2960        );
2961        let mut lock = ProjectLock::acquire(&root, "run", "now").unwrap();
2962        let workspace = prepare_cached_workspace(&root, &lock, &[]).unwrap();
2963        assert!(workspace.starts_with(root.join(".supercov")));
2964        assert_eq!(
2965            fs::read_to_string(root.join(".supercov/.gitignore")).unwrap(),
2966            "*\n"
2967        );
2968        lock.release().unwrap();
2969        fs::remove_dir_all(root).unwrap();
2970    }
2971
2972    #[test]
2973    fn an_unowned_container_gets_a_deterministic_fallback() {
2974        let root = project();
2975        fs::create_dir_all(root.join(".supercov/workspaces")).unwrap();
2976        fs::write(root.join(".supercov/workspaces/user-file"), "mine\n").unwrap();
2977        let container = workspace_container(&root);
2978        assert_ne!(container, root.join(".supercov/workspaces"));
2979        let name = container
2980            .file_name()
2981            .unwrap()
2982            .to_string_lossy()
2983            .into_owned();
2984        assert!(name.starts_with("workspaces-"));
2985        fs::remove_dir_all(root).unwrap();
2986    }
2987
2988    #[test]
2989    fn user_supercov_directory_is_copied_and_never_adopted() {
2990        let root = project();
2991        fs::create_dir(root.join("supercov")).unwrap();
2992        fs::write(root.join("supercov/user-module.js"), "export default 1;\n").unwrap();
2993        let mut lock = ProjectLock::acquire(&root, "run", "now").unwrap();
2994        let workspace = prepare_cached_workspace(&root, &lock, &[]).unwrap();
2995        assert_ne!(workspace_container(&root), root.join("supercov"));
2996        assert_eq!(
2997            fs::read_to_string(workspace.join("supercov/user-module.js")).unwrap(),
2998            "export default 1;\n"
2999        );
3000        assert_eq!(
3001            fs::read_to_string(root.join("supercov/user-module.js")).unwrap(),
3002            "export default 1;\n"
3003        );
3004        assert!(!root.join("supercov").join(WORKSPACE_MARKER).exists());
3005        lock.release().unwrap();
3006        fs::remove_dir_all(root).unwrap();
3007    }
3008
3009    #[cfg(unix)]
3010    #[test]
3011    fn stable_cache_refreshes_atomically_and_reuses_only_explicit_artifacts() {
3012        let root = project();
3013        let mut lock = ProjectLock::acquire(&root, "run", "now").unwrap();
3014        let first = prepare_cached_workspace(&root, &lock, &[]).unwrap();
3015        fs::create_dir_all(first.join("build")).unwrap();
3016        fs::write(first.join("build/output.js"), "instrumented").unwrap();
3017        fs::write(first.join("stale.txt"), "stale").unwrap();
3018        fs::write(root.join("src/index.js"), "two").unwrap();
3019        let second = prepare_cached_workspace(&root, &lock, &[PathBuf::from("build")]).unwrap();
3020        assert_eq!(first, second);
3021        assert_eq!(
3022            fs::read_to_string(second.join("src/index.js")).unwrap(),
3023            "two"
3024        );
3025        assert_eq!(
3026            fs::read_to_string(second.join("build/output.js")).unwrap(),
3027            "instrumented"
3028        );
3029        assert!(!second.join("stale.txt").exists());
3030        lock.release().unwrap();
3031        fs::remove_dir_all(root).unwrap();
3032    }
3033
3034    #[test]
3035    fn reused_artifact_replaces_the_mirrored_stale_copy_wholesale() {
3036        let root = project();
3037        fs::create_dir_all(root.join("packages/app/dist")).unwrap();
3038        fs::write(root.join("packages/app/dist/stale.js"), "uninstrumented").unwrap();
3039        let mut lock = ProjectLock::acquire(&root, "run", "now").unwrap();
3040        let first = prepare_cached_workspace(&root, &lock, &[]).unwrap();
3041        fs::remove_file(first.join("packages/app/dist/stale.js")).unwrap();
3042        fs::write(first.join("packages/app/dist/built.js"), "instrumented").unwrap();
3043        let second =
3044            prepare_cached_workspace(&root, &lock, &[PathBuf::from("packages/app/dist")]).unwrap();
3045        assert_eq!(
3046            fs::read_to_string(second.join("packages/app/dist/built.js")).unwrap(),
3047            "instrumented"
3048        );
3049        assert!(!second.join("packages/app/dist/stale.js").exists());
3050        lock.release().unwrap();
3051        fs::remove_dir_all(root).unwrap();
3052    }
3053
3054    #[test]
3055    fn terminal_workspace_keeps_flat_frontend_cache_without_discoverable_test_sources() {
3056        let root = project();
3057        fs::create_dir_all(root.join("tests/e2e")).unwrap();
3058        fs::write(root.join("tests/e2e/app.spec.js"), "test source").unwrap();
3059        let mut lock = ProjectLock::acquire(&root, "run", "now").unwrap();
3060        let workspace = prepare_cached_workspace(&root, &lock, &[]).unwrap();
3061        let artifacts = workspace.join(".supercov/frontend-cache-artifacts");
3062        fs::create_dir_all(&artifacts).unwrap();
3063        fs::write(artifacts.join("digest"), "instrumented test").unwrap();
3064        fs::write(
3065            workspace.join(".supercov/frontend-cache.json"),
3066            "{\"schemaVersion\":2}",
3067        )
3068        .unwrap();
3069        prune_cached_workspace_sources(&root, &lock).unwrap();
3070        assert!(!workspace.join("tests/e2e/app.spec.js").exists());
3071        assert_eq!(
3072            fs::read_to_string(artifacts.join("digest")).unwrap(),
3073            "instrumented test"
3074        );
3075        lock.release().unwrap();
3076        fs::remove_dir_all(root).unwrap();
3077    }
3078
3079    #[test]
3080    fn ordinary_copy_fallback_preserves_workspace_semantics() {
3081        let root = project();
3082        let mut lock = ProjectLock::acquire(&root, "run", "now").unwrap();
3083        let mut operations = OrdinaryCopyOperations;
3084        let workspace =
3085            prepare_cached_workspace_with_operations(&root, &lock, &[], &mut operations).unwrap();
3086        assert_eq!(
3087            fs::read_to_string(workspace.join("src/index.js")).unwrap(),
3088            "one"
3089        );
3090        assert_eq!(
3091            fs::read_to_string(root.join("src/index.js")).unwrap(),
3092            "one"
3093        );
3094        assert!(transaction_debris(&root).is_empty());
3095        lock.release().unwrap();
3096        fs::remove_dir_all(root).unwrap();
3097    }
3098
3099    #[test]
3100    fn enospc_during_copy_preserves_the_complete_generation() {
3101        let root = project();
3102        let mut lock = ProjectLock::acquire(&root, "run", "now").unwrap();
3103        let workspace = prepare_cached_workspace(&root, &lock, &[]).unwrap();
3104        fs::write(workspace.join("generation"), "complete").unwrap();
3105        fs::write(root.join("src/index.js"), "new source").unwrap();
3106        let mut operations = FaultOperations {
3107            copy_count: 0,
3108            fail_copy_at: Some(1),
3109            rename_count: 0,
3110            fail_rename_at: None,
3111        };
3112        let error = prepare_cached_workspace_with_operations(&root, &lock, &[], &mut operations)
3113            .unwrap_err();
3114        assert!(matches!(
3115            error,
3116            WorkspaceError::Io { ref source, .. }
3117                if source.kind() == io::ErrorKind::StorageFull
3118        ));
3119        assert_eq!(
3120            fs::read_to_string(workspace.join("generation")).unwrap(),
3121            "complete"
3122        );
3123        assert_eq!(
3124            fs::read_to_string(workspace.join("src/index.js")).unwrap(),
3125            "one"
3126        );
3127        assert!(transaction_debris(&root).is_empty());
3128        lock.release().unwrap();
3129        fs::remove_dir_all(root).unwrap();
3130    }
3131
3132    #[test]
3133    fn failed_publication_rename_restores_the_complete_generation() {
3134        let root = project();
3135        let mut lock = ProjectLock::acquire(&root, "run", "now").unwrap();
3136        let workspace = prepare_cached_workspace(&root, &lock, &[]).unwrap();
3137        fs::write(workspace.join("generation"), "complete").unwrap();
3138        fs::write(root.join("src/index.js"), "new source").unwrap();
3139        let mut operations = FaultOperations {
3140            copy_count: 0,
3141            fail_copy_at: None,
3142            rename_count: 0,
3143            fail_rename_at: Some(2),
3144        };
3145        let error = prepare_cached_workspace_with_operations(&root, &lock, &[], &mut operations)
3146            .unwrap_err();
3147        assert!(matches!(
3148            error,
3149            WorkspaceError::Io { ref source, .. }
3150                if source.kind() == io::ErrorKind::Other
3151        ));
3152        assert_eq!(
3153            operations.rename_count, 3,
3154            "prior generation was not restored"
3155        );
3156        assert_eq!(
3157            fs::read_to_string(workspace.join("generation")).unwrap(),
3158            "complete"
3159        );
3160        assert_eq!(
3161            fs::read_to_string(workspace.join("src/index.js")).unwrap(),
3162            "one"
3163        );
3164        assert!(transaction_debris(&root).is_empty());
3165        lock.release().unwrap();
3166        fs::remove_dir_all(root).unwrap();
3167    }
3168
3169    #[cfg(unix)]
3170    #[test]
3171    fn relocates_internal_links_and_rejects_external_links() {
3172        use std::os::unix::fs::symlink;
3173
3174        let root = project();
3175        fs::create_dir_all(root.join("shared")).unwrap();
3176        fs::write(root.join("shared/value"), "inside").unwrap();
3177        symlink("../shared/value", root.join("src/value-link")).unwrap();
3178        let external = project();
3179        fs::write(external.join("outside"), "outside").unwrap();
3180        let mut lock = ProjectLock::acquire(&root, "run", "now").unwrap();
3181        let workspace = prepare_cached_workspace(&root, &lock, &[]).unwrap();
3182        assert_eq!(
3183            fs::read_to_string(workspace.join("src/value-link")).unwrap(),
3184            "inside"
3185        );
3186        symlink(external.join("outside"), root.join("src/external-link")).unwrap();
3187        let refreshed = prepare_cached_workspace(&root, &lock, &[]).unwrap();
3188        assert!(fs::symlink_metadata(refreshed.join("src/external-link")).is_err());
3189        assert_eq!(
3190            fs::read_to_string(workspace.join("src/index.js")).unwrap(),
3191            "one"
3192        );
3193        lock.release().unwrap();
3194        fs::remove_dir_all(root).unwrap();
3195        fs::remove_dir_all(external).unwrap();
3196    }
3197
3198    #[cfg(windows)]
3199    #[test]
3200    fn relocates_internal_junctions_without_symlink_privileges() {
3201        let root = project();
3202        fs::create_dir_all(root.join("shared")).unwrap();
3203        fs::write(root.join("shared/value"), "inside").unwrap();
3204        junction::create(root.join("shared"), root.join("linked-shared")).unwrap();
3205        let mut lock = ProjectLock::acquire(&root, "run", "now").unwrap();
3206        let workspace = prepare_cached_workspace(&root, &lock, &[]).unwrap();
3207        let isolated_link = workspace.join("linked-shared");
3208        assert!(junction::exists(&isolated_link).unwrap());
3209        assert_eq!(
3210            canonicalize_simplified(junction::get_target(&isolated_link).unwrap()).unwrap(),
3211            canonicalize_simplified(workspace.join("shared")).unwrap()
3212        );
3213        assert_eq!(
3214            fs::read_to_string(isolated_link.join("value")).unwrap(),
3215            "inside"
3216        );
3217        lock.release().unwrap();
3218        fs::remove_dir_all(root).unwrap();
3219    }
3220
3221    #[cfg(windows)]
3222    #[test]
3223    fn mounts_node_modules_with_junctions_and_copies_metadata_files() {
3224        let root = project();
3225        fs::create_dir_all(root.join("node_modules/example")).unwrap();
3226        fs::write(root.join("node_modules/example/index.js"), "module").unwrap();
3227        fs::write(root.join("node_modules/.package-lock.json"), "lock").unwrap();
3228        let mut lock = ProjectLock::acquire(&root, "run", "now").unwrap();
3229        let workspace = prepare_cached_workspace(&root, &lock, &[]).unwrap();
3230        let package = workspace.join("node_modules/example");
3231        assert!(junction::exists(&package).unwrap());
3232        assert_eq!(
3233            canonicalize_simplified(junction::get_target(&package).unwrap()).unwrap(),
3234            canonicalize_simplified(root.join("node_modules/example")).unwrap()
3235        );
3236        let metadata = workspace.join("node_modules/.package-lock.json");
3237        assert!(fs::symlink_metadata(&metadata).unwrap().is_file());
3238        assert_eq!(fs::read_to_string(metadata).unwrap(), "lock");
3239        lock.release().unwrap();
3240        fs::remove_dir_all(root).unwrap();
3241    }
3242
3243    #[test]
3244    fn recovery_restores_the_newest_previous_generation_and_discards_staging() {
3245        let root = project();
3246        let mut lock = ProjectLock::acquire(&root, "run", "now").unwrap();
3247        ensure_container(&root).unwrap();
3248        let workspace = cached_workspace_path(&root, &lock).unwrap();
3249        let parent = workspace.parent().unwrap();
3250        fs::create_dir_all(parent).unwrap();
3251        let previous = parent.join(format!(
3252            "{}old",
3253            transaction_prefix(&root, "previous").unwrap()
3254        ));
3255        let staging = parent.join(format!(
3256            "{}new",
3257            transaction_prefix(&root, "staging").unwrap()
3258        ));
3259        fs::create_dir_all(&previous).unwrap();
3260        fs::write(previous.join("complete"), "yes").unwrap();
3261        fs::create_dir_all(&staging).unwrap();
3262        let result = recover_cached_workspace(&root, &lock).unwrap();
3263        assert!(result.restored_previous);
3264        assert_eq!(result.removed_staging, 1);
3265        assert_eq!(
3266            fs::read_to_string(workspace.join("complete")).unwrap(),
3267            "yes"
3268        );
3269        lock.release().unwrap();
3270        fs::remove_dir_all(root).unwrap();
3271    }
3272}