Skip to main content

fallow_engine/
repo_refs.rs

1//! Engine-owned repository reference probes and temporary repo views.
2
3use std::fs::{self, File, OpenOptions};
4use std::io::{BufRead, BufReader, Read, Write};
5use std::path::{Component, Path, PathBuf};
6use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
7use std::sync::atomic::{AtomicU64, Ordering};
8use std::time::SystemTime;
9
10use fallow_config::WorkspaceInfo;
11use fallow_types::audit_cache::{
12    AuditContextDirectoryFingerprint, AuditContextFileFingerprint, AuditContextPathState,
13    AuditMaterializedContextFingerprint,
14};
15use fallow_types::source_fingerprint::SourceFingerprint;
16use xxhash_rust::xxh3::xxh3_64;
17
18use crate::{EngineError, EngineResult};
19
20use crate::base_worktree_context::{
21    AUDIT_CONTEXT_FILE_MAX_BYTES, AUDIT_MATERIALIZED_CONTEXT_DIRS, SVELTE_KIT_DIR,
22    base_has_slot_parent, context_markers, copy_generated_tsconfig,
23};
24pub use crate::base_worktree_orphans::*;
25pub use crate::base_worktree_registration::*;
26
27const RAW_MATERIALIZATION_MARKER: &str = "fallow-raw-materialized-v1";
28
29const AUDIT_LOCKFILES: &[&str] = &[
30    "package-lock.json",
31    "npm-shrinkwrap.json",
32    "pnpm-lock.yaml",
33    "yarn.lock",
34    "bun.lock",
35    "bun.lockb",
36];
37
38const CONTEXT_SYMLINK_STATE: &str = "symlink";
39const CONTEXT_SPECIAL_FILE_STATE: &str = "not_regular_file";
40const CONTEXT_OVERSIZED_FILE_STATE: &str = "file_too_large";
41const CONTEXT_PARENT_UNAVAILABLE_STATE: &str = "parent_context_unavailable";
42const CONTEXT_CHANGED_DURING_READ_STATE: &str = "changed_during_read";
43
44// The flag values differ per architecture (aarch64 Linux uses 0x8000 for
45// O_NOFOLLOW, x86-64 uses 0x20000), so they must come from libc.
46#[cfg(any(
47    target_os = "linux",
48    target_os = "android",
49    target_os = "macos",
50    target_os = "ios",
51    target_os = "freebsd",
52    target_os = "dragonfly",
53    target_os = "openbsd",
54    target_os = "netbsd"
55))]
56const UNIX_CONTEXT_OPEN_FLAGS: i32 = libc::O_NOFOLLOW | libc::O_NONBLOCK;
57
58#[cfg(windows)]
59const WINDOWS_FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
60#[cfg(windows)]
61const WINDOWS_FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400;
62
63/// Resolved base ref for changed-code audit.
64#[derive(Debug, Clone)]
65pub struct ResolvedAuditBase {
66    /// Git ref or SHA used for comparison.
67    pub git_ref: String,
68    /// Human-readable source of the resolved ref.
69    pub description: Option<String>,
70    /// Commits of the remote default branch that the change merged after
71    /// `git_ref`. A finding that one of them has is inherited, not
72    /// introduced. Only an auto-detected base has them.
73    pub inherited_refs: Vec<String>,
74}
75
76/// Temporary detached snapshot for comparing audit results against a base ref.
77/// [`Self::create`] deregisters it from Git, and `Drop` removes the directory.
78#[derive(Debug)]
79pub struct TemporaryBaseWorktree {
80    path: PathBuf,
81}
82
83impl TemporaryBaseWorktree {
84    /// Create a detached base worktree for `base_ref`.
85    ///
86    /// `workspace_patterns` are the `workspaces.patterns` of the resolved
87    /// config. They add packages beyond the manifests, and the base view
88    /// must link the generated context of those packages too.
89    ///
90    /// # Errors
91    ///
92    /// Returns an engine error when the temp path cannot be generated, `git`
93    /// cannot be started, or the worktree cannot be created or deregistered.
94    pub fn create(
95        repo_root: &Path,
96        base_ref: &str,
97        workspace_patterns: &[String],
98    ) -> EngineResult<Self> {
99        sweep_orphan_audit_worktrees(repo_root);
100        let path = base_worktree_path()?;
101        create_detached_base_worktree(repo_root, &path, base_ref)?;
102        if let Err(error) = deregister_base_worktree(repo_root, &path) {
103            remove_registered_worktree(repo_root, &path);
104            let _ = fs::remove_dir_all(&path);
105            return Err(EngineError::new(format!(
106                "could not deregister the temporary worktree for base ref `{base_ref}`: {error}"
107            )));
108        }
109        let worktree = Self { path };
110        materialize_base_dependency_context(repo_root, &worktree.path, workspace_patterns);
111        Ok(worktree)
112    }
113
114    /// Path to the detached worktree.
115    #[must_use]
116    pub fn path(&self) -> &Path {
117        &self.path
118    }
119}
120
121/// Share dependency and generated context from the host checkout with a base view.
122///
123/// `workspace_patterns` are the `workspaces.patterns` of the resolved config.
124pub fn materialize_base_dependency_context(
125    repo_root: &Path,
126    worktree_path: &Path,
127    workspace_patterns: &[String],
128) {
129    for slot in audit_materialized_context_slots(repo_root, workspace_patterns) {
130        let Ok(source) = canonical_context_directory(&slot.source) else {
131            continue;
132        };
133
134        if !base_has_slot_parent(worktree_path, slot.kind, &slot.relative)
135            || validate_materialized_path(&slot.relative).is_err()
136            || create_safe_parent_directories(worktree_path, &slot.relative).is_err()
137        {
138            continue;
139        }
140        let destination = worktree_path.join(&slot.relative);
141        if slot.kind == SVELTE_KIT_DIR {
142            let _ = copy_generated_tsconfig(&source, &destination);
143            continue;
144        }
145        match fs::symlink_metadata(&destination) {
146            Ok(metadata) if metadata.file_type().is_dir() => continue,
147            Ok(metadata) if metadata.file_type().is_symlink() => {
148                if fs::remove_file(&destination).is_err() {
149                    continue;
150                }
151            }
152            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
153            Ok(_) | Err(_) => continue,
154        }
155
156        let _ = symlink_dependency_dir(&source, &destination);
157    }
158}
159
160/// Build a bounded fingerprint of the host context materialized into a base view.
161///
162/// `workspace_patterns` must be the patterns that the base view gets, so the
163/// fingerprint covers each directory that the base view links.
164#[must_use]
165pub fn audit_materialized_context_fingerprint(
166    root: &Path,
167    workspace_patterns: &[String],
168) -> AuditMaterializedContextFingerprint {
169    let lockfiles = AUDIT_LOCKFILES
170        .iter()
171        .map(|name| fingerprint_context_file(root, &root.join(name)))
172        .collect();
173    let directories = audit_materialized_context_slots(root, workspace_patterns)
174        .iter()
175        .map(fingerprint_context_directory)
176        .collect();
177    AuditMaterializedContextFingerprint {
178        lockfiles,
179        directories,
180    }
181}
182
183#[derive(Debug)]
184struct AuditMaterializedContextSlot {
185    kind: &'static str,
186    relative: PathBuf,
187    source: PathBuf,
188}
189
190fn audit_materialized_context_slots(
191    root: &Path,
192    workspace_patterns: &[String],
193) -> Vec<AuditMaterializedContextSlot> {
194    let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
195    let mut slots = AUDIT_MATERIALIZED_CONTEXT_DIRS
196        .iter()
197        .map(|&kind| AuditMaterializedContextSlot {
198            kind,
199            relative: PathBuf::from(kind),
200            source: canonical_root.join(kind),
201        })
202        .collect::<Vec<_>>();
203
204    for workspace in
205        crate::discover::discover_workspace_packages_with_patterns(root, workspace_patterns)
206    {
207        let Ok(canonical_workspace) = dunce::canonicalize(&workspace.root) else {
208            continue;
209        };
210        let Ok(relative_workspace) = canonical_workspace.strip_prefix(&canonical_root) else {
211            continue;
212        };
213        if relative_workspace.as_os_str().is_empty() {
214            continue;
215        }
216        for &kind in AUDIT_MATERIALIZED_CONTEXT_DIRS {
217            slots.push(AuditMaterializedContextSlot {
218                kind,
219                relative: relative_workspace.join(kind),
220                source: canonical_workspace.join(kind),
221            });
222        }
223    }
224
225    slots.sort_by(|left, right| left.relative.cmp(&right.relative));
226    slots.dedup_by(|left, right| left.relative == right.relative);
227    slots
228}
229
230fn fingerprint_context_directory(
231    slot: &AuditMaterializedContextSlot,
232) -> AuditContextDirectoryFingerprint {
233    let path = &slot.source;
234    let (state, canonical_path, source) = match canonical_context_directory(path) {
235        Ok(canonical_path) => {
236            let source = fs::symlink_metadata(&canonical_path)
237                .ok()
238                .as_ref()
239                .map(SourceFingerprint::from_metadata);
240            (AuditContextPathState::Present, Some(canonical_path), source)
241        }
242        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
243            (AuditContextPathState::Missing, None, None)
244        }
245        Err(error) => (
246            AuditContextPathState::Unreadable(error.kind().to_string()),
247            None,
248            fs::symlink_metadata(path)
249                .ok()
250                .as_ref()
251                .map(SourceFingerprint::from_metadata),
252        ),
253    };
254    let canonical_path_display = canonical_path
255        .as_ref()
256        .map(|path| path.to_string_lossy().replace('\\', "/"));
257    let markers = context_markers(slot.kind)
258        .iter()
259        .map(|marker| {
260            let relative = slot
261                .relative
262                .join(marker)
263                .to_string_lossy()
264                .replace('\\', "/");
265            canonical_path.as_ref().map_or_else(
266                || unavailable_context_file(&relative, &state),
267                |path| fingerprint_context_file_at(&path.join(marker), &relative),
268            )
269        })
270        .collect();
271    AuditContextDirectoryFingerprint {
272        name: slot.relative.to_string_lossy().replace('\\', "/"),
273        state,
274        canonical_path: canonical_path_display,
275        source,
276        markers,
277    }
278}
279
280fn canonical_context_directory(path: &Path) -> std::io::Result<PathBuf> {
281    let canonical_path = dunce::canonicalize(path)?;
282    match fs::symlink_metadata(&canonical_path) {
283        Ok(metadata) if metadata.file_type().is_dir() => Ok(canonical_path),
284        Ok(_) => Err(std::io::Error::new(
285            std::io::ErrorKind::InvalidInput,
286            CONTEXT_SPECIAL_FILE_STATE,
287        )),
288        Err(error) => Err(error),
289    }
290}
291
292fn fingerprint_context_file(root: &Path, path: &Path) -> AuditContextFileFingerprint {
293    let relative = path
294        .strip_prefix(root)
295        .unwrap_or(path)
296        .to_string_lossy()
297        .replace('\\', "/");
298    fingerprint_context_file_at(path, &relative)
299}
300
301fn fingerprint_context_file_at(path: &Path, relative: &str) -> AuditContextFileFingerprint {
302    fingerprint_context_file_at_with_hooks(path, relative, || {}, || {})
303}
304
305fn fingerprint_context_file_at_with_hooks(
306    path: &Path,
307    relative: &str,
308    before_open: impl FnOnce(),
309    after_read: impl FnOnce(),
310) -> AuditContextFileFingerprint {
311    before_open();
312    let mut file = match open_context_file(path) {
313        Ok(file) => file,
314        Err(error) => return classify_unopened_context_file(path, relative, error.kind()),
315    };
316    let opened_metadata = match file.metadata() {
317        Ok(metadata) if context_handle_is_regular_file(&metadata) => metadata,
318        Ok(metadata) => {
319            return unreadable_context_file(
320                relative,
321                CONTEXT_SPECIAL_FILE_STATE,
322                Some(SourceFingerprint::from_metadata(&metadata)),
323            );
324        }
325        Err(error) => return unreadable_context_file(relative, error.kind().to_string(), None),
326    };
327    let source = Some(SourceFingerprint::from_metadata(&opened_metadata));
328    if opened_metadata.len() > AUDIT_CONTEXT_FILE_MAX_BYTES {
329        return unreadable_context_file(relative, CONTEXT_OVERSIZED_FILE_STATE, source);
330    }
331
332    let capacity = usize::try_from(opened_metadata.len()).unwrap_or(0);
333    let mut bytes = Vec::with_capacity(capacity);
334    let read_limit = AUDIT_CONTEXT_FILE_MAX_BYTES.saturating_add(1);
335    if let Err(error) = (&mut file).take(read_limit).read_to_end(&mut bytes) {
336        return unreadable_context_file(relative, error.kind().to_string(), source);
337    }
338    if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > AUDIT_CONTEXT_FILE_MAX_BYTES {
339        return unreadable_context_file(relative, CONTEXT_OVERSIZED_FILE_STATE, source);
340    }
341    after_read();
342    let final_metadata = match file.metadata() {
343        Ok(metadata) => metadata,
344        Err(error) => return unreadable_context_file(relative, error.kind().to_string(), source),
345    };
346    if SourceFingerprint::from_metadata(&opened_metadata)
347        != SourceFingerprint::from_metadata(&final_metadata)
348    {
349        return unreadable_context_file(relative, CONTEXT_CHANGED_DURING_READ_STATE, source);
350    }
351
352    AuditContextFileFingerprint {
353        path: relative.to_string(),
354        state: AuditContextPathState::Present,
355        source,
356        content_hash: Some(format!("{:016x}", xxh3_64(&bytes))),
357    }
358}
359
360#[expect(
361    clippy::filetype_is_file,
362    reason = "failed atomic opens are classified conservatively without treating arbitrary non-directories as readable files"
363)]
364fn classify_unopened_context_file(
365    path: &Path,
366    relative: &str,
367    open_error: std::io::ErrorKind,
368) -> AuditContextFileFingerprint {
369    match fs::symlink_metadata(path) {
370        Ok(metadata) if metadata.file_type().is_symlink() => unreadable_context_file(
371            relative,
372            CONTEXT_SYMLINK_STATE,
373            Some(SourceFingerprint::from_metadata(&metadata)),
374        ),
375        Ok(metadata) if !metadata.file_type().is_file() => unreadable_context_file(
376            relative,
377            CONTEXT_SPECIAL_FILE_STATE,
378            Some(SourceFingerprint::from_metadata(&metadata)),
379        ),
380        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
381            missing_context_file(relative)
382        }
383        Ok(metadata) => unreadable_context_file(
384            relative,
385            open_error.to_string(),
386            Some(SourceFingerprint::from_metadata(&metadata)),
387        ),
388        Err(_) => unreadable_context_file(relative, open_error.to_string(), None),
389    }
390}
391
392fn open_context_file(path: &Path) -> std::io::Result<File> {
393    let mut options = OpenOptions::new();
394    options.read(true);
395
396    #[cfg(any(
397        target_os = "linux",
398        target_os = "android",
399        target_os = "macos",
400        target_os = "ios",
401        target_os = "freebsd",
402        target_os = "dragonfly",
403        target_os = "openbsd",
404        target_os = "netbsd"
405    ))]
406    {
407        use std::os::unix::fs::OpenOptionsExt as _;
408
409        options.custom_flags(UNIX_CONTEXT_OPEN_FLAGS);
410    }
411    #[cfg(all(
412        unix,
413        not(any(
414            target_os = "linux",
415            target_os = "android",
416            target_os = "macos",
417            target_os = "ios",
418            target_os = "freebsd",
419            target_os = "dragonfly",
420            target_os = "openbsd",
421            target_os = "netbsd"
422        ))
423    ))]
424    {
425        return Err(std::io::Error::new(
426            std::io::ErrorKind::Unsupported,
427            "atomic no-follow context reads are unavailable on this Unix target",
428        ));
429    }
430    #[cfg(windows)]
431    {
432        use std::os::windows::fs::OpenOptionsExt as _;
433
434        options.custom_flags(WINDOWS_FILE_FLAG_OPEN_REPARSE_POINT);
435    }
436
437    options.open(path)
438}
439
440#[cfg(windows)]
441#[expect(
442    clippy::filetype_is_file,
443    reason = "security boundary intentionally accepts regular files only and rejects reparse points, directories, and special files"
444)]
445fn context_handle_is_regular_file(metadata: &fs::Metadata) -> bool {
446    use std::os::windows::fs::MetadataExt as _;
447
448    metadata.file_type().is_file()
449        && metadata.file_attributes() & WINDOWS_FILE_ATTRIBUTE_REPARSE_POINT == 0
450}
451
452#[cfg(not(windows))]
453#[expect(
454    clippy::filetype_is_file,
455    reason = "security boundary intentionally accepts regular files only and rejects directories, sockets, devices, and pipes"
456)]
457fn context_handle_is_regular_file(metadata: &fs::Metadata) -> bool {
458    metadata.file_type().is_file()
459}
460
461fn missing_context_file(relative: &str) -> AuditContextFileFingerprint {
462    AuditContextFileFingerprint {
463        path: relative.to_string(),
464        state: AuditContextPathState::Missing,
465        source: None,
466        content_hash: None,
467    }
468}
469
470fn unreadable_context_file(
471    relative: &str,
472    reason: impl Into<String>,
473    source: Option<SourceFingerprint>,
474) -> AuditContextFileFingerprint {
475    AuditContextFileFingerprint {
476        path: relative.to_string(),
477        state: AuditContextPathState::Unreadable(reason.into()),
478        source,
479        content_hash: None,
480    }
481}
482
483fn unavailable_context_file(
484    relative: &str,
485    parent_state: &AuditContextPathState,
486) -> AuditContextFileFingerprint {
487    if matches!(parent_state, AuditContextPathState::Missing) {
488        missing_context_file(relative)
489    } else {
490        unreadable_context_file(relative, CONTEXT_PARENT_UNAVAILABLE_STATE, None)
491    }
492}
493
494#[cfg(unix)]
495fn symlink_dependency_dir(source: &Path, destination: &Path) -> std::io::Result<()> {
496    std::os::unix::fs::symlink(source, destination)
497}
498
499#[cfg(windows)]
500fn symlink_dependency_dir(source: &Path, destination: &Path) -> std::io::Result<()> {
501    std::os::windows::fs::symlink_dir(source, destination)
502}
503
504/// Register a detached worktree without checking files out, then materialize
505/// the committed tree directly from Git objects.
506///
507/// This deliberately avoids Git's checkout pipeline. No checkout hook,
508/// smudge filter, process filter, line-ending conversion, or working-tree
509/// encoding is invoked. Regular files contain the raw committed blob bytes.
510///
511/// # Errors
512///
513/// Returns an engine error when the destination is not absolute, Git cannot
514/// create the administrative worktree, the tree contains an unsafe path, or
515/// an object cannot be materialized. A failed materialization removes both
516/// the worktree registration and its partial directory.
517pub fn create_detached_base_worktree(
518    repo_root: &Path,
519    destination: &Path,
520    base_ref: &str,
521) -> EngineResult<()> {
522    if !destination.is_absolute() {
523        return Err(EngineError::new(format!(
524            "base worktree destination must be absolute: {}",
525            destination.display()
526        )));
527    }
528
529    register_no_checkout_worktree(repo_root, destination, base_ref)?;
530    let result = make_worktree_root_private(destination)
531        .and_then(|()| resolve_registered_commit(destination, base_ref))
532        .and_then(|commit| {
533            populate_worktree_index(destination, &commit)?;
534            materialize_committed_tree(repo_root, destination, &commit)
535        })
536        .and_then(|()| write_raw_materialization_marker(destination));
537    if let Err(error) = result {
538        remove_registered_worktree(repo_root, destination);
539        let _ = fs::remove_dir_all(destination);
540        return Err(error);
541    }
542    Ok(())
543}
544
545#[path = "repo_refs_linked_worktree.rs"]
546mod linked_worktree;
547use linked_worktree::make_worktree_root_private;
548pub use linked_worktree::{
549    create_staged_index_worktree, remove_staged_index_worktree, write_index_tree,
550};
551
552/// Return whether a linked worktree was completely materialized by the raw
553/// object path used by [`create_detached_base_worktree`].
554///
555/// Reusable audit caches created by older versions have no marker and must be
556/// rebuilt once so smudged or checkout-generated contents are not reused.
557#[must_use]
558pub fn detached_base_worktree_is_raw_materialized(worktree_root: &Path) -> bool {
559    raw_materialization_marker_path(worktree_root).is_ok_and(|path| path.is_file())
560}
561
562fn write_raw_materialization_marker(worktree_root: &Path) -> EngineResult<()> {
563    let marker = raw_materialization_marker_path(worktree_root)?;
564    fs::write(&marker, b"raw-v1\n").map_err(|error| {
565        EngineError::new(format!(
566            "could not record raw base-worktree materialization at `{}`: {error}",
567            marker.display()
568        ))
569    })
570}
571
572fn raw_materialization_marker_path(worktree_root: &Path) -> EngineResult<PathBuf> {
573    let marker = run_git(
574        worktree_root,
575        &["rev-parse", "--git-path", RAW_MATERIALIZATION_MARKER],
576    )
577    .ok_or_else(|| EngineError::new("could not resolve base-worktree materialization marker"))?;
578    let marker = PathBuf::from(marker);
579    if marker.is_absolute() {
580        Ok(marker)
581    } else {
582        Ok(worktree_root.join(marker))
583    }
584}
585
586fn register_no_checkout_worktree(
587    repo_root: &Path,
588    destination: &Path,
589    base_ref: &str,
590) -> EngineResult<()> {
591    let mut command = git_command(repo_root);
592    command.args([
593        "worktree",
594        "add",
595        "--detach",
596        "--quiet",
597        "--no-checkout",
598        "--",
599    ]);
600    command.arg(destination).arg(base_ref);
601    let output = command.output().map_err(|error| {
602        EngineError::new(format!(
603            "could not create a temporary worktree for base ref `{base_ref}`: {error}"
604        ))
605    })?;
606    if !output.status.success() {
607        return Err(EngineError::new(format!(
608            "could not create a temporary worktree for base ref `{base_ref}`: {}",
609            String::from_utf8_lossy(&output.stderr).trim()
610        )));
611    }
612    Ok(())
613}
614
615fn resolve_registered_commit(destination: &Path, base_ref: &str) -> EngineResult<String> {
616    run_git(destination, &["rev-parse", "--verify", "HEAD^{commit}"]).ok_or_else(|| {
617        EngineError::new(format!(
618            "could not resolve the commit for base ref `{base_ref}` after creating the worktree"
619        ))
620    })
621}
622
623fn populate_worktree_index(destination: &Path, commit: &str) -> EngineResult<()> {
624    let disabled_hooks_path = destination.join(".fallow-disabled-git-hooks");
625    let output = git_command(destination)
626        .env("GIT_CONFIG_COUNT", "2")
627        .env("GIT_CONFIG_KEY_0", "core.hooksPath")
628        .env("GIT_CONFIG_VALUE_0", disabled_hooks_path)
629        .env("GIT_CONFIG_KEY_1", "core.fsmonitor")
630        .env("GIT_CONFIG_VALUE_1", "false")
631        .args(["read-tree", "--reset", commit])
632        .output()
633        .map_err(|error| {
634            EngineError::new(format!("could not populate base worktree index: {error}"))
635        })?;
636    if !output.status.success() {
637        return Err(EngineError::new(format!(
638            "could not populate base worktree index: {}",
639            String::from_utf8_lossy(&output.stderr).trim()
640        )));
641    }
642    Ok(())
643}
644
645#[derive(Debug, Clone, Copy, PartialEq, Eq)]
646enum TreeEntryKind {
647    Regular,
648    Executable,
649    Symlink,
650    Gitlink,
651}
652
653#[derive(Debug)]
654struct TreeEntry {
655    kind: TreeEntryKind,
656    object_id: String,
657    path: PathBuf,
658}
659
660/// Which committed-tree paths a base worktree actually needs on disk.
661///
662/// The raw object materialization deliberately bypasses git's checkout
663/// pipeline (no hooks, smudge filters, or line-ending conversion). Before
664/// that change the worktree checkout honored the host's sparse-checkout cone
665/// and, for a subdirectory analysis root, only the cone was ever read. The
666/// unscoped materialization reads EVERY blob in the commit instead: on a
667/// blobless partial clone (`actions/checkout` sets `--filter=blob:none`
668/// whenever `sparse-checkout` is set) each out-of-cone blob triggers a lazy
669/// promisor fetch via `git-remote-https`. For a large monorepo checked out
670/// sparsely to one subdirectory that turns a seconds-long snapshot into a
671/// fetch of the whole monorepo, which presents as `fallow audit` hanging to
672/// the CI timeout with `git` / `git-remote-https` orphans (issue #2615).
673///
674/// The scope restores the old working set without reintroducing checkout:
675/// - a subdirectory analysis root materializes only that subtree (plus
676///   top-level files and ancestor ignore files, so gitignore parity holds),
677/// - a repository-root run on a sparse checkout materializes the sparse cone
678///   (top-level files plus the listed cone directories),
679/// - otherwise everything is materialized as before.
680///
681/// Both probes fail open to full materialization: a probe error is at worst a
682/// slower snapshot, never a missing-file misattribution.
683struct MaterializationScope {
684    /// Forward-slash repo-relative analysis subdir (e.g. `apps/web`), or
685    /// `None` when the requested root is the repository top level.
686    subdir_prefix: Option<String>,
687    /// Cone-mode sparse directories (forward-slash, no trailing slash), or
688    /// `None` when sparse-checkout is off, non-cone, or unreadable.
689    sparse_dirs: Option<Vec<String>>,
690}
691
692impl MaterializationScope {
693    fn should_materialize(&self, path: &Path) -> bool {
694        let Some(relative) = forward_slash_path(path) else {
695            return true;
696        };
697        if let Some(prefix) = self.subdir_prefix.as_deref() {
698            if relative == prefix || relative.starts_with(&format!("{prefix}/")) {
699                return true;
700            }
701            // Top-level files and ancestor ignore files shape discovery of the
702            // subtree (root `.gitignore` applies hierarchically). They are few
703            // and already present in a sparse checkout, so keeping them is
704            // free and preserves ignore parity with a full snapshot.
705            if !relative.contains('/') {
706                return true;
707            }
708            return is_ancestor_ignore_file(&relative, prefix);
709        }
710        if let Some(dirs) = self.sparse_dirs.as_deref() {
711            if !relative.contains('/') {
712                return true;
713            }
714            return dirs
715                .iter()
716                .any(|dir| relative == *dir || relative.starts_with(&format!("{dir}/")));
717        }
718        true
719    }
720}
721
722/// Forward-slash repo-relative path for scope matching, or `None` when the
723/// path is not valid UTF-8. Non-UTF-8 tree paths are rare; failing open keeps
724/// them materialized rather than risking a misattributed base snapshot.
725fn forward_slash_path(path: &Path) -> Option<String> {
726    let raw = path.to_str()?;
727    Some(raw.replace('\\', "/"))
728}
729
730/// True for an ignore/attributes file that governs `prefix` from an ancestor
731/// directory (including the repository root), e.g. `.gitignore` or
732/// `apps/.gitignore` for prefix `apps/web`.
733fn is_ancestor_ignore_file(relative: &str, prefix: &str) -> bool {
734    const IGNORE_FILES: &[&str] = &[".gitignore", ".gitattributes"];
735    let Some(file_name) = relative.rsplit('/').next() else {
736        return false;
737    };
738    if !IGNORE_FILES.contains(&file_name) {
739        return false;
740    }
741    let parent = relative.rsplit_once('/').map_or("", |(parent, _)| parent);
742    parent.is_empty() || prefix == parent || prefix.starts_with(&format!("{parent}/"))
743}
744
745fn materialization_scope(repo_root: &Path) -> MaterializationScope {
746    MaterializationScope {
747        subdir_prefix: analysis_subdir_prefix(repo_root),
748        sparse_dirs: sparse_cone_dirs(repo_root),
749    }
750}
751
752/// Repo-relative forward-slash subdir of the requested analysis root, or
753/// `None` when it is the repository top level (or the top level cannot be
754/// resolved, which fails open to full materialization).
755fn analysis_subdir_prefix(repo_root: &Path) -> Option<String> {
756    let toplevel = run_git(repo_root, &["rev-parse", "--show-toplevel"])?;
757    let toplevel = PathBuf::from(toplevel);
758    let canonical_toplevel = dunce::canonicalize(&toplevel).unwrap_or(toplevel);
759    let canonical_root = dunce::canonicalize(repo_root).unwrap_or_else(|_| repo_root.to_path_buf());
760    let relative = canonical_root.strip_prefix(&canonical_toplevel).ok()?;
761    if relative.as_os_str().is_empty() {
762        return None;
763    }
764    let prefix = forward_slash_path(relative)?;
765    if prefix.is_empty() {
766        return None;
767    }
768    Some(prefix)
769}
770
771/// Cone-mode sparse-checkout directories of the host checkout, or `None` when
772/// sparse-checkout is off, non-cone, or unreadable (fail open to full).
773///
774/// `git sparse-checkout list` exits non-zero on a non-sparse worktree, which
775/// is the common full-clone case. Non-cone mode uses glob patterns that this
776/// matcher does not implement, so it also falls back to full materialization.
777fn sparse_cone_dirs(repo_root: &Path) -> Option<Vec<String>> {
778    if run_git(repo_root, &["config", "--get", "core.sparseCheckout"])? != "true" {
779        return None;
780    }
781    if run_git(repo_root, &["config", "--get", "core.sparseCheckoutCone"])? != "true" {
782        return None;
783    }
784    let output = git_command(repo_root)
785        .args(["sparse-checkout", "list"])
786        .output()
787        .ok()?;
788    if !output.status.success() {
789        return None;
790    }
791    let list = String::from_utf8(output.stdout).ok()?;
792    let mut dirs = Vec::new();
793    for line in list.lines() {
794        let pattern = line.trim().trim_matches('/');
795        if pattern.is_empty() {
796            continue;
797        }
798        // Cone mode lists directories; a stray glob (non-cone residue) cannot
799        // be matched exactly, so fail open rather than under-materialize.
800        if pattern.contains(['*', '?', '[', '!']) {
801            return None;
802        }
803        dirs.push(pattern.replace('\\', "/"));
804    }
805    Some(dirs)
806}
807
808fn materialize_committed_tree(
809    repo_root: &Path,
810    destination: &Path,
811    commit: &str,
812) -> EngineResult<()> {
813    let entries = committed_tree_entries(repo_root, commit)?;
814    let scope = materialization_scope(repo_root);
815    let entries: Vec<TreeEntry> = entries
816        .into_iter()
817        .filter(|entry| scope.should_materialize(&entry.path))
818        .collect();
819    let mut blobs = BatchBlobReader::spawn(repo_root)?;
820    let mut symlinks = Vec::new();
821
822    for entry in entries {
823        create_safe_parent_directories(destination, &entry.path)?;
824        let output_path = destination.join(&entry.path);
825        match entry.kind {
826            TreeEntryKind::Regular | TreeEntryKind::Executable => {
827                let mut file = OpenOptions::new()
828                    .create_new(true)
829                    .write(true)
830                    .open(&output_path)
831                    .map_err(|error| materialization_error(&entry.path, error))?;
832                blobs.copy_blob(&entry.object_id, &entry.path, &mut file)?;
833                set_regular_file_mode(&output_path, entry.kind == TreeEntryKind::Executable)?;
834            }
835            TreeEntryKind::Symlink => {
836                let target = blobs.read_blob(&entry.object_id, &entry.path)?;
837                symlinks.push((entry.path, target));
838            }
839            TreeEntryKind::Gitlink => {
840                fs::create_dir(&output_path)
841                    .map_err(|error| materialization_error(&entry.path, error))?;
842            }
843        }
844    }
845
846    blobs.finish()?;
847    for (path, target) in symlinks {
848        create_safe_parent_directories(destination, &path)?;
849        create_materialized_symlink(&destination.join(&path), &target)
850            .map_err(|error| materialization_error(&path, error))?;
851    }
852    Ok(())
853}
854
855fn committed_tree_entries(repo_root: &Path, commit: &str) -> EngineResult<Vec<TreeEntry>> {
856    let output = git_command(repo_root)
857        .args(["ls-tree", "-r", "-z", "--full-tree", commit])
858        .output()
859        .map_err(|error| EngineError::new(format!("could not read base commit tree: {error}")))?;
860    if !output.status.success() {
861        return Err(EngineError::new(format!(
862            "could not read base commit tree: {}",
863            String::from_utf8_lossy(&output.stderr).trim()
864        )));
865    }
866
867    output
868        .stdout
869        .split(|byte| *byte == 0)
870        .filter(|record| !record.is_empty())
871        .map(parse_tree_entry)
872        .collect()
873}
874
875fn parse_tree_entry(record: &[u8]) -> EngineResult<TreeEntry> {
876    let tab = record
877        .iter()
878        .position(|byte| *byte == b'\t')
879        .ok_or_else(|| EngineError::new("could not parse base commit tree entry without a path"))?;
880    let header = std::str::from_utf8(&record[..tab])
881        .map_err(|error| EngineError::new(format!("invalid Git tree header: {error}")))?;
882    let mut fields = header.split_ascii_whitespace();
883    let mode = fields.next().unwrap_or_default();
884    let object_type = fields.next().unwrap_or_default();
885    let object_id = fields.next().unwrap_or_default();
886    if fields.next().is_some() || object_id.is_empty() {
887        return Err(EngineError::new(format!(
888            "could not parse Git tree header `{header}`"
889        )));
890    }
891    let kind = match (mode, object_type) {
892        ("100644", "blob") => TreeEntryKind::Regular,
893        ("100755", "blob") => TreeEntryKind::Executable,
894        ("120000", "blob") => TreeEntryKind::Symlink,
895        ("160000", "commit") => TreeEntryKind::Gitlink,
896        _ => {
897            return Err(EngineError::new(format!(
898                "unsupported Git tree entry mode `{mode}` and type `{object_type}`"
899            )));
900        }
901    };
902    let path = git_path_from_bytes(&record[tab + 1..])?;
903    validate_materialized_path(&path)?;
904    Ok(TreeEntry {
905        kind,
906        object_id: object_id.to_owned(),
907        path,
908    })
909}
910
911#[cfg(unix)]
912#[expect(
913    clippy::unnecessary_wraps,
914    reason = "shared cross-platform signature; non-Unix path decoding is fallible"
915)]
916fn git_path_from_bytes(bytes: &[u8]) -> EngineResult<PathBuf> {
917    use std::os::unix::ffi::OsStringExt as _;
918
919    Ok(std::ffi::OsString::from_vec(bytes.to_vec()).into())
920}
921
922#[cfg(not(unix))]
923fn git_path_from_bytes(bytes: &[u8]) -> EngineResult<PathBuf> {
924    String::from_utf8(bytes.to_vec())
925        .map(PathBuf::from)
926        .map_err(|error| EngineError::new(format!("Git tree path is not valid UTF-8: {error}")))
927}
928
929fn validate_materialized_path(path: &Path) -> EngineResult<()> {
930    if path.as_os_str().is_empty() || path.is_absolute() {
931        return Err(unsafe_tree_path(path));
932    }
933
934    let mut saw_component = false;
935    for component in path.components() {
936        let Component::Normal(segment) = component else {
937            return Err(unsafe_tree_path(path));
938        };
939        saw_component = true;
940        if segment.to_str().is_some_and(is_git_admin_alias) {
941            return Err(unsafe_tree_path(path));
942        }
943    }
944    if !saw_component {
945        return Err(unsafe_tree_path(path));
946    }
947    Ok(())
948}
949
950fn is_git_admin_alias(segment: &str) -> bool {
951    let normalized = segment.trim_end_matches([' ', '.']).to_ascii_lowercase();
952    normalized == ".git" || normalized == "git~1"
953}
954
955fn unsafe_tree_path(path: &Path) -> EngineError {
956    EngineError::new(format!(
957        "refusing to materialize unsafe Git tree path `{}`",
958        path.display()
959    ))
960}
961
962fn create_safe_parent_directories(root: &Path, relative: &Path) -> EngineResult<()> {
963    let Some(parent) = relative.parent() else {
964        return Ok(());
965    };
966    let mut current = root.to_path_buf();
967    for component in parent.components() {
968        let Component::Normal(segment) = component else {
969            return Err(unsafe_tree_path(relative));
970        };
971        current.push(segment);
972        match fs::symlink_metadata(&current) {
973            Ok(metadata) if metadata.file_type().is_dir() => {}
974            Ok(_) => {
975                return Err(EngineError::new(format!(
976                    "refusing to materialize through non-directory path `{}`",
977                    current.display()
978                )));
979            }
980            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
981                fs::create_dir(&current).map_err(|error| materialization_error(relative, error))?;
982            }
983            Err(error) => return Err(materialization_error(relative, error)),
984        }
985    }
986    Ok(())
987}
988
989fn materialization_error(path: &Path, error: impl std::fmt::Display) -> EngineError {
990    EngineError::new(format!(
991        "could not materialize base commit path `{}`: {error}",
992        path.display()
993    ))
994}
995
996#[cfg(unix)]
997fn set_regular_file_mode(path: &Path, executable: bool) -> EngineResult<()> {
998    use std::os::unix::fs::PermissionsExt as _;
999
1000    let mode = if executable { 0o755 } else { 0o644 };
1001    let permissions = fs::Permissions::from_mode(mode);
1002    fs::set_permissions(path, permissions).map_err(|error| materialization_error(path, error))
1003}
1004
1005#[cfg(not(unix))]
1006#[expect(
1007    clippy::unnecessary_wraps,
1008    reason = "shared cross-platform signature; Unix permission updates are fallible"
1009)]
1010fn set_regular_file_mode(_path: &Path, _executable: bool) -> EngineResult<()> {
1011    Ok(())
1012}
1013
1014#[cfg(unix)]
1015fn create_materialized_symlink(path: &Path, target: &[u8]) -> std::io::Result<()> {
1016    use std::os::unix::ffi::OsStringExt as _;
1017
1018    std::os::unix::fs::symlink(std::ffi::OsString::from_vec(target.to_vec()), path)
1019}
1020
1021#[cfg(windows)]
1022fn create_materialized_symlink(path: &Path, target: &[u8]) -> std::io::Result<()> {
1023    let target_path = PathBuf::from(String::from_utf8_lossy(target).into_owned());
1024    let resolved_target = path
1025        .parent()
1026        .map_or_else(|| target_path.clone(), |parent| parent.join(&target_path));
1027    let result = if resolved_target.is_dir() {
1028        std::os::windows::fs::symlink_dir(&target_path, path)
1029    } else {
1030        std::os::windows::fs::symlink_file(&target_path, path)
1031    };
1032    result.or_else(|_| fs::write(path, target))
1033}
1034
1035#[cfg(not(any(unix, windows)))]
1036fn create_materialized_symlink(path: &Path, target: &[u8]) -> std::io::Result<()> {
1037    fs::write(path, target)
1038}
1039
1040struct BatchBlobReader {
1041    child: Option<Child>,
1042    stdin: Option<ChildStdin>,
1043    stdout: BufReader<ChildStdout>,
1044}
1045
1046impl BatchBlobReader {
1047    fn spawn(repo_root: &Path) -> EngineResult<Self> {
1048        let mut command = git_command(repo_root);
1049        command
1050            .args(["cat-file", "--batch"])
1051            .stdin(Stdio::piped())
1052            .stdout(Stdio::piped())
1053            .stderr(Stdio::null());
1054        let mut child = command.spawn().map_err(|error| {
1055            EngineError::new(format!("could not start Git object reader: {error}"))
1056        })?;
1057        let stdin = child
1058            .stdin
1059            .take()
1060            .ok_or_else(|| EngineError::new("Git object reader has no stdin pipe"))?;
1061        let stdout = child
1062            .stdout
1063            .take()
1064            .ok_or_else(|| EngineError::new("Git object reader has no stdout pipe"))?;
1065        Ok(Self {
1066            child: Some(child),
1067            stdin: Some(stdin),
1068            stdout: BufReader::new(stdout),
1069        })
1070    }
1071
1072    fn copy_blob(&mut self, object_id: &str, path: &Path, target: &mut File) -> EngineResult<()> {
1073        let size = self.request_blob(object_id, path)?;
1074        let copied = std::io::copy(&mut self.stdout.by_ref().take(size), target)
1075            .map_err(|error| materialization_error(path, error))?;
1076        if copied != size {
1077            return Err(EngineError::new(format!(
1078                "Git object reader returned {copied} of {size} bytes for `{}`",
1079                path.display()
1080            )));
1081        }
1082        self.consume_blob_terminator(path)
1083    }
1084
1085    fn read_blob(&mut self, object_id: &str, path: &Path) -> EngineResult<Vec<u8>> {
1086        let size = self.request_blob(object_id, path)?;
1087        let size = usize::try_from(size).map_err(|error| materialization_error(path, error))?;
1088        let mut bytes = vec![0; size];
1089        self.stdout
1090            .read_exact(&mut bytes)
1091            .map_err(|error| materialization_error(path, error))?;
1092        self.consume_blob_terminator(path)?;
1093        Ok(bytes)
1094    }
1095
1096    fn request_blob(&mut self, object_id: &str, path: &Path) -> EngineResult<u64> {
1097        let stdin = self
1098            .stdin
1099            .as_mut()
1100            .ok_or_else(|| EngineError::new("Git object reader stdin is closed"))?;
1101        writeln!(stdin, "{object_id}").map_err(|error| materialization_error(path, error))?;
1102        stdin
1103            .flush()
1104            .map_err(|error| materialization_error(path, error))?;
1105
1106        let mut header = Vec::new();
1107        self.stdout
1108            .read_until(b'\n', &mut header)
1109            .map_err(|error| materialization_error(path, error))?;
1110        let header = std::str::from_utf8(&header)
1111            .map_err(|error| materialization_error(path, error))?
1112            .trim_end();
1113        let mut fields = header.split_ascii_whitespace();
1114        let returned_id = fields.next().unwrap_or_default();
1115        let object_type = fields.next().unwrap_or_default();
1116        let size = fields.next().unwrap_or_default();
1117        if returned_id != object_id || object_type != "blob" || fields.next().is_some() {
1118            return Err(EngineError::new(format!(
1119                "unexpected Git object response `{header}` for `{}`",
1120                path.display()
1121            )));
1122        }
1123        size.parse::<u64>()
1124            .map_err(|error| materialization_error(path, error))
1125    }
1126
1127    fn consume_blob_terminator(&mut self, path: &Path) -> EngineResult<()> {
1128        let mut terminator = [0; 1];
1129        self.stdout
1130            .read_exact(&mut terminator)
1131            .map_err(|error| materialization_error(path, error))?;
1132        if terminator != *b"\n" {
1133            return Err(EngineError::new(format!(
1134                "Git object response for `{}` had no terminator",
1135                path.display()
1136            )));
1137        }
1138        Ok(())
1139    }
1140
1141    fn finish(mut self) -> EngineResult<()> {
1142        self.stdin.take();
1143        let status = self
1144            .child
1145            .take()
1146            .ok_or_else(|| EngineError::new("Git object reader is already closed"))?
1147            .wait()
1148            .map_err(|error| {
1149                EngineError::new(format!("could not wait for Git object reader: {error}"))
1150            })?;
1151        if !status.success() {
1152            return Err(EngineError::new(format!(
1153                "Git object reader exited with status {status}"
1154            )));
1155        }
1156        Ok(())
1157    }
1158}
1159
1160impl Drop for BatchBlobReader {
1161    fn drop(&mut self) {
1162        self.stdin.take();
1163        if let Some(mut child) = self.child.take() {
1164            let _ = child.kill();
1165            let _ = child.wait();
1166        }
1167    }
1168}
1169
1170fn remove_registered_worktree(repo_root: &Path, destination: &Path) {
1171    let _ = git_command(repo_root)
1172        .args(["worktree", "remove", "--force"])
1173        .arg(destination)
1174        .output();
1175}
1176
1177impl Drop for TemporaryBaseWorktree {
1178    fn drop(&mut self) {
1179        // The snapshot was deregistered in `create`, so cleanup removes only
1180        // the directory and runs no `git` subprocess.
1181        let _ = fs::remove_dir_all(&self.path);
1182    }
1183}
1184
1185/// Resolve the analysis root inside a detached base worktree.
1186///
1187/// This is the one implementation for `fallow audit`, `fallow security --base`
1188/// and the typed routes. Both sides of the prefix comparison are real paths,
1189/// because a caller can spell the root through a symbolic link (`/tmp` on
1190/// macOS resolves to `/private/tmp`) while git reports the resolved top level.
1191/// A comparison across the two path spaces fails, and the base snapshot then
1192/// covers the whole base worktree while the head snapshot stays scoped. Only
1193/// the relative remainder joins `base_worktree_root`, so no canonical spelling
1194/// reaches the result.
1195#[must_use]
1196pub fn base_analysis_root(current_root: &Path, base_worktree_root: &Path) -> PathBuf {
1197    let Some(git_root) = git_toplevel(current_root) else {
1198        return base_worktree_root.to_path_buf();
1199    };
1200    let current_root =
1201        dunce::canonicalize(current_root).unwrap_or_else(|_| current_root.to_path_buf());
1202    match current_root.strip_prefix(&git_root) {
1203        Ok(relative) => base_worktree_root.join(relative),
1204        Err(error) => {
1205            tracing::warn!(
1206                current_root = %current_root.display(),
1207                git_root = %git_root.display(),
1208                error = %error,
1209                "Could not remap the analysis root into the base worktree; falling back to the worktree root"
1210            );
1211            base_worktree_root.to_path_buf()
1212        }
1213    }
1214}
1215
1216/// Move a cache directory inside the analysis root to the same place inside
1217/// the base worktree.
1218///
1219/// A base snapshot that wrote into the head tree's cache would mix two
1220/// commits in one cache. A relative cache directory resolves against the base
1221/// worktree already, and an absolute one outside the root is shared on
1222/// purpose, so both stay unchanged. The prefix check runs on the path as
1223/// written first and then on the real paths, so a symlinked root cannot keep
1224/// the base cache in the head tree.
1225#[must_use]
1226pub fn remap_cache_dir_for_base_worktree(
1227    current_root: &Path,
1228    base_worktree_root: &Path,
1229    cache_dir: &Path,
1230) -> PathBuf {
1231    if !cache_dir.is_absolute() {
1232        return cache_dir.to_path_buf();
1233    }
1234    if let Ok(relative) = cache_dir.strip_prefix(current_root) {
1235        return base_worktree_root.join(relative);
1236    }
1237    let canonical_root =
1238        dunce::canonicalize(current_root).unwrap_or_else(|_| current_root.to_path_buf());
1239    let canonical_cache =
1240        dunce::canonicalize(cache_dir).unwrap_or_else(|_| cache_dir.to_path_buf());
1241    [cache_dir, canonical_cache.as_path()]
1242        .into_iter()
1243        .find_map(|candidate| candidate.strip_prefix(&canonical_root).ok())
1244        .map_or_else(
1245            || cache_dir.to_path_buf(),
1246            |relative| base_worktree_root.join(relative),
1247        )
1248}
1249
1250/// Analysis root for a detached base worktree, and whether the base commit
1251/// contains it at all.
1252#[derive(Debug, Clone, PartialEq, Eq)]
1253pub enum BaseAnalysisRoot {
1254    /// The head analysis root maps onto a directory that the base commit
1255    /// contains, so the base snapshot is analyzed there.
1256    Present(PathBuf),
1257    /// The head analysis root maps onto a directory the base commit does not
1258    /// contain, such as a package added on the branch. Everything under it is
1259    /// new, so the base snapshot for that root is empty.
1260    NewInHead(PathBuf),
1261}
1262
1263/// Resolve the analysis root inside a detached base worktree and report
1264/// whether the base commit contains it.
1265///
1266/// A root that the base commit does not contain is the ordinary shape of
1267/// auditing a package added on the branch. Analyzing the whole base worktree
1268/// instead would compare a subdirectory head snapshot against a
1269/// whole-repository base snapshot, whose key spaces do not intersect, and
1270/// refusing the call would blame a `root` the caller spelled correctly.
1271#[must_use]
1272pub fn resolve_base_analysis_root(
1273    current_root: &Path,
1274    base_worktree_root: &Path,
1275) -> BaseAnalysisRoot {
1276    let root = base_analysis_root(current_root, base_worktree_root);
1277    if root.is_dir() {
1278        BaseAnalysisRoot::Present(root)
1279    } else {
1280        BaseAnalysisRoot::NewInHead(root)
1281    }
1282}
1283
1284/// Auto-detect the base ref used by changed-code audit when no explicit base
1285/// or environment override is set.
1286///
1287/// The base is the `git merge-base` (fork point) against the branch's upstream
1288/// or the remote default, mirroring the `fallow hooks install --target git`
1289/// pre-commit hook (issue #242). Resolving to the merge-base SHA, rather than a
1290/// bare branch name, fixes the long-standing bug where the default branch was
1291/// discovered via `origin/HEAD` but returned as the bare name `main` (issue
1292/// #1168): git resolves a bare `main` to the LOCAL `refs/heads/main`, which is
1293/// stale on worktree checkouts cut from `origin/main`, so the audit diffed
1294/// every branch against an ancient base and false-failed the gate.
1295///
1296/// Resolution order:
1297/// 1. `@{upstream}` merge-base, so a branch forked off a non-default
1298///    integration branch compares against where it actually forked.
1299/// 2. Remote default (`origin/HEAD` -> `origin/main` -> `origin/master`)
1300///    merge-base. The remote-tracking ref refreshes on fetch, unlike a
1301///    long-stale local branch; the merge-base is also immune to an unfetched
1302///    `origin/main` in the false-fail direction.
1303/// 3. Local `main` / `master` when there is no `origin` remote, preserving the
1304///    historical behavior for air-gapped and local-only repositories.
1305///
1306/// A branch with no common ancestor with its base (a shallow clone, unrelated
1307/// history) falls back to the remote-tracking tip rather than failing the
1308/// detection outright.
1309///
1310/// The result also names the commits of the remote default branch that the
1311/// change merged after the base, see [`merged_default_branch_refs`].
1312#[must_use]
1313pub fn auto_detect_audit_base_ref(root: &Path) -> Option<ResolvedAuditBase> {
1314    let mut base = detect_audit_base_ref(root)?;
1315    base.inherited_refs = merged_default_branch_refs(root, &base.git_ref);
1316    Some(base)
1317}
1318
1319fn detect_audit_base_ref(root: &Path) -> Option<ResolvedAuditBase> {
1320    if let Some(upstream) = git_upstream_ref(root) {
1321        if let Some(sha) = git_merge_base(root, &upstream, "HEAD") {
1322            return Some(ResolvedAuditBase {
1323                git_ref: sha,
1324                description: Some(format!("merge-base with {upstream}")),
1325                inherited_refs: Vec::new(),
1326            });
1327        }
1328        return Some(ResolvedAuditBase {
1329            description: Some(format!("{upstream} (tip)")),
1330            git_ref: upstream,
1331            inherited_refs: Vec::new(),
1332        });
1333    }
1334
1335    if let Some(remote_ref) = detect_remote_default_ref(root) {
1336        if let Some(sha) = git_merge_base(root, &remote_ref, "HEAD") {
1337            return Some(ResolvedAuditBase {
1338                git_ref: sha,
1339                description: Some(format!("merge-base with {remote_ref}")),
1340                inherited_refs: Vec::new(),
1341            });
1342        }
1343        return Some(ResolvedAuditBase {
1344            description: Some(format!("{remote_ref} (tip)")),
1345            git_ref: remote_ref,
1346            inherited_refs: Vec::new(),
1347        });
1348    }
1349
1350    for candidate in ["main", "master"] {
1351        if git_ref_exists(root, candidate) {
1352            return Some(ResolvedAuditBase {
1353                git_ref: candidate.to_string(),
1354                description: Some(format!("local {candidate}")),
1355                inherited_refs: Vec::new(),
1356            });
1357        }
1358    }
1359
1360    None
1361}
1362
1363/// Commits of the remote default branch that the change merged after `base`.
1364///
1365/// A merge of the default branch into a feature branch brings in code that
1366/// the default branch already has. Against a base on the feature branch,
1367/// that code reads as new, so the commit gate blocks the merge commit and the
1368/// push that follows it. The code of these commits is inherited instead:
1369///
1370/// - `MERGE_HEAD` of an in-progress merge, when the default branch contains it;
1371/// - the merge-base of the default branch and `HEAD`, after a merge commit.
1372///
1373/// A commit that `base` already contains adds nothing, so it is left out.
1374/// Without a remote default branch, the result is empty.
1375#[must_use]
1376pub fn merged_default_branch_refs(root: &Path, base: &str) -> Vec<String> {
1377    let Some(default_ref) = detect_remote_default_ref(root) else {
1378        return Vec::new();
1379    };
1380    let merge_head = run_git(root, &["rev-parse", "--verify", "--quiet", "MERGE_HEAD"])
1381        .filter(|merge_head| git_is_ancestor(root, merge_head, &default_ref) == Some(true));
1382    let merged_default = git_merge_base(root, &default_ref, "HEAD");
1383    // A git error (a shallow history, a missing object) skips the commit, so
1384    // the audit keeps the stricter single-base comparison.
1385    let mut refs: Vec<String> = merge_head
1386        .into_iter()
1387        .chain(merged_default)
1388        .filter(|commit| git_is_ancestor(root, commit, base) == Some(false))
1389        .collect();
1390    refs.dedup();
1391    refs
1392}
1393
1394/// Whether `ancestor` is `descendant` or one of its ancestors. `None` when
1395/// git cannot tell, for example in a shallow history.
1396fn git_is_ancestor(root: &Path, ancestor: &str, descendant: &str) -> Option<bool> {
1397    let status = git_command(root)
1398        .args(["merge-base", "--is-ancestor", ancestor, descendant])
1399        .stdout(Stdio::null())
1400        .stderr(Stdio::null())
1401        .status()
1402        .ok()?;
1403    match status.code() {
1404        Some(0) => Some(true),
1405        Some(1) => Some(false),
1406        _ => None,
1407    }
1408}
1409
1410/// Short SHA for the current HEAD.
1411#[must_use]
1412pub fn short_head_sha(root: &Path) -> Option<String> {
1413    run_git(root, &["rev-parse", "--short", "HEAD"])
1414}
1415
1416/// Full SHA for the current HEAD.
1417///
1418/// `Ok(None)` means git ran and HEAD does not resolve: the directory is not a
1419/// repository, or the current branch has no commit yet. `Err` means git could not
1420/// be started, so a caller can name that cause in its own error text.
1421///
1422/// # Errors
1423///
1424/// Returns the spawn error when the `git` process cannot be started.
1425pub fn head_sha(root: &Path) -> std::io::Result<Option<String>> {
1426    let output = git_command(root).args(["rev-parse", "HEAD"]).output()?;
1427    if !output.status.success() {
1428        return Ok(None);
1429    }
1430    let value = String::from_utf8_lossy(&output.stdout);
1431    let trimmed = value.trim();
1432    Ok((!trimmed.is_empty()).then(|| trimmed.to_owned()))
1433}
1434
1435/// Resolve a concrete `--changed-workspaces` ref for project-level next steps.
1436///
1437/// `workspace_patterns` are the `workspaces.patterns` of the resolved config.
1438/// Returns `None` when the project has no workspaces, is not a git repository,
1439/// or has no resolvable remote default branch.
1440#[must_use]
1441pub fn default_workspace_ref(root: &Path, workspace_patterns: &[String]) -> Option<String> {
1442    let workspaces =
1443        crate::discover::discover_workspace_packages_with_patterns(root, workspace_patterns);
1444    default_workspace_ref_for_workspaces(root, &workspaces)
1445}
1446
1447/// Resolve a concrete `--changed-workspaces` ref using existing workspace data.
1448#[must_use]
1449pub fn default_workspace_ref_for_workspaces(
1450    root: &Path,
1451    workspaces: &[WorkspaceInfo],
1452) -> Option<String> {
1453    if workspaces.is_empty() || !crate::churn::is_git_repo(root) {
1454        return None;
1455    }
1456    detect_remote_default_ref(root)
1457}
1458
1459pub use crate::git_identity::{current_user_email, current_user_identities};
1460
1461fn git_ref_exists(root: &Path, reference: &str) -> bool {
1462    run_git(root, &["rev-parse", "--verify", "--quiet", reference]).is_some()
1463}
1464
1465/// The repository top level as a real path.
1466///
1467/// Git resolves symbolic links in the toplevel it reports on every host
1468/// checked, so the extra canonicalization is a by-construction guard rather
1469/// than a behavior change. It keeps both sides of the prefix comparison in
1470/// `base_analysis_root` in one path space.
1471fn git_toplevel(root: &Path) -> Option<PathBuf> {
1472    let toplevel = PathBuf::from(run_git(root, &["rev-parse", "--show-toplevel"])?);
1473    Some(dunce::canonicalize(&toplevel).unwrap_or(toplevel))
1474}
1475
1476fn git_upstream_ref(root: &Path) -> Option<String> {
1477    run_git(
1478        root,
1479        &[
1480            "rev-parse",
1481            "--abbrev-ref",
1482            "--symbolic-full-name",
1483            "@{upstream}",
1484        ],
1485    )
1486}
1487
1488fn git_merge_base(root: &Path, a: &str, b: &str) -> Option<String> {
1489    run_git(root, &["merge-base", a, b])
1490}
1491
1492/// The remote default branch as a remote-tracking ref, such as
1493/// `origin/main`.
1494///
1495/// Reads `origin/HEAD` first. A clone can lack it (a mirror, a CI checkout, or
1496/// `git remote set-head origin -d`), so `origin/main` and then `origin/master`
1497/// follow. Returns `None` when none of the three exists.
1498#[must_use]
1499fn detect_remote_default_ref(root: &Path) -> Option<String> {
1500    if let Some(full_ref) = run_git(root, &["symbolic-ref", "refs/remotes/origin/HEAD"])
1501        && let Some(branch) = full_ref.strip_prefix("refs/remotes/origin/")
1502    {
1503        return Some(format!("origin/{branch}"));
1504    }
1505    ["origin/main", "origin/master"]
1506        .into_iter()
1507        .find(|candidate| git_ref_exists(root, candidate))
1508        .map(str::to_string)
1509}
1510
1511fn base_worktree_path() -> EngineResult<PathBuf> {
1512    let nanos = SystemTime::now()
1513        .duration_since(SystemTime::UNIX_EPOCH)
1514        .map_err(|err| EngineError::new(format!("system clock before unix epoch: {err}")))?
1515        .as_nanos();
1516    Ok(std::env::temp_dir().join(base_worktree_name(nanos)))
1517}
1518
1519/// Compose the directory name for a base worktree taken at clock read `nanos`.
1520///
1521/// The pid stays the FIRST `-`-separated segment so the CLI orphan sweep keeps
1522/// parsing it. A process-global monotonic counter is the final segment: `nanos`
1523/// is NOT monotonic and repeats across threads, so two audits running
1524/// concurrently in one process could otherwise compose the same name and the
1525/// loser's `git worktree add` fails with "already exists". `nanos` is a
1526/// parameter so that collision is reproducible in a test without depending on
1527/// the host clock resolution.
1528fn base_worktree_name(nanos: u128) -> String {
1529    static SEQ: AtomicU64 = AtomicU64::new(0);
1530    let seq = SEQ.fetch_add(1, Ordering::Relaxed);
1531    format!("fallow-audit-base-{}-{nanos}-{seq}", std::process::id())
1532}
1533
1534/// Repository probes run in `root` through the shared engine Git wrapper.
1535fn git_command(root: &Path) -> Command {
1536    crate::git_env::git_command(root)
1537}
1538
1539/// Run `git <args>` in `root` and return trimmed, non-empty stdout, or `None`
1540/// on a non-zero exit, empty output, or non-UTF-8 output.
1541///
1542/// Trimming belongs to this contract: git terminates every line it prints, and
1543/// callers feed these values straight back to git as refs and compare them as
1544/// paths, where a trailing newline is rejected or silently mismatches. Non-UTF-8
1545/// output stays `None` rather than becoming a mangled ref or path.
1546pub(crate) fn run_git(root: &Path, args: &[&str]) -> Option<String> {
1547    let output = git_command(root).args(args).output().ok()?;
1548    if !output.status.success() {
1549        return None;
1550    }
1551    let value = String::from_utf8(output.stdout).ok()?;
1552    let trimmed = value.trim();
1553    (!trimmed.is_empty()).then(|| trimmed.to_owned())
1554}
1555
1556#[cfg(test)]
1557mod tests {
1558    use std::fs;
1559    use std::path::PathBuf;
1560
1561    use super::*;
1562
1563    fn git(root: &Path, args: &[&str]) -> String {
1564        let output = git_command(root)
1565            .args(args)
1566            .output()
1567            .expect("git command starts");
1568        assert!(
1569            output.status.success(),
1570            "git {args:?} failed: {}",
1571            String::from_utf8_lossy(&output.stderr)
1572        );
1573        String::from_utf8_lossy(&output.stdout).trim().to_owned()
1574    }
1575
1576    fn init_repo(root: &Path) {
1577        fs::create_dir_all(root).expect("create repo");
1578        git(root, &["init", "-b", "main"]);
1579        git(root, &["config", "user.name", "Test User"]);
1580        git(root, &["config", "user.email", "test@example.com"]);
1581        git(root, &["config", "commit.gpgsign", "false"]);
1582    }
1583
1584    fn commit_all(root: &Path, message: &str) {
1585        git(root, &["add", "."]);
1586        git(root, &["commit", "-m", message]);
1587    }
1588
1589    /// A repository on `main` with one seed commit and no remote.
1590    fn seeded_repo(parent: &Path) -> PathBuf {
1591        let root = parent.join("repo");
1592        init_repo(&root);
1593        fs::write(root.join("README.md"), "seed\n").expect("write seed");
1594        commit_all(&root, "initial");
1595        root
1596    }
1597
1598    /// Add a tracked file, commit it, and return the new HEAD SHA.
1599    fn commit_file(repo: &Path, name: &str, body: &str) -> String {
1600        fs::write(repo.join(name), body).expect("write file");
1601        commit_all(repo, name);
1602        git(repo, &["rev-parse", "HEAD"])
1603    }
1604
1605    #[cfg(unix)]
1606    fn write_executable(path: &Path, source: &str) {
1607        use std::os::unix::fs::PermissionsExt as _;
1608
1609        fs::write(path, source).expect("write executable");
1610        let mut permissions = fs::metadata(path)
1611            .expect("executable metadata")
1612            .permissions();
1613        permissions.set_mode(0o755);
1614        fs::set_permissions(path, permissions).expect("set executable mode");
1615    }
1616
1617    /// Concurrent callers whose clock reads land in the same tick must still
1618    /// each get a distinct name. Before the monotonic counter they composed the
1619    /// identical name, so the second `git worktree add` failed with "already
1620    /// exists" and the audit aborted with `FALLOW_AUDIT_BASE_WORKTREE_FAILED`.
1621    ///
1622    /// The tick is pinned rather than sampled: a real `SystemTime` read is fine
1623    /// enough on most hosts that the collision would surface only as a rare
1624    /// flake, which is exactly the failure this guards.
1625    #[test]
1626    fn base_worktree_names_are_unique_when_the_clock_read_repeats() {
1627        const N: usize = 64;
1628        const SAME_TICK: u128 = 1_788_187_156_297_209_000;
1629
1630        let barrier = std::sync::Barrier::new(N);
1631        let names = std::sync::Mutex::new(Vec::with_capacity(N));
1632        std::thread::scope(|scope| {
1633            for _ in 0..N {
1634                let barrier = &barrier;
1635                let names = &names;
1636                scope.spawn(move || {
1637                    barrier.wait();
1638                    names
1639                        .lock()
1640                        .expect("names lock")
1641                        .push(base_worktree_name(SAME_TICK));
1642                });
1643            }
1644        });
1645
1646        let mut names = names.into_inner().expect("names lock");
1647        assert_eq!(names.len(), N);
1648        names.sort();
1649        names.dedup();
1650        assert_eq!(names.len(), N, "base worktree names collided");
1651    }
1652
1653    /// The pid stays the first segment so the CLI orphan sweep keeps parsing it.
1654    #[test]
1655    fn base_worktree_path_keeps_the_pid_as_the_first_segment() {
1656        let path = base_worktree_path().expect("path should build");
1657        let name = path
1658            .file_name()
1659            .and_then(|name| name.to_str())
1660            .expect("worktree name should be utf-8");
1661        let pid = name
1662            .strip_prefix("fallow-audit-base-")
1663            .and_then(|rest| rest.split('-').next())
1664            .expect("pid segment should be present");
1665        assert_eq!(pid, std::process::id().to_string());
1666    }
1667
1668    /// A subdirectory analysis root only materializes its own subtree (plus
1669    /// top-level files). Without this, a sparse checkout of one subdirectory
1670    /// of a large monorepo materializes the whole monorepo, and on a blobless
1671    /// partial clone each out-of-cone blob triggers a lazy promisor fetch that
1672    /// presents as `fallow audit` hanging to the CI timeout (issue #2615).
1673    #[test]
1674    fn detached_worktree_from_a_subdir_skips_sibling_subtrees() {
1675        let temp = tempfile::tempdir().expect("temp dir");
1676        let repo = temp.path().join("repo");
1677        init_repo(&repo);
1678        fs::create_dir_all(repo.join("sub")).expect("create sub dir");
1679        fs::create_dir_all(repo.join("big")).expect("create big dir");
1680        fs::write(repo.join("sub/a.ts"), "export const a = 1;\n").expect("write sub file");
1681        fs::write(repo.join("big/b.ts"), "export const b = 1;\n").expect("write big file");
1682        fs::write(repo.join("top.ts"), "export const top = 1;\n").expect("write top file");
1683        commit_all(&repo, "initial");
1684
1685        let destination = temp.path().join("base");
1686        create_detached_base_worktree(&repo.join("sub"), &destination, "HEAD")
1687            .expect("base worktree should be created");
1688
1689        assert!(
1690            destination.join("sub/a.ts").is_file(),
1691            "the requested subtree must be materialized"
1692        );
1693        assert!(
1694            destination.join("top.ts").is_file(),
1695            "top-level files shape subdir discovery and stay materialized"
1696        );
1697        assert!(
1698            !destination.join("big/b.ts").exists(),
1699            "sibling subtrees must not be materialized: {}",
1700            destination.join("big/b.ts").display()
1701        );
1702
1703        remove_registered_worktree(&repo, &destination);
1704        let _ = fs::remove_dir_all(&destination);
1705    }
1706
1707    /// A repository-root run on a sparse checkout materializes the cone, not
1708    /// the whole monorepo. This is the `actions/checkout` sparse-checkout
1709    /// shape from issue #2615: cone mode lists the sparse directory, and the
1710    /// blobless partial clone has no out-of-cone blobs locally.
1711    #[test]
1712    fn detached_worktree_at_the_root_respects_the_sparse_cone() {
1713        let temp = tempfile::tempdir().expect("temp dir");
1714        let repo = temp.path().join("repo");
1715        init_repo(&repo);
1716        fs::create_dir_all(repo.join("sub")).expect("create sub dir");
1717        fs::create_dir_all(repo.join("big")).expect("create big dir");
1718        fs::write(repo.join("sub/a.ts"), "export const a = 1;\n").expect("write sub file");
1719        fs::write(repo.join("big/b.ts"), "export const b = 1;\n").expect("write big file");
1720        commit_all(&repo, "initial");
1721        git(&repo, &["sparse-checkout", "init", "--cone"]);
1722        git(&repo, &["sparse-checkout", "set", "sub"]);
1723
1724        let destination = temp.path().join("base");
1725        create_detached_base_worktree(&repo, &destination, "HEAD")
1726            .expect("base worktree should be created");
1727
1728        assert!(
1729            destination.join("sub/a.ts").is_file(),
1730            "the sparse cone must be materialized"
1731        );
1732        assert!(
1733            !destination.join("big/b.ts").exists(),
1734            "paths outside the sparse cone must not be materialized: {}",
1735            destination.join("big/b.ts").display()
1736        );
1737
1738        remove_registered_worktree(&repo, &destination);
1739        let _ = fs::remove_dir_all(&destination);
1740    }
1741
1742    /// Pure scope unit coverage: subdir runs keep their subtree plus top-level
1743    /// and ancestor ignore files; root sparse runs keep the cone; full clones
1744    /// keep everything.
1745    #[test]
1746    fn materialization_scope_filters_to_the_needed_working_set() {
1747        let subdir = MaterializationScope {
1748            subdir_prefix: Some("apps/web".to_string()),
1749            sparse_dirs: None,
1750        };
1751        assert!(subdir.should_materialize(Path::new("apps/web/a.ts")));
1752        assert!(subdir.should_materialize(Path::new("top.ts")));
1753        assert!(subdir.should_materialize(Path::new(".gitignore")));
1754        assert!(subdir.should_materialize(Path::new("apps/.gitignore")));
1755        assert!(!subdir.should_materialize(Path::new("apps/other/b.ts")));
1756        assert!(!subdir.should_materialize(Path::new("apps/.gitignore.bak")));
1757
1758        let sparse = MaterializationScope {
1759            subdir_prefix: None,
1760            sparse_dirs: Some(vec!["apps/web".to_string()]),
1761        };
1762        assert!(sparse.should_materialize(Path::new("apps/web/a.ts")));
1763        assert!(sparse.should_materialize(Path::new("top.ts")));
1764        assert!(!sparse.should_materialize(Path::new("apps/other/b.ts")));
1765
1766        let full = MaterializationScope {
1767            subdir_prefix: None,
1768            sparse_dirs: None,
1769        };
1770        assert!(full.should_materialize(Path::new("apps/other/b.ts")));
1771    }
1772
1773    #[test]
1774    fn default_workspace_ref_skips_projects_without_workspaces() {
1775        assert!(default_workspace_ref_for_workspaces(Path::new("/repo"), &[]).is_none());
1776    }
1777
1778    #[test]
1779    fn default_workspace_ref_skips_non_git_workspace_projects() {
1780        let workspace = WorkspaceInfo {
1781            root: PathBuf::from("/repo/packages/app"),
1782            name: "app".to_owned(),
1783            is_internal_dependency: false,
1784        };
1785
1786        assert!(default_workspace_ref_for_workspaces(Path::new("/repo"), &[workspace]).is_none());
1787    }
1788
1789    #[test]
1790    fn current_user_identities_empty_when_git_config_is_unavailable() {
1791        assert!(current_user_identities(Path::new("/repo")).is_empty());
1792    }
1793
1794    #[test]
1795    fn short_head_sha_omits_git_line_ending() {
1796        let temp = tempfile::tempdir().expect("temp dir");
1797        let repo = temp.path().join("repo");
1798        init_repo(&repo);
1799        fs::write(repo.join("tracked.txt"), "committed\n").expect("write tracked file");
1800        commit_all(&repo, "initial");
1801
1802        let sha = short_head_sha(&repo).expect("HEAD sha");
1803        assert_eq!(sha, sha.trim());
1804        assert!(!sha.is_empty());
1805    }
1806
1807    #[test]
1808    fn short_head_sha_is_absent_outside_a_git_repo() {
1809        let temp = tempfile::tempdir().expect("temp dir");
1810
1811        assert_eq!(short_head_sha(temp.path()), None);
1812    }
1813
1814    /// Regression for issue #2699: the detected ref is handed straight back to
1815    /// git as a diff target, so it must carry no line ending. Without the
1816    /// trimmed probe contract the upstream is `origin/main\n`, the merge-base
1817    /// call against it fails, and the detection degrades to the tip branch with
1818    /// an unusable ref.
1819    #[test]
1820    fn auto_detect_audit_base_ref_omits_git_line_endings_for_the_upstream_merge_base() {
1821        let temp = tempfile::tempdir().expect("temp dir");
1822        let repo = temp.path().join("repo");
1823        init_repo(&repo);
1824        fs::write(repo.join("tracked.txt"), "committed\n").expect("write tracked file");
1825        commit_all(&repo, "initial");
1826        let fork_point = git(&repo, &["rev-parse", "HEAD"]);
1827        git(&repo, &["remote", "add", "origin", &repo.to_string_lossy()]);
1828        git(&repo, &["update-ref", "refs/remotes/origin/main", "main"]);
1829        git(&repo, &["checkout", "-b", "feature"]);
1830        git(
1831            &repo,
1832            &["branch", "--set-upstream-to=origin/main", "feature"],
1833        );
1834        fs::write(repo.join("feature.txt"), "my change\n").expect("write feature file");
1835        commit_all(&repo, "feature");
1836
1837        let detected = auto_detect_audit_base_ref(&repo).expect("base is detected");
1838
1839        assert_eq!(detected.git_ref, fork_point);
1840        assert_eq!(
1841            detected.description.as_deref(),
1842            Some("merge-base with origin/main")
1843        );
1844        assert!(crate::validate::validate_git_ref(&detected.git_ref).is_ok());
1845    }
1846
1847    /// Regression for issue #2699 on the remote-default branch of the
1848    /// detection, where the line ending survives `strip_prefix` and reappears
1849    /// inside the composed `origin/<branch>` ref.
1850    #[test]
1851    fn auto_detect_audit_base_ref_omits_git_line_endings_for_the_remote_default() {
1852        let temp = tempfile::tempdir().expect("temp dir");
1853        let repo = temp.path().join("repo");
1854        init_repo(&repo);
1855        fs::write(repo.join("tracked.txt"), "committed\n").expect("write tracked file");
1856        commit_all(&repo, "initial");
1857        let fork_point = git(&repo, &["rev-parse", "HEAD"]);
1858        git(&repo, &["update-ref", "refs/remotes/origin/main", "main"]);
1859        git(
1860            &repo,
1861            &[
1862                "symbolic-ref",
1863                "refs/remotes/origin/HEAD",
1864                "refs/remotes/origin/main",
1865            ],
1866        );
1867
1868        let detected = auto_detect_audit_base_ref(&repo).expect("base is detected");
1869
1870        assert_eq!(detected.git_ref, fork_point);
1871        assert_eq!(
1872            detected.description.as_deref(),
1873            Some("merge-base with origin/main")
1874        );
1875        assert!(crate::validate::validate_git_ref(&detected.git_ref).is_ok());
1876    }
1877
1878    #[test]
1879    fn auto_detect_audit_base_ref_resolves_origin_default_to_merge_base() {
1880        let temp = tempfile::tempdir().expect("temp dir");
1881        let repo = seeded_repo(temp.path());
1882        let head = git(&repo, &["rev-parse", "HEAD"]);
1883        git(&repo, &["branch", "trunk"]);
1884        git(&repo, &["update-ref", "refs/remotes/origin/trunk", "trunk"]);
1885        git(
1886            &repo,
1887            &[
1888                "symbolic-ref",
1889                "refs/remotes/origin/HEAD",
1890                "refs/remotes/origin/trunk",
1891            ],
1892        );
1893
1894        let detected = auto_detect_audit_base_ref(&repo).expect("base is detected");
1895
1896        // trunk == HEAD, so the merge-base is HEAD's own SHA. The bare branch
1897        // name `trunk` is never returned: it would resolve to a local ref.
1898        assert_eq!(detected.git_ref, head);
1899        assert_eq!(
1900            detected.description.as_deref(),
1901            Some("merge-base with origin/trunk")
1902        );
1903    }
1904
1905    /// Regression for issue #1168: a worktree checkout whose local `main` is
1906    /// stale relative to a fresh `origin/main`. The base must be the fork point
1907    /// (merge-base with `origin/main`), NOT the stale local-`main` commit that
1908    /// the old bare-name resolution diffed against.
1909    #[test]
1910    fn auto_detect_audit_base_ref_ignores_stale_local_main() {
1911        let temp = tempfile::tempdir().expect("temp dir");
1912        let repo = seeded_repo(temp.path());
1913        let stale = git(&repo, &["rev-parse", "HEAD"]);
1914
1915        git(&repo, &["update-ref", "refs/remotes/origin/main", "main"]);
1916        git(
1917            &repo,
1918            &[
1919                "symbolic-ref",
1920                "refs/remotes/origin/HEAD",
1921                "refs/remotes/origin/main",
1922            ],
1923        );
1924        let fork_point = commit_file(&repo, "teammate.txt", "merged work\n");
1925        git(&repo, &["update-ref", "refs/remotes/origin/main", "main"]);
1926
1927        // Cut a feature branch from the fresh origin tip using the raw SHA (no
1928        // upstream tracking), then leave local `main` behind at the stale commit.
1929        git(&repo, &["checkout", "-b", "feature", &fork_point]);
1930        commit_file(&repo, "feature.txt", "my change\n");
1931        git(&repo, &["branch", "-f", "main", &stale]);
1932
1933        let detected = auto_detect_audit_base_ref(&repo).expect("base is detected");
1934
1935        assert_eq!(
1936            detected.git_ref, fork_point,
1937            "base must be the fork point (origin/main), not stale local main"
1938        );
1939        assert_eq!(
1940            detected.description.as_deref(),
1941            Some("merge-base with origin/main")
1942        );
1943    }
1944
1945    #[test]
1946    fn auto_detect_audit_base_ref_prefers_configured_upstream() {
1947        let temp = tempfile::tempdir().expect("temp dir");
1948        let repo = seeded_repo(temp.path());
1949        let fork_point = git(&repo, &["rev-parse", "HEAD"]);
1950        // Configure `origin` so refs/remotes/origin/* are recognized as
1951        // tracking refs and `--set-upstream-to` is accepted.
1952        git(&repo, &["remote", "add", "origin", &repo.to_string_lossy()]);
1953        git(&repo, &["update-ref", "refs/remotes/origin/main", "main"]);
1954        git(&repo, &["checkout", "-b", "feature"]);
1955        git(
1956            &repo,
1957            &["branch", "--set-upstream-to=origin/main", "feature"],
1958        );
1959        commit_file(&repo, "feature.txt", "my change\n");
1960
1961        let detected = auto_detect_audit_base_ref(&repo).expect("base is detected");
1962
1963        assert_eq!(detected.git_ref, fork_point);
1964        assert_eq!(
1965            detected.description.as_deref(),
1966            Some("merge-base with origin/main")
1967        );
1968    }
1969
1970    /// A repo with `origin/main` one commit ahead of the fork point of the
1971    /// branch `feature`. Returns the repo, the fork point and the tip of
1972    /// `origin/main`.
1973    fn repo_with_newer_main(root: &Path) -> (PathBuf, String, String) {
1974        let repo = seeded_repo(root);
1975        let fork_point = git(&repo, &["rev-parse", "HEAD"]);
1976        git(&repo, &["remote", "add", "origin", &repo.to_string_lossy()]);
1977        commit_file(&repo, "main.txt", "main change\n");
1978        let main_tip = git(&repo, &["rev-parse", "HEAD"]);
1979        git(&repo, &["update-ref", "refs/remotes/origin/main", "main"]);
1980        git(&repo, &["checkout", "-b", "feature", &fork_point]);
1981        commit_file(&repo, "feature.txt", "my change\n");
1982        (repo, fork_point, main_tip)
1983    }
1984
1985    #[test]
1986    fn merged_default_branch_refs_is_empty_without_a_merge() {
1987        let temp = tempfile::tempdir().expect("temp dir");
1988        let (repo, fork_point, _) = repo_with_newer_main(temp.path());
1989
1990        assert!(merged_default_branch_refs(&repo, &fork_point).is_empty());
1991    }
1992
1993    #[test]
1994    fn merged_default_branch_refs_names_the_merge_head_of_the_default_branch() {
1995        let temp = tempfile::tempdir().expect("temp dir");
1996        let (repo, fork_point, main_tip) = repo_with_newer_main(temp.path());
1997        git(&repo, &["merge", "--no-commit", "--no-ff", "origin/main"]);
1998
1999        assert_eq!(merged_default_branch_refs(&repo, &fork_point), [main_tip]);
2000    }
2001
2002    #[test]
2003    fn merged_default_branch_refs_names_the_merged_default_after_a_merge_commit() {
2004        let temp = tempfile::tempdir().expect("temp dir");
2005        let (repo, fork_point, main_tip) = repo_with_newer_main(temp.path());
2006        let pushed = git(&repo, &["rev-parse", "HEAD"]);
2007        git(&repo, &["merge", "--no-ff", "--no-edit", "origin/main"]);
2008
2009        assert_eq!(
2010            merged_default_branch_refs(&repo, &pushed),
2011            std::slice::from_ref(&main_tip)
2012        );
2013        // A base that already contains the merged commit gains nothing.
2014        assert!(merged_default_branch_refs(&repo, &main_tip).is_empty());
2015        assert_ne!(fork_point, main_tip);
2016    }
2017
2018    #[test]
2019    fn merged_default_branch_refs_names_the_new_default_after_a_rebase() {
2020        let temp = tempfile::tempdir().expect("temp dir");
2021        let (repo, fork_point, main_tip) = repo_with_newer_main(temp.path());
2022        git(&repo, &["rebase", "-q", "origin/main"]);
2023
2024        // The upstream still holds the pre-rebase branch, so the base is the
2025        // old fork point. The new default commit that the rebase moved under
2026        // the branch is inherited.
2027        assert_eq!(merged_default_branch_refs(&repo, &fork_point), [main_tip]);
2028    }
2029
2030    #[test]
2031    fn merged_default_branch_refs_ignores_a_branch_that_the_default_branch_lacks() {
2032        let temp = tempfile::tempdir().expect("temp dir");
2033        let (repo, fork_point, _) = repo_with_newer_main(temp.path());
2034        git(&repo, &["checkout", "-b", "side", &fork_point]);
2035        commit_file(&repo, "side.txt", "side change\n");
2036        git(&repo, &["checkout", "feature"]);
2037        let base = git(&repo, &["rev-parse", "HEAD"]);
2038        git(&repo, &["merge", "--no-commit", "--no-ff", "side"]);
2039
2040        assert!(merged_default_branch_refs(&repo, &base).is_empty());
2041    }
2042
2043    #[test]
2044    fn merged_default_branch_refs_skips_a_commit_that_git_cannot_place() {
2045        let temp = tempfile::tempdir().expect("temp dir");
2046        let (repo, _, _) = repo_with_newer_main(temp.path());
2047        git(&repo, &["merge", "--no-commit", "--no-ff", "origin/main"]);
2048
2049        // An unknown base makes the ancestry check fail: no ref is inherited.
2050        assert!(
2051            merged_default_branch_refs(&repo, "0000000000000000000000000000000000000000")
2052                .is_empty()
2053        );
2054    }
2055
2056    #[test]
2057    fn auto_detect_audit_base_ref_falls_back_to_local_main_without_remote() {
2058        let temp = tempfile::tempdir().expect("temp dir");
2059        let repo = seeded_repo(temp.path());
2060
2061        let detected = auto_detect_audit_base_ref(&repo).expect("base is detected");
2062
2063        assert_eq!(detected.git_ref, "main");
2064        assert_eq!(detected.description.as_deref(), Some("local main"));
2065    }
2066
2067    #[test]
2068    fn auto_detect_audit_base_ref_falls_back_to_local_master_without_remote() {
2069        let temp = tempfile::tempdir().expect("temp dir");
2070        let repo = temp.path().join("repo");
2071        fs::create_dir_all(&repo).expect("create repo");
2072        git(&repo, &["init", "-b", "master"]);
2073        git(&repo, &["config", "user.name", "Test User"]);
2074        git(&repo, &["config", "user.email", "test@example.com"]);
2075        git(&repo, &["config", "commit.gpgsign", "false"]);
2076        fs::write(repo.join("README.md"), "seed\n").expect("write seed");
2077        commit_all(&repo, "initial");
2078
2079        let detected = auto_detect_audit_base_ref(&repo).expect("base is detected");
2080
2081        assert_eq!(detected.git_ref, "master");
2082        assert_eq!(detected.description.as_deref(), Some("local master"));
2083    }
2084
2085    #[test]
2086    fn auto_detect_audit_base_ref_returns_none_outside_git_repo() {
2087        let temp = tempfile::tempdir().expect("temp dir");
2088
2089        assert!(auto_detect_audit_base_ref(temp.path()).is_none());
2090    }
2091
2092    /// When the remote default shares no history with HEAD (the merge-base
2093    /// failure a shallow clone also hits), auto-detect falls back to the
2094    /// remote-tracking ref tip rather than failing the detection. That tip is
2095    /// the only branch that returns a ref git composed rather than printed, so
2096    /// it also pins the trimming for issue #2699.
2097    #[test]
2098    fn auto_detect_audit_base_ref_falls_back_to_remote_tip_without_common_ancestor() {
2099        let temp = tempfile::tempdir().expect("temp dir");
2100        let repo = seeded_repo(temp.path());
2101        git(&repo, &["checkout", "--orphan", "unrelated"]);
2102        let unrelated = commit_file(&repo, "unrelated.txt", "no shared history\n");
2103        git(
2104            &repo,
2105            &["update-ref", "refs/remotes/origin/main", &unrelated],
2106        );
2107        git(
2108            &repo,
2109            &[
2110                "symbolic-ref",
2111                "refs/remotes/origin/HEAD",
2112                "refs/remotes/origin/main",
2113            ],
2114        );
2115        git(&repo, &["checkout", "main"]);
2116
2117        let detected = auto_detect_audit_base_ref(&repo).expect("base is detected");
2118
2119        assert_eq!(detected.git_ref, "origin/main");
2120        assert_eq!(detected.description.as_deref(), Some("origin/main (tip)"));
2121    }
2122
2123    /// The repository top level is compared as a path prefix, so a line ending
2124    /// on it makes every subdirectory root fall back to the whole base
2125    /// worktree instead of the matching subdirectory (issue #2699).
2126    #[test]
2127    fn base_analysis_root_preserves_repo_subdirectory_roots() {
2128        let temp = tempfile::tempdir().expect("temp dir");
2129        let repo = temp.path().join("repo");
2130        init_repo(&repo);
2131        let app_root = repo.join("apps").join("mobile");
2132        fs::create_dir_all(&app_root).expect("create app root");
2133        let base_worktree = temp.path().join("base-worktree");
2134
2135        assert_eq!(
2136            base_analysis_root(&app_root, &base_worktree),
2137            base_worktree.join("apps").join("mobile")
2138        );
2139    }
2140
2141    /// A caller can spell the analysis root through a symbolic link, and git
2142    /// reports the resolved top level. The two path spaces must meet, or the
2143    /// prefix comparison fails and the base snapshot covers the whole base
2144    /// worktree while the head snapshot stays scoped (issue #2740).
2145    #[cfg(unix)]
2146    #[test]
2147    fn base_analysis_root_maps_a_symlinked_root_spelling() {
2148        let temp = tempfile::tempdir().expect("temp dir");
2149        let real_parent = temp.path().join("real");
2150        let repo = real_parent.join("repo");
2151        init_repo(&repo);
2152        let app_root = repo.join("apps").join("mobile");
2153        fs::create_dir_all(&app_root).expect("create app root");
2154        let linked_parent = temp.path().join("linked");
2155        std::os::unix::fs::symlink(&real_parent, &linked_parent).expect("link the parent");
2156        let base_worktree = temp.path().join("base-worktree");
2157
2158        let linked_app_root = linked_parent.join("repo").join("apps").join("mobile");
2159        assert_eq!(
2160            base_analysis_root(&linked_app_root, &base_worktree),
2161            base_worktree.join("apps").join("mobile")
2162        );
2163    }
2164
2165    #[test]
2166    fn remap_cache_dir_moves_a_cache_under_the_root_into_the_base_worktree() {
2167        let temp = tempfile::tempdir().expect("temp dir");
2168        let root = temp.path().join("repo");
2169        let base = temp.path().join("fallow-base");
2170        let cache_dir = root.join(".cache").join("fallow");
2171
2172        assert_eq!(
2173            remap_cache_dir_for_base_worktree(&root, &base, &cache_dir),
2174            base.join(".cache").join("fallow")
2175        );
2176    }
2177
2178    #[test]
2179    fn remap_cache_dir_keeps_an_absolute_cache_outside_the_root() {
2180        let temp = tempfile::tempdir().expect("temp dir");
2181        let root = temp.path().join("repo");
2182        let base = temp.path().join("fallow-base");
2183        let cache_dir = temp.path().join("shared").join("fallow-cache");
2184
2185        assert_eq!(
2186            remap_cache_dir_for_base_worktree(&root, &base, &cache_dir),
2187            cache_dir
2188        );
2189    }
2190
2191    #[test]
2192    fn remap_cache_dir_keeps_a_relative_cache() {
2193        let temp = tempfile::tempdir().expect("temp dir");
2194        let root = temp.path().join("repo");
2195        let base = temp.path().join("fallow-base");
2196        let cache_dir = Path::new(".fallow").join("cache");
2197
2198        assert_eq!(
2199            remap_cache_dir_for_base_worktree(&root, &base, &cache_dir),
2200            cache_dir
2201        );
2202    }
2203
2204    /// The root can be spelled through a symbolic link while the cache path
2205    /// is the real path. The two spellings must meet, or the base snapshot
2206    /// writes its cache into the head tree (issue #2758).
2207    #[cfg(unix)]
2208    #[test]
2209    fn remap_cache_dir_maps_a_symlinked_root_spelling() {
2210        let temp = tempfile::tempdir().expect("temp dir");
2211        let real_root = temp.path().join("real");
2212        fs::create_dir_all(&real_root).expect("create real root");
2213        let linked_root = temp.path().join("linked");
2214        std::os::unix::fs::symlink(&real_root, &linked_root).expect("link the root");
2215        let base = temp.path().join("fallow-base");
2216        let real_cache = dunce::canonicalize(&real_root)
2217            .expect("canonical root")
2218            .join(".fallow");
2219
2220        assert_eq!(
2221            remap_cache_dir_for_base_worktree(&linked_root, &base, &real_cache),
2222            base.join(".fallow")
2223        );
2224    }
2225
2226    #[test]
2227    fn head_sha_is_none_before_the_first_commit() {
2228        let temp = tempfile::tempdir().expect("temp dir");
2229        let repo = temp.path().join("repo");
2230        init_repo(&repo);
2231
2232        assert_eq!(head_sha(&repo).expect("git starts"), None);
2233    }
2234
2235    #[test]
2236    fn head_sha_returns_the_full_sha() {
2237        let temp = tempfile::tempdir().expect("temp dir");
2238        let repo = seeded_repo(temp.path());
2239
2240        let sha = head_sha(&repo).expect("git starts").expect("HEAD resolves");
2241        assert_eq!(sha, git(&repo, &["rev-parse", "HEAD"]));
2242    }
2243
2244    /// Auditing a package added on the branch is the ordinary case where the
2245    /// remapped root is absent from the base worktree. Consumers need that
2246    /// reported rather than validating the joined path and refusing the call
2247    /// (issue #2699).
2248    #[test]
2249    fn resolve_base_analysis_root_reports_a_root_absent_from_the_base() {
2250        let temp = tempfile::tempdir().expect("temp dir");
2251        let repo = temp.path().join("repo");
2252        init_repo(&repo);
2253        let existing_root = repo.join("apps").join("mobile");
2254        fs::create_dir_all(&existing_root).expect("create existing root");
2255        let new_root = repo.join("apps").join("new");
2256        fs::create_dir_all(&new_root).expect("create new root");
2257
2258        let base_worktree = temp.path().join("base-worktree");
2259        fs::create_dir_all(base_worktree.join("apps").join("mobile"))
2260            .expect("create base subdirectory");
2261
2262        assert_eq!(
2263            resolve_base_analysis_root(&existing_root, &base_worktree),
2264            BaseAnalysisRoot::Present(base_worktree.join("apps").join("mobile"))
2265        );
2266        assert_eq!(
2267            resolve_base_analysis_root(&new_root, &base_worktree),
2268            BaseAnalysisRoot::NewInHead(base_worktree.join("apps").join("new"))
2269        );
2270    }
2271
2272    #[cfg(unix)]
2273    #[test]
2274    fn temporary_base_worktree_does_not_run_post_checkout_hook() {
2275        let temp = tempfile::tempdir().expect("temp dir");
2276        let repo = temp.path().join("repo");
2277        init_repo(&repo);
2278        fs::write(repo.join("tracked.txt"), "committed\n").expect("write tracked file");
2279        commit_all(&repo, "initial");
2280
2281        let sentinel = temp.path().join("post-checkout-ran");
2282        write_executable(
2283            &repo.join(".git/hooks/post-checkout"),
2284            &format!("#!/bin/sh\nprintf ran > '{}'\n", sentinel.display()),
2285        );
2286
2287        let worktree = TemporaryBaseWorktree::create(&repo, "HEAD", &[])
2288            .expect("temporary worktree should be created");
2289
2290        assert_eq!(
2291            fs::read_to_string(worktree.path().join("tracked.txt")).expect("read tracked file"),
2292            "committed\n"
2293        );
2294        assert!(
2295            !sentinel.exists(),
2296            "creating a base view must not execute post-checkout hooks"
2297        );
2298    }
2299
2300    #[cfg(unix)]
2301    #[test]
2302    fn temporary_base_worktree_does_not_run_post_index_change_hook() {
2303        let temp = tempfile::tempdir().expect("temp dir");
2304        let repo = temp.path().join("repo");
2305        init_repo(&repo);
2306        fs::write(repo.join("tracked.txt"), "committed\n").expect("write tracked file");
2307        commit_all(&repo, "initial");
2308
2309        let sentinel = temp.path().join("post-index-change-ran");
2310        write_executable(
2311            &repo.join(".git/hooks/post-index-change"),
2312            &format!("#!/bin/sh\nprintf ran > '{}'\n", sentinel.display()),
2313        );
2314
2315        let worktree = TemporaryBaseWorktree::create(&repo, "HEAD", &[])
2316            .expect("temporary worktree should be created");
2317
2318        assert_eq!(
2319            fs::read_to_string(worktree.path().join("tracked.txt")).expect("read tracked file"),
2320            "committed\n"
2321        );
2322        assert!(
2323            !sentinel.exists(),
2324            "creating a base view must not execute post-index-change hooks"
2325        );
2326    }
2327
2328    #[cfg(unix)]
2329    #[test]
2330    fn temporary_base_worktree_does_not_run_smudge_filter() {
2331        let temp = tempfile::tempdir().expect("temp dir");
2332        let repo = temp.path().join("repo");
2333        init_repo(&repo);
2334        fs::write(
2335            repo.join(".gitattributes"),
2336            "filtered.txt filter=sentinel\n",
2337        )
2338        .expect("write attributes");
2339        fs::write(repo.join("filtered.txt"), "committed raw bytes\n").expect("write filtered file");
2340        commit_all(&repo, "initial");
2341
2342        let sentinel = temp.path().join("smudge-ran");
2343        let filter = temp.path().join("smudge-filter.sh");
2344        write_executable(
2345            &filter,
2346            &format!(
2347                "#!/bin/sh\nprintf ran > '{}'\ncat >/dev/null\nprintf 'smudged bytes\\n'\n",
2348                sentinel.display()
2349            ),
2350        );
2351        git(
2352            &repo,
2353            &[
2354                "config",
2355                "filter.sentinel.smudge",
2356                filter.to_str().expect("filter path is UTF-8"),
2357            ],
2358        );
2359
2360        let worktree = TemporaryBaseWorktree::create(&repo, "HEAD", &[])
2361            .expect("temporary worktree should be created");
2362
2363        assert_eq!(
2364            fs::read(worktree.path().join("filtered.txt")).expect("read filtered file"),
2365            b"committed raw bytes\n"
2366        );
2367        assert!(
2368            !sentinel.exists(),
2369            "creating a base view must not execute smudge filters"
2370        );
2371    }
2372
2373    #[cfg(unix)]
2374    #[test]
2375    fn temporary_base_worktree_does_not_start_process_filter() {
2376        let temp = tempfile::tempdir().expect("temp dir");
2377        let repo = temp.path().join("repo");
2378        init_repo(&repo);
2379        fs::write(
2380            repo.join(".gitattributes"),
2381            "filtered.txt filter=sentinel\n",
2382        )
2383        .expect("write attributes");
2384        fs::write(repo.join("filtered.txt"), "committed raw bytes\n").expect("write filtered file");
2385        commit_all(&repo, "initial");
2386
2387        let sentinel = temp.path().join("process-filter-ran");
2388        let filter = temp.path().join("process-filter.sh");
2389        write_executable(
2390            &filter,
2391            &format!("#!/bin/sh\nprintf ran > '{}'\nexit 1\n", sentinel.display()),
2392        );
2393        git(
2394            &repo,
2395            &[
2396                "config",
2397                "filter.sentinel.process",
2398                filter.to_str().expect("filter path is UTF-8"),
2399            ],
2400        );
2401
2402        let worktree = TemporaryBaseWorktree::create(&repo, "HEAD", &[])
2403            .expect("temporary worktree should be created");
2404
2405        assert_eq!(
2406            fs::read(worktree.path().join("filtered.txt")).expect("read filtered file"),
2407            b"committed raw bytes\n"
2408        );
2409        assert!(
2410            !sentinel.exists(),
2411            "creating a base view must not start process filters"
2412        );
2413    }
2414
2415    #[test]
2416    fn failed_registration_does_not_remove_existing_worktree() {
2417        let temp = tempfile::tempdir().expect("temp dir");
2418        let repo = temp.path().join("repo");
2419        init_repo(&repo);
2420        fs::write(repo.join("tracked.txt"), "committed\n").expect("write tracked file");
2421        commit_all(&repo, "initial");
2422        let destination = temp.path().join("base");
2423
2424        create_detached_base_worktree(&repo, &destination, "HEAD")
2425            .expect("first worktree should be created");
2426        let second = create_detached_base_worktree(&repo, &destination, "HEAD");
2427
2428        assert!(second.is_err(), "duplicate destination must fail");
2429        assert!(
2430            destination.join("tracked.txt").is_file(),
2431            "failed registration must not remove the existing worktree"
2432        );
2433        assert_eq!(git(&destination, &["rev-parse", "HEAD"]).len(), 40);
2434
2435        remove_registered_worktree(&repo, &destination);
2436        let _ = fs::remove_dir_all(destination);
2437    }
2438
2439    #[cfg(unix)]
2440    #[test]
2441    fn temporary_base_worktree_preserves_modes_symlinks_and_gitlinks() {
2442        use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
2443
2444        let temp = tempfile::tempdir().expect("temp dir");
2445        let repo = temp.path().join("repo");
2446        init_repo(&repo);
2447        fs::write(repo.join("regular.txt"), "regular\n").expect("write regular file");
2448        let executable = repo.join("run.sh");
2449        fs::write(&executable, "#!/bin/sh\nexit 0\n").expect("write executable");
2450        let mut permissions = fs::metadata(&executable)
2451            .expect("executable metadata")
2452            .permissions();
2453        permissions.set_mode(0o755);
2454        fs::set_permissions(&executable, permissions).expect("set executable mode");
2455        std::os::unix::fs::symlink("regular.txt", repo.join("regular-link"))
2456            .expect("create symlink");
2457        commit_all(&repo, "files");
2458
2459        let gitlink_commit = git(&repo, &["rev-parse", "HEAD"]);
2460        git(
2461            &repo,
2462            &[
2463                "update-index",
2464                "--add",
2465                "--cacheinfo",
2466                &format!("160000,{gitlink_commit},vendor/submodule"),
2467            ],
2468        );
2469        git(&repo, &["commit", "-m", "gitlink"]);
2470
2471        let worktree = TemporaryBaseWorktree::create(&repo, "HEAD", &[])
2472            .expect("temporary worktree should be created");
2473        let regular_mode = fs::metadata(worktree.path().join("regular.txt"))
2474            .expect("regular metadata")
2475            .mode();
2476        let executable_mode = fs::metadata(worktree.path().join("run.sh"))
2477            .expect("executable metadata")
2478            .mode();
2479
2480        assert_eq!(regular_mode & 0o111, 0);
2481        assert_ne!(executable_mode & 0o111, 0);
2482        assert_eq!(
2483            fs::read_link(worktree.path().join("regular-link")).expect("read symlink"),
2484            PathBuf::from("regular.txt")
2485        );
2486        let gitlink = worktree.path().join("vendor/submodule");
2487        assert!(gitlink.is_dir(), "gitlink must materialize as a directory");
2488        assert!(
2489            fs::read_dir(gitlink)
2490                .expect("read gitlink directory")
2491                .next()
2492                .is_none(),
2493            "an uninitialized gitlink directory must remain empty"
2494        );
2495        // No index after deregistration: `base_worktree_registration` checks it.
2496
2497        let path = worktree.path().to_path_buf();
2498        drop(worktree);
2499        assert!(!path.exists(), "temporary worktree must clean up on drop");
2500    }
2501
2502    #[test]
2503    fn materialized_tree_paths_reject_traversal_and_git_admin_aliases() {
2504        for path in [
2505            Path::new("../escape"),
2506            Path::new("/absolute"),
2507            Path::new(".git/config"),
2508            Path::new("nested/.GIT/config"),
2509            Path::new("nested/.git. /config"),
2510            Path::new("nested/git~1/config"),
2511        ] {
2512            assert!(
2513                validate_materialized_path(path).is_err(),
2514                "unsafe path should be rejected: {}",
2515                path.display()
2516            );
2517        }
2518        assert!(validate_materialized_path(Path::new("src/.github/file.ts")).is_ok());
2519    }
2520
2521    #[cfg(unix)]
2522    #[test]
2523    fn parent_directory_creation_refuses_symlink_traversal() {
2524        let temp = tempfile::tempdir().expect("temp dir");
2525        let root = temp.path().join("root");
2526        let outside = temp.path().join("outside");
2527        fs::create_dir(&root).expect("create root");
2528        fs::create_dir(&outside).expect("create outside");
2529        std::os::unix::fs::symlink(&outside, root.join("link")).expect("create parent symlink");
2530
2531        let result = create_safe_parent_directories(&root, Path::new("link/escaped.txt"));
2532
2533        assert!(result.is_err(), "symlink parent must be rejected");
2534        assert!(!outside.join("escaped.txt").exists());
2535    }
2536
2537    #[test]
2538    fn audit_context_fingerprint_tracks_bounded_lockfiles_and_markers() {
2539        let temp = tempfile::tempdir().expect("temp dir");
2540        let root = temp.path();
2541        fs::write(root.join("pnpm-lock.yaml"), "lockfileVersion: 9\n").expect("lockfile");
2542        fs::create_dir(root.join("node_modules")).expect("node_modules");
2543        fs::write(
2544            root.join("node_modules/.modules.yaml"),
2545            "layoutVersion: 5\n",
2546        )
2547        .expect("node marker");
2548
2549        let first = audit_materialized_context_fingerprint(root, &[]);
2550        let unchanged = audit_materialized_context_fingerprint(root, &[]);
2551        assert_eq!(
2552            first, unchanged,
2553            "unchanged context must preserve a warm key"
2554        );
2555
2556        fs::write(root.join("pnpm-lock.yaml"), "lockfileVersion: 10\n").expect("mutate lockfile");
2557        let lock_changed = audit_materialized_context_fingerprint(root, &[]);
2558        assert_ne!(
2559            first, lock_changed,
2560            "lockfile content must invalidate the key"
2561        );
2562
2563        fs::write(
2564            root.join("node_modules/.modules.yaml"),
2565            "layoutVersion: 6\n",
2566        )
2567        .expect("mutate node marker");
2568        let marker_changed = audit_materialized_context_fingerprint(root, &[]);
2569        assert_ne!(
2570            lock_changed, marker_changed,
2571            "bounded dependency markers must invalidate the key"
2572        );
2573
2574        fs::create_dir(root.join(".nuxt")).expect("nuxt context");
2575        fs::write(root.join(".nuxt/imports.d.ts"), "export {}\n").expect("nuxt marker");
2576        assert_ne!(
2577            marker_changed,
2578            audit_materialized_context_fingerprint(root, &[]),
2579            "missing and materialized generated context must differ"
2580        );
2581    }
2582
2583    #[test]
2584    fn audit_context_fingerprint_tracks_nested_workspace_generated_roots() {
2585        let temp = tempfile::tempdir().expect("temp dir");
2586        let root = temp.path();
2587        fs::write(
2588            root.join("package.json"),
2589            r#"{"private":true,"workspaces":["packages/*"]}"#,
2590        )
2591        .expect("root package");
2592        let nuxt = root.join("packages/nuxt-app");
2593        let astro = root.join("packages/astro-app");
2594        fs::create_dir_all(nuxt.join(".nuxt")).expect("nested nuxt context");
2595        fs::create_dir_all(astro.join(".astro")).expect("nested astro context");
2596        fs::write(nuxt.join("package.json"), r#"{"name":"nuxt-app"}"#).expect("nuxt package");
2597        fs::write(astro.join("package.json"), r#"{"name":"astro-app"}"#).expect("astro package");
2598        fs::write(nuxt.join(".nuxt/imports.d.ts"), "export {};\n").expect("nuxt marker");
2599        fs::write(astro.join(".astro/types.d.ts"), "export {};\n").expect("astro marker");
2600
2601        let first = audit_materialized_context_fingerprint(root, &[]);
2602        assert!(
2603            first
2604                .directories
2605                .iter()
2606                .any(|directory| directory.name == "packages/nuxt-app/.nuxt")
2607        );
2608        assert!(
2609            first
2610                .directories
2611                .iter()
2612                .any(|directory| directory.name == "packages/astro-app/.astro")
2613        );
2614
2615        fs::write(
2616            nuxt.join(".nuxt/imports.d.ts"),
2617            "export type Changed = true;\n",
2618        )
2619        .expect("mutate nuxt marker");
2620        assert_ne!(
2621            first,
2622            audit_materialized_context_fingerprint(root, &[]),
2623            "nested workspace marker changes must invalidate the audit context"
2624        );
2625    }
2626
2627    #[cfg(unix)]
2628    #[test]
2629    fn materialize_base_context_symlinks_nested_workspace_generated_roots() {
2630        let host = tempfile::tempdir().expect("host");
2631        let worktree = tempfile::tempdir().expect("worktree");
2632        fs::write(
2633            host.path().join("package.json"),
2634            r#"{"private":true,"workspaces":["packages/*"]}"#,
2635        )
2636        .expect("root package");
2637
2638        for (workspace, generated, marker) in [
2639            ("nuxt-app", ".nuxt", "imports.d.ts"),
2640            ("astro-app", ".astro", "types.d.ts"),
2641        ] {
2642            let host_workspace = host.path().join("packages").join(workspace);
2643            let worktree_workspace = worktree.path().join("packages").join(workspace);
2644            fs::create_dir_all(host_workspace.join(generated)).expect("host generated context");
2645            fs::create_dir_all(&worktree_workspace).expect("worktree workspace");
2646            fs::write(
2647                host_workspace.join("package.json"),
2648                format!(r#"{{"name":"{workspace}"}}"#),
2649            )
2650            .expect("workspace package");
2651            fs::write(host_workspace.join(generated).join(marker), "export {};\n")
2652                .expect("generated marker");
2653        }
2654
2655        materialize_base_dependency_context(host.path(), worktree.path(), &[]);
2656
2657        for (workspace, generated, marker) in [
2658            ("nuxt-app", ".nuxt", "imports.d.ts"),
2659            ("astro-app", ".astro", "types.d.ts"),
2660        ] {
2661            let mirrored = worktree
2662                .path()
2663                .join("packages")
2664                .join(workspace)
2665                .join(generated);
2666            assert!(
2667                fs::symlink_metadata(&mirrored)
2668                    .expect("mirrored generated root")
2669                    .file_type()
2670                    .is_symlink(),
2671                "{workspace}/{generated} must reuse the host generated root"
2672            );
2673            assert!(mirrored.join(marker).is_file());
2674        }
2675    }
2676
2677    #[cfg(unix)]
2678    #[test]
2679    fn materialize_base_context_resolves_symlinked_source_directories() {
2680        let host = tempfile::tempdir().expect("host");
2681        let targets = tempfile::tempdir().expect("targets");
2682        let worktree = tempfile::tempdir().expect("worktree");
2683
2684        for (kind, marker) in [
2685            ("node_modules", ".modules.yaml"),
2686            (".nuxt", "imports.d.ts"),
2687            (".astro", "types.d.ts"),
2688        ] {
2689            let target = targets.path().join(kind);
2690            fs::create_dir(&target).expect("source target");
2691            fs::write(target.join(marker), "generated context\n").expect("context marker");
2692            std::os::unix::fs::symlink(&target, host.path().join(kind))
2693                .expect("source directory symlink");
2694        }
2695
2696        materialize_base_dependency_context(host.path(), worktree.path(), &[]);
2697
2698        let fingerprint = audit_materialized_context_fingerprint(host.path(), &[]);
2699        for kind in &["node_modules", ".nuxt", ".astro"] {
2700            let target = dunce::canonicalize(targets.path().join(kind)).expect("canonical target");
2701            let mirrored = worktree.path().join(kind);
2702            assert_eq!(
2703                fs::read_link(&mirrored).expect("materialized symlink"),
2704                target,
2705                "{kind} must link directly to the validated canonical target"
2706            );
2707            let directory = fingerprint
2708                .directories
2709                .iter()
2710                .find(|directory| directory.name == *kind)
2711                .expect("fingerprinted context directory");
2712            assert_eq!(directory.state, AuditContextPathState::Present);
2713            assert!(directory.markers.iter().any(|marker| {
2714                matches!(marker.state, AuditContextPathState::Present)
2715                    && marker.content_hash.is_some()
2716            }));
2717        }
2718    }
2719
2720    /// A package that only the config patterns declare gets the same linked
2721    /// context and fingerprint entry as a package that a manifest declares.
2722    #[cfg(unix)]
2723    #[test]
2724    fn materialize_base_context_covers_config_pattern_workspaces() {
2725        let host = tempfile::tempdir().expect("host");
2726        let worktree = tempfile::tempdir().expect("worktree");
2727        fs::write(
2728            host.path().join("package.json"),
2729            r#"{"private":true,"workspaces":["packages/*"]}"#,
2730        )
2731        .expect("root package");
2732        let host_workspace = host.path().join("apps/web");
2733        fs::create_dir_all(host_workspace.join(".nuxt")).expect("host generated context");
2734        fs::write(host_workspace.join("package.json"), r#"{"name":"web"}"#)
2735            .expect("workspace package");
2736        fs::create_dir_all(worktree.path().join("apps/web")).expect("base workspace");
2737        let patterns = vec!["apps/*".to_owned()];
2738        let names = |patterns: &[String]| {
2739            audit_materialized_context_fingerprint(host.path(), patterns)
2740                .directories
2741                .into_iter()
2742                .map(|directory| directory.name)
2743                .collect::<Vec<_>>()
2744        };
2745
2746        assert!(!names(&[]).contains(&"apps/web/.nuxt".to_owned()));
2747        assert!(names(&patterns).contains(&"apps/web/.nuxt".to_owned()));
2748
2749        materialize_base_dependency_context(host.path(), worktree.path(), &patterns);
2750        assert!(
2751            fs::symlink_metadata(worktree.path().join("apps/web/.nuxt"))
2752                .expect("linked generated context")
2753                .file_type()
2754                .is_symlink()
2755        );
2756    }
2757
2758    #[cfg(unix)]
2759    #[test]
2760    fn materialize_base_context_refuses_symlinked_workspace_parent() {
2761        let host = tempfile::tempdir().expect("host");
2762        let worktree = tempfile::tempdir().expect("worktree");
2763        let outside = tempfile::tempdir().expect("outside");
2764        fs::write(
2765            host.path().join("package.json"),
2766            r#"{"private":true,"workspaces":["packages/*"]}"#,
2767        )
2768        .expect("root package");
2769        let host_workspace = host.path().join("packages/app");
2770        fs::create_dir_all(host_workspace.join(".nuxt")).expect("host generated context");
2771        fs::write(host_workspace.join("package.json"), r#"{"name":"app"}"#)
2772            .expect("workspace package");
2773        fs::write(host_workspace.join(".nuxt/imports.d.ts"), "export {};\n")
2774            .expect("generated marker");
2775
2776        let outside_workspace = outside.path().join("app");
2777        fs::create_dir_all(&outside_workspace).expect("outside workspace");
2778        let outside_generated = outside_workspace.join(".nuxt");
2779        std::os::unix::fs::symlink("missing-target", &outside_generated)
2780            .expect("outside sentinel symlink");
2781        std::os::unix::fs::symlink(outside.path(), worktree.path().join("packages"))
2782            .expect("hostile workspace parent symlink");
2783
2784        materialize_base_dependency_context(host.path(), worktree.path(), &[]);
2785
2786        assert_eq!(
2787            fs::read_link(&outside_generated).expect("sentinel symlink must survive"),
2788            PathBuf::from("missing-target")
2789        );
2790        assert!(
2791            !outside.path().join(".nuxt").exists(),
2792            "materialization must not create generated context outside the worktree"
2793        );
2794    }
2795
2796    #[test]
2797    fn audit_context_fingerprint_rejects_oversized_files_without_reading_them() {
2798        let temp = tempfile::tempdir().expect("temp dir");
2799        let path = temp.path().join("pnpm-lock.yaml");
2800        let file = File::create(&path).expect("oversized file");
2801        file.set_len(AUDIT_CONTEXT_FILE_MAX_BYTES.saturating_add(1))
2802            .expect("set oversized length");
2803
2804        let fingerprint = fingerprint_context_file_at(&path, "pnpm-lock.yaml");
2805
2806        assert_eq!(
2807            fingerprint.state,
2808            AuditContextPathState::Unreadable(CONTEXT_OVERSIZED_FILE_STATE.to_string())
2809        );
2810        assert!(fingerprint.source.is_some());
2811        assert!(fingerprint.content_hash.is_none());
2812    }
2813
2814    #[cfg(unix)]
2815    #[test]
2816    fn audit_context_fingerprint_rejects_symlinked_files_without_following_them() {
2817        let temp = tempfile::tempdir().expect("temp dir");
2818        let target = temp.path().join("target-lock.yaml");
2819        let link = temp.path().join("pnpm-lock.yaml");
2820        fs::write(&target, "secret target contents\n").expect("target file");
2821        std::os::unix::fs::symlink(&target, &link).expect("lockfile symlink");
2822
2823        let fingerprint = fingerprint_context_file_at(&link, "pnpm-lock.yaml");
2824
2825        assert_eq!(
2826            fingerprint.state,
2827            AuditContextPathState::Unreadable(CONTEXT_SYMLINK_STATE.to_string())
2828        );
2829        assert!(fingerprint.content_hash.is_none());
2830    }
2831
2832    #[cfg(unix)]
2833    #[test]
2834    fn audit_context_fingerprint_does_not_follow_symlink_swapped_before_open() {
2835        let temp = tempfile::tempdir().expect("temp dir");
2836        let path = temp.path().join("pnpm-lock.yaml");
2837        let target = temp.path().join("target-lock.yaml");
2838        fs::write(&path, "original contents\n").expect("original file");
2839        fs::write(&target, "secret target contents\n").expect("target file");
2840
2841        let fingerprint = fingerprint_context_file_at_with_hooks(
2842            &path,
2843            "pnpm-lock.yaml",
2844            || {
2845                fs::remove_file(&path).expect("remove original");
2846                std::os::unix::fs::symlink(&target, &path).expect("replacement symlink");
2847            },
2848            || {},
2849        );
2850
2851        assert_eq!(
2852            fingerprint.state,
2853            AuditContextPathState::Unreadable(CONTEXT_SYMLINK_STATE.to_string())
2854        );
2855        assert!(fingerprint.content_hash.is_none());
2856    }
2857
2858    #[test]
2859    fn audit_context_fingerprint_rejects_file_changed_during_read() {
2860        let temp = tempfile::tempdir().expect("temp dir");
2861        let path = temp.path().join("pnpm-lock.yaml");
2862        fs::write(&path, "original contents\n").expect("original file");
2863
2864        let fingerprint = fingerprint_context_file_at_with_hooks(
2865            &path,
2866            "pnpm-lock.yaml",
2867            || {},
2868            || {
2869                OpenOptions::new()
2870                    .write(true)
2871                    .open(&path)
2872                    .expect("open replacement")
2873                    .set_len(1)
2874                    .expect("truncate replacement");
2875            },
2876        );
2877
2878        assert_eq!(
2879            fingerprint.state,
2880            AuditContextPathState::Unreadable(CONTEXT_CHANGED_DURING_READ_STATE.to_string())
2881        );
2882        assert!(fingerprint.content_hash.is_none());
2883    }
2884
2885    #[cfg(unix)]
2886    #[test]
2887    fn unix_context_open_does_not_block_on_fifo() {
2888        let temp = tempfile::tempdir().expect("temp dir");
2889        let fifo = temp.path().join("pnpm-lock.yaml");
2890        let status = std::process::Command::new("mkfifo")
2891            .arg(&fifo)
2892            .status()
2893            .expect("run mkfifo");
2894        assert!(status.success(), "mkfifo must create the test pipe");
2895
2896        let fallback_fifo = fifo.clone();
2897        let fallback_writer = std::thread::spawn(move || {
2898            std::thread::sleep(std::time::Duration::from_secs(1));
2899            OpenOptions::new()
2900                .read(true)
2901                .write(true)
2902                .open(fallback_fifo)
2903                .expect("open fallback FIFO writer")
2904        });
2905        let started = std::time::Instant::now();
2906        let fingerprint = fingerprint_context_file_at(&fifo, "pnpm-lock.yaml");
2907        let elapsed = started.elapsed();
2908
2909        assert!(
2910            elapsed < std::time::Duration::from_millis(500),
2911            "nonblocking FIFO open took {elapsed:?}"
2912        );
2913        assert_eq!(
2914            fingerprint.state,
2915            AuditContextPathState::Unreadable(CONTEXT_SPECIAL_FILE_STATE.to_string())
2916        );
2917        assert!(fingerprint.content_hash.is_none());
2918        drop(fallback_writer.join().expect("fallback writer"));
2919    }
2920
2921    #[cfg(unix)]
2922    #[test]
2923    fn audit_context_fingerprint_rejects_special_files_without_opening_them() {
2924        use std::os::unix::net::UnixListener;
2925
2926        let temp = tempfile::tempdir().expect("temp dir");
2927        let socket = temp.path().join("pnpm-lock.yaml");
2928        let _listener = UnixListener::bind(&socket).expect("unix socket");
2929
2930        let fingerprint = fingerprint_context_file_at(&socket, "pnpm-lock.yaml");
2931
2932        assert_eq!(
2933            fingerprint.state,
2934            AuditContextPathState::Unreadable(CONTEXT_SPECIAL_FILE_STATE.to_string())
2935        );
2936        assert!(fingerprint.content_hash.is_none());
2937    }
2938}