aft-base 0.67.1

Shared foundation for Agent Foundational Toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
//! Files that must not be opened as project source by indexers and walkers.

use std::collections::{BTreeSet, HashMap};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock, RwLock};

fn storage_roots() -> &'static RwLock<BTreeSet<PathBuf>> {
    static ROOTS: OnceLock<RwLock<BTreeSet<PathBuf>>> = OnceLock::new();
    ROOTS.get_or_init(RwLock::default)
}

/// Retain resolved storage roots even after reconfiguration: old readers and
/// databases can remain alive while a new route starts using another root.
pub fn register_storage_root(path: &Path) {
    let absolute = if path.is_absolute() {
        path.to_path_buf()
    } else if let Ok(cwd) = std::env::current_dir() {
        cwd.join(path)
    } else {
        return;
    };
    if storage_roots()
        .read()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .contains(&absolute)
    {
        // The absolute spelling is retained together with its canonical one,
        // so a repeat registration adds nothing and can skip the realpath
        // probe that produced them.
        return;
    }
    #[cfg(any(test, feature = "test-support"))]
    REGISTER_CANONICALIZATIONS.with(|count| count.set(count.get() + 1));
    let canonical =
        crate::production_storage::canonicalized_with(&absolute, &|p| p.canonicalize().ok());
    let mut roots = storage_roots().write().unwrap_or_else(|p| p.into_inner());
    roots.insert(absolute);
    roots.insert(canonical);
}

/// A walk-scoped boundary that skips nested linked worktrees of this
/// repository: directories under the project root whose `.git` is a file
/// naming this repository's common git dir `worktrees/` entry (the layout
/// `git worktree add` creates). Indexing those checkouts again duplicates
/// every file, so every content-reading walker prunes them; an explicitly
/// named target inside one still walks, because the boundary only prunes
/// entries below the walk's own root, never the root itself.
///
/// Not a worktree root: a nested independent repository (its own `.git`
/// directory, or a `.git` file naming another common dir), a submodule
/// (its gitdir lives under `.git/modules/`, not `worktrees/`), and the
/// boundary's own root.
///
/// The check is cheap by construction: a directory is only examined past one
/// `symlink_metadata` when it holds a `.git` entry that is a file, the
/// repository's common dir is resolved once per boundary, and each verdict is
/// cached per directory for the boundary's life (one walk, or one watcher
/// filter call).
pub struct NestedWorktreeBoundary {
    root: PathBuf,
    common_dir: OnceLock<Option<PathBuf>>,
    verdicts: Mutex<HashMap<PathBuf, bool>>,
}

impl NestedWorktreeBoundary {
    /// One boundary per walk, rooted at the walk's root. The root itself is
    /// never reported, so a project opened inside a worktree still walks.
    pub fn for_root(root: &Path) -> Self {
        Self {
            root: root.to_path_buf(),
            common_dir: OnceLock::new(),
            verdicts: Mutex::new(HashMap::new()),
        }
    }

    fn common_dir(&self) -> Option<&Path> {
        self.common_dir
            .get_or_init(|| project_git_common_dir(&self.root))
            .as_deref()
    }

    /// True when `dir` itself is a nested linked worktree of this repository.
    /// Only directories below the walk root are ever reported; callers check
    /// `entry.depth() > 0` (or an equivalent) so the named root of an
    /// explicitly targeted walk is always admitted.
    pub fn is_nested_worktree_root(&self, dir: &Path) -> bool {
        if dir == self.root {
            return false;
        }
        if let Some(verdict) = self
            .verdicts
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .get(dir)
        {
            return *verdict;
        }
        // Gate the `.git` file read on the entry existing as a file: ordinary
        // directories cost one metadata probe and never resolve the common dir.
        let verdict = std::fs::symlink_metadata(dir.join(".git"))
            .is_ok_and(|metadata| metadata.is_file())
            && self
                .common_dir()
                .is_some_and(|common| worktree_gitdir_points_at(dir, common));
        self.verdicts
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .insert(dir.to_path_buf(), verdict);
        verdict
    }

