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_base_root.rs"]
546mod base_root;
547#[path = "repo_refs_linked_worktree.rs"]
548mod linked_worktree;
549#[path = "repo_refs_scope.rs"]
550mod scope;
551pub use base_root::{BaseAnalysisRoot, resolve_base_analysis_root};
552use linked_worktree::make_worktree_root_private;
553pub use linked_worktree::{
554    create_staged_index_worktree, remove_staged_index_worktree, write_index_tree,
555};
556use scope::materialization_scope;
557pub use scope::materialization_scope_key;
558
559/// Return whether a linked worktree was completely materialized by the raw
560/// object path used by [`create_detached_base_worktree`].
561///
562/// Reusable audit caches created by older versions have no marker and must be
563/// rebuilt once so smudged or checkout-generated contents are not reused.
564#[must_use]
565pub fn detached_base_worktree_is_raw_materialized(worktree_root: &Path) -> bool {
566    raw_materialization_marker_path(worktree_root).is_ok_and(|path| path.is_file())
567}
568
569fn write_raw_materialization_marker(worktree_root: &Path) -> EngineResult<()> {
570    let marker = raw_materialization_marker_path(worktree_root)?;
571    fs::write(&marker, b"raw-v1\n").map_err(|error| {
572        EngineError::new(format!(
573            "could not record raw base-worktree materialization at `{}`: {error}",
574            marker.display()
575        ))
576    })
577}
578
579fn raw_materialization_marker_path(worktree_root: &Path) -> EngineResult<PathBuf> {
580    let marker = run_git(
581        worktree_root,
582        &["rev-parse", "--git-path", RAW_MATERIALIZATION_MARKER],
583    )
584    .ok_or_else(|| EngineError::new("could not resolve base-worktree materialization marker"))?;
585    let marker = PathBuf::from(marker);
586    if marker.is_absolute() {
587        Ok(marker)
588    } else {
589        Ok(worktree_root.join(marker))
590    }
591}
592
593fn register_no_checkout_worktree(
594    repo_root: &Path,
595    destination: &Path,
596    base_ref: &str,
597) -> EngineResult<()> {
598    let mut command = git_command(repo_root);
599    command.args([
600        "worktree",
601        "add",
602        "--detach",
603        "--quiet",
604        "--no-checkout",
605        "--",
606    ]);
607    command.arg(destination).arg(base_ref);
608    let output = command.output().map_err(|error| {
609        EngineError::new(format!(
610            "could not create a temporary worktree for base ref `{base_ref}`: {error}"
611        ))
612    })?;
613    if !output.status.success() {
614        return Err(EngineError::new(format!(
615            "could not create a temporary worktree for base ref `{base_ref}`: {}",
616            String::from_utf8_lossy(&output.stderr).trim()
617        )));
618    }
619    Ok(())
620}
621
622fn resolve_registered_commit(destination: &Path, base_ref: &str) -> EngineResult<String> {
623    run_git(destination, &["rev-parse", "--verify", "HEAD^{commit}"]).ok_or_else(|| {
624        EngineError::new(format!(
625            "could not resolve the commit for base ref `{base_ref}` after creating the worktree"
626        ))
627    })
628}
629
630fn populate_worktree_index(destination: &Path, commit: &str) -> EngineResult<()> {
631    let disabled_hooks_path = destination.join(".fallow-disabled-git-hooks");
632    let output = git_command(destination)
633        .env("GIT_CONFIG_COUNT", "2")
634        .env("GIT_CONFIG_KEY_0", "core.hooksPath")
635        .env("GIT_CONFIG_VALUE_0", disabled_hooks_path)
636        .env("GIT_CONFIG_KEY_1", "core.fsmonitor")
637        .env("GIT_CONFIG_VALUE_1", "false")
638        .args(["read-tree", "--reset", commit])
639        .output()
640        .map_err(|error| {
641            EngineError::new(format!("could not populate base worktree index: {error}"))
642        })?;
643    if !output.status.success() {
644        return Err(EngineError::new(format!(
645            "could not populate base worktree index: {}",
646            String::from_utf8_lossy(&output.stderr).trim()
647        )));
648    }
649    Ok(())
650}
651
652#[derive(Debug, Clone, Copy, PartialEq, Eq)]
653enum TreeEntryKind {
654    Regular,
655    Executable,
656    Symlink,
657    Gitlink,
658}
659
660#[derive(Debug)]
661struct TreeEntry {
662    kind: TreeEntryKind,
663    object_id: String,
664    path: PathBuf,
665}
666
667fn materialize_committed_tree(
668    repo_root: &Path,
669    destination: &Path,
670    commit: &str,
671) -> EngineResult<()> {
672    let entries = committed_tree_entries(repo_root, commit)?;
673    let scope = materialization_scope(repo_root);
674    let entries: Vec<TreeEntry> = entries
675        .into_iter()
676        .filter(|entry| scope.should_materialize(&entry.path))
677        .collect();
678    let mut blobs = BatchBlobReader::spawn(repo_root)?;
679    let mut symlinks = Vec::new();
680
681    for entry in entries {
682        create_safe_parent_directories(destination, &entry.path)?;
683        let output_path = destination.join(&entry.path);
684        match entry.kind {
685            TreeEntryKind::Regular | TreeEntryKind::Executable => {
686                let mut file = OpenOptions::new()
687                    .create_new(true)
688                    .write(true)
689                    .open(&output_path)
690                    .map_err(|error| materialization_error(&entry.path, error))?;
691                blobs.copy_blob(&entry.object_id, &entry.path, &mut file)?;
692                set_regular_file_mode(&output_path, entry.kind == TreeEntryKind::Executable)?;
693            }
694            TreeEntryKind::Symlink => {
695                let target = blobs.read_blob(&entry.object_id, &entry.path)?;
696                symlinks.push((entry.path, target));
697            }
698            TreeEntryKind::Gitlink => {
699                fs::create_dir(&output_path)
700                    .map_err(|error| materialization_error(&entry.path, error))?;
701            }
702        }
703    }
704
705    blobs.finish()?;
706    for (path, target) in symlinks {
707        create_safe_parent_directories(destination, &path)?;
708        create_materialized_symlink(&destination.join(&path), &target)
709            .map_err(|error| materialization_error(&path, error))?;
710    }
711    Ok(())
712}
713
714fn committed_tree_entries(repo_root: &Path, commit: &str) -> EngineResult<Vec<TreeEntry>> {
715    let output = git_command(repo_root)
716        .args(["ls-tree", "-r", "-z", "--full-tree", commit])
717        .output()
718        .map_err(|error| EngineError::new(format!("could not read base commit tree: {error}")))?;
719    if !output.status.success() {
720        return Err(EngineError::new(format!(
721            "could not read base commit tree: {}",
722            String::from_utf8_lossy(&output.stderr).trim()
723        )));
724    }
725
726    output
727        .stdout
728        .split(|byte| *byte == 0)
729        .filter(|record| !record.is_empty())
730        .map(parse_tree_entry)
731        .collect()
732}
733
734fn parse_tree_entry(record: &[u8]) -> EngineResult<TreeEntry> {
735    let tab = record
736        .iter()
737        .position(|byte| *byte == b'\t')
738        .ok_or_else(|| EngineError::new("could not parse base commit tree entry without a path"))?;
739    let header = std::str::from_utf8(&record[..tab])
740        .map_err(|error| EngineError::new(format!("invalid Git tree header: {error}")))?;
741    let mut fields = header.split_ascii_whitespace();
742    let mode = fields.next().unwrap_or_default();
743    let object_type = fields.next().unwrap_or_default();
744    let object_id = fields.next().unwrap_or_default();
745    if fields.next().is_some() || object_id.is_empty() {
746        return Err(EngineError::new(format!(
747            "could not parse Git tree header `{header}`"
748        )));
749    }
750    let kind = match (mode, object_type) {
751        ("100644", "blob") => TreeEntryKind::Regular,
752        ("100755", "blob") => TreeEntryKind::Executable,
753        ("120000", "blob") => TreeEntryKind::Symlink,
754        ("160000", "commit") => TreeEntryKind::Gitlink,
755        _ => {
756            return Err(EngineError::new(format!(
757                "unsupported Git tree entry mode `{mode}` and type `{object_type}`"
758            )));
759        }
760    };
761    let path = git_path_from_bytes(&record[tab + 1..])?;
762    validate_materialized_path(&path)?;
763    Ok(TreeEntry {
764        kind,
765        object_id: object_id.to_owned(),
766        path,
767    })
768}
769
770#[cfg(unix)]
771#[expect(
772    clippy::unnecessary_wraps,
773    reason = "shared cross-platform signature; non-Unix path decoding is fallible"
774)]
775fn git_path_from_bytes(bytes: &[u8]) -> EngineResult<PathBuf> {
776    use std::os::unix::ffi::OsStringExt as _;
777
778    Ok(std::ffi::OsString::from_vec(bytes.to_vec()).into())
779}
780
781#[cfg(not(unix))]
782fn git_path_from_bytes(bytes: &[u8]) -> EngineResult<PathBuf> {
783    String::from_utf8(bytes.to_vec())
784        .map(PathBuf::from)
785        .map_err(|error| EngineError::new(format!("Git tree path is not valid UTF-8: {error}")))
786}
787
788fn validate_materialized_path(path: &Path) -> EngineResult<()> {
789    if path.as_os_str().is_empty() || path.is_absolute() {
790        return Err(unsafe_tree_path(path));
791    }
792
793    let mut saw_component = false;
794    for component in path.components() {
795        let Component::Normal(segment) = component else {
796            return Err(unsafe_tree_path(path));
797        };
798        saw_component = true;
799        if segment.to_str().is_some_and(is_git_admin_alias) {
800            return Err(unsafe_tree_path(path));
801        }
802    }
803    if !saw_component {
804        return Err(unsafe_tree_path(path));
805    }
806    Ok(())
807}
808
809fn is_git_admin_alias(segment: &str) -> bool {
810    let normalized = segment.trim_end_matches([' ', '.']).to_ascii_lowercase();
811    normalized == ".git" || normalized == "git~1"
812}
813
814fn unsafe_tree_path(path: &Path) -> EngineError {
815    EngineError::new(format!(
816        "refusing to materialize unsafe Git tree path `{}`",
817        path.display()
818    ))
819}
820
821fn create_safe_parent_directories(root: &Path, relative: &Path) -> EngineResult<()> {
822    let Some(parent) = relative.parent() else {
823        return Ok(());
824    };
825    let mut current = root.to_path_buf();
826    for component in parent.components() {
827        let Component::Normal(segment) = component else {
828            return Err(unsafe_tree_path(relative));
829        };
830        current.push(segment);
831        match fs::symlink_metadata(&current) {
832            Ok(metadata) if metadata.file_type().is_dir() => {}
833            Ok(_) => {
834                return Err(EngineError::new(format!(
835                    "refusing to materialize through non-directory path `{}`",
836                    current.display()
837                )));
838            }
839            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
840                fs::create_dir(&current).map_err(|error| materialization_error(relative, error))?;
841            }
842            Err(error) => return Err(materialization_error(relative, error)),
843        }
844    }
845    Ok(())
846}
847
848fn materialization_error(path: &Path, error: impl std::fmt::Display) -> EngineError {
849    EngineError::new(format!(
850        "could not materialize base commit path `{}`: {error}",
851        path.display()
852    ))
853}
854
855#[cfg(unix)]
856fn set_regular_file_mode(path: &Path, executable: bool) -> EngineResult<()> {
857    use std::os::unix::fs::PermissionsExt as _;
858
859    let mode = if executable { 0o755 } else { 0o644 };
860    let permissions = fs::Permissions::from_mode(mode);
861    fs::set_permissions(path, permissions).map_err(|error| materialization_error(path, error))
862}
863
864#[cfg(not(unix))]
865#[expect(
866    clippy::unnecessary_wraps,
867    reason = "shared cross-platform signature; Unix permission updates are fallible"
868)]
869fn set_regular_file_mode(_path: &Path, _executable: bool) -> EngineResult<()> {
870    Ok(())
871}
872
873#[cfg(unix)]
874fn create_materialized_symlink(path: &Path, target: &[u8]) -> std::io::Result<()> {
875    use std::os::unix::ffi::OsStringExt as _;
876
877    std::os::unix::fs::symlink(std::ffi::OsString::from_vec(target.to_vec()), path)
878}
879
880#[cfg(windows)]
881fn create_materialized_symlink(path: &Path, target: &[u8]) -> std::io::Result<()> {
882    let target_path = PathBuf::from(String::from_utf8_lossy(target).into_owned());
883    let resolved_target = path
884        .parent()
885        .map_or_else(|| target_path.clone(), |parent| parent.join(&target_path));
886    let result = if resolved_target.is_dir() {
887        std::os::windows::fs::symlink_dir(&target_path, path)
888    } else {
889        std::os::windows::fs::symlink_file(&target_path, path)
890    };
891    result.or_else(|_| fs::write(path, target))
892}
893
894#[cfg(not(any(unix, windows)))]
895fn create_materialized_symlink(path: &Path, target: &[u8]) -> std::io::Result<()> {
896    fs::write(path, target)
897}
898
899struct BatchBlobReader {
900    child: Option<Child>,
901    stdin: Option<ChildStdin>,
902    stdout: BufReader<ChildStdout>,
903}
904
905impl BatchBlobReader {
906    fn spawn(repo_root: &Path) -> EngineResult<Self> {
907        let mut command = git_command(repo_root);
908        command
909            .args(["cat-file", "--batch"])
910            .stdin(Stdio::piped())
911            .stdout(Stdio::piped())
912            .stderr(Stdio::null());
913        let mut child = command.spawn().map_err(|error| {
914            EngineError::new(format!("could not start Git object reader: {error}"))
915        })?;
916        let stdin = child
917            .stdin
918            .take()
919            .ok_or_else(|| EngineError::new("Git object reader has no stdin pipe"))?;
920        let stdout = child
921            .stdout
922            .take()
923            .ok_or_else(|| EngineError::new("Git object reader has no stdout pipe"))?;
924        Ok(Self {
925            child: Some(child),
926            stdin: Some(stdin),
927            stdout: BufReader::new(stdout),
928        })
929    }
930
931    fn copy_blob(&mut self, object_id: &str, path: &Path, target: &mut File) -> EngineResult<()> {
932        let size = self.request_blob(object_id, path)?;
933        let copied = std::io::copy(&mut self.stdout.by_ref().take(size), target)
934            .map_err(|error| materialization_error(path, error))?;
935        if copied != size {
936            return Err(EngineError::new(format!(
937                "Git object reader returned {copied} of {size} bytes for `{}`",
938                path.display()
939            )));
940        }
941        self.consume_blob_terminator(path)
942    }
943
944    fn read_blob(&mut self, object_id: &str, path: &Path) -> EngineResult<Vec<u8>> {
945        let size = self.request_blob(object_id, path)?;
946        let size = usize::try_from(size).map_err(|error| materialization_error(path, error))?;
947        let mut bytes = vec![0; size];
948        self.stdout
949            .read_exact(&mut bytes)
950            .map_err(|error| materialization_error(path, error))?;
951        self.consume_blob_terminator(path)?;
952        Ok(bytes)
953    }
954
955    fn request_blob(&mut self, object_id: &str, path: &Path) -> EngineResult<u64> {
956        let stdin = self
957            .stdin
958            .as_mut()
959            .ok_or_else(|| EngineError::new("Git object reader stdin is closed"))?;
960        writeln!(stdin, "{object_id}").map_err(|error| materialization_error(path, error))?;
961        stdin
962            .flush()
963            .map_err(|error| materialization_error(path, error))?;
964
965        let mut header = Vec::new();
966        self.stdout
967            .read_until(b'\n', &mut header)
968            .map_err(|error| materialization_error(path, error))?;
969        let header = std::str::from_utf8(&header)
970            .map_err(|error| materialization_error(path, error))?
971            .trim_end();
972        let mut fields = header.split_ascii_whitespace();
973        let returned_id = fields.next().unwrap_or_default();
974        let object_type = fields.next().unwrap_or_default();
975        let size = fields.next().unwrap_or_default();
976        if returned_id != object_id || object_type != "blob" || fields.next().is_some() {
977            return Err(EngineError::new(format!(
978                "unexpected Git object response `{header}` for `{}`",
979                path.display()
980            )));
981        }
982        size.parse::<u64>()
983            .map_err(|error| materialization_error(path, error))
984    }
985
986    fn consume_blob_terminator(&mut self, path: &Path) -> EngineResult<()> {
987        let mut terminator = [0; 1];
988        self.stdout
989            .read_exact(&mut terminator)
990            .map_err(|error| materialization_error(path, error))?;
991        if terminator != *b"\n" {
992            return Err(EngineError::new(format!(
993                "Git object response for `{}` had no terminator",
994                path.display()
995            )));
996        }
997        Ok(())
998    }
999
1000    fn finish(mut self) -> EngineResult<()> {
1001        self.stdin.take();
1002        let status = self
1003            .child
1004            .take()
1005            .ok_or_else(|| EngineError::new("Git object reader is already closed"))?
1006            .wait()
1007            .map_err(|error| {
1008                EngineError::new(format!("could not wait for Git object reader: {error}"))
1009            })?;
1010        if !status.success() {
1011            return Err(EngineError::new(format!(
1012                "Git object reader exited with status {status}"
1013            )));
1014        }
1015        Ok(())
1016    }
1017}
1018
1019impl Drop for BatchBlobReader {
1020    fn drop(&mut self) {
1021        self.stdin.take();
1022        if let Some(mut child) = self.child.take() {
1023            let _ = child.kill();
1024            let _ = child.wait();
1025        }
1026    }
1027}
1028
1029fn remove_registered_worktree(repo_root: &Path, destination: &Path) {
1030    let _ = git_command(repo_root)
1031        .args(["worktree", "remove", "--force"])
1032        .arg(destination)
1033        .output();
1034}
1035
1036impl Drop for TemporaryBaseWorktree {
1037    fn drop(&mut self) {
1038        // The snapshot was deregistered in `create`, so cleanup removes only
1039        // the directory and runs no `git` subprocess.
1040        let _ = fs::remove_dir_all(&self.path);
1041    }
1042}
1043
1044/// Resolve the analysis root inside a detached base worktree.
1045///
1046/// This is the one implementation for `fallow audit`, `fallow security --base`
1047/// and the typed routes. Both sides of the prefix comparison are real paths,
1048/// because a caller can spell the root through a symbolic link (`/tmp` on
1049/// macOS resolves to `/private/tmp`) while git reports the resolved top level.
1050/// A comparison across the two path spaces fails, and the base snapshot then
1051/// covers the whole base worktree while the head snapshot stays scoped. Only
1052/// the relative remainder joins `base_worktree_root`, so no canonical spelling
1053/// reaches the result.
1054#[must_use]
1055pub fn base_analysis_root(current_root: &Path, base_worktree_root: &Path) -> PathBuf {
1056    let Some(git_root) = git_toplevel(current_root) else {
1057        return base_worktree_root.to_path_buf();
1058    };
1059    let current_root =
1060        dunce::canonicalize(current_root).unwrap_or_else(|_| current_root.to_path_buf());
1061    match current_root.strip_prefix(&git_root) {
1062        Ok(relative) => base_worktree_root.join(relative),
1063        Err(error) => {
1064            tracing::warn!(
1065                current_root = %current_root.display(),
1066                git_root = %git_root.display(),
1067                error = %error,
1068                "Could not remap the analysis root into the base worktree; falling back to the worktree root"
1069            );
1070            base_worktree_root.to_path_buf()
1071        }
1072    }
1073}
1074
1075/// Move a cache directory inside the analysis root to the same place inside
1076/// the base worktree.
1077///
1078/// A base snapshot that wrote into the head tree's cache would mix two
1079/// commits in one cache. A relative cache directory resolves against the base
1080/// worktree already, and an absolute one outside the root is shared on
1081/// purpose, so both stay unchanged. The prefix check runs on the path as
1082/// written first and then on the real paths, so a symlinked root cannot keep
1083/// the base cache in the head tree.
1084#[must_use]
1085pub fn remap_cache_dir_for_base_worktree(
1086    current_root: &Path,
1087    base_worktree_root: &Path,
1088    cache_dir: &Path,
1089) -> PathBuf {
1090    if !cache_dir.is_absolute() {
1091        return cache_dir.to_path_buf();
1092    }
1093    if let Ok(relative) = cache_dir.strip_prefix(current_root) {
1094        return base_worktree_root.join(relative);
1095    }
1096    let canonical_root =
1097        dunce::canonicalize(current_root).unwrap_or_else(|_| current_root.to_path_buf());
1098    let canonical_cache =
1099        dunce::canonicalize(cache_dir).unwrap_or_else(|_| cache_dir.to_path_buf());
1100    [cache_dir, canonical_cache.as_path()]
1101        .into_iter()
1102        .find_map(|candidate| candidate.strip_prefix(&canonical_root).ok())
1103        .map_or_else(
1104            || cache_dir.to_path_buf(),
1105            |relative| base_worktree_root.join(relative),
1106        )
1107}
1108
1109/// Auto-detect the base ref used by changed-code audit when no explicit base
1110/// or environment override is set.
1111///
1112/// The base is the `git merge-base` (fork point) against the branch's upstream
1113/// or the remote default, mirroring the `fallow hooks install --target git`
1114/// pre-commit hook (issue #242). Resolving to the merge-base SHA, rather than a
1115/// bare branch name, fixes the long-standing bug where the default branch was
1116/// discovered via `origin/HEAD` but returned as the bare name `main` (issue
1117/// #1168): git resolves a bare `main` to the LOCAL `refs/heads/main`, which is
1118/// stale on worktree checkouts cut from `origin/main`, so the audit diffed
1119/// every branch against an ancient base and false-failed the gate.
1120///
1121/// Resolution order:
1122/// 1. `@{upstream}` merge-base, so a branch forked off a non-default
1123///    integration branch compares against where it actually forked.
1124/// 2. Remote default (`origin/HEAD` -> `origin/main` -> `origin/master`)
1125///    merge-base. The remote-tracking ref refreshes on fetch, unlike a
1126///    long-stale local branch; the merge-base is also immune to an unfetched
1127///    `origin/main` in the false-fail direction.
1128/// 3. Local `main` / `master` when there is no `origin` remote, preserving the
1129///    historical behavior for air-gapped and local-only repositories.
1130///
1131/// A branch with no common ancestor with its base (a shallow clone, unrelated
1132/// history) falls back to the remote-tracking tip rather than failing the
1133/// detection outright.
1134///
1135/// The result also names the commits of the remote default branch that the
1136/// change merged after the base, see [`merged_default_branch_refs`].
1137#[must_use]
1138pub fn auto_detect_audit_base_ref(root: &Path) -> Option<ResolvedAuditBase> {
1139    let mut base = detect_audit_base_ref(root)?;
1140    base.inherited_refs = merged_default_branch_refs(root, &base.git_ref);
1141    Some(base)
1142}
1143
1144fn detect_audit_base_ref(root: &Path) -> Option<ResolvedAuditBase> {
1145    if let Some(upstream) = git_upstream_ref(root) {
1146        if let Some(sha) = git_merge_base(root, &upstream, "HEAD") {
1147            return Some(ResolvedAuditBase {
1148                git_ref: sha,
1149                description: Some(format!("merge-base with {upstream}")),
1150                inherited_refs: Vec::new(),
1151            });
1152        }
1153        return Some(ResolvedAuditBase {
1154            description: Some(format!("{upstream} (tip)")),
1155            git_ref: upstream,
1156            inherited_refs: Vec::new(),
1157        });
1158    }
1159
1160    if let Some(remote_ref) = detect_remote_default_ref(root) {
1161        if let Some(sha) = git_merge_base(root, &remote_ref, "HEAD") {
1162            return Some(ResolvedAuditBase {
1163                git_ref: sha,
1164                description: Some(format!("merge-base with {remote_ref}")),
1165                inherited_refs: Vec::new(),
1166            });
1167        }
1168        return Some(ResolvedAuditBase {
1169            description: Some(format!("{remote_ref} (tip)")),
1170            git_ref: remote_ref,
1171            inherited_refs: Vec::new(),
1172        });
1173    }
1174
1175    for candidate in ["main", "master"] {
1176        if git_ref_exists(root, candidate) {
1177            return Some(ResolvedAuditBase {
1178                git_ref: candidate.to_string(),
1179                description: Some(format!("local {candidate}")),
1180                inherited_refs: Vec::new(),
1181            });
1182        }
1183    }
1184
1185    None
1186}
1187
1188/// Commits of the remote default branch that the change merged after `base`.
1189///
1190/// A merge of the default branch into a feature branch brings in code that
1191/// the default branch already has. Against a base on the feature branch,
1192/// that code reads as new, so the commit gate blocks the merge commit and the
1193/// push that follows it. The code of these commits is inherited instead:
1194///
1195/// - `MERGE_HEAD` of an in-progress merge, when the default branch contains it;
1196/// - the merge-base of the default branch and `HEAD`, after a merge commit.
1197///
1198/// A commit that `base` already contains adds nothing, so it is left out.
1199/// Without a remote default branch, the result is empty.
1200#[must_use]
1201pub fn merged_default_branch_refs(root: &Path, base: &str) -> Vec<String> {
1202    let Some(default_ref) = detect_remote_default_ref(root) else {
1203        return Vec::new();
1204    };
1205    let merge_head = run_git(root, &["rev-parse", "--verify", "--quiet", "MERGE_HEAD"])
1206        .filter(|merge_head| git_is_ancestor(root, merge_head, &default_ref) == Some(true));
1207    let merged_default = git_merge_base(root, &default_ref, "HEAD");
1208    // A git error (a shallow history, a missing object) skips the commit, so
1209    // the audit keeps the stricter single-base comparison.
1210    let mut refs: Vec<String> = merge_head
1211        .into_iter()
1212        .chain(merged_default)
1213        .filter(|commit| git_is_ancestor(root, commit, base) == Some(false))
1214        .collect();
1215    refs.dedup();
1216    refs
1217}
1218
1219/// Whether `ancestor` is `descendant` or one of its ancestors. `None` when
1220/// git cannot tell, for example in a shallow history.
1221fn git_is_ancestor(root: &Path, ancestor: &str, descendant: &str) -> Option<bool> {
1222    let status = git_command(root)
1223        .args(["merge-base", "--is-ancestor", ancestor, descendant])
1224        .stdout(Stdio::null())
1225        .stderr(Stdio::null())
1226        .status()
1227        .ok()?;
1228    match status.code() {
1229        Some(0) => Some(true),
1230        Some(1) => Some(false),
1231        _ => None,
1232    }
1233}
1234
1235/// Short SHA for the current HEAD.
1236#[must_use]
1237pub fn short_head_sha(root: &Path) -> Option<String> {
1238    run_git(root, &["rev-parse", "--short", "HEAD"])
1239}
1240
1241/// Full SHA for the current HEAD.
1242///
1243/// `Ok(None)` means git ran and HEAD does not resolve: the directory is not a
1244/// repository, or the current branch has no commit yet. `Err` means git could not
1245/// be started, so a caller can name that cause in its own error text.
1246///
1247/// # Errors
1248///
1249/// Returns the spawn error when the `git` process cannot be started.
1250pub fn head_sha(root: &Path) -> std::io::Result<Option<String>> {
1251    let output = git_command(root).args(["rev-parse", "HEAD"]).output()?;
1252    if !output.status.success() {
1253        return Ok(None);
1254    }
1255    let value = String::from_utf8_lossy(&output.stdout);
1256    let trimmed = value.trim();
1257    Ok((!trimmed.is_empty()).then(|| trimmed.to_owned()))
1258}
1259
1260/// Resolve a concrete `--changed-workspaces` ref for project-level next steps.
1261///
1262/// `workspace_patterns` are the `workspaces.patterns` of the resolved config.
1263/// Returns `None` when the project has no workspaces, is not a git repository,
1264/// or has no resolvable remote default branch.
1265#[must_use]
1266pub fn default_workspace_ref(root: &Path, workspace_patterns: &[String]) -> Option<String> {
1267    let workspaces =
1268        crate::discover::discover_workspace_packages_with_patterns(root, workspace_patterns);
1269    default_workspace_ref_for_workspaces(root, &workspaces)
1270}
1271
1272/// Resolve a concrete `--changed-workspaces` ref using existing workspace data.
1273#[must_use]
1274pub fn default_workspace_ref_for_workspaces(
1275    root: &Path,
1276    workspaces: &[WorkspaceInfo],
1277) -> Option<String> {
1278    if workspaces.is_empty() || !crate::churn::is_git_repo(root) {
1279        return None;
1280    }
1281    detect_remote_default_ref(root)
1282}
1283
1284pub use crate::git_identity::{current_user_email, current_user_identities};
1285
1286fn git_ref_exists(root: &Path, reference: &str) -> bool {
1287    run_git(root, &["rev-parse", "--verify", "--quiet", reference]).is_some()
1288}
1289
1290/// The repository top level as a real path.
1291///
1292/// Git resolves symbolic links in the toplevel it reports on every host
1293/// checked, so the extra canonicalization is a by-construction guard rather
1294/// than a behavior change. It keeps both sides of the prefix comparison in
1295/// `base_analysis_root` in one path space.
1296fn git_toplevel(root: &Path) -> Option<PathBuf> {
1297    let toplevel = PathBuf::from(run_git(root, &["rev-parse", "--show-toplevel"])?);
1298    Some(dunce::canonicalize(&toplevel).unwrap_or(toplevel))
1299}
1300
1301fn git_upstream_ref(root: &Path) -> Option<String> {
1302    run_git(
1303        root,
1304        &[
1305            "rev-parse",
1306            "--abbrev-ref",
1307            "--symbolic-full-name",
1308            "@{upstream}",
1309        ],
1310    )
1311}
1312
1313fn git_merge_base(root: &Path, a: &str, b: &str) -> Option<String> {
1314    run_git(root, &["merge-base", a, b])
1315}
1316
1317/// The remote default branch as a remote-tracking ref, such as
1318/// `origin/main`.
1319///
1320/// Reads `origin/HEAD` first. A clone can lack it (a mirror, a CI checkout, or
1321/// `git remote set-head origin -d`), so `origin/main` and then `origin/master`
1322/// follow. Returns `None` when none of the three exists.
1323#[must_use]
1324fn detect_remote_default_ref(root: &Path) -> Option<String> {
1325    if let Some(full_ref) = run_git(root, &["symbolic-ref", "refs/remotes/origin/HEAD"])
1326        && let Some(branch) = full_ref.strip_prefix("refs/remotes/origin/")
1327    {
1328        return Some(format!("origin/{branch}"));
1329    }
1330    ["origin/main", "origin/master"]
1331        .into_iter()
1332        .find(|candidate| git_ref_exists(root, candidate))
1333        .map(str::to_string)
1334}
1335
1336fn base_worktree_path() -> EngineResult<PathBuf> {
1337    let nanos = SystemTime::now()
1338        .duration_since(SystemTime::UNIX_EPOCH)
1339        .map_err(|err| EngineError::new(format!("system clock before unix epoch: {err}")))?
1340        .as_nanos();
1341    Ok(std::env::temp_dir().join(base_worktree_name(nanos)))
1342}
1343
1344/// Compose the directory name for a base worktree taken at clock read `nanos`.
1345///
1346/// The pid stays the FIRST `-`-separated segment so the CLI orphan sweep keeps
1347/// parsing it. A process-global monotonic counter is the final segment: `nanos`
1348/// is NOT monotonic and repeats across threads, so two audits running
1349/// concurrently in one process could otherwise compose the same name and the
1350/// loser's `git worktree add` fails with "already exists". `nanos` is a
1351/// parameter so that collision is reproducible in a test without depending on
1352/// the host clock resolution.
1353fn base_worktree_name(nanos: u128) -> String {
1354    static SEQ: AtomicU64 = AtomicU64::new(0);
1355    let seq = SEQ.fetch_add(1, Ordering::Relaxed);
1356    format!("fallow-audit-base-{}-{nanos}-{seq}", std::process::id())
1357}
1358
1359/// Repository probes run in `root` through the shared engine Git wrapper.
1360fn git_command(root: &Path) -> Command {
1361    crate::git_env::git_command(root)
1362}
1363
1364/// Run `git <args>` in `root` and return trimmed, non-empty stdout, or `None`
1365/// on a non-zero exit, empty output, or non-UTF-8 output.
1366///
1367/// Trimming belongs to this contract: git terminates every line it prints, and
1368/// callers feed these values straight back to git as refs and compare them as
1369/// paths, where a trailing newline is rejected or silently mismatches. Non-UTF-8
1370/// output stays `None` rather than becoming a mangled ref or path.
1371pub(crate) fn run_git(root: &Path, args: &[&str]) -> Option<String> {
1372    let output = git_command(root).args(args).output().ok()?;
1373    if !output.status.success() {
1374        return None;
1375    }
1376    let value = String::from_utf8(output.stdout).ok()?;
1377    let trimmed = value.trim();
1378    (!trimmed.is_empty()).then(|| trimmed.to_owned())
1379}
1380
1381#[cfg(test)]
1382mod tests {
1383    use std::fs;
1384    use std::path::PathBuf;
1385
1386    use super::*;
1387
1388    fn git(root: &Path, args: &[&str]) -> String {
1389        let output = crate::git_fixture::fixture_git_command(root)
1390            .args(args)
1391            .output()
1392            .expect("git command starts");
1393        assert!(
1394            output.status.success(),
1395            "git {args:?} failed: {}",
1396            String::from_utf8_lossy(&output.stderr)
1397        );
1398        String::from_utf8_lossy(&output.stdout).trim().to_owned()
1399    }
1400
1401    fn init_repo(root: &Path) {
1402        fs::create_dir_all(root).expect("create repo");
1403        git(root, &["init", "-b", "main"]);
1404    }
1405
1406    fn commit_all(root: &Path, message: &str) {
1407        git(root, &["add", "."]);
1408        git(root, &["commit", "-m", message]);
1409    }
1410
1411    /// A repository on `main` with one seed commit and no remote.
1412    fn seeded_repo(parent: &Path) -> PathBuf {
1413        let root = parent.join("repo");
1414        init_repo(&root);
1415        fs::write(root.join("README.md"), "seed\n").expect("write seed");
1416        commit_all(&root, "initial");
1417        root
1418    }
1419
1420    /// Add a tracked file, commit it, and return the new HEAD SHA.
1421    fn commit_file(repo: &Path, name: &str, body: &str) -> String {
1422        fs::write(repo.join(name), body).expect("write file");
1423        commit_all(repo, name);
1424        git(repo, &["rev-parse", "HEAD"])
1425    }
1426
1427    #[cfg(unix)]
1428    fn write_executable(path: &Path, source: &str) {
1429        use std::os::unix::fs::PermissionsExt as _;
1430
1431        fs::write(path, source).expect("write executable");
1432        let mut permissions = fs::metadata(path)
1433            .expect("executable metadata")
1434            .permissions();
1435        permissions.set_mode(0o755);
1436        fs::set_permissions(path, permissions).expect("set executable mode");
1437    }
1438
1439    /// Concurrent callers whose clock reads land in the same tick must still
1440    /// each get a distinct name. Before the monotonic counter they composed the
1441    /// identical name, so the second `git worktree add` failed with "already
1442    /// exists" and the audit aborted with `FALLOW_AUDIT_BASE_WORKTREE_FAILED`.
1443    ///
1444    /// The tick is pinned rather than sampled: a real `SystemTime` read is fine
1445    /// enough on most hosts that the collision would surface only as a rare
1446    /// flake, which is exactly the failure this guards.
1447    #[test]
1448    fn base_worktree_names_are_unique_when_the_clock_read_repeats() {
1449        const N: usize = 64;
1450        const SAME_TICK: u128 = 1_788_187_156_297_209_000;
1451
1452        let barrier = std::sync::Barrier::new(N);
1453        let names = std::sync::Mutex::new(Vec::with_capacity(N));
1454        std::thread::scope(|scope| {
1455            for _ in 0..N {
1456                let barrier = &barrier;
1457                let names = &names;
1458                scope.spawn(move || {
1459                    barrier.wait();
1460                    names
1461                        .lock()
1462                        .expect("names lock")
1463                        .push(base_worktree_name(SAME_TICK));
1464                });
1465            }
1466        });
1467
1468        let mut names = names.into_inner().expect("names lock");
1469        assert_eq!(names.len(), N);
1470        names.sort();
1471        names.dedup();
1472        assert_eq!(names.len(), N, "base worktree names collided");
1473    }
1474
1475    /// The pid stays the first segment so the CLI orphan sweep keeps parsing it.
1476    #[test]
1477    fn base_worktree_path_keeps_the_pid_as_the_first_segment() {
1478        let path = base_worktree_path().expect("path should build");
1479        let name = path
1480            .file_name()
1481            .and_then(|name| name.to_str())
1482            .expect("worktree name should be utf-8");
1483        let pid = name
1484            .strip_prefix("fallow-audit-base-")
1485            .and_then(|rest| rest.split('-').next())
1486            .expect("pid segment should be present");
1487        assert_eq!(pid, std::process::id().to_string());
1488    }
1489
1490    /// A subdirectory analysis root only materializes its own subtree (plus
1491    /// top-level files). Without this, a sparse checkout of one subdirectory
1492    /// of a large monorepo materializes the whole monorepo, and on a blobless
1493    /// partial clone each out-of-cone blob triggers a lazy promisor fetch that
1494    /// presents as `fallow audit` hanging to the CI timeout (issue #2615).
1495    #[test]
1496    fn detached_worktree_from_a_subdir_skips_sibling_subtrees() {
1497        let temp = tempfile::tempdir().expect("temp dir");
1498        let repo = temp.path().join("repo");
1499        init_repo(&repo);
1500        fs::create_dir_all(repo.join("sub")).expect("create sub dir");
1501        fs::create_dir_all(repo.join("big")).expect("create big dir");
1502        fs::write(repo.join("sub/a.ts"), "export const a = 1;\n").expect("write sub file");
1503        fs::write(repo.join("big/b.ts"), "export const b = 1;\n").expect("write big file");
1504        fs::write(repo.join("top.ts"), "export const top = 1;\n").expect("write top file");
1505        commit_all(&repo, "initial");
1506
1507        let destination = temp.path().join("base");
1508        create_detached_base_worktree(&repo.join("sub"), &destination, "HEAD")
1509            .expect("base worktree should be created");
1510
1511        assert!(
1512            destination.join("sub/a.ts").is_file(),
1513            "the requested subtree must be materialized"
1514        );
1515        assert!(
1516            destination.join("top.ts").is_file(),
1517            "top-level files shape subdir discovery and stay materialized"
1518        );
1519        assert!(
1520            !destination.join("big/b.ts").exists(),
1521            "sibling subtrees must not be materialized: {}",
1522            destination.join("big/b.ts").display()
1523        );
1524
1525        remove_registered_worktree(&repo, &destination);
1526        let _ = fs::remove_dir_all(&destination);
1527    }
1528
1529    /// A repository-root run on a sparse checkout materializes the cone, not
1530    /// the whole monorepo. This is the `actions/checkout` sparse-checkout
1531    /// shape from issue #2615: cone mode lists the sparse directory, and the
1532    /// blobless partial clone has no out-of-cone blobs locally.
1533    #[test]
1534    fn detached_worktree_at_the_root_respects_the_sparse_cone() {
1535        let temp = tempfile::tempdir().expect("temp dir");
1536        let repo = temp.path().join("repo");
1537        init_repo(&repo);
1538        fs::create_dir_all(repo.join("sub")).expect("create sub dir");
1539        fs::create_dir_all(repo.join("big")).expect("create big dir");
1540        fs::write(repo.join("sub/a.ts"), "export const a = 1;\n").expect("write sub file");
1541        fs::write(repo.join("big/b.ts"), "export const b = 1;\n").expect("write big file");
1542        commit_all(&repo, "initial");
1543        git(&repo, &["sparse-checkout", "init", "--cone"]);
1544        git(&repo, &["sparse-checkout", "set", "sub"]);
1545
1546        let destination = temp.path().join("base");
1547        create_detached_base_worktree(&repo, &destination, "HEAD")
1548            .expect("base worktree should be created");
1549
1550        assert!(
1551            destination.join("sub/a.ts").is_file(),
1552            "the sparse cone must be materialized"
1553        );
1554        assert!(
1555            !destination.join("big/b.ts").exists(),
1556            "paths outside the sparse cone must not be materialized: {}",
1557            destination.join("big/b.ts").display()
1558        );
1559
1560        remove_registered_worktree(&repo, &destination);
1561        let _ = fs::remove_dir_all(&destination);
1562    }
1563
1564    /// Git cone mode also checks out the files directly inside each ancestor
1565    /// of a cone directory, such as `apps/package.json` for the cone
1566    /// `apps/web`. The base snapshot must hold the same files as the host
1567    /// checkout, or a workspace manifest or ignore file of the ancestor is
1568    /// present at head and missing at base.
1569    #[test]
1570    fn detached_worktree_at_the_root_keeps_files_of_cone_ancestors() {
1571        let temp = tempfile::tempdir().expect("temp dir");
1572        let repo = temp.path().join("repo");
1573        init_repo(&repo);
1574        fs::create_dir_all(repo.join("apps/web")).expect("create cone dir");
1575        fs::create_dir_all(repo.join("apps/other")).expect("create sibling dir");
1576        fs::write(repo.join("apps/web/a.ts"), "export const a = 1;\n").expect("write cone file");
1577        fs::write(repo.join("apps/package.json"), "{}\n").expect("write ancestor manifest");
1578        fs::write(repo.join("apps/.gitignore"), "dist\n").expect("write ancestor ignore");
1579        fs::write(repo.join("apps/other/b.ts"), "export const b = 1;\n").expect("write sibling");
1580        commit_all(&repo, "initial");
1581        git(&repo, &["sparse-checkout", "init", "--cone"]);
1582        git(&repo, &["sparse-checkout", "set", "apps/web"]);
1583        assert!(
1584            repo.join("apps/package.json").is_file(),
1585            "git cone mode checks out the files of a cone ancestor"
1586        );
1587
1588        let destination = temp.path().join("base");
1589        create_detached_base_worktree(&repo, &destination, "HEAD")
1590            .expect("base worktree should be created");
1591
1592        for kept in ["apps/web/a.ts", "apps/package.json", "apps/.gitignore"] {
1593            assert!(
1594                destination.join(kept).is_file(),
1595                "{kept} is in the host checkout and must be in the base snapshot"
1596            );
1597        }
1598        assert!(
1599            !destination.join("apps/other/b.ts").exists(),
1600            "a sibling directory of the cone stays out of the base snapshot"
1601        );
1602
1603        remove_registered_worktree(&repo, &destination);
1604        let _ = fs::remove_dir_all(&destination);
1605    }
1606
1607    #[test]
1608    fn default_workspace_ref_skips_projects_without_workspaces() {
1609        assert!(default_workspace_ref_for_workspaces(Path::new("/repo"), &[]).is_none());
1610    }
1611
1612    #[test]
1613    fn default_workspace_ref_skips_non_git_workspace_projects() {
1614        let workspace = WorkspaceInfo {
1615            root: PathBuf::from("/repo/packages/app"),
1616            name: "app".to_owned(),
1617            is_internal_dependency: false,
1618        };
1619
1620        assert!(default_workspace_ref_for_workspaces(Path::new("/repo"), &[workspace]).is_none());
1621    }
1622
1623    #[test]
1624    fn current_user_identities_empty_when_git_config_is_unavailable() {
1625        assert!(current_user_identities(Path::new("/repo")).is_empty());
1626    }
1627
1628    #[test]
1629    fn short_head_sha_omits_git_line_ending() {
1630        let temp = tempfile::tempdir().expect("temp dir");
1631        let repo = temp.path().join("repo");
1632        init_repo(&repo);
1633        fs::write(repo.join("tracked.txt"), "committed\n").expect("write tracked file");
1634        commit_all(&repo, "initial");
1635
1636        let sha = short_head_sha(&repo).expect("HEAD sha");
1637        assert_eq!(sha, sha.trim());
1638        assert!(!sha.is_empty());
1639    }
1640
1641    #[test]
1642    fn short_head_sha_is_absent_outside_a_git_repo() {
1643        let temp = tempfile::tempdir().expect("temp dir");
1644
1645        assert_eq!(short_head_sha(temp.path()), None);
1646    }
1647
1648    /// Regression for issue #2699: the detected ref is handed straight back to
1649    /// git as a diff target, so it must carry no line ending. Without the
1650    /// trimmed probe contract the upstream is `origin/main\n`, the merge-base
1651    /// call against it fails, and the detection degrades to the tip branch with
1652    /// an unusable ref.
1653    #[test]
1654    fn auto_detect_audit_base_ref_omits_git_line_endings_for_the_upstream_merge_base() {
1655        let temp = tempfile::tempdir().expect("temp dir");
1656        let repo = temp.path().join("repo");
1657        init_repo(&repo);
1658        fs::write(repo.join("tracked.txt"), "committed\n").expect("write tracked file");
1659        commit_all(&repo, "initial");
1660        let fork_point = git(&repo, &["rev-parse", "HEAD"]);
1661        git(&repo, &["remote", "add", "origin", &repo.to_string_lossy()]);
1662        git(&repo, &["update-ref", "refs/remotes/origin/main", "main"]);
1663        git(&repo, &["checkout", "-b", "feature"]);
1664        git(
1665            &repo,
1666            &["branch", "--set-upstream-to=origin/main", "feature"],
1667        );
1668        fs::write(repo.join("feature.txt"), "my change\n").expect("write feature file");
1669        commit_all(&repo, "feature");
1670
1671        let detected = auto_detect_audit_base_ref(&repo).expect("base is detected");
1672
1673        assert_eq!(detected.git_ref, fork_point);
1674        assert_eq!(
1675            detected.description.as_deref(),
1676            Some("merge-base with origin/main")
1677        );
1678        assert!(crate::validate::validate_git_ref(&detected.git_ref).is_ok());
1679    }
1680
1681    /// Regression for issue #2699 on the remote-default branch of the
1682    /// detection, where the line ending survives `strip_prefix` and reappears
1683    /// inside the composed `origin/<branch>` ref.
1684    #[test]
1685    fn auto_detect_audit_base_ref_omits_git_line_endings_for_the_remote_default() {
1686        let temp = tempfile::tempdir().expect("temp dir");
1687        let repo = temp.path().join("repo");
1688        init_repo(&repo);
1689        fs::write(repo.join("tracked.txt"), "committed\n").expect("write tracked file");
1690        commit_all(&repo, "initial");
1691        let fork_point = git(&repo, &["rev-parse", "HEAD"]);
1692        git(&repo, &["update-ref", "refs/remotes/origin/main", "main"]);
1693        git(
1694            &repo,
1695            &[
1696                "symbolic-ref",
1697                "refs/remotes/origin/HEAD",
1698                "refs/remotes/origin/main",
1699            ],
1700        );
1701
1702        let detected = auto_detect_audit_base_ref(&repo).expect("base is detected");
1703
1704        assert_eq!(detected.git_ref, fork_point);
1705        assert_eq!(
1706            detected.description.as_deref(),
1707            Some("merge-base with origin/main")
1708        );
1709        assert!(crate::validate::validate_git_ref(&detected.git_ref).is_ok());
1710    }
1711
1712    #[test]
1713    fn auto_detect_audit_base_ref_resolves_origin_default_to_merge_base() {
1714        let temp = tempfile::tempdir().expect("temp dir");
1715        let repo = seeded_repo(temp.path());
1716        let head = git(&repo, &["rev-parse", "HEAD"]);
1717        git(&repo, &["branch", "trunk"]);
1718        git(&repo, &["update-ref", "refs/remotes/origin/trunk", "trunk"]);
1719        git(
1720            &repo,
1721            &[
1722                "symbolic-ref",
1723                "refs/remotes/origin/HEAD",
1724                "refs/remotes/origin/trunk",
1725            ],
1726        );
1727
1728        let detected = auto_detect_audit_base_ref(&repo).expect("base is detected");
1729
1730        // trunk == HEAD, so the merge-base is HEAD's own SHA. The bare branch
1731        // name `trunk` is never returned: it would resolve to a local ref.
1732        assert_eq!(detected.git_ref, head);
1733        assert_eq!(
1734            detected.description.as_deref(),
1735            Some("merge-base with origin/trunk")
1736        );
1737    }
1738
1739    /// Regression for issue #1168: a worktree checkout whose local `main` is
1740    /// stale relative to a fresh `origin/main`. The base must be the fork point
1741    /// (merge-base with `origin/main`), NOT the stale local-`main` commit that
1742    /// the old bare-name resolution diffed against.
1743    #[test]
1744    fn auto_detect_audit_base_ref_ignores_stale_local_main() {
1745        let temp = tempfile::tempdir().expect("temp dir");
1746        let repo = seeded_repo(temp.path());
1747        let stale = git(&repo, &["rev-parse", "HEAD"]);
1748
1749        git(&repo, &["update-ref", "refs/remotes/origin/main", "main"]);
1750        git(
1751            &repo,
1752            &[
1753                "symbolic-ref",
1754                "refs/remotes/origin/HEAD",
1755                "refs/remotes/origin/main",
1756            ],
1757        );
1758        let fork_point = commit_file(&repo, "teammate.txt", "merged work\n");
1759        git(&repo, &["update-ref", "refs/remotes/origin/main", "main"]);
1760
1761        // Cut a feature branch from the fresh origin tip using the raw SHA (no
1762        // upstream tracking), then leave local `main` behind at the stale commit.
1763        git(&repo, &["checkout", "-b", "feature", &fork_point]);
1764        commit_file(&repo, "feature.txt", "my change\n");
1765        git(&repo, &["branch", "-f", "main", &stale]);
1766
1767        let detected = auto_detect_audit_base_ref(&repo).expect("base is detected");
1768
1769        assert_eq!(
1770            detected.git_ref, fork_point,
1771            "base must be the fork point (origin/main), not stale local main"
1772        );
1773        assert_eq!(
1774            detected.description.as_deref(),
1775            Some("merge-base with origin/main")
1776        );
1777    }
1778
1779    #[test]
1780    fn auto_detect_audit_base_ref_prefers_configured_upstream() {
1781        let temp = tempfile::tempdir().expect("temp dir");
1782        let repo = seeded_repo(temp.path());
1783        let fork_point = git(&repo, &["rev-parse", "HEAD"]);
1784        // Configure `origin` so refs/remotes/origin/* are recognized as
1785        // tracking refs and `--set-upstream-to` is accepted.
1786        git(&repo, &["remote", "add", "origin", &repo.to_string_lossy()]);
1787        git(&repo, &["update-ref", "refs/remotes/origin/main", "main"]);
1788        git(&repo, &["checkout", "-b", "feature"]);
1789        git(
1790            &repo,
1791            &["branch", "--set-upstream-to=origin/main", "feature"],
1792        );
1793        commit_file(&repo, "feature.txt", "my change\n");
1794
1795        let detected = auto_detect_audit_base_ref(&repo).expect("base is detected");
1796
1797        assert_eq!(detected.git_ref, fork_point);
1798        assert_eq!(
1799            detected.description.as_deref(),
1800            Some("merge-base with origin/main")
1801        );
1802    }
1803
1804    /// A repo with `origin/main` one commit ahead of the fork point of the
1805    /// branch `feature`. Returns the repo, the fork point and the tip of
1806    /// `origin/main`.
1807    fn repo_with_newer_main(root: &Path) -> (PathBuf, String, String) {
1808        let repo = seeded_repo(root);
1809        let fork_point = git(&repo, &["rev-parse", "HEAD"]);
1810        git(&repo, &["remote", "add", "origin", &repo.to_string_lossy()]);
1811        commit_file(&repo, "main.txt", "main change\n");
1812        let main_tip = git(&repo, &["rev-parse", "HEAD"]);
1813        git(&repo, &["update-ref", "refs/remotes/origin/main", "main"]);
1814        git(&repo, &["checkout", "-b", "feature", &fork_point]);
1815        commit_file(&repo, "feature.txt", "my change\n");
1816        (repo, fork_point, main_tip)
1817    }
1818
1819    #[test]
1820    fn merged_default_branch_refs_is_empty_without_a_merge() {
1821        let temp = tempfile::tempdir().expect("temp dir");
1822        let (repo, fork_point, _) = repo_with_newer_main(temp.path());
1823
1824        assert!(merged_default_branch_refs(&repo, &fork_point).is_empty());
1825    }
1826
1827    #[test]
1828    fn merged_default_branch_refs_names_the_merge_head_of_the_default_branch() {
1829        let temp = tempfile::tempdir().expect("temp dir");
1830        let (repo, fork_point, main_tip) = repo_with_newer_main(temp.path());
1831        git(&repo, &["merge", "--no-commit", "--no-ff", "origin/main"]);
1832
1833        assert_eq!(merged_default_branch_refs(&repo, &fork_point), [main_tip]);
1834    }
1835
1836    #[test]
1837    fn merged_default_branch_refs_names_the_merged_default_after_a_merge_commit() {
1838        let temp = tempfile::tempdir().expect("temp dir");
1839        let (repo, fork_point, main_tip) = repo_with_newer_main(temp.path());
1840        let pushed = git(&repo, &["rev-parse", "HEAD"]);
1841        git(&repo, &["merge", "--no-ff", "--no-edit", "origin/main"]);
1842
1843        assert_eq!(
1844            merged_default_branch_refs(&repo, &pushed),
1845            std::slice::from_ref(&main_tip)
1846        );
1847        // A base that already contains the merged commit gains nothing.
1848        assert!(merged_default_branch_refs(&repo, &main_tip).is_empty());
1849        assert_ne!(fork_point, main_tip);
1850    }
1851
1852    #[test]
1853    fn merged_default_branch_refs_names_the_new_default_after_a_rebase() {
1854        let temp = tempfile::tempdir().expect("temp dir");
1855        let (repo, fork_point, main_tip) = repo_with_newer_main(temp.path());
1856        git(&repo, &["rebase", "-q", "origin/main"]);
1857
1858        // The upstream still holds the pre-rebase branch, so the base is the
1859        // old fork point. The new default commit that the rebase moved under
1860        // the branch is inherited.
1861        assert_eq!(merged_default_branch_refs(&repo, &fork_point), [main_tip]);
1862    }
1863
1864    #[test]
1865    fn merged_default_branch_refs_ignores_a_branch_that_the_default_branch_lacks() {
1866        let temp = tempfile::tempdir().expect("temp dir");
1867        let (repo, fork_point, _) = repo_with_newer_main(temp.path());
1868        git(&repo, &["checkout", "-b", "side", &fork_point]);
1869        commit_file(&repo, "side.txt", "side change\n");
1870        git(&repo, &["checkout", "feature"]);
1871        let base = git(&repo, &["rev-parse", "HEAD"]);
1872        git(&repo, &["merge", "--no-commit", "--no-ff", "side"]);
1873
1874        assert!(merged_default_branch_refs(&repo, &base).is_empty());
1875    }
1876
1877    #[test]
1878    fn merged_default_branch_refs_skips_a_commit_that_git_cannot_place() {
1879        let temp = tempfile::tempdir().expect("temp dir");
1880        let (repo, _, _) = repo_with_newer_main(temp.path());
1881        git(&repo, &["merge", "--no-commit", "--no-ff", "origin/main"]);
1882
1883        // An unknown base makes the ancestry check fail: no ref is inherited.
1884        assert!(
1885            merged_default_branch_refs(&repo, "0000000000000000000000000000000000000000")
1886                .is_empty()
1887        );
1888    }
1889
1890    #[test]
1891    fn auto_detect_audit_base_ref_falls_back_to_local_main_without_remote() {
1892        let temp = tempfile::tempdir().expect("temp dir");
1893        let repo = seeded_repo(temp.path());
1894
1895        let detected = auto_detect_audit_base_ref(&repo).expect("base is detected");
1896
1897        assert_eq!(detected.git_ref, "main");
1898        assert_eq!(detected.description.as_deref(), Some("local main"));
1899    }
1900
1901    #[test]
1902    fn auto_detect_audit_base_ref_falls_back_to_local_master_without_remote() {
1903        let temp = tempfile::tempdir().expect("temp dir");
1904        let repo = temp.path().join("repo");
1905        fs::create_dir_all(&repo).expect("create repo");
1906        git(&repo, &["init", "-b", "master"]);
1907        fs::write(repo.join("README.md"), "seed\n").expect("write seed");
1908        commit_all(&repo, "initial");
1909
1910        let detected = auto_detect_audit_base_ref(&repo).expect("base is detected");
1911
1912        assert_eq!(detected.git_ref, "master");
1913        assert_eq!(detected.description.as_deref(), Some("local master"));
1914    }
1915
1916    #[test]
1917    fn auto_detect_audit_base_ref_returns_none_outside_git_repo() {
1918        let temp = tempfile::tempdir().expect("temp dir");
1919
1920        assert!(auto_detect_audit_base_ref(temp.path()).is_none());
1921    }
1922
1923    /// When the remote default shares no history with HEAD (the merge-base
1924    /// failure a shallow clone also hits), auto-detect falls back to the
1925    /// remote-tracking ref tip rather than failing the detection. That tip is
1926    /// the only branch that returns a ref git composed rather than printed, so
1927    /// it also pins the trimming for issue #2699.
1928    #[test]
1929    fn auto_detect_audit_base_ref_falls_back_to_remote_tip_without_common_ancestor() {
1930        let temp = tempfile::tempdir().expect("temp dir");
1931        let repo = seeded_repo(temp.path());
1932        git(&repo, &["checkout", "--orphan", "unrelated"]);
1933        let unrelated = commit_file(&repo, "unrelated.txt", "no shared history\n");
1934        git(
1935            &repo,
1936            &["update-ref", "refs/remotes/origin/main", &unrelated],
1937        );
1938        git(
1939            &repo,
1940            &[
1941                "symbolic-ref",
1942                "refs/remotes/origin/HEAD",
1943                "refs/remotes/origin/main",
1944            ],
1945        );
1946        git(&repo, &["checkout", "main"]);
1947
1948        let detected = auto_detect_audit_base_ref(&repo).expect("base is detected");
1949
1950        assert_eq!(detected.git_ref, "origin/main");
1951        assert_eq!(detected.description.as_deref(), Some("origin/main (tip)"));
1952    }
1953
1954    /// The repository top level is compared as a path prefix, so a line ending
1955    /// on it makes every subdirectory root fall back to the whole base
1956    /// worktree instead of the matching subdirectory (issue #2699).
1957    #[test]
1958    fn base_analysis_root_preserves_repo_subdirectory_roots() {
1959        let temp = tempfile::tempdir().expect("temp dir");
1960        let repo = temp.path().join("repo");
1961        init_repo(&repo);
1962        let app_root = repo.join("apps").join("mobile");
1963        fs::create_dir_all(&app_root).expect("create app root");
1964        let base_worktree = temp.path().join("base-worktree");
1965
1966        assert_eq!(
1967            base_analysis_root(&app_root, &base_worktree),
1968            base_worktree.join("apps").join("mobile")
1969        );
1970    }
1971
1972    /// A caller can spell the analysis root through a symbolic link, and git
1973    /// reports the resolved top level. The two path spaces must meet, or the
1974    /// prefix comparison fails and the base snapshot covers the whole base
1975    /// worktree while the head snapshot stays scoped (issue #2740).
1976    #[cfg(unix)]
1977    #[test]
1978    fn base_analysis_root_maps_a_symlinked_root_spelling() {
1979        let temp = tempfile::tempdir().expect("temp dir");
1980        let real_parent = temp.path().join("real");
1981        let repo = real_parent.join("repo");
1982        init_repo(&repo);
1983        let app_root = repo.join("apps").join("mobile");
1984        fs::create_dir_all(&app_root).expect("create app root");
1985        let linked_parent = temp.path().join("linked");
1986        std::os::unix::fs::symlink(&real_parent, &linked_parent).expect("link the parent");
1987        let base_worktree = temp.path().join("base-worktree");
1988
1989        let linked_app_root = linked_parent.join("repo").join("apps").join("mobile");
1990        assert_eq!(
1991            base_analysis_root(&linked_app_root, &base_worktree),
1992            base_worktree.join("apps").join("mobile")
1993        );
1994    }
1995
1996    #[test]
1997    fn remap_cache_dir_moves_a_cache_under_the_root_into_the_base_worktree() {
1998        let temp = tempfile::tempdir().expect("temp dir");
1999        let root = temp.path().join("repo");
2000        let base = temp.path().join("fallow-base");
2001        let cache_dir = root.join(".cache").join("fallow");
2002
2003        assert_eq!(
2004            remap_cache_dir_for_base_worktree(&root, &base, &cache_dir),
2005            base.join(".cache").join("fallow")
2006        );
2007    }
2008
2009    #[test]
2010    fn remap_cache_dir_keeps_an_absolute_cache_outside_the_root() {
2011        let temp = tempfile::tempdir().expect("temp dir");
2012        let root = temp.path().join("repo");
2013        let base = temp.path().join("fallow-base");
2014        let cache_dir = temp.path().join("shared").join("fallow-cache");
2015
2016        assert_eq!(
2017            remap_cache_dir_for_base_worktree(&root, &base, &cache_dir),
2018            cache_dir
2019        );
2020    }
2021
2022    #[test]
2023    fn remap_cache_dir_keeps_a_relative_cache() {
2024        let temp = tempfile::tempdir().expect("temp dir");
2025        let root = temp.path().join("repo");
2026        let base = temp.path().join("fallow-base");
2027        let cache_dir = Path::new(".fallow").join("cache");
2028
2029        assert_eq!(
2030            remap_cache_dir_for_base_worktree(&root, &base, &cache_dir),
2031            cache_dir
2032        );
2033    }
2034
2035    /// The root can be spelled through a symbolic link while the cache path
2036    /// is the real path. The two spellings must meet, or the base snapshot
2037    /// writes its cache into the head tree (issue #2758).
2038    #[cfg(unix)]
2039    #[test]
2040    fn remap_cache_dir_maps_a_symlinked_root_spelling() {
2041        let temp = tempfile::tempdir().expect("temp dir");
2042        let real_root = temp.path().join("real");
2043        fs::create_dir_all(&real_root).expect("create real root");
2044        let linked_root = temp.path().join("linked");
2045        std::os::unix::fs::symlink(&real_root, &linked_root).expect("link the root");
2046        let base = temp.path().join("fallow-base");
2047        let real_cache = dunce::canonicalize(&real_root)
2048            .expect("canonical root")
2049            .join(".fallow");
2050
2051        assert_eq!(
2052            remap_cache_dir_for_base_worktree(&linked_root, &base, &real_cache),
2053            base.join(".fallow")
2054        );
2055    }
2056
2057    #[test]
2058    fn head_sha_is_none_before_the_first_commit() {
2059        let temp = tempfile::tempdir().expect("temp dir");
2060        let repo = temp.path().join("repo");
2061        init_repo(&repo);
2062
2063        assert_eq!(head_sha(&repo).expect("git starts"), None);
2064    }
2065
2066    #[test]
2067    fn head_sha_returns_the_full_sha() {
2068        let temp = tempfile::tempdir().expect("temp dir");
2069        let repo = seeded_repo(temp.path());
2070
2071        let sha = head_sha(&repo).expect("git starts").expect("HEAD resolves");
2072        assert_eq!(sha, git(&repo, &["rev-parse", "HEAD"]));
2073    }
2074
2075    #[cfg(unix)]
2076    #[test]
2077    fn temporary_base_worktree_does_not_run_post_checkout_hook() {
2078        let temp = tempfile::tempdir().expect("temp dir");
2079        let repo = temp.path().join("repo");
2080        init_repo(&repo);
2081        fs::write(repo.join("tracked.txt"), "committed\n").expect("write tracked file");
2082        commit_all(&repo, "initial");
2083
2084        let sentinel = temp.path().join("post-checkout-ran");
2085        write_executable(
2086            &repo.join(".git/hooks/post-checkout"),
2087            &format!("#!/bin/sh\nprintf ran > '{}'\n", sentinel.display()),
2088        );
2089
2090        let worktree = TemporaryBaseWorktree::create(&repo, "HEAD", &[])
2091            .expect("temporary worktree should be created");
2092
2093        assert_eq!(
2094            fs::read_to_string(worktree.path().join("tracked.txt")).expect("read tracked file"),
2095            "committed\n"
2096        );
2097        assert!(
2098            !sentinel.exists(),
2099            "creating a base view must not execute post-checkout hooks"
2100        );
2101    }
2102
2103    #[cfg(unix)]
2104    #[test]
2105    fn temporary_base_worktree_does_not_run_post_index_change_hook() {
2106        let temp = tempfile::tempdir().expect("temp dir");
2107        let repo = temp.path().join("repo");
2108        init_repo(&repo);
2109        fs::write(repo.join("tracked.txt"), "committed\n").expect("write tracked file");
2110        commit_all(&repo, "initial");
2111
2112        let sentinel = temp.path().join("post-index-change-ran");
2113        write_executable(
2114            &repo.join(".git/hooks/post-index-change"),
2115            &format!("#!/bin/sh\nprintf ran > '{}'\n", sentinel.display()),
2116        );
2117
2118        let worktree = TemporaryBaseWorktree::create(&repo, "HEAD", &[])
2119            .expect("temporary worktree should be created");
2120
2121        assert_eq!(
2122            fs::read_to_string(worktree.path().join("tracked.txt")).expect("read tracked file"),
2123            "committed\n"
2124        );
2125        assert!(
2126            !sentinel.exists(),
2127            "creating a base view must not execute post-index-change hooks"
2128        );
2129    }
2130
2131    #[cfg(unix)]
2132    #[test]
2133    fn temporary_base_worktree_does_not_run_smudge_filter() {
2134        let temp = tempfile::tempdir().expect("temp dir");
2135        let repo = temp.path().join("repo");
2136        init_repo(&repo);
2137        fs::write(
2138            repo.join(".gitattributes"),
2139            "filtered.txt filter=sentinel\n",
2140        )
2141        .expect("write attributes");
2142        fs::write(repo.join("filtered.txt"), "committed raw bytes\n").expect("write filtered file");
2143        commit_all(&repo, "initial");
2144
2145        let sentinel = temp.path().join("smudge-ran");
2146        let filter = temp.path().join("smudge-filter.sh");
2147        write_executable(
2148            &filter,
2149            &format!(
2150                "#!/bin/sh\nprintf ran > '{}'\ncat >/dev/null\nprintf 'smudged bytes\\n'\n",
2151                sentinel.display()
2152            ),
2153        );
2154        git(
2155            &repo,
2156            &[
2157                "config",
2158                "filter.sentinel.smudge",
2159                filter.to_str().expect("filter path is UTF-8"),
2160            ],
2161        );
2162
2163        let worktree = TemporaryBaseWorktree::create(&repo, "HEAD", &[])
2164            .expect("temporary worktree should be created");
2165
2166        assert_eq!(
2167            fs::read(worktree.path().join("filtered.txt")).expect("read filtered file"),
2168            b"committed raw bytes\n"
2169        );
2170        assert!(
2171            !sentinel.exists(),
2172            "creating a base view must not execute smudge filters"
2173        );
2174    }
2175
2176    #[cfg(unix)]
2177    #[test]
2178    fn temporary_base_worktree_does_not_start_process_filter() {
2179        let temp = tempfile::tempdir().expect("temp dir");
2180        let repo = temp.path().join("repo");
2181        init_repo(&repo);
2182        fs::write(
2183            repo.join(".gitattributes"),
2184            "filtered.txt filter=sentinel\n",
2185        )
2186        .expect("write attributes");
2187        fs::write(repo.join("filtered.txt"), "committed raw bytes\n").expect("write filtered file");
2188        commit_all(&repo, "initial");
2189
2190        let sentinel = temp.path().join("process-filter-ran");
2191        let filter = temp.path().join("process-filter.sh");
2192        write_executable(
2193            &filter,
2194            &format!("#!/bin/sh\nprintf ran > '{}'\nexit 1\n", sentinel.display()),
2195        );
2196        git(
2197            &repo,
2198            &[
2199                "config",
2200                "filter.sentinel.process",
2201                filter.to_str().expect("filter path is UTF-8"),
2202            ],
2203        );
2204
2205        let worktree = TemporaryBaseWorktree::create(&repo, "HEAD", &[])
2206            .expect("temporary worktree should be created");
2207
2208        assert_eq!(
2209            fs::read(worktree.path().join("filtered.txt")).expect("read filtered file"),
2210            b"committed raw bytes\n"
2211        );
2212        assert!(
2213            !sentinel.exists(),
2214            "creating a base view must not start process filters"
2215        );
2216    }
2217
2218    #[test]
2219    fn failed_registration_does_not_remove_existing_worktree() {
2220        let temp = tempfile::tempdir().expect("temp dir");
2221        let repo = temp.path().join("repo");
2222        init_repo(&repo);
2223        fs::write(repo.join("tracked.txt"), "committed\n").expect("write tracked file");
2224        commit_all(&repo, "initial");
2225        let destination = temp.path().join("base");
2226
2227        create_detached_base_worktree(&repo, &destination, "HEAD")
2228            .expect("first worktree should be created");
2229        let second = create_detached_base_worktree(&repo, &destination, "HEAD");
2230
2231        assert!(second.is_err(), "duplicate destination must fail");
2232        assert!(
2233            destination.join("tracked.txt").is_file(),
2234            "failed registration must not remove the existing worktree"
2235        );
2236        assert_eq!(git(&destination, &["rev-parse", "HEAD"]).len(), 40);
2237
2238        remove_registered_worktree(&repo, &destination);
2239        let _ = fs::remove_dir_all(destination);
2240    }
2241
2242    #[cfg(unix)]
2243    #[test]
2244    fn temporary_base_worktree_preserves_modes_symlinks_and_gitlinks() {
2245        use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
2246
2247        let temp = tempfile::tempdir().expect("temp dir");
2248        let repo = temp.path().join("repo");
2249        init_repo(&repo);
2250        fs::write(repo.join("regular.txt"), "regular\n").expect("write regular file");
2251        let executable = repo.join("run.sh");
2252        fs::write(&executable, "#!/bin/sh\nexit 0\n").expect("write executable");
2253        let mut permissions = fs::metadata(&executable)
2254            .expect("executable metadata")
2255            .permissions();
2256        permissions.set_mode(0o755);
2257        fs::set_permissions(&executable, permissions).expect("set executable mode");
2258        std::os::unix::fs::symlink("regular.txt", repo.join("regular-link"))
2259            .expect("create symlink");
2260        commit_all(&repo, "files");
2261
2262        let gitlink_commit = git(&repo, &["rev-parse", "HEAD"]);
2263        git(
2264            &repo,
2265            &[
2266                "update-index",
2267                "--add",
2268                "--cacheinfo",
2269                &format!("160000,{gitlink_commit},vendor/submodule"),
2270            ],
2271        );
2272        git(&repo, &["commit", "-m", "gitlink"]);
2273
2274        let worktree = TemporaryBaseWorktree::create(&repo, "HEAD", &[])
2275            .expect("temporary worktree should be created");
2276        let regular_mode = fs::metadata(worktree.path().join("regular.txt"))
2277            .expect("regular metadata")
2278            .mode();
2279        let executable_mode = fs::metadata(worktree.path().join("run.sh"))
2280            .expect("executable metadata")
2281            .mode();
2282
2283        assert_eq!(regular_mode & 0o111, 0);
2284        assert_ne!(executable_mode & 0o111, 0);
2285        assert_eq!(
2286            fs::read_link(worktree.path().join("regular-link")).expect("read symlink"),
2287            PathBuf::from("regular.txt")
2288        );
2289        let gitlink = worktree.path().join("vendor/submodule");
2290        assert!(gitlink.is_dir(), "gitlink must materialize as a directory");
2291        assert!(
2292            fs::read_dir(gitlink)
2293                .expect("read gitlink directory")
2294                .next()
2295                .is_none(),
2296            "an uninitialized gitlink directory must remain empty"
2297        );
2298        // No index after deregistration: `base_worktree_registration` checks it.
2299
2300        let path = worktree.path().to_path_buf();
2301        drop(worktree);
2302        assert!(!path.exists(), "temporary worktree must clean up on drop");
2303    }
2304
2305    #[test]
2306    fn materialized_tree_paths_reject_traversal_and_git_admin_aliases() {
2307        for path in [
2308            Path::new("../escape"),
2309            Path::new("/absolute"),
2310            Path::new(".git/config"),
2311            Path::new("nested/.GIT/config"),
2312            Path::new("nested/.git. /config"),
2313            Path::new("nested/git~1/config"),
2314        ] {
2315            assert!(
2316                validate_materialized_path(path).is_err(),
2317                "unsafe path should be rejected: {}",
2318                path.display()
2319            );
2320        }
2321        assert!(validate_materialized_path(Path::new("src/.github/file.ts")).is_ok());
2322    }
2323
2324    #[cfg(unix)]
2325    #[test]
2326    fn parent_directory_creation_refuses_symlink_traversal() {
2327        let temp = tempfile::tempdir().expect("temp dir");
2328        let root = temp.path().join("root");
2329        let outside = temp.path().join("outside");
2330        fs::create_dir(&root).expect("create root");
2331        fs::create_dir(&outside).expect("create outside");
2332        std::os::unix::fs::symlink(&outside, root.join("link")).expect("create parent symlink");
2333
2334        let result = create_safe_parent_directories(&root, Path::new("link/escaped.txt"));
2335
2336        assert!(result.is_err(), "symlink parent must be rejected");
2337        assert!(!outside.join("escaped.txt").exists());
2338    }
2339
2340    #[test]
2341    fn audit_context_fingerprint_tracks_bounded_lockfiles_and_markers() {
2342        let temp = tempfile::tempdir().expect("temp dir");
2343        let root = temp.path();
2344        fs::write(root.join("pnpm-lock.yaml"), "lockfileVersion: 9\n").expect("lockfile");
2345        fs::create_dir(root.join("node_modules")).expect("node_modules");
2346        fs::write(
2347            root.join("node_modules/.modules.yaml"),
2348            "layoutVersion: 5\n",
2349        )
2350        .expect("node marker");
2351
2352        let first = audit_materialized_context_fingerprint(root, &[]);
2353        let unchanged = audit_materialized_context_fingerprint(root, &[]);
2354        assert_eq!(
2355            first, unchanged,
2356            "unchanged context must preserve a warm key"
2357        );
2358
2359        fs::write(root.join("pnpm-lock.yaml"), "lockfileVersion: 10\n").expect("mutate lockfile");
2360        let lock_changed = audit_materialized_context_fingerprint(root, &[]);
2361        assert_ne!(
2362            first, lock_changed,
2363            "lockfile content must invalidate the key"
2364        );
2365
2366        fs::write(
2367            root.join("node_modules/.modules.yaml"),
2368            "layoutVersion: 6\n",
2369        )
2370        .expect("mutate node marker");
2371        let marker_changed = audit_materialized_context_fingerprint(root, &[]);
2372        assert_ne!(
2373            lock_changed, marker_changed,
2374            "bounded dependency markers must invalidate the key"
2375        );
2376
2377        fs::create_dir(root.join(".nuxt")).expect("nuxt context");
2378        fs::write(root.join(".nuxt/imports.d.ts"), "export {}\n").expect("nuxt marker");
2379        assert_ne!(
2380            marker_changed,
2381            audit_materialized_context_fingerprint(root, &[]),
2382            "missing and materialized generated context must differ"
2383        );
2384    }
2385
2386    #[test]
2387    fn audit_context_fingerprint_tracks_nested_workspace_generated_roots() {
2388        let temp = tempfile::tempdir().expect("temp dir");
2389        let root = temp.path();
2390        fs::write(
2391            root.join("package.json"),
2392            r#"{"private":true,"workspaces":["packages/*"]}"#,
2393        )
2394        .expect("root package");
2395        let nuxt = root.join("packages/nuxt-app");
2396        let astro = root.join("packages/astro-app");
2397        fs::create_dir_all(nuxt.join(".nuxt")).expect("nested nuxt context");
2398        fs::create_dir_all(astro.join(".astro")).expect("nested astro context");
2399        fs::write(nuxt.join("package.json"), r#"{"name":"nuxt-app"}"#).expect("nuxt package");
2400        fs::write(astro.join("package.json"), r#"{"name":"astro-app"}"#).expect("astro package");
2401        fs::write(nuxt.join(".nuxt/imports.d.ts"), "export {};\n").expect("nuxt marker");
2402        fs::write(astro.join(".astro/types.d.ts"), "export {};\n").expect("astro marker");
2403
2404        let first = audit_materialized_context_fingerprint(root, &[]);
2405        assert!(
2406            first
2407                .directories
2408                .iter()
2409                .any(|directory| directory.name == "packages/nuxt-app/.nuxt")
2410        );
2411        assert!(
2412            first
2413                .directories
2414                .iter()
2415                .any(|directory| directory.name == "packages/astro-app/.astro")
2416        );
2417
2418        fs::write(
2419            nuxt.join(".nuxt/imports.d.ts"),
2420            "export type Changed = true;\n",
2421        )
2422        .expect("mutate nuxt marker");
2423        assert_ne!(
2424            first,
2425            audit_materialized_context_fingerprint(root, &[]),
2426            "nested workspace marker changes must invalidate the audit context"
2427        );
2428    }
2429
2430    #[cfg(unix)]
2431    #[test]
2432    fn materialize_base_context_symlinks_nested_workspace_generated_roots() {
2433        let host = tempfile::tempdir().expect("host");
2434        let worktree = tempfile::tempdir().expect("worktree");
2435        fs::write(
2436            host.path().join("package.json"),
2437            r#"{"private":true,"workspaces":["packages/*"]}"#,
2438        )
2439        .expect("root package");
2440
2441        for (workspace, generated, marker) in [
2442            ("nuxt-app", ".nuxt", "imports.d.ts"),
2443            ("astro-app", ".astro", "types.d.ts"),
2444        ] {
2445            let host_workspace = host.path().join("packages").join(workspace);
2446            let worktree_workspace = worktree.path().join("packages").join(workspace);
2447            fs::create_dir_all(host_workspace.join(generated)).expect("host generated context");
2448            fs::create_dir_all(&worktree_workspace).expect("worktree workspace");
2449            fs::write(
2450                host_workspace.join("package.json"),
2451                format!(r#"{{"name":"{workspace}"}}"#),
2452            )
2453            .expect("workspace package");
2454            fs::write(host_workspace.join(generated).join(marker), "export {};\n")
2455                .expect("generated marker");
2456        }
2457
2458        materialize_base_dependency_context(host.path(), worktree.path(), &[]);
2459
2460        for (workspace, generated, marker) in [
2461            ("nuxt-app", ".nuxt", "imports.d.ts"),
2462            ("astro-app", ".astro", "types.d.ts"),
2463        ] {
2464            let mirrored = worktree
2465                .path()
2466                .join("packages")
2467                .join(workspace)
2468                .join(generated);
2469            assert!(
2470                fs::symlink_metadata(&mirrored)
2471                    .expect("mirrored generated root")
2472                    .file_type()
2473                    .is_symlink(),
2474                "{workspace}/{generated} must reuse the host generated root"
2475            );
2476            assert!(mirrored.join(marker).is_file());
2477        }
2478    }
2479
2480    #[cfg(unix)]
2481    #[test]
2482    fn materialize_base_context_resolves_symlinked_source_directories() {
2483        let host = tempfile::tempdir().expect("host");
2484        let targets = tempfile::tempdir().expect("targets");
2485        let worktree = tempfile::tempdir().expect("worktree");
2486
2487        for (kind, marker) in [
2488            ("node_modules", ".modules.yaml"),
2489            (".nuxt", "imports.d.ts"),
2490            (".astro", "types.d.ts"),
2491        ] {
2492            let target = targets.path().join(kind);
2493            fs::create_dir(&target).expect("source target");
2494            fs::write(target.join(marker), "generated context\n").expect("context marker");
2495            std::os::unix::fs::symlink(&target, host.path().join(kind))
2496                .expect("source directory symlink");
2497        }
2498
2499        materialize_base_dependency_context(host.path(), worktree.path(), &[]);
2500
2501        let fingerprint = audit_materialized_context_fingerprint(host.path(), &[]);
2502        for kind in &["node_modules", ".nuxt", ".astro"] {
2503            let target = dunce::canonicalize(targets.path().join(kind)).expect("canonical target");
2504            let mirrored = worktree.path().join(kind);
2505            assert_eq!(
2506                fs::read_link(&mirrored).expect("materialized symlink"),
2507                target,
2508                "{kind} must link directly to the validated canonical target"
2509            );
2510            let directory = fingerprint
2511                .directories
2512                .iter()
2513                .find(|directory| directory.name == *kind)
2514                .expect("fingerprinted context directory");
2515            assert_eq!(directory.state, AuditContextPathState::Present);
2516            assert!(directory.markers.iter().any(|marker| {
2517                matches!(marker.state, AuditContextPathState::Present)
2518                    && marker.content_hash.is_some()
2519            }));
2520        }
2521    }
2522
2523    /// A package that only the config patterns declare gets the same linked
2524    /// context and fingerprint entry as a package that a manifest declares.
2525    #[cfg(unix)]
2526    #[test]
2527    fn materialize_base_context_covers_config_pattern_workspaces() {
2528        let host = tempfile::tempdir().expect("host");
2529        let worktree = tempfile::tempdir().expect("worktree");
2530        fs::write(
2531            host.path().join("package.json"),
2532            r#"{"private":true,"workspaces":["packages/*"]}"#,
2533        )
2534        .expect("root package");
2535        let host_workspace = host.path().join("apps/web");
2536        fs::create_dir_all(host_workspace.join(".nuxt")).expect("host generated context");
2537        fs::write(host_workspace.join("package.json"), r#"{"name":"web"}"#)
2538            .expect("workspace package");
2539        fs::create_dir_all(worktree.path().join("apps/web")).expect("base workspace");
2540        let patterns = vec!["apps/*".to_owned()];
2541        let names = |patterns: &[String]| {
2542            audit_materialized_context_fingerprint(host.path(), patterns)
2543                .directories
2544                .into_iter()
2545                .map(|directory| directory.name)
2546                .collect::<Vec<_>>()
2547        };
2548
2549        assert!(!names(&[]).contains(&"apps/web/.nuxt".to_owned()));
2550        assert!(names(&patterns).contains(&"apps/web/.nuxt".to_owned()));
2551
2552        materialize_base_dependency_context(host.path(), worktree.path(), &patterns);
2553        assert!(
2554            fs::symlink_metadata(worktree.path().join("apps/web/.nuxt"))
2555                .expect("linked generated context")
2556                .file_type()
2557                .is_symlink()
2558        );
2559    }
2560
2561    #[cfg(unix)]
2562    #[test]
2563    fn materialize_base_context_refuses_symlinked_workspace_parent() {
2564        let host = tempfile::tempdir().expect("host");
2565        let worktree = tempfile::tempdir().expect("worktree");
2566        let outside = tempfile::tempdir().expect("outside");
2567        fs::write(
2568            host.path().join("package.json"),
2569            r#"{"private":true,"workspaces":["packages/*"]}"#,
2570        )
2571        .expect("root package");
2572        let host_workspace = host.path().join("packages/app");
2573        fs::create_dir_all(host_workspace.join(".nuxt")).expect("host generated context");
2574        fs::write(host_workspace.join("package.json"), r#"{"name":"app"}"#)
2575            .expect("workspace package");
2576        fs::write(host_workspace.join(".nuxt/imports.d.ts"), "export {};\n")
2577            .expect("generated marker");
2578
2579        let outside_workspace = outside.path().join("app");
2580        fs::create_dir_all(&outside_workspace).expect("outside workspace");
2581        let outside_generated = outside_workspace.join(".nuxt");
2582        std::os::unix::fs::symlink("missing-target", &outside_generated)
2583            .expect("outside sentinel symlink");
2584        std::os::unix::fs::symlink(outside.path(), worktree.path().join("packages"))
2585            .expect("hostile workspace parent symlink");
2586
2587        materialize_base_dependency_context(host.path(), worktree.path(), &[]);
2588
2589        assert_eq!(
2590            fs::read_link(&outside_generated).expect("sentinel symlink must survive"),
2591            PathBuf::from("missing-target")
2592        );
2593        assert!(
2594            !outside.path().join(".nuxt").exists(),
2595            "materialization must not create generated context outside the worktree"
2596        );
2597    }
2598
2599    #[test]
2600    fn audit_context_fingerprint_rejects_oversized_files_without_reading_them() {
2601        let temp = tempfile::tempdir().expect("temp dir");
2602        let path = temp.path().join("pnpm-lock.yaml");
2603        let file = File::create(&path).expect("oversized file");
2604        file.set_len(AUDIT_CONTEXT_FILE_MAX_BYTES.saturating_add(1))
2605            .expect("set oversized length");
2606
2607        let fingerprint = fingerprint_context_file_at(&path, "pnpm-lock.yaml");
2608
2609        assert_eq!(
2610            fingerprint.state,
2611            AuditContextPathState::Unreadable(CONTEXT_OVERSIZED_FILE_STATE.to_string())
2612        );
2613        assert!(fingerprint.source.is_some());
2614        assert!(fingerprint.content_hash.is_none());
2615    }
2616
2617    #[cfg(unix)]
2618    #[test]
2619    fn audit_context_fingerprint_rejects_symlinked_files_without_following_them() {
2620        let temp = tempfile::tempdir().expect("temp dir");
2621        let target = temp.path().join("target-lock.yaml");
2622        let link = temp.path().join("pnpm-lock.yaml");
2623        fs::write(&target, "secret target contents\n").expect("target file");
2624        std::os::unix::fs::symlink(&target, &link).expect("lockfile symlink");
2625
2626        let fingerprint = fingerprint_context_file_at(&link, "pnpm-lock.yaml");
2627
2628        assert_eq!(
2629            fingerprint.state,
2630            AuditContextPathState::Unreadable(CONTEXT_SYMLINK_STATE.to_string())
2631        );
2632        assert!(fingerprint.content_hash.is_none());
2633    }
2634
2635    #[cfg(unix)]
2636    #[test]
2637    fn audit_context_fingerprint_does_not_follow_symlink_swapped_before_open() {
2638        let temp = tempfile::tempdir().expect("temp dir");
2639        let path = temp.path().join("pnpm-lock.yaml");
2640        let target = temp.path().join("target-lock.yaml");
2641        fs::write(&path, "original contents\n").expect("original file");
2642        fs::write(&target, "secret target contents\n").expect("target file");
2643
2644        let fingerprint = fingerprint_context_file_at_with_hooks(
2645            &path,
2646            "pnpm-lock.yaml",
2647            || {
2648                fs::remove_file(&path).expect("remove original");
2649                std::os::unix::fs::symlink(&target, &path).expect("replacement symlink");
2650            },
2651            || {},
2652        );
2653
2654        assert_eq!(
2655            fingerprint.state,
2656            AuditContextPathState::Unreadable(CONTEXT_SYMLINK_STATE.to_string())
2657        );
2658        assert!(fingerprint.content_hash.is_none());
2659    }
2660
2661    #[test]
2662    fn audit_context_fingerprint_rejects_file_changed_during_read() {
2663        let temp = tempfile::tempdir().expect("temp dir");
2664        let path = temp.path().join("pnpm-lock.yaml");
2665        fs::write(&path, "original contents\n").expect("original file");
2666
2667        let fingerprint = fingerprint_context_file_at_with_hooks(
2668            &path,
2669            "pnpm-lock.yaml",
2670            || {},
2671            || {
2672                OpenOptions::new()
2673                    .write(true)
2674                    .open(&path)
2675                    .expect("open replacement")
2676                    .set_len(1)
2677                    .expect("truncate replacement");
2678            },
2679        );
2680
2681        assert_eq!(
2682            fingerprint.state,
2683            AuditContextPathState::Unreadable(CONTEXT_CHANGED_DURING_READ_STATE.to_string())
2684        );
2685        assert!(fingerprint.content_hash.is_none());
2686    }
2687
2688    #[cfg(unix)]
2689    #[test]
2690    fn unix_context_open_does_not_block_on_fifo() {
2691        let temp = tempfile::tempdir().expect("temp dir");
2692        let fifo = temp.path().join("pnpm-lock.yaml");
2693        let status = std::process::Command::new("mkfifo")
2694            .arg(&fifo)
2695            .status()
2696            .expect("run mkfifo");
2697        assert!(status.success(), "mkfifo must create the test pipe");
2698
2699        let fallback_fifo = fifo.clone();
2700        let fallback_writer = std::thread::spawn(move || {
2701            std::thread::sleep(std::time::Duration::from_secs(1));
2702            OpenOptions::new()
2703                .read(true)
2704                .write(true)
2705                .open(fallback_fifo)
2706                .expect("open fallback FIFO writer")
2707        });
2708        let started = std::time::Instant::now();
2709        let fingerprint = fingerprint_context_file_at(&fifo, "pnpm-lock.yaml");
2710        let elapsed = started.elapsed();
2711
2712        assert!(
2713            elapsed < std::time::Duration::from_millis(500),
2714            "nonblocking FIFO open took {elapsed:?}"
2715        );
2716        assert_eq!(
2717            fingerprint.state,
2718            AuditContextPathState::Unreadable(CONTEXT_SPECIAL_FILE_STATE.to_string())
2719        );
2720        assert!(fingerprint.content_hash.is_none());
2721        drop(fallback_writer.join().expect("fallback writer"));
2722    }
2723
2724    #[cfg(unix)]
2725    #[test]
2726    fn audit_context_fingerprint_rejects_special_files_without_opening_them() {
2727        use std::os::unix::net::UnixListener;
2728
2729        let temp = tempfile::tempdir().expect("temp dir");
2730        let socket = temp.path().join("pnpm-lock.yaml");
2731        let _listener = UnixListener::bind(&socket).expect("unix socket");
2732
2733        let fingerprint = fingerprint_context_file_at(&socket, "pnpm-lock.yaml");
2734
2735        assert_eq!(
2736            fingerprint.state,
2737            AuditContextPathState::Unreadable(CONTEXT_SPECIAL_FILE_STATE.to_string())
2738        );
2739        assert!(fingerprint.content_hash.is_none());
2740    }
2741}