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