    /// True when `path` is at or under a nested linked worktree of this
    /// repository. The boundary root itself never counts, even when the
    /// project is opened inside a worktree.
    pub fn is_under_nested_worktree(&self, path: &Path) -> bool {
        let mut current = Some(path);
        while let Some(dir) = current {
            if dir == self.root || !dir.starts_with(&self.root) {
                return false;
            }
            if self.is_nested_worktree_root(dir) {
                return true;
            }
            current = dir.parent();
        }
        false
    }
}

/// This repository's common git dir for walks rooted at `root`: the `.git`
/// directory of a main checkout, the `commondir` target of a linked-worktree
/// checkout, or a submodule admin dir for a submodule checkout. `None` when
/// no ancestor holds `.git`, so there is no repository whose worktrees could
/// be nested below the root.
fn project_git_common_dir(root: &Path) -> Option<PathBuf> {
    let mut current = if root.is_absolute() {
        root.to_path_buf()
    } else {
        std::env::current_dir().ok()?.join(root)
    };
    loop {
        let dot_git = current.join(".git");
        match std::fs::symlink_metadata(&dot_git) {
            Ok(metadata) if metadata.is_dir() => return canonicalized(&dot_git),
            Ok(metadata) if metadata.is_file() => {
                let target = read_gitdir_target(&dot_git)?;
                let target = if target.is_absolute() {
                    target
                } else {
                    current.join(target)
                };
                // A linked-worktree checkout names its admin dir, which carries
                // a `commondir` file pointing at the shared git dir. Anything
                // else (a submodule admin dir, for example) is its own common
                // dir.
                if let Some(common) = read_commondir_target(&target) {
                    let common = if common.is_absolute() {
                        common
                    } else {
                        target.join(common)
                    };
                    return canonicalized(&common);
                }
                return canonicalized(&target);
            }
            Ok(_) => return None,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                let Some(parent) = current.parent().map(Path::to_path_buf) else {
                    return None;
                };
                current = parent;
            }
            Err(_) => return None,
        }
    }
}

/// True when `dir/.git` is a file whose `gitdir:` resolves to
/// `<common_dir>/worktrees/<name>`. Relative gitdir lines resolve against
/// `dir`, matching git; both sides are canonical, so symlinked checkouts and
/// platform spellings compare equal.
fn worktree_gitdir_points_at(dir: &Path, common_dir: &Path) -> bool {
    let target = match read_gitdir_target(&dir.join(".git")) {
        Some(target) => target,
        None => return false,
    };
    let target = if target.is_absolute() {
        target
    } else {
        dir.join(target)
    };
    worktree_common_candidate(&target).is_some_and(|candidate| candidate == *common_dir)
}

/// The canonical common dir when `gitdir_target` names a linked-worktree
/// admin dir (`<common>/worktrees/<name>`); `None` for submodule-style and
/// other gitdirs. Pure path logic, so Windows spellings (forward slashes,
/// drive paths) are covered without touching the filesystem.
fn worktree_common_candidate(gitdir_target: &Path) -> Option<PathBuf> {
    let worktrees = gitdir_target.parent()?;
    if worktrees.file_name()? != std::ffi::OsStr::new("worktrees") {
        return None;
    }
    canonicalized(worktrees.parent()?)
}

fn canonicalized(path: &Path) -> Option<PathBuf> {
    std::fs::canonicalize(path).ok()
}

/// Parse a `.git` file's `gitdir:` line into its (possibly relative) target.
/// The read is capped: a `.git` file is one short line, never bulk data.
fn read_gitdir_target(dot_git: &Path) -> Option<PathBuf> {
    parse_gitdir_bytes(&capped_read(dot_git, 4096)?)
}

/// The `commondir` file a linked worktree's gitdir carries, naming the shared
/// git dir (absolute, or relative to the gitdir).
fn read_commondir_target(gitdir: &Path) -> Option<PathBuf> {
    let bytes = capped_read(&gitdir.join("commondir"), 4096)?;
    let line = bytes.split(|byte| *byte == b'\n').next()?;
    let trimmed = trim_ascii_whitespace(line);
    if trimmed.is_empty() {
        return None;
    }
    bytes_to_path(trimmed)
}

