Skip to main content

folderbase_core/
folderbase_capture.rs

1//! Read-only planning for a future Folderbase Version capture transaction.
2//!
3//! This module inventories bounded filesystem metadata. It does not read
4//! ordinary file contents, seal a Folderbase Version, mutate Local Head, or
5//! write any protocol state.
6
7use std::{
8    collections::{BTreeMap, BTreeSet},
9    ffi::{OsStr, OsString},
10    fmt, fs,
11    io::{self, Read},
12    path::{Component, Path, PathBuf},
13};
14
15use cap_fs_ext::{DirExt, FollowSymlinks, OpenOptionsFollowExt};
16use cap_std::fs::{Dir, DirEntry, Metadata, OpenOptions, ReadDir};
17use ignore::{
18    Match,
19    gitignore::{Gitignore, GitignoreBuilder},
20};
21use serde::{Deserialize, Serialize};
22use sha2::{Digest, Sha256};
23use unicode_casefold::UnicodeCaseFold;
24use unicode_normalization::UnicodeNormalization;
25
26use crate::{
27    FolderbaseError, FolderbaseRootAttestation, RootAttestationError,
28    folderbase_restore_authority::{
29        MAX_RESTORE_AUTHORITIES, MAX_RESTORE_AUTHORITY_BYTES, RESTORE_AUTHORITIES_DIRECTORY,
30        RESTORE_AUTHORITY_FORMAT_V1, RestoreAuthorityRecord, restore_authority_record_path,
31        restore_stage_path, stable_file_identity_sha256, stable_file_link_count,
32    },
33    folderbase_state::FolderbaseState,
34    folderbase_version::{
35        FolderbaseVersionError, MAX_OBJECT_BYTES, MAX_VERSION_ENTRIES, validate_capture_path,
36        validate_capture_sha256, validate_capture_symlink_targets, validate_capture_version_id,
37    },
38    physical_identity::PhysicalIdentity,
39    root_attestation::{
40        ManifestProtocolProfile, RootInstanceAuthority, attest_folderbase_root_with_profile,
41    },
42    traversal_policy::{
43        NestedFolderbaseBoundaryKind, RECONSTRUCTABLE_DIRECTORIES,
44        classify_nested_folderbase_boundary, is_folderbase_state_component,
45    },
46};
47
48#[cfg(unix)]
49use crate::folderbase_restore_authority::stable_unix_file_identity_sha256;
50
51pub const MAX_FOLDERBASEIGNORE_BYTES: u64 = 1024 * 1024;
52pub const MAX_LOCAL_HEAD_BYTES: u64 = 4096;
53pub const MAX_CAPTURE_PLAN_RECORDS: usize = MAX_VERSION_ENTRIES;
54const LOCAL_HEAD_PATH: &str = ".folderbase/local/head.json";
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum CapturePlanLimitKind {
58    Entries,
59    ObjectBytes,
60}
61
62impl fmt::Display for CapturePlanLimitKind {
63    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
64        formatter.write_str(match self {
65            Self::Entries => "entries",
66            Self::ObjectBytes => "object_bytes",
67        })
68    }
69}
70
71/// Metadata kind observed for a future live Path Binding.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
73#[serde(rename_all = "snake_case")]
74pub enum CaptureEntryKind {
75    Directory,
76    RegularFile,
77    Symlink,
78}
79
80/// One metadata-only inventory entry.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct CapturePlanEntry {
83    path: String,
84    kind: CaptureEntryKind,
85    bytes: Option<u64>,
86    executable: Option<bool>,
87    symlink_target: Option<String>,
88    observed: CaptureMetadataFingerprint,
89    link_commitment: CaptureLinkCommitment,
90}
91
92impl CapturePlanEntry {
93    pub fn path(&self) -> &str {
94        &self.path
95    }
96
97    pub fn kind(&self) -> CaptureEntryKind {
98        self.kind
99    }
100
101    pub fn bytes(&self) -> Option<u64> {
102        self.bytes
103    }
104
105    pub fn executable(&self) -> Option<bool> {
106        self.executable
107    }
108
109    pub fn symlink_target(&self) -> Option<&str> {
110        self.symlink_target.as_deref()
111    }
112
113    pub(crate) fn observed(&self) -> &CaptureMetadataFingerprint {
114        &self.observed
115    }
116
117    pub(crate) fn link_commitment(&self) -> &CaptureLinkCommitment {
118        &self.link_commitment
119    }
120}
121
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123#[serde(deny_unknown_fields)]
124pub(crate) struct CaptureAuthorityLink {
125    receipt_path: String,
126    receipt_sha256: String,
127    private_stage_path: String,
128    published_identity_sha256: String,
129}
130
131#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
132#[serde(deny_unknown_fields)]
133pub(crate) struct CaptureLinkCommitment {
134    expected_live_link_count: u64,
135    authority_set_sha256: Option<String>,
136    authorities: Vec<CaptureAuthorityLink>,
137}
138
139impl Default for CaptureLinkCommitment {
140    fn default() -> Self {
141        Self {
142            expected_live_link_count: 1,
143            authority_set_sha256: None,
144            authorities: Vec::new(),
145        }
146    }
147}
148
149impl CaptureLinkCommitment {
150    pub(crate) fn is_legacy_default(&self) -> bool {
151        self == &Self::default()
152    }
153
154    pub(crate) fn is_well_formed(&self) -> bool {
155        let exact_link_count = self
156            .authorities
157            .len()
158            .checked_add(1)
159            .and_then(|count| u64::try_from(count).ok());
160        let expected_digest =
161            (!self.authorities.is_empty()).then(|| capture_authority_set_sha256(&self.authorities));
162        if exact_link_count != Some(self.expected_live_link_count)
163            || self.authority_set_sha256 != expected_digest
164        {
165            return false;
166        }
167        let mut previous = None;
168        for authority in &self.authorities {
169            if previous
170                .is_some_and(|path: &str| path.as_bytes() >= authority.receipt_path.as_bytes())
171                || validate_capture_sha256(&authority.receipt_sha256).is_err()
172                || validate_capture_sha256(&authority.published_identity_sha256).is_err()
173            {
174                return false;
175            }
176            let receipt_path = Path::new(&authority.receipt_path);
177            let Some(transaction_id) = receipt_path
178                .parent()
179                .and_then(Path::file_name)
180                .and_then(OsStr::to_str)
181            else {
182                return false;
183            };
184            if restore_authority_record_path(transaction_id) != receipt_path
185                || restore_stage_path(transaction_id) != Path::new(&authority.private_stage_path)
186            {
187                return false;
188            }
189            previous = Some(authority.receipt_path.as_str());
190        }
191        true
192    }
193}
194
195#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
196pub(crate) struct CaptureMetadataFingerprint {
197    pub(crate) bytes: u64,
198    pub(crate) modified_unix_nanos: Option<u128>,
199    pub(crate) readonly: bool,
200    pub(crate) executable: bool,
201    pub(crate) device: Option<u64>,
202    pub(crate) inode: Option<u64>,
203    #[serde(default)]
204    pub(crate) physical_identity: Option<String>,
205}
206
207impl CaptureMetadataFingerprint {
208    pub(crate) fn from_cap_metadata(metadata: &Metadata) -> Self {
209        let modified_unix_nanos = metadata
210            .modified()
211            .ok()
212            .and_then(|value| value.into_std().duration_since(std::time::UNIX_EPOCH).ok())
213            .map(|value| value.as_nanos());
214        #[cfg(unix)]
215        let (device, inode) = {
216            use cap_std::fs::MetadataExt;
217
218            (Some(metadata.dev()), Some(metadata.ino()))
219        };
220        #[cfg(not(unix))]
221        let (device, inode) = (None, None);
222        Self {
223            bytes: metadata.len(),
224            modified_unix_nanos,
225            readonly: metadata.permissions().readonly(),
226            executable: is_executable(metadata),
227            device,
228            inode,
229            physical_identity: physical_identity_from_cap_metadata(metadata),
230        }
231    }
232
233    pub(crate) fn from_std_metadata(metadata: &fs::Metadata) -> Self {
234        let modified_unix_nanos = metadata
235            .modified()
236            .ok()
237            .and_then(|value| value.duration_since(std::time::UNIX_EPOCH).ok())
238            .map(|value| value.as_nanos());
239        #[cfg(unix)]
240        let (device, inode, executable) = {
241            use std::os::unix::fs::{MetadataExt, PermissionsExt};
242
243            (
244                Some(metadata.dev()),
245                Some(metadata.ino()),
246                metadata.permissions().mode() & 0o111 != 0,
247            )
248        };
249        #[cfg(not(unix))]
250        let (device, inode, executable) = (None, None, false);
251        Self {
252            bytes: metadata.len(),
253            modified_unix_nanos,
254            readonly: metadata.permissions().readonly(),
255            executable,
256            device,
257            inode,
258            physical_identity: physical_identity_from_std_metadata(metadata),
259        }
260    }
261
262    pub(crate) fn from_std_file(file: &fs::File) -> io::Result<Self> {
263        let metadata = file.metadata()?;
264        let fingerprint = Self::from_std_metadata(&metadata);
265        #[cfg(windows)]
266        {
267            return Ok(fingerprint.with_physical_identity(Some(windows_file_identity(file)?)));
268        }
269        #[cfg(not(windows))]
270        Ok(fingerprint)
271    }
272
273    #[cfg(windows)]
274    fn with_physical_identity(mut self, physical_identity: Option<String>) -> Self {
275        self.physical_identity = physical_identity;
276        self
277    }
278}
279
280#[cfg(unix)]
281fn physical_identity_from_cap_metadata(metadata: &Metadata) -> Option<String> {
282    use cap_std::fs::MetadataExt;
283
284    Some(format!(
285        "unix:{:016x}:{:016x}",
286        metadata.dev(),
287        metadata.ino()
288    ))
289}
290
291#[cfg(not(unix))]
292fn physical_identity_from_cap_metadata(_metadata: &Metadata) -> Option<String> {
293    None
294}
295
296#[cfg(unix)]
297fn physical_identity_from_std_metadata(metadata: &fs::Metadata) -> Option<String> {
298    use std::os::unix::fs::MetadataExt;
299
300    Some(format!(
301        "unix:{:016x}:{:016x}",
302        metadata.dev(),
303        metadata.ino()
304    ))
305}
306
307#[cfg(not(unix))]
308fn physical_identity_from_std_metadata(_metadata: &fs::Metadata) -> Option<String> {
309    None
310}
311
312#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
313#[serde(rename_all = "snake_case")]
314pub enum CaptureExclusionKind {
315    NestedFolderbase,
316    HardLink,
317    Fifo,
318    Socket,
319    BlockDevice,
320    CharacterDevice,
321    OtherSpecial,
322}
323
324#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
325#[serde(rename_all = "kebab-case")]
326pub enum CaptureExclusionReason {
327    NestedFolderbaseBoundary,
328    UnsupportedV1,
329}
330
331/// One typed item that cannot become a v1 Path Binding.
332#[derive(Debug, Clone, PartialEq, Eq)]
333pub struct CapturePlanExclusion {
334    path: String,
335    kind: CaptureExclusionKind,
336    reason: CaptureExclusionReason,
337}
338
339impl CapturePlanExclusion {
340    pub fn path(&self) -> &str {
341        &self.path
342    }
343
344    pub fn kind(&self) -> CaptureExclusionKind {
345        self.kind
346    }
347
348    pub fn reason(&self) -> CaptureExclusionReason {
349        self.reason
350    }
351}
352
353/// One path omitted by ordered Folderbase ignore policy.
354#[derive(Debug, Clone, PartialEq, Eq)]
355pub struct CaptureIgnoredPath {
356    path: String,
357}
358
359impl CaptureIgnoredPath {
360    pub fn path(&self) -> &str {
361        &self.path
362    }
363}
364
365/// A device-local pointer observed while planning.
366#[derive(Debug, Clone, PartialEq, Eq)]
367pub struct CaptureLocalHead {
368    version_id: String,
369    version_sha256: String,
370    authority: LocalHeadAuthority,
371    encoded_sha256: String,
372    observed: CaptureMetadataFingerprint,
373}
374
375/// The closed meaning of one Local Head authority digest.
376#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
377#[serde(tag = "kind", deny_unknown_fields)]
378pub enum LocalHeadAuthority {
379    #[serde(rename = "capture_transaction_v1")]
380    CaptureTransactionV1 { sha256: String },
381    #[serde(rename = "version_derived_v1")]
382    VersionDerivedV1 { sha256: String },
383}
384
385impl LocalHeadAuthority {
386    pub fn sha256(&self) -> &str {
387        match self {
388            Self::CaptureTransactionV1 { sha256 } | Self::VersionDerivedV1 { sha256 } => sha256,
389        }
390    }
391}
392
393pub(crate) fn version_derived_local_head_sha256(
394    folderbase_id: &str,
395    root_instance_sha256: &str,
396    version_id: &str,
397    version_sha256: &str,
398) -> Result<String, FolderbaseCaptureError> {
399    #[derive(Serialize)]
400    struct VersionDerivedLocalHeadAuthority<'a> {
401        format: &'static str,
402        folderbase_id: &'a str,
403        root_instance_sha256: &'a str,
404        version_id: &'a str,
405        version_sha256: &'a str,
406    }
407
408    let authority = serde_json::to_vec(&VersionDerivedLocalHeadAuthority {
409        format: "folderbase-local-head-authority-v1",
410        folderbase_id,
411        root_instance_sha256,
412        version_id,
413        version_sha256,
414    })
415    .map_err(|source| {
416        FolderbaseCaptureError::InvalidLocalHead(format!(
417            "Local Head authority encoding failed: {source}"
418        ))
419    })?;
420    Ok(format!("{:x}", Sha256::digest(authority)))
421}
422
423#[derive(Debug, Deserialize)]
424#[serde(untagged)]
425enum LocalHeadWire {
426    V2(LocalHeadWireV2),
427    V1(LocalHeadWireV1),
428}
429
430#[derive(Debug, Deserialize)]
431#[serde(deny_unknown_fields)]
432struct LocalHeadWireV2 {
433    format: String,
434    folderbase_id: String,
435    root_instance_sha256: String,
436    version_id: String,
437    version_sha256: String,
438    authority: LocalHeadAuthority,
439}
440
441#[derive(Debug, Deserialize)]
442#[serde(deny_unknown_fields)]
443struct LocalHeadWireV1 {
444    format: String,
445    folderbase_id: String,
446    root_instance_sha256: String,
447    version_id: String,
448    version_sha256: String,
449    transaction_sha256: String,
450}
451
452impl CaptureLocalHead {
453    pub fn version_id(&self) -> &str {
454        &self.version_id
455    }
456
457    pub fn version_sha256(&self) -> &str {
458        &self.version_sha256
459    }
460
461    pub fn authority(&self) -> &LocalHeadAuthority {
462        &self.authority
463    }
464
465    pub(crate) fn encoded_sha256(&self) -> &str {
466        &self.encoded_sha256
467    }
468
469    pub(crate) fn observed(&self) -> &CaptureMetadataFingerprint {
470        &self.observed
471    }
472}
473
474/// An opaque, read-only metadata inventory bound to one physical root.
475#[derive(Debug)]
476pub struct CapturePlan {
477    root_attestation: FolderbaseRootAttestation,
478    root_manifest_bytes: u64,
479    root_manifest_observed: CaptureMetadataFingerprint,
480    folderbase_version_protocol: &'static str,
481    current_local_head: Option<CaptureLocalHead>,
482    ignore_policy_sha256: String,
483    entries: Vec<CapturePlanEntry>,
484    exclusions: Vec<CapturePlanExclusion>,
485    ignored_paths: Vec<CaptureIgnoredPath>,
486}
487
488impl CapturePlan {
489    pub fn root(&self) -> &Path {
490        &self.root_attestation.root
491    }
492
493    pub fn folderbase_id(&self) -> &str {
494        &self.root_attestation.folderbase_id
495    }
496
497    pub fn root_instance_sha256(&self) -> &str {
498        &self.root_attestation.root_instance_sha256
499    }
500
501    pub fn root_manifest_sha256(&self) -> &str {
502        &self.root_attestation.manifest_sha256
503    }
504
505    pub fn root_manifest_bytes(&self) -> u64 {
506        self.root_manifest_bytes
507    }
508
509    pub(crate) fn root_manifest_observed(&self) -> &CaptureMetadataFingerprint {
510        &self.root_manifest_observed
511    }
512
513    pub(crate) fn folderbase_version_protocol(&self) -> &'static str {
514        self.folderbase_version_protocol
515    }
516
517    pub fn current_local_head(&self) -> Option<&CaptureLocalHead> {
518        self.current_local_head.as_ref()
519    }
520
521    pub fn ignore_policy_sha256(&self) -> &str {
522        &self.ignore_policy_sha256
523    }
524
525    pub fn entries(&self) -> &[CapturePlanEntry] {
526        &self.entries
527    }
528
529    pub fn exclusions(&self) -> &[CapturePlanExclusion] {
530        &self.exclusions
531    }
532
533    pub fn ignored_paths(&self) -> &[CaptureIgnoredPath] {
534        &self.ignored_paths
535    }
536}
537
538/// Failures that prevent a trustworthy metadata-only capture plan.
539#[derive(Debug, thiserror::Error)]
540#[non_exhaustive]
541pub enum FolderbaseCaptureError {
542    #[error(transparent)]
543    RootAttestation(#[from] RootAttestationError),
544
545    #[error("required capture marker is missing or not a regular file: {0}")]
546    RequiredMarker(PathBuf),
547
548    #[error("capture inventory contains an unsafe portable path: {0}")]
549    UnsafePortablePath(PathBuf),
550
551    #[error("portable capture paths collide: {existing} and {path}")]
552    PortablePathCollision { existing: String, path: String },
553
554    #[error("capture inventory contains an unsafe symlink target at: {0}")]
555    UnsafeSymlinkTarget(PathBuf),
556
557    #[error("Folderbase ignore policy exceeds {maximum_bytes} bytes")]
558    IgnorePolicyTooLarge { maximum_bytes: u64 },
559
560    #[error("Folderbase ignore policy is not valid UTF-8")]
561    IgnorePolicyNotUtf8,
562
563    #[error("Folderbase ignore policy is invalid: {0}")]
564    InvalidIgnorePolicy(String),
565
566    #[error("Local Head exceeds {maximum_bytes} bytes")]
567    LocalHeadTooLarge { maximum_bytes: u64 },
568
569    #[error("Local Head is not a safe regular JSON file")]
570    UnsafeLocalHead,
571
572    #[error("Local Head is invalid: {0}")]
573    InvalidLocalHead(String),
574
575    #[error("capture planning state changed while it was being observed")]
576    PlanningStateChanged,
577
578    #[error("capture state changed after planning at: {0}")]
579    CaptureStateChanged(PathBuf),
580
581    #[error("capture plan belongs to a different Folderbase Version Store")]
582    PlanStoreMismatch,
583
584    #[error("Local Head changed after capture planning")]
585    LocalHeadChanged,
586
587    #[error("the prior Local Head cannot be verified: {0}")]
588    InvalidPriorLocalHead(String),
589
590    #[error("a prior live Path Binding became hidden by capture policy or an exclusion: {0}")]
591    PriorBindingHidden(PathBuf),
592
593    #[error("durable capture transaction is invalid: {0}")]
594    InvalidCaptureTransaction(String),
595
596    #[error("no Local Head exists to restore from")]
597    MissingLocalHead,
598
599    #[error("the current Local Head has no Tombstone at: {0}")]
600    TombstoneNotFound(PathBuf),
601
602    #[error("the current Tombstone kind is not supported by v1 restore at: {0}")]
603    UnsupportedTombstoneKind(PathBuf),
604
605    #[error("Tombstone restore ancestry is invalid: {0}")]
606    InvalidRestoreAncestry(String),
607
608    #[error("durable Tombstone restore transaction is invalid: {0}")]
609    InvalidRestoreTransaction(String),
610
611    #[error(
612        "Tombstone restore authority maintenance is required at the bounded limit of {maximum}"
613    )]
614    RestoreAuthorityMaintenanceRequired { maximum: usize },
615
616    #[error("Tombstone restore namespace repair is required before retrying at: {0}")]
617    RestoreNamespaceRepairRequired(PathBuf),
618
619    #[error("Tombstone restore refuses to overwrite the occupied path: {0}")]
620    RestoreTargetOccupied(PathBuf),
621
622    #[error("another Folderbase transaction is active: {0}")]
623    ConflictingTransaction(&'static str),
624
625    #[error(transparent)]
626    LocalStore(#[from] FolderbaseError),
627
628    #[error(transparent)]
629    FolderbaseVersion(#[from] FolderbaseVersionError),
630
631    #[error("capture inventory exceeded the {limit} limit of {maximum} at {path}")]
632    InventoryLimitExceeded {
633        limit: CapturePlanLimitKind,
634        maximum: u64,
635        path: PathBuf,
636    },
637
638    #[error("filesystem I/O failed while planning capture at {path}: {source}")]
639    Io {
640        path: PathBuf,
641        #[source]
642        source: io::Error,
643    },
644}
645
646impl FolderbaseCaptureError {
647    pub(crate) fn proves_query_observation_changed(&self) -> bool {
648        matches!(
649            self,
650            Self::RequiredMarker(_)
651                | Self::UnsafePortablePath(_)
652                | Self::PortablePathCollision { .. }
653                | Self::UnsafeSymlinkTarget(_)
654                | Self::IgnorePolicyTooLarge { .. }
655                | Self::IgnorePolicyNotUtf8
656                | Self::InvalidIgnorePolicy(_)
657                | Self::LocalHeadTooLarge { .. }
658                | Self::UnsafeLocalHead
659                | Self::InvalidLocalHead(_)
660                | Self::PlanningStateChanged
661                | Self::InventoryLimitExceeded { .. }
662        )
663    }
664}
665
666/// Read-only handle for planning Folderbase Version capture.
667pub struct FolderbaseVersionStore {
668    pub(crate) root_attestation: FolderbaseRootAttestation,
669    pub(crate) root_instance_authority: RootInstanceAuthority,
670    pub(crate) protocol_profile: ManifestProtocolProfile,
671    root_capability: Dir,
672    root_physical_identity: PhysicalIdentity,
673    restore_state: FolderbaseState,
674}
675
676impl fmt::Debug for FolderbaseVersionStore {
677    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
678        formatter
679            .debug_struct("FolderbaseVersionStore")
680            .field("root_attestation", &self.root_attestation)
681            .field("root_instance_authority", &self.root_instance_authority)
682            .field("protocol_profile", &self.protocol_profile)
683            .finish_non_exhaustive()
684    }
685}
686
687impl FolderbaseVersionStore {
688    /// Open one exact, existing Folderbase Root without writing any state.
689    pub fn open(root: impl AsRef<Path>) -> Result<Self, FolderbaseCaptureError> {
690        Self::open_with_local_head_validation(root, true)
691    }
692
693    pub(crate) fn open_for_query(root: impl AsRef<Path>) -> Result<Self, FolderbaseCaptureError> {
694        Self::open_with_local_head_validation(root, false)
695    }
696
697    fn open_with_local_head_validation(
698        root: impl AsRef<Path>,
699        validate_local_head: bool,
700    ) -> Result<Self, FolderbaseCaptureError> {
701        let requested_root = root.as_ref();
702        let (requested_attestation, _, requested_profile) =
703            attest_folderbase_root_with_profile(requested_root)?;
704        let canonical_root =
705            requested_root
706                .canonicalize()
707                .map_err(|source| FolderbaseCaptureError::Io {
708                    path: requested_root.to_path_buf(),
709                    source,
710                })?;
711        let (root_attestation, root_instance_authority, protocol_profile) =
712            attest_folderbase_root_with_profile(&canonical_root)?;
713        if requested_attestation.folderbase_id != root_attestation.folderbase_id
714            || requested_attestation.protocol_version != root_attestation.protocol_version
715            || requested_attestation.manifest_sha256 != root_attestation.manifest_sha256
716            || requested_attestation.root_instance_sha256 != root_attestation.root_instance_sha256
717            || requested_profile != protocol_profile
718        {
719            return Err(RootAttestationError::RootChangedDuringAttestation.into());
720        }
721        let root_capability = open_planning_root(&canonical_root)?;
722        verify_root_capability(&root_capability, &canonical_root)?;
723        let legacy_root_files = protocol_profile.requires_legacy_root_files();
724        if legacy_root_files {
725            require_regular_marker(
726                &root_capability,
727                &canonical_root,
728                Path::new(".folderbaseignore"),
729            )?;
730        }
731        if validate_local_head {
732            read_local_head(
733                &root_attestation,
734                &root_instance_authority,
735                &root_capability,
736            )?;
737        }
738        verify_root_capability(&root_capability, &canonical_root)?;
739        let root_physical_identity = directory_identity(&root_capability, &canonical_root)?;
740        let restore_state = FolderbaseState::open_existing_read_only(&canonical_root)?;
741        restore_state.verify_root_identity(&root_physical_identity)?;
742        Ok(Self {
743            root_attestation,
744            root_instance_authority,
745            protocol_profile,
746            root_capability,
747            root_physical_identity,
748            restore_state,
749        })
750    }
751
752    pub(crate) fn root_physical_identity(&self) -> &PhysicalIdentity {
753        &self.root_physical_identity
754    }
755
756    /// Plan a bounded metadata inventory without reading ordinary file bytes.
757    pub fn plan_capture(&self) -> Result<CapturePlan, FolderbaseCaptureError> {
758        self.plan_capture_with_after_protocol_observation(|| ())
759    }
760
761    fn plan_capture_with_after_protocol_observation<G>(
762        &self,
763        after_protocol_observation: impl FnOnce() -> G,
764    ) -> Result<CapturePlan, FolderbaseCaptureError> {
765        let (current, _, current_profile) =
766            attest_folderbase_root_with_profile(&self.root_attestation.root)?;
767        if current.root_instance_sha256 != self.root_attestation.root_instance_sha256 {
768            return Err(RootAttestationError::RootChangedDuringAttestation.into());
769        }
770        if current_profile != self.protocol_profile {
771            return Err(RootAttestationError::RootChangedDuringAttestation.into());
772        }
773        let root_capability =
774            self.root_capability
775                .try_clone()
776                .map_err(|source| FolderbaseCaptureError::Io {
777                    path: current.root.clone(),
778                    source,
779                })?;
780        verify_root_capability(&root_capability, &current.root)?;
781        let legacy_root_files = current_profile.requires_legacy_root_files();
782        if legacy_root_files {
783            require_regular_marker(
784                &root_capability,
785                &current.root,
786                Path::new(".folderbaseignore"),
787            )?;
788        }
789        let root_manifest_observed = protocol_file_observation(
790            &root_capability,
791            &current.root,
792            Path::new(".folderbase/manifest.json"),
793        )?;
794        let root_manifest_bytes = root_manifest_observed.bytes;
795        let ignore = read_ignore_policy(&root_capability, &current.root, &current_profile)?;
796        let current_local_head =
797            read_local_head(&current, &self.root_instance_authority, &root_capability)?;
798        let protocol_observation_guard = after_protocol_observation();
799        let restore_authority_records = read_restore_authority_records_unchecked(
800            &current,
801            &self.root_instance_authority,
802            &self.restore_state,
803            MAX_RESTORE_AUTHORITIES,
804        )?;
805        drop(protocol_observation_guard);
806        self.restore_state.verify_still_attached()?;
807        let restore_authorities = RestoreAuthorityRegistry {
808            state: &self.restore_state,
809            records: restore_authority_records,
810        };
811
812        let mut planner = CapturePlanner::new(
813            &current.root,
814            &ignore,
815            restore_authorities,
816            legacy_root_files,
817        );
818        planner.visit_directory(&root_capability, Path::new(""))?;
819        verify_root_capability(&root_capability, &current.root)?;
820
821        let mut entries = planner.entries;
822        let mut exclusions = planner.exclusions;
823        let mut ignored_paths = planner.ignored_paths;
824        entries.sort_by(|left, right| left.path.as_bytes().cmp(right.path.as_bytes()));
825        exclusions.sort_by(|left, right| left.path.as_bytes().cmp(right.path.as_bytes()));
826        ignored_paths.sort_by(|left, right| left.path.as_bytes().cmp(right.path.as_bytes()));
827        let nested_boundaries = exclusions
828            .iter()
829            .filter(|exclusion| exclusion.kind == CaptureExclusionKind::NestedFolderbase)
830            .map(|exclusion| exclusion.path.clone())
831            .collect::<Vec<_>>();
832        validate_capture_symlink_targets(
833            entries.iter().filter_map(|entry| {
834                entry
835                    .symlink_target
836                    .as_deref()
837                    .map(|target| (entry.path.as_str(), target))
838            }),
839            &nested_boundaries,
840        )
841        .map_err(|path| FolderbaseCaptureError::UnsafeSymlinkTarget(PathBuf::from(path)))?;
842        let final_ignore = read_ignore_policy(&root_capability, &current.root, &current_profile)?;
843        let final_local_head =
844            read_local_head(&current, &self.root_instance_authority, &root_capability)?;
845        let final_manifest_observed = protocol_file_observation(
846            &root_capability,
847            &current.root,
848            Path::new(".folderbase/manifest.json"),
849        )?;
850        verify_root_capability(&root_capability, &current.root)?;
851        let (final_attestation, _, final_profile) =
852            attest_folderbase_root_with_profile(&current.root)?;
853        if final_local_head != current_local_head
854            || final_ignore.sha256 != ignore.sha256
855            || final_attestation != current
856            || final_profile != current_profile
857            || final_manifest_observed != root_manifest_observed
858        {
859            return Err(FolderbaseCaptureError::PlanningStateChanged);
860        }
861
862        Ok(CapturePlan {
863            root_attestation: current,
864            root_manifest_bytes,
865            root_manifest_observed,
866            folderbase_version_protocol: current_profile.folderbase_version_protocol(),
867            current_local_head,
868            ignore_policy_sha256: ignore.sha256,
869            entries,
870            exclusions,
871            ignored_paths,
872        })
873    }
874}
875
876struct CapturePlanner<'a> {
877    root: &'a Path,
878    ignore: &'a IgnorePolicy,
879    restore_authorities: RestoreAuthorityRegistry<'a>,
880    legacy_root_files: bool,
881    entries: Vec<CapturePlanEntry>,
882    exclusions: Vec<CapturePlanExclusion>,
883    ignored_paths: Vec<CaptureIgnoredPath>,
884    path_index: CapturePathIndex,
885}
886
887struct ObservedRestoreAuthority {
888    record: RestoreAuthorityRecord,
889    encoded: Vec<u8>,
890}
891
892struct RestoreAuthorityRegistry<'a> {
893    state: &'a FolderbaseState,
894    records: Vec<ObservedRestoreAuthority>,
895}
896
897impl RestoreAuthorityRegistry<'_> {
898    fn validated_link_commitment(
899        &self,
900        workspace_identity: &str,
901        link_count: usize,
902        workspace_path: &str,
903        display_path: &Path,
904    ) -> Result<CaptureLinkCommitment, FolderbaseCaptureError> {
905        validated_link_commitment(
906            self.state,
907            &self.records,
908            workspace_identity,
909            link_count,
910            workspace_path,
911            display_path,
912        )
913    }
914}
915
916fn validated_link_commitment(
917    state: &FolderbaseState,
918    records: &[ObservedRestoreAuthority],
919    workspace_identity: &str,
920    link_count: usize,
921    workspace_path: &str,
922    display_path: &Path,
923) -> Result<CaptureLinkCommitment, FolderbaseCaptureError> {
924    let mut validated_paths = BTreeSet::new();
925    for observed in records.iter().filter(|observed| {
926        observed.record.workspace_path == workspace_path
927            && observed.record.published_identity_sha256 == workspace_identity
928    }) {
929        let record_path = restore_authority_record_path(&observed.record.transaction_id);
930        if state
931            .read_bounded(&record_path, MAX_RESTORE_AUTHORITY_BYTES)?
932            .as_deref()
933            != Some(observed.encoded.as_slice())
934        {
935            return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
936                "restore authority changed during capture planning".to_owned(),
937            ));
938        }
939        let observed_identity = state.planned_workspace_restore_identity_sha256(
940            Path::new(&observed.record.private_stage_path),
941            Path::new(workspace_path),
942        )?;
943        if observed_identity != workspace_identity {
944            return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
945                "restore authority no longer names the current workspace file".to_owned(),
946            ));
947        }
948        if !validated_paths.insert(observed.record.private_stage_path.as_str()) {
949            return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
950                "restore authorities name one private link more than once".to_owned(),
951            ));
952        }
953    }
954    state.verify_still_attached()?;
955    let mut authorities = records
956        .iter()
957        .filter(|observed| {
958            observed.record.workspace_path == workspace_path
959                && observed.record.published_identity_sha256 == workspace_identity
960        })
961        .map(|observed| {
962            let receipt_path = restore_authority_record_path(&observed.record.transaction_id);
963            CaptureAuthorityLink {
964                receipt_path: receipt_path
965                    .to_str()
966                    .expect("restore authority paths are UTF-8")
967                    .to_owned(),
968                receipt_sha256: format!("{:x}", Sha256::digest(&observed.encoded)),
969                private_stage_path: observed.record.private_stage_path.clone(),
970                published_identity_sha256: observed.record.published_identity_sha256.clone(),
971            }
972        })
973        .collect::<Vec<_>>();
974    authorities.sort_by(|left, right| left.receipt_path.cmp(&right.receipt_path));
975    let authority_set_sha256 =
976        (!authorities.is_empty()).then(|| capture_authority_set_sha256(&authorities));
977    Ok(CaptureLinkCommitment {
978        expected_live_link_count: u64::try_from(link_count)
979            .map_err(|_| FolderbaseCaptureError::CaptureStateChanged(display_path.to_path_buf()))?,
980        authority_set_sha256,
981        authorities,
982    })
983}
984
985fn capture_authority_set_sha256(authorities: &[CaptureAuthorityLink]) -> String {
986    #[derive(Serialize)]
987    struct AuthoritySet<'a> {
988        format: &'static str,
989        authorities: &'a [CaptureAuthorityLink],
990    }
991
992    let encoded = serde_json::to_vec(&AuthoritySet {
993        format: "folderbase-capture-authority-set-v1",
994        authorities,
995    })
996    .expect("capture authority commitments are serializable");
997    format!("{:x}", Sha256::digest(encoded))
998}
999
1000pub(crate) fn restore_authority_count(
1001    root_attestation: &FolderbaseRootAttestation,
1002    root_instance_authority: &RootInstanceAuthority,
1003    maximum: usize,
1004) -> Result<usize, FolderbaseCaptureError> {
1005    let state = FolderbaseState::open_existing_read_only(&root_attestation.root)?;
1006    let records =
1007        read_restore_authority_records(root_attestation, root_instance_authority, &state, maximum)?;
1008    Ok(records.len())
1009}
1010
1011fn read_restore_authority_records(
1012    root_attestation: &FolderbaseRootAttestation,
1013    root_instance_authority: &RootInstanceAuthority,
1014    state: &FolderbaseState,
1015    maximum: usize,
1016) -> Result<Vec<ObservedRestoreAuthority>, FolderbaseCaptureError> {
1017    let records = read_restore_authority_records_unchecked(
1018        root_attestation,
1019        root_instance_authority,
1020        state,
1021        maximum,
1022    )?;
1023    state.verify_still_attached()?;
1024    Ok(records)
1025}
1026
1027fn read_restore_authority_records_unchecked(
1028    root_attestation: &FolderbaseRootAttestation,
1029    root_instance_authority: &RootInstanceAuthority,
1030    state: &FolderbaseState,
1031    maximum: usize,
1032) -> Result<Vec<ObservedRestoreAuthority>, FolderbaseCaptureError> {
1033    let names = match state.private_directory_names(
1034        Path::new(RESTORE_AUTHORITIES_DIRECTORY),
1035        MAX_RESTORE_AUTHORITIES.saturating_add(1024),
1036    ) {
1037        Ok(names) => names,
1038        Err(FolderbaseError::Io { source, .. }) if source.kind() == io::ErrorKind::NotFound => {
1039            Vec::new()
1040        }
1041        Err(error) => return Err(error.into()),
1042    };
1043    let mut records = Vec::new();
1044    for name in names {
1045        let Some(transaction_id) = name.to_str() else {
1046            continue;
1047        };
1048        let Some(uuid) = transaction_id.strip_prefix("fbrestore_") else {
1049            continue;
1050        };
1051        if uuid::Uuid::parse_str(uuid).is_err() {
1052            continue;
1053        }
1054        let relative = restore_authority_record_path(transaction_id);
1055        let Some(encoded) = state.read_bounded(&relative, MAX_RESTORE_AUTHORITY_BYTES)? else {
1056            continue;
1057        };
1058        let record: RestoreAuthorityRecord =
1059            serde_json::from_slice(&encoded).map_err(|source| {
1060                FolderbaseCaptureError::InvalidRestoreTransaction(format!(
1061                    "restore authority is invalid JSON: {source}"
1062                ))
1063            })?;
1064        validate_restore_authority(
1065            root_attestation,
1066            root_instance_authority,
1067            transaction_id,
1068            &record,
1069        )?;
1070        records.push(ObservedRestoreAuthority { record, encoded });
1071        if records.len() > maximum {
1072            return Err(FolderbaseCaptureError::RestoreAuthorityMaintenanceRequired { maximum });
1073        }
1074    }
1075    Ok(records)
1076}
1077
1078pub(crate) fn verify_capture_link_commitment(
1079    root_attestation: &FolderbaseRootAttestation,
1080    root_instance_authority: &RootInstanceAuthority,
1081    state: &FolderbaseState,
1082    entry: &CapturePlanEntry,
1083    workspace_file: &fs::File,
1084) -> Result<(), FolderbaseCaptureError> {
1085    if entry.kind() != CaptureEntryKind::RegularFile {
1086        return Ok(());
1087    }
1088    let display_path = root_attestation.root.join(entry.path());
1089    let link_count = usize::try_from(stable_file_link_count(workspace_file).map_err(|source| {
1090        FolderbaseCaptureError::Io {
1091            path: display_path.clone(),
1092            source,
1093        }
1094    })?)
1095    .map_err(|_| FolderbaseCaptureError::CaptureStateChanged(PathBuf::from(entry.path())))?;
1096    let records = read_restore_authority_records(
1097        root_attestation,
1098        root_instance_authority,
1099        state,
1100        MAX_RESTORE_AUTHORITIES,
1101    )?;
1102    let workspace_identity = stable_file_identity_sha256(workspace_file).map_err(|source| {
1103        FolderbaseCaptureError::Io {
1104            path: display_path.clone(),
1105            source,
1106        }
1107    })?;
1108    let actual = validated_link_commitment(
1109        state,
1110        &records,
1111        &workspace_identity,
1112        link_count,
1113        entry.path(),
1114        &display_path,
1115    )?;
1116    let exact_expected_link_count = entry
1117        .link_commitment()
1118        .authorities
1119        .len()
1120        .checked_add(1)
1121        .and_then(|count| u64::try_from(count).ok());
1122    let exact_actual_link_count = actual
1123        .authorities
1124        .len()
1125        .checked_add(1)
1126        .and_then(|count| u64::try_from(count).ok());
1127    let expected_digest = (!entry.link_commitment().authorities.is_empty())
1128        .then(|| capture_authority_set_sha256(&entry.link_commitment().authorities));
1129    if exact_expected_link_count != Some(entry.link_commitment().expected_live_link_count)
1130        || entry.link_commitment().authority_set_sha256 != expected_digest
1131        || exact_actual_link_count != Some(actual.expected_live_link_count)
1132        || &actual != entry.link_commitment()
1133    {
1134        return Err(FolderbaseCaptureError::CaptureStateChanged(PathBuf::from(
1135            entry.path(),
1136        )));
1137    }
1138    Ok(())
1139}
1140
1141fn validate_restore_authority(
1142    root_attestation: &FolderbaseRootAttestation,
1143    root_instance_authority: &RootInstanceAuthority,
1144    transaction_id: &str,
1145    record: &RestoreAuthorityRecord,
1146) -> Result<(), FolderbaseCaptureError> {
1147    if record.format != RESTORE_AUTHORITY_FORMAT_V1
1148        || record.folderbase_id != root_attestation.folderbase_id
1149        || root_instance_authority
1150            .admit(&record.root_instance_sha256)
1151            .is_none()
1152        || record.transaction_id != transaction_id
1153        || record.private_stage_path
1154            != restore_stage_path(transaction_id)
1155                .to_str()
1156                .expect("restore authority paths are UTF-8")
1157        || validate_capture_path(&record.workspace_path).is_err()
1158        || validate_capture_sha256(&record.published_identity_sha256).is_err()
1159    {
1160        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
1161            "restore authority does not match its Folderbase, path, identity, or slot".to_owned(),
1162        ));
1163    }
1164    Ok(())
1165}
1166
1167struct CaptureDirectoryFrame {
1168    directory: Dir,
1169    entries: ReadDir,
1170    relative_parent: PathBuf,
1171    completion: Option<CaptureChildVerification>,
1172}
1173
1174struct CaptureChildVerification {
1175    name: OsString,
1176    identity: PhysicalIdentity,
1177    display_path: PathBuf,
1178}
1179
1180struct PendingCaptureDirectory {
1181    directory: Dir,
1182    relative_parent: PathBuf,
1183    verification: CaptureChildVerification,
1184}
1185
1186impl<'a> CapturePlanner<'a> {
1187    fn new(
1188        root: &'a Path,
1189        ignore: &'a IgnorePolicy,
1190        restore_authorities: RestoreAuthorityRegistry<'a>,
1191        legacy_root_files: bool,
1192    ) -> Self {
1193        Self {
1194            root,
1195            ignore,
1196            restore_authorities,
1197            legacy_root_files,
1198            entries: Vec::new(),
1199            exclusions: Vec::new(),
1200            ignored_paths: Vec::new(),
1201            path_index: CapturePathIndex::default(),
1202        }
1203    }
1204
1205    fn visit_directory(
1206        &mut self,
1207        directory: &Dir,
1208        relative_parent: &Path,
1209    ) -> Result<(), FolderbaseCaptureError> {
1210        let root_directory =
1211            directory
1212                .try_clone()
1213                .map_err(|source| FolderbaseCaptureError::Io {
1214                    path: self.root.join(relative_parent),
1215                    source,
1216                })?;
1217        let mut stack = vec![capture_directory_frame(
1218            root_directory,
1219            relative_parent.to_path_buf(),
1220            self.root,
1221            None,
1222        )?];
1223
1224        while !stack.is_empty() {
1225            let next = stack
1226                .last_mut()
1227                .expect("non-empty traversal stack")
1228                .entries
1229                .next();
1230            let Some(entry) = next else {
1231                let completed = stack.pop().expect("non-empty traversal stack");
1232                if let Some(verification) = completed.completion {
1233                    let parent = stack
1234                        .last()
1235                        .ok_or(FolderbaseCaptureError::PlanningStateChanged)?;
1236                    verify_child_identity(
1237                        &parent.directory,
1238                        &verification.name,
1239                        &verification.identity,
1240                        &verification.display_path,
1241                    )?;
1242                }
1243                continue;
1244            };
1245            let entry = entry.map_err(|source| {
1246                let relative_parent = &stack
1247                    .last()
1248                    .expect("non-empty traversal stack")
1249                    .relative_parent;
1250                FolderbaseCaptureError::Io {
1251                    path: self.root.join(relative_parent),
1252                    source,
1253                }
1254            })?;
1255            let pending = {
1256                let current = stack.last().expect("non-empty traversal stack");
1257                self.visit_entry(&current.directory, &current.relative_parent, entry)?
1258            };
1259            if let Some(pending) = pending {
1260                stack.push(capture_directory_frame(
1261                    pending.directory,
1262                    pending.relative_parent,
1263                    self.root,
1264                    Some(pending.verification),
1265                )?);
1266            }
1267        }
1268        Ok(())
1269    }
1270
1271    fn visit_entry(
1272        &mut self,
1273        directory: &Dir,
1274        relative_parent: &Path,
1275        entry: DirEntry,
1276    ) -> Result<Option<PendingCaptureDirectory>, FolderbaseCaptureError> {
1277        let name = entry.file_name();
1278        let relative = relative_parent.join(&name);
1279        let display_path = self.root.join(&relative);
1280        let metadata =
1281            directory
1282                .symlink_metadata(&name)
1283                .map_err(|source| FolderbaseCaptureError::Io {
1284                    path: display_path.clone(),
1285                    source,
1286                })?;
1287
1288        if name == OsStr::new(".folderbase") {
1289            return Ok(None);
1290        }
1291        if is_folderbase_state_component(&name) {
1292            return Err(FolderbaseCaptureError::UnsafePortablePath(relative));
1293        }
1294
1295        let required_marker = relative == Path::new(".folderbaseignore")
1296            || (self.legacy_root_files && relative == Path::new("FOLDERBASE.md"));
1297        let force_included = relative == Path::new(".folderbaseignore")
1298            || (self.legacy_root_files && relative == Path::new("FOLDERBASE.md"));
1299        if !force_included
1300            && matches!(
1301                self.ignore
1302                    .matcher
1303                    .matched(self.root.join(&relative), metadata.is_dir()),
1304                Match::Ignore(_)
1305            )
1306        {
1307            self.ensure_capacity(&relative)?;
1308            self.ignored_paths.push(CaptureIgnoredPath {
1309                path: portable_relative(&relative)?,
1310            });
1311            return Ok(None);
1312        }
1313
1314        self.ensure_capacity(&relative)?;
1315        let path = portable_relative(&relative)?;
1316        validate_capture_path(&path)
1317            .map_err(|_| FolderbaseCaptureError::UnsafePortablePath(relative.clone()))?;
1318        self.path_index.insert(&path)?;
1319
1320        if metadata.is_dir() && !metadata.file_type().is_symlink() {
1321            let (child, identity) = open_stable_child(directory, &name, &display_path)?;
1322            match classify_nested_folderbase_boundary(&child, &display_path)? {
1323                NestedFolderbaseBoundaryKind::ExactBoundary => {
1324                    verify_child_identity(directory, &name, &identity, &display_path)?;
1325                    self.exclusions.push(CapturePlanExclusion {
1326                        path,
1327                        kind: CaptureExclusionKind::NestedFolderbase,
1328                        reason: CaptureExclusionReason::NestedFolderbaseBoundary,
1329                    });
1330                    return Ok(None);
1331                }
1332                NestedFolderbaseBoundaryKind::UnsafeAliasShape => {
1333                    return Err(FolderbaseCaptureError::UnsafePortablePath(display_path));
1334                }
1335                NestedFolderbaseBoundaryKind::None => {}
1336            }
1337            self.entries.push(CapturePlanEntry {
1338                path,
1339                kind: CaptureEntryKind::Directory,
1340                bytes: None,
1341                executable: None,
1342                symlink_target: None,
1343                observed: capture_entry_fingerprint(
1344                    directory,
1345                    &name,
1346                    CaptureEntryKind::Directory,
1347                    &metadata,
1348                    &display_path,
1349                )?,
1350                link_commitment: CaptureLinkCommitment::default(),
1351            });
1352            return Ok(Some(PendingCaptureDirectory {
1353                directory: child,
1354                relative_parent: relative,
1355                verification: CaptureChildVerification {
1356                    name,
1357                    identity,
1358                    display_path,
1359                },
1360            }));
1361        }
1362
1363        let mut link_commitment = CaptureLinkCommitment::default();
1364        let mut regular_observed = None;
1365        let mut regular_bytes = None;
1366        let mut regular_executable = None;
1367        if metadata.is_file() && !metadata.file_type().is_symlink() {
1368            let (observed, workspace_identity, link_count) =
1369                planned_regular_link_observation(directory, &name, &metadata, &display_path)?;
1370            regular_bytes = Some(observed.bytes);
1371            regular_executable = Some(observed.executable);
1372            regular_observed = Some(observed);
1373            link_commitment = self.restore_authorities.validated_link_commitment(
1374                &workspace_identity,
1375                link_count,
1376                &path,
1377                &display_path,
1378            )?;
1379            if link_count != link_commitment.authorities.len().saturating_add(1) {
1380                if required_marker {
1381                    return Err(FolderbaseCaptureError::RequiredMarker(display_path));
1382                }
1383                self.exclusions.push(CapturePlanExclusion {
1384                    path,
1385                    kind: CaptureExclusionKind::HardLink,
1386                    reason: CaptureExclusionReason::UnsupportedV1,
1387                });
1388                return Ok(None);
1389            }
1390        }
1391
1392        if let Some(kind) = unsupported_entry_kind(directory, &name, &display_path, &metadata)? {
1393            if required_marker {
1394                return Err(FolderbaseCaptureError::RequiredMarker(display_path));
1395            }
1396            self.exclusions.push(CapturePlanExclusion {
1397                path,
1398                kind,
1399                reason: CaptureExclusionReason::UnsupportedV1,
1400            });
1401            return Ok(None);
1402        }
1403
1404        let (kind, bytes, executable, symlink_target) = if metadata.file_type().is_symlink() {
1405            let target = read_stable_symlink(directory, &name, &relative, &display_path)?;
1406            (CaptureEntryKind::Symlink, None, None, Some(target))
1407        } else if metadata.is_file() {
1408            let bytes = regular_bytes.ok_or(FolderbaseCaptureError::PlanningStateChanged)?;
1409            if bytes > MAX_OBJECT_BYTES {
1410                return Err(FolderbaseCaptureError::InventoryLimitExceeded {
1411                    limit: CapturePlanLimitKind::ObjectBytes,
1412                    maximum: MAX_OBJECT_BYTES,
1413                    path: relative,
1414                });
1415            }
1416            (
1417                CaptureEntryKind::RegularFile,
1418                Some(bytes),
1419                regular_executable,
1420                None,
1421            )
1422        } else {
1423            return Err(FolderbaseCaptureError::PlanningStateChanged);
1424        };
1425        let observed = match kind {
1426            CaptureEntryKind::RegularFile => {
1427                regular_observed.ok_or(FolderbaseCaptureError::PlanningStateChanged)?
1428            }
1429            CaptureEntryKind::Directory | CaptureEntryKind::Symlink => {
1430                capture_entry_fingerprint(directory, &name, kind, &metadata, &display_path)?
1431            }
1432        };
1433        self.entries.push(CapturePlanEntry {
1434            path,
1435            kind,
1436            bytes,
1437            executable,
1438            symlink_target,
1439            observed,
1440            link_commitment,
1441        });
1442        Ok(None)
1443    }
1444
1445    fn ensure_capacity(&self, path: &Path) -> Result<(), FolderbaseCaptureError> {
1446        ensure_record_capacity(
1447            self.entries.len() + self.exclusions.len() + self.ignored_paths.len(),
1448            path,
1449        )
1450    }
1451}
1452
1453fn capture_directory_frame(
1454    directory: Dir,
1455    relative_parent: PathBuf,
1456    root: &Path,
1457    completion: Option<CaptureChildVerification>,
1458) -> Result<CaptureDirectoryFrame, FolderbaseCaptureError> {
1459    let entries = directory
1460        .read_dir(".")
1461        .map_err(|source| FolderbaseCaptureError::Io {
1462            path: root.join(&relative_parent),
1463            source,
1464        })?;
1465    Ok(CaptureDirectoryFrame {
1466        directory,
1467        entries,
1468        relative_parent,
1469        completion,
1470    })
1471}
1472
1473struct IgnorePolicy {
1474    matcher: ignore::gitignore::Gitignore,
1475    sha256: String,
1476}
1477
1478#[derive(Default)]
1479struct CapturePathIndex {
1480    exact: BTreeMap<String, String>,
1481    nfc: BTreeMap<String, String>,
1482    folded: BTreeMap<String, String>,
1483}
1484
1485impl CapturePathIndex {
1486    fn insert(&mut self, path: &str) -> Result<(), FolderbaseCaptureError> {
1487        let nfc = path.nfc().collect::<String>();
1488        let folded = nfc
1489            .case_fold()
1490            .collect::<String>()
1491            .nfc()
1492            .collect::<String>();
1493        if let Some(existing) = self.exact.get(path) {
1494            return Err(FolderbaseCaptureError::PortablePathCollision {
1495                existing: existing.clone(),
1496                path: path.to_owned(),
1497            });
1498        }
1499        if let Some(existing) = [self.nfc.get(&nfc), self.folded.get(&folded)]
1500            .into_iter()
1501            .flatten()
1502            .next()
1503        {
1504            return Err(FolderbaseCaptureError::PortablePathCollision {
1505                existing: existing.clone(),
1506                path: path.to_owned(),
1507            });
1508        }
1509        self.exact.insert(path.to_owned(), path.to_owned());
1510        self.nfc.insert(nfc, path.to_owned());
1511        self.folded.insert(folded, path.to_owned());
1512        Ok(())
1513    }
1514}
1515
1516fn portable_relative(path: &Path) -> Result<String, FolderbaseCaptureError> {
1517    let mut parts = Vec::new();
1518    for component in path.components() {
1519        let Component::Normal(part) = component else {
1520            return Err(FolderbaseCaptureError::UnsafePortablePath(
1521                path.to_path_buf(),
1522            ));
1523        };
1524        parts.push(
1525            part.to_str()
1526                .ok_or_else(|| FolderbaseCaptureError::UnsafePortablePath(path.to_path_buf()))?
1527                .to_owned(),
1528        );
1529    }
1530    if parts.is_empty() {
1531        return Err(FolderbaseCaptureError::UnsafePortablePath(
1532            path.to_path_buf(),
1533        ));
1534    }
1535    Ok(parts.join("/"))
1536}
1537
1538#[cfg(unix)]
1539fn is_executable(metadata: &Metadata) -> bool {
1540    use cap_std::fs::PermissionsExt;
1541
1542    metadata.permissions().mode() & 0o111 != 0
1543}
1544
1545#[cfg(windows)]
1546fn is_executable(_metadata: &Metadata) -> bool {
1547    false
1548}
1549
1550#[cfg(unix)]
1551pub(crate) fn capture_entry_fingerprint(
1552    _directory: &Dir,
1553    _name: &OsStr,
1554    _kind: CaptureEntryKind,
1555    metadata: &Metadata,
1556    _display_path: &Path,
1557) -> Result<CaptureMetadataFingerprint, FolderbaseCaptureError> {
1558    Ok(CaptureMetadataFingerprint::from_cap_metadata(metadata))
1559}
1560
1561#[cfg(windows)]
1562pub(crate) fn capture_entry_fingerprint(
1563    directory: &Dir,
1564    name: &OsStr,
1565    kind: CaptureEntryKind,
1566    metadata: &Metadata,
1567    display_path: &Path,
1568) -> Result<CaptureMetadataFingerprint, FolderbaseCaptureError> {
1569    let file = match kind {
1570        CaptureEntryKind::Directory => directory
1571            .open_dir_nofollow(name)
1572            .map_err(|source| FolderbaseCaptureError::Io {
1573                path: display_path.to_path_buf(),
1574                source,
1575            })?
1576            .into_std_file(),
1577        CaptureEntryKind::RegularFile | CaptureEntryKind::Symlink => {
1578            use cap_std::fs::OpenOptionsExt;
1579            use windows_sys::Win32::Storage::FileSystem::{
1580                FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT,
1581            };
1582
1583            let mut options = OpenOptions::new();
1584            options
1585                .read(true)
1586                .follow(FollowSymlinks::No)
1587                .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT);
1588            directory
1589                .open_with(name, &options)
1590                .map_err(|source| FolderbaseCaptureError::Io {
1591                    path: display_path.to_path_buf(),
1592                    source,
1593                })?
1594                .into_std()
1595        }
1596    };
1597    let identity = windows_file_identity(&file).map_err(|source| FolderbaseCaptureError::Io {
1598        path: display_path.to_path_buf(),
1599        source,
1600    })?;
1601    Ok(CaptureMetadataFingerprint::from_cap_metadata(metadata)
1602        .with_physical_identity(Some(identity)))
1603}
1604
1605#[cfg(unix)]
1606fn planned_regular_link_observation(
1607    _directory: &Dir,
1608    _name: &OsStr,
1609    metadata: &Metadata,
1610    _display_path: &Path,
1611) -> Result<(CaptureMetadataFingerprint, String, usize), FolderbaseCaptureError> {
1612    use cap_std::fs::MetadataExt;
1613
1614    let link_count = usize::try_from(metadata.nlink())
1615        .map_err(|_| FolderbaseCaptureError::PlanningStateChanged)?;
1616    Ok((
1617        CaptureMetadataFingerprint::from_cap_metadata(metadata),
1618        stable_unix_file_identity_sha256(metadata.dev(), metadata.ino()),
1619        link_count,
1620    ))
1621}
1622
1623#[cfg(windows)]
1624fn planned_regular_link_observation(
1625    directory: &Dir,
1626    name: &OsStr,
1627    metadata: &Metadata,
1628    display_path: &Path,
1629) -> Result<(CaptureMetadataFingerprint, String, usize), FolderbaseCaptureError> {
1630    use cap_std::fs::OpenOptionsExt;
1631    use windows_sys::Win32::Storage::FileSystem::{
1632        FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_DELETE,
1633        FILE_SHARE_READ, FILE_SHARE_WRITE,
1634    };
1635
1636    let mut options = OpenOptions::new();
1637    options
1638        .access_mode(0)
1639        .follow(FollowSymlinks::No)
1640        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
1641        .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE);
1642    let file = directory
1643        .open_with(name, &options)
1644        .map_err(|source| FolderbaseCaptureError::Io {
1645            path: display_path.to_path_buf(),
1646            source,
1647        })?
1648        .into_std();
1649    let identity =
1650        stable_file_identity_sha256(&file).map_err(|source| FolderbaseCaptureError::Io {
1651            path: display_path.to_path_buf(),
1652            source,
1653        })?;
1654    let link_count = usize::try_from(stable_file_link_count(&file).map_err(|source| {
1655        FolderbaseCaptureError::Io {
1656            path: display_path.to_path_buf(),
1657            source,
1658        }
1659    })?)
1660    .map_err(|_| FolderbaseCaptureError::PlanningStateChanged)?;
1661    Ok((
1662        CaptureMetadataFingerprint::from_cap_metadata(metadata).with_physical_identity(Some(
1663            windows_file_identity(&file).map_err(|source| FolderbaseCaptureError::Io {
1664                path: display_path.to_path_buf(),
1665                source,
1666            })?,
1667        )),
1668        identity,
1669        link_count,
1670    ))
1671}
1672
1673#[cfg(windows)]
1674fn windows_file_identity(file: &fs::File) -> io::Result<String> {
1675    use std::{mem::size_of, os::windows::io::AsRawHandle};
1676    use windows_sys::Win32::{
1677        Foundation::HANDLE,
1678        Storage::FileSystem::{FILE_ID_INFO, FileIdInfo, GetFileInformationByHandleEx},
1679    };
1680
1681    let mut information = FILE_ID_INFO::default();
1682    if unsafe {
1683        GetFileInformationByHandleEx(
1684            file.as_raw_handle() as HANDLE,
1685            FileIdInfo,
1686            (&raw mut information).cast(),
1687            size_of::<FILE_ID_INFO>() as u32,
1688        )
1689    } == 0
1690    {
1691        return Err(io::Error::last_os_error());
1692    }
1693    let mut encoded = format!(
1694        "windows-file-id-128:{:016x}:",
1695        information.VolumeSerialNumber
1696    );
1697    for byte in information.FileId.Identifier {
1698        use fmt::Write as _;
1699        let _ = write!(encoded, "{byte:02x}");
1700    }
1701    Ok(encoded)
1702}
1703
1704#[cfg(unix)]
1705fn unsupported_entry_kind(
1706    _directory: &Dir,
1707    _name: &OsStr,
1708    _display_path: &Path,
1709    metadata: &Metadata,
1710) -> Result<Option<CaptureExclusionKind>, FolderbaseCaptureError> {
1711    use cap_std::fs::FileTypeExt;
1712
1713    let file_type = metadata.file_type();
1714    let kind = if file_type.is_fifo() {
1715        Some(CaptureExclusionKind::Fifo)
1716    } else if file_type.is_socket() {
1717        Some(CaptureExclusionKind::Socket)
1718    } else if file_type.is_block_device() {
1719        Some(CaptureExclusionKind::BlockDevice)
1720    } else if file_type.is_char_device() {
1721        Some(CaptureExclusionKind::CharacterDevice)
1722    } else if !metadata.is_file() && !metadata.is_dir() && !metadata.file_type().is_symlink() {
1723        Some(CaptureExclusionKind::OtherSpecial)
1724    } else {
1725        None
1726    };
1727    Ok(kind)
1728}
1729
1730#[cfg(windows)]
1731fn unsupported_entry_kind(
1732    _directory: &Dir,
1733    _name: &OsStr,
1734    _display_path: &Path,
1735    _metadata: &Metadata,
1736) -> Result<Option<CaptureExclusionKind>, FolderbaseCaptureError> {
1737    Ok(None)
1738}
1739
1740fn open_planning_root(root: &Path) -> Result<Dir, FolderbaseCaptureError> {
1741    let mut options = fs::OpenOptions::new();
1742    options.read(true);
1743    #[cfg(unix)]
1744    {
1745        use std::os::unix::fs::OpenOptionsExt;
1746
1747        options.custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW);
1748    }
1749    #[cfg(windows)]
1750    {
1751        use std::os::windows::fs::OpenOptionsExt;
1752        use windows_sys::Win32::Storage::FileSystem::{
1753            FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_DELETE,
1754            FILE_SHARE_READ, FILE_SHARE_WRITE,
1755        };
1756
1757        options
1758            .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
1759            .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE);
1760    }
1761    let file = options
1762        .open(root)
1763        .map_err(|source| FolderbaseCaptureError::Io {
1764            path: root.to_path_buf(),
1765            source,
1766        })?;
1767    let metadata = file
1768        .metadata()
1769        .map_err(|source| FolderbaseCaptureError::Io {
1770            path: root.to_path_buf(),
1771            source,
1772        })?;
1773    if !metadata.is_dir() || std_metadata_is_link_or_reparse(&metadata) {
1774        return Err(FolderbaseCaptureError::PlanningStateChanged);
1775    }
1776    Ok(Dir::from_std_file(file))
1777}
1778
1779#[cfg(unix)]
1780fn std_metadata_is_link_or_reparse(metadata: &fs::Metadata) -> bool {
1781    metadata.file_type().is_symlink()
1782}
1783
1784#[cfg(windows)]
1785fn std_metadata_is_link_or_reparse(metadata: &fs::Metadata) -> bool {
1786    use std::os::windows::fs::MetadataExt;
1787    use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT;
1788
1789    metadata.file_type().is_symlink()
1790        || metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
1791}
1792
1793fn directory_identity(
1794    directory: &Dir,
1795    display_path: &Path,
1796) -> Result<PhysicalIdentity, FolderbaseCaptureError> {
1797    let file = directory
1798        .try_clone()
1799        .map_err(|source| FolderbaseCaptureError::Io {
1800            path: display_path.to_path_buf(),
1801            source,
1802        })?
1803        .into_std_file();
1804    PhysicalIdentity::from_file(&file).map_err(|source| FolderbaseCaptureError::Io {
1805        path: display_path.to_path_buf(),
1806        source,
1807    })
1808}
1809
1810fn verify_root_capability(expected: &Dir, root: &Path) -> Result<(), FolderbaseCaptureError> {
1811    let expected = directory_identity(expected, root)?;
1812    let reopened = open_planning_root(root)?;
1813    if directory_identity(&reopened, root)? != expected {
1814        return Err(FolderbaseCaptureError::PlanningStateChanged);
1815    }
1816    Ok(())
1817}
1818
1819fn open_stable_child(
1820    parent: &Dir,
1821    name: &OsStr,
1822    display_path: &Path,
1823) -> Result<(Dir, PhysicalIdentity), FolderbaseCaptureError> {
1824    let child = parent
1825        .open_dir_nofollow(name)
1826        .map_err(|source| FolderbaseCaptureError::Io {
1827            path: display_path.to_path_buf(),
1828            source,
1829        })?;
1830    let identity = directory_identity(&child, display_path)?;
1831    verify_child_identity(parent, name, &identity, display_path)?;
1832    Ok((child, identity))
1833}
1834
1835fn verify_child_identity(
1836    parent: &Dir,
1837    name: &OsStr,
1838    expected: &PhysicalIdentity,
1839    display_path: &Path,
1840) -> Result<(), FolderbaseCaptureError> {
1841    let reopened = parent
1842        .open_dir_nofollow(name)
1843        .map_err(|source| FolderbaseCaptureError::Io {
1844            path: display_path.to_path_buf(),
1845            source,
1846        })?;
1847    if &directory_identity(&reopened, display_path)? != expected {
1848        return Err(FolderbaseCaptureError::PlanningStateChanged);
1849    }
1850    Ok(())
1851}
1852
1853fn read_stable_symlink(
1854    directory: &Dir,
1855    name: &OsStr,
1856    relative: &Path,
1857    display_path: &Path,
1858) -> Result<String, FolderbaseCaptureError> {
1859    let target = directory
1860        .read_link(name)
1861        .map_err(|source| FolderbaseCaptureError::Io {
1862            path: display_path.to_path_buf(),
1863            source,
1864        })?;
1865    let rechecked = directory
1866        .read_link(name)
1867        .map_err(|source| FolderbaseCaptureError::Io {
1868            path: display_path.to_path_buf(),
1869            source,
1870        })?;
1871    if rechecked != target {
1872        return Err(FolderbaseCaptureError::PlanningStateChanged);
1873    }
1874    portable_symlink_target(&target)
1875        .ok_or_else(|| FolderbaseCaptureError::UnsafeSymlinkTarget(relative.to_path_buf()))
1876}
1877
1878fn portable_symlink_target(target: &Path) -> Option<String> {
1879    let target = target.to_str()?;
1880    #[cfg(windows)]
1881    {
1882        // Windows exposes path separators in link targets as `\`. Folderbase
1883        // records use `/` on every platform; validation still rejects drive,
1884        // UNC, absolute, escaping, and otherwise unsafe targets afterwards.
1885        Some(target.replace('\\', "/"))
1886    }
1887    #[cfg(not(windows))]
1888    {
1889        Some(target.to_owned())
1890    }
1891}
1892
1893fn ensure_record_capacity(current: usize, path: &Path) -> Result<(), FolderbaseCaptureError> {
1894    if current == MAX_CAPTURE_PLAN_RECORDS {
1895        return Err(FolderbaseCaptureError::InventoryLimitExceeded {
1896            limit: CapturePlanLimitKind::Entries,
1897            maximum: MAX_CAPTURE_PLAN_RECORDS as u64,
1898            path: path.to_path_buf(),
1899        });
1900    }
1901    Ok(())
1902}
1903
1904fn read_local_head(
1905    attestation: &FolderbaseRootAttestation,
1906    root_instance_authority: &RootInstanceAuthority,
1907    root: &Dir,
1908) -> Result<Option<CaptureLocalHead>, FolderbaseCaptureError> {
1909    let path = attestation.root.join(LOCAL_HEAD_PATH);
1910    let state = root
1911        .open_dir_nofollow(".folderbase")
1912        .map_err(|_| FolderbaseCaptureError::UnsafeLocalHead)?;
1913    let local_metadata = match state.symlink_metadata("local") {
1914        Ok(metadata) => metadata,
1915        Err(source) if source.kind() == io::ErrorKind::NotFound => return Ok(None),
1916        Err(source) => return Err(FolderbaseCaptureError::Io { path, source }),
1917    };
1918    if local_metadata.file_type().is_symlink() || !local_metadata.is_dir() {
1919        return Err(FolderbaseCaptureError::UnsafeLocalHead);
1920    }
1921    let local = state
1922        .open_dir_nofollow("local")
1923        .map_err(|_| FolderbaseCaptureError::UnsafeLocalHead)?;
1924    let metadata = match local.symlink_metadata("head.json") {
1925        Ok(metadata) => metadata,
1926        Err(source) if source.kind() == io::ErrorKind::NotFound => return Ok(None),
1927        Err(source) => return Err(FolderbaseCaptureError::Io { path, source }),
1928    };
1929    if metadata.file_type().is_symlink() || !metadata.is_file() {
1930        return Err(FolderbaseCaptureError::UnsafeLocalHead);
1931    }
1932    if metadata.len() > MAX_LOCAL_HEAD_BYTES {
1933        return Err(FolderbaseCaptureError::LocalHeadTooLarge {
1934            maximum_bytes: MAX_LOCAL_HEAD_BYTES,
1935        });
1936    }
1937    let mut file = open_regular_nofollow(&local, Path::new("head.json"))
1938        .map_err(|_| FolderbaseCaptureError::UnsafeLocalHead)?;
1939    let observed = CaptureMetadataFingerprint::from_std_file(&file).map_err(|source| {
1940        FolderbaseCaptureError::Io {
1941            path: path.clone(),
1942            source,
1943        }
1944    })?;
1945    let mut encoded = Vec::new();
1946    file.by_ref()
1947        .take(MAX_LOCAL_HEAD_BYTES + 1)
1948        .read_to_end(&mut encoded)
1949        .map_err(|source| FolderbaseCaptureError::Io {
1950            path: path.clone(),
1951            source,
1952        })?;
1953    if encoded.len() as u64 > MAX_LOCAL_HEAD_BYTES {
1954        return Err(FolderbaseCaptureError::LocalHeadTooLarge {
1955            maximum_bytes: MAX_LOCAL_HEAD_BYTES,
1956        });
1957    }
1958    let final_observed = CaptureMetadataFingerprint::from_std_file(&file).map_err(|source| {
1959        FolderbaseCaptureError::Io {
1960            path: path.clone(),
1961            source,
1962        }
1963    })?;
1964    if final_observed != observed {
1965        return Err(FolderbaseCaptureError::PlanningStateChanged);
1966    }
1967    let encoded_sha256 = format!("{:x}", Sha256::digest(&encoded));
1968    let head: LocalHeadWire = serde_json::from_slice(&encoded)
1969        .map_err(|error| FolderbaseCaptureError::InvalidLocalHead(error.to_string()))?;
1970    let (folderbase_id, root_instance_sha256, version_id, version_sha256, authority) = match head {
1971        LocalHeadWire::V2(head) if head.format == "folderbase-local-head-v2" => (
1972            head.folderbase_id,
1973            head.root_instance_sha256,
1974            head.version_id,
1975            head.version_sha256,
1976            head.authority,
1977        ),
1978        LocalHeadWire::V1(head) if head.format == "folderbase-local-head-v1" => (
1979            head.folderbase_id,
1980            head.root_instance_sha256,
1981            head.version_id,
1982            head.version_sha256,
1983            LocalHeadAuthority::CaptureTransactionV1 {
1984                sha256: head.transaction_sha256,
1985            },
1986        ),
1987        _ => {
1988            return Err(FolderbaseCaptureError::InvalidLocalHead(
1989                "record has an unsupported Local Head format".to_owned(),
1990            ));
1991        }
1992    };
1993    if folderbase_id != attestation.folderbase_id
1994        || root_instance_authority
1995            .admit(&root_instance_sha256)
1996            .is_none()
1997    {
1998        return Err(FolderbaseCaptureError::InvalidLocalHead(
1999            "record does not bind the attested physical Folderbase Root".to_owned(),
2000        ));
2001    }
2002    validate_capture_sha256(&root_instance_sha256)
2003        .map_err(|error| FolderbaseCaptureError::InvalidLocalHead(error.to_string()))?;
2004    validate_capture_version_id(&version_id)
2005        .map_err(|error| FolderbaseCaptureError::InvalidLocalHead(error.to_string()))?;
2006    validate_capture_sha256(&version_sha256)
2007        .map_err(|error| FolderbaseCaptureError::InvalidLocalHead(error.to_string()))?;
2008    validate_capture_sha256(authority.sha256())
2009        .map_err(|error| FolderbaseCaptureError::InvalidLocalHead(error.to_string()))?;
2010    if let LocalHeadAuthority::VersionDerivedV1 { sha256 } = &authority {
2011        let expected = version_derived_local_head_sha256(
2012            &folderbase_id,
2013            &root_instance_sha256,
2014            &version_id,
2015            &version_sha256,
2016        )?;
2017        if sha256 != &expected {
2018            return Err(FolderbaseCaptureError::InvalidLocalHead(
2019                "version-derived Local Head authority does not match its bound Folderbase Version"
2020                    .to_owned(),
2021            ));
2022        }
2023    }
2024    Ok(Some(CaptureLocalHead {
2025        version_id,
2026        version_sha256,
2027        authority,
2028        encoded_sha256,
2029        observed,
2030    }))
2031}
2032
2033fn read_ignore_policy(
2034    root_directory: &Dir,
2035    root: &Path,
2036    profile: &ManifestProtocolProfile,
2037) -> Result<IgnorePolicy, FolderbaseCaptureError> {
2038    let required = profile.requires_legacy_root_files();
2039    let path = root.join(".folderbaseignore");
2040    let mut encoded = Vec::new();
2041    let present = match root_directory.symlink_metadata(".folderbaseignore") {
2042        Ok(metadata) => {
2043            if metadata.file_type().is_symlink() || !metadata.is_file() {
2044                return Err(FolderbaseCaptureError::RequiredMarker(path));
2045            }
2046            if metadata.len() > MAX_FOLDERBASEIGNORE_BYTES {
2047                return Err(FolderbaseCaptureError::IgnorePolicyTooLarge {
2048                    maximum_bytes: MAX_FOLDERBASEIGNORE_BYTES,
2049                });
2050            }
2051            let mut file = open_regular_nofollow(root_directory, Path::new(".folderbaseignore"))
2052                .map_err(|source| FolderbaseCaptureError::Io {
2053                    path: path.clone(),
2054                    source,
2055                })?;
2056            file.by_ref()
2057                .take(MAX_FOLDERBASEIGNORE_BYTES + 1)
2058                .read_to_end(&mut encoded)
2059                .map_err(|source| FolderbaseCaptureError::Io {
2060                    path: path.clone(),
2061                    source,
2062                })?;
2063            true
2064        }
2065        Err(source) if source.kind() == io::ErrorKind::NotFound && !required => false,
2066        Err(_) if required => return Err(FolderbaseCaptureError::RequiredMarker(path)),
2067        Err(source) => return Err(FolderbaseCaptureError::Io { path, source }),
2068    };
2069    if encoded.len() as u64 > MAX_FOLDERBASEIGNORE_BYTES {
2070        return Err(FolderbaseCaptureError::IgnorePolicyTooLarge {
2071            maximum_bytes: MAX_FOLDERBASEIGNORE_BYTES,
2072        });
2073    }
2074    let policy =
2075        std::str::from_utf8(&encoded).map_err(|_| FolderbaseCaptureError::IgnorePolicyNotUtf8)?;
2076    let mut digest = Sha256::new();
2077    let engine_rules = if required {
2078        digest.update(b"folderbase-ignore-policy-v1\0");
2079        RECONSTRUCTABLE_DIRECTORIES
2080            .iter()
2081            .map(|directory| format!("{directory}/"))
2082            .chain([".DS_Store", "*.tmp", "~$*"].into_iter().map(str::to_owned))
2083            .collect::<Vec<_>>()
2084    } else {
2085        digest.update(b"folderbase-ignore-policy-v2\0");
2086        digest.update(if present {
2087            b"present\0".as_slice()
2088        } else {
2089            b"absent\0".as_slice()
2090        });
2091        profile
2092            .capture_ignore_rules()
2093            .expect("ordinary profile carries exact engine rules")
2094            .to_vec()
2095    };
2096    for pattern in &engine_rules {
2097        digest.update(pattern.as_bytes());
2098        digest.update(b"\n");
2099    }
2100    digest.update(b"\0");
2101    digest.update(&encoded);
2102    let matcher = build_folderbaseignore_matcher(root, &path, &engine_rules, policy)?;
2103    Ok(IgnorePolicy {
2104        matcher,
2105        sha256: format!("{:x}", digest.finalize()),
2106    })
2107}
2108
2109pub(crate) fn validate_folderbaseignore_content(
2110    root: &Path,
2111    content: &str,
2112) -> Result<(), FolderbaseCaptureError> {
2113    build_folderbaseignore_matcher(root, &root.join(".folderbaseignore"), &[], content).map(drop)
2114}
2115
2116fn build_folderbaseignore_matcher(
2117    root: &Path,
2118    path: &Path,
2119    engine_rules: &[String],
2120    content: &str,
2121) -> Result<Gitignore, FolderbaseCaptureError> {
2122    if content.len() as u64 > MAX_FOLDERBASEIGNORE_BYTES {
2123        return Err(FolderbaseCaptureError::IgnorePolicyTooLarge {
2124            maximum_bytes: MAX_FOLDERBASEIGNORE_BYTES,
2125        });
2126    }
2127    let mut builder = GitignoreBuilder::new(root);
2128    for pattern in engine_rules {
2129        builder
2130            .add_line(None, pattern)
2131            .map_err(|error| FolderbaseCaptureError::InvalidIgnorePolicy(error.to_string()))?;
2132    }
2133    for line in content.lines() {
2134        builder
2135            .add_line(Some(path.to_path_buf()), line)
2136            .map_err(|error| FolderbaseCaptureError::InvalidIgnorePolicy(error.to_string()))?;
2137    }
2138    builder
2139        .build()
2140        .map_err(|error| FolderbaseCaptureError::InvalidIgnorePolicy(error.to_string()))
2141}
2142
2143fn require_regular_marker(
2144    root_directory: &Dir,
2145    root: &Path,
2146    relative: &Path,
2147) -> Result<(), FolderbaseCaptureError> {
2148    let path = root.join(relative);
2149    let metadata = root_directory
2150        .symlink_metadata(relative)
2151        .map_err(|_| FolderbaseCaptureError::RequiredMarker(path.clone()))?;
2152    if metadata.file_type().is_symlink() || !metadata.is_file() {
2153        return Err(FolderbaseCaptureError::RequiredMarker(path));
2154    }
2155    Ok(())
2156}
2157
2158fn protocol_file_observation(
2159    root_directory: &Dir,
2160    root: &Path,
2161    relative: &Path,
2162) -> Result<CaptureMetadataFingerprint, FolderbaseCaptureError> {
2163    let path = root.join(relative);
2164    let state_directory = root_directory
2165        .open_dir_nofollow(".folderbase")
2166        .map_err(|source| FolderbaseCaptureError::Io {
2167            path: path.clone(),
2168            source,
2169        })?;
2170    let file =
2171        open_regular_nofollow(&state_directory, Path::new("manifest.json")).map_err(|source| {
2172            FolderbaseCaptureError::Io {
2173                path: path.clone(),
2174                source,
2175            }
2176        })?;
2177    let metadata = file
2178        .metadata()
2179        .map_err(|source| FolderbaseCaptureError::Io {
2180            path: path.clone(),
2181            source,
2182        })?;
2183    if !metadata.is_file() {
2184        return Err(FolderbaseCaptureError::RequiredMarker(root.join(relative)));
2185    }
2186    CaptureMetadataFingerprint::from_std_file(&file)
2187        .map_err(|source| FolderbaseCaptureError::Io { path, source })
2188}
2189
2190fn open_regular_nofollow(root: &Dir, relative: &Path) -> io::Result<fs::File> {
2191    let mut options = OpenOptions::new();
2192    options.read(true).follow(FollowSymlinks::No);
2193    root.open_with(relative, &options)
2194        .map(|file| file.into_std())
2195}
2196
2197#[cfg(test)]
2198mod capability_tests {
2199    use super::*;
2200
2201    const MANIFEST: &[u8] = br#"{
2202      "$schema": "https://folderbase.ai/protocol/0.5/folderbase.schema.json",
2203      "protocol_version": "0.5.0",
2204      "folderbase": {
2205        "id": "folderbase_019f9b75-4f42-7f65-a012-2bfecdd8c473",
2206        "name": "Capture capability fixture",
2207        "kind": "project",
2208        "status": "active",
2209        "created_at": "2026-08-04T00:00:00Z"
2210      },
2211      "adapters": [],
2212      "policies": {
2213        "availability": "keep_local",
2214        "structural_changes": "approve",
2215        "archive": "manual",
2216        "cloud_sync": "disabled",
2217        "capture_ignore": {"format": "folderbase-capture-ignore-v1", "rules": []}
2218      }
2219    }"#;
2220
2221    struct AmbientRootSwap {
2222        visible: PathBuf,
2223        detached: PathBuf,
2224        replacement: PathBuf,
2225    }
2226
2227    impl AmbientRootSwap {
2228        fn activate(visible: &Path, replacement: &Path) -> Self {
2229            let detached = visible.with_file_name("detached-capture-root");
2230            fs::rename(visible, &detached).expect("detach capture root");
2231            fs::rename(replacement, visible).expect("install replacement root");
2232            Self {
2233                visible: visible.to_path_buf(),
2234                detached,
2235                replacement: replacement.to_path_buf(),
2236            }
2237        }
2238    }
2239
2240    impl Drop for AmbientRootSwap {
2241        fn drop(&mut self) {
2242            fs::rename(&self.visible, &self.replacement).expect("remove replacement root");
2243            fs::rename(&self.detached, &self.visible).expect("restore capture root");
2244        }
2245    }
2246
2247    fn initialize_root(root: &Path) {
2248        fs::create_dir(root).expect("Folderbase root");
2249        fs::create_dir(root.join(".folderbase")).expect("state");
2250        fs::write(root.join(".folderbase/manifest.json"), MANIFEST).expect("manifest");
2251    }
2252
2253    #[cfg(windows)]
2254    #[test]
2255    fn windows_symlink_targets_are_canonicalized_before_portable_validation() {
2256        assert_eq!(
2257            portable_symlink_target(Path::new(r"..\notes\Brief.md")).as_deref(),
2258            Some("../notes/Brief.md")
2259        );
2260        assert_eq!(
2261            portable_symlink_target(Path::new(r"C:\outside\secret.md")).as_deref(),
2262            Some("C:/outside/secret.md")
2263        );
2264    }
2265
2266    #[cfg(unix)]
2267    #[test]
2268    fn retained_child_identity_rejects_a_directory_to_symlink_swap() {
2269        let root = tempfile::tempdir().expect("root");
2270        let outside = tempfile::tempdir().expect("outside");
2271        fs::create_dir(root.path().join("child")).expect("child");
2272        let root_directory = open_planning_root(root.path()).expect("root capability");
2273        let (_child, identity) = open_stable_child(
2274            &root_directory,
2275            OsStr::new("child"),
2276            &root.path().join("child"),
2277        )
2278        .expect("retained child");
2279
2280        fs::rename(root.path().join("child"), root.path().join("detached")).expect("detach child");
2281        std::os::unix::fs::symlink(outside.path(), root.path().join("child"))
2282            .expect("outside replacement");
2283
2284        assert!(
2285            verify_child_identity(
2286                &root_directory,
2287                OsStr::new("child"),
2288                &identity,
2289                &root.path().join("child"),
2290            )
2291            .is_err()
2292        );
2293    }
2294
2295    #[cfg(unix)]
2296    #[test]
2297    fn capture_restore_authorities_never_cross_an_ambient_root_aba() {
2298        let owner = tempfile::tempdir().expect("root owner");
2299        let visible = owner.path().join("workspace");
2300        let replacement = owner.path().join("replacement");
2301        initialize_root(&visible);
2302        initialize_root(&replacement);
2303        let opening_file = visible.join("ordinary.md");
2304        fs::write(&opening_file, b"opening bytes\n").expect("opening file");
2305        let store = FolderbaseVersionStore::open(&visible).expect("version store");
2306
2307        let transaction_id = "fbrestore_019f0000-0000-7000-8000-000000000077";
2308        let stage = replacement.join(restore_stage_path(transaction_id));
2309        fs::create_dir_all(stage.parent().expect("stage parent")).expect("restore transaction");
2310        fs::hard_link(&opening_file, replacement.join("ordinary.md"))
2311            .expect("replacement workspace hard link");
2312        fs::hard_link(&opening_file, &stage).expect("replacement private authority link");
2313        let file = fs::File::open(&opening_file).expect("opening file identity");
2314        let record = RestoreAuthorityRecord {
2315            format: RESTORE_AUTHORITY_FORMAT_V1.to_owned(),
2316            folderbase_id: store.root_attestation.folderbase_id.clone(),
2317            root_instance_sha256: store.root_attestation.root_instance_sha256.clone(),
2318            transaction_id: transaction_id.to_owned(),
2319            workspace_path: "ordinary.md".to_owned(),
2320            private_stage_path: restore_stage_path(transaction_id)
2321                .to_str()
2322                .expect("UTF-8 stage")
2323                .to_owned(),
2324            published_identity_sha256: stable_file_identity_sha256(&file)
2325                .expect("opening identity"),
2326        };
2327        fs::write(
2328            replacement.join(restore_authority_record_path(transaction_id)),
2329            serde_json::to_vec(&record).expect("authority record"),
2330        )
2331        .expect("B-only restore authority");
2332
2333        let plan = store
2334            .plan_capture_with_after_protocol_observation(|| {
2335                AmbientRootSwap::activate(&visible, &replacement)
2336            })
2337            .expect("capture opening root");
2338
2339        assert!(
2340            plan.entries()
2341                .iter()
2342                .all(|entry| entry.path() != "ordinary.md")
2343        );
2344        assert!(plan.exclusions().iter().any(|exclusion| {
2345            exclusion.path() == "ordinary.md" && exclusion.kind() == CaptureExclusionKind::HardLink
2346        }));
2347    }
2348}