Skip to main content

folderbase_core/
folderbase_seal.rs

1//! Durable, byte-verified Folderbase Version capture and device-local Head.
2//!
3//! Capture journals IDs before installing immutable records. The Folderbase
4//! Version remains the only full-state manifest; mutable object projections and
5//! Local Head are derived, recoverable local state.
6
7use std::{
8    collections::{BTreeMap, BTreeSet, VecDeque},
9    fs::{File, OpenOptions},
10    io::{Read, Write},
11    ops::Deref,
12    path::{Component, Path, PathBuf},
13};
14
15#[cfg(not(windows))]
16use cap_fs_ext::DirExt;
17use cap_fs_ext::{FollowSymlinks, OpenOptionsFollowExt};
18use cap_std::fs::{Dir, OpenOptions as CapOpenOptions};
19use chrono::{SecondsFormat, Utc};
20use serde::{Deserialize, Serialize};
21use sha2::{Digest, Sha256};
22use uuid::Uuid;
23
24use crate::{
25    FolderbaseError, FolderbaseRootAttestation,
26    change_set::{DeltaState, ObjectDelta},
27    folderbase_capture::{
28        CaptureEntryKind, CaptureExclusionKind, CaptureExclusionReason, CaptureLinkCommitment,
29        CaptureLocalHead, CaptureMetadataFingerprint, CapturePlan, CapturePlanEntry,
30        FolderbaseCaptureError, FolderbaseVersionStore, LocalHeadAuthority,
31        capture_entry_fingerprint, restore_authority_count, verify_capture_link_commitment,
32        version_derived_local_head_sha256,
33    },
34    folderbase_restore_authority::{
35        MAX_RESTORE_AUTHORITIES, MAX_RESTORE_AUTHORITY_BYTES, RESTORE_AUTHORITY_FORMAT_V1,
36        RestoreAuthorityRecord, restore_authority_record_path,
37    },
38    folderbase_state::FolderbaseState,
39    folderbase_version::{
40        DeletedKind, Exclusion, ExclusionKind, ExclusionReason, FolderbaseVersion,
41        FolderbaseVersionEntries, FolderbaseVersionParts, MAX_ENCODED_VERSION_BYTES, PathBinding,
42        PathBindingKind, RootManifest, Tombstone, validate_capture_path,
43        validate_capture_version_id,
44    },
45    local_versions::{
46        ContentDigest, LocalObjectRecord, LocalVersionRecord, LocalVersionStore, ObjectId,
47        ObjectLifecycle, ObjectProvenance, VersionId, safe_content_path,
48    },
49    root_attestation::{attest_folderbase_root, metadata_is_link_or_reparse},
50};
51
52#[cfg(test)]
53use crate::folderbase_restore_authority::RESTORE_AUTHORITY_FILENAME;
54
55const CAPTURE_TRANSACTION_FORMAT_V1: &str = "folderbase-capture-transaction-v1";
56const CAPTURE_TRANSACTIONS_DIRECTORY: &str = ".folderbase/transactions/folderbase-version-captures";
57const ACTIVE_CAPTURE_TRANSACTION_PATH: &str =
58    ".folderbase/transactions/folderbase-version-captures/active.json";
59const RESTORE_TRANSACTION_FORMAT_V1: &str = "folderbase-tombstone-restore-v1";
60const RESTORE_TRANSACTIONS_DIRECTORY: &str = ".folderbase/transactions/folderbase-version-restores";
61const ACTIVE_RESTORE_TRANSACTION_PATH: &str =
62    ".folderbase/transactions/folderbase-version-restores/active.json";
63const RESTORE_CLEANUP_RECOVERY_PATH: &str =
64    ".folderbase/transactions/folderbase-version-restores/cleanup.json";
65const RESTORE_CLEANUP_RECOVERY_FORMAT_V2: &str = "folderbase-restore-cleanup-v2";
66const RESTORE_COMPLETION_PATH: &str = ".folderbase/local/completed-restore.json";
67const RESTORE_COMPLETION_FORMAT_V2: &str = "folderbase-restore-completion-v2";
68const FOLDERBASE_VERSIONS_DIRECTORY: &str = ".folderbase/versions/folderbase";
69const CAPTURE_IDENTITIES_DIRECTORY: &str = ".folderbase/local/capture-identities";
70const LOCAL_HEAD_PATH: &str = ".folderbase/local/head.json";
71const RECONSTRUCTED_TOMBSTONE_ASSOCIATIONS_DIRECTORY: &str =
72    ".folderbase/local/root-reconstruction/tombstone-associations";
73const RECONSTRUCTED_TOMBSTONE_ASSOCIATION_FORMAT_V1: &str =
74    "folderbase-reconstructed-tombstone-association-v1";
75const IO_BUFFER_BYTES: usize = 64 * 1024;
76const MAX_CAPTURE_TRANSACTION_BYTES: u64 = MAX_ENCODED_VERSION_BYTES;
77
78/// Result of sealing or converging on one durable device-local Folderbase Version.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct SealedCapture {
81    version_id: String,
82    version_sha256: String,
83    created: bool,
84}
85
86/// Result of restoring the exact bytes named by one current-Head Tombstone.
87#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
88pub struct RestoredTombstone {
89    path: PathBuf,
90    object_id: String,
91    object_version_id: String,
92    version_id: String,
93    version_sha256: String,
94    created: bool,
95}
96
97#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
98#[serde(deny_unknown_fields)]
99pub(crate) struct ReconstructedTombstoneAssociation {
100    pub(crate) format: String,
101    pub(crate) path: String,
102    pub(crate) object_id: String,
103    pub(crate) object_version_id: String,
104    pub(crate) content_sha256: String,
105    pub(crate) bytes: u64,
106    pub(crate) executable: bool,
107}
108
109pub(crate) struct ReconstructedHistoryClosure {
110    pub(crate) object_versions: Vec<LocalVersionRecord>,
111    pub(crate) object_projections: Vec<LocalObjectRecord>,
112    pub(crate) tombstone_associations: Vec<ReconstructedTombstoneAssociation>,
113}
114
115impl ReconstructedTombstoneAssociation {
116    pub(crate) fn for_tombstone(
117        path: impl Into<String>,
118        object_id: impl Into<String>,
119        object_version_id: impl Into<String>,
120        content_sha256: impl Into<String>,
121        bytes: u64,
122        executable: bool,
123    ) -> Self {
124        Self {
125            format: RECONSTRUCTED_TOMBSTONE_ASSOCIATION_FORMAT_V1.to_owned(),
126            path: path.into(),
127            object_id: object_id.into(),
128            object_version_id: object_version_id.into(),
129            content_sha256: content_sha256.into(),
130            bytes,
131            executable,
132        }
133    }
134}
135
136impl RestoredTombstone {
137    pub fn path(&self) -> &Path {
138        &self.path
139    }
140
141    pub fn object_id(&self) -> &str {
142        &self.object_id
143    }
144
145    pub fn object_version_id(&self) -> &str {
146        &self.object_version_id
147    }
148
149    pub fn version_id(&self) -> &str {
150        &self.version_id
151    }
152
153    pub fn version_sha256(&self) -> &str {
154        &self.version_sha256
155    }
156
157    pub fn created(&self) -> bool {
158        self.created
159    }
160}
161
162impl SealedCapture {
163    pub fn version_id(&self) -> &str {
164        &self.version_id
165    }
166
167    pub fn version_sha256(&self) -> &str {
168        &self.version_sha256
169    }
170
171    /// Whether this call advanced Local Head to a newly sealed version.
172    pub fn created(&self) -> bool {
173        self.created
174    }
175}
176
177#[derive(Debug, Clone, PartialEq, Eq)]
178enum CaptureCheckpoint {
179    StateCapabilityOpen,
180    BeforeObjectBytesRead(String),
181    AfterObjectBytesRead(String),
182    JournalDurable,
183    ObjectWritesDurable,
184    VersionDurable,
185    HeadReplaced,
186    CleanupComplete,
187}
188
189#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
190enum RestoreCheckpoint {
191    JournalDurable,
192    StageDurable,
193    WorkspaceParentOpened,
194    WorkspaceLinkCreated,
195    TargetPublished,
196    VersionDurable,
197    HeadReplaced,
198    PublicationVerified,
199    ProjectionDurable,
200    CleanupRecoveryDurable,
201    BeforeStageRetirement,
202    AfterStageRetirement,
203    CleanupIntentRetired,
204    CompletionDurable,
205    CleanupComplete,
206    BeforeLegacyRootHeadRebind,
207    AfterLegacyRootHeadRebind,
208}
209
210#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
211#[serde(deny_unknown_fields)]
212struct JournalHead {
213    version_id: String,
214    version_sha256: String,
215    authority: LocalHeadAuthority,
216}
217
218impl From<&CaptureLocalHead> for JournalHead {
219    fn from(value: &CaptureLocalHead) -> Self {
220        Self {
221            version_id: value.version_id().to_owned(),
222            version_sha256: value.version_sha256().to_owned(),
223            authority: value.authority().clone(),
224        }
225    }
226}
227
228#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
229#[serde(deny_unknown_fields)]
230struct CaptureAssignment {
231    path: String,
232    kind: CaptureEntryKind,
233    object_id: String,
234    candidate_object_version_id: Option<String>,
235    prior_object_version_id: Option<String>,
236    reused_object: bool,
237    observed: CaptureMetadataFingerprint,
238    #[serde(
239        default,
240        skip_serializing_if = "CaptureLinkCommitment::is_legacy_default"
241    )]
242    link_commitment: CaptureLinkCommitment,
243}
244
245#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
246#[serde(deny_unknown_fields)]
247struct CaptureTransaction {
248    format: String,
249    transaction_id: String,
250    folderbase_id: String,
251    root_instance_sha256: String,
252    plan_sha256: String,
253    expected_head: Option<JournalHead>,
254    target_version_id: String,
255    created_at: String,
256    root_manifest_object_id: String,
257    root_manifest_candidate_version_id: String,
258    prior_root_manifest_version_id: Option<String>,
259    assignments: Vec<CaptureAssignment>,
260    #[serde(default, skip_serializing_if = "Vec::is_empty")]
261    target_tombstones: Vec<Tombstone>,
262}
263
264#[derive(Debug)]
265struct ActiveCaptureTransaction {
266    transaction: CaptureTransaction,
267    authority_sha256: String,
268    wire: CaptureTransactionWire,
269}
270
271impl Deref for ActiveCaptureTransaction {
272    type Target = CaptureTransaction;
273
274    fn deref(&self) -> &Self::Target {
275        &self.transaction
276    }
277}
278
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280enum CaptureTransactionWire {
281    Current,
282    ReleasedV1 { encoded_bytes: u64 },
283}
284
285#[derive(Debug, Serialize, Deserialize)]
286#[serde(deny_unknown_fields)]
287struct ReleasedV1JournalHead {
288    version_id: String,
289    version_sha256: String,
290    transaction_sha256: String,
291}
292
293#[derive(Debug, Deserialize)]
294#[serde(deny_unknown_fields)]
295struct ReleasedV1CaptureAssignment {
296    path: String,
297    kind: CaptureEntryKind,
298    object_id: String,
299    candidate_object_version_id: Option<String>,
300    prior_object_version_id: Option<String>,
301    reused_object: bool,
302    observed: CaptureMetadataFingerprint,
303}
304
305impl From<ReleasedV1CaptureAssignment> for CaptureAssignment {
306    fn from(value: ReleasedV1CaptureAssignment) -> Self {
307        Self {
308            path: value.path,
309            kind: value.kind,
310            object_id: value.object_id,
311            candidate_object_version_id: value.candidate_object_version_id,
312            prior_object_version_id: value.prior_object_version_id,
313            reused_object: value.reused_object,
314            observed: value.observed,
315            link_commitment: CaptureLinkCommitment::default(),
316        }
317    }
318}
319
320#[derive(Debug, Deserialize)]
321#[serde(deny_unknown_fields)]
322struct ReleasedV1CaptureTransaction {
323    format: String,
324    transaction_id: String,
325    folderbase_id: String,
326    root_instance_sha256: String,
327    plan_sha256: String,
328    expected_head: Option<ReleasedV1JournalHead>,
329    target_version_id: String,
330    created_at: String,
331    root_manifest_object_id: String,
332    root_manifest_candidate_version_id: String,
333    prior_root_manifest_version_id: Option<String>,
334    assignments: Vec<ReleasedV1CaptureAssignment>,
335    #[serde(default)]
336    target_tombstones: Vec<Tombstone>,
337}
338
339impl From<ReleasedV1CaptureTransaction> for CaptureTransaction {
340    fn from(value: ReleasedV1CaptureTransaction) -> Self {
341        Self {
342            format: value.format,
343            transaction_id: value.transaction_id,
344            folderbase_id: value.folderbase_id,
345            root_instance_sha256: value.root_instance_sha256,
346            plan_sha256: value.plan_sha256,
347            expected_head: value.expected_head.map(|head| JournalHead {
348                version_id: head.version_id,
349                version_sha256: head.version_sha256,
350                authority: LocalHeadAuthority::CaptureTransactionV1 {
351                    sha256: head.transaction_sha256,
352                },
353            }),
354            target_version_id: value.target_version_id,
355            created_at: value.created_at,
356            root_manifest_object_id: value.root_manifest_object_id,
357            root_manifest_candidate_version_id: value.root_manifest_candidate_version_id,
358            prior_root_manifest_version_id: value.prior_root_manifest_version_id,
359            assignments: value.assignments.into_iter().map(Into::into).collect(),
360            target_tombstones: value.target_tombstones,
361        }
362    }
363}
364
365#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
366#[serde(deny_unknown_fields)]
367struct RestoreTransaction {
368    format: String,
369    transaction_id: String,
370    folderbase_id: String,
371    root_instance_sha256: String,
372    expected_head: JournalHead,
373    target_version_id: String,
374    target_version_sha256: String,
375    created_at: String,
376    path: String,
377    tombstone: Tombstone,
378    binding: PathBinding,
379}
380
381#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
382#[serde(rename_all = "snake_case")]
383enum RestoreCleanupDisposition {
384    Committed,
385    Modified,
386    CommittedModified,
387}
388
389#[derive(Debug, Clone, Copy, PartialEq, Eq)]
390enum RestoreCleanupOutcome {
391    Restored,
392    WorkspaceModified,
393}
394
395#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
396#[serde(deny_unknown_fields)]
397struct RestoreCleanupRecovery {
398    format: String,
399    disposition: RestoreCleanupDisposition,
400    transaction: RestoreTransaction,
401    published_identity_sha256: String,
402}
403
404#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
405#[serde(deny_unknown_fields)]
406struct RestoreCompletionReceipt {
407    format: String,
408    transaction: RestoreTransaction,
409    published_identity_sha256: String,
410}
411
412#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
413#[serde(deny_unknown_fields)]
414struct LocalHeadRecord {
415    format: String,
416    folderbase_id: String,
417    root_instance_sha256: String,
418    version_id: String,
419    version_sha256: String,
420    authority: LocalHeadAuthority,
421}
422
423#[derive(Debug, Deserialize)]
424#[serde(untagged)]
425enum LocalHeadRecordWire {
426    V2(LocalHeadRecordV2Wire),
427    V1(LocalHeadRecordV1Wire),
428}
429
430#[derive(Debug, Deserialize)]
431#[serde(deny_unknown_fields)]
432struct LocalHeadRecordV2Wire {
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 LocalHeadRecordV1Wire {
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
452#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
453#[serde(deny_unknown_fields)]
454struct CaptureIdentityRecord {
455    format: String,
456    object_id: String,
457    kind: CaptureEntryKind,
458    observed: CaptureMetadataFingerprint,
459}
460
461struct BuiltCapture {
462    version: FolderbaseVersion,
463    version_sha256: String,
464    regular_projections: Vec<LocalObjectRecord>,
465}
466
467impl FolderbaseVersionStore {
468    /// Verify every included byte, install immutable records append-only, and
469    /// advance this device's Local Head only after all references verify.
470    pub fn seal_capture(&self, plan: CapturePlan) -> Result<SealedCapture, FolderbaseCaptureError> {
471        self.seal_capture_with_hook(plan, |_| {})
472    }
473
474    /// Read one complete append-only Folderbase Version and verify every
475    /// referenced local Object Version and content blob.
476    pub fn read_version(
477        &self,
478        version_id: &str,
479    ) -> Result<FolderbaseVersion, FolderbaseCaptureError> {
480        let local = LocalVersionStore::open_read_only(&self.root_attestation.root)?;
481        let state = FolderbaseState::open_existing_read_only(&self.root_attestation.root)?;
482        read_and_verify_folderbase_version(self, &local, &state, version_id)
483    }
484
485    /// Restore the exact ordinary-file bytes named by a Tombstone in the
486    /// current verified Local Head.
487    ///
488    /// Restore is same-path and no-clobber. It creates one new full-state
489    /// Folderbase Version and advances Local Head only after the file and all
490    /// immutable references verify.
491    pub fn restore_tombstone(
492        &self,
493        portable_path: &str,
494    ) -> Result<RestoredTombstone, FolderbaseCaptureError> {
495        self.restore_tombstone_with_hook_and_authority_limit(
496            portable_path,
497            |_| {},
498            MAX_RESTORE_AUTHORITIES,
499        )
500    }
501
502    #[cfg(test)]
503    fn restore_tombstone_with_hook(
504        &self,
505        portable_path: &str,
506        checkpoint: impl FnMut(&RestoreCheckpoint),
507    ) -> Result<RestoredTombstone, FolderbaseCaptureError> {
508        self.restore_tombstone_with_hook_and_authority_limit(
509            portable_path,
510            checkpoint,
511            MAX_RESTORE_AUTHORITIES,
512        )
513    }
514
515    fn restore_tombstone_with_hook_and_authority_limit(
516        &self,
517        portable_path: &str,
518        mut checkpoint: impl FnMut(&RestoreCheckpoint),
519        maximum_restore_authorities: usize,
520    ) -> Result<RestoredTombstone, FolderbaseCaptureError> {
521        validate_capture_path(portable_path)?;
522        let path = safe_content_path(Path::new(portable_path))?;
523        let path_string = portable_path.to_owned();
524        verify_restore_root_instance(self)?;
525        let local = LocalVersionStore::open_read_only(&self.root_attestation.root)?;
526        let state = FolderbaseState::open_existing(&self.root_attestation.root)?;
527        let _lock = local.acquire_transaction_lock_in(&state)?;
528        verify_restore_root_instance(self)?;
529        state.verify_still_attached()?;
530        state.ensure_private_dir(Path::new(RESTORE_TRANSACTIONS_DIRECTORY))?;
531        state.ensure_private_dir(Path::new(FOLDERBASE_VERSIONS_DIRECTORY))?;
532        ensure_no_active_capture(&state)?;
533
534        let active = read_active_restore_transaction(&state)?;
535        if let Some(recovery) = read_restore_cleanup_recovery(&state)? {
536            if recovery.transaction.path != path_string {
537                return Err(FolderbaseCaptureError::ConflictingTransaction(
538                    "a different Tombstone restore cleanup is pending",
539                ));
540            }
541            if active
542                .as_ref()
543                .is_some_and(|active| active != &recovery.transaction)
544            {
545                return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
546                    "active restore and cleanup recovery name different transactions".to_owned(),
547                ));
548            }
549            return match recovery.disposition {
550                RestoreCleanupDisposition::Committed => finish_restore_cleanup_recovery(
551                    self,
552                    &local,
553                    &state,
554                    &recovery.transaction,
555                    &recovery.published_identity_sha256,
556                    &mut checkpoint,
557                ),
558                RestoreCleanupDisposition::Modified => {
559                    finish_modified_restore_cleanup_recovery(
560                        self,
561                        &local,
562                        &state,
563                        &recovery.transaction,
564                        &recovery.published_identity_sha256,
565                        &mut checkpoint,
566                    )?;
567                    Err(FolderbaseCaptureError::RestoreTargetOccupied(path))
568                }
569                RestoreCleanupDisposition::CommittedModified => {
570                    finish_committed_modified_restore_cleanup_recovery(
571                        self,
572                        &local,
573                        &state,
574                        &recovery.transaction,
575                        &recovery.published_identity_sha256,
576                        &mut checkpoint,
577                    )?;
578                    Err(FolderbaseCaptureError::RestoreTargetOccupied(path))
579                }
580            };
581        }
582        if active.is_none()
583            && let Some(completion) = read_restore_completion_receipt(&state)?
584            && completion.transaction.path == path_string
585            && let Some(restored) = completed_restore_result(
586                self,
587                &local,
588                &state,
589                &completion.transaction,
590                &completion.published_identity_sha256,
591            )?
592        {
593            checkpoint(&RestoreCheckpoint::BeforeLegacyRootHeadRebind);
594            rebind_legacy_root_local_head(self, &local, &state)?;
595            checkpoint(&RestoreCheckpoint::AfterLegacyRootHeadRebind);
596            verify_restore_success_linearization(
597                self,
598                &local,
599                &state,
600                &completion.transaction,
601                &completion.published_identity_sha256,
602            )?;
603            return Ok(restored);
604        }
605        if active.is_none() {
606            rebind_legacy_root_local_head(self, &local, &state)?;
607        }
608        let transaction = match active {
609            Some(transaction) => {
610                validate_restore_transaction(self, &transaction)?;
611                if transaction.path != path_string {
612                    return Err(FolderbaseCaptureError::ConflictingTransaction(
613                        "a different Tombstone restore is pending",
614                    ));
615                }
616                transaction
617            }
618            None => {
619                if !state.workspace_path_is_absent(&path)? {
620                    return Err(FolderbaseCaptureError::RestoreTargetOccupied(path));
621                }
622                if restore_authority_count(
623                    &self.root_attestation,
624                    &self.root_instance_authority,
625                    maximum_restore_authorities,
626                )? >= maximum_restore_authorities
627                {
628                    return Err(
629                        FolderbaseCaptureError::RestoreAuthorityMaintenanceRequired {
630                            maximum: maximum_restore_authorities,
631                        },
632                    );
633                }
634                let mut head =
635                    read_head_record(&state)?.ok_or(FolderbaseCaptureError::MissingLocalHead)?;
636                if head.folderbase_id != self.root_attestation.folderbase_id
637                    || self
638                        .root_instance_authority
639                        .admit(&head.root_instance_sha256)
640                        .is_none()
641                {
642                    return Err(FolderbaseCaptureError::InvalidLocalHead(
643                        "Local Head belongs to a different Folderbase Root".to_owned(),
644                    ));
645                }
646                let current =
647                    read_and_verify_folderbase_version(self, &local, &state, &head.version_id)?;
648                if current.canonical_digest()? != head.version_sha256 {
649                    return Err(FolderbaseCaptureError::InvalidLocalHead(
650                        "Local Head digest does not match its Folderbase Version".to_owned(),
651                    ));
652                }
653                let tombstone = current
654                    .tombstones()
655                    .iter()
656                    .find(|tombstone| tombstone.path() == path_string)
657                    .cloned()
658                    .ok_or_else(|| FolderbaseCaptureError::TombstoneNotFound(path.to_path_buf()))?;
659                if tombstone.deleted_kind() != DeletedKind::RegularFile {
660                    return Err(FolderbaseCaptureError::UnsupportedTombstoneKind(
661                        path.to_path_buf(),
662                    ));
663                }
664                let binding = find_restore_binding(self, &local, &state, &current, &tombstone)?;
665                let restore_authority_sha256 =
666                    local_head_authority_sha256(self, &head.version_id, &head.version_sha256)?;
667                let restore_authority = LocalHeadAuthority::VersionDerivedV1 {
668                    sha256: restore_authority_sha256,
669                };
670                if head.authority != restore_authority {
671                    let rebound = LocalHeadRecord {
672                        format: "folderbase-local-head-v2".to_owned(),
673                        authority: restore_authority,
674                        ..head.clone()
675                    };
676                    compare_and_swap_exact_local_head(&state, &head, &rebound)?;
677                    head = rebound;
678                }
679                let transaction =
680                    build_restore_transaction(self, &head, &current, tombstone, binding)?;
681                write_active_restore_transaction(&state, &transaction)?;
682                checkpoint(&RestoreCheckpoint::JournalDurable);
683                transaction
684            }
685        };
686
687        let result =
688            execute_restore_transaction(self, &local, &state, &transaction, &mut checkpoint);
689        if result.is_err() {
690            retire_modified_restore(self, &local, &state, &transaction, &mut checkpoint)?;
691        }
692        result
693    }
694
695    fn seal_capture_with_hook(
696        &self,
697        plan: CapturePlan,
698        checkpoint: impl FnMut(&CaptureCheckpoint),
699    ) -> Result<SealedCapture, FolderbaseCaptureError> {
700        self.seal_capture_with_hook_and_limits(
701            plan,
702            checkpoint,
703            MAX_CAPTURE_TRANSACTION_BYTES,
704            MAX_ENCODED_VERSION_BYTES,
705        )
706    }
707
708    fn seal_capture_with_hook_and_limits(
709        &self,
710        plan: CapturePlan,
711        mut checkpoint: impl FnMut(&CaptureCheckpoint),
712        maximum_transaction_bytes: u64,
713        maximum_version_bytes: u64,
714    ) -> Result<SealedCapture, FolderbaseCaptureError> {
715        if plan.root() != self.root_attestation.root
716            || plan.folderbase_id() != self.root_attestation.folderbase_id
717            || plan.root_instance_sha256() != self.root_attestation.root_instance_sha256
718        {
719            return Err(FolderbaseCaptureError::PlanStoreMismatch);
720        }
721
722        let local = LocalVersionStore::open_read_only(&self.root_attestation.root)?;
723        let state = FolderbaseState::open_existing(&self.root_attestation.root)?;
724        checkpoint(&CaptureCheckpoint::StateCapabilityOpen);
725
726        let current_plan = self.plan_capture()?;
727        ensure_same_plan(&plan, &current_plan)?;
728        state.verify_still_attached()?;
729
730        let _lock = local.acquire_transaction_lock_in(&state)?;
731        for relative in [
732            ".folderbase/objects",
733            ".folderbase/versions/records",
734            ".folderbase/versions/blobs/sha256",
735        ] {
736            state.ensure_private_dir(Path::new(relative))?;
737        }
738        state.ensure_private_dir(Path::new(CAPTURE_TRANSACTIONS_DIRECTORY))?;
739        state.ensure_private_dir(Path::new(RESTORE_TRANSACTIONS_DIRECTORY))?;
740        ensure_no_active_restore(&state)?;
741        state.ensure_private_dir(Path::new(FOLDERBASE_VERSIONS_DIRECTORY))?;
742        state.ensure_private_dir(Path::new(CAPTURE_IDENTITIES_DIRECTORY))?;
743        normalize_legacy_local_head(&state)?;
744        let mut active = read_active_transaction_with_limit(&state, maximum_transaction_bytes)?;
745
746        let current_plan = self.plan_capture()?;
747        ensure_same_plan(&plan, &current_plan)?;
748        let mut plan_sha256 = capture_plan_sha256(&plan)?;
749        let current_head = current_plan.current_local_head().map(JournalHead::from);
750
751        if let Some(transaction) = active.as_ref() {
752            validate_transaction(self, transaction)?;
753            let admitted_root = self
754                .root_instance_authority
755                .admit(&transaction.root_instance_sha256)
756                .ok_or_else(|| {
757                    FolderbaseCaptureError::InvalidCaptureTransaction(
758                        "active journal is bound to another physical Folderbase Root".to_owned(),
759                    )
760                })?;
761            plan_sha256 =
762                capture_plan_sha256_with_root_instance(&plan, admitted_root.recorded_sha256())?;
763            let target_head = current_head
764                .as_ref()
765                .filter(|head| head.version_id == transaction.target_version_id);
766            if let Some(head) = target_head {
767                if head.authority
768                    != (LocalHeadAuthority::CaptureTransactionV1 {
769                        sha256: transaction.authority_sha256.clone(),
770                    })
771                {
772                    return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
773                        "active journal digest does not match Local Head".to_owned(),
774                    ));
775                }
776                let version = read_and_verify_folderbase_version(
777                    self,
778                    &local,
779                    &state,
780                    &transaction.target_version_id,
781                )?;
782                if version.canonical_digest()? != head.version_sha256 {
783                    return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
784                        "Local Head target digest does not match its complete Folderbase Version"
785                            .to_owned(),
786                    ));
787                }
788                let transaction_prior = load_transaction_prior(
789                    self,
790                    &local,
791                    &state,
792                    transaction.expected_head.as_ref(),
793                )?;
794                validate_committed_transaction(transaction, &version, transaction_prior.as_ref())?;
795                finish_committed_transaction(self, &local, &state, transaction)?;
796                remove_active_transaction(&state)?;
797                rebind_legacy_root_local_head(self, &local, &state)?;
798                checkpoint(&CaptureCheckpoint::CleanupComplete);
799                active = None;
800            } else if transaction.expected_head != current_head {
801                return Err(FolderbaseCaptureError::LocalHeadChanged);
802            } else if transaction.plan_sha256 != plan_sha256 {
803                let prior = load_prior_head(self, &local, &state, plan.current_local_head())?;
804                ensure_prior_bindings_observable(&plan, prior.as_ref())?;
805                // The old Head still owns authority. Immutable records already
806                // installed by the abandoned attempt remain safe orphans;
807                // removing only the active intent permits a fresh assignment.
808                remove_active_transaction(&state)?;
809                active = None;
810            }
811        }
812        if active.is_none() {
813            plan_sha256 = capture_plan_sha256(&plan)?;
814        }
815
816        let prior = load_prior_head(self, &local, &state, plan.current_local_head())?;
817        ensure_prior_bindings_observable(&plan, prior.as_ref())?;
818        if active.is_none()
819            && live_state_matches_prior(
820                self,
821                &plan,
822                &local,
823                &state,
824                prior.as_ref(),
825                &mut checkpoint,
826            )?
827        {
828            rebind_legacy_root_local_head(self, &local, &state)?;
829            let head = plan
830                .current_local_head()
831                .expect("matched prior requires Head");
832            return Ok(SealedCapture {
833                version_id: head.version_id().to_owned(),
834                version_sha256: head.version_sha256().to_owned(),
835                created: false,
836            });
837        }
838
839        let transaction = match active {
840            Some(transaction) => transaction,
841            None => {
842                let transaction = assign_capture_transaction(&plan, &plan_sha256, prior.as_ref())?;
843                preflight_capture_envelopes(
844                    &plan,
845                    &transaction,
846                    CaptureTransactionWire::Current,
847                    maximum_transaction_bytes,
848                    maximum_version_bytes,
849                )?;
850                let authority_sha256 = write_active_transaction_with_limit(
851                    &state,
852                    &transaction,
853                    maximum_transaction_bytes,
854                )?;
855                checkpoint(&CaptureCheckpoint::JournalDurable);
856                ActiveCaptureTransaction {
857                    transaction,
858                    authority_sha256,
859                    wire: CaptureTransactionWire::Current,
860                }
861            }
862        };
863
864        if transaction.plan_sha256 != plan_sha256
865            || transaction.expected_head != plan.current_local_head().map(JournalHead::from)
866        {
867            return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
868                "active intent does not match the approved CapturePlan".to_owned(),
869            ));
870        }
871        validate_transaction_against_plan(&plan, &transaction, prior.as_ref())?;
872        preflight_capture_envelopes(
873            &plan,
874            &transaction,
875            transaction.wire,
876            maximum_transaction_bytes,
877            maximum_version_bytes,
878        )?;
879
880        let built = build_and_install_capture(
881            self,
882            &plan,
883            &local,
884            &state,
885            &transaction,
886            prior.as_ref(),
887            &mut checkpoint,
888        )?;
889        checkpoint(&CaptureCheckpoint::ObjectWritesDurable);
890        install_folderbase_version(&state, &built.version, &built.version_sha256)?;
891        let installed =
892            read_and_verify_folderbase_version(self, &local, &state, built.version.version_id())?;
893        if installed.canonical_digest()? != built.version_sha256 {
894            return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
895                "installed Folderbase Version digest changed".to_owned(),
896            ));
897        }
898        checkpoint(&CaptureCheckpoint::VersionDurable);
899
900        let final_plan = self.plan_capture()?;
901        ensure_same_plan(&plan, &final_plan)?;
902        compare_and_swap_local_head(
903            &state,
904            plan.current_local_head(),
905            &LocalHeadRecord {
906                format: "folderbase-local-head-v2".to_owned(),
907                folderbase_id: self.root_attestation.folderbase_id.clone(),
908                root_instance_sha256: self.root_attestation.root_instance_sha256.clone(),
909                version_id: built.version.version_id().to_owned(),
910                version_sha256: built.version_sha256.clone(),
911                authority: LocalHeadAuthority::CaptureTransactionV1 {
912                    sha256: transaction.authority_sha256.clone(),
913                },
914            },
915        )?;
916        checkpoint(&CaptureCheckpoint::HeadReplaced);
917
918        for projection in &built.regular_projections {
919            local.write_capture_object_projection_in(&state, projection)?;
920        }
921        write_capture_identities(&state, &transaction)?;
922        remove_active_transaction(&state)?;
923        checkpoint(&CaptureCheckpoint::CleanupComplete);
924
925        Ok(SealedCapture {
926            version_id: built.version.version_id().to_owned(),
927            version_sha256: built.version_sha256,
928            created: true,
929        })
930    }
931}
932
933impl FolderbaseVersionStore {
934    /// Replace an intermediate capture Head with the real proposal/merge
935    /// history proved by one scoped Change Set.
936    ///
937    /// The intermediate capture installs all verified Object Version records.
938    /// This method then constructs a proposal from the trusted projection base
939    /// and, when concurrent disjoint work existed, a two-parent merge whose
940    /// content is the already-verified final capture.
941    pub(crate) fn finalize_change_set_history(
942        &self,
943        base_version_id: &str,
944        final_capture_version_id: &str,
945        created_at: &str,
946        change_set_sha256: &str,
947        deltas: &[ObjectDelta],
948    ) -> Result<SealedCapture, FolderbaseCaptureError> {
949        let local = LocalVersionStore::open_read_only(&self.root_attestation.root)?;
950        let state = FolderbaseState::open_existing(&self.root_attestation.root)?;
951        let _lock = local.acquire_transaction_lock_in(&state)?;
952        ensure_no_active_capture(&state)?;
953        ensure_no_active_restore(&state)?;
954
955        // Assessment already verified the base and seal_capture already
956        // verified the final capture, including every referenced byte. Under
957        // the same append-only store and transaction lease, history assembly
958        // needs only re-decode those immutable envelopes; rehashing a 10 GiB
959        // unchanged movie once per derived parent would add no authority.
960        let base = read_folderbase_version_envelope(&state, base_version_id)?;
961        let final_capture = read_folderbase_version_envelope(&state, final_capture_version_id)?;
962        let live_head =
963            read_head_record(&state)?.ok_or(FolderbaseCaptureError::MissingLocalHead)?;
964
965        let current_version_id = deterministic_change_set_version_id(change_set_sha256, "current");
966        let proposal_version_id =
967            deterministic_change_set_version_id(change_set_sha256, "proposal");
968        let merge_version_id = deterministic_change_set_version_id(change_set_sha256, "merge");
969        if [proposal_version_id.as_str(), merge_version_id.as_str()]
970            .contains(&live_head.version_id.as_str())
971        {
972            let installed = read_folderbase_version_envelope(&state, &live_head.version_id)?;
973            let installed_sha256 = installed.canonical_digest()?;
974            if installed_sha256 != live_head.version_sha256 {
975                return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
976                    "installed Change Set history differs from Local Head".to_owned(),
977                ));
978            }
979            return Ok(SealedCapture {
980                version_id: live_head.version_id,
981                version_sha256: installed_sha256,
982                created: false,
983            });
984        }
985        if live_head.version_id != final_capture.version_id()
986            || live_head.version_sha256 != final_capture.canonical_digest()?
987        {
988            return Err(FolderbaseCaptureError::LocalHeadChanged);
989        }
990
991        let current = build_change_set_current(
992            &base,
993            &final_capture,
994            &current_version_id,
995            final_capture.created_at(),
996            deltas,
997        )?;
998        if let Some(current) = &current {
999            let current_sha256 = current.canonical_digest()?;
1000            install_folderbase_version(&state, current, &current_sha256)?;
1001            let installed = read_folderbase_version_envelope(&state, current.version_id())?;
1002            if installed.canonical_digest()? != current_sha256 {
1003                return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
1004                    "installed pre-apply Change Set Version changed".to_owned(),
1005                ));
1006            }
1007        }
1008
1009        install_change_set_object_versions(&local, &state, &final_capture, created_at, deltas)?;
1010
1011        let proposal = build_change_set_proposal(
1012            &base,
1013            &final_capture,
1014            &proposal_version_id,
1015            created_at,
1016            deltas,
1017        )?;
1018        let proposal_sha256 = proposal.canonical_digest()?;
1019        install_folderbase_version(&state, &proposal, &proposal_sha256)?;
1020        let installed = read_folderbase_version_envelope(&state, proposal.version_id())?;
1021        if installed.canonical_digest()? != proposal_sha256 {
1022            return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
1023                "installed Change Set proposal Version changed".to_owned(),
1024            ));
1025        }
1026
1027        let target = match current.as_ref() {
1028            None => proposal,
1029            Some(current) => build_change_set_merge(
1030                current,
1031                &proposal,
1032                &final_capture,
1033                &merge_version_id,
1034                final_capture.created_at(),
1035                deltas,
1036            )?,
1037        };
1038        let target_sha256 = target.canonical_digest()?;
1039        install_folderbase_version(&state, &target, &target_sha256)?;
1040        let installed = read_folderbase_version_envelope(&state, target.version_id())?;
1041        if installed.canonical_digest()? != target_sha256 {
1042            return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
1043                "installed Change Set merge Version changed".to_owned(),
1044            ));
1045        }
1046
1047        let target_head = LocalHeadRecord {
1048            format: "folderbase-local-head-v2".to_owned(),
1049            folderbase_id: self.root_attestation.folderbase_id.clone(),
1050            root_instance_sha256: self.root_attestation.root_instance_sha256.clone(),
1051            version_id: target.version_id().to_owned(),
1052            version_sha256: target_sha256.clone(),
1053            authority: LocalHeadAuthority::VersionDerivedV1 {
1054                sha256: version_derived_local_head_sha256(
1055                    &self.root_attestation.folderbase_id,
1056                    &self.root_attestation.root_instance_sha256,
1057                    target.version_id(),
1058                    &target_sha256,
1059                )?,
1060            },
1061        };
1062        state.replace(Path::new(LOCAL_HEAD_PATH), &json_bytes(&target_head)?)?;
1063        if read_head_record(&state)?.as_ref() != Some(&target_head) {
1064            return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
1065                "Change Set history Head replacement did not verify".to_owned(),
1066            ));
1067        }
1068        Ok(SealedCapture {
1069            version_id: target.version_id().to_owned(),
1070            version_sha256: target_sha256,
1071            created: true,
1072        })
1073    }
1074}
1075
1076fn install_change_set_object_versions(
1077    local: &LocalVersionStore,
1078    state: &FolderbaseState,
1079    final_capture: &FolderbaseVersion,
1080    created_at: &str,
1081    deltas: &[ObjectDelta],
1082) -> Result<(), FolderbaseCaptureError> {
1083    for delta in deltas {
1084        let Some(after) = &delta.after else {
1085            continue;
1086        };
1087        let (desired_version_id, content) = match after {
1088            DeltaState::Directory(_) => continue,
1089            DeltaState::RegularFile(value) => (
1090                value.object_version_id.as_str(),
1091                ContentDigest {
1092                    algorithm: "sha256".to_owned(),
1093                    digest: value.content_sha256.clone(),
1094                    bytes: value.bytes,
1095                },
1096            ),
1097            DeltaState::Symlink(value) => (
1098                value.object_version_id.as_str(),
1099                content_digest(value.target.as_bytes()),
1100            ),
1101        };
1102        let final_binding = final_capture.lookup_binding(after.path()).ok_or_else(|| {
1103            FolderbaseCaptureError::InvalidCaptureTransaction(format!(
1104                "final capture omitted Change Set path {}",
1105                after.path()
1106            ))
1107        })?;
1108        if final_binding.object_id() != delta.object_id {
1109            return Err(FolderbaseCaptureError::InvalidCaptureTransaction(format!(
1110                "final capture changed Change Set Object identity at {}",
1111                after.path()
1112            )));
1113        }
1114        if final_binding.object_version_id() == Some(desired_version_id) {
1115            continue;
1116        }
1117        let object_id = ObjectId::parse(delta.object_id.clone())?;
1118        let version_id = VersionId::parse(desired_version_id.to_owned())?;
1119        let record = LocalVersionRecord {
1120            id: version_id.clone(),
1121            object_id: object_id.clone(),
1122            content: content.clone(),
1123            captured_at: created_at.to_owned(),
1124            extensions: BTreeMap::new(),
1125        };
1126        local.install_or_verify_version_record_in(state, &record)?;
1127        let mut projection = local
1128            .read_capture_object_projection_in(state, &object_id)?
1129            .ok_or_else(|| {
1130                FolderbaseCaptureError::InvalidCaptureTransaction(format!(
1131                    "final capture omitted Object projection {}",
1132                    delta.object_id
1133                ))
1134            })?;
1135        if !projection.versions.contains(&version_id) {
1136            projection.versions.push(version_id.clone());
1137        }
1138        projection.current_version = version_id.clone();
1139        projection.path = after.path().to_owned();
1140        local.write_capture_object_projection_in(state, &projection)?;
1141        local.verify_capture_object_version_in(state, &object_id, &version_id, &content)?;
1142    }
1143    Ok(())
1144}
1145
1146fn read_folderbase_version_envelope(
1147    state: &FolderbaseState,
1148    version_id: &str,
1149) -> Result<FolderbaseVersion, FolderbaseCaptureError> {
1150    validate_capture_version_id(version_id)?;
1151    let relative = folderbase_version_relative_path(version_id);
1152    let encoded = state
1153        .read_bounded(&relative, MAX_ENCODED_VERSION_BYTES)?
1154        .ok_or_else(|| {
1155            FolderbaseCaptureError::InvalidCaptureTransaction(format!(
1156                "Folderbase Version envelope is missing: {version_id}"
1157            ))
1158        })?;
1159    let version = FolderbaseVersion::decode_bounded(encoded.as_slice())?;
1160    if version.version_id() != version_id {
1161        return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
1162            "Folderbase Version envelope ID differs from its append-only path".to_owned(),
1163        ));
1164    }
1165    Ok(version)
1166}
1167
1168fn build_change_set_current(
1169    base: &FolderbaseVersion,
1170    final_capture: &FolderbaseVersion,
1171    version_id: &str,
1172    created_at: &str,
1173    deltas: &[ObjectDelta],
1174) -> Result<Option<FolderbaseVersion>, FolderbaseCaptureError> {
1175    let mut bindings = final_capture
1176        .bindings()
1177        .iter()
1178        .cloned()
1179        .map(|binding| (binding.object_id().to_owned(), binding))
1180        .collect::<BTreeMap<_, _>>();
1181    let base_bindings = base
1182        .bindings()
1183        .iter()
1184        .map(|binding| (binding.object_id(), binding))
1185        .collect::<BTreeMap<_, _>>();
1186    let mut tombstones = final_capture
1187        .tombstones()
1188        .iter()
1189        .cloned()
1190        .map(|tombstone| (tombstone.path().to_owned(), tombstone))
1191        .collect::<BTreeMap<_, _>>();
1192    for delta in deltas {
1193        if delta.after.is_some() && bindings.remove(&delta.object_id).is_none() {
1194            return Err(FolderbaseCaptureError::InvalidCaptureTransaction(format!(
1195                "final capture omitted Change Set Object {}",
1196                delta.object_id
1197            )));
1198        }
1199        if let Some(before) = &delta.before {
1200            let binding = base_bindings.get(delta.object_id.as_str()).ok_or_else(|| {
1201                FolderbaseCaptureError::InvalidCaptureTransaction(format!(
1202                    "projection base omitted Change Set Object {}",
1203                    delta.object_id
1204                ))
1205            })?;
1206            bindings.insert(delta.object_id.clone(), (*binding).clone());
1207            tombstones.remove(before.path());
1208        }
1209    }
1210    let mut bindings = bindings.into_values().collect::<Vec<_>>();
1211    bindings.sort_by(|left, right| left.path().as_bytes().cmp(right.path().as_bytes()));
1212    let tombstones = tombstones.into_values().collect::<Vec<_>>();
1213    if bindings == base.bindings()
1214        && tombstones == base.tombstones()
1215        && final_capture.exclusions() == base.exclusions()
1216        && final_capture.root_manifest() == base.root_manifest()
1217    {
1218        return Ok(None);
1219    }
1220    let entries = FolderbaseVersionEntries::from_verified_producer(
1221        bindings,
1222        tombstones,
1223        final_capture.exclusions().to_vec(),
1224    );
1225    Ok(Some(FolderbaseVersion::from_verified_parts(
1226        FolderbaseVersionParts::portable_v1_for_protocol_from_verified_producer(
1227            final_capture.protocol_version(),
1228            final_capture.folderbase_id(),
1229            version_id.to_owned(),
1230            vec![base.version_id().to_owned()],
1231            created_at,
1232            final_capture.root_manifest().clone(),
1233            entries,
1234        ),
1235    )?))
1236}
1237
1238fn build_change_set_proposal(
1239    base: &FolderbaseVersion,
1240    final_capture: &FolderbaseVersion,
1241    version_id: &str,
1242    created_at: &str,
1243    deltas: &[ObjectDelta],
1244) -> Result<FolderbaseVersion, FolderbaseCaptureError> {
1245    let mut bindings = base
1246        .bindings()
1247        .iter()
1248        .cloned()
1249        .map(|binding| (binding.object_id().to_owned(), binding))
1250        .collect::<BTreeMap<_, _>>();
1251    let mut tombstones = base
1252        .tombstones()
1253        .iter()
1254        .cloned()
1255        .map(|tombstone| (tombstone.path().to_owned(), tombstone))
1256        .collect::<BTreeMap<_, _>>();
1257    for delta in deltas {
1258        if delta.before.is_some() && bindings.remove(&delta.object_id).is_none() {
1259            return Err(FolderbaseCaptureError::InvalidCaptureTransaction(format!(
1260                "Change Set proposal base omitted Object {}",
1261                delta.object_id
1262            )));
1263        }
1264        match &delta.after {
1265            Some(after) => {
1266                let final_binding =
1267                    final_capture.lookup_binding(after.path()).ok_or_else(|| {
1268                        FolderbaseCaptureError::InvalidCaptureTransaction(format!(
1269                            "final capture omitted Change Set path {}",
1270                            after.path()
1271                        ))
1272                    })?;
1273                if final_binding.object_id() != delta.object_id {
1274                    return Err(FolderbaseCaptureError::InvalidCaptureTransaction(format!(
1275                        "final capture changed Change Set Object identity at {}",
1276                        after.path()
1277                    )));
1278                }
1279                tombstones.retain(|_, tombstone| tombstone.object_id() != delta.object_id);
1280                let binding = match after {
1281                    DeltaState::Directory(value) => PathBinding::directory_from_verified_producer(
1282                        value.path.clone(),
1283                        delta.object_id.clone(),
1284                    ),
1285                    DeltaState::RegularFile(value) => {
1286                        PathBinding::regular_file_from_verified_producer(
1287                            value.path.clone(),
1288                            delta.object_id.clone(),
1289                            value.object_version_id.clone(),
1290                            value.content_sha256.clone(),
1291                            value.bytes,
1292                            value.executable,
1293                        )
1294                    }
1295                    DeltaState::Symlink(value) => PathBinding::symlink_from_verified_producer(
1296                        value.path.clone(),
1297                        delta.object_id.clone(),
1298                        value.object_version_id.clone(),
1299                        value.target.clone(),
1300                    ),
1301                };
1302                bindings.insert(delta.object_id.clone(), binding);
1303            }
1304            None => {
1305                let before = delta.before.as_ref().expect("validated delete delta");
1306                let (deleted_kind, last_object_version_id) = match before {
1307                    DeltaState::Directory(_) => (DeletedKind::Directory, None),
1308                    DeltaState::RegularFile(value) => (
1309                        DeletedKind::RegularFile,
1310                        Some(value.object_version_id.clone()),
1311                    ),
1312                    DeltaState::Symlink(value) => {
1313                        (DeletedKind::Symlink, Some(value.object_version_id.clone()))
1314                    }
1315                };
1316                tombstones.insert(
1317                    before.path().to_owned(),
1318                    Tombstone::from_verified_producer(
1319                        before.path(),
1320                        delta.object_id.clone(),
1321                        deleted_kind,
1322                        last_object_version_id,
1323                    ),
1324                );
1325            }
1326        }
1327    }
1328    let mut bindings = bindings.into_values().collect::<Vec<_>>();
1329    bindings.sort_by(|left, right| left.path().as_bytes().cmp(right.path().as_bytes()));
1330    let entries = FolderbaseVersionEntries::from_verified_producer(
1331        bindings,
1332        tombstones.into_values().collect(),
1333        base.exclusions().to_vec(),
1334    );
1335    Ok(FolderbaseVersion::from_verified_parts(
1336        FolderbaseVersionParts::portable_v1_for_protocol_from_verified_producer(
1337            base.protocol_version(),
1338            base.folderbase_id(),
1339            version_id.to_owned(),
1340            vec![base.version_id().to_owned()],
1341            created_at,
1342            base.root_manifest().clone(),
1343            entries,
1344        ),
1345    )?)
1346}
1347
1348fn build_change_set_merge(
1349    current: &FolderbaseVersion,
1350    proposal: &FolderbaseVersion,
1351    final_capture: &FolderbaseVersion,
1352    version_id: &str,
1353    created_at: &str,
1354    deltas: &[ObjectDelta],
1355) -> Result<FolderbaseVersion, FolderbaseCaptureError> {
1356    let mut bindings = final_capture
1357        .bindings()
1358        .iter()
1359        .cloned()
1360        .map(|binding| (binding.object_id().to_owned(), binding))
1361        .collect::<BTreeMap<_, _>>();
1362    let proposal_bindings = proposal
1363        .bindings()
1364        .iter()
1365        .map(|binding| (binding.object_id(), binding))
1366        .collect::<BTreeMap<_, _>>();
1367    for delta in deltas {
1368        match &delta.after {
1369            Some(_) => {
1370                let binding = proposal_bindings
1371                    .get(delta.object_id.as_str())
1372                    .ok_or_else(|| {
1373                        FolderbaseCaptureError::InvalidCaptureTransaction(format!(
1374                            "proposal omitted Change Set Object {}",
1375                            delta.object_id
1376                        ))
1377                    })?;
1378                bindings.insert(delta.object_id.clone(), (*binding).clone());
1379            }
1380            None => {
1381                bindings.remove(&delta.object_id);
1382            }
1383        }
1384    }
1385    let mut bindings = bindings.into_values().collect::<Vec<_>>();
1386    bindings.sort_by(|left, right| left.path().as_bytes().cmp(right.path().as_bytes()));
1387    let entries = FolderbaseVersionEntries::from_verified_producer(
1388        bindings,
1389        final_capture.tombstones().to_vec(),
1390        final_capture.exclusions().to_vec(),
1391    );
1392    Ok(FolderbaseVersion::from_verified_parts(
1393        FolderbaseVersionParts::portable_v1_for_protocol_from_verified_producer(
1394            final_capture.protocol_version(),
1395            final_capture.folderbase_id(),
1396            version_id.to_owned(),
1397            vec![
1398                current.version_id().to_owned(),
1399                proposal.version_id().to_owned(),
1400            ],
1401            created_at,
1402            final_capture.root_manifest().clone(),
1403            entries,
1404        ),
1405    )?)
1406}
1407
1408fn deterministic_change_set_version_id(change_set_sha256: &str, role: &str) -> String {
1409    let mut hasher = Sha256::new();
1410    hasher.update(b"folderbase-change-set-history-v1\0");
1411    hasher.update(change_set_sha256.as_bytes());
1412    hasher.update(b"\0");
1413    hasher.update(role.as_bytes());
1414    let digest = hasher.finalize();
1415    let mut bytes = [0_u8; 16];
1416    bytes.copy_from_slice(&digest[..16]);
1417    bytes[6] = (bytes[6] & 0x0f) | 0x70;
1418    bytes[8] = (bytes[8] & 0x3f) | 0x80;
1419    format!("fbversion_{}", Uuid::from_bytes(bytes))
1420}
1421
1422fn build_restore_transaction(
1423    store: &FolderbaseVersionStore,
1424    head: &LocalHeadRecord,
1425    current: &FolderbaseVersion,
1426    tombstone: Tombstone,
1427    binding: PathBinding,
1428) -> Result<RestoreTransaction, FolderbaseCaptureError> {
1429    let (transaction_id, target_version_id, created_at) =
1430        assigned_restore_identity(store, head, current, &tombstone, &binding)?;
1431    let target = restored_version(
1432        store,
1433        current,
1434        &target_version_id,
1435        &created_at,
1436        &tombstone,
1437        &binding,
1438    )?;
1439    let transaction = RestoreTransaction {
1440        format: RESTORE_TRANSACTION_FORMAT_V1.to_owned(),
1441        transaction_id,
1442        folderbase_id: store.root_attestation.folderbase_id.clone(),
1443        root_instance_sha256: head.root_instance_sha256.clone(),
1444        expected_head: JournalHead::from(head),
1445        target_version_id,
1446        target_version_sha256: target.canonical_digest()?,
1447        created_at,
1448        path: tombstone.path().to_owned(),
1449        tombstone,
1450        binding,
1451    };
1452    validate_restore_transaction(store, &transaction)?;
1453    // Bound all serialized intent before any journal or workspace mutation.
1454    let _ = encode_restore_transaction(&transaction)?;
1455    Ok(transaction)
1456}
1457
1458fn assigned_restore_identity(
1459    store: &FolderbaseVersionStore,
1460    head: &LocalHeadRecord,
1461    current: &FolderbaseVersion,
1462    tombstone: &Tombstone,
1463    binding: &PathBinding,
1464) -> Result<(String, String, String), FolderbaseCaptureError> {
1465    #[derive(Serialize)]
1466    struct RestoreAuthority<'a> {
1467        format: &'static str,
1468        folderbase_id: &'a str,
1469        root_instance_sha256: &'a str,
1470        expected_head: JournalHead,
1471        tombstone: &'a Tombstone,
1472        binding: &'a PathBinding,
1473    }
1474
1475    let authority = serde_json::to_vec(&RestoreAuthority {
1476        format: "folderbase-tombstone-restore-authority-v1",
1477        folderbase_id: &store.root_attestation.folderbase_id,
1478        root_instance_sha256: &head.root_instance_sha256,
1479        expected_head: JournalHead::from(head),
1480        tombstone,
1481        binding,
1482    })
1483    .map_err(|source| {
1484        FolderbaseCaptureError::InvalidRestoreTransaction(format!(
1485            "restore authority encoding failed: {source}"
1486        ))
1487    })?;
1488    let assigned_uuid = |domain: &[u8]| {
1489        let mut digest = Sha256::new();
1490        digest.update(domain);
1491        digest.update(&authority);
1492        let digest = digest.finalize();
1493        let mut bytes = [0_u8; 16];
1494        bytes.copy_from_slice(&digest[..16]);
1495        bytes[6] = (bytes[6] & 0x0f) | 0x80;
1496        bytes[8] = (bytes[8] & 0x3f) | 0x80;
1497        Uuid::from_bytes(bytes).hyphenated().to_string()
1498    };
1499    Ok((
1500        format!("fbrestore_{}", assigned_uuid(b"transaction")),
1501        format!("fbversion_{}", assigned_uuid(b"version")),
1502        current.created_at().to_owned(),
1503    ))
1504}
1505
1506fn restored_version(
1507    store: &FolderbaseVersionStore,
1508    current: &FolderbaseVersion,
1509    target_version_id: &str,
1510    created_at: &str,
1511    tombstone: &Tombstone,
1512    binding: &PathBinding,
1513) -> Result<FolderbaseVersion, FolderbaseCaptureError> {
1514    if current.folderbase_id() != store.root_attestation.folderbase_id {
1515        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
1516            "restore parent belongs to a different Folderbase".to_owned(),
1517        ));
1518    }
1519    if current.protocol_version() != store.protocol_profile.folderbase_version_protocol() {
1520        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
1521            "capture a Folderbase Version for the active live-root protocol before restoring"
1522                .to_owned(),
1523        ));
1524    }
1525    let mut bindings = current.bindings().to_vec();
1526    bindings.push(binding.clone());
1527    bindings.sort_by(|left, right| left.path().as_bytes().cmp(right.path().as_bytes()));
1528    let tombstones = current
1529        .tombstones()
1530        .iter()
1531        .filter(|candidate| **candidate != *tombstone)
1532        .cloned()
1533        .collect();
1534    let entries = FolderbaseVersionEntries::from_verified_producer(
1535        bindings,
1536        tombstones,
1537        current.exclusions().to_vec(),
1538    );
1539    Ok(FolderbaseVersion::from_verified_parts(
1540        FolderbaseVersionParts::portable_v1_for_protocol_from_verified_producer(
1541            current.protocol_version(),
1542            store.root_attestation.folderbase_id.clone(),
1543            target_version_id.to_owned(),
1544            vec![current.version_id().to_owned()],
1545            created_at.to_owned(),
1546            current.root_manifest().clone(),
1547            entries,
1548        ),
1549    )?)
1550}
1551
1552fn find_restore_binding(
1553    store: &FolderbaseVersionStore,
1554    local: &LocalVersionStore,
1555    state: &FolderbaseState,
1556    current: &FolderbaseVersion,
1557    tombstone: &Tombstone,
1558) -> Result<PathBinding, FolderbaseCaptureError> {
1559    find_restore_binding_with_limit(
1560        store,
1561        local,
1562        state,
1563        current,
1564        tombstone,
1565        crate::folderbase_version::MAX_VERSION_ENTRIES,
1566    )
1567}
1568
1569fn find_restore_binding_with_limit(
1570    store: &FolderbaseVersionStore,
1571    local: &LocalVersionStore,
1572    state: &FolderbaseState,
1573    current: &FolderbaseVersion,
1574    tombstone: &Tombstone,
1575    maximum_ancestors: usize,
1576) -> Result<PathBinding, FolderbaseCaptureError> {
1577    let expected_version = tombstone.last_object_version_id().ok_or_else(|| {
1578        FolderbaseCaptureError::InvalidRestoreAncestry(
1579            "regular-file Tombstone omitted its Object Version".to_owned(),
1580        )
1581    })?;
1582    let mut queue = VecDeque::new();
1583    for parent in current.parents() {
1584        queue.push_back((parent.clone(), 1_usize));
1585    }
1586    let mut expanded = BTreeSet::new();
1587    let mut adjacency =
1588        BTreeMap::from([(current.version_id().to_owned(), current.parents().to_vec())]);
1589    let mut visited = 0_usize;
1590    let mut candidates = Vec::new();
1591    let mut candidate_depth = None;
1592    while let Some((version_id, depth)) = queue.pop_front() {
1593        if !expanded.insert(version_id.clone()) {
1594            continue;
1595        }
1596        visited += 1;
1597        if visited > maximum_ancestors {
1598            return Err(FolderbaseCaptureError::InvalidRestoreAncestry(
1599                "ancestor search exceeded the bounded version limit".to_owned(),
1600            ));
1601        }
1602        let version = read_and_verify_folderbase_version(store, local, state, &version_id)
1603            .map_err(|error| {
1604                FolderbaseCaptureError::InvalidRestoreAncestry(format!(
1605                    "ancestor {version_id} could not be verified: {error}"
1606                ))
1607            })?;
1608        adjacency.insert(version_id.clone(), version.parents().to_vec());
1609        if let Some(binding) = version.lookup_binding(tombstone.path())
1610            && binding.kind() == PathBindingKind::RegularFile
1611            && binding.object_id() == tombstone.object_id()
1612            && binding.object_version_id() == Some(expected_version)
1613            && candidate_depth.is_none_or(|candidate_depth| candidate_depth == depth)
1614        {
1615            candidate_depth.get_or_insert(depth);
1616            candidates.push(binding.clone());
1617        }
1618        for parent in version.parents() {
1619            queue.push_back((parent.clone(), depth + 1));
1620        }
1621    }
1622    ensure_restore_ancestry_acyclic(&adjacency)?;
1623    if !candidates.is_empty() {
1624        return unique_restore_candidate(candidates, tombstone);
1625    }
1626    if let Some(association) =
1627        read_reconstructed_tombstone_association(local, state, tombstone, expected_version)?
1628    {
1629        return Ok(PathBinding::regular_file_from_verified_producer(
1630            tombstone.path(),
1631            tombstone.object_id(),
1632            expected_version,
1633            association.content_sha256,
1634            association.bytes,
1635            association.executable,
1636        ));
1637    }
1638    Err(FolderbaseCaptureError::InvalidRestoreAncestry(format!(
1639        "no verified live ancestor preserves exact fidelity for {}",
1640        tombstone.path()
1641    )))
1642}
1643
1644fn ensure_restore_ancestry_acyclic(
1645    adjacency: &BTreeMap<String, Vec<String>>,
1646) -> Result<(), FolderbaseCaptureError> {
1647    let mut incoming = adjacency
1648        .keys()
1649        .map(|version_id| (version_id.clone(), 0_usize))
1650        .collect::<BTreeMap<_, _>>();
1651    for parents in adjacency.values() {
1652        for parent in parents {
1653            let Some(count) = incoming.get_mut(parent) else {
1654                return Err(FolderbaseCaptureError::InvalidRestoreAncestry(format!(
1655                    "ancestor graph omitted reachable version {parent}"
1656                )));
1657            };
1658            *count = count.saturating_add(1);
1659        }
1660    }
1661    let mut ready = incoming
1662        .iter()
1663        .filter_map(|(version_id, count)| (*count == 0).then_some(version_id.clone()))
1664        .collect::<VecDeque<_>>();
1665    let mut removed = 0_usize;
1666    while let Some(version_id) = ready.pop_front() {
1667        removed += 1;
1668        for parent in adjacency
1669            .get(&version_id)
1670            .expect("ready versions came from adjacency")
1671        {
1672            let count = incoming
1673                .get_mut(parent)
1674                .expect("all reachable parents are in adjacency");
1675            *count -= 1;
1676            if *count == 0 {
1677                ready.push_back(parent.clone());
1678            }
1679        }
1680    }
1681    if removed != adjacency.len() {
1682        return Err(FolderbaseCaptureError::InvalidRestoreAncestry(
1683            "ancestor graph contains a cycle".to_owned(),
1684        ));
1685    }
1686    Ok(())
1687}
1688
1689fn unique_restore_candidate(
1690    candidates: Vec<PathBinding>,
1691    tombstone: &Tombstone,
1692) -> Result<PathBinding, FolderbaseCaptureError> {
1693    let first = candidates
1694        .first()
1695        .expect("candidate set is known non-empty")
1696        .clone();
1697    if candidates.iter().any(|candidate| candidate != &first) {
1698        return Err(FolderbaseCaptureError::InvalidRestoreAncestry(format!(
1699            "nearest ancestors disagree about fidelity for {}",
1700            tombstone.path()
1701        )));
1702    }
1703    Ok(first)
1704}
1705
1706fn execute_restore_transaction(
1707    store: &FolderbaseVersionStore,
1708    local: &LocalVersionStore,
1709    state: &FolderbaseState,
1710    transaction: &RestoreTransaction,
1711    checkpoint: &mut impl FnMut(&RestoreCheckpoint),
1712) -> Result<RestoredTombstone, FolderbaseCaptureError> {
1713    verify_restore_root_instance(store)?;
1714    state.verify_still_attached()?;
1715    validate_restore_transaction(store, transaction)?;
1716    let current_head = read_head_record(state)?.ok_or(FolderbaseCaptureError::MissingLocalHead)?;
1717    if current_head.folderbase_id != store.root_attestation.folderbase_id
1718        || store
1719            .root_instance_authority
1720            .admit(&current_head.root_instance_sha256)
1721            .is_none()
1722    {
1723        return Err(FolderbaseCaptureError::InvalidLocalHead(
1724            "Local Head belongs to a different Folderbase Root".to_owned(),
1725        ));
1726    }
1727    let current_summary = JournalHead::from(&current_head);
1728    let target_summary = JournalHead {
1729        version_id: transaction.target_version_id.clone(),
1730        version_sha256: transaction.target_version_sha256.clone(),
1731        authority: LocalHeadAuthority::VersionDerivedV1 {
1732            sha256: restore_transaction_local_head_authority_sha256(
1733                transaction,
1734                &transaction.target_version_id,
1735                &transaction.target_version_sha256,
1736            )?,
1737        },
1738    };
1739    let target = derive_authoritative_restore_target(store, local, state, transaction)?;
1740    let created = if current_summary == target_summary {
1741        let installed = read_and_verify_folderbase_version(
1742            store,
1743            local,
1744            state,
1745            &transaction.target_version_id,
1746        )?;
1747        if installed.canonical_digest()? != transaction.target_version_sha256 {
1748            return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
1749                "committed target digest changed".to_owned(),
1750            ));
1751        }
1752        if let Err(error) =
1753            finish_restore_materialization(store, local, state, transaction, checkpoint)
1754        {
1755            rollback_restore_head(store, state, transaction)?;
1756            return Err(error);
1757        }
1758        false
1759    } else if current_summary == transaction.expected_head {
1760        stage_and_publish_restore(state, transaction, checkpoint)?;
1761        install_folderbase_version(state, &target, &transaction.target_version_sha256)?;
1762        let installed = read_and_verify_folderbase_version(
1763            store,
1764            local,
1765            state,
1766            &transaction.target_version_id,
1767        )?;
1768        if installed.canonical_digest()? != transaction.target_version_sha256 {
1769            return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
1770                "installed restore version failed verification".to_owned(),
1771            ));
1772        }
1773        checkpoint(&RestoreCheckpoint::VersionDurable);
1774        verify_restore_publication(store, state, transaction)?;
1775        compare_and_swap_restore_head(
1776            state,
1777            &transaction.expected_head,
1778            &LocalHeadRecord {
1779                format: "folderbase-local-head-v2".to_owned(),
1780                folderbase_id: transaction.folderbase_id.clone(),
1781                root_instance_sha256: transaction.root_instance_sha256.clone(),
1782                version_id: transaction.target_version_id.clone(),
1783                version_sha256: transaction.target_version_sha256.clone(),
1784                authority: LocalHeadAuthority::VersionDerivedV1 {
1785                    sha256: restore_transaction_local_head_authority_sha256(
1786                        transaction,
1787                        &transaction.target_version_id,
1788                        &transaction.target_version_sha256,
1789                    )?,
1790                },
1791            },
1792        )?;
1793        checkpoint(&RestoreCheckpoint::HeadReplaced);
1794        if let Err(error) = verify_restore_publication(store, state, transaction) {
1795            rollback_restore_head(store, state, transaction)?;
1796            return Err(error);
1797        }
1798        checkpoint(&RestoreCheckpoint::PublicationVerified);
1799        if let Err(error) = finish_restore_projection(store, local, state, transaction)
1800            .and_then(|()| verify_restore_publication(store, state, transaction))
1801        {
1802            rollback_restore_head(store, state, transaction)?;
1803            return Err(error);
1804        }
1805        checkpoint(&RestoreCheckpoint::ProjectionDurable);
1806        true
1807    } else {
1808        return Err(FolderbaseCaptureError::LocalHeadChanged);
1809    };
1810
1811    let published_identity_sha256 = state.workspace_restore_identity_sha256(
1812        &restore_stage_path(transaction),
1813        Path::new(&transaction.path),
1814    )?;
1815    if finish_restore_cleanup_with_identity(
1816        state,
1817        transaction,
1818        &published_identity_sha256,
1819        checkpoint,
1820    )? == RestoreCleanupOutcome::WorkspaceModified
1821    {
1822        return Err(FolderbaseCaptureError::RestoreTargetOccupied(
1823            PathBuf::from(&transaction.path),
1824        ));
1825    }
1826    checkpoint(&RestoreCheckpoint::CleanupComplete);
1827    verify_restore_success_linearization(
1828        store,
1829        local,
1830        state,
1831        transaction,
1832        &published_identity_sha256,
1833    )?;
1834    checkpoint(&RestoreCheckpoint::BeforeLegacyRootHeadRebind);
1835    rebind_legacy_root_local_head(store, local, state)?;
1836    checkpoint(&RestoreCheckpoint::AfterLegacyRootHeadRebind);
1837    verify_restore_success_linearization(
1838        store,
1839        local,
1840        state,
1841        transaction,
1842        &published_identity_sha256,
1843    )?;
1844    Ok(restored_tombstone(transaction, created))
1845}
1846
1847fn restored_tombstone(transaction: &RestoreTransaction, created: bool) -> RestoredTombstone {
1848    RestoredTombstone {
1849        path: PathBuf::from(&transaction.path),
1850        object_id: transaction.binding.object_id().to_owned(),
1851        object_version_id: transaction
1852            .binding
1853            .object_version_id()
1854            .expect("validated regular binding")
1855            .to_owned(),
1856        version_id: transaction.target_version_id.clone(),
1857        version_sha256: transaction.target_version_sha256.clone(),
1858        created,
1859    }
1860}
1861
1862fn finish_restore_cleanup_recovery(
1863    store: &FolderbaseVersionStore,
1864    local: &LocalVersionStore,
1865    state: &FolderbaseState,
1866    transaction: &RestoreTransaction,
1867    published_identity_sha256: &str,
1868    checkpoint: &mut impl FnMut(&RestoreCheckpoint),
1869) -> Result<RestoredTombstone, FolderbaseCaptureError> {
1870    validate_restore_transaction(store, transaction)?;
1871    let target = derive_authoritative_restore_target(store, local, state, transaction)?;
1872    if target.canonical_digest()? != transaction.target_version_sha256 {
1873        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
1874            "cleanup recovery target digest changed".to_owned(),
1875        ));
1876    }
1877    let target_head = JournalHead {
1878        version_id: transaction.target_version_id.clone(),
1879        version_sha256: transaction.target_version_sha256.clone(),
1880        authority: LocalHeadAuthority::VersionDerivedV1 {
1881            sha256: restore_transaction_local_head_authority_sha256(
1882                transaction,
1883                &transaction.target_version_id,
1884                &transaction.target_version_sha256,
1885            )?,
1886        },
1887    };
1888    let current_head = read_head_record(state)?.ok_or(FolderbaseCaptureError::MissingLocalHead)?;
1889    if JournalHead::from(&current_head) != target_head {
1890        return Err(FolderbaseCaptureError::LocalHeadChanged);
1891    }
1892    let installed =
1893        read_and_verify_folderbase_version(store, local, state, &transaction.target_version_id)?;
1894    if installed.canonical_digest()? != transaction.target_version_sha256 {
1895        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
1896            "cleanup recovery installed version changed".to_owned(),
1897        ));
1898    }
1899
1900    if finish_restore_cleanup_with_identity(
1901        state,
1902        transaction,
1903        published_identity_sha256,
1904        checkpoint,
1905    )? == RestoreCleanupOutcome::WorkspaceModified
1906    {
1907        return Err(FolderbaseCaptureError::RestoreTargetOccupied(
1908            PathBuf::from(&transaction.path),
1909        ));
1910    }
1911    checkpoint(&RestoreCheckpoint::CleanupComplete);
1912    verify_restore_success_linearization(
1913        store,
1914        local,
1915        state,
1916        transaction,
1917        published_identity_sha256,
1918    )?;
1919    checkpoint(&RestoreCheckpoint::BeforeLegacyRootHeadRebind);
1920    rebind_legacy_root_local_head(store, local, state)?;
1921    checkpoint(&RestoreCheckpoint::AfterLegacyRootHeadRebind);
1922    verify_restore_success_linearization(
1923        store,
1924        local,
1925        state,
1926        transaction,
1927        published_identity_sha256,
1928    )?;
1929    Ok(restored_tombstone(transaction, false))
1930}
1931
1932fn finish_restore_cleanup_with_identity(
1933    state: &FolderbaseState,
1934    transaction: &RestoreTransaction,
1935    published_identity_sha256: &str,
1936    checkpoint: &mut impl FnMut(&RestoreCheckpoint),
1937) -> Result<RestoreCleanupOutcome, FolderbaseCaptureError> {
1938    let committed = RestoreCleanupRecovery {
1939        format: RESTORE_CLEANUP_RECOVERY_FORMAT_V2.to_owned(),
1940        disposition: RestoreCleanupDisposition::Committed,
1941        transaction: transaction.clone(),
1942        published_identity_sha256: published_identity_sha256.to_owned(),
1943    };
1944    write_restore_cleanup_recovery(state, &committed)?;
1945    checkpoint(&RestoreCheckpoint::CleanupRecoveryDurable);
1946    let digest = transaction
1947        .binding
1948        .content_sha256()
1949        .expect("validated regular binding");
1950    let bytes = transaction
1951        .binding
1952        .bytes()
1953        .expect("validated regular binding");
1954    let executable = transaction
1955        .binding
1956        .executable()
1957        .expect("validated regular binding");
1958    let retirement = state.retain_workspace_restore_authority_with_hook(
1959        &restore_stage_path(transaction),
1960        Path::new(&transaction.path),
1961        published_identity_sha256,
1962        Some((digest, bytes, executable)),
1963        |stage_removed| {
1964            checkpoint(if stage_removed {
1965                &RestoreCheckpoint::AfterStageRetirement
1966            } else {
1967                &RestoreCheckpoint::BeforeStageRetirement
1968            });
1969        },
1970    );
1971    if let Err(error) = retirement {
1972        let modified_observation = state.workspace_restore_was_modified_in_place(
1973            &restore_stage_path(transaction),
1974            Path::new(&transaction.path),
1975            digest,
1976            bytes,
1977            executable,
1978        );
1979        if matches!(modified_observation, Ok(true)) {
1980            let modified = RestoreCleanupRecovery {
1981                format: RESTORE_CLEANUP_RECOVERY_FORMAT_V2.to_owned(),
1982                disposition: RestoreCleanupDisposition::CommittedModified,
1983                transaction: transaction.clone(),
1984                published_identity_sha256: published_identity_sha256.to_owned(),
1985            };
1986            replace_restore_cleanup_recovery(state, &committed, &modified)?;
1987            finish_committed_modified_restore_cleanup_recovery_stage(
1988                state,
1989                transaction,
1990                published_identity_sha256,
1991                checkpoint,
1992            )?;
1993            return Ok(RestoreCleanupOutcome::WorkspaceModified);
1994        }
1995        return Err(error.into());
1996    }
1997    write_restore_authority_record(state, transaction, published_identity_sha256)?;
1998    remove_active_restore_transaction(state)?;
1999    checkpoint(&RestoreCheckpoint::CleanupIntentRetired);
2000    write_restore_completion_receipt(state, transaction, published_identity_sha256)?;
2001    checkpoint(&RestoreCheckpoint::CompletionDurable);
2002    remove_restore_cleanup_recovery(state)?;
2003    Ok(RestoreCleanupOutcome::Restored)
2004}
2005
2006fn derive_authoritative_restore_target(
2007    store: &FolderbaseVersionStore,
2008    local: &LocalVersionStore,
2009    state: &FolderbaseState,
2010    transaction: &RestoreTransaction,
2011) -> Result<FolderbaseVersion, FolderbaseCaptureError> {
2012    let parent = read_and_verify_folderbase_version(
2013        store,
2014        local,
2015        state,
2016        &transaction.expected_head.version_id,
2017    )?;
2018    if parent.canonical_digest()? != transaction.expected_head.version_sha256 {
2019        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
2020            "restore parent digest changed".to_owned(),
2021        ));
2022    }
2023    if transaction.expected_head.authority
2024        != (LocalHeadAuthority::VersionDerivedV1 {
2025            sha256: restore_transaction_local_head_authority_sha256(
2026                transaction,
2027                &transaction.expected_head.version_id,
2028                &transaction.expected_head.version_sha256,
2029            )?,
2030        })
2031    {
2032        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
2033            "restore parent Head authority is not independently derivable".to_owned(),
2034        ));
2035    }
2036    let parent_tombstone = parent
2037        .tombstones()
2038        .iter()
2039        .find(|tombstone| tombstone.path() == transaction.path)
2040        .ok_or_else(|| {
2041            FolderbaseCaptureError::InvalidRestoreTransaction(
2042                "restore parent no longer contains the selected Tombstone".to_owned(),
2043            )
2044        })?;
2045    if parent_tombstone != &transaction.tombstone {
2046        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
2047            "restore journal Tombstone differs from the verified parent".to_owned(),
2048        ));
2049    }
2050    let authoritative = find_restore_binding(store, local, state, &parent, parent_tombstone)?;
2051    if authoritative != transaction.binding {
2052        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
2053            "restore journal fidelity differs from verified ancestry".to_owned(),
2054        ));
2055    }
2056    let parent_head = LocalHeadRecord {
2057        format: "folderbase-local-head-v2".to_owned(),
2058        folderbase_id: transaction.folderbase_id.clone(),
2059        root_instance_sha256: transaction.root_instance_sha256.clone(),
2060        version_id: transaction.expected_head.version_id.clone(),
2061        version_sha256: transaction.expected_head.version_sha256.clone(),
2062        authority: transaction.expected_head.authority.clone(),
2063    };
2064    let (transaction_id, target_version_id, created_at) = assigned_restore_identity(
2065        store,
2066        &parent_head,
2067        &parent,
2068        parent_tombstone,
2069        &authoritative,
2070    )?;
2071    if transaction.transaction_id != transaction_id
2072        || transaction.target_version_id != target_version_id
2073        || transaction.created_at != created_at
2074    {
2075        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
2076            "restore assignment differs from verified immutable authority".to_owned(),
2077        ));
2078    }
2079    let target = restored_version(
2080        store,
2081        &parent,
2082        &transaction.target_version_id,
2083        &transaction.created_at,
2084        &transaction.tombstone,
2085        &transaction.binding,
2086    )?;
2087    if target.canonical_digest()? != transaction.target_version_sha256 {
2088        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
2089            "restore target no longer matches its durable journal".to_owned(),
2090        ));
2091    }
2092    Ok(target)
2093}
2094
2095fn verify_restore_root_instance(
2096    store: &FolderbaseVersionStore,
2097) -> Result<(), FolderbaseCaptureError> {
2098    let observed = attest_folderbase_root(&store.root_attestation.root)
2099        .map_err(|_| FolderbaseCaptureError::PlanStoreMismatch)?;
2100    if observed.folderbase_id != store.root_attestation.folderbase_id
2101        || observed.protocol_version != store.root_attestation.protocol_version
2102        || observed.manifest_sha256 != store.root_attestation.manifest_sha256
2103        || observed.root_instance_sha256 != store.root_attestation.root_instance_sha256
2104    {
2105        return Err(FolderbaseCaptureError::PlanStoreMismatch);
2106    }
2107    Ok(())
2108}
2109
2110fn verify_restore_publication(
2111    store: &FolderbaseVersionStore,
2112    state: &FolderbaseState,
2113    transaction: &RestoreTransaction,
2114) -> Result<(), FolderbaseCaptureError> {
2115    verify_restore_root_instance(store)?;
2116    state.verify_still_attached()?;
2117    let digest = transaction
2118        .binding
2119        .content_sha256()
2120        .expect("validated regular binding");
2121    let bytes = transaction
2122        .binding
2123        .bytes()
2124        .expect("validated regular binding");
2125    let executable = transaction
2126        .binding
2127        .executable()
2128        .expect("validated regular binding");
2129    state
2130        .verify_workspace_restore(
2131            &restore_stage_path(transaction),
2132            Path::new(&transaction.path),
2133            digest,
2134            bytes,
2135            executable,
2136        )
2137        .map_err(|error| match error {
2138            FolderbaseError::WouldOverwrite(path) => {
2139                FolderbaseCaptureError::RestoreTargetOccupied(path)
2140            }
2141            error => FolderbaseCaptureError::LocalStore(error),
2142        })
2143}
2144
2145fn retire_modified_restore(
2146    store: &FolderbaseVersionStore,
2147    local: &LocalVersionStore,
2148    state: &FolderbaseState,
2149    transaction: &RestoreTransaction,
2150    checkpoint: &mut impl FnMut(&RestoreCheckpoint),
2151) -> Result<bool, FolderbaseCaptureError> {
2152    let digest = transaction
2153        .binding
2154        .content_sha256()
2155        .expect("validated regular binding");
2156    let bytes = transaction
2157        .binding
2158        .bytes()
2159        .expect("validated regular binding");
2160    let executable = transaction
2161        .binding
2162        .executable()
2163        .expect("validated regular binding");
2164    if !matches!(
2165        state.workspace_restore_was_modified_in_place(
2166            &restore_stage_path(transaction),
2167            Path::new(&transaction.path),
2168            digest,
2169            bytes,
2170            executable,
2171        ),
2172        Ok(true)
2173    ) {
2174        return Ok(false);
2175    }
2176    let Some(current_head) = read_head_record(state)? else {
2177        return Ok(false);
2178    };
2179    if JournalHead::from(&current_head) != transaction.expected_head {
2180        return Ok(false);
2181    }
2182
2183    let published_identity_sha256 = state.workspace_restore_identity_sha256(
2184        &restore_stage_path(transaction),
2185        Path::new(&transaction.path),
2186    )?;
2187    write_restore_cleanup_recovery(
2188        state,
2189        &RestoreCleanupRecovery {
2190            format: RESTORE_CLEANUP_RECOVERY_FORMAT_V2.to_owned(),
2191            disposition: RestoreCleanupDisposition::Modified,
2192            transaction: transaction.clone(),
2193            published_identity_sha256: published_identity_sha256.clone(),
2194        },
2195    )?;
2196    checkpoint(&RestoreCheckpoint::CleanupRecoveryDurable);
2197    finish_modified_restore_cleanup_recovery(
2198        store,
2199        local,
2200        state,
2201        transaction,
2202        &published_identity_sha256,
2203        checkpoint,
2204    )?;
2205    Ok(true)
2206}
2207
2208fn finish_modified_restore_cleanup_recovery(
2209    store: &FolderbaseVersionStore,
2210    local: &LocalVersionStore,
2211    state: &FolderbaseState,
2212    transaction: &RestoreTransaction,
2213    published_identity_sha256: &str,
2214    checkpoint: &mut impl FnMut(&RestoreCheckpoint),
2215) -> Result<(), FolderbaseCaptureError> {
2216    rederive_authoritative_modified_restore_transaction(store, local, state, transaction)?;
2217    state.retain_workspace_restore_authority_with_hook(
2218        &restore_stage_path(transaction),
2219        Path::new(&transaction.path),
2220        published_identity_sha256,
2221        None,
2222        |stage_removed| {
2223            checkpoint(if stage_removed {
2224                &RestoreCheckpoint::AfterStageRetirement
2225            } else {
2226                &RestoreCheckpoint::BeforeStageRetirement
2227            });
2228        },
2229    )?;
2230    write_restore_authority_record(state, transaction, published_identity_sha256)?;
2231    remove_active_restore_transaction(state)?;
2232    remove_restore_cleanup_recovery(state)?;
2233    rebind_legacy_root_local_head(store, local, state)
2234}
2235
2236fn finish_committed_modified_restore_cleanup_recovery(
2237    store: &FolderbaseVersionStore,
2238    local: &LocalVersionStore,
2239    state: &FolderbaseState,
2240    transaction: &RestoreTransaction,
2241    published_identity_sha256: &str,
2242    checkpoint: &mut impl FnMut(&RestoreCheckpoint),
2243) -> Result<(), FolderbaseCaptureError> {
2244    validate_restore_transaction(store, transaction)?;
2245    let target = derive_authoritative_restore_target(store, local, state, transaction)?;
2246    if target.canonical_digest()? != transaction.target_version_sha256 {
2247        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
2248            "committed-modified cleanup target digest changed".to_owned(),
2249        ));
2250    }
2251    let target_head = JournalHead {
2252        version_id: transaction.target_version_id.clone(),
2253        version_sha256: transaction.target_version_sha256.clone(),
2254        authority: LocalHeadAuthority::VersionDerivedV1 {
2255            sha256: restore_transaction_local_head_authority_sha256(
2256                transaction,
2257                &transaction.target_version_id,
2258                &transaction.target_version_sha256,
2259            )?,
2260        },
2261    };
2262    let current_head = read_head_record(state)?.ok_or(FolderbaseCaptureError::MissingLocalHead)?;
2263    if JournalHead::from(&current_head) != target_head {
2264        return Err(FolderbaseCaptureError::LocalHeadChanged);
2265    }
2266    let installed =
2267        read_and_verify_folderbase_version(store, local, state, &transaction.target_version_id)?;
2268    if installed.canonical_digest()? != transaction.target_version_sha256 {
2269        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
2270            "committed-modified cleanup installed version changed".to_owned(),
2271        ));
2272    }
2273    finish_committed_modified_restore_cleanup_recovery_stage(
2274        state,
2275        transaction,
2276        published_identity_sha256,
2277        checkpoint,
2278    )?;
2279    rebind_legacy_root_local_head(store, local, state)
2280}
2281
2282fn finish_committed_modified_restore_cleanup_recovery_stage(
2283    state: &FolderbaseState,
2284    transaction: &RestoreTransaction,
2285    published_identity_sha256: &str,
2286    checkpoint: &mut impl FnMut(&RestoreCheckpoint),
2287) -> Result<(), FolderbaseCaptureError> {
2288    state.retain_workspace_restore_authority_with_hook(
2289        &restore_stage_path(transaction),
2290        Path::new(&transaction.path),
2291        published_identity_sha256,
2292        None,
2293        |stage_removed| {
2294            checkpoint(if stage_removed {
2295                &RestoreCheckpoint::AfterStageRetirement
2296            } else {
2297                &RestoreCheckpoint::BeforeStageRetirement
2298            });
2299        },
2300    )?;
2301    write_restore_authority_record(state, transaction, published_identity_sha256)?;
2302    remove_active_restore_transaction(state)?;
2303    remove_restore_cleanup_recovery(state)
2304}
2305
2306fn rederive_authoritative_modified_restore_transaction(
2307    store: &FolderbaseVersionStore,
2308    local: &LocalVersionStore,
2309    state: &FolderbaseState,
2310    transaction: &RestoreTransaction,
2311) -> Result<(), FolderbaseCaptureError> {
2312    let current_head = read_head_record(state)?.ok_or(FolderbaseCaptureError::MissingLocalHead)?;
2313    if JournalHead::from(&current_head) != transaction.expected_head {
2314        return Err(FolderbaseCaptureError::LocalHeadChanged);
2315    }
2316    rederive_authoritative_restore_transaction(store, local, state, transaction)
2317}
2318
2319fn rederive_authoritative_restore_transaction(
2320    store: &FolderbaseVersionStore,
2321    local: &LocalVersionStore,
2322    state: &FolderbaseState,
2323    transaction: &RestoreTransaction,
2324) -> Result<(), FolderbaseCaptureError> {
2325    validate_restore_transaction(store, transaction)?;
2326    let current = read_and_verify_folderbase_version(
2327        store,
2328        local,
2329        state,
2330        &transaction.expected_head.version_id,
2331    )?;
2332    if current.canonical_digest()? != transaction.expected_head.version_sha256 {
2333        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
2334            "modified cleanup parent digest changed".to_owned(),
2335        ));
2336    }
2337    let tombstone = current
2338        .tombstones()
2339        .iter()
2340        .find(|candidate| candidate.path() == transaction.path)
2341        .cloned()
2342        .ok_or_else(|| {
2343            FolderbaseCaptureError::InvalidRestoreTransaction(
2344                "modified cleanup path is not a current Tombstone".to_owned(),
2345            )
2346        })?;
2347    let binding = find_restore_binding(store, local, state, &current, &tombstone)?;
2348    let authoritative = build_restore_transaction(
2349        store,
2350        &LocalHeadRecord {
2351            format: "folderbase-local-head-v2".to_owned(),
2352            folderbase_id: transaction.folderbase_id.clone(),
2353            root_instance_sha256: transaction.root_instance_sha256.clone(),
2354            version_id: transaction.expected_head.version_id.clone(),
2355            version_sha256: transaction.expected_head.version_sha256.clone(),
2356            authority: transaction.expected_head.authority.clone(),
2357        },
2358        &current,
2359        tombstone,
2360        binding,
2361    )?;
2362    if authoritative != *transaction {
2363        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
2364            "restore transaction does not match immutable restore authority".to_owned(),
2365        ));
2366    }
2367    Ok(())
2368}
2369
2370fn restore_target_head_for_root(
2371    transaction: &RestoreTransaction,
2372    root_instance_sha256: &str,
2373) -> Result<LocalHeadRecord, FolderbaseCaptureError> {
2374    Ok(LocalHeadRecord {
2375        format: "folderbase-local-head-v2".to_owned(),
2376        folderbase_id: transaction.folderbase_id.clone(),
2377        root_instance_sha256: root_instance_sha256.to_owned(),
2378        version_id: transaction.target_version_id.clone(),
2379        version_sha256: transaction.target_version_sha256.clone(),
2380        authority: LocalHeadAuthority::VersionDerivedV1 {
2381            sha256: version_derived_local_head_sha256(
2382                &transaction.folderbase_id,
2383                root_instance_sha256,
2384                &transaction.target_version_id,
2385                &transaction.target_version_sha256,
2386            )?,
2387        },
2388    })
2389}
2390
2391fn is_exact_restore_target_head(
2392    store: &FolderbaseVersionStore,
2393    transaction: &RestoreTransaction,
2394    current_head: &LocalHeadRecord,
2395) -> Result<bool, FolderbaseCaptureError> {
2396    let admission = store
2397        .root_instance_authority
2398        .admit(&transaction.root_instance_sha256)
2399        .ok_or_else(|| {
2400            FolderbaseCaptureError::InvalidRestoreTransaction(
2401                "restore transaction is bound to another physical Folderbase Root".to_owned(),
2402            )
2403        })?;
2404    let recorded = restore_target_head_for_root(transaction, admission.recorded_sha256())?;
2405    if current_head == &recorded {
2406        return Ok(true);
2407    }
2408    if !admission.is_legacy_v1() {
2409        return Ok(false);
2410    }
2411    let rebound =
2412        restore_target_head_for_root(transaction, store.root_instance_authority.current_sha256())?;
2413    Ok(current_head == &rebound)
2414}
2415
2416fn verify_restore_success_linearization(
2417    store: &FolderbaseVersionStore,
2418    local: &LocalVersionStore,
2419    state: &FolderbaseState,
2420    transaction: &RestoreTransaction,
2421    published_identity_sha256: &str,
2422) -> Result<(), FolderbaseCaptureError> {
2423    verify_restore_root_instance(store)?;
2424    state.verify_still_attached()?;
2425    validate_restore_transaction(store, transaction)?;
2426
2427    let target = derive_authoritative_restore_target(store, local, state, transaction)?;
2428    if target.canonical_digest()? != transaction.target_version_sha256 {
2429        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
2430            "final restore target digest changed".to_owned(),
2431        ));
2432    }
2433    let installed =
2434        read_and_verify_folderbase_version(store, local, state, &transaction.target_version_id)?;
2435    if installed.canonical_digest()? != transaction.target_version_sha256 {
2436        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
2437            "final installed restore Version changed".to_owned(),
2438        ));
2439    }
2440    let current_head = read_head_record(state)?.ok_or(FolderbaseCaptureError::MissingLocalHead)?;
2441    if !is_exact_restore_target_head(store, transaction, &current_head)? {
2442        return Err(FolderbaseCaptureError::LocalHeadChanged);
2443    }
2444
2445    let expected_completion = RestoreCompletionReceipt {
2446        format: RESTORE_COMPLETION_FORMAT_V2.to_owned(),
2447        transaction: transaction.clone(),
2448        published_identity_sha256: published_identity_sha256.to_owned(),
2449    };
2450    let expected_completion = encode_restore_completion_receipt(&expected_completion)?;
2451    if state
2452        .read_bounded(
2453            Path::new(RESTORE_COMPLETION_PATH),
2454            MAX_CAPTURE_TRANSACTION_BYTES,
2455        )?
2456        .as_deref()
2457        != Some(expected_completion.as_slice())
2458    {
2459        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
2460            "final restore completion receipt changed".to_owned(),
2461        ));
2462    }
2463    if state
2464        .read_bounded(
2465            Path::new(ACTIVE_RESTORE_TRANSACTION_PATH),
2466            MAX_CAPTURE_TRANSACTION_BYTES,
2467        )?
2468        .is_some()
2469        || state
2470            .read_bounded(
2471                Path::new(RESTORE_CLEANUP_RECOVERY_PATH),
2472                MAX_CAPTURE_TRANSACTION_BYTES,
2473            )?
2474            .is_some()
2475    {
2476        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
2477            "final restore still has mutable transaction state".to_owned(),
2478        ));
2479    }
2480
2481    let authority = restore_authority_record(transaction, published_identity_sha256);
2482    let expected_authority = encode_restore_authority_record(&authority)?;
2483    let authority_path = restore_authority_record_path(&transaction.transaction_id);
2484    if state
2485        .read_bounded(&authority_path, MAX_RESTORE_AUTHORITY_BYTES)?
2486        .as_deref()
2487        != Some(expected_authority.as_slice())
2488    {
2489        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
2490            "final restore authority path or exact bytes changed".to_owned(),
2491        ));
2492    }
2493
2494    let path = Path::new(&transaction.path);
2495    let retained_identity =
2496        state.workspace_restore_identity_sha256(&restore_stage_path(transaction), path)?;
2497    if retained_identity != published_identity_sha256 {
2498        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
2499            "final retained stage or destination identity changed".to_owned(),
2500        ));
2501    }
2502    state.verify_workspace_regular_file_identity_and_fidelity(
2503        path,
2504        published_identity_sha256,
2505        transaction
2506            .binding
2507            .content_sha256()
2508            .expect("validated regular binding"),
2509        transaction
2510            .binding
2511            .bytes()
2512            .expect("validated regular binding"),
2513        transaction
2514            .binding
2515            .executable()
2516            .expect("validated regular binding"),
2517    )?;
2518    state.verify_still_attached()?;
2519    Ok(())
2520}
2521
2522fn completed_restore_result(
2523    store: &FolderbaseVersionStore,
2524    local: &LocalVersionStore,
2525    state: &FolderbaseState,
2526    transaction: &RestoreTransaction,
2527    published_identity_sha256: &str,
2528) -> Result<Option<RestoredTombstone>, FolderbaseCaptureError> {
2529    validate_restore_transaction(store, transaction)?;
2530    let current_head = read_head_record(state)?.ok_or(FolderbaseCaptureError::MissingLocalHead)?;
2531    if !is_exact_restore_target_head(store, transaction, &current_head)? {
2532        return Ok(None);
2533    }
2534    rederive_authoritative_restore_transaction(store, local, state, transaction)?;
2535    let installed =
2536        read_and_verify_folderbase_version(store, local, state, &transaction.target_version_id)?;
2537    if installed.canonical_digest()? != transaction.target_version_sha256 {
2538        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
2539            "completed restore version digest changed".to_owned(),
2540        ));
2541    }
2542
2543    let path = Path::new(&transaction.path);
2544    let digest = transaction
2545        .binding
2546        .content_sha256()
2547        .expect("validated regular binding");
2548    let bytes = transaction
2549        .binding
2550        .bytes()
2551        .expect("validated regular binding");
2552    let executable = transaction
2553        .binding
2554        .executable()
2555        .expect("validated regular binding");
2556    let expected_authority = restore_authority_record(transaction, published_identity_sha256);
2557    let authority_path = restore_authority_record_path(&transaction.transaction_id);
2558    let authority = state
2559        .read_bounded(&authority_path, MAX_RESTORE_AUTHORITY_BYTES)?
2560        .and_then(|encoded| serde_json::from_slice::<RestoreAuthorityRecord>(&encoded).ok());
2561    let retained_identity =
2562        state.workspace_restore_identity_sha256(&restore_stage_path(transaction), path);
2563    if authority.as_ref() != Some(&expected_authority)
2564        || !matches!(
2565            retained_identity,
2566            Ok(observed) if observed == published_identity_sha256
2567        )
2568    {
2569        return Ok(None);
2570    }
2571    if state
2572        .verify_workspace_regular_file_identity_and_fidelity(
2573            path,
2574            published_identity_sha256,
2575            digest,
2576            bytes,
2577            executable,
2578        )
2579        .is_err()
2580    {
2581        return Ok(None);
2582    }
2583    verify_restore_success_linearization(
2584        store,
2585        local,
2586        state,
2587        transaction,
2588        published_identity_sha256,
2589    )?;
2590    Ok(Some(restored_tombstone(transaction, false)))
2591}
2592
2593fn rollback_restore_head(
2594    _store: &FolderbaseVersionStore,
2595    state: &FolderbaseState,
2596    transaction: &RestoreTransaction,
2597) -> Result<(), FolderbaseCaptureError> {
2598    let target = JournalHead {
2599        version_id: transaction.target_version_id.clone(),
2600        version_sha256: transaction.target_version_sha256.clone(),
2601        authority: LocalHeadAuthority::VersionDerivedV1 {
2602            sha256: restore_transaction_local_head_authority_sha256(
2603                transaction,
2604                &transaction.target_version_id,
2605                &transaction.target_version_sha256,
2606            )?,
2607        },
2608    };
2609    let prior = LocalHeadRecord {
2610        format: "folderbase-local-head-v2".to_owned(),
2611        folderbase_id: transaction.folderbase_id.clone(),
2612        root_instance_sha256: transaction.root_instance_sha256.clone(),
2613        version_id: transaction.expected_head.version_id.clone(),
2614        version_sha256: transaction.expected_head.version_sha256.clone(),
2615        authority: transaction.expected_head.authority.clone(),
2616    };
2617    // Rollback deliberately uses the already-retained state capability rather
2618    // than the ambient root path. If that path was swapped after the forward
2619    // CAS, the exact original root still has to regain its prior Head while
2620    // the replacement path remains untouched.
2621    let current = read_head_record(state)?.ok_or(FolderbaseCaptureError::LocalHeadChanged)?;
2622    if JournalHead::from(&current) != target {
2623        return Err(FolderbaseCaptureError::LocalHeadChanged);
2624    }
2625    state.replace(Path::new(LOCAL_HEAD_PATH), &json_bytes(&prior)?)?;
2626    if read_head_record(state)?.as_ref() != Some(&prior) {
2627        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
2628            "Local Head rollback did not verify".to_owned(),
2629        ));
2630    }
2631    Ok(())
2632}
2633
2634fn finish_restore_materialization(
2635    store: &FolderbaseVersionStore,
2636    local: &LocalVersionStore,
2637    state: &FolderbaseState,
2638    transaction: &RestoreTransaction,
2639    checkpoint: &mut impl FnMut(&RestoreCheckpoint),
2640) -> Result<(), FolderbaseCaptureError> {
2641    stage_and_publish_restore(state, transaction, checkpoint)?;
2642    let installed =
2643        read_and_verify_folderbase_version(store, local, state, &transaction.target_version_id)?;
2644    if installed.canonical_digest()? != transaction.target_version_sha256 {
2645        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
2646            "committed restore version failed verification".to_owned(),
2647        ));
2648    }
2649    checkpoint(&RestoreCheckpoint::VersionDurable);
2650    checkpoint(&RestoreCheckpoint::HeadReplaced);
2651    verify_restore_publication(store, state, transaction)?;
2652    checkpoint(&RestoreCheckpoint::PublicationVerified);
2653    finish_restore_projection(store, local, state, transaction)?;
2654    verify_restore_publication(store, state, transaction)?;
2655    checkpoint(&RestoreCheckpoint::ProjectionDurable);
2656    Ok(())
2657}
2658
2659fn stage_and_publish_restore(
2660    state: &FolderbaseState,
2661    transaction: &RestoreTransaction,
2662    checkpoint: &mut impl FnMut(&RestoreCheckpoint),
2663) -> Result<(), FolderbaseCaptureError> {
2664    let transaction_directory =
2665        Path::new(RESTORE_TRANSACTIONS_DIRECTORY).join(&transaction.transaction_id);
2666    state.ensure_private_dir(&transaction_directory)?;
2667    let stage = restore_stage_path(transaction);
2668    let digest = transaction
2669        .binding
2670        .content_sha256()
2671        .expect("validated regular binding");
2672    let bytes = transaction
2673        .binding
2674        .bytes()
2675        .expect("validated regular binding");
2676    let executable = transaction
2677        .binding
2678        .executable()
2679        .expect("validated regular binding");
2680    let source = Path::new(".folderbase/versions/blobs/sha256").join(digest);
2681    state.stage_restore_blob(&source, &stage, digest, bytes, executable)?;
2682    checkpoint(&RestoreCheckpoint::StageDurable);
2683    let result = state
2684        .publish_workspace_restore_with_hook(
2685            &stage,
2686            Path::new(&transaction.path),
2687            digest,
2688            bytes,
2689            executable,
2690            |linked| {
2691                checkpoint(if linked {
2692                    &RestoreCheckpoint::WorkspaceLinkCreated
2693                } else {
2694                    &RestoreCheckpoint::WorkspaceParentOpened
2695                });
2696            },
2697        )
2698        .map(|_| ())
2699        .map_err(|error| match error {
2700            FolderbaseError::WouldOverwrite(path) => {
2701                FolderbaseCaptureError::RestoreTargetOccupied(path)
2702            }
2703            FolderbaseError::RestoreNamespaceRepairRequired(_) => {
2704                FolderbaseCaptureError::RestoreNamespaceRepairRequired(
2705                    Path::new(&transaction.path).to_path_buf(),
2706                )
2707            }
2708            error => FolderbaseCaptureError::LocalStore(error),
2709        });
2710    if result.is_ok() {
2711        checkpoint(&RestoreCheckpoint::TargetPublished);
2712    }
2713    result
2714}
2715
2716fn finish_restore_projection(
2717    store: &FolderbaseVersionStore,
2718    local: &LocalVersionStore,
2719    state: &FolderbaseState,
2720    transaction: &RestoreTransaction,
2721) -> Result<(), FolderbaseCaptureError> {
2722    let file = state.open_workspace_regular_file(Path::new(&transaction.path))?;
2723    let observed =
2724        fingerprint_std_file(&file, &store.root_attestation.root.join(&transaction.path))?;
2725    let assignment = CaptureAssignment {
2726        path: transaction.path.clone(),
2727        kind: CaptureEntryKind::RegularFile,
2728        object_id: transaction.binding.object_id().to_owned(),
2729        candidate_object_version_id: transaction.binding.object_version_id().map(str::to_owned),
2730        prior_object_version_id: transaction.binding.object_version_id().map(str::to_owned),
2731        reused_object: true,
2732        observed,
2733        link_commitment: CaptureLinkCommitment::default(),
2734    };
2735    let version_id = VersionId::parse(
2736        transaction
2737            .binding
2738            .object_version_id()
2739            .expect("validated regular binding")
2740            .to_owned(),
2741    )?;
2742    if can_project_legacy_object(&transaction.path) {
2743        let projection = regular_projection(
2744            local,
2745            state,
2746            &assignment,
2747            &version_id,
2748            Some(version_id.as_str()),
2749            &transaction.created_at,
2750        )?;
2751        local.write_capture_object_projection_in(state, &projection)?;
2752    }
2753    let identity = CaptureIdentityRecord {
2754        format: "folderbase-capture-identity-v1".to_owned(),
2755        object_id: assignment.object_id,
2756        kind: assignment.kind,
2757        observed: assignment.observed,
2758    };
2759    state.replace(
2760        &capture_identity_relative_path(transaction.binding.object_id()),
2761        &json_bytes(&identity)?,
2762    )?;
2763    Ok(())
2764}
2765
2766fn restore_stage_path(transaction: &RestoreTransaction) -> PathBuf {
2767    restore_transaction_directory(transaction).join("content")
2768}
2769
2770fn restore_transaction_directory(transaction: &RestoreTransaction) -> PathBuf {
2771    Path::new(RESTORE_TRANSACTIONS_DIRECTORY).join(&transaction.transaction_id)
2772}
2773
2774impl From<&LocalHeadRecord> for JournalHead {
2775    fn from(value: &LocalHeadRecord) -> Self {
2776        Self {
2777            version_id: value.version_id.clone(),
2778            version_sha256: value.version_sha256.clone(),
2779            authority: value.authority.clone(),
2780        }
2781    }
2782}
2783
2784#[derive(Serialize)]
2785struct PlanDigestV2<'a> {
2786    format: &'static str,
2787    folderbase_id: &'a str,
2788    root_instance_sha256: &'a str,
2789    root_manifest_sha256: &'a str,
2790    root_manifest_bytes: u64,
2791    ignore_policy_sha256: &'a str,
2792    current_head: Option<JournalHead>,
2793    entries: Vec<PlanDigestV2Entry<'a>>,
2794    exclusions: Vec<PlanDigestV2Exclusion<'a>>,
2795    ignored_paths: Vec<&'a str>,
2796}
2797
2798#[derive(Serialize)]
2799struct ReleasedV1PlanDigest<'a> {
2800    format: &'static str,
2801    folderbase_id: &'a str,
2802    root_instance_sha256: &'a str,
2803    root_manifest_sha256: &'a str,
2804    root_manifest_bytes: u64,
2805    ignore_policy_sha256: &'a str,
2806    current_head: Option<ReleasedV1JournalHead>,
2807    entries: Vec<ReleasedV1PlanDigestEntry<'a>>,
2808    exclusions: Vec<ReleasedV1PlanDigestExclusion<'a>>,
2809    ignored_paths: Vec<&'a str>,
2810}
2811
2812#[derive(Serialize)]
2813struct PlanDigestV2Entry<'a> {
2814    path: &'a str,
2815    kind: CaptureEntryKind,
2816    bytes: Option<u64>,
2817    executable: Option<bool>,
2818    symlink_target: Option<&'a str>,
2819    observed: &'a CaptureMetadataFingerprint,
2820    #[serde(skip_serializing_if = "Option::is_none")]
2821    link_commitment: Option<&'a CaptureLinkCommitment>,
2822}
2823
2824#[derive(Serialize)]
2825struct ReleasedV1PlanDigestEntry<'a> {
2826    path: &'a str,
2827    kind: CaptureEntryKind,
2828    bytes: Option<u64>,
2829    executable: Option<bool>,
2830    symlink_target: Option<&'a str>,
2831    observed: &'a CaptureMetadataFingerprint,
2832}
2833
2834#[derive(Serialize)]
2835struct PlanDigestV2Exclusion<'a> {
2836    path: &'a str,
2837    kind: CaptureExclusionKind,
2838    reason: CaptureExclusionReason,
2839}
2840
2841#[derive(Serialize)]
2842struct ReleasedV1PlanDigestExclusion<'a> {
2843    path: &'a str,
2844    kind: CaptureExclusionKind,
2845    reason: CaptureExclusionReason,
2846}
2847
2848fn capture_plan_sha256(plan: &CapturePlan) -> Result<String, FolderbaseCaptureError> {
2849    capture_plan_sha256_with_root_instance(plan, plan.root_instance_sha256())
2850}
2851
2852fn capture_plan_sha256_with_root_instance(
2853    plan: &CapturePlan,
2854    root_instance_sha256: &str,
2855) -> Result<String, FolderbaseCaptureError> {
2856    let has_restore_authority = plan
2857        .entries()
2858        .iter()
2859        .any(|entry| !entry.link_commitment().is_legacy_default());
2860    let has_version_derived_head = plan.current_local_head().is_some_and(|head| {
2861        matches!(
2862            head.authority(),
2863            LocalHeadAuthority::VersionDerivedV1 { .. }
2864        )
2865    });
2866    if !has_restore_authority && !has_version_derived_head {
2867        return released_v1_capture_plan_sha256_with_root_instance(plan, root_instance_sha256);
2868    }
2869    let digest = PlanDigestV2 {
2870        format: "folderbase-capture-plan-digest-v2",
2871        folderbase_id: plan.folderbase_id(),
2872        root_instance_sha256,
2873        root_manifest_sha256: plan.root_manifest_sha256(),
2874        root_manifest_bytes: plan.root_manifest_bytes(),
2875        ignore_policy_sha256: plan.ignore_policy_sha256(),
2876        current_head: plan.current_local_head().map(JournalHead::from),
2877        entries: plan
2878            .entries()
2879            .iter()
2880            .map(|entry| PlanDigestV2Entry {
2881                path: entry.path(),
2882                kind: entry.kind(),
2883                bytes: entry.bytes(),
2884                executable: entry.executable(),
2885                symlink_target: entry.symlink_target(),
2886                observed: entry.observed(),
2887                link_commitment: (!entry.link_commitment().is_legacy_default())
2888                    .then_some(entry.link_commitment()),
2889            })
2890            .collect(),
2891        exclusions: plan
2892            .exclusions()
2893            .iter()
2894            .map(|exclusion| PlanDigestV2Exclusion {
2895                path: exclusion.path(),
2896                kind: exclusion.kind(),
2897                reason: exclusion.reason(),
2898            })
2899            .collect(),
2900        ignored_paths: plan
2901            .ignored_paths()
2902            .iter()
2903            .map(|path| path.path())
2904            .collect(),
2905    };
2906    let encoded = serde_json::to_vec(&digest).map_err(|source| {
2907        FolderbaseCaptureError::InvalidCaptureTransaction(format!(
2908            "CapturePlan digest encoding failed: {source}"
2909        ))
2910    })?;
2911    Ok(format!("{:x}", Sha256::digest(encoded)))
2912}
2913
2914fn released_v1_capture_plan_sha256_with_root_instance(
2915    plan: &CapturePlan,
2916    root_instance_sha256: &str,
2917) -> Result<String, FolderbaseCaptureError> {
2918    if plan
2919        .entries()
2920        .iter()
2921        .any(|entry| !entry.link_commitment().is_legacy_default())
2922    {
2923        return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
2924            "released v1 CapturePlan digest cannot bind restore authority links".to_owned(),
2925        ));
2926    }
2927    let current_head = match plan.current_local_head() {
2928        Some(head) => {
2929            let LocalHeadAuthority::CaptureTransactionV1 { sha256 } = head.authority() else {
2930                return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
2931                    "released v1 CapturePlan digest cannot bind version-derived Head authority"
2932                        .to_owned(),
2933                ));
2934            };
2935            Some(ReleasedV1JournalHead {
2936                version_id: head.version_id().to_owned(),
2937                version_sha256: head.version_sha256().to_owned(),
2938                transaction_sha256: sha256.to_owned(),
2939            })
2940        }
2941        None => None,
2942    };
2943    let digest = ReleasedV1PlanDigest {
2944        format: "folderbase-capture-plan-digest-v1",
2945        folderbase_id: plan.folderbase_id(),
2946        root_instance_sha256,
2947        root_manifest_sha256: plan.root_manifest_sha256(),
2948        root_manifest_bytes: plan.root_manifest_bytes(),
2949        ignore_policy_sha256: plan.ignore_policy_sha256(),
2950        current_head,
2951        entries: plan
2952            .entries()
2953            .iter()
2954            .map(|entry| ReleasedV1PlanDigestEntry {
2955                path: entry.path(),
2956                kind: entry.kind(),
2957                bytes: entry.bytes(),
2958                executable: entry.executable(),
2959                symlink_target: entry.symlink_target(),
2960                observed: entry.observed(),
2961            })
2962            .collect(),
2963        exclusions: plan
2964            .exclusions()
2965            .iter()
2966            .map(|exclusion| ReleasedV1PlanDigestExclusion {
2967                path: exclusion.path(),
2968                kind: exclusion.kind(),
2969                reason: exclusion.reason(),
2970            })
2971            .collect(),
2972        ignored_paths: plan
2973            .ignored_paths()
2974            .iter()
2975            .map(|path| path.path())
2976            .collect(),
2977    };
2978    let encoded = serde_json::to_vec(&digest).map_err(|source| {
2979        FolderbaseCaptureError::InvalidCaptureTransaction(format!(
2980            "released v1 CapturePlan digest encoding failed: {source}"
2981        ))
2982    })?;
2983    Ok(format!("{:x}", Sha256::digest(encoded)))
2984}
2985
2986fn local_head_authority_sha256(
2987    store: &FolderbaseVersionStore,
2988    version_id: &str,
2989    version_sha256: &str,
2990) -> Result<String, FolderbaseCaptureError> {
2991    version_derived_local_head_sha256(
2992        &store.root_attestation.folderbase_id,
2993        &store.root_attestation.root_instance_sha256,
2994        version_id,
2995        version_sha256,
2996    )
2997}
2998
2999fn restore_transaction_local_head_authority_sha256(
3000    transaction: &RestoreTransaction,
3001    version_id: &str,
3002    version_sha256: &str,
3003) -> Result<String, FolderbaseCaptureError> {
3004    version_derived_local_head_sha256(
3005        &transaction.folderbase_id,
3006        &transaction.root_instance_sha256,
3007        version_id,
3008        version_sha256,
3009    )
3010}
3011
3012#[cfg(test)]
3013fn capture_transaction_sha256(
3014    transaction: &CaptureTransaction,
3015) -> Result<String, FolderbaseCaptureError> {
3016    Ok(format!("{:x}", Sha256::digest(json_bytes(transaction)?)))
3017}
3018
3019fn ensure_same_plan(
3020    expected: &CapturePlan,
3021    actual: &CapturePlan,
3022) -> Result<(), FolderbaseCaptureError> {
3023    if expected.root() != actual.root()
3024        || expected.folderbase_id() != actual.folderbase_id()
3025        || expected.root_instance_sha256() != actual.root_instance_sha256()
3026    {
3027        return Err(FolderbaseCaptureError::PlanStoreMismatch);
3028    }
3029    if expected.current_local_head().map(JournalHead::from)
3030        != actual.current_local_head().map(JournalHead::from)
3031    {
3032        return Err(FolderbaseCaptureError::LocalHeadChanged);
3033    }
3034    if expected.root_manifest_sha256() != actual.root_manifest_sha256()
3035        || expected.root_manifest_bytes() != actual.root_manifest_bytes()
3036    {
3037        return Err(FolderbaseCaptureError::CaptureStateChanged(PathBuf::from(
3038            ".folderbase/manifest.json",
3039        )));
3040    }
3041    if expected.ignore_policy_sha256() != actual.ignore_policy_sha256() {
3042        return Err(FolderbaseCaptureError::CaptureStateChanged(PathBuf::from(
3043            ".folderbaseignore",
3044        )));
3045    }
3046    for (left, right) in expected.entries().iter().zip(actual.entries()) {
3047        if left.path() != right.path()
3048            || left.kind() != right.kind()
3049            || left.bytes() != right.bytes()
3050            || left.executable() != right.executable()
3051            || left.symlink_target() != right.symlink_target()
3052            || left.observed() != right.observed()
3053            || left.link_commitment() != right.link_commitment()
3054        {
3055            return Err(FolderbaseCaptureError::CaptureStateChanged(PathBuf::from(
3056                if left.path() <= right.path() {
3057                    left.path()
3058                } else {
3059                    right.path()
3060                },
3061            )));
3062        }
3063    }
3064    if expected.entries().len() != actual.entries().len() {
3065        let path = expected
3066            .entries()
3067            .iter()
3068            .zip(actual.entries())
3069            .find_map(|(left, right)| (left.path() != right.path()).then_some(left.path()))
3070            .or_else(|| expected.entries().last().map(CapturePlanEntry::path))
3071            .or_else(|| actual.entries().last().map(CapturePlanEntry::path))
3072            .unwrap_or(".");
3073        return Err(FolderbaseCaptureError::CaptureStateChanged(PathBuf::from(
3074            path,
3075        )));
3076    }
3077    let same_exclusions = expected.exclusions().len() == actual.exclusions().len()
3078        && expected
3079            .exclusions()
3080            .iter()
3081            .zip(actual.exclusions())
3082            .all(|(left, right)| {
3083                left.path() == right.path()
3084                    && left.kind() == right.kind()
3085                    && left.reason() == right.reason()
3086            });
3087    if !same_exclusions {
3088        let path = expected
3089            .exclusions()
3090            .first()
3091            .map(|value| value.path())
3092            .or_else(|| actual.exclusions().first().map(|value| value.path()))
3093            .unwrap_or(".");
3094        return Err(FolderbaseCaptureError::CaptureStateChanged(PathBuf::from(
3095            path,
3096        )));
3097    }
3098    let same_ignored = expected.ignored_paths().len() == actual.ignored_paths().len()
3099        && expected
3100            .ignored_paths()
3101            .iter()
3102            .zip(actual.ignored_paths())
3103            .all(|(left, right)| left.path() == right.path());
3104    if !same_ignored {
3105        let path = expected
3106            .ignored_paths()
3107            .first()
3108            .map(|value| value.path())
3109            .or_else(|| actual.ignored_paths().first().map(|value| value.path()))
3110            .unwrap_or(".");
3111        return Err(FolderbaseCaptureError::CaptureStateChanged(PathBuf::from(
3112            path,
3113        )));
3114    }
3115    Ok(())
3116}
3117
3118fn assign_capture_transaction(
3119    plan: &CapturePlan,
3120    plan_sha256: &str,
3121    prior: Option<&FolderbaseVersion>,
3122) -> Result<CaptureTransaction, FolderbaseCaptureError> {
3123    let identity_state = FolderbaseState::open_existing_read_only(plan.root())?;
3124    let mut assignments = Vec::with_capacity(plan.entries().len());
3125    for entry in plan.entries() {
3126        let prior_binding =
3127            prior_binding_for_capture_entry(prior, &identity_state, plan.root(), entry)?;
3128        let reused_object =
3129            prior_binding.is_some_and(|binding| binding.kind() == path_binding_kind(entry.kind()));
3130        let object_id = prior_binding
3131            .filter(|_| reused_object)
3132            .map(|binding| binding.object_id().to_owned())
3133            .unwrap_or_else(|| ObjectId::new().to_string());
3134        let candidate_object_version_id =
3135            (entry.kind() != CaptureEntryKind::Directory).then(|| VersionId::new().to_string());
3136        let prior_object_version_id = prior_binding
3137            .filter(|_| reused_object)
3138            .and_then(|binding| binding.object_version_id())
3139            .map(str::to_owned);
3140        assignments.push(CaptureAssignment {
3141            path: entry.path().to_owned(),
3142            kind: entry.kind(),
3143            object_id,
3144            candidate_object_version_id,
3145            prior_object_version_id,
3146            reused_object,
3147            observed: entry.observed().clone(),
3148            link_commitment: entry.link_commitment().clone(),
3149        });
3150    }
3151
3152    let target_tombstones = project_target_tombstones(prior, &assignments);
3153    Ok(CaptureTransaction {
3154        format: CAPTURE_TRANSACTION_FORMAT_V1.to_owned(),
3155        transaction_id: format!("fbcapture_{}", Uuid::now_v7()),
3156        folderbase_id: plan.folderbase_id().to_owned(),
3157        root_instance_sha256: plan.root_instance_sha256().to_owned(),
3158        plan_sha256: plan_sha256.to_owned(),
3159        expected_head: plan.current_local_head().map(JournalHead::from),
3160        target_version_id: format!("fbversion_{}", Uuid::now_v7()),
3161        created_at: Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true),
3162        root_manifest_object_id: ObjectId::new().to_string(),
3163        root_manifest_candidate_version_id: VersionId::new().to_string(),
3164        prior_root_manifest_version_id: prior
3165            .map(|version| version.root_manifest().object_version_id().to_owned()),
3166        assignments,
3167        target_tombstones,
3168    })
3169}
3170
3171fn ensure_prior_bindings_observable(
3172    plan: &CapturePlan,
3173    prior: Option<&FolderbaseVersion>,
3174) -> Result<(), FolderbaseCaptureError> {
3175    let Some(prior) = prior else {
3176        return Ok(());
3177    };
3178    let live_paths = plan
3179        .entries()
3180        .iter()
3181        .map(|entry| entry.path())
3182        .collect::<std::collections::BTreeSet<_>>();
3183    for binding in prior.bindings() {
3184        if live_paths.contains(binding.path()) {
3185            continue;
3186        }
3187        let state = FolderbaseState::open_existing_read_only(plan.root())?;
3188        let moved_with_stable_identity = plan.entries().iter().any(|entry| {
3189            entry.kind() == capture_entry_kind(binding.kind())
3190                && identity_allows_reuse(&state, plan.root(), binding.object_id(), entry)
3191                    .unwrap_or(false)
3192        });
3193        if moved_with_stable_identity {
3194            continue;
3195        }
3196        let hidden_by_ignore = plan
3197            .ignored_paths()
3198            .iter()
3199            .any(|ignored| path_is_same_or_descendant_of(binding.path(), ignored.path()));
3200        let hidden_by_exclusion = plan.exclusions().iter().any(|exclusion| {
3201            binding.path() == exclusion.path()
3202                || (exclusion.kind() == CaptureExclusionKind::NestedFolderbase
3203                    && path_is_same_or_descendant_of(binding.path(), exclusion.path()))
3204        });
3205        if hidden_by_ignore || hidden_by_exclusion {
3206            return Err(FolderbaseCaptureError::PriorBindingHidden(PathBuf::from(
3207                binding.path(),
3208            )));
3209        }
3210    }
3211    Ok(())
3212}
3213
3214fn path_is_same_or_descendant_of(path: &str, ancestor: &str) -> bool {
3215    path == ancestor
3216        || path
3217            .strip_prefix(ancestor)
3218            .is_some_and(|suffix| suffix.starts_with('/'))
3219}
3220
3221fn project_target_tombstones(
3222    prior: Option<&FolderbaseVersion>,
3223    assignments: &[CaptureAssignment],
3224) -> Vec<Tombstone> {
3225    let Some(prior) = prior else {
3226        return Vec::new();
3227    };
3228    let mut by_path = prior
3229        .tombstones()
3230        .iter()
3231        .cloned()
3232        .map(|tombstone| (tombstone.path().to_owned(), tombstone))
3233        .collect::<BTreeMap<_, _>>();
3234    for binding in prior.bindings() {
3235        let continued = assignments.iter().any(|assignment| {
3236            assignment.reused_object && assignment.object_id == binding.object_id()
3237        });
3238        if continued {
3239            continue;
3240        }
3241        by_path.insert(
3242            binding.path().to_owned(),
3243            Tombstone::from_verified_producer(
3244                binding.path(),
3245                binding.object_id(),
3246                deleted_kind(binding.kind()),
3247                binding.object_version_id().map(str::to_owned),
3248            ),
3249        );
3250    }
3251    by_path.into_values().collect()
3252}
3253
3254fn deleted_kind(kind: PathBindingKind) -> DeletedKind {
3255    match kind {
3256        PathBindingKind::Directory => DeletedKind::Directory,
3257        PathBindingKind::RegularFile => DeletedKind::RegularFile,
3258        PathBindingKind::Symlink => DeletedKind::Symlink,
3259    }
3260}
3261
3262fn path_binding_kind(kind: CaptureEntryKind) -> PathBindingKind {
3263    match kind {
3264        CaptureEntryKind::Directory => PathBindingKind::Directory,
3265        CaptureEntryKind::RegularFile => PathBindingKind::RegularFile,
3266        CaptureEntryKind::Symlink => PathBindingKind::Symlink,
3267    }
3268}
3269
3270fn capture_entry_kind(kind: PathBindingKind) -> CaptureEntryKind {
3271    match kind {
3272        PathBindingKind::Directory => CaptureEntryKind::Directory,
3273        PathBindingKind::RegularFile => CaptureEntryKind::RegularFile,
3274        PathBindingKind::Symlink => CaptureEntryKind::Symlink,
3275    }
3276}
3277
3278fn prior_binding_for_capture_entry<'a>(
3279    prior: Option<&'a FolderbaseVersion>,
3280    state: &FolderbaseState,
3281    root: &Path,
3282    entry: &CapturePlanEntry,
3283) -> Result<Option<&'a PathBinding>, FolderbaseCaptureError> {
3284    let Some(prior) = prior else {
3285        return Ok(None);
3286    };
3287    if let Some(binding) = prior.lookup_binding(entry.path())
3288        && binding.kind() == path_binding_kind(entry.kind())
3289    {
3290        return Ok(Some(binding));
3291    }
3292    let mut matched = None;
3293    for binding in prior.bindings() {
3294        if binding.kind() != path_binding_kind(entry.kind())
3295            || !identity_allows_reuse(state, root, binding.object_id(), entry)?
3296        {
3297            continue;
3298        }
3299        if matched.is_some() {
3300            return Err(FolderbaseCaptureError::InvalidPriorLocalHead(
3301                "more than one prior Object identity matches a moved entry".to_owned(),
3302            ));
3303        }
3304        matched = Some(binding);
3305    }
3306    Ok(matched)
3307}
3308
3309fn identity_allows_reuse(
3310    state: &FolderbaseState,
3311    root: &Path,
3312    object_id: &str,
3313    entry: &CapturePlanEntry,
3314) -> Result<bool, FolderbaseCaptureError> {
3315    let relative = capture_identity_relative_path(object_id);
3316    let path = root.join(&relative);
3317    let Some(encoded) = state.read_bounded(&relative, 64 * 1024)? else {
3318        return Ok(false);
3319    };
3320    let record: CaptureIdentityRecord = serde_json::from_slice(&encoded).map_err(|source| {
3321        FolderbaseCaptureError::InvalidPriorLocalHead(format!(
3322            "capture identity {} is invalid: {source}",
3323            path.display()
3324        ))
3325    })?;
3326    if record.format != "folderbase-capture-identity-v1"
3327        || record.object_id != object_id
3328        || record.kind != entry.kind()
3329    {
3330        return Err(FolderbaseCaptureError::InvalidPriorLocalHead(format!(
3331            "capture identity {} does not match its binding",
3332            path.display()
3333        )));
3334    }
3335    match (
3336        record.observed.physical_identity.as_deref(),
3337        entry.observed().physical_identity.as_deref(),
3338    ) {
3339        (Some(previous), Some(current)) => return Ok(previous == current),
3340        (Some(_), None) | (None, Some(_)) => return Ok(false),
3341        (None, None) => {}
3342    }
3343    match (
3344        (record.observed.device, record.observed.inode),
3345        (entry.observed().device, entry.observed().inode),
3346    ) {
3347        ((Some(old_device), Some(old_inode)), (Some(device), Some(inode))) => {
3348            Ok(old_device == device && old_inode == inode)
3349        }
3350        _ => Ok(false),
3351    }
3352}
3353
3354fn load_prior_head(
3355    store: &FolderbaseVersionStore,
3356    local: &LocalVersionStore,
3357    state: &FolderbaseState,
3358    head: Option<&CaptureLocalHead>,
3359) -> Result<Option<FolderbaseVersion>, FolderbaseCaptureError> {
3360    let Some(head) = head else {
3361        return Ok(None);
3362    };
3363    let version = read_and_verify_folderbase_version(store, local, state, head.version_id())
3364        .map_err(|error| FolderbaseCaptureError::InvalidPriorLocalHead(error.to_string()))?;
3365    let digest = version
3366        .canonical_digest()
3367        .map_err(|error| FolderbaseCaptureError::InvalidPriorLocalHead(error.to_string()))?;
3368    if digest != head.version_sha256() {
3369        return Err(FolderbaseCaptureError::InvalidPriorLocalHead(
3370            "Local Head digest does not match the complete Folderbase Version".to_owned(),
3371        ));
3372    }
3373    Ok(Some(version))
3374}
3375
3376fn load_transaction_prior(
3377    store: &FolderbaseVersionStore,
3378    local: &LocalVersionStore,
3379    state: &FolderbaseState,
3380    head: Option<&JournalHead>,
3381) -> Result<Option<FolderbaseVersion>, FolderbaseCaptureError> {
3382    let Some(head) = head else {
3383        return Ok(None);
3384    };
3385    let version = read_and_verify_folderbase_version(store, local, state, &head.version_id)
3386        .map_err(|error| FolderbaseCaptureError::InvalidPriorLocalHead(error.to_string()))?;
3387    if version.canonical_digest()? != head.version_sha256 {
3388        return Err(FolderbaseCaptureError::InvalidPriorLocalHead(
3389            "transaction parent digest does not match its complete Folderbase Version".to_owned(),
3390        ));
3391    }
3392    Ok(Some(version))
3393}
3394
3395fn live_state_matches_prior(
3396    store: &FolderbaseVersionStore,
3397    plan: &CapturePlan,
3398    local: &LocalVersionStore,
3399    state: &FolderbaseState,
3400    prior: Option<&FolderbaseVersion>,
3401    checkpoint: &mut impl FnMut(&CaptureCheckpoint),
3402) -> Result<bool, FolderbaseCaptureError> {
3403    let Some(prior) = prior else {
3404        return Ok(false);
3405    };
3406    if prior.folderbase_id() != plan.folderbase_id()
3407        || prior.root_manifest().content_sha256() != plan.root_manifest_sha256()
3408        || prior.root_manifest().bytes() != plan.root_manifest_bytes()
3409        || prior.bindings().len() != plan.entries().len()
3410        || prior.exclusions().len() != plan.exclusions().len()
3411    {
3412        return Ok(false);
3413    }
3414    for (entry, binding) in plan.entries().iter().zip(prior.bindings()) {
3415        if entry.path() != binding.path()
3416            || path_binding_kind(entry.kind()) != binding.kind()
3417            || !identity_allows_reuse(
3418                state,
3419                &store.root_attestation.root,
3420                binding.object_id(),
3421                entry,
3422            )?
3423        {
3424            return Ok(false);
3425        }
3426        match entry.kind() {
3427            CaptureEntryKind::Directory => {}
3428            CaptureEntryKind::RegularFile => {
3429                let content = hash_regular_entry(
3430                    &store.root_attestation,
3431                    &store.root_instance_authority,
3432                    state,
3433                    entry,
3434                    None,
3435                    checkpoint,
3436                )?;
3437                if binding.content_sha256() != Some(content.digest.as_str())
3438                    || binding.bytes() != Some(content.bytes)
3439                    || binding.executable() != entry.executable()
3440                {
3441                    return Ok(false);
3442                }
3443                let object_id = ObjectId::parse(binding.object_id().to_owned())?;
3444                let version_id = VersionId::parse(binding.object_version_id().unwrap().to_owned())?;
3445                local.verify_capture_object_version_in(state, &object_id, &version_id, &content)?;
3446            }
3447            CaptureEntryKind::Symlink => {
3448                verify_symlink_entry(&store.root_attestation.root, entry)?;
3449                if binding.symlink_target() != entry.symlink_target() {
3450                    return Ok(false);
3451                }
3452                let target = entry.symlink_target().expect("planned symlink target");
3453                let content = content_digest(target.as_bytes());
3454                let object_id = ObjectId::parse(binding.object_id().to_owned())?;
3455                let version_id = VersionId::parse(binding.object_version_id().unwrap().to_owned())?;
3456                local.verify_capture_object_version_in(state, &object_id, &version_id, &content)?;
3457            }
3458        }
3459    }
3460    for (planned, sealed) in plan.exclusions().iter().zip(prior.exclusions()) {
3461        if planned.path() != sealed.path()
3462            || exclusion_kind(planned.kind()) != sealed.kind()
3463            || exclusion_reason(planned.reason()) != sealed.reason()
3464        {
3465            return Ok(false);
3466        }
3467    }
3468    Ok(true)
3469}
3470
3471fn preflight_capture_envelopes(
3472    plan: &CapturePlan,
3473    transaction: &CaptureTransaction,
3474    wire: CaptureTransactionWire,
3475    maximum_transaction_bytes: u64,
3476    maximum_version_bytes: u64,
3477) -> Result<(), FolderbaseCaptureError> {
3478    match wire {
3479        CaptureTransactionWire::Current => {
3480            encode_active_transaction(transaction, maximum_transaction_bytes)?;
3481        }
3482        CaptureTransactionWire::ReleasedV1 { encoded_bytes }
3483            if encoded_bytes > maximum_transaction_bytes =>
3484        {
3485            return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
3486                "released v1 active journal exceeds its bounded record limit".to_owned(),
3487            ));
3488        }
3489        CaptureTransactionWire::ReleasedV1 { .. } => {}
3490    }
3491
3492    if transaction.assignments.len() != plan.entries().len() {
3493        return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
3494            "journal assignment cardinality does not match the CapturePlan".to_owned(),
3495        ));
3496    }
3497
3498    let placeholder_sha256 = "0".repeat(64);
3499    let mut bindings = Vec::with_capacity(plan.entries().len());
3500    for (entry, assignment) in plan.entries().iter().zip(&transaction.assignments) {
3501        if assignment.path != entry.path() || assignment.kind != entry.kind() {
3502            return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
3503                "journal assignment does not match the CapturePlan".to_owned(),
3504            ));
3505        }
3506        let binding = match entry.kind() {
3507            CaptureEntryKind::Directory => PathBinding::directory_from_verified_producer(
3508                entry.path(),
3509                assignment.object_id.clone(),
3510            ),
3511            CaptureEntryKind::RegularFile => PathBinding::regular_file_from_verified_producer(
3512                entry.path(),
3513                assignment.object_id.clone(),
3514                assigned_object_version_id(assignment)?,
3515                placeholder_sha256.clone(),
3516                entry.bytes().ok_or_else(|| {
3517                    FolderbaseCaptureError::InvalidCaptureTransaction(format!(
3518                        "regular CapturePlan entry has no byte length: {}",
3519                        entry.path()
3520                    ))
3521                })?,
3522                entry.executable().unwrap_or(false),
3523            ),
3524            CaptureEntryKind::Symlink => PathBinding::symlink_from_verified_producer(
3525                entry.path(),
3526                assignment.object_id.clone(),
3527                assigned_object_version_id(assignment)?,
3528                entry.symlink_target().ok_or_else(|| {
3529                    FolderbaseCaptureError::InvalidCaptureTransaction(format!(
3530                        "symlink CapturePlan entry has no target: {}",
3531                        entry.path()
3532                    ))
3533                })?,
3534            ),
3535        };
3536        bindings.push(binding);
3537    }
3538
3539    let exclusions = plan
3540        .exclusions()
3541        .iter()
3542        .map(|exclusion| {
3543            Exclusion::from_verified_producer(
3544                exclusion.path(),
3545                exclusion_kind(exclusion.kind()),
3546                exclusion_reason(exclusion.reason()),
3547            )
3548        })
3549        .collect();
3550    let tombstones = transaction.target_tombstones.clone();
3551    let parts = FolderbaseVersionParts::portable_v1_for_protocol_from_verified_producer(
3552        plan.folderbase_version_protocol(),
3553        plan.folderbase_id(),
3554        transaction.target_version_id.clone(),
3555        plan.current_local_head()
3556            .map(|head| vec![head.version_id().to_owned()])
3557            .unwrap_or_default(),
3558        transaction.created_at.clone(),
3559        RootManifest::from_verified_producer(
3560            assigned_root_manifest_version_id(transaction),
3561            plan.root_manifest_sha256(),
3562            plan.root_manifest_bytes(),
3563        ),
3564        FolderbaseVersionEntries::from_verified_producer(bindings, tombstones, exclusions),
3565    );
3566    let version = FolderbaseVersion::from_verified_parts(parts)?;
3567    let mut encoded = BoundedJsonWriter::new(maximum_version_bytes);
3568    let result = version.encode_bounded(&mut encoded);
3569    if encoded.exceeded {
3570        return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
3571            "future Folderbase Version envelope exceeds its bounded record limit".to_owned(),
3572        ));
3573    }
3574    result.map_err(|source| {
3575        FolderbaseCaptureError::InvalidCaptureTransaction(format!(
3576            "future Folderbase Version envelope could not be encoded: {source}"
3577        ))
3578    })?;
3579    Ok(())
3580}
3581
3582fn assigned_object_version_id(
3583    assignment: &CaptureAssignment,
3584) -> Result<String, FolderbaseCaptureError> {
3585    assignment
3586        .prior_object_version_id
3587        .clone()
3588        .or_else(|| assignment.candidate_object_version_id.clone())
3589        .ok_or_else(|| {
3590            FolderbaseCaptureError::InvalidCaptureTransaction(format!(
3591                "Object Version assignment is missing for {}",
3592                assignment.path
3593            ))
3594        })
3595}
3596
3597fn assigned_root_manifest_version_id(transaction: &CaptureTransaction) -> String {
3598    transaction
3599        .prior_root_manifest_version_id
3600        .clone()
3601        .unwrap_or_else(|| transaction.root_manifest_candidate_version_id.clone())
3602}
3603
3604fn build_and_install_capture(
3605    store: &FolderbaseVersionStore,
3606    plan: &CapturePlan,
3607    local: &LocalVersionStore,
3608    state: &FolderbaseState,
3609    transaction: &CaptureTransaction,
3610    prior: Option<&FolderbaseVersion>,
3611    checkpoint: &mut impl FnMut(&CaptureCheckpoint),
3612) -> Result<BuiltCapture, FolderbaseCaptureError> {
3613    let root_content = capture_root_manifest(store, plan, local, state, || {
3614        checkpoint(&CaptureCheckpoint::BeforeObjectBytesRead(
3615            ".folderbase/manifest.json".to_owned(),
3616        ));
3617    })?;
3618    let root_object_version_id = if prior.is_some_and(|version| {
3619        version.root_manifest().content_sha256() == root_content.digest
3620            && version.root_manifest().bytes() == root_content.bytes
3621    }) {
3622        let version_id = VersionId::parse(
3623            transaction
3624                .prior_root_manifest_version_id
3625                .clone()
3626                .ok_or_else(|| {
3627                    FolderbaseCaptureError::InvalidCaptureTransaction(
3628                        "prior root manifest assignment is missing".to_owned(),
3629                    )
3630                })?,
3631        )?;
3632        local.verify_capture_version_record_in(state, &version_id, &root_content)?;
3633        version_id
3634    } else {
3635        install_object_version(
3636            local,
3637            state,
3638            &transaction.root_manifest_object_id,
3639            &transaction.root_manifest_candidate_version_id,
3640            &root_content,
3641            &transaction.created_at,
3642        )?
3643    };
3644
3645    let mut bindings = Vec::with_capacity(plan.entries().len());
3646    let mut regular_projections = Vec::new();
3647    for (entry, assignment) in plan.entries().iter().zip(&transaction.assignments) {
3648        if assignment.path != entry.path()
3649            || assignment.kind != entry.kind()
3650            || assignment.observed != *entry.observed()
3651            || assignment.link_commitment != *entry.link_commitment()
3652        {
3653            return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
3654                "journal assignment does not match CapturePlan metadata".to_owned(),
3655            ));
3656        }
3657        match entry.kind() {
3658            CaptureEntryKind::Directory => {
3659                bindings.push(PathBinding::directory_from_verified_producer(
3660                    entry.path(),
3661                    assignment.object_id.clone(),
3662                ));
3663            }
3664            CaptureEntryKind::RegularFile => {
3665                let content = hash_regular_entry(
3666                    &store.root_attestation,
3667                    &store.root_instance_authority,
3668                    state,
3669                    entry,
3670                    Some(local),
3671                    checkpoint,
3672                )?;
3673                let prior_binding = prior.and_then(|version| {
3674                    version
3675                        .bindings()
3676                        .iter()
3677                        .find(|binding| binding.object_id() == assignment.object_id)
3678                });
3679                let object_version_id = if prior_binding.is_some_and(|binding| {
3680                    binding.object_id() == assignment.object_id
3681                        && binding.content_sha256() == Some(content.digest.as_str())
3682                        && binding.bytes() == Some(content.bytes)
3683                        && binding.executable() == entry.executable()
3684                }) {
3685                    let version_id = VersionId::parse(
3686                        assignment.prior_object_version_id.clone().ok_or_else(|| {
3687                            FolderbaseCaptureError::InvalidCaptureTransaction(format!(
3688                                "prior Object Version is missing for {}",
3689                                entry.path()
3690                            ))
3691                        })?,
3692                    )?;
3693                    let object_id = ObjectId::parse(assignment.object_id.clone())?;
3694                    local.verify_capture_object_version_in(
3695                        state,
3696                        &object_id,
3697                        &version_id,
3698                        &content,
3699                    )?;
3700                    version_id
3701                } else {
3702                    install_object_version(
3703                        local,
3704                        state,
3705                        &assignment.object_id,
3706                        assignment
3707                            .candidate_object_version_id
3708                            .as_deref()
3709                            .expect("regular assignment has Object Version"),
3710                        &content,
3711                        &transaction.created_at,
3712                    )?
3713                };
3714                bindings.push(PathBinding::regular_file_from_verified_producer(
3715                    entry.path(),
3716                    assignment.object_id.clone(),
3717                    object_version_id.to_string(),
3718                    content.digest.clone(),
3719                    content.bytes,
3720                    entry.executable().unwrap_or(false),
3721                ));
3722                if can_project_legacy_object(entry.path()) {
3723                    regular_projections.push(regular_projection(
3724                        local,
3725                        state,
3726                        assignment,
3727                        &object_version_id,
3728                        prior_binding.and_then(|binding| binding.object_version_id()),
3729                        &transaction.created_at,
3730                    )?);
3731                }
3732            }
3733            CaptureEntryKind::Symlink => {
3734                verify_symlink_entry(&store.root_attestation.root, entry)?;
3735                let target = entry.symlink_target().expect("planned symlink");
3736                let content = local.install_content_bytes_in(state, target.as_bytes())?;
3737                let prior_binding = prior.and_then(|version| {
3738                    version
3739                        .bindings()
3740                        .iter()
3741                        .find(|binding| binding.object_id() == assignment.object_id)
3742                });
3743                let object_version_id = if prior_binding.is_some_and(|binding| {
3744                    binding.object_id() == assignment.object_id
3745                        && binding.symlink_target() == Some(target)
3746                }) {
3747                    let version_id = VersionId::parse(
3748                        assignment.prior_object_version_id.clone().ok_or_else(|| {
3749                            FolderbaseCaptureError::InvalidCaptureTransaction(format!(
3750                                "prior symlink Object Version is missing for {}",
3751                                entry.path()
3752                            ))
3753                        })?,
3754                    )?;
3755                    let object_id = ObjectId::parse(assignment.object_id.clone())?;
3756                    local.verify_capture_object_version_in(
3757                        state,
3758                        &object_id,
3759                        &version_id,
3760                        &content,
3761                    )?;
3762                    version_id
3763                } else {
3764                    install_object_version(
3765                        local,
3766                        state,
3767                        &assignment.object_id,
3768                        assignment
3769                            .candidate_object_version_id
3770                            .as_deref()
3771                            .expect("symlink assignment has Object Version"),
3772                        &content,
3773                        &transaction.created_at,
3774                    )?
3775                };
3776                bindings.push(PathBinding::symlink_from_verified_producer(
3777                    entry.path(),
3778                    assignment.object_id.clone(),
3779                    object_version_id.to_string(),
3780                    target,
3781                ));
3782            }
3783        }
3784    }
3785
3786    let exclusions = plan
3787        .exclusions()
3788        .iter()
3789        .map(|exclusion| {
3790            Exclusion::from_verified_producer(
3791                exclusion.path(),
3792                exclusion_kind(exclusion.kind()),
3793                exclusion_reason(exclusion.reason()),
3794            )
3795        })
3796        .collect();
3797    let tombstones = transaction.target_tombstones.clone();
3798    let parts = FolderbaseVersionParts::portable_v1_for_protocol_from_verified_producer(
3799        plan.folderbase_version_protocol(),
3800        plan.folderbase_id(),
3801        transaction.target_version_id.clone(),
3802        plan.current_local_head()
3803            .map(|head| vec![head.version_id().to_owned()])
3804            .unwrap_or_default(),
3805        transaction.created_at.clone(),
3806        RootManifest::from_verified_producer(
3807            root_object_version_id.to_string(),
3808            root_content.digest,
3809            root_content.bytes,
3810        ),
3811        FolderbaseVersionEntries::from_verified_producer(bindings, tombstones, exclusions),
3812    );
3813    let version = FolderbaseVersion::from_verified_parts(parts)?;
3814    let version_sha256 = version.canonical_digest()?;
3815    Ok(BuiltCapture {
3816        version,
3817        version_sha256,
3818        regular_projections,
3819    })
3820}
3821
3822fn capture_root_manifest(
3823    store: &FolderbaseVersionStore,
3824    plan: &CapturePlan,
3825    local: &LocalVersionStore,
3826    state: &FolderbaseState,
3827    before_read: impl FnOnce(),
3828) -> Result<ContentDigest, FolderbaseCaptureError> {
3829    let relative = Path::new(".folderbase/manifest.json");
3830    let mut file = open_regular_beneath(&store.root_attestation.root, relative)?;
3831    let display = store.root_attestation.root.join(relative);
3832    let before = fingerprint_std_file(&file, &display)?;
3833    before_read();
3834    let content = local
3835        .install_content_reader_in(
3836            state,
3837            &mut file,
3838            &store.root_attestation.root.join(relative),
3839            plan.root_manifest_bytes(),
3840        )
3841        .map_err(|source| bounded_source_error(source, relative))?;
3842    let after = fingerprint_std_file(&file, &display)?;
3843    let reopened = open_regular_beneath(&store.root_attestation.root, relative)?;
3844    let reopened_fingerprint = fingerprint_std_file(&reopened, &display)?;
3845    if before != after
3846        || before != reopened_fingerprint
3847        || content.bytes != plan.root_manifest_bytes()
3848        || content.digest != plan.root_manifest_sha256()
3849    {
3850        return Err(FolderbaseCaptureError::CaptureStateChanged(
3851            relative.to_path_buf(),
3852        ));
3853    }
3854    Ok(content)
3855}
3856
3857fn hash_regular_entry(
3858    root_attestation: &FolderbaseRootAttestation,
3859    root_instance_authority: &crate::root_attestation::RootInstanceAuthority,
3860    state: &FolderbaseState,
3861    entry: &CapturePlanEntry,
3862    installer: Option<&LocalVersionStore>,
3863    checkpoint: &mut impl FnMut(&CaptureCheckpoint),
3864) -> Result<ContentDigest, FolderbaseCaptureError> {
3865    let relative = Path::new(entry.path());
3866    let display = root_attestation.root.join(relative);
3867    let mut file = open_regular_beneath(&root_attestation.root, relative)?;
3868    let before = fingerprint_std_file(&file, &display)?;
3869    if before != *entry.observed() {
3870        return Err(FolderbaseCaptureError::CaptureStateChanged(
3871            relative.to_path_buf(),
3872        ));
3873    }
3874    checkpoint(&CaptureCheckpoint::BeforeObjectBytesRead(
3875        entry.path().to_owned(),
3876    ));
3877    verify_capture_link_commitment(
3878        root_attestation,
3879        root_instance_authority,
3880        state,
3881        entry,
3882        &file,
3883    )?;
3884    let content = match installer {
3885        Some(local) => local
3886            .install_content_reader_in(
3887                state,
3888                &mut file,
3889                &display,
3890                entry.bytes().expect("planned regular length"),
3891            )
3892            .map_err(|source| bounded_source_error(source, relative))?,
3893        None => hash_reader(
3894            &mut file,
3895            &display,
3896            entry.bytes().expect("planned regular length"),
3897        )
3898        .map_err(|source| bounded_source_error(source, relative))?,
3899    };
3900    checkpoint(&CaptureCheckpoint::AfterObjectBytesRead(
3901        entry.path().to_owned(),
3902    ));
3903    verify_capture_link_commitment(
3904        root_attestation,
3905        root_instance_authority,
3906        state,
3907        entry,
3908        &file,
3909    )?;
3910    let after = fingerprint_std_file(&file, &display)?;
3911    let reopened = open_regular_beneath(&root_attestation.root, relative)?;
3912    let reopened_fingerprint = fingerprint_std_file(&reopened, &display)?;
3913    if after != *entry.observed()
3914        || reopened_fingerprint != *entry.observed()
3915        || content.bytes != entry.bytes().expect("planned regular length")
3916    {
3917        return Err(FolderbaseCaptureError::CaptureStateChanged(
3918            relative.to_path_buf(),
3919        ));
3920    }
3921    Ok(content)
3922}
3923
3924fn bounded_source_error(error: FolderbaseError, path: &Path) -> FolderbaseCaptureError {
3925    match error {
3926        FolderbaseError::InvalidRecord { ref message, .. }
3927            if message.contains("grew beyond its approved byte length") =>
3928        {
3929            FolderbaseCaptureError::CaptureStateChanged(path.to_path_buf())
3930        }
3931        error => FolderbaseCaptureError::LocalStore(error),
3932    }
3933}
3934
3935fn fingerprint_std_file(
3936    file: &File,
3937    display: &Path,
3938) -> Result<CaptureMetadataFingerprint, FolderbaseCaptureError> {
3939    CaptureMetadataFingerprint::from_std_file(file).map_err(|source| FolderbaseCaptureError::Io {
3940        path: display.to_path_buf(),
3941        source,
3942    })
3943}
3944
3945fn install_object_version(
3946    local: &LocalVersionStore,
3947    state: &FolderbaseState,
3948    object_id: &str,
3949    version_id: &str,
3950    content: &ContentDigest,
3951    captured_at: &str,
3952) -> Result<VersionId, FolderbaseCaptureError> {
3953    let object_id = ObjectId::parse(object_id.to_owned())?;
3954    let version_id = VersionId::parse(version_id.to_owned())?;
3955    let record = LocalVersionRecord {
3956        id: version_id.clone(),
3957        object_id: object_id.clone(),
3958        content: content.clone(),
3959        captured_at: captured_at.to_owned(),
3960        extensions: BTreeMap::new(),
3961    };
3962    local.install_or_verify_version_record_in(state, &record)?;
3963    local.verify_capture_object_version_in(state, &object_id, &version_id, content)?;
3964    Ok(version_id)
3965}
3966
3967fn regular_projection(
3968    local: &LocalVersionStore,
3969    state: &FolderbaseState,
3970    assignment: &CaptureAssignment,
3971    current_version: &VersionId,
3972    prior_version: Option<&str>,
3973    captured_at: &str,
3974) -> Result<LocalObjectRecord, FolderbaseCaptureError> {
3975    let object_id = ObjectId::parse(assignment.object_id.clone())?;
3976    let existing = local.read_capture_object_projection_in(state, &object_id)?;
3977    let mut record = existing.unwrap_or_else(|| {
3978        let mut versions = prior_version
3979            .map(|value| VersionId::parse(value.to_owned()).expect("verified prior version"))
3980            .into_iter()
3981            .collect::<Vec<_>>();
3982        if !versions.contains(current_version) {
3983            versions.push(current_version.clone());
3984        }
3985        LocalObjectRecord {
3986            schema: "https://folderbase.ai/protocol/0.1/object.schema.json".to_owned(),
3987            id: object_id.clone(),
3988            object_type: "file".to_owned(),
3989            path: assignment.path.clone(),
3990            lifecycle: ObjectLifecycle {
3991                status: "canonical".to_owned(),
3992                extensions: BTreeMap::new(),
3993            },
3994            provenance: ObjectProvenance {
3995                created_at: captured_at.to_owned(),
3996                source: "folderbase-version-capture".to_owned(),
3997                extensions: BTreeMap::new(),
3998            },
3999            current_version: current_version.clone(),
4000            versions,
4001            extensions: BTreeMap::new(),
4002        }
4003    });
4004    if record.id != object_id {
4005        return Err(FolderbaseCaptureError::InvalidPriorLocalHead(format!(
4006            "object projection for {} has the wrong stable ID",
4007            assignment.path
4008        )));
4009    }
4010    record.path.clone_from(&assignment.path);
4011    if !record.versions.contains(current_version) {
4012        record.versions.push(current_version.clone());
4013    }
4014    record.current_version = current_version.clone();
4015    Ok(record)
4016}
4017
4018fn can_project_legacy_object(path: &str) -> bool {
4019    !Path::new(path).components().any(|component| {
4020        matches!(
4021            component,
4022            Component::Normal(name)
4023                if name.to_str().is_some_and(|name| {
4024                    name.eq_ignore_ascii_case(".git")
4025                        || name.eq_ignore_ascii_case(".folderbase")
4026                })
4027        )
4028    })
4029}
4030
4031fn verify_symlink_entry(
4032    root: &Path,
4033    entry: &CapturePlanEntry,
4034) -> Result<(), FolderbaseCaptureError> {
4035    let relative = Path::new(entry.path());
4036    let (parent, name) = open_parent_beneath(root, relative)?;
4037    let display = root.join(relative);
4038    let metadata = parent
4039        .symlink_metadata(&name)
4040        .map_err(|source| FolderbaseCaptureError::Io {
4041            path: display.clone(),
4042            source,
4043        })?;
4044    let target = parent
4045        .read_link(&name)
4046        .map_err(|source| FolderbaseCaptureError::Io {
4047            path: display.clone(),
4048            source,
4049        })?;
4050    let rechecked = parent
4051        .read_link(&name)
4052        .map_err(|source| FolderbaseCaptureError::Io {
4053            path: display,
4054            source,
4055        })?;
4056    if !metadata.file_type().is_symlink()
4057        || capture_entry_fingerprint(
4058            &parent,
4059            &name,
4060            CaptureEntryKind::Symlink,
4061            &metadata,
4062            &root.join(relative),
4063        )? != *entry.observed()
4064        || target != rechecked
4065        || target.to_str() != entry.symlink_target()
4066    {
4067        return Err(FolderbaseCaptureError::CaptureStateChanged(
4068            relative.to_path_buf(),
4069        ));
4070    }
4071    Ok(())
4072}
4073
4074fn exclusion_kind(kind: CaptureExclusionKind) -> ExclusionKind {
4075    match kind {
4076        CaptureExclusionKind::NestedFolderbase => ExclusionKind::NestedFolderbase,
4077        CaptureExclusionKind::HardLink => ExclusionKind::HardLink,
4078        CaptureExclusionKind::Fifo => ExclusionKind::Fifo,
4079        CaptureExclusionKind::Socket => ExclusionKind::Socket,
4080        CaptureExclusionKind::BlockDevice => ExclusionKind::BlockDevice,
4081        CaptureExclusionKind::CharacterDevice => ExclusionKind::CharacterDevice,
4082        CaptureExclusionKind::OtherSpecial => ExclusionKind::OtherSpecial,
4083    }
4084}
4085
4086fn exclusion_reason(reason: CaptureExclusionReason) -> ExclusionReason {
4087    match reason {
4088        CaptureExclusionReason::NestedFolderbaseBoundary => {
4089            ExclusionReason::NestedFolderbaseBoundary
4090        }
4091        CaptureExclusionReason::UnsupportedV1 => ExclusionReason::UnsupportedV1,
4092    }
4093}
4094
4095fn hash_reader(
4096    mut reader: impl Read,
4097    path: &Path,
4098    maximum_bytes: u64,
4099) -> Result<ContentDigest, FolderbaseError> {
4100    let mut digest = Sha256::new();
4101    let mut bytes = 0_u64;
4102    let mut buffer = [0_u8; IO_BUFFER_BYTES];
4103    let mut bounded = reader.by_ref().take(maximum_bytes.saturating_add(1));
4104    loop {
4105        let read = bounded
4106            .read(&mut buffer)
4107            .map_err(|source| FolderbaseError::io(path, source))?;
4108        if read == 0 {
4109            break;
4110        }
4111        bytes = bytes
4112            .checked_add(read as u64)
4113            .ok_or_else(|| FolderbaseError::InvalidRecord {
4114                path: path.to_path_buf(),
4115                message: "content length exceeds supported range".to_owned(),
4116            })?;
4117        if bytes > maximum_bytes {
4118            return Err(FolderbaseError::InvalidRecord {
4119                path: path.to_path_buf(),
4120                message: "source grew beyond its approved byte length".to_owned(),
4121            });
4122        }
4123        digest.update(&buffer[..read]);
4124    }
4125    Ok(ContentDigest {
4126        algorithm: "sha256".to_owned(),
4127        digest: format!("{:x}", digest.finalize()),
4128        bytes,
4129    })
4130}
4131
4132fn content_digest(bytes: &[u8]) -> ContentDigest {
4133    ContentDigest {
4134        algorithm: "sha256".to_owned(),
4135        digest: format!("{:x}", Sha256::digest(bytes)),
4136        bytes: bytes.len() as u64,
4137    }
4138}
4139
4140fn read_and_verify_folderbase_version(
4141    store: &FolderbaseVersionStore,
4142    local: &LocalVersionStore,
4143    state: &FolderbaseState,
4144    version_id: &str,
4145) -> Result<FolderbaseVersion, FolderbaseCaptureError> {
4146    validate_capture_version_id(version_id)?;
4147    let relative = folderbase_version_relative_path(version_id);
4148    let encoded = state
4149        .read_bounded(&relative, MAX_ENCODED_VERSION_BYTES)?
4150        .ok_or_else(|| {
4151            FolderbaseCaptureError::InvalidPriorLocalHead("version is missing".to_owned())
4152        })?;
4153    let version = FolderbaseVersion::decode_bounded(encoded.as_slice())?;
4154    if version.version_id() != version_id
4155        || version.folderbase_id() != store.root_attestation.folderbase_id
4156    {
4157        return Err(FolderbaseCaptureError::InvalidPriorLocalHead(
4158            "Folderbase Version ID or Folderbase membership does not match its path".to_owned(),
4159        ));
4160    }
4161    verify_version_references(local, state, &version)?;
4162    Ok(version)
4163}
4164
4165fn verify_version_references(
4166    local: &LocalVersionStore,
4167    state: &FolderbaseState,
4168    version: &FolderbaseVersion,
4169) -> Result<(), FolderbaseCaptureError> {
4170    let root_content = ContentDigest {
4171        algorithm: "sha256".to_owned(),
4172        digest: version.root_manifest().content_sha256().to_owned(),
4173        bytes: version.root_manifest().bytes(),
4174    };
4175    local.verify_capture_version_record_in(
4176        state,
4177        &VersionId::parse(version.root_manifest().object_version_id().to_owned())?,
4178        &root_content,
4179    )?;
4180    for binding in version.bindings() {
4181        match binding.kind() {
4182            PathBindingKind::Directory => {}
4183            PathBindingKind::RegularFile => {
4184                let content = ContentDigest {
4185                    algorithm: "sha256".to_owned(),
4186                    digest: binding.content_sha256().expect("regular digest").to_owned(),
4187                    bytes: binding.bytes().expect("regular bytes"),
4188                };
4189                local.verify_capture_object_version_in(
4190                    state,
4191                    &ObjectId::parse(binding.object_id().to_owned())?,
4192                    &VersionId::parse(
4193                        binding
4194                            .object_version_id()
4195                            .expect("regular version")
4196                            .to_owned(),
4197                    )?,
4198                    &content,
4199                )?;
4200            }
4201            PathBindingKind::Symlink => {
4202                let content =
4203                    content_digest(binding.symlink_target().expect("symlink target").as_bytes());
4204                local.verify_capture_object_version_in(
4205                    state,
4206                    &ObjectId::parse(binding.object_id().to_owned())?,
4207                    &VersionId::parse(
4208                        binding
4209                            .object_version_id()
4210                            .expect("symlink version")
4211                            .to_owned(),
4212                    )?,
4213                    &content,
4214                )?;
4215            }
4216        }
4217    }
4218    for tombstone in version.tombstones() {
4219        if let Some(version_id) = tombstone.last_object_version_id() {
4220            local.verify_capture_record_integrity_in(
4221                state,
4222                &ObjectId::parse(tombstone.object_id().to_owned())?,
4223                &VersionId::parse(version_id.to_owned())?,
4224            )?;
4225        }
4226    }
4227    Ok(())
4228}
4229
4230fn install_folderbase_version(
4231    state: &FolderbaseState,
4232    version: &FolderbaseVersion,
4233    expected_sha256: &str,
4234) -> Result<(), FolderbaseCaptureError> {
4235    let mut encoded = Vec::new();
4236    version.encode_bounded(&mut encoded)?;
4237    let relative = folderbase_version_relative_path(version.version_id());
4238    match state.publish_new(&relative, &encoded) {
4239        Ok(()) => {}
4240        Err(FolderbaseError::WouldOverwrite(_)) => {
4241            let existing = state
4242                .read_bounded(&relative, MAX_ENCODED_VERSION_BYTES)?
4243                .ok_or_else(|| {
4244                    FolderbaseCaptureError::InvalidCaptureTransaction(
4245                        "append-only Folderbase Version disappeared".to_owned(),
4246                    )
4247                })?;
4248            if existing != encoded {
4249                return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
4250                    "append-only Folderbase Version ID already names different bytes".to_owned(),
4251                ));
4252            }
4253        }
4254        Err(error) => return Err(error.into()),
4255    }
4256    let installed = FolderbaseVersion::decode_bounded(
4257        state
4258            .read_bounded(&relative, MAX_ENCODED_VERSION_BYTES)?
4259            .ok_or_else(|| {
4260                FolderbaseCaptureError::InvalidCaptureTransaction(
4261                    "installed Folderbase Version is missing".to_owned(),
4262                )
4263            })?
4264            .as_slice(),
4265    )?;
4266    if installed.canonical_digest()? != expected_sha256 {
4267        return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
4268            "installed Folderbase Version failed digest verification".to_owned(),
4269        ));
4270    }
4271    Ok(())
4272}
4273
4274/// Install one reconstructed history closure in the same order used by
4275/// capture sealing: immutable Object Versions, immutable Folderbase Version,
4276/// verified version-derived Local Head, then mutable Object projections.
4277///
4278/// The caller owns package-byte verification and the reconstruction journal;
4279/// this helper owns the invariant that no Local Head can name incomplete
4280/// history.
4281pub(crate) fn install_reconstructed_history(
4282    local: &LocalVersionStore,
4283    state: &FolderbaseState,
4284    root_attestation: &FolderbaseRootAttestation,
4285    version: &FolderbaseVersion,
4286    expected_version_sha256: &str,
4287    history: &ReconstructedHistoryClosure,
4288) -> Result<(), FolderbaseCaptureError> {
4289    prepare_reconstructed_history(state)?;
4290    for record in &history.object_versions {
4291        local.install_or_verify_version_record_in(state, record)?;
4292        local.verify_capture_version_record_in(state, &record.id, &record.content)?;
4293    }
4294    for association in &history.tombstone_associations {
4295        install_reconstructed_tombstone_association(state, association)?;
4296    }
4297
4298    install_folderbase_version(state, version, expected_version_sha256)?;
4299    verify_version_references(local, state, version)?;
4300
4301    let target_head = LocalHeadRecord {
4302        format: "folderbase-local-head-v2".to_owned(),
4303        folderbase_id: root_attestation.folderbase_id.clone(),
4304        root_instance_sha256: root_attestation.root_instance_sha256.clone(),
4305        version_id: version.version_id().to_owned(),
4306        version_sha256: expected_version_sha256.to_owned(),
4307        authority: LocalHeadAuthority::VersionDerivedV1 {
4308            sha256: version_derived_local_head_sha256(
4309                &root_attestation.folderbase_id,
4310                &root_attestation.root_instance_sha256,
4311                version.version_id(),
4312                expected_version_sha256,
4313            )?,
4314        },
4315    };
4316    match read_head_record(state)? {
4317        None => state.replace(Path::new(LOCAL_HEAD_PATH), &json_bytes(&target_head)?)?,
4318        Some(existing) if existing == target_head => {}
4319        Some(_) => {
4320            return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
4321                "reconstructed Local Head conflicts with retained staged history".to_owned(),
4322            ));
4323        }
4324    }
4325    if read_head_record(state)?.as_ref() != Some(&target_head) {
4326        return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
4327            "reconstructed Local Head did not verify".to_owned(),
4328        ));
4329    }
4330    verify_version_references(local, state, version)?;
4331
4332    for projection in &history.object_projections {
4333        local.write_capture_object_projection_in(state, projection)?;
4334    }
4335    Ok(())
4336}
4337
4338/// Prepare the one retained state layout required before reconstructed object
4339/// bytes or history records can be installed. Ordering is significant because
4340/// every intermediate directory is created and durably verified before its
4341/// children.
4342pub(crate) fn prepare_reconstructed_history(
4343    state: &FolderbaseState,
4344) -> Result<(), FolderbaseCaptureError> {
4345    LocalVersionStore::prepare_store_layout_in(state)?;
4346    for relative in [
4347        ".folderbase/versions",
4348        ".folderbase/versions/blobs",
4349        FOLDERBASE_VERSIONS_DIRECTORY,
4350        ".folderbase/local",
4351        CAPTURE_TRANSACTIONS_DIRECTORY,
4352        CAPTURE_IDENTITIES_DIRECTORY,
4353        ".folderbase/local/root-reconstruction",
4354        RECONSTRUCTED_TOMBSTONE_ASSOCIATIONS_DIRECTORY,
4355    ] {
4356        state.ensure_private_dir(Path::new(relative))?;
4357    }
4358    Ok(())
4359}
4360
4361fn reconstructed_tombstone_association_relative_path(
4362    path: &str,
4363    object_id: &str,
4364    version_id: &str,
4365) -> PathBuf {
4366    let mut digest = Sha256::new();
4367    digest.update(b"folderbase-reconstructed-tombstone-association-path-v1\0");
4368    digest.update(path.as_bytes());
4369    digest.update(b"\0");
4370    digest.update(object_id.as_bytes());
4371    digest.update(b"\0");
4372    digest.update(version_id.as_bytes());
4373    Path::new(RECONSTRUCTED_TOMBSTONE_ASSOCIATIONS_DIRECTORY)
4374        .join(format!("{:x}.json", digest.finalize()))
4375}
4376
4377fn install_reconstructed_tombstone_association(
4378    state: &FolderbaseState,
4379    association: &ReconstructedTombstoneAssociation,
4380) -> Result<(), FolderbaseCaptureError> {
4381    validate_capture_path(&association.path)?;
4382    let object_id = ObjectId::parse(association.object_id.clone())?;
4383    let version_id = VersionId::parse(association.object_version_id.clone())?;
4384    if association.format != RECONSTRUCTED_TOMBSTONE_ASSOCIATION_FORMAT_V1
4385        || !is_lowercase_sha256(&association.content_sha256)
4386    {
4387        return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
4388            "reconstructed Tombstone association is invalid".to_owned(),
4389        ));
4390    }
4391    let relative = reconstructed_tombstone_association_relative_path(
4392        &association.path,
4393        object_id.as_str(),
4394        version_id.as_str(),
4395    );
4396    let encoded = json_bytes(association)?;
4397    match state.publish_new(&relative, &encoded) {
4398        Ok(()) => {}
4399        Err(FolderbaseError::WouldOverwrite(_)) => {
4400            if state
4401                .read_bounded(&relative, MAX_ENCODED_VERSION_BYTES)?
4402                .as_deref()
4403                != Some(encoded.as_slice())
4404            {
4405                return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
4406                    "reconstructed Tombstone association conflicts with retained state".to_owned(),
4407                ));
4408            }
4409        }
4410        Err(error) => return Err(error.into()),
4411    }
4412    Ok(())
4413}
4414
4415fn read_reconstructed_tombstone_association(
4416    local: &LocalVersionStore,
4417    state: &FolderbaseState,
4418    tombstone: &Tombstone,
4419    expected_version: &str,
4420) -> Result<Option<ReconstructedTombstoneAssociation>, FolderbaseCaptureError> {
4421    let version_id = VersionId::parse(expected_version.to_owned())?;
4422    let relative = reconstructed_tombstone_association_relative_path(
4423        tombstone.path(),
4424        tombstone.object_id(),
4425        expected_version,
4426    );
4427    let Some(encoded) = state.read_bounded(&relative, MAX_ENCODED_VERSION_BYTES)? else {
4428        return Ok(None);
4429    };
4430    let association: ReconstructedTombstoneAssociation =
4431        serde_json::from_slice(&encoded).map_err(|source| {
4432            FolderbaseCaptureError::InvalidRestoreAncestry(format!(
4433                "reconstructed Tombstone association JSON is invalid: {source}"
4434            ))
4435        })?;
4436    if json_bytes(&association)? != encoded
4437        || association.format != RECONSTRUCTED_TOMBSTONE_ASSOCIATION_FORMAT_V1
4438        || association.path != tombstone.path()
4439        || association.object_id != tombstone.object_id()
4440        || association.object_version_id != expected_version
4441        || !is_lowercase_sha256(&association.content_sha256)
4442    {
4443        return Err(FolderbaseCaptureError::InvalidRestoreAncestry(
4444            "reconstructed Tombstone association does not match the current Tombstone".to_owned(),
4445        ));
4446    }
4447    let content = ContentDigest {
4448        algorithm: "sha256".to_owned(),
4449        digest: association.content_sha256.clone(),
4450        bytes: association.bytes,
4451    };
4452    local.verify_capture_object_version_in(
4453        state,
4454        &ObjectId::parse(tombstone.object_id().to_owned())?,
4455        &version_id,
4456        &content,
4457    )?;
4458    Ok(Some(association))
4459}
4460
4461fn folderbase_version_relative_path(version_id: &str) -> PathBuf {
4462    Path::new(FOLDERBASE_VERSIONS_DIRECTORY).join(format!("{version_id}.json"))
4463}
4464
4465fn validate_transaction(
4466    store: &FolderbaseVersionStore,
4467    transaction: &CaptureTransaction,
4468) -> Result<(), FolderbaseCaptureError> {
4469    let aggregate_entries = transaction
4470        .assignments
4471        .len()
4472        .checked_add(transaction.target_tombstones.len())
4473        .ok_or_else(|| {
4474            FolderbaseCaptureError::InvalidCaptureTransaction(
4475                "active journal entry aggregate exceeds the supported range".to_owned(),
4476            )
4477        })?;
4478    if transaction.format != CAPTURE_TRANSACTION_FORMAT_V1
4479        || !transaction.transaction_id.starts_with("fbcapture_")
4480        || Uuid::parse_str(
4481            transaction
4482                .transaction_id
4483                .strip_prefix("fbcapture_")
4484                .unwrap_or_default(),
4485        )
4486        .is_err()
4487        || transaction.folderbase_id != store.root_attestation.folderbase_id
4488        || store
4489            .root_instance_authority
4490            .admit(&transaction.root_instance_sha256)
4491            .is_none()
4492        || transaction.plan_sha256.len() != 64
4493        || aggregate_entries > crate::folderbase_version::MAX_VERSION_ENTRIES
4494    {
4495        return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
4496            "active journal metadata or entry aggregate is inconsistent".to_owned(),
4497        ));
4498    }
4499    validate_capture_version_id(&transaction.target_version_id)?;
4500    ObjectId::parse(transaction.root_manifest_object_id.clone())?;
4501    VersionId::parse(transaction.root_manifest_candidate_version_id.clone())?;
4502    let mut previous = None;
4503    for assignment in &transaction.assignments {
4504        if previous.is_some_and(|value: &str| value.as_bytes() >= assignment.path.as_bytes()) {
4505            return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
4506                "journal assignments are not in strict portable-path order".to_owned(),
4507            ));
4508        }
4509        ObjectId::parse(assignment.object_id.clone())?;
4510        match (
4511            assignment.kind,
4512            assignment.candidate_object_version_id.as_deref(),
4513        ) {
4514            (CaptureEntryKind::Directory, None) => {}
4515            (CaptureEntryKind::RegularFile | CaptureEntryKind::Symlink, Some(version_id)) => {
4516                VersionId::parse(version_id.to_owned())?;
4517            }
4518            _ => {
4519                return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
4520                    "journal Object Version assignment does not match entry kind".to_owned(),
4521                ));
4522            }
4523        }
4524        if let Some(version_id) = &assignment.prior_object_version_id {
4525            VersionId::parse(version_id.clone())?;
4526        }
4527        if !assignment.link_commitment.is_well_formed()
4528            || (assignment.kind != CaptureEntryKind::RegularFile
4529                && !assignment.link_commitment.is_legacy_default())
4530        {
4531            return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
4532                "journal link commitment is malformed or belongs to a non-regular entry".to_owned(),
4533            ));
4534        }
4535        previous = Some(assignment.path.as_str());
4536    }
4537    let mut previous = None;
4538    for tombstone in &transaction.target_tombstones {
4539        if previous.is_some_and(|value: &str| value.as_bytes() >= tombstone.path().as_bytes()) {
4540            return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
4541                "journal Tombstones are not in strict portable-path order".to_owned(),
4542            ));
4543        }
4544        ObjectId::parse(tombstone.object_id().to_owned())?;
4545        match (tombstone.deleted_kind(), tombstone.last_object_version_id()) {
4546            (DeletedKind::Directory, None) => {}
4547            (DeletedKind::RegularFile | DeletedKind::Symlink, Some(version_id)) => {
4548                VersionId::parse(version_id.to_owned())?;
4549            }
4550            _ => {
4551                return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
4552                    "journal Tombstone Object Version does not match its deleted kind".to_owned(),
4553                ));
4554            }
4555        }
4556        previous = Some(tombstone.path());
4557    }
4558    Ok(())
4559}
4560
4561fn validate_transaction_against_plan(
4562    plan: &CapturePlan,
4563    transaction: &CaptureTransaction,
4564    prior: Option<&FolderbaseVersion>,
4565) -> Result<(), FolderbaseCaptureError> {
4566    if transaction.assignments.len() != plan.entries().len() {
4567        return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
4568            "journal assignment count does not match the approved CapturePlan".to_owned(),
4569        ));
4570    }
4571    let prior_bindings = prior
4572        .map(|version| {
4573            version
4574                .bindings()
4575                .iter()
4576                .map(|binding| (binding.path(), binding))
4577                .collect::<BTreeMap<_, _>>()
4578        })
4579        .unwrap_or_default();
4580    for (entry, assignment) in plan.entries().iter().zip(&transaction.assignments) {
4581        if assignment.path != entry.path()
4582            || assignment.kind != entry.kind()
4583            || assignment.observed != *entry.observed()
4584            || assignment.link_commitment != *entry.link_commitment()
4585        {
4586            return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
4587                "journal assignment does not exactly match the approved CapturePlan".to_owned(),
4588            ));
4589        }
4590        let prior_binding = prior
4591            .and_then(|version| {
4592                version
4593                    .bindings()
4594                    .iter()
4595                    .find(|binding| binding.object_id() == assignment.object_id)
4596            })
4597            .or_else(|| prior_bindings.get(entry.path()).copied());
4598        match prior_binding {
4599            Some(binding)
4600                if assignment.reused_object
4601                    && binding.kind() == path_binding_kind(entry.kind())
4602                    && assignment.object_id == binding.object_id()
4603                    && assignment.prior_object_version_id.as_deref()
4604                        == binding.object_version_id() => {}
4605            Some(binding)
4606                if !assignment.reused_object
4607                    && binding.kind() != path_binding_kind(entry.kind())
4608                    && assignment.object_id != binding.object_id()
4609                    && assignment.prior_object_version_id.is_none() => {}
4610            None if !assignment.reused_object && assignment.prior_object_version_id.is_none() => {}
4611            _ => {
4612                return Err(FolderbaseCaptureError::InvalidCaptureTransaction(format!(
4613                    "journal identity lineage does not match the verified parent at {}",
4614                    entry.path()
4615                )));
4616            }
4617        }
4618    }
4619    if transaction.target_tombstones != project_target_tombstones(prior, &transaction.assignments) {
4620        return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
4621            "journal Tombstones do not match the verified parent and approved CapturePlan"
4622                .to_owned(),
4623        ));
4624    }
4625    let expected_prior_root = prior.map(|version| version.root_manifest().object_version_id());
4626    if transaction.prior_root_manifest_version_id.as_deref() != expected_prior_root {
4627        return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
4628            "journal root-manifest lineage does not match the verified parent".to_owned(),
4629        ));
4630    }
4631    Ok(())
4632}
4633
4634fn validate_committed_transaction(
4635    transaction: &CaptureTransaction,
4636    committed: &FolderbaseVersion,
4637    prior: Option<&FolderbaseVersion>,
4638) -> Result<(), FolderbaseCaptureError> {
4639    let expected_parents = transaction
4640        .expected_head
4641        .as_ref()
4642        .map(|head| vec![head.version_id.clone()])
4643        .unwrap_or_default();
4644    if committed.version_id() != transaction.target_version_id
4645        || committed.bindings().len() != transaction.assignments.len()
4646        || committed.tombstones() != transaction.target_tombstones
4647        || committed.parents() != expected_parents
4648        || committed.created_at() != transaction.created_at
4649    {
4650        return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
4651            "committed Folderbase Version does not match its active journal".to_owned(),
4652        ));
4653    }
4654    let prior_bindings = prior
4655        .map(|version| {
4656            version
4657                .bindings()
4658                .iter()
4659                .map(|binding| (binding.path(), binding))
4660                .collect::<BTreeMap<_, _>>()
4661        })
4662        .unwrap_or_default();
4663    for (binding, assignment) in committed.bindings().iter().zip(&transaction.assignments) {
4664        if binding.path() != assignment.path
4665            || binding.kind() != path_binding_kind(assignment.kind)
4666            || binding.object_id() != assignment.object_id
4667        {
4668            return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
4669                "committed binding does not match its active journal".to_owned(),
4670            ));
4671        }
4672        let expected_version = match (
4673            prior_bindings.get(binding.path()).copied(),
4674            assignment.reused_object,
4675        ) {
4676            (Some(parent), true)
4677                if parent.kind() == binding.kind()
4678                    && parent.object_id() == assignment.object_id
4679                    && parent.object_version_id()
4680                        == assignment.prior_object_version_id.as_deref() =>
4681            {
4682                if binding.object_version_id() == parent.object_version_id() {
4683                    assignment.prior_object_version_id.as_deref()
4684                } else {
4685                    assignment.candidate_object_version_id.as_deref()
4686                }
4687            }
4688            (Some(parent), false)
4689                if parent.kind() != binding.kind()
4690                    && parent.object_id() != assignment.object_id
4691                    && assignment.prior_object_version_id.is_none() =>
4692            {
4693                assignment.candidate_object_version_id.as_deref()
4694            }
4695            (None, false) if assignment.prior_object_version_id.is_none() => {
4696                assignment.candidate_object_version_id.as_deref()
4697            }
4698            _ => {
4699                return Err(FolderbaseCaptureError::InvalidCaptureTransaction(format!(
4700                    "committed identity lineage does not match the verified parent at {}",
4701                    binding.path()
4702                )));
4703            }
4704        };
4705        if binding.object_version_id() != expected_version {
4706            return Err(FolderbaseCaptureError::InvalidCaptureTransaction(format!(
4707                "committed Object Version does not match its journal assignment at {}",
4708                binding.path()
4709            )));
4710        }
4711    }
4712    let expected_prior_root = prior.map(|version| version.root_manifest().object_version_id());
4713    if transaction.prior_root_manifest_version_id.as_deref() != expected_prior_root {
4714        return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
4715            "committed root-manifest lineage does not match the verified parent".to_owned(),
4716        ));
4717    }
4718    let expected_root_version = if committed.root_manifest().object_version_id()
4719        == expected_prior_root.unwrap_or_default()
4720    {
4721        transaction.prior_root_manifest_version_id.as_deref()
4722    } else {
4723        Some(transaction.root_manifest_candidate_version_id.as_str())
4724    };
4725    if committed.root_manifest().object_version_id() != expected_root_version.unwrap_or_default() {
4726        return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
4727            "committed root-manifest Object Version does not match its journal assignment"
4728                .to_owned(),
4729        ));
4730    }
4731    Ok(())
4732}
4733
4734#[cfg(test)]
4735fn read_active_transaction(
4736    state: &FolderbaseState,
4737) -> Result<Option<ActiveCaptureTransaction>, FolderbaseCaptureError> {
4738    read_active_transaction_with_limit(state, MAX_CAPTURE_TRANSACTION_BYTES)
4739}
4740
4741fn read_active_transaction_with_limit(
4742    state: &FolderbaseState,
4743    maximum_bytes: u64,
4744) -> Result<Option<ActiveCaptureTransaction>, FolderbaseCaptureError> {
4745    let Some(encoded) =
4746        state.read_bounded(Path::new(ACTIVE_CAPTURE_TRANSACTION_PATH), maximum_bytes)?
4747    else {
4748        return Ok(None);
4749    };
4750    let authority_sha256 = format!("{:x}", Sha256::digest(&encoded));
4751    let (transaction, wire) = match serde_json::from_slice::<CaptureTransaction>(&encoded) {
4752        Ok(transaction) => (transaction, CaptureTransactionWire::Current),
4753        Err(current_error) => {
4754            match serde_json::from_slice::<ReleasedV1CaptureTransaction>(&encoded) {
4755                Ok(transaction) => (
4756                    transaction.into(),
4757                    CaptureTransactionWire::ReleasedV1 {
4758                        encoded_bytes: encoded.len() as u64,
4759                    },
4760                ),
4761                Err(released_error) => {
4762                    return Err(FolderbaseCaptureError::InvalidCaptureTransaction(format!(
4763                        "active journal is invalid JSON for current ({current_error}) and released v1 ({released_error}) wire formats"
4764                    )));
4765                }
4766            }
4767        }
4768    };
4769    Ok(Some(ActiveCaptureTransaction {
4770        transaction,
4771        authority_sha256,
4772        wire,
4773    }))
4774}
4775
4776fn ensure_no_active_capture(state: &FolderbaseState) -> Result<(), FolderbaseCaptureError> {
4777    if state
4778        .read_bounded(
4779            Path::new(ACTIVE_CAPTURE_TRANSACTION_PATH),
4780            MAX_CAPTURE_TRANSACTION_BYTES,
4781        )?
4782        .is_some()
4783    {
4784        return Err(FolderbaseCaptureError::ConflictingTransaction(
4785            "a Folderbase Version capture is pending",
4786        ));
4787    }
4788    Ok(())
4789}
4790
4791fn ensure_no_active_restore(state: &FolderbaseState) -> Result<(), FolderbaseCaptureError> {
4792    if state
4793        .read_bounded(
4794            Path::new(ACTIVE_RESTORE_TRANSACTION_PATH),
4795            MAX_CAPTURE_TRANSACTION_BYTES,
4796        )?
4797        .is_some()
4798        || state
4799            .read_bounded(
4800                Path::new(RESTORE_CLEANUP_RECOVERY_PATH),
4801                MAX_CAPTURE_TRANSACTION_BYTES,
4802            )?
4803            .is_some()
4804    {
4805        return Err(FolderbaseCaptureError::ConflictingTransaction(
4806            "a Tombstone restore is pending",
4807        ));
4808    }
4809    Ok(())
4810}
4811
4812fn read_active_restore_transaction(
4813    state: &FolderbaseState,
4814) -> Result<Option<RestoreTransaction>, FolderbaseCaptureError> {
4815    let Some(encoded) = state.read_bounded(
4816        Path::new(ACTIVE_RESTORE_TRANSACTION_PATH),
4817        MAX_CAPTURE_TRANSACTION_BYTES,
4818    )?
4819    else {
4820        return Ok(None);
4821    };
4822    serde_json::from_slice(&encoded)
4823        .map(Some)
4824        .map_err(|source| {
4825            FolderbaseCaptureError::InvalidRestoreTransaction(format!(
4826                "active restore journal is invalid JSON: {source}"
4827            ))
4828        })
4829}
4830
4831fn write_active_restore_transaction(
4832    state: &FolderbaseState,
4833    transaction: &RestoreTransaction,
4834) -> Result<(), FolderbaseCaptureError> {
4835    let encoded = encode_restore_transaction(transaction)?;
4836    state
4837        .publish_new(Path::new(ACTIVE_RESTORE_TRANSACTION_PATH), &encoded)
4838        .map_err(Into::into)
4839}
4840
4841fn read_restore_cleanup_recovery(
4842    state: &FolderbaseState,
4843) -> Result<Option<RestoreCleanupRecovery>, FolderbaseCaptureError> {
4844    let relative = Path::new(RESTORE_CLEANUP_RECOVERY_PATH);
4845    let Some(encoded) = state.read_bounded(relative, MAX_CAPTURE_TRANSACTION_BYTES)? else {
4846        return Ok(None);
4847    };
4848    let recovery: RestoreCleanupRecovery = serde_json::from_slice(&encoded).map_err(|source| {
4849        FolderbaseCaptureError::InvalidRestoreTransaction(format!(
4850            "restore cleanup recovery is invalid JSON: {source}"
4851        ))
4852    })?;
4853    if recovery.format != RESTORE_CLEANUP_RECOVERY_FORMAT_V2
4854        || !is_lowercase_sha256(&recovery.published_identity_sha256)
4855    {
4856        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
4857            "restore cleanup recovery format or publication identity is invalid".to_owned(),
4858        ));
4859    }
4860    Ok(Some(recovery))
4861}
4862
4863fn write_restore_cleanup_recovery(
4864    state: &FolderbaseState,
4865    recovery: &RestoreCleanupRecovery,
4866) -> Result<(), FolderbaseCaptureError> {
4867    let relative = Path::new(RESTORE_CLEANUP_RECOVERY_PATH);
4868    let encoded = encode_restore_cleanup_recovery(recovery)?;
4869    match state.publish_new(relative, &encoded) {
4870        Ok(()) => Ok(()),
4871        Err(FolderbaseError::WouldOverwrite(_)) => {
4872            let existing = state
4873                .read_bounded(relative, MAX_CAPTURE_TRANSACTION_BYTES)?
4874                .ok_or_else(|| {
4875                    FolderbaseCaptureError::InvalidRestoreTransaction(
4876                        "restore cleanup recovery disappeared".to_owned(),
4877                    )
4878                })?;
4879            if existing != encoded {
4880                return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
4881                    "restore cleanup recovery slot names different bytes".to_owned(),
4882                ));
4883            }
4884            Ok(())
4885        }
4886        Err(error) => Err(error.into()),
4887    }
4888}
4889
4890fn replace_restore_cleanup_recovery(
4891    state: &FolderbaseState,
4892    expected: &RestoreCleanupRecovery,
4893    target: &RestoreCleanupRecovery,
4894) -> Result<(), FolderbaseCaptureError> {
4895    let relative = Path::new(RESTORE_CLEANUP_RECOVERY_PATH);
4896    let expected = encode_restore_cleanup_recovery(expected)?;
4897    let target = encode_restore_cleanup_recovery(target)?;
4898    let current = state
4899        .read_bounded(relative, MAX_CAPTURE_TRANSACTION_BYTES)?
4900        .ok_or_else(|| {
4901            FolderbaseCaptureError::InvalidRestoreTransaction(
4902                "restore cleanup recovery disappeared before transition".to_owned(),
4903            )
4904        })?;
4905    if current != expected {
4906        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
4907            "restore cleanup recovery changed before transition".to_owned(),
4908        ));
4909    }
4910    state.replace(relative, &target)?;
4911    if state
4912        .read_bounded(relative, MAX_CAPTURE_TRANSACTION_BYTES)?
4913        .as_deref()
4914        != Some(target.as_slice())
4915    {
4916        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
4917            "restore cleanup recovery transition did not verify".to_owned(),
4918        ));
4919    }
4920    Ok(())
4921}
4922
4923fn encode_restore_cleanup_recovery(
4924    recovery: &RestoreCleanupRecovery,
4925) -> Result<Vec<u8>, FolderbaseCaptureError> {
4926    let mut encoded = serde_json::to_vec_pretty(recovery).map_err(|source| {
4927        FolderbaseCaptureError::InvalidRestoreTransaction(format!(
4928            "restore cleanup recovery encoding failed: {source}"
4929        ))
4930    })?;
4931    encoded.push(b'\n');
4932    if encoded.len() as u64 > MAX_CAPTURE_TRANSACTION_BYTES {
4933        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
4934            "restore cleanup recovery exceeds its bounded record limit".to_owned(),
4935        ));
4936    }
4937    Ok(encoded)
4938}
4939
4940fn remove_restore_cleanup_recovery(state: &FolderbaseState) -> Result<(), FolderbaseCaptureError> {
4941    let relative = Path::new(RESTORE_CLEANUP_RECOVERY_PATH);
4942    match state.remove_durable(relative) {
4943        Ok(()) => Ok(()),
4944        Err(error) => match state.read_bounded(relative, MAX_CAPTURE_TRANSACTION_BYTES) {
4945            Ok(None) => Ok(()),
4946            Ok(Some(_)) | Err(_) => Err(error.into()),
4947        },
4948    }
4949}
4950
4951fn read_restore_completion_receipt(
4952    state: &FolderbaseState,
4953) -> Result<Option<RestoreCompletionReceipt>, FolderbaseCaptureError> {
4954    let relative = Path::new(RESTORE_COMPLETION_PATH);
4955    let Some(encoded) = state.read_bounded(relative, MAX_CAPTURE_TRANSACTION_BYTES)? else {
4956        return Ok(None);
4957    };
4958    let completion: RestoreCompletionReceipt =
4959        serde_json::from_slice(&encoded).map_err(|source| {
4960            FolderbaseCaptureError::InvalidRestoreTransaction(format!(
4961                "restore completion receipt is invalid JSON: {source}"
4962            ))
4963        })?;
4964    if completion.format != RESTORE_COMPLETION_FORMAT_V2
4965        || !is_lowercase_sha256(&completion.published_identity_sha256)
4966    {
4967        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
4968            "restore completion receipt format or publication identity is invalid".to_owned(),
4969        ));
4970    }
4971    Ok(Some(completion))
4972}
4973
4974fn write_restore_authority_record(
4975    state: &FolderbaseState,
4976    transaction: &RestoreTransaction,
4977    published_identity_sha256: &str,
4978) -> Result<(), FolderbaseCaptureError> {
4979    let record = restore_authority_record(transaction, published_identity_sha256);
4980    let encoded = encode_restore_authority_record(&record)?;
4981    let relative = restore_authority_record_path(&transaction.transaction_id);
4982    match state.publish_new(&relative, &encoded) {
4983        Ok(()) => Ok(()),
4984        Err(FolderbaseError::WouldOverwrite(_)) => {
4985            if state
4986                .read_bounded(&relative, MAX_RESTORE_AUTHORITY_BYTES)?
4987                .as_deref()
4988                == Some(encoded.as_slice())
4989            {
4990                Ok(())
4991            } else {
4992                Err(FolderbaseCaptureError::InvalidRestoreTransaction(
4993                    "restore authority slot names different bytes".to_owned(),
4994                ))
4995            }
4996        }
4997        Err(error) => Err(error.into()),
4998    }
4999}
5000
5001fn encode_restore_authority_record(
5002    record: &RestoreAuthorityRecord,
5003) -> Result<Vec<u8>, FolderbaseCaptureError> {
5004    let mut encoded = serde_json::to_vec_pretty(record).map_err(|source| {
5005        FolderbaseCaptureError::InvalidRestoreTransaction(format!(
5006            "restore authority encoding failed: {source}"
5007        ))
5008    })?;
5009    encoded.push(b'\n');
5010    if encoded.len() as u64 > MAX_RESTORE_AUTHORITY_BYTES {
5011        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
5012            "restore authority exceeds its bounded record limit".to_owned(),
5013        ));
5014    }
5015    Ok(encoded)
5016}
5017
5018fn restore_authority_record(
5019    transaction: &RestoreTransaction,
5020    published_identity_sha256: &str,
5021) -> RestoreAuthorityRecord {
5022    RestoreAuthorityRecord {
5023        format: RESTORE_AUTHORITY_FORMAT_V1.to_owned(),
5024        folderbase_id: transaction.folderbase_id.clone(),
5025        root_instance_sha256: transaction.root_instance_sha256.clone(),
5026        transaction_id: transaction.transaction_id.clone(),
5027        workspace_path: transaction.path.clone(),
5028        private_stage_path: restore_stage_path(transaction)
5029            .to_str()
5030            .expect("validated restore stage paths are UTF-8")
5031            .to_owned(),
5032        published_identity_sha256: published_identity_sha256.to_owned(),
5033    }
5034}
5035
5036fn write_restore_completion_receipt(
5037    state: &FolderbaseState,
5038    transaction: &RestoreTransaction,
5039    published_identity_sha256: &str,
5040) -> Result<(), FolderbaseCaptureError> {
5041    let completion = RestoreCompletionReceipt {
5042        format: RESTORE_COMPLETION_FORMAT_V2.to_owned(),
5043        transaction: transaction.clone(),
5044        published_identity_sha256: published_identity_sha256.to_owned(),
5045    };
5046    let encoded = encode_restore_completion_receipt(&completion)?;
5047    state
5048        .replace(Path::new(RESTORE_COMPLETION_PATH), &encoded)
5049        .map_err(Into::into)
5050}
5051
5052fn encode_restore_completion_receipt(
5053    completion: &RestoreCompletionReceipt,
5054) -> Result<Vec<u8>, FolderbaseCaptureError> {
5055    let mut encoded = serde_json::to_vec_pretty(completion).map_err(|source| {
5056        FolderbaseCaptureError::InvalidRestoreTransaction(format!(
5057            "restore completion receipt encoding failed: {source}"
5058        ))
5059    })?;
5060    encoded.push(b'\n');
5061    if encoded.len() as u64 > MAX_CAPTURE_TRANSACTION_BYTES {
5062        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
5063            "restore completion receipt exceeds its bounded record limit".to_owned(),
5064        ));
5065    }
5066    Ok(encoded)
5067}
5068
5069fn encode_restore_transaction(
5070    transaction: &RestoreTransaction,
5071) -> Result<Vec<u8>, FolderbaseCaptureError> {
5072    let mut encoded = serde_json::to_vec_pretty(transaction).map_err(|source| {
5073        FolderbaseCaptureError::InvalidRestoreTransaction(format!(
5074            "restore journal encoding failed: {source}"
5075        ))
5076    })?;
5077    encoded.push(b'\n');
5078    if encoded.len() as u64 > MAX_CAPTURE_TRANSACTION_BYTES {
5079        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
5080            "restore journal exceeds its bounded record limit".to_owned(),
5081        ));
5082    }
5083    Ok(encoded)
5084}
5085
5086fn remove_active_restore_transaction(
5087    state: &FolderbaseState,
5088) -> Result<(), FolderbaseCaptureError> {
5089    state
5090        .remove_durable(Path::new(ACTIVE_RESTORE_TRANSACTION_PATH))
5091        .map_err(Into::into)
5092}
5093
5094fn validate_restore_transaction(
5095    store: &FolderbaseVersionStore,
5096    transaction: &RestoreTransaction,
5097) -> Result<(), FolderbaseCaptureError> {
5098    validate_capture_path(&transaction.path).map_err(|_| {
5099        FolderbaseCaptureError::InvalidRestoreTransaction(
5100            "restore path is not an ordinary portable content path".to_owned(),
5101        )
5102    })?;
5103    safe_content_path(Path::new(&transaction.path)).map_err(|_| {
5104        FolderbaseCaptureError::InvalidRestoreTransaction(
5105            "restore path is not an ordinary portable content path".to_owned(),
5106        )
5107    })?;
5108    if transaction.format != RESTORE_TRANSACTION_FORMAT_V1
5109        || transaction.folderbase_id != store.root_attestation.folderbase_id
5110        || store
5111            .root_instance_authority
5112            .admit(&transaction.root_instance_sha256)
5113            .is_none()
5114        || !transaction.transaction_id.starts_with("fbrestore_")
5115        || Uuid::parse_str(
5116            transaction
5117                .transaction_id
5118                .strip_prefix("fbrestore_")
5119                .unwrap_or_default(),
5120        )
5121        .is_err()
5122        || !is_lowercase_sha256(&transaction.expected_head.version_sha256)
5123        || !is_lowercase_sha256(transaction.expected_head.authority.sha256())
5124        || !is_lowercase_sha256(&transaction.target_version_sha256)
5125    {
5126        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
5127            "restore journal identity or digest fields are invalid".to_owned(),
5128        ));
5129    }
5130    validate_capture_version_id(&transaction.expected_head.version_id)?;
5131    validate_capture_version_id(&transaction.target_version_id)?;
5132    if transaction.expected_head.version_id == transaction.target_version_id
5133        || transaction.tombstone.path() != transaction.path
5134        || transaction.binding.path() != transaction.path
5135        || transaction.tombstone.deleted_kind() != DeletedKind::RegularFile
5136        || transaction.binding.kind() != PathBindingKind::RegularFile
5137        || transaction.tombstone.object_id() != transaction.binding.object_id()
5138        || transaction.tombstone.last_object_version_id() != transaction.binding.object_version_id()
5139        || transaction.binding.content_sha256().is_none()
5140        || transaction.binding.bytes().is_none()
5141        || transaction.binding.executable().is_none()
5142    {
5143        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
5144            "restore Tombstone and live binding do not describe one exact ordinary file".to_owned(),
5145        ));
5146    }
5147    ObjectId::parse(transaction.binding.object_id().to_owned())?;
5148    VersionId::parse(
5149        transaction
5150            .binding
5151            .object_version_id()
5152            .expect("validated regular binding")
5153            .to_owned(),
5154    )?;
5155    Ok(())
5156}
5157
5158fn is_lowercase_sha256(value: &str) -> bool {
5159    value.len() == 64
5160        && value
5161            .bytes()
5162            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
5163}
5164
5165fn compare_and_swap_restore_head(
5166    state: &FolderbaseState,
5167    expected: &JournalHead,
5168    target: &LocalHeadRecord,
5169) -> Result<(), FolderbaseCaptureError> {
5170    let encoded = json_bytes(target)?;
5171    state.verify_still_attached()?;
5172    let current = read_head_record(state)?.ok_or(FolderbaseCaptureError::LocalHeadChanged)?;
5173    if JournalHead::from(&current) != *expected {
5174        return Err(FolderbaseCaptureError::LocalHeadChanged);
5175    }
5176    state.replace(Path::new(LOCAL_HEAD_PATH), &encoded)?;
5177    state.verify_still_attached()?;
5178    if read_head_record(state)?.as_ref() != Some(target) {
5179        return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
5180            "Local Head replacement did not verify".to_owned(),
5181        ));
5182    }
5183    Ok(())
5184}
5185
5186fn compare_and_swap_exact_local_head(
5187    state: &FolderbaseState,
5188    expected: &LocalHeadRecord,
5189    target: &LocalHeadRecord,
5190) -> Result<(), FolderbaseCaptureError> {
5191    let encoded = json_bytes(target)?;
5192    state.verify_still_attached()?;
5193    if read_head_record(state)?.as_ref() != Some(expected) {
5194        return Err(FolderbaseCaptureError::LocalHeadChanged);
5195    }
5196    state.replace(Path::new(LOCAL_HEAD_PATH), &encoded)?;
5197    state.verify_still_attached()?;
5198    if read_head_record(state)?.as_ref() != Some(target) {
5199        return Err(FolderbaseCaptureError::InvalidLocalHead(
5200            "Local Head authority replacement did not verify".to_owned(),
5201        ));
5202    }
5203    Ok(())
5204}
5205
5206fn normalize_legacy_local_head(state: &FolderbaseState) -> Result<(), FolderbaseCaptureError> {
5207    let Some(legacy) = read_head_record(state)? else {
5208        return Ok(());
5209    };
5210    if legacy.format != "folderbase-local-head-v1" {
5211        return Ok(());
5212    }
5213    let normalized = LocalHeadRecord {
5214        format: "folderbase-local-head-v2".to_owned(),
5215        ..legacy.clone()
5216    };
5217    compare_and_swap_exact_local_head(state, &legacy, &normalized)
5218}
5219
5220fn rebind_legacy_root_local_head(
5221    store: &FolderbaseVersionStore,
5222    local: &LocalVersionStore,
5223    state: &FolderbaseState,
5224) -> Result<(), FolderbaseCaptureError> {
5225    rebind_legacy_root_local_head_with_hook(store, local, state, |_| {})
5226}
5227
5228#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5229enum LocalHeadRebindCheckpoint {
5230    BeforeCas,
5231    AfterCas,
5232}
5233
5234fn rebind_legacy_root_local_head_with_hook(
5235    store: &FolderbaseVersionStore,
5236    local: &LocalVersionStore,
5237    state: &FolderbaseState,
5238    mut checkpoint: impl FnMut(LocalHeadRebindCheckpoint),
5239) -> Result<(), FolderbaseCaptureError> {
5240    let Some(head) = read_head_record(state)? else {
5241        return Ok(());
5242    };
5243    if head.folderbase_id != store.root_attestation.folderbase_id {
5244        return Err(FolderbaseCaptureError::InvalidLocalHead(
5245            "Local Head belongs to another Folderbase".to_owned(),
5246        ));
5247    }
5248    let admission = store
5249        .root_instance_authority
5250        .admit(&head.root_instance_sha256)
5251        .ok_or_else(|| {
5252            FolderbaseCaptureError::InvalidLocalHead(
5253                "Local Head belongs to another physical Folderbase Root".to_owned(),
5254            )
5255        })?;
5256    if !admission.is_legacy_v1() {
5257        return Ok(());
5258    }
5259    let version = read_and_verify_folderbase_version(store, local, state, &head.version_id)?;
5260    if version.canonical_digest()? != head.version_sha256 {
5261        return Err(FolderbaseCaptureError::InvalidLocalHead(
5262            "Local Head digest does not match its immutable Folderbase Version".to_owned(),
5263        ));
5264    }
5265    let current_root = store.root_instance_authority.current_sha256();
5266    let authority = match &head.authority {
5267        LocalHeadAuthority::CaptureTransactionV1 { sha256 } => {
5268            LocalHeadAuthority::CaptureTransactionV1 {
5269                sha256: sha256.clone(),
5270            }
5271        }
5272        LocalHeadAuthority::VersionDerivedV1 { sha256 } => {
5273            let expected = version_derived_local_head_sha256(
5274                &head.folderbase_id,
5275                admission.recorded_sha256(),
5276                &head.version_id,
5277                &head.version_sha256,
5278            )?;
5279            if sha256 != &expected {
5280                return Err(FolderbaseCaptureError::InvalidLocalHead(
5281                    "legacy Local Head authority is not independently derivable".to_owned(),
5282                ));
5283            }
5284            LocalHeadAuthority::VersionDerivedV1 {
5285                sha256: version_derived_local_head_sha256(
5286                    &head.folderbase_id,
5287                    current_root,
5288                    &head.version_id,
5289                    &head.version_sha256,
5290                )?,
5291            }
5292        }
5293    };
5294    let rebound = LocalHeadRecord {
5295        format: "folderbase-local-head-v2".to_owned(),
5296        root_instance_sha256: current_root.to_owned(),
5297        authority,
5298        ..head.clone()
5299    };
5300    checkpoint(LocalHeadRebindCheckpoint::BeforeCas);
5301    compare_and_swap_exact_local_head(state, &head, &rebound)?;
5302    checkpoint(LocalHeadRebindCheckpoint::AfterCas);
5303    Ok(())
5304}
5305
5306fn write_active_transaction_with_limit(
5307    state: &FolderbaseState,
5308    transaction: &CaptureTransaction,
5309    maximum_bytes: u64,
5310) -> Result<String, FolderbaseCaptureError> {
5311    let encoded = encode_active_transaction(transaction, maximum_bytes)?;
5312    state
5313        .publish_new(Path::new(ACTIVE_CAPTURE_TRANSACTION_PATH), &encoded)
5314        .map_err(FolderbaseCaptureError::from)?;
5315    Ok(format!("{:x}", Sha256::digest(&encoded)))
5316}
5317
5318fn encode_active_transaction(
5319    transaction: &CaptureTransaction,
5320    maximum_bytes: u64,
5321) -> Result<Vec<u8>, FolderbaseCaptureError> {
5322    let mut encoded = BoundedJsonWriter::new(maximum_bytes);
5323    let result = serde_json::to_writer_pretty(&mut encoded, transaction);
5324    if encoded.exceeded {
5325        return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
5326            "active journal exceeds its bounded record limit".to_owned(),
5327        ));
5328    }
5329    result.map_err(|source| {
5330        FolderbaseCaptureError::InvalidCaptureTransaction(format!(
5331            "capture record encoding failed: {source}"
5332        ))
5333    })?;
5334    encoded.write_all(b"\n").map_err(|_| {
5335        FolderbaseCaptureError::InvalidCaptureTransaction(
5336            "active journal exceeds its bounded record limit".to_owned(),
5337        )
5338    })?;
5339    Ok(encoded.bytes)
5340}
5341
5342struct BoundedJsonWriter {
5343    bytes: Vec<u8>,
5344    maximum_bytes: u64,
5345    exceeded: bool,
5346}
5347
5348impl BoundedJsonWriter {
5349    fn new(maximum_bytes: u64) -> Self {
5350        Self {
5351            bytes: Vec::with_capacity(maximum_bytes.min(64 * 1024) as usize),
5352            maximum_bytes,
5353            exceeded: false,
5354        }
5355    }
5356}
5357
5358impl Write for BoundedJsonWriter {
5359    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
5360        let Some(next_len) = (self.bytes.len() as u64).checked_add(bytes.len() as u64) else {
5361            self.exceeded = true;
5362            return Err(std::io::Error::other("bounded JSON record exceeded"));
5363        };
5364        if next_len > self.maximum_bytes {
5365            self.exceeded = true;
5366            return Err(std::io::Error::other("bounded JSON record exceeded"));
5367        }
5368        self.bytes.extend_from_slice(bytes);
5369        Ok(bytes.len())
5370    }
5371
5372    fn flush(&mut self) -> std::io::Result<()> {
5373        Ok(())
5374    }
5375}
5376
5377fn remove_active_transaction(state: &FolderbaseState) -> Result<(), FolderbaseCaptureError> {
5378    state
5379        .remove_durable(Path::new(ACTIVE_CAPTURE_TRANSACTION_PATH))
5380        .map_err(Into::into)
5381}
5382
5383fn compare_and_swap_local_head(
5384    state: &FolderbaseState,
5385    expected: Option<&CaptureLocalHead>,
5386    target: &LocalHeadRecord,
5387) -> Result<(), FolderbaseCaptureError> {
5388    let expected = expected.map(JournalHead::from);
5389    let encoded = json_bytes(target)?;
5390    state.verify_still_attached()?;
5391    let current = read_head_record(state)?;
5392    let current_summary = current.as_ref().map(|head| JournalHead {
5393        version_id: head.version_id.clone(),
5394        version_sha256: head.version_sha256.clone(),
5395        authority: head.authority.clone(),
5396    });
5397    if current_summary != expected {
5398        return Err(FolderbaseCaptureError::LocalHeadChanged);
5399    }
5400    state.replace(Path::new(LOCAL_HEAD_PATH), &encoded)?;
5401    state.verify_still_attached()?;
5402    if read_head_record(state)?.as_ref() != Some(target) {
5403        return Err(FolderbaseCaptureError::InvalidCaptureTransaction(
5404            "Local Head replacement did not verify".to_owned(),
5405        ));
5406    }
5407    Ok(())
5408}
5409
5410fn read_head_record(
5411    state: &FolderbaseState,
5412) -> Result<Option<LocalHeadRecord>, FolderbaseCaptureError> {
5413    let Some(encoded) =
5414        state.read_bounded(Path::new(LOCAL_HEAD_PATH), crate::MAX_LOCAL_HEAD_BYTES)?
5415    else {
5416        return Ok(None);
5417    };
5418    let wire: LocalHeadRecordWire = serde_json::from_slice(&encoded).map_err(|source| {
5419        FolderbaseCaptureError::InvalidLocalHead(format!("Local Head JSON is invalid: {source}"))
5420    })?;
5421    let head = match wire {
5422        LocalHeadRecordWire::V2(head) if head.format == "folderbase-local-head-v2" => {
5423            LocalHeadRecord {
5424                format: head.format,
5425                folderbase_id: head.folderbase_id,
5426                root_instance_sha256: head.root_instance_sha256,
5427                version_id: head.version_id,
5428                version_sha256: head.version_sha256,
5429                authority: head.authority,
5430            }
5431        }
5432        LocalHeadRecordWire::V1(head) if head.format == "folderbase-local-head-v1" => {
5433            LocalHeadRecord {
5434                format: head.format,
5435                folderbase_id: head.folderbase_id,
5436                root_instance_sha256: head.root_instance_sha256,
5437                version_id: head.version_id,
5438                version_sha256: head.version_sha256,
5439                authority: LocalHeadAuthority::CaptureTransactionV1 {
5440                    sha256: head.transaction_sha256,
5441                },
5442            }
5443        }
5444        _ => {
5445            return Err(FolderbaseCaptureError::InvalidLocalHead(
5446                "Local Head format is unsupported".to_owned(),
5447            ));
5448        }
5449    };
5450    if head.version_sha256.len() != 64
5451        || head.authority.sha256().len() != 64
5452        || !head
5453            .version_sha256
5454            .bytes()
5455            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
5456        || !head
5457            .authority
5458            .sha256()
5459            .bytes()
5460            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
5461    {
5462        return Err(FolderbaseCaptureError::InvalidLocalHead(
5463            "Local Head fields are invalid".to_owned(),
5464        ));
5465    }
5466    validate_capture_version_id(&head.version_id)?;
5467    Ok(Some(head))
5468}
5469
5470fn finish_committed_transaction(
5471    store: &FolderbaseVersionStore,
5472    local: &LocalVersionStore,
5473    state: &FolderbaseState,
5474    transaction: &CaptureTransaction,
5475) -> Result<(), FolderbaseCaptureError> {
5476    let version =
5477        read_and_verify_folderbase_version(store, local, state, &transaction.target_version_id)?;
5478    for assignment in &transaction.assignments {
5479        let Some(binding) = version.lookup_binding(&assignment.path) else {
5480            return Err(FolderbaseCaptureError::InvalidCaptureTransaction(format!(
5481                "committed version has no assignment for {}",
5482                assignment.path
5483            )));
5484        };
5485        if binding.object_id() != assignment.object_id
5486            || binding.kind() != path_binding_kind(assignment.kind)
5487        {
5488            return Err(FolderbaseCaptureError::InvalidCaptureTransaction(format!(
5489                "committed binding differs from journal assignment at {}",
5490                assignment.path
5491            )));
5492        }
5493        if assignment.kind == CaptureEntryKind::RegularFile
5494            && can_project_legacy_object(&assignment.path)
5495        {
5496            let projection = regular_projection(
5497                local,
5498                state,
5499                assignment,
5500                &VersionId::parse(
5501                    binding
5502                        .object_version_id()
5503                        .expect("regular version")
5504                        .to_owned(),
5505                )?,
5506                assignment.prior_object_version_id.as_deref(),
5507                &transaction.created_at,
5508            )?;
5509            local.write_capture_object_projection_in(state, &projection)?;
5510        }
5511    }
5512    write_capture_identities(state, transaction)
5513}
5514
5515fn write_capture_identities(
5516    state: &FolderbaseState,
5517    transaction: &CaptureTransaction,
5518) -> Result<(), FolderbaseCaptureError> {
5519    for assignment in &transaction.assignments {
5520        // This records the identity of the bytes that Head sealed, not a claim
5521        // about whatever currently occupies the path. If the live entry was
5522        // replaced after Head, the mismatch makes subsequent reuse fail closed.
5523        let record = CaptureIdentityRecord {
5524            format: "folderbase-capture-identity-v1".to_owned(),
5525            object_id: assignment.object_id.clone(),
5526            kind: assignment.kind,
5527            observed: assignment.observed.clone(),
5528        };
5529        state.replace(
5530            &capture_identity_relative_path(&assignment.object_id),
5531            &json_bytes(&record)?,
5532        )?;
5533    }
5534    Ok(())
5535}
5536
5537fn capture_identity_relative_path(object_id: &str) -> PathBuf {
5538    Path::new(CAPTURE_IDENTITIES_DIRECTORY).join(format!("{object_id}.json"))
5539}
5540
5541fn open_root_capability(root: &Path) -> Result<Dir, FolderbaseCaptureError> {
5542    let mut options = OpenOptions::new();
5543    options.read(true);
5544    #[cfg(unix)]
5545    {
5546        use std::os::unix::fs::OpenOptionsExt;
5547
5548        options.custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW);
5549    }
5550    #[cfg(windows)]
5551    {
5552        use std::os::windows::fs::OpenOptionsExt;
5553        use windows_sys::Win32::Storage::FileSystem::{
5554            FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ,
5555            FILE_SHARE_WRITE,
5556        };
5557
5558        options
5559            .access_mode(0)
5560            .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
5561            .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE);
5562    }
5563    let file = options
5564        .open(root)
5565        .map_err(|source| FolderbaseCaptureError::Io {
5566            path: root.to_path_buf(),
5567            source,
5568        })?;
5569    let metadata = file
5570        .metadata()
5571        .map_err(|source| FolderbaseCaptureError::Io {
5572            path: root.to_path_buf(),
5573            source,
5574        })?;
5575    if metadata_is_link_or_reparse(&metadata) || !metadata.is_dir() {
5576        return Err(FolderbaseCaptureError::PlanStoreMismatch);
5577    }
5578    Ok(Dir::from_std_file(file))
5579}
5580
5581#[cfg(not(windows))]
5582fn open_child_directory_capability(
5583    parent: &Dir,
5584    name: &std::ffi::OsStr,
5585    _display: &Path,
5586) -> std::io::Result<Dir> {
5587    parent.open_dir_nofollow(name)
5588}
5589
5590#[cfg(windows)]
5591fn open_child_directory_capability(
5592    parent: &Dir,
5593    name: &std::ffi::OsStr,
5594    display: &Path,
5595) -> std::io::Result<Dir> {
5596    use cap_std::fs::OpenOptionsExt;
5597    use windows_sys::Win32::Storage::FileSystem::{
5598        FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ, FILE_SHARE_WRITE,
5599    };
5600
5601    let mut options = CapOpenOptions::new();
5602    options
5603        .access_mode(0)
5604        .follow(FollowSymlinks::No)
5605        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
5606        .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE);
5607    let file = parent.open_with(name, &options)?.into_std();
5608    let metadata = file.metadata()?;
5609    if metadata_is_link_or_reparse(&metadata) || !metadata.is_dir() {
5610        return Err(std::io::Error::other(format!(
5611            "unsafe Folderbase directory capability: {}",
5612            display.display()
5613        )));
5614    }
5615    Ok(Dir::from_std_file(file))
5616}
5617
5618fn open_parent_beneath(
5619    root: &Path,
5620    relative: &Path,
5621) -> Result<(Dir, std::ffi::OsString), FolderbaseCaptureError> {
5622    let mut components = relative.components().peekable();
5623    let mut directory = open_root_capability(root)?;
5624    let mut traversed = PathBuf::new();
5625    while let Some(component) = components.next() {
5626        let Component::Normal(name) = component else {
5627            return Err(FolderbaseCaptureError::CaptureStateChanged(
5628                relative.to_path_buf(),
5629            ));
5630        };
5631        if components.peek().is_none() {
5632            return Ok((directory, name.to_os_string()));
5633        }
5634        traversed.push(name);
5635        let display = root.join(&traversed);
5636        directory =
5637            open_child_directory_capability(&directory, name, &display).map_err(|source| {
5638                FolderbaseCaptureError::Io {
5639                    path: display,
5640                    source,
5641                }
5642            })?;
5643    }
5644    Err(FolderbaseCaptureError::CaptureStateChanged(
5645        relative.to_path_buf(),
5646    ))
5647}
5648
5649fn open_regular_beneath(root: &Path, relative: &Path) -> Result<File, FolderbaseCaptureError> {
5650    let (parent, name) = open_parent_beneath(root, relative)?;
5651    let mut options = CapOpenOptions::new();
5652    options.read(true).follow(FollowSymlinks::No);
5653    #[cfg(windows)]
5654    {
5655        use cap_std::fs::OpenOptionsExt;
5656        use windows_sys::Win32::Storage::FileSystem::{
5657            FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ, FILE_SHARE_WRITE,
5658        };
5659
5660        options
5661            .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
5662            .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE);
5663    }
5664    let file = parent
5665        .open_with(&name, &options)
5666        .map_err(|source| FolderbaseCaptureError::Io {
5667            path: root.join(relative),
5668            source,
5669        })?
5670        .into_std();
5671    let metadata = file
5672        .metadata()
5673        .map_err(|source| FolderbaseCaptureError::Io {
5674            path: root.join(relative),
5675            source,
5676        })?;
5677    if !metadata.is_file() || metadata_is_link_or_reparse(&metadata) {
5678        return Err(FolderbaseCaptureError::CaptureStateChanged(
5679            relative.to_path_buf(),
5680        ));
5681    }
5682    Ok(file)
5683}
5684
5685#[cfg(test)]
5686fn read_regular_beneath(
5687    root: &Path,
5688    relative: &Path,
5689    maximum_bytes: u64,
5690) -> Result<Option<Vec<u8>>, FolderbaseCaptureError> {
5691    let mut file = match open_regular_beneath(root, relative) {
5692        Ok(file) => file,
5693        Err(FolderbaseCaptureError::Io { source, .. })
5694            if source.kind() == std::io::ErrorKind::NotFound =>
5695        {
5696            return Ok(None);
5697        }
5698        Err(error) => return Err(error),
5699    };
5700    if file
5701        .metadata()
5702        .map_err(|source| FolderbaseCaptureError::Io {
5703            path: root.join(relative),
5704            source,
5705        })?
5706        .len()
5707        > maximum_bytes
5708    {
5709        return Err(FolderbaseCaptureError::InvalidCaptureTransaction(format!(
5710            "{} exceeds its bounded record limit",
5711            relative.display()
5712        )));
5713    }
5714    let mut encoded = Vec::new();
5715    Read::by_ref(&mut file)
5716        .take(maximum_bytes + 1)
5717        .read_to_end(&mut encoded)
5718        .map_err(|source| FolderbaseCaptureError::Io {
5719            path: root.join(relative),
5720            source,
5721        })?;
5722    if encoded.len() as u64 > maximum_bytes {
5723        return Err(FolderbaseCaptureError::InvalidCaptureTransaction(format!(
5724            "{} exceeds its bounded record limit",
5725            relative.display()
5726        )));
5727    }
5728    Ok(Some(encoded))
5729}
5730
5731fn json_bytes(value: &impl Serialize) -> Result<Vec<u8>, FolderbaseCaptureError> {
5732    let mut encoded = serde_json::to_vec_pretty(value).map_err(|source| {
5733        FolderbaseCaptureError::InvalidCaptureTransaction(format!(
5734            "capture record encoding failed: {source}"
5735        ))
5736    })?;
5737    encoded.push(b'\n');
5738    Ok(encoded)
5739}
5740
5741#[cfg(test)]
5742mod tests {
5743    use std::{
5744        fs,
5745        panic::{AssertUnwindSafe, catch_unwind},
5746        sync::{Arc, Barrier},
5747        thread,
5748    };
5749
5750    use tempfile::{TempDir, tempdir};
5751
5752    use super::*;
5753
5754    const MANIFEST: &[u8] = br#"{
5755  "protocol_version": "0.1.0",
5756  "folderbase": {
5757    "id": "folderbase_019f9b75-4f42-7f65-a012-2bfecdd8c473"
5758  }
5759}
5760"#;
5761    const LEGACY_ROOT_INSTANCE_SHA256: &str =
5762        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
5763
5764    fn folderbase() -> TempDir {
5765        let root = tempdir().expect("temporary Folderbase");
5766        fs::create_dir(root.path().join(".folderbase")).expect("state");
5767        fs::write(root.path().join(".folderbase/manifest.json"), MANIFEST).expect("manifest");
5768        fs::write(root.path().join(".folderbaseignore"), "").expect("ignore");
5769        fs::write(root.path().join("FOLDERBASE.md"), "# Folderbase\n").expect("entry");
5770        fs::write(root.path().join("active.bin"), b"first opaque bytes").expect("content");
5771        root
5772    }
5773
5774    fn copy_directory(source: &Path, destination: &Path) {
5775        fs::create_dir_all(destination).expect("create copied directory");
5776        for entry in fs::read_dir(source).expect("read copied directory") {
5777            let entry = entry.expect("directory entry");
5778            let destination = destination.join(entry.file_name());
5779            if entry.file_type().expect("entry type").is_dir() {
5780                copy_directory(&entry.path(), &destination);
5781            } else {
5782                fs::copy(entry.path(), destination).expect("copy file");
5783            }
5784        }
5785    }
5786
5787    fn active_transaction(root: &Path) -> Option<CaptureTransaction> {
5788        read_active_transaction(&FolderbaseState::open(root).expect("state"))
5789            .expect("active intent")
5790            .map(|active| active.transaction)
5791    }
5792
5793    fn local_head(root: &Path) -> Option<LocalHeadRecord> {
5794        read_head_record(&FolderbaseState::open(root).expect("state")).expect("Local Head")
5795    }
5796
5797    fn install_test_version(root: &Path, version: &FolderbaseVersion) {
5798        let state = FolderbaseState::open(root).expect("state");
5799        install_folderbase_version(
5800            &state,
5801            version,
5802            &version.canonical_digest().expect("version digest"),
5803        )
5804        .expect("install test version");
5805    }
5806
5807    fn point_test_head(root: &Path, version: &FolderbaseVersion) {
5808        let state = FolderbaseState::open(root).expect("state");
5809        let store = FolderbaseVersionStore::open(root).expect("store");
5810        let version_sha256 = version.canonical_digest().expect("version digest");
5811        state
5812            .replace(
5813                Path::new(LOCAL_HEAD_PATH),
5814                &json_bytes(&LocalHeadRecord {
5815                    format: "folderbase-local-head-v2".to_owned(),
5816                    folderbase_id: version.folderbase_id().to_owned(),
5817                    root_instance_sha256: store.root_attestation.root_instance_sha256.clone(),
5818                    version_id: version.version_id().to_owned(),
5819                    version_sha256: version_sha256.clone(),
5820                    authority: LocalHeadAuthority::VersionDerivedV1 {
5821                        sha256: local_head_authority_sha256(
5822                            &store,
5823                            version.version_id(),
5824                            &version_sha256,
5825                        )
5826                        .expect("Head authority"),
5827                    },
5828                })
5829                .expect("Head bytes"),
5830            )
5831            .expect("point test Head");
5832    }
5833
5834    fn admit_test_legacy_root(store: &mut FolderbaseVersionStore) {
5835        store.root_instance_authority = crate::root_attestation::RootInstanceAuthority::for_test(
5836            store.root_attestation.root_instance_sha256.clone(),
5837            Some(LEGACY_ROOT_INSTANCE_SHA256.to_owned()),
5838        );
5839    }
5840
5841    fn write_test_head(root: &Path, head: &LocalHeadRecord) {
5842        FolderbaseState::open(root)
5843            .expect("state")
5844            .replace(
5845                Path::new(LOCAL_HEAD_PATH),
5846                &json_bytes(head).expect("Head bytes"),
5847            )
5848            .expect("replace Head");
5849    }
5850
5851    fn released_root_restore_fixture()
5852    -> (TempDir, FolderbaseVersionStore, RestoreTransaction, Vec<u8>) {
5853        let root = folderbase();
5854        let mut store = FolderbaseVersionStore::open(root.path()).expect("open");
5855        store
5856            .seal_capture(store.plan_capture().expect("genesis"))
5857            .expect("genesis");
5858        fs::remove_file(root.path().join("active.bin")).expect("delete");
5859        store
5860            .seal_capture(store.plan_capture().expect("deletion"))
5861            .expect("deletion");
5862        admit_test_legacy_root(&mut store);
5863
5864        let mut legacy_head = local_head(root.path()).expect("deletion Head");
5865        legacy_head.root_instance_sha256 = LEGACY_ROOT_INSTANCE_SHA256.to_owned();
5866        legacy_head.authority = LocalHeadAuthority::VersionDerivedV1 {
5867            sha256: version_derived_local_head_sha256(
5868                &legacy_head.folderbase_id,
5869                LEGACY_ROOT_INSTANCE_SHA256,
5870                &legacy_head.version_id,
5871                &legacy_head.version_sha256,
5872            )
5873            .expect("released parent authority"),
5874        };
5875        write_test_head(root.path(), &legacy_head);
5876
5877        let local = LocalVersionStore::open_read_only(root.path()).expect("local");
5878        let state = FolderbaseState::open_existing(root.path()).expect("state");
5879        let current =
5880            read_and_verify_folderbase_version(&store, &local, &state, &legacy_head.version_id)
5881                .expect("deletion Version");
5882        let tombstone = current
5883            .tombstones()
5884            .iter()
5885            .find(|candidate| candidate.path() == "active.bin")
5886            .expect("Tombstone")
5887            .clone();
5888        let binding = find_restore_binding(&store, &local, &state, &current, &tombstone)
5889            .expect("restore binding");
5890        let transaction =
5891            build_restore_transaction(&store, &legacy_head, &current, tombstone, binding)
5892                .expect("released-root restore transaction");
5893        write_active_restore_transaction(&state, &transaction).expect("durable journal");
5894        let transaction_bytes =
5895            encode_restore_transaction(&transaction).expect("exact journal bytes");
5896        assert_eq!(
5897            fs::read(root.path().join(ACTIVE_RESTORE_TRANSACTION_PATH)).expect("installed journal"),
5898            transaction_bytes
5899        );
5900
5901        (root, store, transaction, transaction_bytes)
5902    }
5903
5904    #[test]
5905    fn tombstone_restore_reopens_and_converges_at_every_persistence_checkpoint() {
5906        for fault in [
5907            RestoreCheckpoint::JournalDurable,
5908            RestoreCheckpoint::StageDurable,
5909            RestoreCheckpoint::TargetPublished,
5910            RestoreCheckpoint::VersionDurable,
5911            RestoreCheckpoint::HeadReplaced,
5912            RestoreCheckpoint::PublicationVerified,
5913            RestoreCheckpoint::ProjectionDurable,
5914            RestoreCheckpoint::CleanupRecoveryDurable,
5915            RestoreCheckpoint::BeforeStageRetirement,
5916            RestoreCheckpoint::AfterStageRetirement,
5917            RestoreCheckpoint::CleanupIntentRetired,
5918            RestoreCheckpoint::CompletionDurable,
5919            RestoreCheckpoint::CleanupComplete,
5920        ] {
5921            let root = folderbase();
5922            let store = FolderbaseVersionStore::open(root.path()).expect("open");
5923            store
5924                .seal_capture(store.plan_capture().expect("genesis"))
5925                .expect("genesis");
5926            fs::remove_file(root.path().join("active.bin")).expect("delete");
5927            let deletion = store
5928                .seal_capture(store.plan_capture().expect("deletion"))
5929                .expect("deletion");
5930            let interrupted = catch_unwind(AssertUnwindSafe(|| {
5931                store.restore_tombstone_with_hook("active.bin", |checkpoint| {
5932                    if checkpoint == &fault {
5933                        panic!("simulated restore termination at {fault:?}");
5934                    }
5935                })
5936            }));
5937            assert!(interrupted.is_err(), "fault {fault:?}");
5938            drop(store);
5939
5940            let reopened = FolderbaseVersionStore::open(root.path()).expect("reopen");
5941            let retry = reopened
5942                .restore_tombstone("active.bin")
5943                .expect("every durable checkpoint must retain an exact retry result");
5944            assert!(retry.created() || fault >= RestoreCheckpoint::HeadReplaced);
5945            let restored = reopened
5946                .read_version(retry.version_id())
5947                .expect("restored version");
5948            assert_eq!(restored.parents(), &[deletion.version_id().to_owned()]);
5949            assert_eq!(
5950                fs::read(root.path().join("active.bin")).expect("restored bytes"),
5951                b"first opaque bytes"
5952            );
5953            assert!(restored.lookup_binding("active.bin").is_some());
5954            assert!(
5955                restored
5956                    .tombstones()
5957                    .iter()
5958                    .all(|tombstone| tombstone.path() != "active.bin")
5959            );
5960            assert!(
5961                read_active_restore_transaction(
5962                    &FolderbaseState::open(root.path()).expect("state")
5963                )
5964                .expect("active restore")
5965                .is_none()
5966            );
5967        }
5968    }
5969
5970    #[test]
5971    fn released_root_restore_converges_without_rewriting_durable_authority() {
5972        for fault in [
5973            RestoreCheckpoint::StageDurable,
5974            RestoreCheckpoint::TargetPublished,
5975            RestoreCheckpoint::VersionDurable,
5976            RestoreCheckpoint::HeadReplaced,
5977            RestoreCheckpoint::PublicationVerified,
5978            RestoreCheckpoint::ProjectionDurable,
5979            RestoreCheckpoint::CleanupRecoveryDurable,
5980            RestoreCheckpoint::BeforeStageRetirement,
5981            RestoreCheckpoint::AfterStageRetirement,
5982            RestoreCheckpoint::CleanupIntentRetired,
5983            RestoreCheckpoint::CompletionDurable,
5984            RestoreCheckpoint::CleanupComplete,
5985        ] {
5986            let root = folderbase();
5987            let mut store = FolderbaseVersionStore::open(root.path()).expect("open");
5988            store
5989                .seal_capture(store.plan_capture().expect("genesis"))
5990                .expect("genesis");
5991            fs::remove_file(root.path().join("active.bin")).expect("delete");
5992            store
5993                .seal_capture(store.plan_capture().expect("deletion"))
5994                .expect("deletion");
5995            admit_test_legacy_root(&mut store);
5996
5997            let mut legacy_head = local_head(root.path()).expect("deletion Head");
5998            legacy_head.root_instance_sha256 = LEGACY_ROOT_INSTANCE_SHA256.to_owned();
5999            legacy_head.authority = LocalHeadAuthority::VersionDerivedV1 {
6000                sha256: version_derived_local_head_sha256(
6001                    &legacy_head.folderbase_id,
6002                    LEGACY_ROOT_INSTANCE_SHA256,
6003                    &legacy_head.version_id,
6004                    &legacy_head.version_sha256,
6005                )
6006                .expect("released parent authority"),
6007            };
6008            write_test_head(root.path(), &legacy_head);
6009            let local = LocalVersionStore::open_read_only(root.path()).expect("local");
6010            let state = FolderbaseState::open_existing(root.path()).expect("state");
6011            let current =
6012                read_and_verify_folderbase_version(&store, &local, &state, &legacy_head.version_id)
6013                    .expect("deletion Version");
6014            let tombstone = current
6015                .tombstones()
6016                .iter()
6017                .find(|candidate| candidate.path() == "active.bin")
6018                .expect("Tombstone")
6019                .clone();
6020            let binding = find_restore_binding(&store, &local, &state, &current, &tombstone)
6021                .expect("restore binding");
6022            let transaction =
6023                build_restore_transaction(&store, &legacy_head, &current, tombstone, binding)
6024                    .expect("released-root restore transaction");
6025            write_active_restore_transaction(&state, &transaction).expect("durable journal");
6026            let transaction_bytes =
6027                encode_restore_transaction(&transaction).expect("exact journal bytes");
6028            assert_eq!(
6029                fs::read(root.path().join(ACTIVE_RESTORE_TRANSACTION_PATH))
6030                    .expect("installed journal"),
6031                transaction_bytes,
6032                "the fixture starts at the released JournalDurable boundary"
6033            );
6034
6035            let interrupted = catch_unwind(AssertUnwindSafe(|| {
6036                store.restore_tombstone_with_hook("active.bin", |checkpoint| {
6037                    if checkpoint == &fault {
6038                        panic!("terminate released-root restore at {fault:?}");
6039                    }
6040                })
6041            }));
6042            assert!(
6043                interrupted.is_err(),
6044                "fault {fault:?} returned before its checkpoint: {interrupted:?}"
6045            );
6046
6047            if let Ok(encoded) = fs::read(root.path().join(ACTIVE_RESTORE_TRANSACTION_PATH)) {
6048                assert_eq!(
6049                    encoded, transaction_bytes,
6050                    "active restore bytes changed at {fault:?}"
6051                );
6052            }
6053            if let Some(recovery) = read_restore_cleanup_recovery(&state).expect("cleanup recovery")
6054            {
6055                assert_eq!(recovery.transaction, transaction);
6056                assert_eq!(
6057                    recovery.transaction.root_instance_sha256,
6058                    LEGACY_ROOT_INSTANCE_SHA256
6059                );
6060            }
6061            if let Some(completion) = read_restore_completion_receipt(&state).expect("completion") {
6062                assert_eq!(completion.transaction, transaction);
6063                assert_eq!(
6064                    completion.transaction.root_instance_sha256,
6065                    LEGACY_ROOT_INSTANCE_SHA256
6066                );
6067            }
6068            let authority_path = restore_authority_record_path(&transaction.transaction_id);
6069            let authority_before = state
6070                .read_bounded(&authority_path, MAX_RESTORE_AUTHORITY_BYTES)
6071                .expect("authority before retry");
6072            let authority_digest_before = authority_before
6073                .as_ref()
6074                .map(|encoded| format!("{:x}", Sha256::digest(encoded)));
6075
6076            let restored = store
6077                .restore_tombstone("active.bin")
6078                .expect("converge released-root restore");
6079            assert_eq!(restored.version_id(), transaction.target_version_id);
6080            let final_head = local_head(root.path()).expect("rebound final Head");
6081            assert_eq!(
6082                final_head.root_instance_sha256,
6083                store.root_attestation.root_instance_sha256
6084            );
6085            assert_eq!(
6086                final_head.authority,
6087                LocalHeadAuthority::VersionDerivedV1 {
6088                    sha256: local_head_authority_sha256(
6089                        &store,
6090                        &final_head.version_id,
6091                        &final_head.version_sha256,
6092                    )
6093                    .expect("current final authority"),
6094                }
6095            );
6096
6097            let authority_after = state
6098                .read_bounded(&authority_path, MAX_RESTORE_AUTHORITY_BYTES)
6099                .expect("authority after retry")
6100                .expect("durable authority");
6101            let authority: RestoreAuthorityRecord =
6102                serde_json::from_slice(&authority_after).expect("authority JSON");
6103            assert_eq!(
6104                authority.root_instance_sha256, LEGACY_ROOT_INSTANCE_SHA256,
6105                "immutable authority retains the exact recorded root"
6106            );
6107            if let Some(before) = authority_before {
6108                assert_eq!(
6109                    authority_after, before,
6110                    "authority bytes changed at {fault:?}"
6111                );
6112                assert_eq!(
6113                    format!("{:x}", Sha256::digest(&authority_after)),
6114                    authority_digest_before.expect("prior authority digest"),
6115                    "authority digest changed at {fault:?}"
6116                );
6117            }
6118        }
6119    }
6120
6121    #[test]
6122    fn released_root_restore_revalidates_an_ordinary_edit_after_head_rebind() {
6123        let (root, store, _transaction, _transaction_bytes) = released_root_restore_fixture();
6124
6125        let result = store.restore_tombstone_with_hook("active.bin", |checkpoint| {
6126            if checkpoint == &RestoreCheckpoint::BeforeLegacyRootHeadRebind {
6127                fs::write(root.path().join("active.bin"), b"edited after final proof")
6128                    .expect("ordinary edit");
6129            }
6130        });
6131
6132        assert!(
6133            result.is_err(),
6134            "restore must not return Restored when bytes change around root-Head rebind"
6135        );
6136    }
6137
6138    #[test]
6139    fn released_root_restore_revalidates_inode_replacement_after_head_rebind() {
6140        let (root, store, _transaction, _transaction_bytes) = released_root_restore_fixture();
6141
6142        let result = store.restore_tombstone_with_hook("active.bin", |checkpoint| {
6143            if checkpoint == &RestoreCheckpoint::BeforeLegacyRootHeadRebind {
6144                let replacement = root.path().join("same-bytes-replacement");
6145                fs::write(&replacement, b"first opaque bytes").expect("replacement bytes");
6146                fs::rename(replacement, root.path().join("active.bin"))
6147                    .expect("replace restored inode");
6148            }
6149        });
6150
6151        assert!(
6152            result.is_err(),
6153            "restore must not return Restored when its inode is replaced around root-Head rebind"
6154        );
6155    }
6156
6157    #[test]
6158    fn released_root_restore_rebind_crash_retries_exactly_without_rewriting_authority() {
6159        let (root, store, transaction, transaction_bytes) = released_root_restore_fixture();
6160
6161        let interrupted = catch_unwind(AssertUnwindSafe(|| {
6162            store.restore_tombstone_with_hook("active.bin", |checkpoint| {
6163                if checkpoint == &RestoreCheckpoint::AfterLegacyRootHeadRebind {
6164                    panic!("terminate immediately after root-Head rebind CAS");
6165                }
6166            })
6167        }));
6168        assert!(interrupted.is_err());
6169
6170        let state = FolderbaseState::open_existing(root.path()).expect("state");
6171        let completion_before = fs::read(root.path().join(RESTORE_COMPLETION_PATH))
6172            .expect("completion receipt after rebind crash");
6173        let decoded_completion: RestoreCompletionReceipt =
6174            serde_json::from_slice(&completion_before).expect("completion JSON");
6175        assert_eq!(decoded_completion.transaction, transaction);
6176        assert_eq!(
6177            encode_restore_transaction(&decoded_completion.transaction)
6178                .expect("embedded transaction bytes"),
6179            transaction_bytes,
6180            "completion must retain the exact released-root transaction"
6181        );
6182        let authority_path = restore_authority_record_path(&transaction.transaction_id);
6183        let authority_before = state
6184            .read_bounded(&authority_path, MAX_RESTORE_AUTHORITY_BYTES)
6185            .expect("authority read")
6186            .expect("durable authority");
6187        let decoded_authority: RestoreAuthorityRecord =
6188            serde_json::from_slice(&authority_before).expect("authority JSON");
6189        assert_eq!(
6190            decoded_authority.root_instance_sha256,
6191            LEGACY_ROOT_INSTANCE_SHA256
6192        );
6193
6194        let first_retry = store
6195            .restore_tombstone("active.bin")
6196            .expect("post-rebind crash must retain exact committed result");
6197        let second_retry = store
6198            .restore_tombstone("active.bin")
6199            .expect("second identical retry must retain exact committed result");
6200        assert_eq!(first_retry, second_retry);
6201        assert_eq!(first_retry.version_id(), transaction.target_version_id);
6202        assert_eq!(
6203            fs::read(root.path().join(RESTORE_COMPLETION_PATH)).expect("completion after retries"),
6204            completion_before,
6205            "completion receipt bytes must remain immutable"
6206        );
6207        assert_eq!(
6208            state
6209                .read_bounded(&authority_path, MAX_RESTORE_AUTHORITY_BYTES)
6210                .expect("authority after retries")
6211                .expect("durable authority after retries"),
6212            authority_before,
6213            "restore authority bytes must remain immutable"
6214        );
6215    }
6216
6217    #[test]
6218    fn same_byte_foreign_target_after_staging_is_never_adopted_as_restore_owned() {
6219        let root = folderbase();
6220        let store = FolderbaseVersionStore::open(root.path()).expect("open");
6221        store
6222            .seal_capture(store.plan_capture().expect("genesis"))
6223            .expect("genesis");
6224        fs::remove_file(root.path().join("active.bin")).expect("delete");
6225        let deletion = store
6226            .seal_capture(store.plan_capture().expect("deletion"))
6227            .expect("deletion");
6228
6229        let error = store
6230            .restore_tombstone_with_hook("active.bin", |checkpoint| {
6231                if checkpoint == &RestoreCheckpoint::StageDurable {
6232                    fs::write(root.path().join("active.bin"), b"first opaque bytes")
6233                        .expect("same-byte foreign competitor");
6234                }
6235            })
6236            .expect_err("same-byte foreign target must not be transaction-owned");
6237        assert!(matches!(
6238            error,
6239            FolderbaseCaptureError::RestoreTargetOccupied(path)
6240                if path.ends_with("active.bin")
6241        ));
6242        assert_eq!(
6243            local_head(root.path()).expect("deletion Head").version_id,
6244            deletion.version_id()
6245        );
6246        assert!(
6247            read_active_restore_transaction(&FolderbaseState::open(root.path()).expect("state"))
6248                .expect("active restore")
6249                .is_some(),
6250            "durable intent and retained stage remain available for diagnosis/retry"
6251        );
6252        assert!(matches!(
6253            FolderbaseVersionStore::open(root.path())
6254                .expect("reopen")
6255                .restore_tombstone("active.bin"),
6256            Err(FolderbaseCaptureError::RestoreTargetOccupied(_))
6257        ));
6258        assert_eq!(
6259            fs::read(root.path().join("active.bin")).expect("foreign bytes preserved"),
6260            b"first opaque bytes"
6261        );
6262    }
6263
6264    #[test]
6265    fn capture_and_restore_active_journals_mutually_exclude_each_other() {
6266        let root = folderbase();
6267        let store = FolderbaseVersionStore::open(root.path()).expect("open");
6268        store
6269            .seal_capture(store.plan_capture().expect("genesis"))
6270            .expect("genesis");
6271        fs::remove_file(root.path().join("active.bin")).expect("delete");
6272        let deletion = store
6273            .seal_capture(store.plan_capture().expect("deletion"))
6274            .expect("deletion");
6275        fs::write(root.path().join("FOLDERBASE.md"), "# changed\n").expect("unrelated update");
6276        let interrupted = catch_unwind(AssertUnwindSafe(|| {
6277            store.seal_capture_with_hook(
6278                store.plan_capture().expect("capture plan"),
6279                |checkpoint| {
6280                    if checkpoint == &CaptureCheckpoint::JournalDurable {
6281                        panic!("leave capture active");
6282                    }
6283                },
6284            )
6285        }));
6286        assert!(interrupted.is_err());
6287        assert!(matches!(
6288            store.restore_tombstone("active.bin"),
6289            Err(FolderbaseCaptureError::ConflictingTransaction(message))
6290                if message.contains("capture")
6291        ));
6292        assert_eq!(
6293            local_head(root.path()).expect("deletion Head").version_id,
6294            deletion.version_id()
6295        );
6296
6297        let root = folderbase();
6298        let store = FolderbaseVersionStore::open(root.path()).expect("open");
6299        store
6300            .seal_capture(store.plan_capture().expect("genesis"))
6301            .expect("genesis");
6302        fs::remove_file(root.path().join("active.bin")).expect("delete");
6303        let deletion = store
6304            .seal_capture(store.plan_capture().expect("deletion"))
6305            .expect("deletion");
6306        let interrupted = catch_unwind(AssertUnwindSafe(|| {
6307            store.restore_tombstone_with_hook("active.bin", |checkpoint| {
6308                if checkpoint == &RestoreCheckpoint::JournalDurable {
6309                    panic!("leave restore active");
6310                }
6311            })
6312        }));
6313        assert!(interrupted.is_err());
6314        assert!(matches!(
6315            store.seal_capture(store.plan_capture().expect("capture plan")),
6316            Err(FolderbaseCaptureError::ConflictingTransaction(message))
6317                if message.contains("restore")
6318        ));
6319        assert_eq!(
6320            local_head(root.path()).expect("deletion Head").version_id,
6321            deletion.version_id()
6322        );
6323    }
6324
6325    #[test]
6326    fn restore_journal_and_head_tamper_fail_closed_before_workspace_publication() {
6327        let root = folderbase();
6328        let store = FolderbaseVersionStore::open(root.path()).expect("open");
6329        store
6330            .seal_capture(store.plan_capture().expect("genesis"))
6331            .expect("genesis");
6332        fs::remove_file(root.path().join("active.bin")).expect("delete");
6333        let deletion = store
6334            .seal_capture(store.plan_capture().expect("deletion"))
6335            .expect("deletion");
6336        let interrupted = catch_unwind(AssertUnwindSafe(|| {
6337            store.restore_tombstone_with_hook("active.bin", |checkpoint| {
6338                if checkpoint == &RestoreCheckpoint::JournalDurable {
6339                    panic!("leave restore journal");
6340                }
6341            })
6342        }));
6343        assert!(interrupted.is_err());
6344        let state = FolderbaseState::open(root.path()).expect("state");
6345        let mut transaction = read_active_restore_transaction(&state)
6346            .expect("journal")
6347            .expect("active");
6348        transaction.target_version_sha256 = "0".repeat(64);
6349        state
6350            .replace(
6351                Path::new(ACTIVE_RESTORE_TRANSACTION_PATH),
6352                &encode_restore_transaction(&transaction).expect("tampered journal"),
6353            )
6354            .expect("replace journal");
6355        assert!(matches!(
6356            store.restore_tombstone("active.bin"),
6357            Err(FolderbaseCaptureError::InvalidRestoreTransaction(_))
6358        ));
6359        assert!(!root.path().join("active.bin").exists());
6360        assert_eq!(
6361            local_head(root.path()).expect("deletion Head").version_id,
6362            deletion.version_id()
6363        );
6364
6365        let root = folderbase();
6366        let store = FolderbaseVersionStore::open(root.path()).expect("open");
6367        store
6368            .seal_capture(store.plan_capture().expect("genesis"))
6369            .expect("genesis");
6370        fs::remove_file(root.path().join("active.bin")).expect("delete");
6371        let deletion = store
6372            .seal_capture(store.plan_capture().expect("deletion"))
6373            .expect("deletion");
6374        let interrupted = catch_unwind(AssertUnwindSafe(|| {
6375            store.restore_tombstone_with_hook("active.bin", |checkpoint| {
6376                if checkpoint == &RestoreCheckpoint::JournalDurable {
6377                    panic!("leave restore journal");
6378                }
6379            })
6380        }));
6381        assert!(interrupted.is_err());
6382        let state = FolderbaseState::open(root.path()).expect("state");
6383        let mut head = read_head_record(&state).expect("Head").expect("Head");
6384        head.authority = LocalHeadAuthority::CaptureTransactionV1 {
6385            sha256: "0".repeat(64),
6386        };
6387        state
6388            .replace(
6389                Path::new(LOCAL_HEAD_PATH),
6390                &json_bytes(&head).expect("tampered Head"),
6391            )
6392            .expect("replace Head");
6393        assert!(matches!(
6394            store.restore_tombstone("active.bin"),
6395            Err(FolderbaseCaptureError::LocalHeadChanged)
6396        ));
6397        assert!(!root.path().join("active.bin").exists());
6398        assert_eq!(head.version_id, deletion.version_id());
6399
6400        let root = folderbase();
6401        let store = FolderbaseVersionStore::open(root.path()).expect("open");
6402        store
6403            .seal_capture(store.plan_capture().expect("genesis"))
6404            .expect("genesis");
6405        fs::remove_file(root.path().join("active.bin")).expect("delete");
6406        let deletion = store
6407            .seal_capture(store.plan_capture().expect("deletion"))
6408            .expect("deletion");
6409        let interrupted = catch_unwind(AssertUnwindSafe(|| {
6410            store.restore_tombstone_with_hook("active.bin", |checkpoint| {
6411                if checkpoint == &RestoreCheckpoint::JournalDurable {
6412                    panic!("leave restore journal");
6413                }
6414            })
6415        }));
6416        assert!(interrupted.is_err());
6417        let state = FolderbaseState::open(root.path()).expect("state");
6418        let mut transaction = read_active_restore_transaction(&state)
6419            .expect("journal")
6420            .expect("active");
6421        transaction.binding = PathBinding::regular_file_from_verified_producer(
6422            transaction.binding.path(),
6423            transaction.binding.object_id(),
6424            transaction
6425                .binding
6426                .object_version_id()
6427                .expect("Object Version"),
6428            transaction.binding.content_sha256().expect("digest"),
6429            transaction.binding.bytes().expect("bytes"),
6430            !transaction.binding.executable().expect("executable"),
6431        );
6432        let parent = store.read_version(deletion.version_id()).expect("parent");
6433        transaction.target_version_sha256 = restored_version(
6434            &store,
6435            &parent,
6436            &transaction.target_version_id,
6437            &transaction.created_at,
6438            &transaction.tombstone,
6439            &transaction.binding,
6440        )
6441        .expect("tampered target")
6442        .canonical_digest()
6443        .expect("tampered digest");
6444        state
6445            .replace(
6446                Path::new(ACTIVE_RESTORE_TRANSACTION_PATH),
6447                &encode_restore_transaction(&transaction).expect("tampered journal"),
6448            )
6449            .expect("replace journal");
6450        assert!(matches!(
6451            store.restore_tombstone("active.bin"),
6452            Err(FolderbaseCaptureError::InvalidRestoreTransaction(_))
6453        ));
6454        assert!(!root.path().join("active.bin").exists());
6455        assert_eq!(
6456            local_head(root.path()).expect("deletion Head").version_id,
6457            deletion.version_id()
6458        );
6459
6460        let root = folderbase();
6461        let store = FolderbaseVersionStore::open(root.path()).expect("open");
6462        store
6463            .seal_capture(store.plan_capture().expect("genesis"))
6464            .expect("genesis");
6465        fs::remove_file(root.path().join("active.bin")).expect("delete");
6466        let deletion = store
6467            .seal_capture(store.plan_capture().expect("deletion"))
6468            .expect("deletion");
6469        let interrupted = catch_unwind(AssertUnwindSafe(|| {
6470            store.restore_tombstone_with_hook("active.bin", |checkpoint| {
6471                if checkpoint == &RestoreCheckpoint::JournalDurable {
6472                    panic!("leave restore journal");
6473                }
6474            })
6475        }));
6476        assert!(interrupted.is_err());
6477        let state = FolderbaseState::open(root.path()).expect("state");
6478        let mut transaction = read_active_restore_transaction(&state)
6479            .expect("journal")
6480            .expect("active");
6481        transaction.target_version_id = format!("fbversion_{}", Uuid::now_v7());
6482        transaction.created_at = "2035-01-02T03:04:05Z".to_owned();
6483        let parent = store.read_version(deletion.version_id()).expect("parent");
6484        transaction.target_version_sha256 = restored_version(
6485            &store,
6486            &parent,
6487            &transaction.target_version_id,
6488            &transaction.created_at,
6489            &transaction.tombstone,
6490            &transaction.binding,
6491        )
6492        .expect("rewritten target")
6493        .canonical_digest()
6494        .expect("rewritten digest");
6495        state
6496            .replace(
6497                Path::new(ACTIVE_RESTORE_TRANSACTION_PATH),
6498                &encode_restore_transaction(&transaction).expect("tampered journal"),
6499            )
6500            .expect("replace journal");
6501        assert!(matches!(
6502            store.restore_tombstone("active.bin"),
6503            Err(FolderbaseCaptureError::InvalidRestoreTransaction(_))
6504        ));
6505        assert!(!root.path().join("active.bin").exists());
6506        assert_eq!(
6507            local_head(root.path()).expect("deletion Head").version_id,
6508            deletion.version_id()
6509        );
6510    }
6511
6512    #[test]
6513    fn committed_restore_rederives_authority_before_recovery() {
6514        let root = folderbase();
6515        let store = FolderbaseVersionStore::open(root.path()).expect("open");
6516        store
6517            .seal_capture(store.plan_capture().expect("genesis"))
6518            .expect("genesis");
6519        fs::remove_file(root.path().join("active.bin")).expect("delete");
6520        let deletion = store
6521            .seal_capture(store.plan_capture().expect("deletion"))
6522            .expect("deletion");
6523        let interrupted = catch_unwind(AssertUnwindSafe(|| {
6524            store.restore_tombstone_with_hook("active.bin", |checkpoint| {
6525                if checkpoint == &RestoreCheckpoint::HeadReplaced {
6526                    panic!("leave committed restore intent");
6527                }
6528            })
6529        }));
6530        assert!(interrupted.is_err());
6531
6532        let state = FolderbaseState::open(root.path()).expect("state");
6533        let mut transaction = read_active_restore_transaction(&state)
6534            .expect("journal")
6535            .expect("active");
6536        let parent = store.read_version(deletion.version_id()).expect("parent");
6537        transaction.expected_head.authority = LocalHeadAuthority::VersionDerivedV1 {
6538            sha256: "a".repeat(64),
6539        };
6540        let forged_parent_head = LocalHeadRecord {
6541            format: "folderbase-local-head-v2".to_owned(),
6542            folderbase_id: transaction.folderbase_id.clone(),
6543            root_instance_sha256: transaction.root_instance_sha256.clone(),
6544            version_id: transaction.expected_head.version_id.clone(),
6545            version_sha256: transaction.expected_head.version_sha256.clone(),
6546            authority: transaction.expected_head.authority.clone(),
6547        };
6548        let (transaction_id, target_version_id, created_at) = assigned_restore_identity(
6549            &store,
6550            &forged_parent_head,
6551            &parent,
6552            &transaction.tombstone,
6553            &transaction.binding,
6554        )
6555        .expect("forge every dependent deterministic assignment");
6556        transaction.transaction_id = transaction_id;
6557        transaction.target_version_id = target_version_id;
6558        transaction.created_at = created_at;
6559        let forged = restored_version(
6560            &store,
6561            &parent,
6562            &transaction.target_version_id,
6563            &transaction.created_at,
6564            &transaction.tombstone,
6565            &transaction.binding,
6566        )
6567        .expect("forged target");
6568        transaction.target_version_sha256 =
6569            forged.canonical_digest().expect("forged target digest");
6570        install_test_version(root.path(), &forged);
6571        let forged_stage_directory = root
6572            .path()
6573            .join(RESTORE_TRANSACTIONS_DIRECTORY)
6574            .join(&transaction.transaction_id);
6575        fs::create_dir(&forged_stage_directory).expect("forged transaction directory");
6576        fs::hard_link(
6577            root.path().join("active.bin"),
6578            forged_stage_directory.join("content"),
6579        )
6580        .expect("retain the published destination under the forged assignment");
6581        state
6582            .replace(
6583                Path::new(ACTIVE_RESTORE_TRANSACTION_PATH),
6584                &encode_restore_transaction(&transaction).expect("forged journal"),
6585            )
6586            .expect("replace journal");
6587        state
6588            .replace(
6589                Path::new(LOCAL_HEAD_PATH),
6590                &json_bytes(&LocalHeadRecord {
6591                    format: "folderbase-local-head-v2".to_owned(),
6592                    folderbase_id: transaction.folderbase_id.clone(),
6593                    root_instance_sha256: transaction.root_instance_sha256.clone(),
6594                    version_id: transaction.target_version_id.clone(),
6595                    version_sha256: transaction.target_version_sha256.clone(),
6596                    authority: LocalHeadAuthority::VersionDerivedV1 {
6597                        sha256: local_head_authority_sha256(
6598                            &store,
6599                            &transaction.target_version_id,
6600                            &transaction.target_version_sha256,
6601                        )
6602                        .expect("forged Head authority"),
6603                    },
6604                })
6605                .expect("forged Head"),
6606            )
6607            .expect("replace Head");
6608
6609        assert!(matches!(
6610            store.restore_tombstone("active.bin"),
6611            Err(FolderbaseCaptureError::InvalidRestoreTransaction(_))
6612        ));
6613    }
6614
6615    #[test]
6616    fn restore_ancestor_search_is_bounded_before_any_restore_intent() {
6617        let root = folderbase();
6618        let store = FolderbaseVersionStore::open(root.path()).expect("open");
6619        store
6620            .seal_capture(store.plan_capture().expect("genesis"))
6621            .expect("genesis");
6622        fs::remove_file(root.path().join("active.bin")).expect("delete");
6623        let deletion = store
6624            .seal_capture(store.plan_capture().expect("deletion"))
6625            .expect("deletion");
6626        let local = LocalVersionStore::open_read_only(root.path()).expect("local");
6627        let state = FolderbaseState::open_existing(root.path()).expect("state");
6628        let current =
6629            read_and_verify_folderbase_version(&store, &local, &state, deletion.version_id())
6630                .expect("current");
6631        let tombstone = &current.tombstones()[0];
6632
6633        assert!(matches!(
6634            find_restore_binding_with_limit(&store, &local, &state, &current, tombstone, 0),
6635            Err(FolderbaseCaptureError::InvalidRestoreAncestry(message))
6636                if message.contains("bounded")
6637        ));
6638        assert!(!root.path().join("active.bin").exists());
6639        assert!(
6640            read_active_restore_transaction(&state)
6641                .expect("active restore")
6642                .is_none()
6643        );
6644    }
6645
6646    #[test]
6647    fn reconstructed_tombstone_associations_are_path_scoped_for_shared_object_versions() {
6648        let root = folderbase();
6649        let store = FolderbaseVersionStore::open(root.path()).expect("open");
6650        let sealed = store
6651            .seal_capture(store.plan_capture().expect("genesis"))
6652            .expect("genesis");
6653        let version = store.read_version(sealed.version_id()).expect("version");
6654        let binding = version
6655            .lookup_binding("active.bin")
6656            .expect("active binding");
6657        let object_id = binding.object_id();
6658        let object_version_id = binding.object_version_id().expect("Object Version");
6659        let content_sha256 = binding.content_sha256().expect("content digest");
6660        let bytes = binding.bytes().expect("content bytes");
6661        let local = LocalVersionStore::open_read_only(root.path()).expect("local");
6662        let state = FolderbaseState::open_existing(root.path()).expect("state");
6663        prepare_reconstructed_history(&state).expect("reconstruction state");
6664
6665        let first_path = "deleted/first.bin";
6666        let second_path = "deleted/second.bin";
6667        for association in [
6668            ReconstructedTombstoneAssociation::for_tombstone(
6669                first_path,
6670                object_id,
6671                object_version_id,
6672                content_sha256,
6673                bytes,
6674                false,
6675            ),
6676            ReconstructedTombstoneAssociation::for_tombstone(
6677                second_path,
6678                object_id,
6679                object_version_id,
6680                content_sha256,
6681                bytes,
6682                true,
6683            ),
6684        ] {
6685            install_reconstructed_tombstone_association(&state, &association)
6686                .expect("path-scoped association");
6687        }
6688
6689        let first = Tombstone::from_verified_producer(
6690            first_path,
6691            object_id,
6692            DeletedKind::RegularFile,
6693            Some(object_version_id.to_owned()),
6694        );
6695        let second = Tombstone::from_verified_producer(
6696            second_path,
6697            object_id,
6698            DeletedKind::RegularFile,
6699            Some(object_version_id.to_owned()),
6700        );
6701        assert!(
6702            !read_reconstructed_tombstone_association(&local, &state, &first, object_version_id,)
6703                .expect("first association")
6704                .expect("first association exists")
6705                .executable
6706        );
6707        assert!(
6708            read_reconstructed_tombstone_association(&local, &state, &second, object_version_id,)
6709                .expect("second association")
6710                .expect("second association exists")
6711                .executable
6712        );
6713        assert_ne!(
6714            reconstructed_tombstone_association_relative_path(
6715                first_path,
6716                object_id,
6717                object_version_id,
6718            ),
6719            reconstructed_tombstone_association_relative_path(
6720                second_path,
6721                object_id,
6722                object_version_id,
6723            ),
6724        );
6725    }
6726
6727    #[test]
6728    fn reconstructed_tombstone_restore_rejects_path_substitution() {
6729        let root = folderbase();
6730        let store = FolderbaseVersionStore::open(root.path()).expect("open");
6731        let sealed = store
6732            .seal_capture(store.plan_capture().expect("genesis"))
6733            .expect("genesis");
6734        let version = store.read_version(sealed.version_id()).expect("version");
6735        let binding = version
6736            .lookup_binding("active.bin")
6737            .expect("active binding");
6738        let object_id = binding.object_id();
6739        let object_version_id = binding.object_version_id().expect("Object Version");
6740        let state = FolderbaseState::open_existing(root.path()).expect("state");
6741        prepare_reconstructed_history(&state).expect("reconstruction state");
6742        let expected_path = "deleted/expected.bin";
6743        let tombstone = Tombstone::from_verified_producer(
6744            expected_path,
6745            object_id,
6746            DeletedKind::RegularFile,
6747            Some(object_version_id.to_owned()),
6748        );
6749        let current = FolderbaseVersion::from_verified_parts(
6750            FolderbaseVersionParts::portable_v1_from_verified_producer(
6751                version.folderbase_id(),
6752                format!("fbversion_{}", Uuid::now_v7()),
6753                Vec::new(),
6754                version.created_at(),
6755                version.root_manifest().clone(),
6756                FolderbaseVersionEntries::from_verified_producer(
6757                    version
6758                        .bindings()
6759                        .iter()
6760                        .filter(|candidate| candidate.path() != "active.bin")
6761                        .cloned()
6762                        .collect(),
6763                    vec![tombstone],
6764                    version.exclusions().to_vec(),
6765                ),
6766            ),
6767        )
6768        .expect("reconstructed current Version");
6769        install_test_version(root.path(), &current);
6770        point_test_head(root.path(), &current);
6771        let substituted = ReconstructedTombstoneAssociation::for_tombstone(
6772            "deleted/substituted.bin",
6773            object_id,
6774            object_version_id,
6775            binding.content_sha256().expect("content digest"),
6776            binding.bytes().expect("content bytes"),
6777            false,
6778        );
6779        state
6780            .replace(
6781                &reconstructed_tombstone_association_relative_path(
6782                    expected_path,
6783                    object_id,
6784                    object_version_id,
6785                ),
6786                &json_bytes(&substituted).expect("association bytes"),
6787            )
6788            .expect("substitute association path");
6789        fs::create_dir_all(root.path().join("deleted")).expect("restore destination parent");
6790
6791        let error = FolderbaseVersionStore::open(root.path())
6792            .expect("reopen")
6793            .restore_tombstone(expected_path)
6794            .expect_err("path-substituted association must be refused");
6795        assert!(
6796            matches!(
6797                &error,
6798                FolderbaseCaptureError::InvalidRestoreAncestry(message)
6799                    if message.contains("does not match the current Tombstone")
6800            ),
6801            "unexpected restore error: {error:?}"
6802        );
6803    }
6804
6805    #[test]
6806    fn nearest_ancestor_fidelity_disagreement_is_refused_as_ambiguous() {
6807        let root = folderbase();
6808        let store = FolderbaseVersionStore::open(root.path()).expect("open");
6809        let genesis = store
6810            .seal_capture(store.plan_capture().expect("genesis"))
6811            .expect("genesis");
6812        let genesis_version = store.read_version(genesis.version_id()).expect("genesis");
6813        let original = genesis_version
6814            .lookup_binding("active.bin")
6815            .expect("active")
6816            .clone();
6817        let alternate_binding = PathBinding::regular_file_from_verified_producer(
6818            original.path(),
6819            original.object_id(),
6820            original.object_version_id().expect("Object Version"),
6821            original.content_sha256().expect("digest"),
6822            original.bytes().expect("bytes"),
6823            !original.executable().expect("executable"),
6824        );
6825        let mut alternate_bindings = genesis_version.bindings().to_vec();
6826        let index = alternate_bindings
6827            .iter()
6828            .position(|binding| binding.path() == "active.bin")
6829            .expect("active index");
6830        alternate_bindings[index] = alternate_binding;
6831        let alternate = FolderbaseVersion::from_verified_parts(
6832            FolderbaseVersionParts::portable_v1_from_verified_producer(
6833                genesis_version.folderbase_id(),
6834                format!("fbversion_{}", Uuid::now_v7()),
6835                Vec::new(),
6836                Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true),
6837                genesis_version.root_manifest().clone(),
6838                FolderbaseVersionEntries::from_verified_producer(
6839                    alternate_bindings,
6840                    Vec::new(),
6841                    genesis_version.exclusions().to_vec(),
6842                ),
6843            ),
6844        )
6845        .expect("alternate");
6846        install_test_version(root.path(), &alternate);
6847
6848        fs::remove_file(root.path().join("active.bin")).expect("delete");
6849        let current = FolderbaseVersion::from_verified_parts(
6850            FolderbaseVersionParts::portable_v1_from_verified_producer(
6851                genesis_version.folderbase_id(),
6852                format!("fbversion_{}", Uuid::now_v7()),
6853                vec![
6854                    genesis_version.version_id().to_owned(),
6855                    alternate.version_id().to_owned(),
6856                ],
6857                Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true),
6858                genesis_version.root_manifest().clone(),
6859                FolderbaseVersionEntries::from_verified_producer(
6860                    genesis_version
6861                        .bindings()
6862                        .iter()
6863                        .filter(|binding| binding.path() != "active.bin")
6864                        .cloned()
6865                        .collect(),
6866                    vec![Tombstone::from_verified_producer(
6867                        original.path(),
6868                        original.object_id(),
6869                        DeletedKind::RegularFile,
6870                        original.object_version_id().map(str::to_owned),
6871                    )],
6872                    genesis_version.exclusions().to_vec(),
6873                ),
6874            ),
6875        )
6876        .expect("ambiguous current");
6877        install_test_version(root.path(), &current);
6878        point_test_head(root.path(), &current);
6879
6880        assert!(matches!(
6881            FolderbaseVersionStore::open(root.path())
6882                .expect("reopen")
6883                .restore_tombstone("active.bin"),
6884            Err(FolderbaseCaptureError::InvalidRestoreAncestry(message))
6885                if message.contains("disagree")
6886        ));
6887        assert!(!root.path().join("active.bin").exists());
6888    }
6889
6890    #[test]
6891    fn cyclic_ancestor_graph_is_refused_before_restore_publication() {
6892        let root = folderbase();
6893        let store = FolderbaseVersionStore::open(root.path()).expect("open");
6894        let genesis = store
6895            .seal_capture(store.plan_capture().expect("genesis"))
6896            .expect("genesis");
6897        let genesis_version = store.read_version(genesis.version_id()).expect("genesis");
6898        let original = genesis_version
6899            .lookup_binding("active.bin")
6900            .expect("active")
6901            .clone();
6902        fs::remove_file(root.path().join("active.bin")).expect("delete");
6903        let surviving = genesis_version
6904            .bindings()
6905            .iter()
6906            .filter(|binding| binding.path() != "active.bin")
6907            .cloned()
6908            .collect::<Vec<_>>();
6909        let tombstones = vec![Tombstone::from_verified_producer(
6910            original.path(),
6911            original.object_id(),
6912            DeletedKind::RegularFile,
6913            original.object_version_id().map(str::to_owned),
6914        )];
6915        let first_id = format!("fbversion_{}", Uuid::now_v7());
6916        let second_id = format!("fbversion_{}", Uuid::now_v7());
6917        let cycle_version = |version_id: &str, parent: &str| {
6918            FolderbaseVersion::from_verified_parts(
6919                FolderbaseVersionParts::portable_v1_from_verified_producer(
6920                    genesis_version.folderbase_id(),
6921                    version_id,
6922                    vec![parent.to_owned()],
6923                    Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true),
6924                    genesis_version.root_manifest().clone(),
6925                    FolderbaseVersionEntries::from_verified_producer(
6926                        surviving.clone(),
6927                        tombstones.clone(),
6928                        genesis_version.exclusions().to_vec(),
6929                    ),
6930                ),
6931            )
6932            .expect("cycle member")
6933        };
6934        let first = cycle_version(&first_id, &second_id);
6935        let second = cycle_version(&second_id, &first_id);
6936        install_test_version(root.path(), &first);
6937        install_test_version(root.path(), &second);
6938        let current = FolderbaseVersion::from_verified_parts(
6939            FolderbaseVersionParts::portable_v1_from_verified_producer(
6940                genesis_version.folderbase_id(),
6941                format!("fbversion_{}", Uuid::now_v7()),
6942                vec![first_id],
6943                Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true),
6944                genesis_version.root_manifest().clone(),
6945                FolderbaseVersionEntries::from_verified_producer(
6946                    surviving,
6947                    tombstones,
6948                    genesis_version.exclusions().to_vec(),
6949                ),
6950            ),
6951        )
6952        .expect("current");
6953        install_test_version(root.path(), &current);
6954        point_test_head(root.path(), &current);
6955
6956        assert!(matches!(
6957            FolderbaseVersionStore::open(root.path())
6958                .expect("reopen")
6959                .restore_tombstone("active.bin"),
6960            Err(FolderbaseCaptureError::InvalidRestoreAncestry(message))
6961                if message.contains("cycle")
6962        ));
6963        assert!(!root.path().join("active.bin").exists());
6964    }
6965
6966    #[test]
6967    fn nearest_candidate_does_not_hide_a_deeper_ancestor_cycle() {
6968        let root = folderbase();
6969        let store = FolderbaseVersionStore::open(root.path()).expect("open");
6970        let genesis = store
6971            .seal_capture(store.plan_capture().expect("genesis"))
6972            .expect("genesis");
6973        let genesis_version = store.read_version(genesis.version_id()).expect("genesis");
6974        let original = genesis_version
6975            .lookup_binding("active.bin")
6976            .expect("active")
6977            .clone();
6978        fs::remove_file(root.path().join("active.bin")).expect("delete");
6979        let surviving = genesis_version
6980            .bindings()
6981            .iter()
6982            .filter(|binding| binding.path() != "active.bin")
6983            .cloned()
6984            .collect::<Vec<_>>();
6985        let tombstones = vec![Tombstone::from_verified_producer(
6986            original.path(),
6987            original.object_id(),
6988            DeletedKind::RegularFile,
6989            original.object_version_id().map(str::to_owned),
6990        )];
6991        let candidate_id = format!("fbversion_{}", Uuid::now_v7());
6992        let deeper_id = format!("fbversion_{}", Uuid::now_v7());
6993        let candidate = FolderbaseVersion::from_verified_parts(
6994            FolderbaseVersionParts::portable_v1_from_verified_producer(
6995                genesis_version.folderbase_id(),
6996                &candidate_id,
6997                vec![deeper_id.clone()],
6998                genesis_version.created_at(),
6999                genesis_version.root_manifest().clone(),
7000                FolderbaseVersionEntries::from_verified_producer(
7001                    genesis_version.bindings().to_vec(),
7002                    Vec::new(),
7003                    genesis_version.exclusions().to_vec(),
7004                ),
7005            ),
7006        )
7007        .expect("candidate");
7008        let deeper = FolderbaseVersion::from_verified_parts(
7009            FolderbaseVersionParts::portable_v1_from_verified_producer(
7010                genesis_version.folderbase_id(),
7011                &deeper_id,
7012                vec![candidate_id.clone()],
7013                genesis_version.created_at(),
7014                genesis_version.root_manifest().clone(),
7015                FolderbaseVersionEntries::from_verified_producer(
7016                    surviving.clone(),
7017                    tombstones.clone(),
7018                    genesis_version.exclusions().to_vec(),
7019                ),
7020            ),
7021        )
7022        .expect("deeper cycle");
7023        install_test_version(root.path(), &candidate);
7024        install_test_version(root.path(), &deeper);
7025        let current = FolderbaseVersion::from_verified_parts(
7026            FolderbaseVersionParts::portable_v1_from_verified_producer(
7027                genesis_version.folderbase_id(),
7028                format!("fbversion_{}", Uuid::now_v7()),
7029                vec![candidate_id],
7030                genesis_version.created_at(),
7031                genesis_version.root_manifest().clone(),
7032                FolderbaseVersionEntries::from_verified_producer(
7033                    surviving,
7034                    tombstones,
7035                    genesis_version.exclusions().to_vec(),
7036                ),
7037            ),
7038        )
7039        .expect("current");
7040        install_test_version(root.path(), &current);
7041        point_test_head(root.path(), &current);
7042
7043        assert!(matches!(
7044            FolderbaseVersionStore::open(root.path())
7045                .expect("reopen")
7046                .restore_tombstone("active.bin"),
7047            Err(FolderbaseCaptureError::InvalidRestoreAncestry(message))
7048                if message.contains("cycle")
7049        ));
7050        assert!(!root.path().join("active.bin").exists());
7051    }
7052
7053    #[test]
7054    fn convergent_ancestor_dag_restores_from_one_shared_verified_candidate() {
7055        let root = folderbase();
7056        let store = FolderbaseVersionStore::open(root.path()).expect("open");
7057        let genesis = store
7058            .seal_capture(store.plan_capture().expect("genesis"))
7059            .expect("genesis");
7060        let genesis_version = store.read_version(genesis.version_id()).expect("genesis");
7061        let original = genesis_version
7062            .lookup_binding("active.bin")
7063            .expect("active")
7064            .clone();
7065        fs::remove_file(root.path().join("active.bin")).expect("delete");
7066        let surviving = genesis_version
7067            .bindings()
7068            .iter()
7069            .filter(|binding| binding.path() != "active.bin")
7070            .cloned()
7071            .collect::<Vec<_>>();
7072        let tombstones = vec![Tombstone::from_verified_producer(
7073            original.path(),
7074            original.object_id(),
7075            DeletedKind::RegularFile,
7076            original.object_version_id().map(str::to_owned),
7077        )];
7078        let branch = |version_id: String| {
7079            FolderbaseVersion::from_verified_parts(
7080                FolderbaseVersionParts::portable_v1_from_verified_producer(
7081                    genesis_version.folderbase_id(),
7082                    version_id,
7083                    vec![genesis_version.version_id().to_owned()],
7084                    genesis_version.created_at(),
7085                    genesis_version.root_manifest().clone(),
7086                    FolderbaseVersionEntries::from_verified_producer(
7087                        surviving.clone(),
7088                        tombstones.clone(),
7089                        genesis_version.exclusions().to_vec(),
7090                    ),
7091                ),
7092            )
7093            .expect("branch")
7094        };
7095        let left = branch(format!("fbversion_{}", Uuid::now_v7()));
7096        let right = branch(format!("fbversion_{}", Uuid::now_v7()));
7097        install_test_version(root.path(), &left);
7098        install_test_version(root.path(), &right);
7099        let current = FolderbaseVersion::from_verified_parts(
7100            FolderbaseVersionParts::portable_v1_from_verified_producer(
7101                genesis_version.folderbase_id(),
7102                format!("fbversion_{}", Uuid::now_v7()),
7103                vec![left.version_id().to_owned(), right.version_id().to_owned()],
7104                genesis_version.created_at(),
7105                genesis_version.root_manifest().clone(),
7106                FolderbaseVersionEntries::from_verified_producer(
7107                    surviving,
7108                    tombstones,
7109                    genesis_version.exclusions().to_vec(),
7110                ),
7111            ),
7112        )
7113        .expect("convergent current");
7114        install_test_version(root.path(), &current);
7115        point_test_head(root.path(), &current);
7116
7117        FolderbaseVersionStore::open(root.path())
7118            .expect("reopen")
7119            .restore_tombstone("active.bin")
7120            .expect("restore through convergent DAG");
7121        assert_eq!(
7122            fs::read(root.path().join("active.bin")).expect("restored"),
7123            b"first opaque bytes"
7124        );
7125    }
7126
7127    #[test]
7128    fn convergent_edges_cannot_hide_any_reachable_ancestor_cycle() {
7129        for shape in ["shared-cycle", "cross-branch-cycle"] {
7130            let root = folderbase();
7131            let store = FolderbaseVersionStore::open(root.path()).expect("open");
7132            let genesis = store
7133                .seal_capture(store.plan_capture().expect("genesis"))
7134                .expect("genesis");
7135            let genesis_version = store.read_version(genesis.version_id()).expect("genesis");
7136            let original = genesis_version
7137                .lookup_binding("active.bin")
7138                .expect("active")
7139                .clone();
7140            fs::remove_file(root.path().join("active.bin")).expect("delete");
7141            let surviving = genesis_version
7142                .bindings()
7143                .iter()
7144                .filter(|binding| binding.path() != "active.bin")
7145                .cloned()
7146                .collect::<Vec<_>>();
7147            let tombstones = vec![Tombstone::from_verified_producer(
7148                original.path(),
7149                original.object_id(),
7150                DeletedKind::RegularFile,
7151                original.object_version_id().map(str::to_owned),
7152            )];
7153            let a = format!("fbversion_{}", Uuid::now_v7());
7154            let b = format!("fbversion_{}", Uuid::now_v7());
7155            let c = format!("fbversion_{}", Uuid::now_v7());
7156            let d = format!("fbversion_{}", Uuid::now_v7());
7157            let definitions = match shape {
7158                "shared-cycle" => vec![
7159                    (a.clone(), vec![c.clone()], true),
7160                    (b.clone(), vec![c.clone()], false),
7161                    (c.clone(), vec![b.clone()], false),
7162                ],
7163                "cross-branch-cycle" => vec![
7164                    (a.clone(), vec![c.clone()], true),
7165                    (b.clone(), vec![d.clone()], false),
7166                    (c.clone(), vec![d.clone()], false),
7167                    (d.clone(), vec![a.clone()], false),
7168                ],
7169                _ => unreachable!(),
7170            };
7171            for (version_id, parents, live) in definitions {
7172                let version = FolderbaseVersion::from_verified_parts(
7173                    FolderbaseVersionParts::portable_v1_from_verified_producer(
7174                        genesis_version.folderbase_id(),
7175                        version_id,
7176                        parents,
7177                        genesis_version.created_at(),
7178                        genesis_version.root_manifest().clone(),
7179                        FolderbaseVersionEntries::from_verified_producer(
7180                            if live {
7181                                genesis_version.bindings().to_vec()
7182                            } else {
7183                                surviving.clone()
7184                            },
7185                            if live { Vec::new() } else { tombstones.clone() },
7186                            genesis_version.exclusions().to_vec(),
7187                        ),
7188                    ),
7189                )
7190                .expect("graph member");
7191                install_test_version(root.path(), &version);
7192            }
7193            let current = FolderbaseVersion::from_verified_parts(
7194                FolderbaseVersionParts::portable_v1_from_verified_producer(
7195                    genesis_version.folderbase_id(),
7196                    format!("fbversion_{}", Uuid::now_v7()),
7197                    vec![a, b],
7198                    genesis_version.created_at(),
7199                    genesis_version.root_manifest().clone(),
7200                    FolderbaseVersionEntries::from_verified_producer(
7201                        surviving,
7202                        tombstones,
7203                        genesis_version.exclusions().to_vec(),
7204                    ),
7205                ),
7206            )
7207            .expect("current");
7208            install_test_version(root.path(), &current);
7209            point_test_head(root.path(), &current);
7210
7211            assert!(matches!(
7212                FolderbaseVersionStore::open(root.path())
7213                    .expect("reopen")
7214                    .restore_tombstone("active.bin"),
7215                Err(FolderbaseCaptureError::InvalidRestoreAncestry(message))
7216                    if message.contains("cycle")
7217            ));
7218        }
7219    }
7220
7221    #[test]
7222    fn restore_revalidates_owned_target_and_boundary_before_and_after_head() {
7223        for mutation in [
7224            "same-byte-replacement",
7225            "in-place",
7226            "late-boundary",
7227            "post-head",
7228            "post-head-in-place",
7229        ] {
7230            let root = folderbase();
7231            let store = FolderbaseVersionStore::open(root.path()).expect("open");
7232            store
7233                .seal_capture(store.plan_capture().expect("genesis"))
7234                .expect("genesis");
7235            fs::remove_file(root.path().join("active.bin")).expect("delete");
7236            let deletion = store
7237                .seal_capture(store.plan_capture().expect("deletion"))
7238                .expect("deletion");
7239            let result = store.restore_tombstone_with_hook("active.bin", |checkpoint| {
7240                if checkpoint == &RestoreCheckpoint::TargetPublished {
7241                    match mutation {
7242                        "same-byte-replacement" => {
7243                            fs::remove_file(root.path().join("active.bin")).expect("unlink target");
7244                            fs::write(root.path().join("active.bin"), b"first opaque bytes")
7245                                .expect("replace with same bytes");
7246                        }
7247                        "in-place" => {
7248                            fs::write(root.path().join("active.bin"), b"mutated")
7249                                .expect("mutate target inode");
7250                        }
7251                        "late-boundary" => {
7252                            fs::create_dir_all(root.path().join(".folderbase-probe")).ok();
7253                        }
7254                        _ => {}
7255                    }
7256                }
7257                if mutation == "post-head" && checkpoint == &RestoreCheckpoint::HeadReplaced {
7258                    fs::remove_file(root.path().join("active.bin"))
7259                        .expect("unlink committed target");
7260                    fs::write(root.path().join("active.bin"), b"first opaque bytes")
7261                        .expect("post-Head same-byte replacement");
7262                }
7263                if mutation == "post-head-in-place"
7264                    && checkpoint == &RestoreCheckpoint::HeadReplaced
7265                {
7266                    fs::write(root.path().join("active.bin"), b"post-Head mutation")
7267                        .expect("post-Head in-place mutation");
7268                }
7269            });
7270            if mutation == "late-boundary" {
7271                // Root-level content has no ancestor at which to introduce a
7272                // nested boundary; this case is covered by the nested-path test.
7273                assert!(result.is_ok());
7274                continue;
7275            }
7276            assert!(result.is_err(), "{mutation} must fail closed");
7277            assert_eq!(
7278                local_head(root.path()).expect("deletion Head").version_id,
7279                deletion.version_id(),
7280                "{mutation} must not leave the restore Head committed"
7281            );
7282        }
7283    }
7284
7285    #[test]
7286    fn in_place_edit_of_published_restore_is_preserved_and_capture_is_unblocked() {
7287        for fault in [
7288            RestoreCheckpoint::TargetPublished,
7289            RestoreCheckpoint::HeadReplaced,
7290        ] {
7291            let root = folderbase();
7292            let store = FolderbaseVersionStore::open(root.path()).expect("open");
7293            store
7294                .seal_capture(store.plan_capture().expect("genesis"))
7295                .expect("genesis");
7296            fs::remove_file(root.path().join("active.bin")).expect("delete");
7297            let deletion = store
7298                .seal_capture(store.plan_capture().expect("deletion"))
7299                .expect("deletion");
7300            let user_bytes = format!("user work after {fault:?}");
7301
7302            store
7303                .restore_tombstone_with_hook("active.bin", |checkpoint| {
7304                    if checkpoint == &fault {
7305                        fs::write(root.path().join("active.bin"), user_bytes.as_bytes())
7306                            .expect("edit published file in place");
7307                    }
7308                })
7309                .expect_err("an in-place edit must stop the restore");
7310
7311            assert_eq!(
7312                fs::read(root.path().join("active.bin")).expect("preserved user work"),
7313                user_bytes.as_bytes()
7314            );
7315            assert_eq!(
7316                local_head(root.path()).expect("deletion Head").version_id,
7317                deletion.version_id(),
7318                "restore must roll back before relinquishing the edited file"
7319            );
7320
7321            let captured = store
7322                .seal_capture(store.plan_capture().expect("capture edited workspace"))
7323                .expect("the abandoned restore must not block a normal capture");
7324            let captured_version = store
7325                .read_version(captured.version_id())
7326                .expect("captured version");
7327            assert_eq!(
7328                captured_version.parents(),
7329                &[deletion.version_id().to_owned()]
7330            );
7331            assert_eq!(
7332                fs::read(root.path().join("active.bin")).expect("captured user work"),
7333                user_bytes.as_bytes()
7334            );
7335        }
7336    }
7337
7338    #[cfg(unix)]
7339    #[test]
7340    fn modified_restore_cleanup_failure_reopens_and_capture_adopts_preserved_bytes() {
7341        use std::{
7342            cell::RefCell,
7343            os::unix::fs::{MetadataExt, PermissionsExt},
7344        };
7345
7346        let root = folderbase();
7347        let store = FolderbaseVersionStore::open(root.path()).expect("open");
7348        store
7349            .seal_capture(store.plan_capture().expect("genesis"))
7350            .expect("genesis");
7351        fs::remove_file(root.path().join("active.bin")).expect("delete");
7352        store
7353            .seal_capture(store.plan_capture().expect("deletion"))
7354            .expect("deletion");
7355        let transaction_directory = RefCell::new(None);
7356        let user_bytes = b"user work preserved across cleanup failure";
7357
7358        let cleanup_error = store
7359            .restore_tombstone_with_hook("active.bin", |checkpoint| {
7360                if checkpoint == &RestoreCheckpoint::TargetPublished {
7361                    let transaction = read_active_restore_transaction(
7362                        &FolderbaseState::open(root.path()).expect("state"),
7363                    )
7364                    .expect("restore journal")
7365                    .expect("active restore");
7366                    let directory = root
7367                        .path()
7368                        .join(restore_transaction_directory(&transaction));
7369                    transaction_directory.replace(Some(directory.clone()));
7370                    fs::write(root.path().join("active.bin"), user_bytes)
7371                        .expect("edit restored target in place");
7372                    fs::set_permissions(&directory, fs::Permissions::from_mode(0o500))
7373                        .expect("deny private stage cleanup");
7374                }
7375            })
7376            .expect_err("private-stage cleanup failure must be reported");
7377        assert!(matches!(
7378            cleanup_error,
7379            FolderbaseCaptureError::LocalStore(FolderbaseError::Io { .. })
7380        ));
7381        assert_eq!(
7382            fs::read(root.path().join("active.bin")).expect("preserved workspace bytes"),
7383            user_bytes
7384        );
7385        assert!(
7386            fs::metadata(root.path().join("active.bin"))
7387                .expect("preserved workspace metadata")
7388                .nlink()
7389                > 1,
7390            "failed cleanup must leave the visible file linked to its private stage"
7391        );
7392
7393        let transaction_directory = transaction_directory
7394            .into_inner()
7395            .expect("transaction directory");
7396        fs::set_permissions(&transaction_directory, fs::Permissions::from_mode(0o700))
7397            .expect("restore cleanup permissions");
7398        drop(store);
7399
7400        let reopened = FolderbaseVersionStore::open(root.path()).expect("fresh-process reopen");
7401        assert!(matches!(
7402            reopened.restore_tombstone("active.bin"),
7403            Err(FolderbaseCaptureError::RestoreTargetOccupied(path))
7404                if path == Path::new("active.bin")
7405        ));
7406        let captured = reopened
7407            .seal_capture(
7408                reopened
7409                    .plan_capture()
7410                    .expect("capture preserved user work"),
7411            )
7412            .expect("completed cleanup must unblock capture");
7413        let captured_version = reopened
7414            .read_version(captured.version_id())
7415            .expect("captured version");
7416        let binding = captured_version
7417            .lookup_binding("active.bin")
7418            .expect("preserved user work must become a live binding");
7419        assert_eq!(binding.bytes(), Some(user_bytes.len() as u64));
7420        assert_eq!(
7421            fs::metadata(root.path().join("active.bin"))
7422                .expect("captured workspace metadata")
7423                .nlink(),
7424            2,
7425            "capture keeps exactly one validated Folderbase authority link"
7426        );
7427        assert!(
7428            transaction_directory
7429                .join(RESTORE_AUTHORITY_FILENAME)
7430                .is_file(),
7431            "cleanup retry must retain a durable authority receipt"
7432        );
7433    }
7434
7435    #[cfg(unix)]
7436    #[test]
7437    fn modified_restore_cleanup_retry_accepts_the_same_owned_inode_reverted_to_sealed_bytes() {
7438        use std::{cell::RefCell, os::unix::fs::PermissionsExt};
7439
7440        let root = folderbase();
7441        let store = FolderbaseVersionStore::open(root.path()).expect("open");
7442        store
7443            .seal_capture(store.plan_capture().expect("genesis"))
7444            .expect("genesis");
7445        fs::remove_file(root.path().join("active.bin")).expect("delete");
7446        store
7447            .seal_capture(store.plan_capture().expect("deletion"))
7448            .expect("deletion");
7449        let transaction_directory = RefCell::new(None);
7450
7451        store
7452            .restore_tombstone_with_hook("active.bin", |checkpoint| {
7453                if checkpoint == &RestoreCheckpoint::TargetPublished {
7454                    let transaction = read_active_restore_transaction(
7455                        &FolderbaseState::open(root.path()).expect("state"),
7456                    )
7457                    .expect("restore journal")
7458                    .expect("active restore");
7459                    let directory = root
7460                        .path()
7461                        .join(restore_transaction_directory(&transaction));
7462                    transaction_directory.replace(Some(directory.clone()));
7463                    fs::write(root.path().join("active.bin"), b"temporary user edit")
7464                        .expect("edit restored target in place");
7465                    fs::set_permissions(&directory, fs::Permissions::from_mode(0o500))
7466                        .expect("deny private stage cleanup");
7467                }
7468            })
7469            .expect_err("private-stage cleanup failure must be reported");
7470
7471        let transaction_directory = transaction_directory
7472            .into_inner()
7473            .expect("transaction directory");
7474        fs::set_permissions(&transaction_directory, fs::Permissions::from_mode(0o700))
7475            .expect("restore cleanup permissions");
7476        fs::write(root.path().join("active.bin"), b"first opaque bytes")
7477            .expect("revert the same restore-owned inode");
7478        drop(store);
7479
7480        let reopened = FolderbaseVersionStore::open(root.path()).expect("fresh-process reopen");
7481        assert!(matches!(
7482            reopened.restore_tombstone("active.bin"),
7483            Err(FolderbaseCaptureError::RestoreTargetOccupied(path))
7484                if path == Path::new("active.bin")
7485        ));
7486        assert!(
7487            transaction_directory
7488                .join(RESTORE_AUTHORITY_FILENAME)
7489                .is_file(),
7490            "durable modified ownership must become a retained capture authority"
7491        );
7492        reopened
7493            .seal_capture(reopened.plan_capture().expect("capture reverted file"))
7494            .expect("completed cleanup must leave capture unblocked");
7495    }
7496
7497    #[cfg(unix)]
7498    #[test]
7499    fn coordinated_modified_receipt_and_active_rewrite_cannot_retire_forged_state() {
7500        use std::{cell::RefCell, os::unix::fs::PermissionsExt};
7501
7502        let root = folderbase();
7503        let store = FolderbaseVersionStore::open(root.path()).expect("open");
7504        store
7505            .seal_capture(store.plan_capture().expect("genesis"))
7506            .expect("genesis");
7507        fs::remove_file(root.path().join("active.bin")).expect("delete");
7508        store
7509            .seal_capture(store.plan_capture().expect("deletion"))
7510            .expect("deletion");
7511        let transaction_directory = RefCell::new(None);
7512
7513        store
7514            .restore_tombstone_with_hook("active.bin", |checkpoint| {
7515                if checkpoint == &RestoreCheckpoint::TargetPublished {
7516                    let transaction = read_active_restore_transaction(
7517                        &FolderbaseState::open(root.path()).expect("state"),
7518                    )
7519                    .expect("restore journal")
7520                    .expect("active restore");
7521                    let directory = root
7522                        .path()
7523                        .join(restore_transaction_directory(&transaction));
7524                    transaction_directory.replace(Some(directory.clone()));
7525                    fs::write(root.path().join("active.bin"), b"user-edited restore")
7526                        .expect("edit restored target in place");
7527                    fs::set_permissions(&directory, fs::Permissions::from_mode(0o500))
7528                        .expect("deny private stage cleanup");
7529                }
7530            })
7531            .expect_err("private-stage cleanup failure must be reported");
7532
7533        let real_transaction_directory = transaction_directory
7534            .into_inner()
7535            .expect("real transaction directory");
7536        fs::set_permissions(
7537            &real_transaction_directory,
7538            fs::Permissions::from_mode(0o700),
7539        )
7540        .expect("restore cleanup permissions");
7541        let state = FolderbaseState::open(root.path()).expect("state");
7542        let mut forged = read_active_restore_transaction(&state)
7543            .expect("active restore")
7544            .expect("durable active restore");
7545        forged.transaction_id = "fbrestore_00000000-0000-8000-8000-000000000001".to_owned();
7546        let forged_directory = root.path().join(restore_transaction_directory(&forged));
7547        fs::create_dir(&forged_directory).expect("forged transaction directory");
7548        fs::hard_link(
7549            root.path().join("active.bin"),
7550            forged_directory.join("content"),
7551        )
7552        .expect("forged private link");
7553        state
7554            .replace(
7555                Path::new(ACTIVE_RESTORE_TRANSACTION_PATH),
7556                &encode_restore_transaction(&forged).expect("forged active bytes"),
7557            )
7558            .expect("coordinated active rewrite");
7559        let forged_identity_sha256 = state
7560            .workspace_restore_identity_sha256(
7561                &restore_stage_path(&forged),
7562                Path::new(&forged.path),
7563            )
7564            .expect("forged publication identity");
7565        state
7566            .replace(
7567                Path::new(RESTORE_CLEANUP_RECOVERY_PATH),
7568                &encode_restore_cleanup_recovery(&RestoreCleanupRecovery {
7569                    format: RESTORE_CLEANUP_RECOVERY_FORMAT_V2.to_owned(),
7570                    disposition: RestoreCleanupDisposition::Modified,
7571                    transaction: forged.clone(),
7572                    published_identity_sha256: forged_identity_sha256,
7573                })
7574                .expect("forged cleanup bytes"),
7575            )
7576            .expect("coordinated cleanup rewrite");
7577        drop(state);
7578        drop(store);
7579
7580        let error = FolderbaseVersionStore::open(root.path())
7581            .expect("fresh-process reopen")
7582            .restore_tombstone("active.bin")
7583            .expect_err("mutable journals cannot assign cleanup ownership");
7584        assert!(matches!(
7585            error,
7586            FolderbaseCaptureError::InvalidRestoreTransaction(_)
7587        ));
7588        assert!(
7589            real_transaction_directory.join("content").exists(),
7590            "forged cleanup must not strand and forget the real private stage"
7591        );
7592        assert!(
7593            forged_directory.join("content").exists(),
7594            "untrusted forged state must not be deleted"
7595        );
7596        assert!(
7597            root.path().join(ACTIVE_RESTORE_TRANSACTION_PATH).exists(),
7598            "global restore intent must remain until authority is proven"
7599        );
7600    }
7601
7602    #[cfg(unix)]
7603    #[test]
7604    fn cleanup_receipt_identity_rejects_coordinated_same_byte_stage_and_destination_replacement() {
7605        use std::os::unix::fs::MetadataExt;
7606
7607        let root = folderbase();
7608        let store = FolderbaseVersionStore::open(root.path()).expect("open");
7609        store
7610            .seal_capture(store.plan_capture().expect("genesis"))
7611            .expect("genesis");
7612        fs::remove_file(root.path().join("active.bin")).expect("delete");
7613        store
7614            .seal_capture(store.plan_capture().expect("deletion"))
7615            .expect("deletion");
7616        let mut foreign_identity = None;
7617
7618        let result = store.restore_tombstone_with_hook("active.bin", |checkpoint| {
7619            if checkpoint == &RestoreCheckpoint::CleanupRecoveryDurable {
7620                let transaction = read_active_restore_transaction(
7621                    &FolderbaseState::open(root.path()).expect("state"),
7622                )
7623                .expect("restore journal")
7624                .expect("active restore");
7625                let stage = root.path().join(restore_stage_path(&transaction));
7626                let destination = root.path().join("active.bin");
7627                let foreign = root.path().join("same-byte-foreign.bin");
7628                fs::write(&foreign, b"first opaque bytes").expect("same-byte foreign file");
7629                let metadata = fs::metadata(&foreign).expect("foreign metadata");
7630                foreign_identity = Some((metadata.dev(), metadata.ino()));
7631                fs::remove_file(&stage).expect("replace exact stage");
7632                fs::remove_file(&destination).expect("replace exact destination");
7633                fs::hard_link(&foreign, &stage).expect("foreign stage link");
7634                fs::rename(&foreign, &destination).expect("foreign destination link");
7635            }
7636        });
7637
7638        result.expect_err("receipt identity must reject coordinated foreign hard links");
7639        let transaction =
7640            read_active_restore_transaction(&FolderbaseState::open(root.path()).expect("state"))
7641                .expect("restore journal")
7642                .expect("retained active restore");
7643        for path in [
7644            root.path().join(restore_stage_path(&transaction)),
7645            root.path().join("active.bin"),
7646        ] {
7647            let metadata = fs::metadata(path).expect("foreign replacement preserved");
7648            assert_eq!(
7649                (metadata.dev(), metadata.ino()),
7650                foreign_identity.expect("foreign identity")
7651            );
7652        }
7653        assert!(root.path().join(RESTORE_CLEANUP_RECOVERY_PATH).exists());
7654    }
7655
7656    #[cfg(unix)]
7657    #[derive(Clone, Copy)]
7658    enum CleanupBoundarySwap {
7659        Destination,
7660        Stage,
7661        Rescue,
7662    }
7663
7664    #[cfg(unix)]
7665    fn assert_cleanup_boundary_swap_fails_closed(
7666        modified: bool,
7667        swap: CleanupBoundarySwap,
7668        after_stage_retirement: bool,
7669    ) {
7670        let root = folderbase();
7671        let store = FolderbaseVersionStore::open(root.path()).expect("open");
7672        store
7673            .seal_capture(store.plan_capture().expect("genesis"))
7674            .expect("genesis");
7675        fs::remove_file(root.path().join("active.bin")).expect("delete");
7676        store
7677            .seal_capture(store.plan_capture().expect("deletion"))
7678            .expect("deletion");
7679        let owned_bytes: &[u8] = if modified {
7680            b"user-edited restore at cleanup boundary"
7681        } else {
7682            b"first opaque bytes"
7683        };
7684        let competitor = b"unrelated replacement must survive";
7685        let mut transaction_directory = None;
7686
7687        let result = store.restore_tombstone_with_hook("active.bin", |checkpoint| {
7688            if modified && checkpoint == &RestoreCheckpoint::TargetPublished {
7689                fs::write(root.path().join("active.bin"), owned_bytes)
7690                    .expect("edit restored target in place");
7691            }
7692            let mutation_checkpoint = if after_stage_retirement {
7693                &RestoreCheckpoint::AfterStageRetirement
7694            } else {
7695                &RestoreCheckpoint::BeforeStageRetirement
7696            };
7697            if checkpoint == mutation_checkpoint {
7698                let transaction = read_active_restore_transaction(
7699                    &FolderbaseState::open(root.path()).expect("state"),
7700                )
7701                .expect("restore journal")
7702                .expect("active restore");
7703                let directory = root
7704                    .path()
7705                    .join(restore_transaction_directory(&transaction));
7706                transaction_directory = Some(directory.clone());
7707                let target = match swap {
7708                    CleanupBoundarySwap::Destination => root.path().join("active.bin"),
7709                    CleanupBoundarySwap::Stage => directory.join("content"),
7710                    CleanupBoundarySwap::Rescue => directory.join("content.rescue"),
7711                };
7712                if !matches!(swap, CleanupBoundarySwap::Rescue) {
7713                    fs::remove_file(&target).expect("remove exact cleanup-owned name");
7714                }
7715                fs::write(&target, competitor).expect("install unrelated boundary replacement");
7716            }
7717        });
7718        if matches!(swap, CleanupBoundarySwap::Rescue) {
7719            if modified {
7720                result.expect_err("the prior same-inode edit still prevents Restored");
7721            } else {
7722                result.expect("unused legacy rescue names cannot block a restore");
7723            }
7724        } else {
7725            result.expect_err("an authority-boundary replacement must fail closed");
7726        }
7727
7728        let transaction_directory = transaction_directory.expect("transaction directory");
7729        let replacement_survived = match swap {
7730            CleanupBoundarySwap::Destination => {
7731                fs::read(root.path().join("active.bin")).expect("unrelated replacement")
7732                    == competitor
7733            }
7734            CleanupBoundarySwap::Stage | CleanupBoundarySwap::Rescue => {
7735                fs::read_dir(&transaction_directory)
7736                    .expect("retained transaction directory")
7737                    .filter_map(|entry| entry.ok())
7738                    .filter_map(|entry| fs::read(entry.path()).ok())
7739                    .any(|bytes| bytes == competitor)
7740            }
7741        };
7742        assert!(
7743            replacement_survived,
7744            "cleanup must preserve the boundary replacement under a private quarantine name"
7745        );
7746        let uncertain_authority = !matches!(swap, CleanupBoundarySwap::Rescue);
7747        assert_eq!(
7748            root.path().join(ACTIVE_RESTORE_TRANSACTION_PATH).exists(),
7749            uncertain_authority,
7750            "only an authority-path or destination replacement retains global restore intent"
7751        );
7752        assert_eq!(
7753            root.path().join(RESTORE_CLEANUP_RECOVERY_PATH).exists(),
7754            uncertain_authority,
7755            "only an authority-path or destination replacement retains recovery evidence"
7756        );
7757        let retained_owned_bytes_in_private_state = fs::read_dir(&transaction_directory)
7758            .expect("retained transaction directory")
7759            .filter_map(|entry| entry.ok())
7760            .filter_map(|entry| fs::read(entry.path()).ok())
7761            .any(|bytes| bytes == owned_bytes);
7762        let retained_owned_bytes = retained_owned_bytes_in_private_state
7763            || fs::read(root.path().join("active.bin")).is_ok_and(|bytes| bytes == owned_bytes);
7764        assert!(
7765            retained_owned_bytes,
7766            "the workspace or retained authority must preserve the exact owned inode bytes"
7767        );
7768    }
7769
7770    #[cfg(unix)]
7771    #[test]
7772    fn modified_cleanup_retains_owned_bytes_when_destination_swaps_at_unlink_boundary() {
7773        assert_cleanup_boundary_swap_fails_closed(true, CleanupBoundarySwap::Destination, false);
7774    }
7775
7776    #[cfg(unix)]
7777    #[test]
7778    fn modified_cleanup_never_unlinks_a_stage_name_replacement() {
7779        assert_cleanup_boundary_swap_fails_closed(true, CleanupBoundarySwap::Stage, false);
7780    }
7781
7782    #[cfg(unix)]
7783    #[test]
7784    fn committed_cleanup_retains_owned_bytes_when_destination_swaps_at_unlink_boundary() {
7785        assert_cleanup_boundary_swap_fails_closed(false, CleanupBoundarySwap::Destination, false);
7786    }
7787
7788    #[cfg(unix)]
7789    #[test]
7790    fn committed_cleanup_never_unlinks_a_stage_name_replacement() {
7791        assert_cleanup_boundary_swap_fails_closed(false, CleanupBoundarySwap::Stage, false);
7792    }
7793
7794    #[cfg(unix)]
7795    #[test]
7796    fn modified_cleanup_rescue_survives_destination_swap_after_stage_unlink() {
7797        assert_cleanup_boundary_swap_fails_closed(true, CleanupBoundarySwap::Destination, true);
7798    }
7799
7800    #[cfg(unix)]
7801    #[test]
7802    fn committed_cleanup_rescue_survives_destination_swap_after_stage_unlink() {
7803        assert_cleanup_boundary_swap_fails_closed(false, CleanupBoundarySwap::Destination, true);
7804    }
7805
7806    #[cfg(unix)]
7807    #[test]
7808    fn modified_cleanup_never_unlinks_a_rescue_name_replacement() {
7809        assert_cleanup_boundary_swap_fails_closed(true, CleanupBoundarySwap::Rescue, true);
7810    }
7811
7812    #[cfg(unix)]
7813    #[test]
7814    fn committed_cleanup_never_unlinks_a_rescue_name_replacement() {
7815        assert_cleanup_boundary_swap_fails_closed(false, CleanupBoundarySwap::Rescue, true);
7816    }
7817
7818    #[test]
7819    fn successful_restore_retains_one_private_authority_link() {
7820        let root = folderbase();
7821        let store = FolderbaseVersionStore::open(root.path()).expect("open");
7822        store
7823            .seal_capture(store.plan_capture().expect("genesis"))
7824            .expect("genesis");
7825        fs::remove_file(root.path().join("active.bin")).expect("delete");
7826        store
7827            .seal_capture(store.plan_capture().expect("deletion"))
7828            .expect("deletion");
7829
7830        let restored = store
7831            .restore_tombstone("active.bin")
7832            .expect("successful restore");
7833
7834        let transaction_entries = fs::read_dir(root.path().join(RESTORE_TRANSACTIONS_DIRECTORY))
7835            .expect("restore transaction directory")
7836            .collect::<std::io::Result<Vec<_>>>()
7837            .expect("transaction entries");
7838        assert_eq!(transaction_entries.len(), 1);
7839        let completion =
7840            read_restore_completion_receipt(&FolderbaseState::open(root.path()).expect("state"))
7841                .expect("completion receipt")
7842                .expect("completed restore");
7843        assert_eq!(
7844            completion.transaction.target_version_id,
7845            restored.version_id()
7846        );
7847        let retained_stage = root
7848            .path()
7849            .join(restore_stage_path(&completion.transaction));
7850        assert!(retained_stage.is_file());
7851        assert!(
7852            root.path()
7853                .join(restore_authority_record_path(
7854                    &completion.transaction.transaction_id
7855                ))
7856                .is_file()
7857        );
7858        #[cfg(unix)]
7859        {
7860            use std::os::unix::fs::MetadataExt;
7861            assert_eq!(
7862                fs::metadata(&retained_stage)
7863                    .expect("retained authority metadata")
7864                    .nlink(),
7865                2
7866            );
7867        }
7868        let plan = store.plan_capture().expect("authority-aware capture plan");
7869        assert!(
7870            plan.entries()
7871                .iter()
7872                .any(|entry| entry.path() == "active.bin")
7873        );
7874        assert!(
7875            !plan
7876                .exclusions()
7877                .iter()
7878                .any(|entry| entry.path() == "active.bin")
7879        );
7880    }
7881
7882    #[cfg(unix)]
7883    #[test]
7884    fn restore_authority_allows_same_inode_edits_but_not_extra_user_hard_links() {
7885        let root = folderbase();
7886        let store = FolderbaseVersionStore::open(root.path()).expect("open");
7887        store
7888            .seal_capture(store.plan_capture().expect("genesis"))
7889            .expect("genesis");
7890        fs::remove_file(root.path().join("active.bin")).expect("delete");
7891        store
7892            .seal_capture(store.plan_capture().expect("deletion"))
7893            .expect("deletion");
7894        store
7895            .restore_tombstone("active.bin")
7896            .expect("successful restore");
7897        fs::write(root.path().join("active.bin"), b"same-inode user edit").expect("edit");
7898
7899        let edited_plan = store.plan_capture().expect("edited authority plan");
7900        assert!(
7901            edited_plan
7902                .entries()
7903                .iter()
7904                .any(|entry| entry.path() == "active.bin")
7905        );
7906        store
7907            .seal_capture(edited_plan)
7908            .expect("same-inode edit with one authority link is capturable");
7909
7910        fs::hard_link(
7911            root.path().join("active.bin"),
7912            root.path().join("ordinary-user-link.bin"),
7913        )
7914        .expect("ordinary user hard link");
7915        let linked_plan = store.plan_capture().expect("hard-link exclusion plan");
7916        for path in ["active.bin", "ordinary-user-link.bin"] {
7917            assert!(linked_plan.exclusions().iter().any(|exclusion| {
7918                exclusion.path() == path && exclusion.kind() == CaptureExclusionKind::HardLink
7919            }));
7920        }
7921    }
7922
7923    #[cfg(unix)]
7924    #[test]
7925    fn old_restore_authority_never_authorizes_a_replaced_workspace_inode() {
7926        let root = folderbase();
7927        let store = FolderbaseVersionStore::open(root.path()).expect("open");
7928        store
7929            .seal_capture(store.plan_capture().expect("genesis"))
7930            .expect("genesis");
7931        fs::remove_file(root.path().join("active.bin")).expect("delete");
7932        store
7933            .seal_capture(store.plan_capture().expect("deletion"))
7934            .expect("deletion");
7935        store
7936            .restore_tombstone("active.bin")
7937            .expect("successful restore");
7938
7939        fs::remove_file(root.path().join("active.bin")).expect("replace restored inode");
7940        fs::write(root.path().join("active.bin"), b"foreign replacement").expect("replacement");
7941        fs::hard_link(
7942            root.path().join("active.bin"),
7943            root.path().join("foreign-user-link.bin"),
7944        )
7945        .expect("foreign hard link");
7946
7947        let plan = store.plan_capture().expect("replacement plan");
7948        for path in ["active.bin", "foreign-user-link.bin"] {
7949            assert!(plan.exclusions().iter().any(|exclusion| {
7950                exclusion.path() == path && exclusion.kind() == CaptureExclusionKind::HardLink
7951            }));
7952        }
7953    }
7954
7955    #[test]
7956    fn restore_authority_limit_fails_closed_with_typed_maintenance_error() {
7957        let root = folderbase();
7958        let store = FolderbaseVersionStore::open(root.path()).expect("open");
7959        store
7960            .seal_capture(store.plan_capture().expect("genesis"))
7961            .expect("genesis");
7962        fs::remove_file(root.path().join("active.bin")).expect("first delete");
7963        store
7964            .seal_capture(store.plan_capture().expect("first deletion"))
7965            .expect("first deletion");
7966        store
7967            .restore_tombstone("active.bin")
7968            .expect("first restore authority");
7969        fs::remove_file(root.path().join("active.bin")).expect("second delete");
7970        store
7971            .seal_capture(store.plan_capture().expect("second deletion"))
7972            .expect("second deletion");
7973
7974        assert!(matches!(
7975            store.restore_tombstone_with_hook_and_authority_limit("active.bin", |_| {}, 1),
7976            Err(FolderbaseCaptureError::RestoreAuthorityMaintenanceRequired { maximum: 1 })
7977        ));
7978        assert!(!root.path().join("active.bin").exists());
7979    }
7980
7981    #[test]
7982    fn retained_authority_never_overwrites_legacy_quarantine_names() {
7983        let root = folderbase();
7984        let store = FolderbaseVersionStore::open(root.path()).expect("open");
7985        store
7986            .seal_capture(store.plan_capture().expect("genesis"))
7987            .expect("genesis");
7988        fs::remove_file(root.path().join("active.bin")).expect("delete");
7989        store
7990            .seal_capture(store.plan_capture().expect("deletion"))
7991            .expect("deletion");
7992        let foreign = b"foreign quarantine target";
7993        let mut preserved = Vec::new();
7994
7995        store
7996            .restore_tombstone_with_hook("active.bin", |checkpoint| {
7997                if checkpoint == &RestoreCheckpoint::CleanupRecoveryDurable {
7998                    let transaction = read_active_restore_transaction(
7999                        &FolderbaseState::open(root.path()).expect("state"),
8000                    )
8001                    .expect("restore journal")
8002                    .expect("active restore");
8003                    let stage = root.path().join(restore_stage_path(&transaction));
8004                    for name in ["content.rescue", "content.folderbase-quarantine"] {
8005                        let path = stage.with_file_name(name);
8006                        fs::write(&path, foreign).expect("foreign legacy target");
8007                        preserved.push(path);
8008                    }
8009                }
8010            })
8011            .expect("legacy names do not participate in retained authority");
8012
8013        for path in preserved {
8014            assert_eq!(fs::read(path).expect("preserved legacy target"), foreign);
8015        }
8016    }
8017
8018    #[test]
8019    fn completion_receipt_is_a_bounded_singleton_and_never_blocks_capture() {
8020        let root = folderbase();
8021        let store = FolderbaseVersionStore::open(root.path()).expect("open");
8022        store
8023            .seal_capture(store.plan_capture().expect("genesis"))
8024            .expect("genesis");
8025        fs::remove_file(root.path().join("active.bin")).expect("first delete");
8026        store
8027            .seal_capture(store.plan_capture().expect("first deletion"))
8028            .expect("first deletion");
8029        let first = store
8030            .restore_tombstone("active.bin")
8031            .expect("first restore");
8032        let state = FolderbaseState::open(root.path()).expect("state");
8033        let first_receipt = read_restore_completion_receipt(&state)
8034            .expect("first completion receipt")
8035            .expect("durable first completion");
8036        assert_eq!(
8037            first_receipt.transaction.target_version_id,
8038            first.version_id()
8039        );
8040        assert!(
8041            fs::metadata(root.path().join(RESTORE_COMPLETION_PATH))
8042                .expect("completion metadata")
8043                .len()
8044                <= MAX_CAPTURE_TRANSACTION_BYTES
8045        );
8046
8047        let unchanged = store
8048            .seal_capture(store.plan_capture().expect("unchanged capture"))
8049            .expect("completion receipt must not block capture");
8050        assert!(!unchanged.created());
8051        fs::remove_file(root.path().join("active.bin")).expect("second delete");
8052        store
8053            .seal_capture(store.plan_capture().expect("second deletion"))
8054            .expect("stale completion must not block a later deletion");
8055        let second = store
8056            .restore_tombstone("active.bin")
8057            .expect("second restore");
8058        let second_receipt = read_restore_completion_receipt(&state)
8059            .expect("second completion receipt")
8060            .expect("durable second completion");
8061        assert_eq!(
8062            second_receipt.transaction.target_version_id,
8063            second.version_id()
8064        );
8065        assert_ne!(
8066            second_receipt.transaction.target_version_id,
8067            first_receipt.transaction.target_version_id,
8068            "later completion must replace, not append to, the singleton"
8069        );
8070    }
8071
8072    #[test]
8073    fn completion_receipt_never_blesses_changed_workspace_bytes() {
8074        let root = folderbase();
8075        let store = FolderbaseVersionStore::open(root.path()).expect("open");
8076        store
8077            .seal_capture(store.plan_capture().expect("genesis"))
8078            .expect("genesis");
8079        fs::remove_file(root.path().join("active.bin")).expect("delete");
8080        store
8081            .seal_capture(store.plan_capture().expect("deletion"))
8082            .expect("deletion");
8083        store
8084            .restore_tombstone("active.bin")
8085            .expect("completed restore");
8086        fs::write(root.path().join("active.bin"), b"later workspace edit")
8087            .expect("edit completed target");
8088
8089        assert!(matches!(
8090            store.restore_tombstone("active.bin"),
8091            Err(FolderbaseCaptureError::RestoreTargetOccupied(path))
8092                if path == Path::new("active.bin")
8093        ));
8094        store
8095            .seal_capture(store.plan_capture().expect("edited capture"))
8096            .expect("advisory completion evidence must not block later work");
8097    }
8098
8099    #[cfg(unix)]
8100    #[test]
8101    fn completion_receipt_never_blesses_identical_bytes_from_a_foreign_inode() {
8102        use std::os::unix::fs::MetadataExt;
8103
8104        let root = folderbase();
8105        let store = FolderbaseVersionStore::open(root.path()).expect("open");
8106        store
8107            .seal_capture(store.plan_capture().expect("genesis"))
8108            .expect("genesis");
8109        fs::remove_file(root.path().join("active.bin")).expect("delete");
8110        store
8111            .seal_capture(store.plan_capture().expect("deletion"))
8112            .expect("deletion");
8113        store
8114            .restore_tombstone("active.bin")
8115            .expect("completed restore");
8116
8117        let restored_metadata =
8118            fs::metadata(root.path().join("active.bin")).expect("restored metadata");
8119        fs::write(root.path().join("foreign.bin"), b"first opaque bytes")
8120            .expect("write identical foreign file");
8121        let foreign_metadata =
8122            fs::metadata(root.path().join("foreign.bin")).expect("foreign metadata");
8123        assert_ne!(
8124            (restored_metadata.dev(), restored_metadata.ino()),
8125            (foreign_metadata.dev(), foreign_metadata.ino()),
8126            "fixture must use a distinct filesystem object"
8127        );
8128        fs::remove_file(root.path().join("active.bin")).expect("remove restored inode");
8129        fs::rename(
8130            root.path().join("foreign.bin"),
8131            root.path().join("active.bin"),
8132        )
8133        .expect("publish identical-byte foreign inode");
8134
8135        assert!(matches!(
8136            store.restore_tombstone("active.bin"),
8137            Err(FolderbaseCaptureError::RestoreTargetOccupied(path))
8138                if path == Path::new("active.bin")
8139        ));
8140    }
8141
8142    #[test]
8143    fn completion_receipt_requires_its_retained_authority_link() {
8144        let root = folderbase();
8145        let store = FolderbaseVersionStore::open(root.path()).expect("open");
8146        store
8147            .seal_capture(store.plan_capture().expect("genesis"))
8148            .expect("genesis");
8149        fs::remove_file(root.path().join("active.bin")).expect("delete");
8150        store
8151            .seal_capture(store.plan_capture().expect("deletion"))
8152            .expect("deletion");
8153        store
8154            .restore_tombstone("active.bin")
8155            .expect("completed restore");
8156        let completion =
8157            read_restore_completion_receipt(&FolderbaseState::open(root.path()).expect("state"))
8158                .expect("completion receipt")
8159                .expect("completed restore");
8160        fs::remove_file(
8161            root.path()
8162                .join(restore_stage_path(&completion.transaction)),
8163        )
8164        .expect("remove retained authority link");
8165
8166        assert!(matches!(
8167            store.restore_tombstone("active.bin"),
8168            Err(FolderbaseCaptureError::RestoreTargetOccupied(path))
8169                if path == Path::new("active.bin")
8170        ));
8171        assert_eq!(
8172            fs::read(root.path().join("active.bin")).expect("workspace file preserved"),
8173            b"first opaque bytes"
8174        );
8175    }
8176
8177    #[test]
8178    fn late_same_inode_edit_after_projection_retires_without_false_restore_success() {
8179        let root = folderbase();
8180        let store = FolderbaseVersionStore::open(root.path()).expect("open");
8181        store
8182            .seal_capture(store.plan_capture().expect("genesis"))
8183            .expect("genesis");
8184        fs::remove_file(root.path().join("active.bin")).expect("delete");
8185        store
8186            .seal_capture(store.plan_capture().expect("deletion"))
8187            .expect("deletion");
8188        let edited = b"user edit after projection became durable";
8189
8190        store
8191            .restore_tombstone_with_hook("active.bin", |checkpoint| {
8192                if checkpoint == &RestoreCheckpoint::ProjectionDurable {
8193                    fs::write(root.path().join("active.bin"), edited)
8194                        .expect("late same-inode edit");
8195                }
8196            })
8197            .expect_err("late edit must prevent restored-success acknowledgement");
8198        drop(store);
8199
8200        let reopened = FolderbaseVersionStore::open(root.path()).expect("fresh-process reopen");
8201        assert!(matches!(
8202            reopened.restore_tombstone("active.bin"),
8203            Err(FolderbaseCaptureError::RestoreTargetOccupied(path))
8204                if path == Path::new("active.bin")
8205        ));
8206        assert_eq!(
8207            fs::read(root.path().join("active.bin")).expect("preserved edit"),
8208            edited
8209        );
8210        let captured = reopened
8211            .seal_capture(reopened.plan_capture().expect("edited capture"))
8212            .expect("late edit cleanup must not wedge capture");
8213        assert!(captured.created());
8214    }
8215
8216    #[test]
8217    fn partial_restore_authority_record_fails_closed_before_capture() {
8218        let root = folderbase();
8219        let store = FolderbaseVersionStore::open(root.path()).expect("open");
8220        store
8221            .seal_capture(store.plan_capture().expect("genesis"))
8222            .expect("genesis");
8223        fs::remove_file(root.path().join("active.bin")).expect("delete");
8224        store
8225            .seal_capture(store.plan_capture().expect("deletion"))
8226            .expect("deletion");
8227        let restored = store
8228            .restore_tombstone("active.bin")
8229            .expect("restore with retained authority");
8230        let state = FolderbaseState::open(root.path()).expect("state");
8231        let completion = read_restore_completion_receipt(&state)
8232            .expect("completion")
8233            .expect("completed restore");
8234        fs::write(
8235            root.path().join(restore_authority_record_path(
8236                &completion.transaction.transaction_id,
8237            )),
8238            b"{",
8239        )
8240        .expect("simulate a torn authority receipt");
8241
8242        let error = store
8243            .plan_capture()
8244            .expect_err("partial engine metadata must fail closed");
8245        assert!(matches!(
8246            error,
8247            FolderbaseCaptureError::InvalidRestoreTransaction(message)
8248                if message.contains("invalid JSON")
8249        ));
8250        assert_eq!(
8251            local_head(root.path()).expect("unchanged Head").version_id,
8252            restored.version_id()
8253        );
8254    }
8255
8256    fn assert_cleanup_hook_edit_never_returns_restored(checkpoint_to_edit: RestoreCheckpoint) {
8257        let root = folderbase();
8258        let store = FolderbaseVersionStore::open(root.path()).expect("open");
8259        store
8260            .seal_capture(store.plan_capture().expect("genesis"))
8261            .expect("genesis");
8262        fs::remove_file(root.path().join("active.bin")).expect("delete");
8263        store
8264            .seal_capture(store.plan_capture().expect("deletion"))
8265            .expect("deletion");
8266        let edited = b"user edit during restore cleanup";
8267
8268        store
8269            .restore_tombstone_with_hook("active.bin", |checkpoint| {
8270                if checkpoint == &checkpoint_to_edit {
8271                    fs::write(root.path().join("active.bin"), edited)
8272                        .expect("same-inode cleanup edit");
8273                }
8274            })
8275            .expect_err("cleanup edit must prevent restored-success acknowledgement");
8276        assert_eq!(
8277            fs::read(root.path().join("active.bin")).expect("preserved cleanup edit"),
8278            edited
8279        );
8280        drop(store);
8281
8282        let reopened = FolderbaseVersionStore::open(root.path()).expect("fresh-process reopen");
8283        assert!(matches!(
8284            reopened.restore_tombstone("active.bin"),
8285            Err(FolderbaseCaptureError::RestoreTargetOccupied(path))
8286                if path == Path::new("active.bin")
8287        ));
8288        reopened
8289            .seal_capture(reopened.plan_capture().expect("edited capture"))
8290            .expect("cleanup edit must remain capturable");
8291    }
8292
8293    fn assert_cleanup_hook_substitution_never_returns_restored(
8294        checkpoint_to_replace: RestoreCheckpoint,
8295    ) {
8296        let root = folderbase();
8297        let store = FolderbaseVersionStore::open(root.path()).expect("open");
8298        store
8299            .seal_capture(store.plan_capture().expect("genesis"))
8300            .expect("genesis");
8301        fs::remove_file(root.path().join("active.bin")).expect("delete");
8302        store
8303            .seal_capture(store.plan_capture().expect("deletion"))
8304            .expect("deletion");
8305        let replacement = b"foreign replacement during restore cleanup";
8306
8307        store
8308            .restore_tombstone_with_hook("active.bin", |checkpoint| {
8309                if checkpoint == &checkpoint_to_replace {
8310                    fs::remove_file(root.path().join("active.bin"))
8311                        .expect("remove published inode");
8312                    fs::write(root.path().join("active.bin"), replacement)
8313                        .expect("install foreign inode");
8314                }
8315            })
8316            .expect_err("cleanup substitution must prevent restored-success acknowledgement");
8317        assert_eq!(
8318            fs::read(root.path().join("active.bin")).expect("preserved replacement"),
8319            replacement
8320        );
8321    }
8322
8323    #[test]
8324    fn same_inode_edit_before_stage_retirement_never_returns_restored() {
8325        assert_cleanup_hook_edit_never_returns_restored(RestoreCheckpoint::BeforeStageRetirement);
8326    }
8327
8328    #[test]
8329    fn same_inode_edit_after_stage_retirement_never_returns_restored() {
8330        assert_cleanup_hook_edit_never_returns_restored(RestoreCheckpoint::AfterStageRetirement);
8331    }
8332
8333    #[test]
8334    fn same_inode_edit_after_cleanup_intent_retirement_never_returns_restored() {
8335        assert_cleanup_hook_edit_never_returns_restored(RestoreCheckpoint::CleanupIntentRetired);
8336    }
8337
8338    #[test]
8339    fn same_inode_edit_after_completion_durability_never_returns_restored() {
8340        assert_cleanup_hook_edit_never_returns_restored(RestoreCheckpoint::CompletionDurable);
8341    }
8342
8343    #[test]
8344    fn same_inode_edit_at_cleanup_completion_never_returns_restored() {
8345        assert_cleanup_hook_edit_never_returns_restored(RestoreCheckpoint::CleanupComplete);
8346    }
8347
8348    #[test]
8349    fn inode_substitution_after_cleanup_intent_retirement_never_returns_restored() {
8350        assert_cleanup_hook_substitution_never_returns_restored(
8351            RestoreCheckpoint::CleanupIntentRetired,
8352        );
8353    }
8354
8355    #[test]
8356    fn inode_substitution_after_completion_durability_never_returns_restored() {
8357        assert_cleanup_hook_substitution_never_returns_restored(
8358            RestoreCheckpoint::CompletionDurable,
8359        );
8360    }
8361
8362    #[test]
8363    fn inode_substitution_at_cleanup_completion_never_returns_restored() {
8364        assert_cleanup_hook_substitution_never_returns_restored(RestoreCheckpoint::CleanupComplete);
8365    }
8366
8367    #[cfg(unix)]
8368    #[test]
8369    fn cleanup_failure_reopens_from_durable_recovery_and_converges() {
8370        use std::{cell::RefCell, os::unix::fs::PermissionsExt};
8371
8372        let root = folderbase();
8373        let store = FolderbaseVersionStore::open(root.path()).expect("open");
8374        store
8375            .seal_capture(store.plan_capture().expect("genesis"))
8376            .expect("genesis");
8377        fs::remove_file(root.path().join("active.bin")).expect("delete");
8378        store
8379            .seal_capture(store.plan_capture().expect("deletion"))
8380            .expect("deletion");
8381        let transaction_directory = RefCell::new(None);
8382
8383        let cleanup_error = store
8384            .restore_tombstone_with_hook("active.bin", |checkpoint| {
8385                if checkpoint == &RestoreCheckpoint::JournalDurable {
8386                    let transaction = read_active_restore_transaction(
8387                        &FolderbaseState::open(root.path()).expect("state"),
8388                    )
8389                    .expect("restore journal")
8390                    .expect("active restore");
8391                    transaction_directory.replace(Some(
8392                        root.path()
8393                            .join(restore_transaction_directory(&transaction)),
8394                    ));
8395                }
8396                if checkpoint == &RestoreCheckpoint::CleanupRecoveryDurable {
8397                    fs::set_permissions(
8398                        transaction_directory
8399                            .borrow()
8400                            .as_ref()
8401                            .expect("transaction directory"),
8402                        fs::Permissions::from_mode(0o500),
8403                    )
8404                    .expect("deny stage cleanup");
8405                }
8406            })
8407            .expect_err("stage cleanup failure must be reported");
8408        assert!(matches!(
8409            cleanup_error,
8410            FolderbaseCaptureError::LocalStore(FolderbaseError::Io { .. })
8411        ));
8412        let transaction_directory = transaction_directory
8413            .into_inner()
8414            .expect("transaction directory");
8415        fs::set_permissions(&transaction_directory, fs::Permissions::from_mode(0o700))
8416            .expect("restore cleanup permissions");
8417        drop(store);
8418
8419        let reopened = FolderbaseVersionStore::open(root.path()).expect("reopen");
8420        let restored = reopened
8421            .restore_tombstone("active.bin")
8422            .expect("durable cleanup retry");
8423        assert!(!restored.created());
8424        assert_eq!(
8425            fs::read(root.path().join("active.bin")).expect("restored workspace bytes"),
8426            b"first opaque bytes"
8427        );
8428        assert!(
8429            transaction_directory
8430                .join(RESTORE_AUTHORITY_FILENAME)
8431                .is_file(),
8432            "retry must retain the private authority and its durable receipt"
8433        );
8434    }
8435
8436    #[test]
8437    fn committed_cleanup_without_private_links_never_blesses_missing_or_foreign_publication() {
8438        for replacement in ["missing", "foreign"] {
8439            let root = folderbase();
8440            let store = FolderbaseVersionStore::open(root.path()).expect("open");
8441            store
8442                .seal_capture(store.plan_capture().expect("genesis"))
8443                .expect("genesis");
8444            fs::remove_file(root.path().join("active.bin")).expect("delete");
8445            store
8446                .seal_capture(store.plan_capture().expect("deletion"))
8447                .expect("deletion");
8448
8449            store
8450                .restore_tombstone_with_hook("active.bin", |checkpoint| {
8451                    if checkpoint == &RestoreCheckpoint::AfterStageRetirement {
8452                        let transaction = read_active_restore_transaction(
8453                            &FolderbaseState::open(root.path()).expect("state"),
8454                        )
8455                        .expect("restore journal")
8456                        .expect("active restore");
8457                        fs::remove_file(root.path().join(restore_stage_path(&transaction)))
8458                            .expect("simulate lost retained authority link");
8459                    }
8460                })
8461                .expect_err("missing retained authority must interrupt cleanup");
8462            if replacement == "missing" {
8463                fs::remove_file(root.path().join("active.bin")).expect("remove publication");
8464            } else {
8465                fs::remove_file(root.path().join("active.bin")).expect("remove publication");
8466                fs::write(
8467                    root.path().join("active.bin"),
8468                    b"foreign workspace replacement",
8469                )
8470                .expect("foreign replacement");
8471            }
8472            drop(store);
8473
8474            let reopened = FolderbaseVersionStore::open(root.path()).expect("fresh-process reopen");
8475            reopened
8476                .restore_tombstone("active.bin")
8477                .expect_err("unproven publication must never return Restored");
8478            assert!(
8479                root.path().join(ACTIVE_RESTORE_TRANSACTION_PATH).exists(),
8480                "{replacement}: unproven cleanup must retain active restore intent"
8481            );
8482            assert!(
8483                root.path().join(RESTORE_CLEANUP_RECOVERY_PATH).exists(),
8484                "{replacement}: unproven cleanup must retain recovery evidence"
8485            );
8486        }
8487    }
8488
8489    #[test]
8490    fn committed_cleanup_without_private_links_never_converges_as_restored() {
8491        let root = folderbase();
8492        let store = FolderbaseVersionStore::open(root.path()).expect("open");
8493        store
8494            .seal_capture(store.plan_capture().expect("genesis"))
8495            .expect("genesis");
8496        fs::remove_file(root.path().join("active.bin")).expect("delete");
8497        store
8498            .seal_capture(store.plan_capture().expect("deletion"))
8499            .expect("deletion");
8500
8501        store
8502            .restore_tombstone_with_hook("active.bin", |checkpoint| {
8503                if checkpoint == &RestoreCheckpoint::AfterStageRetirement {
8504                    let transaction = read_active_restore_transaction(
8505                        &FolderbaseState::open(root.path()).expect("state"),
8506                    )
8507                    .expect("restore journal")
8508                    .expect("active restore");
8509                    fs::remove_file(root.path().join(restore_stage_path(&transaction)))
8510                        .expect("simulate lost retained authority link");
8511                }
8512            })
8513            .expect_err("missing retained authority must interrupt cleanup");
8514        drop(store);
8515
8516        FolderbaseVersionStore::open(root.path())
8517            .expect("fresh-process reopen")
8518            .restore_tombstone("active.bin")
8519            .expect_err("publication without its retained authority cannot return Restored");
8520        assert_eq!(
8521            fs::read(root.path().join("active.bin")).expect("restored bytes"),
8522            b"first opaque bytes"
8523        );
8524        assert!(root.path().join(ACTIVE_RESTORE_TRANSACTION_PATH).exists());
8525        assert!(root.path().join(RESTORE_CLEANUP_RECOVERY_PATH).exists());
8526    }
8527
8528    #[cfg(unix)]
8529    #[test]
8530    fn cleanup_receipt_survives_active_retirement_and_blocks_capture() {
8531        use std::os::unix::fs::PermissionsExt;
8532
8533        let root = folderbase();
8534        let store = FolderbaseVersionStore::open(root.path()).expect("open");
8535        store
8536            .seal_capture(store.plan_capture().expect("genesis"))
8537            .expect("genesis");
8538        fs::remove_file(root.path().join("active.bin")).expect("delete");
8539        store
8540            .seal_capture(store.plan_capture().expect("deletion"))
8541            .expect("deletion");
8542        let restore_transactions = root.path().join(RESTORE_TRANSACTIONS_DIRECTORY);
8543
8544        let cleanup_error = store
8545            .restore_tombstone_with_hook("active.bin", |checkpoint| {
8546                if checkpoint == &RestoreCheckpoint::CleanupIntentRetired {
8547                    fs::set_permissions(&restore_transactions, fs::Permissions::from_mode(0o500))
8548                        .expect("deny cleanup receipt removal");
8549                }
8550            })
8551            .expect_err("receipt cleanup failure must be reported");
8552        assert!(matches!(
8553            cleanup_error,
8554            FolderbaseCaptureError::LocalStore(FolderbaseError::Io { .. })
8555        ));
8556        assert!(matches!(
8557            store.seal_capture(store.plan_capture().expect("capture plan")),
8558            Err(FolderbaseCaptureError::ConflictingTransaction(message))
8559                if message.contains("restore")
8560        ));
8561        fs::set_permissions(&restore_transactions, fs::Permissions::from_mode(0o700))
8562            .expect("restore transaction permissions");
8563        drop(store);
8564
8565        let restored = FolderbaseVersionStore::open(root.path())
8566            .expect("reopen")
8567            .restore_tombstone("active.bin")
8568            .expect("cleanup receipt retry");
8569        assert!(!restored.created());
8570        assert!(
8571            !root.path().join(ACTIVE_RESTORE_TRANSACTION_PATH).exists()
8572                && !root.path().join(RESTORE_CLEANUP_RECOVERY_PATH).exists(),
8573            "receipt retry must retire only global mutable intent"
8574        );
8575        assert!(
8576            fs::read_dir(&restore_transactions)
8577                .expect("restore transactions")
8578                .filter_map(|entry| entry.ok())
8579                .any(|entry| entry.path().join(RESTORE_AUTHORITY_FILENAME).is_file()),
8580            "receipt retry must retain one durable private authority"
8581        );
8582    }
8583
8584    #[test]
8585    fn projection_failure_after_head_restores_the_prior_head() {
8586        let root = folderbase();
8587        let store = FolderbaseVersionStore::open(root.path()).expect("open");
8588        store
8589            .seal_capture(store.plan_capture().expect("genesis"))
8590            .expect("genesis");
8591        fs::remove_file(root.path().join("active.bin")).expect("delete");
8592        let deletion = store
8593            .seal_capture(store.plan_capture().expect("deletion"))
8594            .expect("deletion");
8595
8596        let error = store
8597            .restore_tombstone_with_hook("active.bin", |checkpoint| {
8598                if checkpoint == &RestoreCheckpoint::PublicationVerified {
8599                    let transaction = read_active_restore_transaction(
8600                        &FolderbaseState::open(root.path()).expect("state"),
8601                    )
8602                    .expect("restore journal")
8603                    .expect("active restore");
8604                    let identity = root.path().join(capture_identity_relative_path(
8605                        transaction.binding.object_id(),
8606                    ));
8607                    fs::remove_file(&identity).expect("remove prior identity projection");
8608                    fs::create_dir(&identity).expect("block identity projection");
8609                }
8610            })
8611            .expect_err("projection failure after Head must fail the restore");
8612
8613        assert!(matches!(error, FolderbaseCaptureError::LocalStore(_)));
8614        assert_eq!(
8615            local_head(root.path())
8616                .expect("rolled back deletion Head")
8617                .version_id,
8618            deletion.version_id()
8619        );
8620    }
8621
8622    #[cfg(unix)]
8623    #[test]
8624    fn projection_never_reopens_a_replacement_ambient_root() {
8625        let root = folderbase();
8626        let store = FolderbaseVersionStore::open(root.path()).expect("open");
8627        store
8628            .seal_capture(store.plan_capture().expect("genesis"))
8629            .expect("genesis");
8630        fs::remove_file(root.path().join("active.bin")).expect("delete");
8631        let deletion = store
8632            .seal_capture(store.plan_capture().expect("deletion"))
8633            .expect("deletion");
8634        let detached = root.path().with_extension("projection-detached");
8635
8636        let result = store.restore_tombstone_with_hook("active.bin", |checkpoint| {
8637            if checkpoint == &RestoreCheckpoint::PublicationVerified {
8638                fs::rename(root.path(), &detached).expect("detach retained root");
8639                copy_directory(&detached, root.path());
8640            }
8641        });
8642
8643        assert!(
8644            result.is_err(),
8645            "replacement ambient root must revoke restore"
8646        );
8647        assert_eq!(
8648            local_head(&detached)
8649                .expect("retained root rolled back")
8650                .version_id,
8651            deletion.version_id()
8652        );
8653        fs::remove_dir_all(&detached).expect("remove detached fixture");
8654    }
8655
8656    #[test]
8657    fn restore_rechecks_a_nested_boundary_created_after_publication() {
8658        let root = folderbase();
8659        fs::create_dir(root.path().join("client")).expect("client");
8660        fs::rename(
8661            root.path().join("active.bin"),
8662            root.path().join("client/active.bin"),
8663        )
8664        .expect("nested active");
8665        let store = FolderbaseVersionStore::open(root.path()).expect("open");
8666        store
8667            .seal_capture(store.plan_capture().expect("genesis"))
8668            .expect("genesis");
8669        fs::remove_file(root.path().join("client/active.bin")).expect("delete");
8670        let deletion = store
8671            .seal_capture(store.plan_capture().expect("deletion"))
8672            .expect("deletion");
8673        let result = store.restore_tombstone_with_hook("client/active.bin", |checkpoint| {
8674            if checkpoint == &RestoreCheckpoint::TargetPublished {
8675                fs::create_dir(root.path().join("client/.FOLDERBASE")).expect("late nested state");
8676                fs::write(
8677                    root.path().join("client/.FOLDERBASE/MANIFEST.JSON"),
8678                    MANIFEST,
8679                )
8680                .expect("late nested manifest");
8681                fs::write(root.path().join("client/FOLDERBASE.md"), "# Child\n")
8682                    .expect("late nested entry");
8683            }
8684        });
8685        assert!(result.is_err());
8686        assert_eq!(
8687            local_head(root.path()).expect("deletion Head").version_id,
8688            deletion.version_id()
8689        );
8690
8691        let root = folderbase();
8692        fs::create_dir(root.path().join("client")).expect("client");
8693        fs::rename(
8694            root.path().join("active.bin"),
8695            root.path().join("client/active.bin"),
8696        )
8697        .expect("nested active");
8698        let store = FolderbaseVersionStore::open(root.path()).expect("open");
8699        store
8700            .seal_capture(store.plan_capture().expect("genesis"))
8701            .expect("genesis");
8702        fs::remove_file(root.path().join("client/active.bin")).expect("delete");
8703        let deletion = store
8704            .seal_capture(store.plan_capture().expect("deletion"))
8705            .expect("deletion");
8706        let interrupted = catch_unwind(AssertUnwindSafe(|| {
8707            store.restore_tombstone_with_hook("client/active.bin", |checkpoint| {
8708                if checkpoint == &RestoreCheckpoint::HeadReplaced {
8709                    panic!("crash after Head replacement");
8710                }
8711            })
8712        }));
8713        assert!(interrupted.is_err());
8714        fs::create_dir(root.path().join("client/.FOLDERBASE")).expect("late nested state");
8715        fs::write(
8716            root.path().join("client/.FOLDERBASE/MANIFEST.JSON"),
8717            MANIFEST,
8718        )
8719        .expect("late nested manifest");
8720        fs::write(root.path().join("client/FOLDERBASE.md"), "# Child\n")
8721            .expect("late nested entry");
8722        assert!(store.restore_tombstone("client/active.bin").is_err());
8723        assert_eq!(
8724            local_head(root.path())
8725                .expect("rolled back deletion Head")
8726                .version_id,
8727            deletion.version_id()
8728        );
8729    }
8730
8731    #[cfg(unix)]
8732    #[test]
8733    fn stale_store_refuses_a_replacement_physical_root_with_copied_state() {
8734        let root = folderbase();
8735        let store = FolderbaseVersionStore::open(root.path()).expect("open");
8736        store
8737            .seal_capture(store.plan_capture().expect("genesis"))
8738            .expect("genesis");
8739        fs::remove_file(root.path().join("active.bin")).expect("delete");
8740        let deletion = store
8741            .seal_capture(store.plan_capture().expect("deletion"))
8742            .expect("deletion");
8743        let detached = root.path().with_extension("detached");
8744        fs::rename(root.path(), &detached).expect("detach original root");
8745        copy_directory(&detached, root.path());
8746
8747        assert!(store.restore_tombstone("active.bin").is_err());
8748        assert!(!root.path().join("active.bin").exists());
8749        assert_eq!(
8750            local_head(root.path())
8751                .expect("copied deletion Head")
8752                .version_id,
8753            deletion.version_id()
8754        );
8755    }
8756
8757    #[cfg(unix)]
8758    #[test]
8759    fn post_head_root_swap_rolls_back_the_exact_detached_root() {
8760        let root = folderbase();
8761        let store = FolderbaseVersionStore::open(root.path()).expect("open");
8762        store
8763            .seal_capture(store.plan_capture().expect("genesis"))
8764            .expect("genesis");
8765        fs::remove_file(root.path().join("active.bin")).expect("delete");
8766        let deletion = store
8767            .seal_capture(store.plan_capture().expect("deletion"))
8768            .expect("deletion");
8769        let detached = root.path().with_extension("post-head-detached");
8770        let result = store.restore_tombstone_with_hook("active.bin", |checkpoint| {
8771            if checkpoint == &RestoreCheckpoint::HeadReplaced {
8772                fs::rename(root.path(), &detached).expect("detach committed root");
8773                copy_directory(&detached, root.path());
8774            }
8775        });
8776        assert!(result.is_err());
8777        assert_eq!(
8778            local_head(&detached)
8779                .expect("detached prior Head")
8780                .version_id,
8781            deletion.version_id()
8782        );
8783        fs::remove_dir_all(&detached).expect("remove detached fixture");
8784    }
8785
8786    #[cfg(unix)]
8787    #[test]
8788    fn restore_parent_symlink_swap_never_writes_outside_retained_root() {
8789        use std::os::unix::fs::symlink;
8790
8791        let root = folderbase();
8792        fs::create_dir(root.path().join("docs")).expect("docs");
8793        fs::rename(
8794            root.path().join("active.bin"),
8795            root.path().join("docs/active.bin"),
8796        )
8797        .expect("nested active");
8798        let store = FolderbaseVersionStore::open(root.path()).expect("open");
8799        store
8800            .seal_capture(store.plan_capture().expect("genesis"))
8801            .expect("genesis");
8802        fs::remove_file(root.path().join("docs/active.bin")).expect("delete");
8803        store
8804            .seal_capture(store.plan_capture().expect("deletion"))
8805            .expect("deletion");
8806        let outside = tempdir().expect("outside");
8807
8808        let error = store
8809            .restore_tombstone_with_hook("docs/active.bin", |checkpoint| {
8810                if checkpoint == &RestoreCheckpoint::StageDurable {
8811                    fs::rename(root.path().join("docs"), root.path().join("detached-docs"))
8812                        .expect("detach parent");
8813                    symlink(outside.path(), root.path().join("docs")).expect("redirect parent");
8814                }
8815            })
8816            .expect_err("parent symlink swap must fail closed");
8817        assert!(matches!(
8818            error,
8819            FolderbaseCaptureError::LocalStore(_)
8820                | FolderbaseCaptureError::RestoreTargetOccupied(_)
8821        ));
8822        assert!(!outside.path().join("active.bin").exists());
8823        assert!(!root.path().join("detached-docs/active.bin").exists());
8824    }
8825
8826    #[cfg(unix)]
8827    #[test]
8828    fn restore_parent_detach_after_capability_open_never_publishes_or_moves_head() {
8829        use std::os::unix::fs::symlink;
8830
8831        let root = folderbase();
8832        fs::create_dir(root.path().join("docs")).expect("docs");
8833        fs::rename(
8834            root.path().join("active.bin"),
8835            root.path().join("docs/active.bin"),
8836        )
8837        .expect("nested active");
8838        let store = FolderbaseVersionStore::open(root.path()).expect("open");
8839        store
8840            .seal_capture(store.plan_capture().expect("genesis"))
8841            .expect("genesis");
8842        fs::remove_file(root.path().join("docs/active.bin")).expect("delete");
8843        let deletion = store
8844            .seal_capture(store.plan_capture().expect("deletion"))
8845            .expect("deletion");
8846        let outside =
8847            tempfile::tempdir_in(root.path().parent().expect("fixture parent")).expect("outside");
8848        let detached = outside.path().join("detached-docs");
8849        let redirect = outside.path().join("redirect");
8850        fs::create_dir(&redirect).expect("redirect");
8851
8852        let error = store
8853            .restore_tombstone_with_hook("docs/active.bin", |checkpoint| {
8854                if checkpoint == &RestoreCheckpoint::WorkspaceParentOpened {
8855                    fs::rename(root.path().join("docs"), &detached)
8856                        .expect("detach opened workspace parent");
8857                    symlink(&redirect, root.path().join("docs"))
8858                        .expect("install redirecting workspace parent");
8859                }
8860            })
8861            .expect_err("detached parent capability must fail before publication");
8862        assert!(matches!(
8863            error,
8864            FolderbaseCaptureError::LocalStore(_)
8865                | FolderbaseCaptureError::RestoreTargetOccupied(_)
8866        ));
8867        assert!(!detached.join("active.bin").exists());
8868        assert!(!redirect.join("active.bin").exists());
8869        assert_eq!(
8870            local_head(root.path())
8871                .expect("deletion Head remains")
8872                .version_id,
8873            deletion.version_id()
8874        );
8875        let state = FolderbaseState::open(root.path()).expect("state");
8876        let transaction = read_active_restore_transaction(&state)
8877            .expect("active restore read")
8878            .expect("restore journal remains");
8879        assert!(root.path().join(restore_stage_path(&transaction)).exists());
8880    }
8881
8882    #[cfg(unix)]
8883    #[test]
8884    fn restore_parent_detach_after_link_leaves_only_owned_orphan_and_never_moves_head() {
8885        use std::os::unix::fs::MetadataExt;
8886
8887        let root = folderbase();
8888        fs::create_dir(root.path().join("docs")).expect("docs");
8889        fs::rename(
8890            root.path().join("active.bin"),
8891            root.path().join("docs/active.bin"),
8892        )
8893        .expect("nested active");
8894        let store = FolderbaseVersionStore::open(root.path()).expect("open");
8895        store
8896            .seal_capture(store.plan_capture().expect("genesis"))
8897            .expect("genesis");
8898        fs::remove_file(root.path().join("docs/active.bin")).expect("delete");
8899        let deletion = store
8900            .seal_capture(store.plan_capture().expect("deletion"))
8901            .expect("deletion");
8902        let outside =
8903            tempfile::tempdir_in(root.path().parent().expect("fixture parent")).expect("outside");
8904        let detached = outside.path().join("detached-docs");
8905
8906        let error = store
8907            .restore_tombstone_with_hook("docs/active.bin", |checkpoint| {
8908                if checkpoint == &RestoreCheckpoint::WorkspaceLinkCreated {
8909                    fs::rename(root.path().join("docs"), &detached)
8910                        .expect("detach linked workspace parent");
8911                    fs::create_dir(root.path().join("docs"))
8912                        .expect("install replacement workspace parent");
8913                    fs::write(root.path().join("docs/sentinel"), b"replacement\n")
8914                        .expect("replacement sentinel");
8915                }
8916            })
8917            .expect_err("detached linked parent must fail before durable restore progress");
8918        assert!(matches!(
8919            error,
8920            FolderbaseCaptureError::LocalStore(_)
8921                | FolderbaseCaptureError::RestoreTargetOccupied(_)
8922        ));
8923        assert_eq!(
8924            fs::read(detached.join("active.bin")).expect("operation-owned detached link"),
8925            b"first opaque bytes",
8926            "a concurrently moved directory may retain only the exact operation-owned link"
8927        );
8928        assert_eq!(
8929            fs::read(root.path().join("docs/sentinel")).expect("replacement sentinel"),
8930            b"replacement\n"
8931        );
8932        assert!(!root.path().join("docs/active.bin").exists());
8933        assert_eq!(
8934            local_head(root.path())
8935                .expect("deletion Head remains")
8936                .version_id,
8937            deletion.version_id()
8938        );
8939        let state = FolderbaseState::open(root.path()).expect("state");
8940        let transaction = read_active_restore_transaction(&state)
8941            .expect("active restore read")
8942            .expect("restore journal remains");
8943        let stage = root.path().join(restore_stage_path(&transaction));
8944        assert!(stage.exists());
8945        let links_before_retry = fs::metadata(&stage).expect("stage metadata").nlink();
8946        assert_eq!(
8947            links_before_retry, 2,
8948            "the stage and detached operation-owned publication are the only links"
8949        );
8950
8951        assert!(matches!(
8952            store.restore_tombstone("docs/active.bin"),
8953            Err(FolderbaseCaptureError::RestoreNamespaceRepairRequired(path))
8954                if path == Path::new("docs/active.bin")
8955        ));
8956        assert!(
8957            !root.path().join("docs/active.bin").exists(),
8958            "a refused retry must not add another publication link"
8959        );
8960        assert_eq!(
8961            fs::metadata(&stage)
8962                .expect("stage metadata after refused retry")
8963                .nlink(),
8964            links_before_retry,
8965            "a refused retry must not grow the hard-link set"
8966        );
8967        assert_eq!(
8968            local_head(root.path())
8969                .expect("deletion Head still remains")
8970                .version_id,
8971            deletion.version_id()
8972        );
8973
8974        fs::remove_dir_all(root.path().join("docs")).expect("remove replacement after inspection");
8975        fs::rename(&detached, root.path().join("docs"))
8976            .expect("explicitly return the operation-owned publication");
8977        let restored = store
8978            .restore_tombstone("docs/active.bin")
8979            .expect("retry converges after explicit namespace repair");
8980        assert_eq!(
8981            fs::read(root.path().join("docs/active.bin")).expect("restored bytes"),
8982            b"first opaque bytes"
8983        );
8984        assert_ne!(restored.version_id(), deletion.version_id());
8985    }
8986
8987    #[cfg(unix)]
8988    #[test]
8989    fn restore_parent_detach_during_cleanup_never_reports_success_and_can_resume_after_repair() {
8990        let root = folderbase();
8991        fs::create_dir(root.path().join("docs")).expect("docs");
8992        fs::rename(
8993            root.path().join("active.bin"),
8994            root.path().join("docs/active.bin"),
8995        )
8996        .expect("nested active");
8997        let store = FolderbaseVersionStore::open(root.path()).expect("open");
8998        store
8999            .seal_capture(store.plan_capture().expect("genesis"))
9000            .expect("genesis");
9001        fs::remove_file(root.path().join("docs/active.bin")).expect("delete");
9002        store
9003            .seal_capture(store.plan_capture().expect("deletion"))
9004            .expect("deletion");
9005        let outside =
9006            tempfile::tempdir_in(root.path().parent().expect("fixture parent")).expect("outside");
9007        let detached = outside.path().join("detached-docs");
9008
9009        let error = store
9010            .restore_tombstone_with_hook("docs/active.bin", |checkpoint| {
9011                if checkpoint == &RestoreCheckpoint::BeforeStageRetirement {
9012                    fs::rename(root.path().join("docs"), &detached)
9013                        .expect("detach cleanup workspace parent");
9014                    fs::create_dir(root.path().join("docs"))
9015                        .expect("install replacement workspace parent");
9016                    fs::write(root.path().join("docs/sentinel"), b"replacement\n")
9017                        .expect("replacement sentinel");
9018                }
9019            })
9020            .expect_err("cleanup must not acknowledge a detached publication");
9021        assert!(matches!(error, FolderbaseCaptureError::LocalStore(_)));
9022        assert_eq!(
9023            fs::read(detached.join("active.bin")).expect("detached operation-owned publication"),
9024            b"first opaque bytes"
9025        );
9026        assert_eq!(
9027            fs::read(root.path().join("docs/sentinel")).expect("replacement sentinel"),
9028            b"replacement\n"
9029        );
9030        assert!(!root.path().join("docs/active.bin").exists());
9031
9032        let state = FolderbaseState::open(root.path()).expect("state");
9033        let transaction = read_active_restore_transaction(&state)
9034            .expect("active restore read")
9035            .expect("restore journal remains");
9036        let cleanup = read_restore_cleanup_recovery(&state)
9037            .expect("cleanup recovery read")
9038            .expect("cleanup recovery remains");
9039        assert_eq!(cleanup.transaction, transaction);
9040        assert_eq!(
9041            local_head(root.path())
9042                .expect("forward Head remains recoverable")
9043                .version_id,
9044            transaction.target_version_id
9045        );
9046
9047        fs::remove_dir_all(root.path().join("docs")).expect("remove replacement after inspection");
9048        fs::rename(&detached, root.path().join("docs"))
9049            .expect("explicitly return the operation-owned publication");
9050        let restored = store
9051            .restore_tombstone("docs/active.bin")
9052            .expect("cleanup resumes after explicit namespace repair");
9053        assert_eq!(restored.version_id(), transaction.target_version_id);
9054        assert_eq!(
9055            fs::read(root.path().join("docs/active.bin")).expect("restored bytes"),
9056            b"first opaque bytes"
9057        );
9058    }
9059
9060    #[cfg(windows)]
9061    #[test]
9062    fn restore_parent_detach_is_detected_before_windows_publication() {
9063        let root = folderbase();
9064        fs::create_dir(root.path().join("docs")).expect("docs");
9065        fs::rename(
9066            root.path().join("active.bin"),
9067            root.path().join("docs/active.bin"),
9068        )
9069        .expect("nested active");
9070        let store = FolderbaseVersionStore::open(root.path()).expect("open");
9071        store
9072            .seal_capture(store.plan_capture().expect("genesis"))
9073            .expect("genesis");
9074        fs::remove_file(root.path().join("docs/active.bin")).expect("delete");
9075        let deletion = store
9076            .seal_capture(store.plan_capture().expect("deletion"))
9077            .expect("deletion");
9078        let outside =
9079            tempfile::tempdir_in(root.path().parent().expect("fixture parent")).expect("outside");
9080        let detached = outside.path().join("detached-docs");
9081
9082        let error = store
9083            .restore_tombstone_with_hook("docs/active.bin", |checkpoint| {
9084                if checkpoint == &RestoreCheckpoint::WorkspaceParentOpened {
9085                    fs::rename(root.path().join("docs"), &detached)
9086                        .expect("detach opened workspace parent");
9087                    fs::create_dir(root.path().join("docs"))
9088                        .expect("install replacement workspace parent");
9089                    fs::write(root.path().join("docs/sentinel"), b"replacement\n")
9090                        .expect("replacement sentinel");
9091                }
9092            })
9093            .expect_err("detached Windows parent must fail before publication");
9094        assert!(matches!(error, FolderbaseCaptureError::LocalStore(_)));
9095        assert!(!detached.join("active.bin").exists());
9096        assert!(!root.path().join("docs/active.bin").exists());
9097        assert_eq!(
9098            fs::read(root.path().join("docs/sentinel")).expect("replacement sentinel"),
9099            b"replacement\n"
9100        );
9101        assert_eq!(
9102            local_head(root.path())
9103                .expect("deletion Head remains")
9104                .version_id,
9105            deletion.version_id()
9106        );
9107
9108        fs::remove_dir_all(root.path().join("docs")).expect("remove replacement");
9109        fs::rename(&detached, root.path().join("docs")).expect("repair original parent");
9110        store
9111            .restore_tombstone("docs/active.bin")
9112            .expect("retry after explicit parent repair");
9113        assert_eq!(
9114            fs::read(root.path().join("docs/active.bin")).expect("restored bytes"),
9115            b"first opaque bytes"
9116        );
9117    }
9118
9119    #[test]
9120    fn restore_never_crosses_a_new_nested_folderbase_boundary() {
9121        let root = folderbase();
9122        fs::create_dir(root.path().join("client")).expect("client");
9123        fs::rename(
9124            root.path().join("active.bin"),
9125            root.path().join("client/active.bin"),
9126        )
9127        .expect("nested active");
9128        let store = FolderbaseVersionStore::open(root.path()).expect("open");
9129        store
9130            .seal_capture(store.plan_capture().expect("genesis"))
9131            .expect("genesis");
9132        fs::remove_file(root.path().join("client/active.bin")).expect("delete");
9133        let deletion = store
9134            .seal_capture(store.plan_capture().expect("deletion"))
9135            .expect("deletion");
9136        fs::create_dir(root.path().join("client/.folderbase")).expect("nested state");
9137        fs::write(
9138            root.path().join("client/.folderbase/manifest.json"),
9139            br#"{
9140  "protocol_version": "0.1.0",
9141  "folderbase": {
9142    "id": "folderbase_019f9b75-4f42-7f65-a012-2bfecdd8c474"
9143  }
9144}
9145"#,
9146        )
9147        .expect("nested manifest");
9148        fs::write(
9149            root.path().join("client/FOLDERBASE.md"),
9150            "# Nested Folderbase\n",
9151        )
9152        .expect("nested entry");
9153
9154        assert!(store.restore_tombstone("client/active.bin").is_err());
9155        assert!(!root.path().join("client/active.bin").exists());
9156        assert_eq!(
9157            local_head(root.path()).expect("deletion Head").version_id,
9158            deletion.version_id()
9159        );
9160    }
9161
9162    #[test]
9163    fn restore_never_crosses_a_case_folded_nested_folderbase_boundary() {
9164        let root = folderbase();
9165        fs::create_dir(root.path().join("client")).expect("client");
9166        fs::rename(
9167            root.path().join("active.bin"),
9168            root.path().join("client/active.bin"),
9169        )
9170        .expect("nested active");
9171        let store = FolderbaseVersionStore::open(root.path()).expect("open");
9172        store
9173            .seal_capture(store.plan_capture().expect("genesis"))
9174            .expect("genesis");
9175        fs::remove_file(root.path().join("client/active.bin")).expect("delete");
9176        let deletion = store
9177            .seal_capture(store.plan_capture().expect("deletion"))
9178            .expect("deletion");
9179        fs::create_dir(root.path().join("client/.FOLDERBASE")).expect("nested state alias");
9180        fs::write(
9181            root.path().join("client/.FOLDERBASE/MANIFEST.JSON"),
9182            br#"{
9183  "protocol_version": "0.1.0",
9184  "folderbase": {
9185    "id": "folderbase_019f9b75-4f42-7f65-a012-2bfecdd8c474"
9186  }
9187}
9188"#,
9189        )
9190        .expect("nested manifest alias");
9191
9192        assert!(store.restore_tombstone("client/active.bin").is_err());
9193        assert!(!root.path().join("client/active.bin").exists());
9194        assert_eq!(
9195            local_head(root.path()).expect("deletion Head").version_id,
9196            deletion.version_id()
9197        );
9198    }
9199
9200    #[test]
9201    fn every_persistence_checkpoint_reopens_and_converges_on_exact_assigned_version() {
9202        for fault in [
9203            CaptureCheckpoint::JournalDurable,
9204            CaptureCheckpoint::ObjectWritesDurable,
9205            CaptureCheckpoint::VersionDurable,
9206            CaptureCheckpoint::HeadReplaced,
9207            CaptureCheckpoint::CleanupComplete,
9208        ] {
9209            let root = folderbase();
9210            let store = FolderbaseVersionStore::open(root.path()).expect("open");
9211            let plan = store.plan_capture().expect("plan");
9212            let interrupted = catch_unwind(AssertUnwindSafe(|| {
9213                store.seal_capture_with_hook(plan, |checkpoint| {
9214                    if checkpoint == &fault {
9215                        panic!("simulated process termination at {fault:?}");
9216                    }
9217                })
9218            }));
9219            assert!(interrupted.is_err(), "fault {fault:?}");
9220
9221            let assigned = active_transaction(root.path())
9222                .map(|transaction| transaction.target_version_id)
9223                .or_else(|| local_head(root.path()).map(|head| head.version_id))
9224                .expect("durable assigned target");
9225            drop(store);
9226            let reopened = FolderbaseVersionStore::open(root.path()).expect("crash reopen");
9227            let retry = reopened
9228                .seal_capture(reopened.plan_capture().expect("reopen plan"))
9229                .expect("exact retry");
9230            assert_eq!(retry.version_id(), assigned, "fault {fault:?}");
9231            let verified = reopened
9232                .read_version(retry.version_id())
9233                .expect("all referenced bytes verify");
9234            assert_eq!(verified.canonical_digest().unwrap(), retry.version_sha256());
9235            assert!(active_transaction(root.path()).is_none());
9236            let head = local_head(root.path()).expect("Local Head");
9237            assert_eq!(head.version_id, assigned);
9238        }
9239    }
9240
9241    #[test]
9242    fn released_root_capture_journal_survives_before_and_after_head_recovery_exactly() {
9243        let root = folderbase();
9244        let mut store = FolderbaseVersionStore::open(root.path()).expect("open");
9245        admit_test_legacy_root(&mut store);
9246        let plan = store.plan_capture().expect("plan");
9247        let legacy_plan_sha256 =
9248            capture_plan_sha256_with_root_instance(&plan, LEGACY_ROOT_INSTANCE_SHA256)
9249                .expect("legacy-root plan digest");
9250
9251        let interrupted = catch_unwind(AssertUnwindSafe(|| {
9252            store.seal_capture_with_hook(plan, |checkpoint| {
9253                if checkpoint == &CaptureCheckpoint::JournalDurable {
9254                    let state = FolderbaseState::open(root.path()).expect("state");
9255                    let mut transaction = active_transaction(root.path()).expect("active");
9256                    transaction.root_instance_sha256 = LEGACY_ROOT_INSTANCE_SHA256.to_owned();
9257                    transaction.plan_sha256 = legacy_plan_sha256.clone();
9258                    state
9259                        .replace(
9260                            Path::new(ACTIVE_CAPTURE_TRANSACTION_PATH),
9261                            &json_bytes(&transaction).expect("released journal bytes"),
9262                        )
9263                        .expect("install released-root journal");
9264                    panic!("terminate with released-root journal durable");
9265                }
9266            })
9267        }));
9268        assert!(interrupted.is_err());
9269        let journal_before =
9270            fs::read(root.path().join(ACTIVE_CAPTURE_TRANSACTION_PATH)).expect("journal");
9271        let assigned = active_transaction(root.path())
9272            .expect("released-root active journal")
9273            .target_version_id;
9274
9275        let after_head = catch_unwind(AssertUnwindSafe(|| {
9276            store.seal_capture_with_hook(store.plan_capture().expect("retry plan"), |checkpoint| {
9277                if checkpoint == &CaptureCheckpoint::HeadReplaced {
9278                    assert_eq!(
9279                        fs::read(root.path().join(ACTIVE_CAPTURE_TRANSACTION_PATH))
9280                            .expect("journal through Head CAS"),
9281                        journal_before,
9282                        "recovery must never normalize the active journal"
9283                    );
9284                    let head = local_head(root.path()).expect("recovered Head");
9285                    assert_eq!(
9286                        head.root_instance_sha256, store.root_attestation.root_instance_sha256,
9287                        "the normal next Head CAS may bind the current stronger root identity"
9288                    );
9289                    panic!("terminate after Head CAS");
9290                }
9291            })
9292        }));
9293        assert!(after_head.is_err());
9294        assert_eq!(
9295            fs::read(root.path().join(ACTIVE_CAPTURE_TRANSACTION_PATH)).expect("post-Head journal"),
9296            journal_before
9297        );
9298
9299        let recovered = store
9300            .seal_capture(store.plan_capture().expect("final retry"))
9301            .expect("recover exact released-root journal");
9302        assert_eq!(recovered.version_id(), assigned);
9303        assert!(active_transaction(root.path()).is_none());
9304        assert_eq!(
9305            local_head(root.path())
9306                .expect("final Head")
9307                .root_instance_sha256,
9308            store.root_attestation.root_instance_sha256
9309        );
9310    }
9311
9312    #[test]
9313    fn local_head_wire_distinguishes_capture_and_version_derived_authority() {
9314        let root = folderbase();
9315        let store = FolderbaseVersionStore::open(root.path()).expect("open");
9316        store
9317            .seal_capture(store.plan_capture().expect("genesis"))
9318            .expect("genesis");
9319        let captured: serde_json::Value = serde_json::from_slice(
9320            &fs::read(root.path().join(LOCAL_HEAD_PATH)).expect("captured Head"),
9321        )
9322        .expect("captured Head JSON");
9323        assert_eq!(captured["format"], "folderbase-local-head-v2");
9324        assert_eq!(captured["authority"]["kind"], "capture_transaction_v1");
9325        assert!(captured["authority"]["sha256"].as_str().is_some());
9326        assert!(captured.get("transaction_sha256").is_none());
9327
9328        fs::remove_file(root.path().join("active.bin")).expect("delete");
9329        store
9330            .seal_capture(store.plan_capture().expect("deletion"))
9331            .expect("deletion");
9332        store
9333            .restore_tombstone("active.bin")
9334            .expect("restore Tombstone");
9335        let restored: serde_json::Value = serde_json::from_slice(
9336            &fs::read(root.path().join(LOCAL_HEAD_PATH)).expect("restored Head"),
9337        )
9338        .expect("restored Head JSON");
9339        assert_eq!(restored["format"], "folderbase-local-head-v2");
9340        assert_eq!(restored["authority"]["kind"], "version_derived_v1");
9341        assert!(restored["authority"]["sha256"].as_str().is_some());
9342        assert!(restored.get("transaction_sha256").is_none());
9343    }
9344
9345    #[test]
9346    fn legacy_root_head_rebind_is_atomic_and_verifies_its_immutable_version() {
9347        let root = folderbase();
9348        let mut store = FolderbaseVersionStore::open(root.path()).expect("open");
9349        store
9350            .seal_capture(store.plan_capture().expect("genesis"))
9351            .expect("genesis");
9352        admit_test_legacy_root(&mut store);
9353
9354        let mut legacy = local_head(root.path()).expect("captured Head");
9355        legacy.root_instance_sha256 = LEGACY_ROOT_INSTANCE_SHA256.to_owned();
9356        let retained_authority = legacy.authority.clone();
9357        write_test_head(root.path(), &legacy);
9358        let legacy_bytes = fs::read(root.path().join(LOCAL_HEAD_PATH)).expect("legacy Head bytes");
9359        let local = LocalVersionStore::open_read_only(root.path()).expect("local");
9360        let state = FolderbaseState::open_existing(root.path()).expect("state");
9361
9362        let before = catch_unwind(AssertUnwindSafe(|| {
9363            rebind_legacy_root_local_head_with_hook(&store, &local, &state, |checkpoint| {
9364                if checkpoint == LocalHeadRebindCheckpoint::BeforeCas {
9365                    panic!("terminate before Head CAS");
9366                }
9367            })
9368        }));
9369        assert!(before.is_err());
9370        assert_eq!(
9371            fs::read(root.path().join(LOCAL_HEAD_PATH)).expect("Head after pre-CAS fault"),
9372            legacy_bytes,
9373            "a pre-CAS fault must preserve the exact released Head bytes"
9374        );
9375
9376        let after = catch_unwind(AssertUnwindSafe(|| {
9377            rebind_legacy_root_local_head_with_hook(&store, &local, &state, |checkpoint| {
9378                if checkpoint == LocalHeadRebindCheckpoint::AfterCas {
9379                    panic!("terminate after Head CAS");
9380                }
9381            })
9382        }));
9383        assert!(after.is_err());
9384        let rebound = local_head(root.path()).expect("rebound Head");
9385        assert_eq!(
9386            rebound.root_instance_sha256,
9387            store.root_attestation.root_instance_sha256
9388        );
9389        assert_eq!(
9390            rebound.authority, retained_authority,
9391            "capture-transaction authority continues to hash the exact journal bytes"
9392        );
9393
9394        let mut invalid = rebound;
9395        invalid.root_instance_sha256 = LEGACY_ROOT_INSTANCE_SHA256.to_owned();
9396        invalid.version_sha256 =
9397            "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb".to_owned();
9398        write_test_head(root.path(), &invalid);
9399        let invalid_bytes = fs::read(root.path().join(LOCAL_HEAD_PATH)).expect("invalid Head");
9400        assert!(matches!(
9401            rebind_legacy_root_local_head(&store, &local, &state),
9402            Err(FolderbaseCaptureError::InvalidLocalHead(_))
9403        ));
9404        assert_eq!(
9405            fs::read(root.path().join(LOCAL_HEAD_PATH)).expect("rejected Head"),
9406            invalid_bytes,
9407            "rebind must not bless a Head whose immutable Version digest is invalid"
9408        );
9409    }
9410
9411    #[test]
9412    fn legacy_version_derived_head_rebinds_only_its_root_derived_authority() {
9413        let root = folderbase();
9414        let mut store = FolderbaseVersionStore::open(root.path()).expect("open");
9415        store
9416            .seal_capture(store.plan_capture().expect("genesis"))
9417            .expect("genesis");
9418        fs::remove_file(root.path().join("active.bin")).expect("delete");
9419        store
9420            .seal_capture(store.plan_capture().expect("deletion"))
9421            .expect("deletion");
9422        store
9423            .restore_tombstone("active.bin")
9424            .expect("restore to version-derived Head");
9425        admit_test_legacy_root(&mut store);
9426
9427        let mut legacy = local_head(root.path()).expect("version-derived Head");
9428        legacy.root_instance_sha256 = LEGACY_ROOT_INSTANCE_SHA256.to_owned();
9429        legacy.authority = LocalHeadAuthority::VersionDerivedV1 {
9430            sha256: version_derived_local_head_sha256(
9431                &legacy.folderbase_id,
9432                LEGACY_ROOT_INSTANCE_SHA256,
9433                &legacy.version_id,
9434                &legacy.version_sha256,
9435            )
9436            .expect("released authority"),
9437        };
9438        let legacy_authority = legacy.authority.clone();
9439        write_test_head(root.path(), &legacy);
9440
9441        let local = LocalVersionStore::open_read_only(root.path()).expect("local");
9442        let state = FolderbaseState::open_existing(root.path()).expect("state");
9443        rebind_legacy_root_local_head(&store, &local, &state).expect("rebind");
9444        let rebound = local_head(root.path()).expect("rebound Head");
9445        assert_eq!(
9446            rebound.root_instance_sha256,
9447            store.root_attestation.root_instance_sha256
9448        );
9449        assert_ne!(rebound.authority, legacy_authority);
9450        assert_eq!(
9451            rebound.authority,
9452            LocalHeadAuthority::VersionDerivedV1 {
9453                sha256: local_head_authority_sha256(
9454                    &store,
9455                    &rebound.version_id,
9456                    &rebound.version_sha256,
9457                )
9458                .expect("current authority"),
9459            }
9460        );
9461    }
9462
9463    #[test]
9464    fn full_windows_v2_collision_is_rejected_by_local_head_admission() {
9465        const WINDOWS_V2_FIRST: &str =
9466            "8ff64630529b2fbda0062c3c15b8109e050e99f905cf497ad3a864cc19db6b2c";
9467        const RELEASED_WINDOWS_V1: &str =
9468            "b3bd16243ce08bcb477e45af8682519dbbbeb3d33bd50d4a1660fe04a073bc03";
9469        const WINDOWS_V2_LEGACY_COLLISION: &str =
9470            "2afb8ccf76a5f517a400d52b539060d66a99ee816b9f2c94f63a7c3e2a32b6dc";
9471
9472        let root = folderbase();
9473        let mut store = FolderbaseVersionStore::open(root.path()).expect("open");
9474        store
9475            .seal_capture(store.plan_capture().expect("genesis"))
9476            .expect("genesis");
9477        store.root_attestation.root_instance_sha256 = WINDOWS_V2_FIRST.to_owned();
9478        store.root_instance_authority = crate::root_attestation::RootInstanceAuthority::for_test(
9479            WINDOWS_V2_FIRST.to_owned(),
9480            Some(RELEASED_WINDOWS_V1.to_owned()),
9481        );
9482        let mut forged = local_head(root.path()).expect("Head");
9483        forged.root_instance_sha256 = WINDOWS_V2_LEGACY_COLLISION.to_owned();
9484        write_test_head(root.path(), &forged);
9485        let exact_bytes = fs::read(root.path().join(LOCAL_HEAD_PATH)).expect("forged Head");
9486        let local = LocalVersionStore::open_read_only(root.path()).expect("local");
9487        let state = FolderbaseState::open_existing(root.path()).expect("state");
9488
9489        assert!(matches!(
9490            rebind_legacy_root_local_head(&store, &local, &state),
9491            Err(FolderbaseCaptureError::InvalidLocalHead(_))
9492        ));
9493        assert_eq!(
9494            fs::read(root.path().join(LOCAL_HEAD_PATH)).expect("rejected Head"),
9495            exact_bytes,
9496            "a V2 identity that collided under released truncation must never be admitted"
9497        );
9498    }
9499
9500    #[test]
9501    fn released_v1_capture_heads_recover_and_normalize_without_losing_authority() {
9502        fn write_v1_head(root: &Path, transaction_sha256: &str) {
9503            let head = local_head(root).expect("current Head");
9504            FolderbaseState::open(root)
9505                .expect("state")
9506                .replace(
9507                    Path::new(LOCAL_HEAD_PATH),
9508                    &json_bytes(&serde_json::json!({
9509                        "format": "folderbase-local-head-v1",
9510                        "folderbase_id": head.folderbase_id,
9511                        "root_instance_sha256": head.root_instance_sha256,
9512                        "version_id": head.version_id,
9513                        "version_sha256": head.version_sha256,
9514                        "transaction_sha256": transaction_sha256
9515                    }))
9516                    .expect("v1 Head bytes"),
9517                )
9518                .expect("install v1 Head");
9519        }
9520
9521        let recovering = folderbase();
9522        let store = FolderbaseVersionStore::open(recovering.path()).expect("open");
9523        let interrupted = catch_unwind(AssertUnwindSafe(|| {
9524            store.seal_capture_with_hook(store.plan_capture().expect("plan"), |checkpoint| {
9525                if checkpoint == &CaptureCheckpoint::HeadReplaced {
9526                    let transaction =
9527                        active_transaction(recovering.path()).expect("active capture transaction");
9528                    write_v1_head(
9529                        recovering.path(),
9530                        &capture_transaction_sha256(&transaction).expect("transaction authority"),
9531                    );
9532                    panic!("simulate released v1 process termination");
9533                }
9534            })
9535        }));
9536        assert!(interrupted.is_err());
9537        drop(store);
9538
9539        let reopened = FolderbaseVersionStore::open(recovering.path()).expect("reopen");
9540        let recovered = reopened
9541            .seal_capture(reopened.plan_capture().expect("v1 recovery plan"))
9542            .expect("recover v1 Head and active capture");
9543        let recovered_head: serde_json::Value = serde_json::from_slice(
9544            &fs::read(recovering.path().join(LOCAL_HEAD_PATH)).expect("recovered Head"),
9545        )
9546        .expect("recovered Head JSON");
9547        assert_eq!(recovered_head["format"], "folderbase-local-head-v2");
9548        assert_eq!(
9549            recovered_head["authority"]["kind"],
9550            "capture_transaction_v1"
9551        );
9552        assert_eq!(recovered_head["version_id"], recovered.version_id());
9553
9554        let steady = folderbase();
9555        let steady_store = FolderbaseVersionStore::open(steady.path()).expect("open steady");
9556        steady_store
9557            .seal_capture(steady_store.plan_capture().expect("steady plan"))
9558            .expect("steady capture");
9559        let authority = local_head(steady.path())
9560            .expect("steady Head")
9561            .authority
9562            .sha256()
9563            .to_owned();
9564        write_v1_head(steady.path(), &authority);
9565        drop(steady_store);
9566
9567        let reopened = FolderbaseVersionStore::open(steady.path()).expect("reopen steady");
9568        let unchanged = reopened
9569            .seal_capture(reopened.plan_capture().expect("steady v1 plan"))
9570            .expect("normalize steady v1 Head");
9571        assert!(!unchanged.created());
9572        let normalized: serde_json::Value = serde_json::from_slice(
9573            &fs::read(steady.path().join(LOCAL_HEAD_PATH)).expect("normalized Head"),
9574        )
9575        .expect("normalized Head JSON");
9576        assert_eq!(normalized["format"], "folderbase-local-head-v2");
9577        assert_eq!(normalized["authority"]["sha256"], authority);
9578    }
9579
9580    #[test]
9581    fn released_v1_non_genesis_active_journal_recovers_before_and_after_head() {
9582        #[derive(Serialize)]
9583        struct ReleasedJournalHead {
9584            version_id: String,
9585            version_sha256: String,
9586            transaction_sha256: String,
9587        }
9588
9589        #[derive(Serialize)]
9590        struct ReleasedPlanHead<'a> {
9591            version_id: &'a str,
9592            version_sha256: &'a str,
9593            transaction_sha256: &'a str,
9594        }
9595
9596        #[derive(Serialize)]
9597        struct ReleasedPlanDigest<'a> {
9598            format: &'static str,
9599            folderbase_id: &'a str,
9600            root_instance_sha256: &'a str,
9601            root_manifest_sha256: &'a str,
9602            root_manifest_bytes: u64,
9603            ignore_policy_sha256: &'a str,
9604            current_head: Option<ReleasedPlanHead<'a>>,
9605            entries: Vec<ReleasedPlanDigestEntry<'a>>,
9606            exclusions: Vec<ReleasedPlanDigestExclusion<'a>>,
9607            ignored_paths: Vec<&'a str>,
9608        }
9609
9610        #[derive(Serialize)]
9611        struct ReleasedPlanDigestEntry<'a> {
9612            path: &'a str,
9613            kind: CaptureEntryKind,
9614            bytes: Option<u64>,
9615            executable: Option<bool>,
9616            symlink_target: Option<&'a str>,
9617            observed: &'a CaptureMetadataFingerprint,
9618        }
9619
9620        #[derive(Serialize)]
9621        struct ReleasedPlanDigestExclusion<'a> {
9622            path: &'a str,
9623            kind: CaptureExclusionKind,
9624            reason: CaptureExclusionReason,
9625        }
9626
9627        #[derive(Serialize)]
9628        struct ReleasedCaptureAssignment {
9629            path: String,
9630            kind: CaptureEntryKind,
9631            object_id: String,
9632            candidate_object_version_id: Option<String>,
9633            prior_object_version_id: Option<String>,
9634            reused_object: bool,
9635            observed: CaptureMetadataFingerprint,
9636        }
9637
9638        #[derive(Serialize)]
9639        struct ReleasedCaptureTransaction {
9640            format: String,
9641            transaction_id: String,
9642            folderbase_id: String,
9643            root_instance_sha256: String,
9644            plan_sha256: String,
9645            expected_head: Option<ReleasedJournalHead>,
9646            target_version_id: String,
9647            created_at: String,
9648            root_manifest_object_id: String,
9649            root_manifest_candidate_version_id: String,
9650            prior_root_manifest_version_id: Option<String>,
9651            assignments: Vec<ReleasedCaptureAssignment>,
9652            #[serde(skip_serializing_if = "Vec::is_empty")]
9653            target_tombstones: Vec<Tombstone>,
9654        }
9655
9656        fn released_plan_sha256(plan: &CapturePlan) -> String {
9657            assert!(
9658                plan.entries()
9659                    .iter()
9660                    .all(|entry| entry.link_commitment().is_legacy_default()),
9661                "released v1 had no retained-authority link commitment"
9662            );
9663            let current_head = plan.current_local_head().map(|head| {
9664                let LocalHeadAuthority::CaptureTransactionV1 { sha256 } = head.authority() else {
9665                    panic!("released v1 cannot encode version-derived Head authority");
9666                };
9667                ReleasedPlanHead {
9668                    version_id: head.version_id(),
9669                    version_sha256: head.version_sha256(),
9670                    transaction_sha256: sha256,
9671                }
9672            });
9673            let released = ReleasedPlanDigest {
9674                format: "folderbase-capture-plan-digest-v1",
9675                folderbase_id: plan.folderbase_id(),
9676                root_instance_sha256: plan.root_instance_sha256(),
9677                root_manifest_sha256: plan.root_manifest_sha256(),
9678                root_manifest_bytes: plan.root_manifest_bytes(),
9679                ignore_policy_sha256: plan.ignore_policy_sha256(),
9680                current_head,
9681                entries: plan
9682                    .entries()
9683                    .iter()
9684                    .map(|entry| ReleasedPlanDigestEntry {
9685                        path: entry.path(),
9686                        kind: entry.kind(),
9687                        bytes: entry.bytes(),
9688                        executable: entry.executable(),
9689                        symlink_target: entry.symlink_target(),
9690                        observed: entry.observed(),
9691                    })
9692                    .collect(),
9693                exclusions: plan
9694                    .exclusions()
9695                    .iter()
9696                    .map(|exclusion| ReleasedPlanDigestExclusion {
9697                        path: exclusion.path(),
9698                        kind: exclusion.kind(),
9699                        reason: exclusion.reason(),
9700                    })
9701                    .collect(),
9702                ignored_paths: plan
9703                    .ignored_paths()
9704                    .iter()
9705                    .map(|path| path.path())
9706                    .collect(),
9707            };
9708            let encoded =
9709                serde_json::to_vec(&released).expect("independent released v1 plan digest bytes");
9710            format!("{:x}", Sha256::digest(encoded))
9711        }
9712
9713        fn released_journal_bytes(
9714            transaction: &CaptureTransaction,
9715            released_plan_sha256: &str,
9716        ) -> Vec<u8> {
9717            let expected_head = transaction.expected_head.as_ref().map(|head| {
9718                let LocalHeadAuthority::CaptureTransactionV1 { sha256 } = &head.authority else {
9719                    panic!("released capture parent must retain capture authority");
9720                };
9721                ReleasedJournalHead {
9722                    version_id: head.version_id.clone(),
9723                    version_sha256: head.version_sha256.clone(),
9724                    transaction_sha256: sha256.clone(),
9725                }
9726            });
9727            let released = ReleasedCaptureTransaction {
9728                format: transaction.format.clone(),
9729                transaction_id: transaction.transaction_id.clone(),
9730                folderbase_id: transaction.folderbase_id.clone(),
9731                root_instance_sha256: transaction.root_instance_sha256.clone(),
9732                plan_sha256: released_plan_sha256.to_owned(),
9733                expected_head,
9734                target_version_id: transaction.target_version_id.clone(),
9735                created_at: transaction.created_at.clone(),
9736                root_manifest_object_id: transaction.root_manifest_object_id.clone(),
9737                root_manifest_candidate_version_id: transaction
9738                    .root_manifest_candidate_version_id
9739                    .clone(),
9740                prior_root_manifest_version_id: transaction.prior_root_manifest_version_id.clone(),
9741                assignments: transaction
9742                    .assignments
9743                    .iter()
9744                    .map(|assignment| ReleasedCaptureAssignment {
9745                        path: assignment.path.clone(),
9746                        kind: assignment.kind,
9747                        object_id: assignment.object_id.clone(),
9748                        candidate_object_version_id: assignment.candidate_object_version_id.clone(),
9749                        prior_object_version_id: assignment.prior_object_version_id.clone(),
9750                        reused_object: assignment.reused_object,
9751                        observed: assignment.observed.clone(),
9752                    })
9753                    .collect(),
9754                target_tombstones: transaction.target_tombstones.clone(),
9755            };
9756            let mut encoded =
9757                serde_json::to_vec_pretty(&released).expect("released capture journal JSON");
9758            encoded.push(b'\n');
9759            encoded
9760        }
9761
9762        fn write_released_head(root: &Path, transaction_sha256: &str) {
9763            let head = local_head(root).expect("current Head");
9764            FolderbaseState::open(root)
9765                .expect("state")
9766                .replace(
9767                    Path::new(LOCAL_HEAD_PATH),
9768                    &json_bytes(&serde_json::json!({
9769                        "format": "folderbase-local-head-v1",
9770                        "folderbase_id": head.folderbase_id,
9771                        "root_instance_sha256": head.root_instance_sha256,
9772                        "version_id": head.version_id,
9773                        "version_sha256": head.version_sha256,
9774                        "transaction_sha256": transaction_sha256
9775                    }))
9776                    .expect("released Head bytes"),
9777                )
9778                .expect("install released Head");
9779        }
9780
9781        for fault in [
9782            CaptureCheckpoint::JournalDurable,
9783            CaptureCheckpoint::HeadReplaced,
9784        ] {
9785            let root = folderbase();
9786            let store = FolderbaseVersionStore::open(root.path()).expect("open");
9787            store
9788                .seal_capture(store.plan_capture().expect("genesis"))
9789                .expect("genesis");
9790            fs::write(root.path().join("active.bin"), b"non-genesis update")
9791                .expect("update live file");
9792            let plan = store.plan_capture().expect("update plan");
9793            let released_plan_sha256 = released_plan_sha256(&plan);
9794            let interrupted = catch_unwind(AssertUnwindSafe(|| {
9795                store.seal_capture_with_hook(plan, |checkpoint| {
9796                    if checkpoint == &fault {
9797                        panic!("simulate released v1 process termination at {fault:?}");
9798                    }
9799                })
9800            }));
9801            assert!(interrupted.is_err(), "fault {fault:?}");
9802
9803            let transaction = active_transaction(root.path()).expect("active capture");
9804            let original_transaction_id = transaction.transaction_id.clone();
9805            assert!(
9806                transaction.expected_head.is_some(),
9807                "fixture must be non-genesis"
9808            );
9809            assert_eq!(
9810                transaction.plan_sha256, released_plan_sha256,
9811                "ordinary capture Heads must retain the exact released flat-Head v1 plan digest"
9812            );
9813            let released_bytes = released_journal_bytes(&transaction, &released_plan_sha256);
9814            let released_json: serde_json::Value =
9815                serde_json::from_slice(&released_bytes).expect("released journal value");
9816            assert_eq!(
9817                released_json["transaction_id"], original_transaction_id,
9818                "released recovery must preserve the original transaction identity"
9819            );
9820            let released_sha256 = format!("{:x}", Sha256::digest(&released_bytes));
9821            let normalized_current_bytes =
9822                encode_active_transaction(&transaction, MAX_CAPTURE_TRANSACTION_BYTES)
9823                    .expect("normalized current journal");
9824            assert!(
9825                released_bytes.len() < normalized_current_bytes.len(),
9826                "fixture needs a bound that accepts compact released v1 but rejects normalized current wire"
9827            );
9828            let released_limit = released_bytes.len() as u64;
9829            let state = FolderbaseState::open(root.path()).expect("state");
9830            state
9831                .replace(Path::new(ACTIVE_CAPTURE_TRANSACTION_PATH), &released_bytes)
9832                .expect("install exact released active journal bytes");
9833            if fault == CaptureCheckpoint::JournalDurable {
9834                let original_head =
9835                    fs::read(root.path().join(LOCAL_HEAD_PATH)).expect("prior Head bytes");
9836
9837                let mut hybrid = released_json.clone();
9838                hybrid["assignments"][0]["link_commitment"] = serde_json::json!({
9839                    "expected_live_link_count": 1,
9840                    "authority_set_sha256": null,
9841                    "authorities": []
9842                });
9843                let hybrid_bytes =
9844                    serde_json::to_vec_pretty(&hybrid).expect("hybrid active journal");
9845                state
9846                    .replace(Path::new(ACTIVE_CAPTURE_TRANSACTION_PATH), &hybrid_bytes)
9847                    .expect("install hybrid active journal");
9848                assert!(
9849                    read_active_transaction_with_limit(
9850                        &state,
9851                        u64::try_from(hybrid_bytes.len()).expect("hybrid length")
9852                    )
9853                    .is_err(),
9854                    "a flat released Head with a current-only assignment must not be classified as released v1"
9855                );
9856                assert_eq!(
9857                    fs::read(root.path().join(LOCAL_HEAD_PATH)).expect("unchanged prior Head"),
9858                    original_head,
9859                    "rejecting a hybrid journal must not move Head"
9860                );
9861
9862                let mut maximum_released = released_bytes.clone();
9863                maximum_released.resize(
9864                    usize::try_from(MAX_CAPTURE_TRANSACTION_BYTES)
9865                        .expect("capture transaction maximum fits usize"),
9866                    b' ',
9867                );
9868                state
9869                    .replace(
9870                        Path::new(ACTIVE_CAPTURE_TRANSACTION_PATH),
9871                        &maximum_released,
9872                    )
9873                    .expect("install released journal at the exact raw maximum");
9874                let maximum_active =
9875                    read_active_transaction_with_limit(&state, MAX_CAPTURE_TRANSACTION_BYTES)
9876                        .expect("read exact-maximum released journal")
9877                        .expect("active exact-maximum released journal");
9878                assert_eq!(maximum_active.transaction_id, original_transaction_id);
9879                assert_eq!(
9880                    maximum_active.wire,
9881                    CaptureTransactionWire::ReleasedV1 {
9882                        encoded_bytes: MAX_CAPTURE_TRANSACTION_BYTES
9883                    },
9884                    "accepted trailing JSON whitespace remains part of the exact released authority wire"
9885                );
9886
9887                use std::io::Write as _;
9888                fs::OpenOptions::new()
9889                    .append(true)
9890                    .open(root.path().join(ACTIVE_CAPTURE_TRANSACTION_PATH))
9891                    .expect("open exact-maximum journal")
9892                    .write_all(b" ")
9893                    .expect("grow journal one byte beyond maximum");
9894                assert!(
9895                    read_active_transaction_with_limit(&state, MAX_CAPTURE_TRANSACTION_BYTES)
9896                        .is_err(),
9897                    "a released raw journal one byte beyond the actual maximum must fail closed"
9898                );
9899
9900                let mut truncated_released = released_bytes.clone();
9901                while truncated_released
9902                    .last()
9903                    .is_some_and(u8::is_ascii_whitespace)
9904                {
9905                    truncated_released.pop();
9906                }
9907                assert_eq!(truncated_released.pop(), Some(b'}'));
9908                state
9909                    .replace(
9910                        Path::new(ACTIVE_CAPTURE_TRANSACTION_PATH),
9911                        &truncated_released,
9912                    )
9913                    .expect("install truncated released journal");
9914                assert!(
9915                    read_active_transaction_with_limit(
9916                        &state,
9917                        u64::try_from(truncated_released.len()).expect("truncated length")
9918                    )
9919                    .is_err(),
9920                    "raw released JSON truncation must fail closed"
9921                );
9922
9923                state
9924                    .replace(Path::new(ACTIVE_CAPTURE_TRANSACTION_PATH), &released_bytes)
9925                    .expect("restore exact released active journal bytes");
9926            }
9927            assert!(
9928                read_active_transaction_with_limit(&state, released_limit - 1).is_err(),
9929                "oversized released raw wire must still fail its exact read bound"
9930            );
9931            let head_authority = if fault == CaptureCheckpoint::HeadReplaced {
9932                released_sha256.clone()
9933            } else {
9934                local_head(root.path())
9935                    .expect("prior Head")
9936                    .authority
9937                    .sha256()
9938                    .to_owned()
9939            };
9940            write_released_head(root.path(), &head_authority);
9941            drop(store);
9942
9943            let reopened = FolderbaseVersionStore::open(root.path()).expect("fresh reopen");
9944            let recovered = reopened
9945                .seal_capture_with_hook_and_limits(
9946                    reopened.plan_capture().expect("recovery plan"),
9947                    |_| {},
9948                    released_limit,
9949                    MAX_ENCODED_VERSION_BYTES,
9950                )
9951                .expect("released active journal recovery");
9952            assert_eq!(recovered.version_id(), transaction.target_version_id);
9953            assert!(active_transaction(root.path()).is_none());
9954            let head = local_head(root.path()).expect("normalized recovered Head");
9955            assert_eq!(head.format, "folderbase-local-head-v2");
9956            assert_eq!(head.authority.sha256(), released_sha256);
9957        }
9958    }
9959
9960    #[test]
9961    fn local_head_rejects_unknown_or_mismatched_authority_discriminators() {
9962        let root = folderbase();
9963        let store = FolderbaseVersionStore::open(root.path()).expect("open");
9964        store
9965            .seal_capture(store.plan_capture().expect("genesis"))
9966            .expect("genesis");
9967        let head = local_head(root.path()).expect("captured Head");
9968        let version_authority =
9969            local_head_authority_sha256(&store, &head.version_id, &head.version_sha256)
9970                .expect("version authority");
9971        assert_ne!(head.authority.sha256(), version_authority);
9972        let head_path = Path::new(LOCAL_HEAD_PATH);
9973        let state = FolderbaseState::open(root.path()).expect("state");
9974        let mut wire: serde_json::Value = serde_json::from_slice(
9975            &state
9976                .read_bounded(head_path, crate::MAX_LOCAL_HEAD_BYTES)
9977                .expect("read Head")
9978                .expect("Head"),
9979        )
9980        .expect("Head JSON");
9981
9982        wire["authority"]["kind"] = serde_json::Value::String("version_derived_v1".to_owned());
9983        state
9984            .replace(head_path, &json_bytes(&wire).expect("mismatched Head"))
9985            .expect("install mismatched Head");
9986        assert!(matches!(
9987            FolderbaseVersionStore::open(root.path()),
9988            Err(FolderbaseCaptureError::InvalidLocalHead(message))
9989                if message.contains("version-derived")
9990        ));
9991
9992        wire["authority"]["kind"] = serde_json::Value::String("future_authority_v9".to_owned());
9993        state
9994            .replace(head_path, &json_bytes(&wire).expect("unknown Head"))
9995            .expect("install unknown Head");
9996        assert!(matches!(
9997            FolderbaseVersionStore::open(root.path()),
9998            Err(FolderbaseCaptureError::InvalidLocalHead(_))
9999        ));
10000    }
10001
10002    #[test]
10003    fn post_head_legacy_journal_without_tombstone_field_still_recovers() {
10004        let root = folderbase();
10005        let store = FolderbaseVersionStore::open(root.path()).expect("open");
10006        let plan = store.plan_capture().expect("plan");
10007        let interrupted = catch_unwind(AssertUnwindSafe(|| {
10008            store.seal_capture_with_hook(plan, |checkpoint| {
10009                if checkpoint == &CaptureCheckpoint::HeadReplaced {
10010                    let state = FolderbaseState::open(root.path()).expect("state");
10011                    let active_path = Path::new(ACTIVE_CAPTURE_TRANSACTION_PATH);
10012                    let encoded = state
10013                        .read_bounded(active_path, MAX_CAPTURE_TRANSACTION_BYTES)
10014                        .expect("read active journal")
10015                        .expect("active journal");
10016                    let mut wire: serde_json::Value =
10017                        serde_json::from_slice(&encoded).expect("journal JSON");
10018                    wire.as_object_mut()
10019                        .expect("journal object")
10020                        .remove("target_tombstones");
10021                    for assignment in wire["assignments"]
10022                        .as_array_mut()
10023                        .expect("legacy assignments")
10024                    {
10025                        assignment
10026                            .as_object_mut()
10027                            .expect("legacy assignment")
10028                            .remove("link_commitment");
10029                    }
10030                    assert!(wire.get("target_tombstones").is_none());
10031                    let legacy_encoded = json_bytes(&wire).expect("legacy journal bytes");
10032                    state
10033                        .replace(active_path, &legacy_encoded)
10034                        .expect("install legacy journal");
10035
10036                    let mut head = local_head(root.path()).expect("Local Head");
10037                    head.authority = LocalHeadAuthority::CaptureTransactionV1 {
10038                        sha256: format!("{:x}", Sha256::digest(&legacy_encoded)),
10039                    };
10040                    state
10041                        .replace(Path::new(LOCAL_HEAD_PATH), &json_bytes(&head).unwrap())
10042                        .expect("bind Head to legacy journal");
10043                    panic!("stop after legacy Head replacement");
10044                }
10045            })
10046        }));
10047        assert!(interrupted.is_err());
10048
10049        let legacy_head = local_head(root.path()).expect("legacy Head");
10050        let legacy_sha256 = legacy_head.authority.sha256().to_owned();
10051        let assigned = legacy_head.version_id;
10052        let reopened = FolderbaseVersionStore::open(root.path()).expect("reopen");
10053        let retry = reopened
10054            .seal_capture(reopened.plan_capture().expect("same live plan"))
10055            .expect("legacy post-Head intent must recover");
10056        assert_eq!(retry.version_id(), assigned);
10057        assert!(reopened.read_version(retry.version_id()).is_ok());
10058        assert!(active_transaction(root.path()).is_none());
10059        assert_eq!(
10060            local_head(root.path())
10061                .expect("recovered legacy Head")
10062                .authority
10063                .sha256(),
10064            legacy_sha256,
10065            "recovery must retain the SHA-256 of the exact installed legacy journal bytes"
10066        );
10067    }
10068
10069    fn interrupt_update_after_journal(
10070        root: &Path,
10071        store: &FolderbaseVersionStore,
10072    ) -> (Vec<u8>, String) {
10073        fs::write(root.join("pending.bin"), b"pending update").expect("pending update");
10074        let plan = store.plan_capture().expect("update plan");
10075        let interrupted = catch_unwind(AssertUnwindSafe(|| {
10076            store.seal_capture_with_hook(plan, |checkpoint| {
10077                if checkpoint == &CaptureCheckpoint::JournalDurable {
10078                    panic!("stop after active journal");
10079                }
10080            })
10081        }));
10082        assert!(interrupted.is_err());
10083        let transaction = active_transaction(root).expect("active intent");
10084        let encoded = fs::read(root.join(ACTIVE_CAPTURE_TRANSACTION_PATH))
10085            .expect("exact active journal bytes");
10086        (encoded, transaction.target_version_id)
10087    }
10088
10089    fn assert_hidden_retry_preserves_active_intent(
10090        root: &Path,
10091        store: &FolderbaseVersionStore,
10092        journal_before: &[u8],
10093        hidden_path: &Path,
10094    ) {
10095        let head_before = fs::read(root.join(LOCAL_HEAD_PATH)).expect("prior Head");
10096        let error = store
10097            .seal_capture(store.plan_capture().expect("scope-change plan"))
10098            .expect_err("hidden prior binding must be refused");
10099        assert!(matches!(
10100            error,
10101            FolderbaseCaptureError::PriorBindingHidden(path) if path == hidden_path
10102        ));
10103        assert_eq!(
10104            fs::read(root.join(ACTIVE_CAPTURE_TRANSACTION_PATH)).expect("preserved active intent"),
10105            journal_before
10106        );
10107        assert_eq!(
10108            fs::read(root.join(LOCAL_HEAD_PATH)).expect("unchanged prior Head"),
10109            head_before
10110        );
10111    }
10112
10113    #[test]
10114    fn newly_ignored_path_preserves_stale_active_intent_before_refusal() {
10115        let root = folderbase();
10116        let store = FolderbaseVersionStore::open(root.path()).expect("open");
10117        store
10118            .seal_capture(store.plan_capture().expect("genesis plan"))
10119            .expect("genesis");
10120        let ignore_path = root.path().join(".folderbaseignore");
10121        let original_modified = fs::metadata(&ignore_path)
10122            .expect("ignore metadata")
10123            .modified()
10124            .expect("ignore modified time");
10125        let (journal, assigned) = interrupt_update_after_journal(root.path(), &store);
10126
10127        fs::write(&ignore_path, "active.bin\n").expect("hide prior binding");
10128        assert_hidden_retry_preserves_active_intent(
10129            root.path(),
10130            &store,
10131            &journal,
10132            Path::new("active.bin"),
10133        );
10134
10135        fs::write(&ignore_path, "").expect("restore ignore policy");
10136        File::options()
10137            .write(true)
10138            .open(&ignore_path)
10139            .expect("open restored policy")
10140            .set_times(std::fs::FileTimes::new().set_modified(original_modified))
10141            .expect("restore approved plan time");
10142        let retry = store
10143            .seal_capture(store.plan_capture().expect("restored update plan"))
10144            .expect("preserved intent remains recoverable");
10145        assert_eq!(retry.version_id(), assigned);
10146        assert!(active_transaction(root.path()).is_none());
10147    }
10148
10149    #[test]
10150    fn new_nested_boundary_preserves_stale_active_intent_before_refusal() {
10151        let root = folderbase();
10152        fs::create_dir(root.path().join("client")).expect("client");
10153        fs::write(root.path().join("client/notes.md"), "client notes").expect("client notes");
10154        let store = FolderbaseVersionStore::open(root.path()).expect("open");
10155        store
10156            .seal_capture(store.plan_capture().expect("genesis plan"))
10157            .expect("genesis");
10158        let (journal, _) = interrupt_update_after_journal(root.path(), &store);
10159
10160        fs::create_dir(root.path().join("client/.folderbase")).expect("nested state");
10161        fs::write(
10162            root.path().join("client/.folderbase/manifest.json"),
10163            br#"{
10164  "protocol_version": "0.1.0",
10165  "folderbase": {
10166    "id": "folderbase_019f9b75-4f42-7f65-a012-2bfecdd8c474"
10167  }
10168}
10169"#,
10170        )
10171        .expect("nested manifest");
10172        fs::write(
10173            root.path().join("client/FOLDERBASE.md"),
10174            "# Nested Folderbase\n",
10175        )
10176        .expect("nested entry");
10177        assert_hidden_retry_preserves_active_intent(
10178            root.path(),
10179            &store,
10180            &journal,
10181            Path::new("client"),
10182        );
10183    }
10184
10185    #[cfg(unix)]
10186    #[test]
10187    fn unsupported_replacement_preserves_stale_active_intent_before_refusal() {
10188        let root = folderbase();
10189        let store = FolderbaseVersionStore::open(root.path()).expect("open");
10190        store
10191            .seal_capture(store.plan_capture().expect("genesis plan"))
10192            .expect("genesis");
10193        let (journal, _) = interrupt_update_after_journal(root.path(), &store);
10194
10195        let original = root.path().join("original-active.bin");
10196        fs::rename(root.path().join("active.bin"), &original).expect("retain original inode");
10197        fs::hard_link(&original, root.path().join("active.bin")).expect("unsupported hard link");
10198        assert_hidden_retry_preserves_active_intent(
10199            root.path(),
10200            &store,
10201            &journal,
10202            Path::new("active.bin"),
10203        );
10204    }
10205
10206    #[test]
10207    fn tombstone_capture_reopens_and_converges_at_every_persistence_checkpoint() {
10208        for fault in [
10209            CaptureCheckpoint::JournalDurable,
10210            CaptureCheckpoint::ObjectWritesDurable,
10211            CaptureCheckpoint::VersionDurable,
10212            CaptureCheckpoint::HeadReplaced,
10213            CaptureCheckpoint::CleanupComplete,
10214        ] {
10215            let root = folderbase();
10216            let store = FolderbaseVersionStore::open(root.path()).expect("open");
10217            let genesis = store
10218                .seal_capture(store.plan_capture().expect("genesis plan"))
10219                .expect("genesis");
10220            let prior = store
10221                .read_version(genesis.version_id())
10222                .expect("genesis version");
10223            let prior_binding = prior.lookup_binding("active.bin").expect("prior binding");
10224            let prior_object_id = prior_binding.object_id().to_owned();
10225            let prior_object_version_id = prior_binding
10226                .object_version_id()
10227                .expect("prior Object Version")
10228                .to_owned();
10229            fs::remove_file(root.path().join("active.bin")).expect("delete active file");
10230
10231            let plan = store.plan_capture().expect("deletion plan");
10232            let interrupted = catch_unwind(AssertUnwindSafe(|| {
10233                store.seal_capture_with_hook(plan, |checkpoint| {
10234                    if checkpoint == &fault {
10235                        panic!("simulated Tombstone termination at {fault:?}");
10236                    }
10237                })
10238            }));
10239            assert!(interrupted.is_err(), "fault {fault:?}");
10240
10241            let assigned = active_transaction(root.path())
10242                .map(|transaction| transaction.target_version_id)
10243                .or_else(|| local_head(root.path()).map(|head| head.version_id))
10244                .expect("durable assigned Tombstone target");
10245            drop(store);
10246            let reopened = FolderbaseVersionStore::open(root.path()).expect("crash reopen");
10247            let retry = reopened
10248                .seal_capture(reopened.plan_capture().expect("reopen deletion plan"))
10249                .expect("exact Tombstone retry");
10250            assert_eq!(retry.version_id(), assigned, "fault {fault:?}");
10251            let verified = reopened
10252                .read_version(retry.version_id())
10253                .expect("Tombstone references verify");
10254            assert_eq!(verified.parents(), &[genesis.version_id().to_owned()]);
10255            assert!(verified.lookup_binding("active.bin").is_none());
10256            assert_eq!(verified.tombstones().len(), 1);
10257            let tombstone = &verified.tombstones()[0];
10258            assert_eq!(tombstone.path(), "active.bin");
10259            assert_eq!(tombstone.object_id(), prior_object_id);
10260            assert_eq!(
10261                tombstone.last_object_version_id(),
10262                Some(prior_object_version_id.as_str())
10263            );
10264            assert!(active_transaction(root.path()).is_none());
10265            assert_eq!(
10266                local_head(root.path()).expect("Local Head").version_id,
10267                assigned
10268            );
10269        }
10270    }
10271
10272    #[test]
10273    fn active_journal_tombstone_tamper_never_changes_the_verified_deletion_target() {
10274        let root = folderbase();
10275        let store = FolderbaseVersionStore::open(root.path()).expect("open");
10276        let genesis = store
10277            .seal_capture(store.plan_capture().expect("genesis plan"))
10278            .expect("genesis");
10279        fs::remove_file(root.path().join("active.bin")).expect("delete active file");
10280        let plan = store.plan_capture().expect("deletion plan");
10281        let interrupted = catch_unwind(AssertUnwindSafe(|| {
10282            store.seal_capture_with_hook(plan, |checkpoint| {
10283                if checkpoint == &CaptureCheckpoint::JournalDurable {
10284                    panic!("stop after Tombstone journal");
10285                }
10286            })
10287        }));
10288        assert!(interrupted.is_err());
10289
10290        let mut transaction = active_transaction(root.path()).expect("active Tombstone intent");
10291        let original = transaction
10292            .target_tombstones
10293            .first()
10294            .expect("target Tombstone")
10295            .clone();
10296        transaction.target_tombstones[0] = Tombstone::from_verified_producer(
10297            original.path(),
10298            ObjectId::new().to_string(),
10299            original.deleted_kind(),
10300            original.last_object_version_id().map(str::to_owned),
10301        );
10302        FolderbaseState::open(root.path())
10303            .expect("state")
10304            .replace(
10305                Path::new(ACTIVE_CAPTURE_TRANSACTION_PATH),
10306                &json_bytes(&transaction).expect("tampered journal"),
10307            )
10308            .expect("replace active journal");
10309
10310        let reopened = FolderbaseVersionStore::open(root.path()).expect("reopen");
10311        let error = reopened
10312            .seal_capture(reopened.plan_capture().expect("same deletion plan"))
10313            .expect_err("tampered target Tombstone must fail closed");
10314        assert!(matches!(
10315            error,
10316            FolderbaseCaptureError::InvalidCaptureTransaction(message)
10317                if message.contains("Tombstones")
10318        ));
10319        assert_eq!(
10320            local_head(root.path()).expect("prior Head").version_id,
10321            genesis.version_id()
10322        );
10323    }
10324
10325    #[cfg(unix)]
10326    #[test]
10327    fn seal_retains_state_capability_before_any_publication_and_never_writes_through_a_swap() {
10328        use std::os::unix::fs::symlink;
10329
10330        let root = folderbase();
10331        let outside = tempdir().expect("outside");
10332        fs::write(outside.path().join("sentinel"), b"outside").expect("sentinel");
10333        let store = FolderbaseVersionStore::open(root.path()).expect("open");
10334        let plan = store.plan_capture().expect("plan");
10335        let error = store
10336            .seal_capture_with_hook(plan, |checkpoint| {
10337                if checkpoint == &CaptureCheckpoint::StateCapabilityOpen {
10338                    assert!(
10339                        !root
10340                            .path()
10341                            .join(".folderbase/locks/transactions.lock")
10342                            .exists(),
10343                        "no mutating prelude may run before the retained state capability"
10344                    );
10345                    fs::rename(
10346                        root.path().join(".folderbase"),
10347                        root.path().join(".folderbase-detached"),
10348                    )
10349                    .expect("detach original state");
10350                    symlink(outside.path(), root.path().join(".folderbase"))
10351                        .expect("replace visible state with outside link");
10352                }
10353            })
10354            .expect_err("state attachment swap must fail closed");
10355        assert!(matches!(
10356            error,
10357            FolderbaseCaptureError::PlanningStateChanged
10358                | FolderbaseCaptureError::PlanStoreMismatch
10359                | FolderbaseCaptureError::CaptureStateChanged(_)
10360                | FolderbaseCaptureError::LocalStore(_)
10361                | FolderbaseCaptureError::RootAttestation(_)
10362        ));
10363        assert_eq!(
10364            fs::read_dir(outside.path())
10365                .expect("outside directory")
10366                .map(|entry| entry.expect("entry").file_name())
10367                .collect::<Vec<_>>(),
10368            vec![std::ffi::OsString::from("sentinel")],
10369            "the swapped outside directory receives no Folderbase state"
10370        );
10371    }
10372
10373    #[test]
10374    fn update_faults_never_lose_prior_head_and_retry_preserves_parent() {
10375        for fault in [
10376            CaptureCheckpoint::JournalDurable,
10377            CaptureCheckpoint::ObjectWritesDurable,
10378            CaptureCheckpoint::VersionDurable,
10379            CaptureCheckpoint::HeadReplaced,
10380            CaptureCheckpoint::CleanupComplete,
10381        ] {
10382            let root = folderbase();
10383            let store = FolderbaseVersionStore::open(root.path()).expect("open");
10384            let genesis = store
10385                .seal_capture(store.plan_capture().expect("genesis plan"))
10386                .expect("genesis");
10387            fs::write(root.path().join("active.bin"), b"second opaque byte")
10388                .expect("same-inode edit");
10389            let plan = store.plan_capture().expect("update plan");
10390            let interrupted = catch_unwind(AssertUnwindSafe(|| {
10391                store.seal_capture_with_hook(plan, |checkpoint| {
10392                    if checkpoint == &fault {
10393                        panic!("simulated update termination at {fault:?}");
10394                    }
10395                })
10396            }));
10397            assert!(interrupted.is_err());
10398            let active = active_transaction(root.path());
10399            let head = local_head(root.path()).expect("Head survives");
10400            if matches!(
10401                fault,
10402                CaptureCheckpoint::JournalDurable
10403                    | CaptureCheckpoint::ObjectWritesDurable
10404                    | CaptureCheckpoint::VersionDurable
10405            ) {
10406                assert_eq!(head.version_id, genesis.version_id());
10407            }
10408            let assigned = active
10409                .map(|transaction| transaction.target_version_id)
10410                .unwrap_or_else(|| head.version_id.clone());
10411            drop(store);
10412            let reopened = FolderbaseVersionStore::open(root.path()).expect("crash reopen");
10413            let retry = reopened
10414                .seal_capture(reopened.plan_capture().expect("retry plan"))
10415                .expect("retry");
10416            assert_eq!(retry.version_id(), assigned);
10417            let update = reopened.read_version(retry.version_id()).expect("update");
10418            assert_eq!(update.parents(), &[genesis.version_id().to_owned()]);
10419        }
10420    }
10421
10422    #[test]
10423    fn mutation_after_preflight_and_before_byte_read_fails_without_head_movement() {
10424        let root = folderbase();
10425        let store = FolderbaseVersionStore::open(root.path()).expect("open");
10426        let plan = store.plan_capture().expect("plan");
10427        let error = store
10428            .seal_capture_with_hook(plan, |checkpoint| {
10429                if checkpoint == &CaptureCheckpoint::BeforeObjectBytesRead("active.bin".to_owned())
10430                {
10431                    fs::write(root.path().join("active.bin"), b"mutated opaque data")
10432                        .expect("concurrent edit");
10433                }
10434            })
10435            .expect_err("concurrent edit fails");
10436        assert!(matches!(
10437            error,
10438            FolderbaseCaptureError::CaptureStateChanged(path)
10439                if path == Path::new("active.bin")
10440        ));
10441        assert!(local_head(root.path()).is_none());
10442    }
10443
10444    #[test]
10445    fn extra_hard_link_before_restored_object_bytes_read_fails_without_head_movement() {
10446        let root = folderbase();
10447        let store = FolderbaseVersionStore::open(root.path()).expect("open");
10448        store
10449            .seal_capture(store.plan_capture().expect("genesis"))
10450            .expect("genesis");
10451        fs::remove_file(root.path().join("active.bin")).expect("delete");
10452        store
10453            .seal_capture(store.plan_capture().expect("deletion"))
10454            .expect("deletion");
10455        let restored = store
10456            .restore_tombstone("active.bin")
10457            .expect("restore with retained authority");
10458        let plan = store.plan_capture().expect("authority-aware plan");
10459
10460        let error = store
10461            .seal_capture_with_hook(plan, |checkpoint| {
10462                if checkpoint == &CaptureCheckpoint::BeforeObjectBytesRead("active.bin".to_owned())
10463                {
10464                    fs::hard_link(
10465                        root.path().join("active.bin"),
10466                        root.path().join("unapproved-extra-link.bin"),
10467                    )
10468                    .expect("concurrent extra hard link");
10469                }
10470            })
10471            .expect_err("an uncommitted hard link must fail closed");
10472        assert!(matches!(
10473            error,
10474            FolderbaseCaptureError::CaptureStateChanged(path)
10475                if path == Path::new("active.bin")
10476        ));
10477        assert_eq!(
10478            local_head(root.path())
10479                .expect("restored Local Head remains")
10480                .version_id,
10481            restored.version_id()
10482        );
10483    }
10484
10485    #[test]
10486    fn extra_hard_link_after_restored_object_bytes_read_fails_without_head_movement() {
10487        let root = folderbase();
10488        let store = FolderbaseVersionStore::open(root.path()).expect("open");
10489        store
10490            .seal_capture(store.plan_capture().expect("genesis"))
10491            .expect("genesis");
10492        fs::remove_file(root.path().join("active.bin")).expect("delete");
10493        store
10494            .seal_capture(store.plan_capture().expect("deletion"))
10495            .expect("deletion");
10496        let restored = store
10497            .restore_tombstone("active.bin")
10498            .expect("restore with retained authority");
10499        let plan = store.plan_capture().expect("authority-aware plan");
10500
10501        let error = store
10502            .seal_capture_with_hook(plan, |checkpoint| {
10503                if checkpoint == &CaptureCheckpoint::AfterObjectBytesRead("active.bin".to_owned()) {
10504                    fs::hard_link(
10505                        root.path().join("active.bin"),
10506                        root.path().join("unapproved-after-read-link.bin"),
10507                    )
10508                    .expect("concurrent extra hard link after read");
10509                }
10510            })
10511            .expect_err("an uncommitted hard link after read must fail closed");
10512        assert!(matches!(
10513            error,
10514            FolderbaseCaptureError::CaptureStateChanged(path)
10515                if path == Path::new("active.bin")
10516        ));
10517        assert_eq!(
10518            local_head(root.path())
10519                .expect("restored Local Head remains")
10520                .version_id,
10521            restored.version_id()
10522        );
10523    }
10524
10525    #[test]
10526    fn same_count_authority_set_swap_before_byte_read_fails_closed() {
10527        let root = folderbase();
10528        let store = FolderbaseVersionStore::open(root.path()).expect("open");
10529        store
10530            .seal_capture(store.plan_capture().expect("genesis"))
10531            .expect("genesis");
10532        fs::remove_file(root.path().join("active.bin")).expect("delete");
10533        store
10534            .seal_capture(store.plan_capture().expect("deletion"))
10535            .expect("deletion");
10536        store
10537            .restore_tombstone("active.bin")
10538            .expect("restore with retained authority");
10539        fs::write(
10540            root.path().join("active.bin"),
10541            b"authority-bearing workspace edit",
10542        )
10543        .expect("same-inode edit requiring a new capture");
10544        let plan = store.plan_capture().expect("authority-aware plan");
10545        let state = FolderbaseState::open(root.path()).expect("state");
10546        let completion = read_restore_completion_receipt(&state)
10547            .expect("completion")
10548            .expect("completed restore");
10549        let original_stage = root
10550            .path()
10551            .join(restore_stage_path(&completion.transaction));
10552        let original_receipt = root.path().join(restore_authority_record_path(
10553            &completion.transaction.transaction_id,
10554        ));
10555
10556        let error = store
10557            .seal_capture_with_hook(plan, |checkpoint| {
10558                if checkpoint == &CaptureCheckpoint::BeforeObjectBytesRead("active.bin".to_owned())
10559                {
10560                    fs::remove_file(&original_stage).expect("retire original stage");
10561                    fs::remove_file(&original_receipt).expect("retire original receipt");
10562                    let mut replacement = completion.transaction.clone();
10563                    replacement.transaction_id = format!("fbrestore_{}", Uuid::now_v7());
10564                    fs::create_dir(
10565                        root.path()
10566                            .join(restore_transaction_directory(&replacement)),
10567                    )
10568                    .expect("replacement authority directory");
10569                    fs::hard_link(
10570                        root.path().join("active.bin"),
10571                        root.path().join(restore_stage_path(&replacement)),
10572                    )
10573                    .expect("same-count replacement stage");
10574                    write_restore_authority_record(
10575                        &state,
10576                        &replacement,
10577                        &completion.published_identity_sha256,
10578                    )
10579                    .expect("replacement authority receipt");
10580                }
10581            })
10582            .expect_err("an exact authority-set swap must fail closed");
10583        assert!(matches!(
10584            error,
10585            FolderbaseCaptureError::CaptureStateChanged(path)
10586                if path == Path::new("active.bin")
10587        ));
10588    }
10589
10590    #[test]
10591    fn same_count_authority_set_swap_after_byte_read_fails_without_head_movement() {
10592        let root = folderbase();
10593        let store = FolderbaseVersionStore::open(root.path()).expect("open");
10594        store
10595            .seal_capture(store.plan_capture().expect("genesis"))
10596            .expect("genesis");
10597        fs::remove_file(root.path().join("active.bin")).expect("delete");
10598        store
10599            .seal_capture(store.plan_capture().expect("deletion"))
10600            .expect("deletion");
10601        let restored = store
10602            .restore_tombstone("active.bin")
10603            .expect("restore with retained authority");
10604        fs::write(
10605            root.path().join("active.bin"),
10606            b"authority-bearing workspace edit",
10607        )
10608        .expect("same-inode edit requiring a new capture");
10609        let plan = store.plan_capture().expect("authority-aware plan");
10610        let state = FolderbaseState::open(root.path()).expect("state");
10611        let completion = read_restore_completion_receipt(&state)
10612            .expect("completion")
10613            .expect("completed restore");
10614        let original_stage = root
10615            .path()
10616            .join(restore_stage_path(&completion.transaction));
10617        let original_receipt = root.path().join(restore_authority_record_path(
10618            &completion.transaction.transaction_id,
10619        ));
10620
10621        let error = store
10622            .seal_capture_with_hook(plan, |checkpoint| {
10623                if checkpoint == &CaptureCheckpoint::AfterObjectBytesRead("active.bin".to_owned()) {
10624                    fs::remove_file(&original_stage).expect("retire original stage");
10625                    fs::remove_file(&original_receipt).expect("retire original receipt");
10626                    let mut replacement = completion.transaction.clone();
10627                    replacement.transaction_id = format!("fbrestore_{}", Uuid::now_v7());
10628                    fs::create_dir(
10629                        root.path()
10630                            .join(restore_transaction_directory(&replacement)),
10631                    )
10632                    .expect("replacement authority directory");
10633                    fs::hard_link(
10634                        root.path().join("active.bin"),
10635                        root.path().join(restore_stage_path(&replacement)),
10636                    )
10637                    .expect("same-count replacement stage");
10638                    write_restore_authority_record(
10639                        &state,
10640                        &replacement,
10641                        &completion.published_identity_sha256,
10642                    )
10643                    .expect("replacement authority receipt");
10644                }
10645            })
10646            .expect_err("a post-read exact authority-set swap must fail closed");
10647        assert!(matches!(
10648            error,
10649            FolderbaseCaptureError::CaptureStateChanged(path)
10650                if path == Path::new("active.bin")
10651        ));
10652        assert_eq!(
10653            local_head(root.path())
10654                .expect("restored Local Head remains")
10655                .version_id,
10656            restored.version_id()
10657        );
10658    }
10659
10660    #[cfg(unix)]
10661    #[test]
10662    fn planning_restored_unreadable_sparse_file_is_metadata_only() {
10663        use std::os::unix::fs::PermissionsExt;
10664
10665        const SPARSE_BYTES: u64 = 10 * 1024 * 1024 * 1024;
10666
10667        let root = folderbase();
10668        let store = FolderbaseVersionStore::open(root.path()).expect("open");
10669        store
10670            .seal_capture(store.plan_capture().expect("genesis"))
10671            .expect("genesis");
10672        fs::remove_file(root.path().join("active.bin")).expect("delete");
10673        store
10674            .seal_capture(store.plan_capture().expect("deletion"))
10675            .expect("deletion");
10676        store
10677            .restore_tombstone("active.bin")
10678            .expect("restore with retained authority");
10679
10680        let workspace = root.path().join("active.bin");
10681        fs::OpenOptions::new()
10682            .write(true)
10683            .open(&workspace)
10684            .expect("open restored file before removing read access")
10685            .set_len(SPARSE_BYTES)
10686            .expect("expand restored inode sparsely");
10687        fs::set_permissions(&workspace, fs::Permissions::from_mode(0o000))
10688            .expect("remove all data access from restored inode");
10689
10690        let plan = store
10691            .plan_capture()
10692            .expect("capture planning must inspect metadata without opening content");
10693        let entry = plan
10694            .entries()
10695            .iter()
10696            .find(|entry| entry.path() == "active.bin")
10697            .expect("planned restored file");
10698        assert_eq!(entry.bytes(), Some(SPARSE_BYTES));
10699        assert!(
10700            !entry.link_commitment().is_legacy_default(),
10701            "metadata-only planning must still bind the retained restore authority"
10702        );
10703
10704        fs::set_permissions(&workspace, fs::Permissions::from_mode(0o600))
10705            .expect("restore cleanup permissions");
10706    }
10707
10708    #[test]
10709    fn authority_bearing_capture_journal_recovers_with_exact_link_commitment() {
10710        let root = folderbase();
10711        let store = FolderbaseVersionStore::open(root.path()).expect("open");
10712        store
10713            .seal_capture(store.plan_capture().expect("genesis"))
10714            .expect("genesis");
10715        fs::remove_file(root.path().join("active.bin")).expect("delete");
10716        store
10717            .seal_capture(store.plan_capture().expect("deletion"))
10718            .expect("deletion");
10719        store
10720            .restore_tombstone("active.bin")
10721            .expect("restore with retained authority");
10722        fs::write(
10723            root.path().join("active.bin"),
10724            b"authority-bearing journal recovery edit",
10725        )
10726        .expect("same-inode edit requiring a new capture");
10727        let plan = store.plan_capture().expect("authority-aware plan");
10728        let interrupted = catch_unwind(AssertUnwindSafe(|| {
10729            store.seal_capture_with_hook(plan, |checkpoint| {
10730                if checkpoint == &CaptureCheckpoint::JournalDurable {
10731                    panic!("simulated crash after authority-bearing journal");
10732                }
10733            })
10734        }));
10735        assert!(interrupted.is_err());
10736        let raw = fs::read(root.path().join(ACTIVE_CAPTURE_TRANSACTION_PATH))
10737            .expect("durable active journal");
10738        let wire: serde_json::Value = serde_json::from_slice(&raw).expect("journal JSON");
10739        let assignment = wire["assignments"]
10740            .as_array()
10741            .expect("assignments")
10742            .iter()
10743            .find(|assignment| assignment["path"] == "active.bin")
10744            .expect("restored assignment");
10745        assert_eq!(assignment["link_commitment"]["expected_live_link_count"], 2);
10746        assert_eq!(
10747            assignment["link_commitment"]["authorities"]
10748                .as_array()
10749                .expect("authority set")
10750                .len(),
10751            1
10752        );
10753        drop(store);
10754
10755        let reopened = FolderbaseVersionStore::open(root.path()).expect("fresh-process reopen");
10756        reopened
10757            .seal_capture(reopened.plan_capture().expect("retry plan"))
10758            .expect("recover authority-bearing journal");
10759        assert!(active_transaction(root.path()).is_none());
10760    }
10761
10762    #[test]
10763    fn abandoned_attempt_removes_only_intent_and_reuses_safe_content_addressed_orphans() {
10764        let root = folderbase();
10765        let store = FolderbaseVersionStore::open(root.path()).expect("open");
10766        let plan = store.plan_capture().expect("plan");
10767        let interrupted = catch_unwind(AssertUnwindSafe(|| {
10768            store.seal_capture_with_hook(plan, |checkpoint| {
10769                if checkpoint == &CaptureCheckpoint::ObjectWritesDurable {
10770                    panic!("crash after immutable object writes");
10771                }
10772            })
10773        }));
10774        assert!(interrupted.is_err());
10775        let abandoned = active_transaction(root.path())
10776            .expect("abandoned intent")
10777            .target_version_id;
10778        fs::write(root.path().join("active.bin"), b"newer opaque bytes").expect("new state");
10779        let sealed = store
10780            .seal_capture(store.plan_capture().expect("fresh plan"))
10781            .expect("fresh capture cleans stale intent");
10782        assert_ne!(sealed.version_id(), abandoned);
10783        assert!(active_transaction(root.path()).is_none());
10784        assert!(
10785            read_regular_beneath(
10786                root.path(),
10787                &folderbase_version_relative_path(&abandoned),
10788                MAX_ENCODED_VERSION_BYTES
10789            )
10790            .unwrap()
10791            .is_none(),
10792            "an uncommitted Folderbase Version never became visible"
10793        );
10794        assert!(
10795            fs::read_dir(root.path().join(".folderbase/versions/blobs/sha256"))
10796                .unwrap()
10797                .count()
10798                >= 2,
10799            "verified content-addressed orphans are safe and reusable"
10800        );
10801    }
10802
10803    #[test]
10804    fn missing_physical_identity_rebuilds_evidence_without_splitting_logical_identity() {
10805        let root = folderbase();
10806        let store = FolderbaseVersionStore::open(root.path()).expect("open");
10807        let genesis = store
10808            .seal_capture(store.plan_capture().expect("genesis plan"))
10809            .expect("genesis");
10810        let version = store.read_version(genesis.version_id()).expect("version");
10811        let prior = version
10812            .lookup_binding("active.bin")
10813            .expect("active binding");
10814        let object_id = prior.object_id().to_owned();
10815        let object_version_id = prior
10816            .object_version_id()
10817            .expect("Object Version")
10818            .to_owned();
10819        fs::remove_file(root.path().join(capture_identity_relative_path(&object_id)))
10820            .expect("remove local identity evidence");
10821
10822        let repaired = store
10823            .seal_capture(store.plan_capture().expect("next plan"))
10824            .expect("same-path same-kind continuity");
10825        assert!(repaired.created());
10826        let current = store
10827            .read_version(repaired.version_id())
10828            .expect("repaired version");
10829        let current = current
10830            .lookup_binding("active.bin")
10831            .expect("active binding");
10832        assert_eq!(current.object_id(), object_id);
10833        assert_eq!(
10834            current.object_version_id(),
10835            Some(object_version_id.as_str())
10836        );
10837        assert!(
10838            root.path()
10839                .join(capture_identity_relative_path(&object_id))
10840                .is_file()
10841        );
10842    }
10843
10844    fn assert_same_kind_replacement_after_head_preserves_logical_identity(start: Option<&Barrier>) {
10845        let root = folderbase();
10846        let store = FolderbaseVersionStore::open(root.path()).expect("open");
10847        let plan = store.plan_capture().expect("plan");
10848        if let Some(start) = start {
10849            start.wait();
10850        }
10851        let mut head_replaced_count = 0;
10852        let mut replacement_identities = None;
10853        let interrupted = catch_unwind(AssertUnwindSafe(|| {
10854            store.seal_capture_with_hook(plan, |checkpoint| {
10855                if checkpoint == &CaptureCheckpoint::HeadReplaced {
10856                    head_replaced_count += 1;
10857                    let active_path = root.path().join("active.bin");
10858                    let captured = File::open(&active_path).expect("open captured file");
10859                    let captured_identity = CaptureMetadataFingerprint::from_std_file(&captured)
10860                        .expect("captured fingerprint")
10861                        .physical_identity;
10862                    fs::remove_file(&active_path).expect("remove captured file");
10863                    fs::write(&active_path, b"same path, replacement identity")
10864                        .expect("replace captured file");
10865                    let replacement = File::open(&active_path).expect("open replacement file");
10866                    let replacement_identity =
10867                        CaptureMetadataFingerprint::from_std_file(&replacement)
10868                            .expect("replacement fingerprint")
10869                            .physical_identity;
10870                    replacement_identities = Some((captured_identity, replacement_identity));
10871                    drop(captured);
10872                    panic!("stop before identity projection");
10873                }
10874            })
10875        }));
10876        assert!(interrupted.is_err());
10877        assert_eq!(
10878            head_replaced_count, 1,
10879            "one per-call fault hook must observe Head replacement exactly once"
10880        );
10881        let (captured_identity, replacement_identity) =
10882            replacement_identities.expect("fault hook records both physical identities");
10883        assert_ne!(
10884            captured_identity, replacement_identity,
10885            "the fault fixture must create a provably different filesystem object"
10886        );
10887
10888        let reopened = FolderbaseVersionStore::open(root.path()).expect("reopen");
10889        let captured_head = reopened
10890            .plan_capture()
10891            .expect("replacement plan")
10892            .current_local_head()
10893            .expect("captured Head")
10894            .version_id()
10895            .to_owned();
10896        let captured = reopened
10897            .read_version(&captured_head)
10898            .expect("captured version");
10899        let captured_binding = captured
10900            .lookup_binding("active.bin")
10901            .expect("captured binding");
10902        let captured_object_id = captured_binding.object_id().to_owned();
10903        let captured_object_version_id = captured_binding
10904            .object_version_id()
10905            .expect("captured Object Version")
10906            .to_owned();
10907        let updated = reopened
10908            .seal_capture(reopened.plan_capture().expect("replacement plan"))
10909            .expect("same-kind replacement remains the same Knowledge Object");
10910        let current = reopened
10911            .read_version(updated.version_id())
10912            .expect("replacement version");
10913        let current_binding = current
10914            .lookup_binding("active.bin")
10915            .expect("replacement binding");
10916        assert_eq!(current.parents(), &[captured_head]);
10917        assert_eq!(current_binding.object_id(), captured_object_id);
10918        assert_ne!(
10919            current_binding.object_version_id(),
10920            Some(captured_object_version_id.as_str())
10921        );
10922        assert!(current.tombstones().is_empty());
10923    }
10924
10925    #[test]
10926    fn replacement_after_head_and_before_identity_projection_preserves_logical_identity() {
10927        assert_same_kind_replacement_after_head_preserves_logical_identity(None);
10928    }
10929
10930    #[test]
10931    fn post_head_replacement_faults_remain_isolated_under_parallel_stress() {
10932        const WORKERS: usize = 8;
10933
10934        let start = Arc::new(Barrier::new(WORKERS));
10935        thread::scope(|scope| {
10936            let workers = (0..WORKERS)
10937                .map(|_| {
10938                    let start = Arc::clone(&start);
10939                    scope.spawn(move || {
10940                        assert_same_kind_replacement_after_head_preserves_logical_identity(Some(
10941                            &start,
10942                        ));
10943                    })
10944                })
10945                .collect::<Vec<_>>();
10946            for worker in workers {
10947                worker.join().expect("parallel seal worker");
10948            }
10949        });
10950    }
10951
10952    #[test]
10953    fn post_head_journal_observation_tamper_never_blesses_a_replacement_identity() {
10954        let root = folderbase();
10955        let store = FolderbaseVersionStore::open(root.path()).expect("open");
10956        let plan = store.plan_capture().expect("plan");
10957        let interrupted = catch_unwind(AssertUnwindSafe(|| {
10958            store.seal_capture_with_hook(plan, |checkpoint| {
10959                if checkpoint == &CaptureCheckpoint::HeadReplaced {
10960                    let active_path = root.path().join("active.bin");
10961                    let sealed_bytes = fs::read(&active_path).expect("sealed bytes");
10962                    fs::remove_file(&active_path).expect("remove captured identity");
10963                    fs::write(&active_path, sealed_bytes).expect("same-byte replacement");
10964
10965                    let replacement = File::open(&active_path).expect("replacement file");
10966                    let replacement_observed =
10967                        CaptureMetadataFingerprint::from_std_file(&replacement)
10968                            .expect("replacement fingerprint");
10969                    let mut transaction = active_transaction(root.path()).expect("active journal");
10970                    transaction
10971                        .assignments
10972                        .iter_mut()
10973                        .find(|assignment| assignment.path == "active.bin")
10974                        .expect("active assignment")
10975                        .observed = replacement_observed;
10976                    FolderbaseState::open(root.path())
10977                        .expect("state")
10978                        .replace(
10979                            Path::new(ACTIVE_CAPTURE_TRANSACTION_PATH),
10980                            &json_bytes(&transaction).unwrap(),
10981                        )
10982                        .expect("tamper post-Head journal");
10983                    panic!("stop before identity projection");
10984                }
10985            })
10986        }));
10987        assert!(interrupted.is_err());
10988
10989        let reopened = FolderbaseVersionStore::open(root.path()).expect("reopen");
10990        let error = reopened
10991            .seal_capture(reopened.plan_capture().expect("replacement plan"))
10992            .expect_err("mutable journal evidence must not authorize identity continuity");
10993        assert!(matches!(
10994            error,
10995            FolderbaseCaptureError::InvalidCaptureTransaction(_)
10996        ));
10997    }
10998
10999    #[test]
11000    fn post_head_committed_parent_and_time_tamper_never_recovers_as_the_journal_target() {
11001        let root = folderbase();
11002        let store = FolderbaseVersionStore::open(root.path()).expect("open");
11003        let plan = store.plan_capture().expect("plan");
11004        let interrupted = catch_unwind(AssertUnwindSafe(|| {
11005            store.seal_capture_with_hook(plan, |checkpoint| {
11006                if checkpoint == &CaptureCheckpoint::HeadReplaced {
11007                    let state = FolderbaseState::open(root.path()).expect("state");
11008                    let transaction = active_transaction(root.path()).expect("active journal");
11009                    let relative = folderbase_version_relative_path(&transaction.target_version_id);
11010                    let encoded = state
11011                        .read_bounded(&relative, MAX_ENCODED_VERSION_BYTES)
11012                        .expect("read version")
11013                        .expect("committed version");
11014                    let mut wire: serde_json::Value =
11015                        serde_json::from_slice(&encoded).expect("version JSON");
11016                    wire["created_at"] =
11017                        serde_json::Value::String("2026-01-01T00:00:00Z".to_owned());
11018                    wire["parents"] =
11019                        serde_json::json!(["fbversion_019faf78-b120-73c9-a6d4-07112d2517ba"]);
11020                    let tampered = serde_json::to_vec(&wire).expect("tampered version");
11021                    let decoded = FolderbaseVersion::decode_bounded(tampered.as_slice())
11022                        .expect("well-formed tampered version");
11023                    state
11024                        .replace(&relative, &tampered)
11025                        .expect("replace committed bytes");
11026
11027                    let mut head = local_head(root.path()).expect("Local Head");
11028                    head.version_sha256 = decoded.canonical_digest().expect("tampered digest");
11029                    state
11030                        .replace(Path::new(LOCAL_HEAD_PATH), &json_bytes(&head).unwrap())
11031                        .expect("bind Head to tampered version");
11032                    panic!("stop before committed recovery");
11033                }
11034            })
11035        }));
11036        assert!(interrupted.is_err());
11037
11038        let reopened = FolderbaseVersionStore::open(root.path()).expect("reopen");
11039        let error = reopened
11040            .seal_capture(reopened.plan_capture().expect("same live plan"))
11041            .expect_err("committed lineage and time must match the anchored journal");
11042        assert!(matches!(
11043            error,
11044            FolderbaseCaptureError::InvalidCaptureTransaction(_)
11045        ));
11046    }
11047
11048    #[test]
11049    fn truncated_active_journal_cannot_seal_a_subset_of_the_plan() {
11050        let root = folderbase();
11051        let store = FolderbaseVersionStore::open(root.path()).expect("open");
11052        let plan = store.plan_capture().expect("plan");
11053        let interrupted = catch_unwind(AssertUnwindSafe(|| {
11054            store.seal_capture_with_hook(plan, |checkpoint| {
11055                if checkpoint == &CaptureCheckpoint::JournalDurable {
11056                    panic!("stop after journal");
11057                }
11058            })
11059        }));
11060        assert!(interrupted.is_err());
11061
11062        let mut transaction = active_transaction(root.path()).expect("active journal");
11063        transaction.assignments.pop().expect("trailing assignment");
11064        FolderbaseState::open(root.path())
11065            .expect("state")
11066            .replace(
11067                Path::new(ACTIVE_CAPTURE_TRANSACTION_PATH),
11068                &json_bytes(&transaction).unwrap(),
11069            )
11070            .expect("tamper journal");
11071
11072        let error = store
11073            .seal_capture(store.plan_capture().expect("same plan"))
11074            .expect_err("subset journal must fail closed");
11075        assert!(matches!(
11076            error,
11077            FolderbaseCaptureError::InvalidCaptureTransaction(_)
11078        ));
11079        assert!(local_head(root.path()).is_none());
11080    }
11081
11082    #[test]
11083    fn tampered_reused_assignment_cannot_rewrite_prior_identity_lineage() {
11084        let root = folderbase();
11085        let store = FolderbaseVersionStore::open(root.path()).expect("open");
11086        let genesis = store
11087            .seal_capture(store.plan_capture().expect("genesis plan"))
11088            .expect("genesis");
11089        fs::write(root.path().join("active.bin"), b"same object, new bytes").expect("edit");
11090        let plan = store.plan_capture().expect("update plan");
11091        let interrupted = catch_unwind(AssertUnwindSafe(|| {
11092            store.seal_capture_with_hook(plan, |checkpoint| {
11093                if checkpoint == &CaptureCheckpoint::JournalDurable {
11094                    panic!("stop after journal");
11095                }
11096            })
11097        }));
11098        assert!(interrupted.is_err());
11099
11100        let mut transaction = active_transaction(root.path()).expect("active journal");
11101        let assignment = transaction
11102            .assignments
11103            .iter_mut()
11104            .find(|assignment| assignment.path == "active.bin")
11105            .expect("active assignment");
11106        assignment.object_id = ObjectId::new().to_string();
11107        FolderbaseState::open(root.path())
11108            .expect("state")
11109            .replace(
11110                Path::new(ACTIVE_CAPTURE_TRANSACTION_PATH),
11111                &json_bytes(&transaction).unwrap(),
11112            )
11113            .expect("tamper journal lineage");
11114
11115        let error = store
11116            .seal_capture(store.plan_capture().expect("same update plan"))
11117            .expect_err("lineage rewrite must fail closed");
11118        assert!(matches!(
11119            error,
11120            FolderbaseCaptureError::InvalidCaptureTransaction(_)
11121        ));
11122        assert_eq!(
11123            local_head(root.path()).expect("prior Head").version_id,
11124            genesis.version_id()
11125        );
11126    }
11127
11128    #[test]
11129    fn active_journal_write_and_restart_use_one_explicit_byte_bound() {
11130        let root = folderbase();
11131        let store = FolderbaseVersionStore::open(root.path()).expect("open");
11132        let plan = store.plan_capture().expect("plan");
11133        let transaction = assign_capture_transaction(
11134            &plan,
11135            &capture_plan_sha256(&plan).expect("plan digest"),
11136            None,
11137        )
11138        .expect("assignment");
11139        let encoded = json_bytes(&transaction).expect("journal bytes");
11140
11141        assert_eq!(
11142            encode_active_transaction(&transaction, encoded.len() as u64)
11143                .expect("exact bound accepted"),
11144            encoded
11145        );
11146        assert!(matches!(
11147            encode_active_transaction(&transaction, encoded.len() as u64 - 1),
11148            Err(FolderbaseCaptureError::InvalidCaptureTransaction(message))
11149                if message.contains("bounded record limit")
11150        ));
11151        assert_eq!(
11152            MAX_CAPTURE_TRANSACTION_BYTES, MAX_ENCODED_VERSION_BYTES,
11153            "writer and restart reader intentionally share one declared bound"
11154        );
11155    }
11156
11157    #[test]
11158    fn active_journal_bounds_assignments_and_tombstones_as_one_version_entry_set() {
11159        let root = folderbase();
11160        let store = FolderbaseVersionStore::open(root.path()).expect("open");
11161        let plan = store.plan_capture().expect("plan");
11162        let mut transaction = assign_capture_transaction(
11163            &plan,
11164            &capture_plan_sha256(&plan).expect("plan digest"),
11165            None,
11166        )
11167        .expect("assignment");
11168        transaction.target_tombstones = (0..crate::folderbase_version::MAX_VERSION_ENTRIES)
11169            .map(|index| {
11170                Tombstone::from_verified_producer(
11171                    format!("deleted/{index:05}.bin"),
11172                    ObjectId::new().to_string(),
11173                    DeletedKind::RegularFile,
11174                    Some(VersionId::new().to_string()),
11175                )
11176            })
11177            .collect();
11178
11179        let error = validate_transaction(&store, &transaction)
11180            .expect_err("journal aggregate must fit one bounded Folderbase Version");
11181        assert!(matches!(
11182            error,
11183            FolderbaseCaptureError::InvalidCaptureTransaction(message)
11184                if message.contains("aggregate")
11185        ));
11186    }
11187
11188    #[test]
11189    fn future_version_envelope_is_bounded_before_journal_or_immutable_writes() {
11190        let root = folderbase();
11191        let store = FolderbaseVersionStore::open(root.path()).expect("open");
11192        let plan = store.plan_capture().expect("plan");
11193        let error = store
11194            .seal_capture_with_hook_and_limits(plan, |_| {}, MAX_CAPTURE_TRANSACTION_BYTES, 1)
11195            .expect_err("future version envelope must be preflighted");
11196        assert!(matches!(
11197            error,
11198            FolderbaseCaptureError::InvalidCaptureTransaction(message)
11199                if message.contains("Folderbase Version envelope")
11200        ));
11201        assert!(active_transaction(root.path()).is_none());
11202        assert!(local_head(root.path()).is_none());
11203        assert_eq!(
11204            fs::read_dir(root.path().join(".folderbase/versions/blobs/sha256"))
11205                .expect("blob directory")
11206                .count(),
11207            0,
11208            "preflight refusal occurs before immutable content writes"
11209        );
11210    }
11211
11212    #[test]
11213    fn repeat_capture_stops_at_the_approved_length_without_moving_local_head() {
11214        let root = folderbase();
11215        let store = FolderbaseVersionStore::open(root.path()).expect("open");
11216        let genesis = store
11217            .seal_capture(store.plan_capture().expect("genesis plan"))
11218            .expect("genesis");
11219        let repeat = store.plan_capture().expect("repeat plan");
11220        let mut grew_source = false;
11221
11222        let error = store
11223            .seal_capture_with_hook(repeat, |checkpoint| {
11224                if !grew_source
11225                    && checkpoint
11226                        == &CaptureCheckpoint::BeforeObjectBytesRead("active.bin".to_owned())
11227                {
11228                    grew_source = true;
11229                    use std::io::Write;
11230
11231                    fs::OpenOptions::new()
11232                        .append(true)
11233                        .open(root.path().join("active.bin"))
11234                        .expect("open growing regular source")
11235                        .write_all(b"x")
11236                        .expect("grow beyond approved length");
11237                }
11238            })
11239            .expect_err("repeat capture must reject growth beyond the approved length");
11240
11241        assert!(
11242            grew_source,
11243            "repeat verification must expose its byte-read seam"
11244        );
11245        assert!(matches!(
11246            error,
11247            FolderbaseCaptureError::CaptureStateChanged(path)
11248                if path == Path::new("active.bin")
11249        ));
11250        assert_eq!(
11251            local_head(root.path())
11252                .expect("prior Local Head")
11253                .version_id,
11254            genesis.version_id()
11255        );
11256        assert!(
11257            active_transaction(root.path()).is_none(),
11258            "repeat verification must fail before assigning a new transaction"
11259        );
11260    }
11261}