Skip to main content

fallow_engine/
repo_refs.rs

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