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