fn parse_gitdir_bytes(bytes: &[u8]) -> Option<PathBuf> {
    let line = bytes.split(|byte| *byte == b'\n').next()?;
    let line = line.strip_suffix(b"\r").unwrap_or(line);
    let line = trim_ascii_whitespace(line);
    let rest = trim_ascii_whitespace(line.strip_prefix(b"gitdir:")?);
    if rest.is_empty() {
        return None;
    }
    bytes_to_path(rest)
}

fn trim_ascii_whitespace(mut bytes: &[u8]) -> &[u8] {
    while let Some((first, rest)) = bytes.split_first() {
        if first.is_ascii_whitespace() {
            bytes = rest;
        } else {
            break;
        }
    }
    while let Some((last, rest)) = bytes.split_last() {
        if last.is_ascii_whitespace() {
            bytes = rest;
        } else {
            break;
        }
    }
    bytes
}

#[cfg(unix)]
fn bytes_to_path(bytes: &[u8]) -> Option<PathBuf> {
    use std::os::unix::ffi::OsStringExt;
    Some(PathBuf::from(std::ffi::OsString::from_vec(bytes.to_vec())))
}

#[cfg(not(unix))]
fn bytes_to_path(bytes: &[u8]) -> Option<PathBuf> {
    std::str::from_utf8(bytes).ok().map(PathBuf::from)
}

fn capped_read(path: &Path, cap: u64) -> Option<Vec<u8>> {
    use std::io::Read;
    let file = crate::bounded_io::open_content_file(path).ok()?;
    let mut bytes = Vec::new();
    file.take(cap).read_to_end(&mut bytes).ok()?;
    Some(bytes)
}
// Test hook counting realpath probes for storage-root registration. The
// health rollup resolves process-wide storage paths once per tick, so one
// tick over many contexts sharing a root must barely move this count.
#[cfg(any(test, feature = "test-support"))]
thread_local! {
    static REGISTER_CANONICALIZATIONS: std::cell::Cell<u64> =
        const { std::cell::Cell::new(0) };
}

#[cfg(any(test, feature = "test-support"))]
pub fn register_canonicalizations_for_test() -> u64 {
    REGISTER_CANONICALIZATIONS.with(|count| count.get())
}

#[cfg(any(test, feature = "test-support"))]
pub fn reset_register_canonicalizations_for_test() {
    REGISTER_CANONICALIZATIONS.with(|count| count.set(0));
}

/// SQLite uses `-shm` files as shared-memory indexes and protects them with
/// process-wide file locks on macOS and Linux. Closing any descriptor to one of
/// these files, even a read-only indexing probe, releases SQLite's locks. A
/// second connection can then shrink the shared file and crash the first with
/// SIGBUS when it reads the old mapping. Reject databases and their sidecars
/// before binary detection, which would already open and close them. Internal
/// storage is also excluded wholesale so its generated source and cache files
/// never feed back into project indexing.
/// Walkers use the guarded readers' admission check to skip known live-file
/// aliases before scheduling source reads or reusing cached entries.
pub fn is_excluded(path: &Path) -> bool {
    admit(path, None).is_err()
}

pub fn is_excluded_with_file_type(path: &Path, file_type: Option<&std::fs::FileType>) -> bool {
    admit(path, file_type).is_err()
}

/// Watcher events can name vanished directories. A SQLite suffix only excludes
/// a known non-directory; an unknown type must still trigger reconciliation.
/// Unlike source walks, this check does not scan live SQLite identities.
pub fn is_excluded_event(path: &Path) -> bool {
    is_storage_path(path)
        || crate::os_metadata::is_os_metadata_path(path)
        || crate::live_db_files::is_registered_file_path(path)
        || has_sqlite_suffix(path) && path.metadata().is_ok_and(|metadata| !metadata.is_dir())
}

/// The part of a walk's admission of a regular file that its path decides
/// alone: AFT's own storage, watcher markers, OS metadata files, SQLite file
/// names and registered database paths. It skips the inode check a walk
/// makes for a file hard-linked to a live database, so use it only for paths
/// another scan already admitted and read, such as an index-store
/// checkout's members.
pub fn is_excluded_file_by_path(path: &Path) -> bool {
    crate::watcher_markers::is_marker_path(path)
        || is_storage_path(path)
        || crate::os_metadata::is_os_metadata_path(path)
        || has_sqlite_suffix(path)
        || crate::live_db_files::is_registered_file_path(path)
}

