Skip to main content

folderbase_core/
folderbase_seal.rs

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