fn is_storage_path(path: &Path) -> bool {
    storage_roots()
        .read()
        .unwrap_or_else(|p| p.into_inner())
        .iter()
        .any(|root| path.starts_with(root))
}

/// Resolve aliases without opening file contents before checking retained stores.
pub fn storage_root_for_path(
    path: &Path,
    policy: &dyn crate::read_policy::StoragePathPolicy,
) -> Option<PathBuf> {
    let path = policy.identity(path);
    storage_roots()
        .read()
        .unwrap_or_else(|p| p.into_inner())
        .iter()
        .find(|root| policy.contains(&path, root))
        .cloned()
}

fn is_excluded_file(path: &Path) -> bool {
    crate::os_metadata::is_os_metadata_path(path)
        || has_sqlite_suffix(path) && !path.is_dir()
        || crate::live_db_files::is_registered_file_path(path)
}

fn has_sqlite_suffix(path: &Path) -> bool {
    path.file_name().is_some_and(|name| {
        let name = name.as_encoded_bytes();
        [
            b"-wal".as_slice(),
            b"-shm",
            b"-journal",
            b".db",
            b".sqlite",
            b".sqlite3",
        ]
        .iter()
        .any(|suffix| {
            name.len() >= suffix.len()
                && name[name.len() - suffix.len()..].eq_ignore_ascii_case(suffix)
        })
    })
}

fn is_excluded_file_with_metadata(
    path: &Path,
    file_type: Option<&std::fs::FileType>,
    metadata: Option<&std::fs::Metadata>,
) -> bool {
    crate::os_metadata::is_os_metadata_path(path)
        || has_sqlite_suffix(path)
            && !file_type.is_some_and(std::fs::FileType::is_dir)
            && !metadata.is_some_and(std::fs::Metadata::is_dir)
        || crate::live_db_files::is_registered_file_path(path)
}

/// Authorized task content is not project source, but must still be checked
/// before a pinned-directory permission probe opens and closes its descriptor.
pub fn is_sqlite_or_metadata(path: &Path) -> bool {
    is_excluded_file(path) || crate::live_db_files::is_live_sqlite_file(path)
}

/// Only explicit, ownership-checked registered task artifacts may bypass the
/// storage root exclusion. SQLite names and aliases remain forbidden.
pub fn reader_bounded(
    path: &Path,
    deadline: Option<std::time::Instant>,
    authorized_task_artifact: bool,
) -> std::io::Result<crate::bounded_io::Reader> {
    admit_bounded(path, authorized_task_artifact)?;
    crate::bounded_io::reader(path, deadline)
}

fn admit_bounded(path: &Path, authorized_task_artifact: bool) -> std::io::Result<()> {
    if authorized_task_artifact {
        if is_sqlite_or_metadata(path) || std::fs::symlink_metadata(path)?.file_type().is_symlink()
        {
            return Err(std::io::Error::new(
                std::io::ErrorKind::PermissionDenied,
                "SQLite files and aliases are not readable task content",
            ));
        }
    } else {
        admit(path, None)?;
    }
    #[cfg(any(test, feature = "test-support"))]
    record_open(path);
    Ok(())
}

/// Guard direct source reads as well as enumeration. Watcher deltas and queued
/// view work can hold paths admitted before storage was configured.
pub fn read(path: impl AsRef<Path>) -> std::io::Result<Vec<u8>> {
    let path = path.as_ref();
    admit(path, None)?;
    #[cfg(any(test, feature = "test-support"))]
    record_open(path);
    use std::io::Read;
    crate::io_accounting::WORK
        .content_reads
        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let mut bytes = Vec::new();
    crate::task_temp_reads::open(path)?.read_to_end(&mut bytes)?;
    crate::io_accounting::WORK
        .content_read_bytes
        .fetch_add(bytes.len() as u64, std::sync::atomic::Ordering::Relaxed);
    Ok(bytes)
}

pub fn read_to_string(path: impl AsRef<Path>) -> std::io::Result<String> {
    String::from_utf8(read(path)?)
        .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
}

pub fn open(path: impl AsRef<Path>) -> std::io::Result<std::fs::File> {
    let path = path.as_ref();
    admit(path, None)?;
    #[cfg(any(test, feature = "test-support"))]
    record_open(path);
    crate::io_accounting::WORK
        .content_reads
        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    crate::task_temp_reads::open(path)
}

fn admit(path: &Path, file_type: Option<&std::fs::FileType>) -> std::io::Result<()> {
    // Walker types are enough for name/storage exclusions and for entries that
    // cannot alias SQLite. Regular files still need inode checks: a harmless
    // source name may be a hard link to a live database or a newly created sidecar.
    if crate::watcher_markers::is_marker_path(path)
        || is_storage_path(path)
        || match file_type {
            Some(_) => is_excluded_file_with_metadata(path, file_type, None),
            None => {
                crate::os_metadata::is_os_metadata_path(path)
                    || crate::live_db_files::is_registered_file_path(path)
            }
        }
    {
        return Err(excluded_error());
    }
    if file_type.is_some_and(|kind| !kind.is_file() && !kind.is_symlink()) {
        return Ok(());
    }
    let metadata = crate::live_db_files::candidate_metadata(path).ok();
    if file_type.is_none()
        && has_sqlite_suffix(path)
        && !metadata.as_ref().is_some_and(std::fs::Metadata::is_dir)
    {
        return Err(excluded_error());
    }
    if metadata.as_ref().is_some_and(std::fs::Metadata::is_dir) {
        return Ok(());
    }
    let excluded_alias = metadata
        .as_ref()
        .is_some_and(|metadata| metadata.file_type().is_symlink())
        && path.canonicalize().is_ok_and(|target| is_excluded(&target));
    if excluded_alias
        || crate::live_db_files::is_live_sqlite_file_with_metadata(path, metadata.as_ref())
    {
        Err(excluded_error())
    } else {
        Ok(())
    }
}

fn excluded_error() -> std::io::Error {
    std::io::Error::new(
        std::io::ErrorKind::PermissionDenied,
        "internal storage and SQLite files are not project source",
    )
}

#[cfg(any(test, feature = "test-support"))]
pub use open_probe::{record_open, Probe};

#[cfg(any(test, feature = "test-support"))]
pub mod open_probe {
    use super::*;
    use std::collections::BTreeMap;
    use std::sync::{Arc, Mutex};

    type Opens = Arc<Mutex<Vec<PathBuf>>>;
    fn probes() -> &'static Mutex<BTreeMap<PathBuf, Opens>> {
        static PROBES: OnceLock<Mutex<BTreeMap<PathBuf, Opens>>> = OnceLock::new();
        PROBES.get_or_init(Mutex::default)
    }

    pub struct Probe {
        root: PathBuf,
        opens: Opens,
    }

    impl Probe {
        pub fn new(root: &Path) -> Self {
            let opens = Arc::new(Mutex::new(Vec::new()));
            probes()
                .lock()
                .unwrap()
                .insert(root.to_path_buf(), opens.clone());
            Self {
                root: root.to_path_buf(),
                opens,
            }
        }

        pub fn paths(&self) -> Vec<PathBuf> {
            self.opens.lock().unwrap().clone()
        }
    }

    impl Drop for Probe {
        fn drop(&mut self) {
            probes().lock().unwrap().remove(&self.root);
        }
    }

    pub fn record_open(path: &Path) {
        for (root, opens) in probes().lock().unwrap().iter() {
            if path.starts_with(root) {
                opens.lock().unwrap().push(path.to_path_buf());
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn storage_root_lookup_uses_supplied_identity_and_containment() {
        struct Policy {
            original: PathBuf,
            identity: PathBuf,
            storage: PathBuf,
            allow: bool,
            compared: std::cell::Cell<bool>,
        }
        impl crate::read_policy::StoragePathPolicy for Policy {
            fn identity(&self, path: &Path) -> PathBuf {
                assert_eq!(path, self.original);
                self.identity.clone()
            }

            fn contains(&self, path: &Path, prefix: &Path) -> bool {
                assert_eq!(path, self.identity);
                if prefix == self.storage {
                    self.compared.set(true);
                    self.allow
                } else {
                    false
                }
            }
        }

        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let storage = root.join("storage");
        register_storage_root(&storage);
        let mut policy = Policy {
            original: root.join("alias"),
            identity: root.join("opaque-identity"),
            storage: storage.clone(),
            allow: true,
            compared: std::cell::Cell::new(false),
        };
        assert_eq!(
            storage_root_for_path(&policy.original, &policy),
            Some(storage)
        );
        assert!(policy.compared.get());
        policy.allow = false;
        policy.compared.set(false);
        assert_eq!(storage_root_for_path(&policy.original, &policy), None);
        assert!(policy.compared.get());
    }

    #[test]
    fn gitdir_lines_parse_absolute_relative_and_malformed() {
        // Absolute, relative, and CRLF-terminated lines resolve; anything else
        // is not a worktree marker and must not prune.
        assert_eq!(
            parse_gitdir_bytes(b"gitdir: /repo/.git/worktrees/wt\n"),
            Some(PathBuf::from("/repo/.git/worktrees/wt"))
        );
        assert_eq!(
            parse_gitdir_bytes(b"  gitdir:  ../.git/worktrees/wt  \r\n"),
            Some(PathBuf::from("../.git/worktrees/wt"))
        );
        for malformed in [
            b"gitdir:".as_slice(),
            b"gitdir:   \n",
            b"not a gitdir\n",
            b"",
            b"gitdir : /repo/.git/worktrees/wt\n",
        ] {
            assert_eq!(parse_gitdir_bytes(malformed), None, "{malformed:?}");
        }
    }

    #[test]
    fn windows_gitdir_lines_name_a_worktrees_admin_dir() {
        // Worktree gitdir lines on Windows use forward slashes or drive paths.
        // Pure path logic, so this runs on every platform without git.
        for line in [
            "gitdir: C:/repo/.git/worktrees/wt\n",
            "gitdir: C:/repo/.git/worktrees/wt",
        ] {
            let target =
                parse_gitdir_bytes(line.as_bytes()).expect("Windows gitdir line must parse");
            assert_eq!(
                target.parent().and_then(|parent| parent.file_name()),
                Some(std::ffi::OsStr::new("worktrees"))
            );
            assert_eq!(
                target.parent().and_then(|parent| parent.parent()),
                Some(std::path::Path::new("C:/repo/.git"))
            );
        }
        // A submodule-style gitdir never names `worktrees/`.
        let target = parse_gitdir_bytes(b"gitdir: ../.git/modules/sub\n").unwrap();
        assert_ne!(
            target.parent().and_then(|parent| parent.file_name()),
            Some(std::ffi::OsStr::new("worktrees"))
        );
    }

    #[test]
    fn commondir_points_at_the_shared_git_dir() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let common = root.join(".git");
        let admin = common.join("worktrees").join("wt");
        std::fs::create_dir_all(&admin).unwrap();
        std::fs::write(admin.join("commondir"), "../../\n").unwrap();
        assert_eq!(read_commondir_target(&admin), Some(PathBuf::from("../../")));
        assert_eq!(read_commondir_target(&common), None);
    }

    #[test]
    fn hand_rolled_worktree_layout_resolves_without_git() {
        // The same layout `git worktree add` creates, without needing git:
        // main/.git is the common dir, main/linked/.git names its admin entry.
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let main = root.join("main");
        let linked = main.join("linked");
        let admin = main.join(".git").join("worktrees").join("linked");
        std::fs::create_dir_all(&admin).unwrap();
        std::fs::create_dir_all(&linked).unwrap();
        std::fs::write(
            linked.join(".git"),
            format!("gitdir: {}\n", admin.display()),
        )
        .unwrap();
        std::fs::write(
            admin.join("gitdir"),
            format!("{}\n", linked.join(".git").display()),
        )
        .unwrap();
        std::fs::write(admin.join("commondir"), "../..\n").unwrap();
        let boundary = NestedWorktreeBoundary::for_root(&main);
        assert!(boundary.is_nested_worktree_root(&linked));
        assert!(!boundary.is_nested_worktree_root(&main));
        assert!(!boundary.is_nested_worktree_root(&root));
        assert!(boundary.is_under_nested_worktree(&linked.join("file.rs")));
        assert!(!boundary.is_under_nested_worktree(&main.join("file.rs")));
    }
}