Skip to main content

folderbase_core/
protocol_upgrade.rs

1//! Explicit, reviewable transition from legacy live-root semantics to 0.5.
2
3use std::{
4    io::Read,
5    path::{Path, PathBuf},
6};
7
8use serde::{Deserialize, Serialize};
9use serde_json::{Value, json};
10use sha2::{Digest, Sha256};
11use uuid::Uuid;
12
13use crate::{
14    FolderbaseError, FolderbaseVersionStore, LocalVersionStore, MAX_FOLDERBASEIGNORE_BYTES, Result,
15    folderbase_restore_authority::{stable_file_identity_sha256, stable_file_link_count},
16    folderbase_state::FolderbaseState,
17    migration::durable_migration_execution_is_terminal,
18    root_attestation::{
19        DEFAULT_V05_CAPTURE_IGNORE_RULES, MAX_FOLDERBASE_MANIFEST_BYTES, ManifestProtocolProfile,
20        PROTOCOL_UPGRADE_RECEIPT_FIELD, PROTOCOL_UPGRADE_RECEIPT_FORMAT,
21        attest_folderbase_root_with_profile,
22        attest_folderbase_root_with_profile_allowing_upgrade_recovery,
23        decode_manifest_protocol_profile,
24    },
25};
26
27const MANIFEST_PATH: &str = ".folderbase/manifest.json";
28const IGNORE_POLICY_PATH: &str = ".folderbaseignore";
29const ACTIVE_CAPTURE_PATH: &str =
30    ".folderbase/transactions/folderbase-version-captures/active.json";
31const ACTIVE_RESTORE_PATH: &str =
32    ".folderbase/transactions/folderbase-version-restores/active.json";
33const RESTORE_CLEANUP_PATH: &str =
34    ".folderbase/transactions/folderbase-version-restores/cleanup.json";
35const ACTIVE_REORGANIZATION_PATH: &str = ".folderbase/reorganizations/active.json";
36const MIGRATIONS_PATH: &str = ".folderbase/migrations";
37const UPGRADE_INTENT_DIRECTORY: &str = "transactions/protocol-upgrades";
38const UPGRADE_INTENT_PATH: &str = "transactions/protocol-upgrades/active.json";
39const UPGRADE_INTENT_FORMAT: &str = "folderbase-protocol-upgrade-intent-v2";
40const MAX_PENDING_RECORD_BYTES: u64 = 16 * 1024 * 1024;
41// The intent embeds two manifests as JSON strings. Each manifest can require up
42// to twice its original bytes when quotes and escapes are encoded, while the
43// fixed record fields need only a small, closed amount of additional space.
44const MAX_PROTOCOL_UPGRADE_INTENT_BYTES: u64 = MAX_FOLDERBASE_MANIFEST_BYTES * 4 + 64 * 1024;
45const MAX_MIGRATION_DIRECTORIES: usize = 16_384;
46const MAX_TRANSACTION_ENTRIES: usize = 16_384;
47
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub(crate) enum PendingWork {
50    Capture,
51    TombstoneRestore,
52    TombstoneRestoreCleanup,
53    Reorganization,
54    LocalVersionIntent(String),
55    Migration(String),
56}
57
58impl PendingWork {
59    pub(crate) fn description(&self) -> String {
60        match self {
61            Self::Capture => "Folderbase Version capture".to_owned(),
62            Self::TombstoneRestore => "Tombstone restore".to_owned(),
63            Self::TombstoneRestoreCleanup => "Tombstone restore cleanup".to_owned(),
64            Self::Reorganization => "Folderbase reorganization".to_owned(),
65            Self::LocalVersionIntent(name) => {
66                format!("local-version transaction `{name}`")
67            }
68            Self::Migration(id) => format!("migration `{id}`"),
69        }
70    }
71
72    fn protocol_upgrade_label(&self) -> &'static str {
73        match self {
74            Self::Capture => "Folderbase Version capture",
75            Self::TombstoneRestore => "Tombstone restore",
76            Self::TombstoneRestoreCleanup => "Tombstone restore cleanup",
77            Self::Reorganization => "Folderbase reorganization",
78            Self::LocalVersionIntent(_) => "Folderbase local-version transaction",
79            Self::Migration(_) => "Folderbase migration",
80        }
81    }
82}
83
84#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
85#[serde(deny_unknown_fields)]
86pub struct ProtocolUpgradePlanDigest {
87    algorithm: String,
88    digest: String,
89}
90
91impl ProtocolUpgradePlanDigest {
92    pub fn parse_sha256(digest: impl Into<String>) -> Result<Self> {
93        let digest = digest.into();
94        if digest.len() != 64
95            || !digest
96                .bytes()
97                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
98        {
99            return Err(FolderbaseError::InvalidProtocolUpgradePlanDigest);
100        }
101        Ok(Self {
102            algorithm: "sha256".to_owned(),
103            digest,
104        })
105    }
106
107    pub fn algorithm(&self) -> &str {
108        &self.algorithm
109    }
110
111    pub fn digest(&self) -> &str {
112        &self.digest
113    }
114}
115
116#[derive(Debug, Serialize)]
117pub struct ProtocolUpgradePlan {
118    root: PathBuf,
119    folderbase_id: String,
120    from_protocol_version: String,
121    to_protocol_version: String,
122    changed_paths: Vec<PathBuf>,
123    plan_digest: ProtocolUpgradePlanDigest,
124    #[serde(skip_serializing)]
125    upgraded_manifest: Vec<u8>,
126    #[serde(skip_serializing)]
127    attested_manifest: Vec<u8>,
128    #[serde(skip_serializing)]
129    attested_manifest_sha256: String,
130    #[serde(skip_serializing)]
131    root_instance_sha256: String,
132    #[serde(skip_serializing)]
133    attested_ignore_snapshot: Option<IgnorePolicySnapshot>,
134    #[serde(skip_serializing)]
135    exchange_owner: Option<String>,
136    #[serde(skip_serializing)]
137    already_applied: bool,
138}
139
140impl ProtocolUpgradePlan {
141    pub fn root(&self) -> &Path {
142        &self.root
143    }
144
145    pub fn plan_digest(&self) -> &ProtocolUpgradePlanDigest {
146        &self.plan_digest
147    }
148}
149
150#[derive(Debug, Serialize)]
151pub struct ProtocolUpgradeResult {
152    pub root: PathBuf,
153    pub folderbase_id: String,
154    pub from_protocol_version: String,
155    pub to_protocol_version: String,
156    pub changed_paths: Vec<PathBuf>,
157    pub applied_plan_digest: ProtocolUpgradePlanDigest,
158}
159
160#[derive(Debug, Clone, Serialize, Deserialize)]
161#[serde(deny_unknown_fields)]
162struct ProtocolUpgradeReceipt {
163    format: String,
164    from_protocol_version: String,
165    target_manifest_without_receipt_sha256: String,
166    plan_digest: ProtocolUpgradePlanDigest,
167}
168
169#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
170#[serde(tag = "presence", rename_all = "snake_case", deny_unknown_fields)]
171enum IgnorePolicySnapshot {
172    Absent,
173    Present {
174        kind: String,
175        bytes: u64,
176        sha256: String,
177        physical_identity_sha256: String,
178        link_count: u64,
179    },
180}
181
182impl IgnorePolicySnapshot {
183    fn binding_sha256(&self) -> Result<String> {
184        let encoded = serde_json::to_vec(self)
185            .map_err(|source| FolderbaseError::json(Path::new(IGNORE_POLICY_PATH), source))?;
186        let mut digest = Sha256::new();
187        digest.update(b"folderbase-protocol-upgrade-ignore-snapshot-v2\0");
188        update_bytes(&mut digest, &encoded);
189        Ok(format!("{:x}", digest.finalize()))
190    }
191}
192
193#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
194#[serde(deny_unknown_fields)]
195struct ProtocolUpgradeIntent {
196    format: String,
197    exchange_owner: String,
198    folderbase_id: String,
199    root_instance_sha256: String,
200    from_protocol_version: String,
201    to_protocol_version: String,
202    plan_digest: ProtocolUpgradePlanDigest,
203    source_manifest_sha256: String,
204    source_manifest: String,
205    target_manifest_sha256: String,
206    target_manifest: String,
207    ignore_snapshot: IgnorePolicySnapshot,
208}
209
210pub fn plan_protocol_upgrade(root: impl AsRef<Path>) -> Result<ProtocolUpgradePlan> {
211    let supplied_root = root.as_ref();
212    let (supplied_attestation, _, supplied_profile) =
213        attest_folderbase_root_with_profile_allowing_upgrade_recovery(supplied_root)
214            .map_err(|source| invalid_upgrade(supplied_root, source.to_string()))?;
215    let root = supplied_root
216        .canonicalize()
217        .map_err(|source| FolderbaseError::io(supplied_root, source))?;
218    let (attestation, _, profile) =
219        attest_folderbase_root_with_profile_allowing_upgrade_recovery(&root)
220            .map_err(|source| invalid_upgrade(&root, source.to_string()))?;
221    if supplied_attestation.folderbase_id != attestation.folderbase_id
222        || supplied_attestation.protocol_version != attestation.protocol_version
223        || supplied_attestation.manifest_sha256 != attestation.manifest_sha256
224        || supplied_attestation.root_instance_sha256 != attestation.root_instance_sha256
225        || supplied_profile != profile
226    {
227        return Err(invalid_upgrade(
228            &root,
229            "Folderbase root changed while establishing upgrade authority",
230        ));
231    }
232    let state = FolderbaseState::open_existing_read_only(&root)?;
233    state.verify_still_attached()?;
234    ensure_no_pending_transactions(&state)?;
235
236    let manifest_bytes = state
237        .read_bounded(Path::new("manifest.json"), MAX_FOLDERBASE_MANIFEST_BYTES)?
238        .ok_or_else(|| invalid_upgrade(&root, "manifest disappeared during planning"))?;
239    let observed_manifest_sha256 = format!("{:x}", Sha256::digest(&manifest_bytes));
240    if observed_manifest_sha256 != attestation.manifest_sha256 {
241        return Err(invalid_upgrade(
242            &root,
243            "manifest changed after root attestation",
244        ));
245    }
246    let (mut manifest, folderbase_id, from_protocol_version, decoded_profile) =
247        decode_manifest_protocol_profile(&manifest_bytes)
248            .map_err(|source| invalid_upgrade(&root, source.to_string()))?;
249    if decoded_profile != profile
250        || folderbase_id != attestation.folderbase_id
251        || from_protocol_version != attestation.protocol_version
252    {
253        return Err(invalid_upgrade(
254            &root,
255            "manifest profile changed during planning",
256        ));
257    }
258    let pending_intent = read_protocol_upgrade_intent(&state, &root)?;
259    if matches!(profile, ManifestProtocolProfile::OrdinaryV05 { .. }) {
260        let Some(_) = manifest.get(PROTOCOL_UPGRADE_RECEIPT_FIELD) else {
261            let mut digest = Sha256::new();
262            digest.update(b"folderbase-protocol-current-plan-v1\0");
263            update_bytes(&mut digest, folderbase_id.as_bytes());
264            update_bytes(&mut digest, attestation.root_instance_sha256.as_bytes());
265            update_bytes(&mut digest, attestation.manifest_sha256.as_bytes());
266            return Ok(ProtocolUpgradePlan {
267                root,
268                folderbase_id,
269                from_protocol_version: "0.5.0".to_owned(),
270                to_protocol_version: "0.5.0".to_owned(),
271                changed_paths: Vec::new(),
272                plan_digest: ProtocolUpgradePlanDigest {
273                    algorithm: "sha256".to_owned(),
274                    digest: format!("{:x}", digest.finalize()),
275                },
276                attested_manifest: manifest_bytes.clone(),
277                upgraded_manifest: manifest_bytes,
278                attested_manifest_sha256: attestation.manifest_sha256,
279                root_instance_sha256: attestation.root_instance_sha256,
280                attested_ignore_snapshot: None,
281                exchange_owner: None,
282                already_applied: true,
283            });
284        };
285        let receipt = decode_applied_receipt(&root, &manifest)?;
286        return Ok(ProtocolUpgradePlan {
287            root,
288            folderbase_id,
289            from_protocol_version: receipt.from_protocol_version,
290            to_protocol_version: "0.5.0".to_owned(),
291            changed_paths: vec![PathBuf::from(MANIFEST_PATH)],
292            plan_digest: receipt.plan_digest,
293            attested_manifest: manifest_bytes.clone(),
294            upgraded_manifest: manifest_bytes,
295            attested_manifest_sha256: attestation.manifest_sha256,
296            root_instance_sha256: attestation.root_instance_sha256,
297            attested_ignore_snapshot: None,
298            exchange_owner: None,
299            already_applied: true,
300        });
301    }
302    if let Some(intent) = pending_intent {
303        return plan_from_pending_intent(root, attestation, manifest_bytes, intent);
304    }
305
306    if manifest.get(PROTOCOL_UPGRADE_RECEIPT_FIELD).is_some()
307        || manifest.pointer("/policies/capture_ignore").is_some()
308    {
309        return Err(invalid_upgrade(
310            &root,
311            "legacy extension collides with reserved 0.5 protocol fields",
312        ));
313    }
314
315    let store = FolderbaseVersionStore::open(&root)
316        .map_err(|source| invalid_upgrade(&root, source.to_string()))?;
317    let capture = store
318        .plan_capture()
319        .map_err(|source| invalid_upgrade(&root, source.to_string()))?;
320    let ignore_snapshot = read_ignore_snapshot(&state, &root)?;
321    let ignore_snapshot_sha256 = ignore_snapshot.binding_sha256()?;
322    if let Some(head) = capture.current_local_head() {
323        store
324            .read_version(head.version_id())
325            .map_err(|source| invalid_upgrade(&root, source.to_string()))?;
326    }
327
328    let manifest_path = root.join(MANIFEST_PATH);
329    let root_record = manifest
330        .as_object_mut()
331        .ok_or_else(|| invalid_upgrade(&root, "manifest root must be an object"))?;
332    root_record.insert(
333        "$schema".to_owned(),
334        Value::String("https://folderbase.ai/protocol/0.5/folderbase.schema.json".to_owned()),
335    );
336    root_record.insert(
337        "protocol_version".to_owned(),
338        Value::String("0.5.0".to_owned()),
339    );
340    root_record
341        .get_mut("folderbase")
342        .and_then(Value::as_object_mut)
343        .ok_or_else(|| invalid_upgrade(&root, "folderbase must be an object"))?
344        .remove("entry");
345    let policies = root_record
346        .get_mut("policies")
347        .and_then(Value::as_object_mut)
348        .ok_or_else(|| invalid_upgrade(&root, "policies must be an object"))?;
349    policies.insert(
350        "capture_ignore".to_owned(),
351        json!({
352            "format": "folderbase-capture-ignore-v1",
353            "rules": DEFAULT_V05_CAPTURE_IGNORE_RULES
354        }),
355    );
356    let upgraded_manifest_without_receipt = serde_json::to_string_pretty(&manifest)
357        .map(|encoded| format!("{encoded}\n").into_bytes())
358        .map_err(|source| FolderbaseError::json(&manifest_path, source))?;
359    validate_generated_upgrade_manifest(&root, &upgraded_manifest_without_receipt)?;
360
361    let mut digest = Sha256::new();
362    digest.update(b"folderbase-protocol-upgrade-plan-v1\0");
363    update_bytes(&mut digest, attestation.folderbase_id.as_bytes());
364    update_bytes(&mut digest, attestation.root_instance_sha256.as_bytes());
365    update_bytes(&mut digest, attestation.manifest_sha256.as_bytes());
366    update_bytes(&mut digest, capture.ignore_policy_sha256().as_bytes());
367    update_bytes(&mut digest, ignore_snapshot_sha256.as_bytes());
368    if let Some(head) = capture.current_local_head() {
369        digest.update([1]);
370        update_bytes(&mut digest, head.version_id().as_bytes());
371        update_bytes(&mut digest, head.version_sha256().as_bytes());
372    } else {
373        digest.update([0]);
374    }
375    update_bytes(
376        &mut digest,
377        &Sha256::digest(&upgraded_manifest_without_receipt),
378    );
379    let plan_digest = ProtocolUpgradePlanDigest {
380        algorithm: "sha256".to_owned(),
381        digest: format!("{:x}", digest.finalize()),
382    };
383    let target_manifest_without_receipt_sha256 =
384        format!("{:x}", Sha256::digest(&upgraded_manifest_without_receipt));
385    manifest
386        .as_object_mut()
387        .expect("manifest object was checked")
388        .insert(
389            PROTOCOL_UPGRADE_RECEIPT_FIELD.to_owned(),
390            serde_json::to_value(ProtocolUpgradeReceipt {
391                format: PROTOCOL_UPGRADE_RECEIPT_FORMAT.to_owned(),
392                from_protocol_version: from_protocol_version.clone(),
393                target_manifest_without_receipt_sha256,
394                plan_digest: plan_digest.clone(),
395            })
396            .map_err(|source| FolderbaseError::json(&manifest_path, source))?,
397        );
398    let upgraded_manifest = serde_json::to_string_pretty(&manifest)
399        .map(|encoded| format!("{encoded}\n").into_bytes())
400        .map_err(|source| FolderbaseError::json(&manifest_path, source))?;
401    validate_generated_upgrade_manifest(&root, &upgraded_manifest)?;
402    Ok(ProtocolUpgradePlan {
403        root,
404        folderbase_id,
405        from_protocol_version,
406        to_protocol_version: "0.5.0".to_owned(),
407        changed_paths: vec![PathBuf::from(MANIFEST_PATH)],
408        plan_digest,
409        upgraded_manifest,
410        attested_manifest: manifest_bytes,
411        attested_manifest_sha256: attestation.manifest_sha256,
412        root_instance_sha256: attestation.root_instance_sha256,
413        attested_ignore_snapshot: Some(ignore_snapshot),
414        exchange_owner: None,
415        already_applied: false,
416    })
417}
418
419pub fn apply_protocol_upgrade(
420    plan: &ProtocolUpgradePlan,
421    expected: &ProtocolUpgradePlanDigest,
422) -> Result<ProtocolUpgradeResult> {
423    apply_protocol_upgrade_with_hooks(plan, expected, || {}, || Ok(()))
424}
425
426#[cfg(test)]
427fn apply_protocol_upgrade_with_hook(
428    plan: &ProtocolUpgradePlan,
429    expected: &ProtocolUpgradePlanDigest,
430    before_activation: impl FnOnce(),
431) -> Result<ProtocolUpgradeResult> {
432    apply_protocol_upgrade_with_hooks(plan, expected, before_activation, || Ok(()))
433}
434
435fn apply_protocol_upgrade_with_hooks(
436    plan: &ProtocolUpgradePlan,
437    expected: &ProtocolUpgradePlanDigest,
438    before_activation: impl FnOnce(),
439    after_activation: impl FnOnce() -> Result<()>,
440) -> Result<ProtocolUpgradeResult> {
441    apply_protocol_upgrade_with_ack_hooks(
442        plan,
443        expected,
444        before_activation,
445        after_activation,
446        || {},
447        || {},
448        || {},
449    )
450}
451
452fn apply_protocol_upgrade_with_ack_hooks(
453    plan: &ProtocolUpgradePlan,
454    expected: &ProtocolUpgradePlanDigest,
455    before_activation: impl FnOnce(),
456    after_activation: impl FnOnce() -> Result<()>,
457    after_revalidation: impl FnOnce(),
458    before_final_ack: impl FnOnce(),
459    after_intent_retirement: impl FnOnce(),
460) -> Result<ProtocolUpgradeResult> {
461    expected.validate()?;
462    let local = LocalVersionStore::open_read_only(&plan.root)?;
463    let state = FolderbaseState::open_existing(&plan.root)?;
464    let _lock = local.acquire_transaction_lock_in_allowing_protocol_upgrade(&state)?;
465    state.verify_still_attached()?;
466    recover_pending_protocol_upgrade(&state, &plan.root, expected)?;
467    ensure_no_pending_transactions(&state)?;
468    let current = plan_protocol_upgrade(&plan.root)?;
469    after_revalidation();
470    state.verify_still_attached()?;
471    if current.folderbase_id != plan.folderbase_id
472        || current.root_instance_sha256 != plan.root_instance_sha256
473        || current.attested_manifest_sha256 != plan.attested_manifest_sha256
474    {
475        return Err(FolderbaseError::ProtocolUpgradePlanChanged {
476            expected: expected.digest.clone(),
477            actual: "root_or_manifest_changed_at_acknowledgement".to_owned(),
478        });
479    }
480    if current.plan_digest != *expected || current.plan_digest != plan.plan_digest {
481        return Err(FolderbaseError::ProtocolUpgradePlanChanged {
482            expected: expected.digest.clone(),
483            actual: current.plan_digest.digest,
484        });
485    }
486    if current.upgraded_manifest != plan.upgraded_manifest {
487        return Err(FolderbaseError::ProtocolUpgradePlanChanged {
488            expected: expected.digest.clone(),
489            actual: current.plan_digest.digest,
490        });
491    }
492    if current.already_applied {
493        return Ok(upgrade_result(&current));
494    }
495    if current.attested_manifest_sha256 != plan.attested_manifest_sha256 {
496        return Err(FolderbaseError::ProtocolUpgradePlanChanged {
497            expected: expected.digest.clone(),
498            actual: current.plan_digest.digest,
499        });
500    }
501    let intent = ProtocolUpgradeIntent::from_plan(&current)?;
502    prepare_protocol_upgrade_intent(&state, &plan.root, &intent)?;
503    state
504        .compare_exchange_exact_owned_with_hook(
505            Path::new(MANIFEST_PATH),
506            &plan.attested_manifest,
507            &plan.upgraded_manifest,
508            &intent.exchange_owner,
509            before_activation,
510        )
511        .map_err(|error| match error {
512            FolderbaseError::WouldOverwrite(_) => FolderbaseError::ProtocolUpgradePlanChanged {
513                expected: expected.digest.clone(),
514                actual: "manifest_changed_at_activation".to_owned(),
515            },
516            other => other,
517        })?;
518    after_activation()?;
519    attest_exact_protocol_upgrade_target(&state, &plan.root, &intent)?;
520    let current_ignore_snapshot = read_ignore_snapshot(&state, &plan.root);
521    if !matches!(
522        current_ignore_snapshot,
523        Ok(ref actual) if actual == &intent.ignore_snapshot
524    ) {
525        state.verify_still_attached()?;
526        rollback_protocol_upgrade(&state, &plan.root, &intent)?;
527        return Err(FolderbaseError::ProtocolUpgradePlanChanged {
528            expected: expected.digest.clone(),
529            actual: "ignore_policy_changed_at_activation".to_owned(),
530        });
531    }
532    before_final_ack();
533    attest_exact_protocol_upgrade_target(&state, &plan.root, &intent)?;
534    state.verify_still_attached()?;
535    state.remove_durable(Path::new(UPGRADE_INTENT_PATH))?;
536    after_intent_retirement();
537    attest_retired_protocol_upgrade_target(&plan.root, &intent)?;
538    Ok(upgrade_result(plan))
539}
540
541impl ProtocolUpgradePlanDigest {
542    fn validate(&self) -> Result<()> {
543        if self.algorithm != "sha256"
544            || self.digest.len() != 64
545            || !self
546                .digest
547                .bytes()
548                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
549        {
550            return Err(FolderbaseError::InvalidProtocolUpgradePlanDigest);
551        }
552        Ok(())
553    }
554}
555
556fn ensure_no_pending_transactions(state: &FolderbaseState) -> Result<()> {
557    match scan_pending_work(state, None) {
558        Ok(Some(work)) => Err(FolderbaseError::ProtocolUpgradeBlocked(
559            work.protocol_upgrade_label(),
560        )),
561        Ok(None) => Ok(()),
562        Err(_) => Err(FolderbaseError::ProtocolUpgradeBlocked(
563            "Folderbase transaction recovery",
564        )),
565    }
566}
567
568pub(crate) fn scan_pending_work(
569    state: &FolderbaseState,
570    allowed_migration_id: Option<&str>,
571) -> Result<Option<PendingWork>> {
572    for (path, work) in [
573        (ACTIVE_CAPTURE_PATH, PendingWork::Capture),
574        (ACTIVE_RESTORE_PATH, PendingWork::TombstoneRestore),
575        (RESTORE_CLEANUP_PATH, PendingWork::TombstoneRestoreCleanup),
576        (ACTIVE_REORGANIZATION_PATH, PendingWork::Reorganization),
577    ] {
578        let state_path = path
579            .strip_prefix(".folderbase/")
580            .expect("pending path is state-relative");
581        match state.read_bounded_if_present(Path::new(state_path), MAX_PENDING_RECORD_BYTES) {
582            Ok(Some(_)) => return Ok(Some(work)),
583            Ok(None) => {}
584            Err(error) => return Err(error),
585        }
586    }
587
588    for name in state
589        .private_directory_names_if_present(Path::new("transactions"), MAX_TRANSACTION_ENTRIES)?
590    {
591        let Some(name) = name.to_str() else {
592            return Ok(Some(PendingWork::LocalVersionIntent(
593                "<non-utf8>".to_owned(),
594            )));
595        };
596        if !name.ends_with(".json") {
597            continue;
598        }
599        let path = Path::new("transactions").join(name);
600        match state.read_bounded_if_present(&path, MAX_PENDING_RECORD_BYTES) {
601            Ok(Some(_)) => {
602                return Ok(Some(PendingWork::LocalVersionIntent(name.to_owned())));
603            }
604            Ok(None) => {}
605            Err(_) => return Ok(Some(PendingWork::LocalVersionIntent(name.to_owned()))),
606        }
607    }
608
609    let migration_names = state.private_directory_names_if_present(
610        Path::new(
611            MIGRATIONS_PATH
612                .strip_prefix(".folderbase/")
613                .expect("migration path is state-relative"),
614        ),
615        MAX_MIGRATION_DIRECTORIES,
616    )?;
617    for migration_name in migration_names {
618        let migration_id = migration_name.to_string_lossy().into_owned();
619        if allowed_migration_id == Some(migration_id.as_str()) {
620            continue;
621        }
622        match durable_migration_execution_is_terminal(state, &migration_id)? {
623            Some(true) => continue,
624            Some(false) => return Ok(Some(PendingWork::Migration(migration_id))),
625            None if allowed_migration_id.is_some() => continue,
626            None => {}
627        }
628        let path = Path::new("migrations")
629            .join(&migration_name)
630            .join("plan.json");
631        let Some(bytes) = state.read_bounded_if_present(&path, MAX_PENDING_RECORD_BYTES)? else {
632            return Ok(Some(PendingWork::Migration(migration_id)));
633        };
634        let record: Value = match serde_json::from_slice(&bytes) {
635            Ok(record) => record,
636            Err(_) => return Ok(Some(PendingWork::Migration(migration_id))),
637        };
638        let Some(migration_state) = record.get("state").and_then(Value::as_str) else {
639            return Ok(Some(PendingWork::Migration(migration_id)));
640        };
641        if migration_state != "rejected" {
642            return Ok(Some(PendingWork::Migration(migration_id)));
643        }
644    }
645    Ok(None)
646}
647
648fn decode_applied_receipt(root: &Path, manifest: &Value) -> Result<ProtocolUpgradeReceipt> {
649    let receipt: ProtocolUpgradeReceipt = serde_json::from_value(
650        manifest
651            .get(PROTOCOL_UPGRADE_RECEIPT_FIELD)
652            .cloned()
653            .ok_or_else(|| {
654                invalid_upgrade(root, "0.5 manifest has no applied legacy-upgrade receipt")
655            })?,
656    )
657    .map_err(|source| {
658        invalid_upgrade(root, format!("invalid protocol-upgrade receipt: {source}"))
659    })?;
660    if receipt.format != PROTOCOL_UPGRADE_RECEIPT_FORMAT
661        || !matches!(
662            semver::Version::parse(&receipt.from_protocol_version),
663            Ok(version) if version.major == 0 && matches!(version.minor, 1 | 2)
664        )
665    {
666        return Err(invalid_upgrade(root, "invalid protocol-upgrade receipt"));
667    }
668    receipt.plan_digest.validate()?;
669    if receipt.target_manifest_without_receipt_sha256.len() != 64
670        || !receipt
671            .target_manifest_without_receipt_sha256
672            .bytes()
673            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
674    {
675        return Err(invalid_upgrade(root, "invalid protocol-upgrade receipt"));
676    }
677    let mut target = manifest.clone();
678    target
679        .as_object_mut()
680        .ok_or_else(|| invalid_upgrade(root, "manifest root must be an object"))?
681        .remove(PROTOCOL_UPGRADE_RECEIPT_FIELD);
682    let manifest_path = root.join(MANIFEST_PATH);
683    let target_encoded = serde_json::to_string_pretty(&target)
684        .map(|encoded| format!("{encoded}\n").into_bytes())
685        .map_err(|source| FolderbaseError::json(&manifest_path, source))?;
686    let actual_target_sha256 = format!("{:x}", Sha256::digest(&target_encoded));
687    if receipt.target_manifest_without_receipt_sha256 != actual_target_sha256 {
688        return Err(invalid_upgrade(
689            root,
690            "protocol-upgrade receipt does not bind the activated manifest",
691        ));
692    }
693    Ok(receipt)
694}
695
696fn upgrade_result(plan: &ProtocolUpgradePlan) -> ProtocolUpgradeResult {
697    ProtocolUpgradeResult {
698        root: plan.root.clone(),
699        folderbase_id: plan.folderbase_id.clone(),
700        from_protocol_version: plan.from_protocol_version.clone(),
701        to_protocol_version: plan.to_protocol_version.clone(),
702        changed_paths: plan.changed_paths.clone(),
703        applied_plan_digest: plan.plan_digest.clone(),
704    }
705}
706
707fn update_bytes(digest: &mut Sha256, bytes: &[u8]) {
708    digest.update((bytes.len() as u64).to_be_bytes());
709    digest.update(bytes);
710}
711
712impl ProtocolUpgradeIntent {
713    fn from_plan(plan: &ProtocolUpgradePlan) -> Result<Self> {
714        let ignore_snapshot = plan.attested_ignore_snapshot.clone().ok_or_else(|| {
715            invalid_upgrade(&plan.root, "legacy upgrade plan has no ignore snapshot")
716        })?;
717        let source_manifest = String::from_utf8(plan.attested_manifest.clone())
718            .map_err(|_| invalid_upgrade(&plan.root, "source manifest is not UTF-8"))?;
719        let target_manifest = String::from_utf8(plan.upgraded_manifest.clone())
720            .map_err(|_| invalid_upgrade(&plan.root, "target manifest is not UTF-8"))?;
721        Ok(Self {
722            format: UPGRADE_INTENT_FORMAT.to_owned(),
723            exchange_owner: plan
724                .exchange_owner
725                .clone()
726                .unwrap_or_else(|| Uuid::now_v7().to_string()),
727            folderbase_id: plan.folderbase_id.clone(),
728            root_instance_sha256: plan.root_instance_sha256.clone(),
729            from_protocol_version: plan.from_protocol_version.clone(),
730            to_protocol_version: plan.to_protocol_version.clone(),
731            plan_digest: plan.plan_digest.clone(),
732            source_manifest_sha256: format!("{:x}", Sha256::digest(source_manifest.as_bytes())),
733            source_manifest,
734            target_manifest_sha256: format!("{:x}", Sha256::digest(target_manifest.as_bytes())),
735            target_manifest,
736            ignore_snapshot,
737        })
738    }
739
740    fn validate(&self, root: &Path) -> Result<()> {
741        if self.format != UPGRADE_INTENT_FORMAT
742            || !matches!(
743                Uuid::parse_str(&self.exchange_owner),
744                Ok(owner) if owner.hyphenated().to_string() == self.exchange_owner
745            )
746            || self.to_protocol_version != "0.5.0"
747            || !valid_sha256(&self.root_instance_sha256)
748            || !valid_sha256(&self.source_manifest_sha256)
749            || !valid_sha256(&self.target_manifest_sha256)
750            || format!("{:x}", Sha256::digest(self.source_manifest.as_bytes()))
751                != self.source_manifest_sha256
752            || format!("{:x}", Sha256::digest(self.target_manifest.as_bytes()))
753                != self.target_manifest_sha256
754        {
755            return Err(invalid_upgrade(root, "invalid protocol-upgrade intent"));
756        }
757        self.plan_digest.validate()?;
758        self.ignore_snapshot.validate(root)?;
759        let (_, source_id, source_version, source_profile) =
760            decode_manifest_protocol_profile(self.source_manifest.as_bytes())
761                .map_err(|source| invalid_upgrade(root, source.to_string()))?;
762        let (target, target_id, target_version, target_profile) =
763            decode_manifest_protocol_profile(self.target_manifest.as_bytes())
764                .map_err(|source| invalid_upgrade(root, source.to_string()))?;
765        if source_id != self.folderbase_id
766            || target_id != self.folderbase_id
767            || source_version != self.from_protocol_version
768            || target_version != self.to_protocol_version
769            || !matches!(source_profile, ManifestProtocolProfile::LegacyV01V02)
770            || !matches!(target_profile, ManifestProtocolProfile::OrdinaryV05 { .. })
771        {
772            return Err(invalid_upgrade(
773                root,
774                "protocol-upgrade intent does not bind its manifest transition",
775            ));
776        }
777        let receipt = decode_applied_receipt(root, &target)?;
778        if receipt.plan_digest != self.plan_digest
779            || receipt.from_protocol_version != self.from_protocol_version
780        {
781            return Err(invalid_upgrade(
782                root,
783                "protocol-upgrade intent does not bind its target receipt",
784            ));
785        }
786        Ok(())
787    }
788
789    fn source_bytes(&self) -> &[u8] {
790        self.source_manifest.as_bytes()
791    }
792
793    fn target_bytes(&self) -> &[u8] {
794        self.target_manifest.as_bytes()
795    }
796}
797
798impl IgnorePolicySnapshot {
799    fn validate(&self, root: &Path) -> Result<()> {
800        match self {
801            Self::Absent => Ok(()),
802            Self::Present {
803                kind,
804                bytes,
805                sha256,
806                physical_identity_sha256,
807                link_count,
808            } if kind == "regular_file"
809                && *bytes <= MAX_FOLDERBASEIGNORE_BYTES
810                && valid_sha256(sha256)
811                && valid_sha256(physical_identity_sha256)
812                && *link_count == 1 =>
813            {
814                Ok(())
815            }
816            Self::Present { .. } => Err(invalid_upgrade(
817                root,
818                "protocol-upgrade ignore snapshot is invalid",
819            )),
820        }
821    }
822}
823
824fn valid_sha256(value: &str) -> bool {
825    value.len() == 64
826        && value
827            .bytes()
828            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
829}
830
831fn validate_generated_upgrade_manifest(root: &Path, manifest: &[u8]) -> Result<()> {
832    if u64::try_from(manifest.len()).unwrap_or(u64::MAX) > MAX_FOLDERBASE_MANIFEST_BYTES {
833        return Err(invalid_upgrade(
834            root,
835            "generated protocol-upgrade manifest exceeds the live manifest bound",
836        ));
837    }
838    decode_manifest_protocol_profile(manifest)
839        .map_err(|source| invalid_upgrade(root, source.to_string()))?;
840    Ok(())
841}
842
843fn plan_from_pending_intent(
844    root: PathBuf,
845    attestation: crate::FolderbaseRootAttestation,
846    manifest_bytes: Vec<u8>,
847    intent: ProtocolUpgradeIntent,
848) -> Result<ProtocolUpgradePlan> {
849    intent.validate(&root)?;
850    if intent.folderbase_id != attestation.folderbase_id
851        || intent.root_instance_sha256 != attestation.root_instance_sha256
852        || manifest_bytes != intent.source_bytes()
853    {
854        return Err(invalid_upgrade(
855            &root,
856            "pending protocol-upgrade intent does not bind the live legacy root",
857        ));
858    }
859    Ok(ProtocolUpgradePlan {
860        root,
861        folderbase_id: intent.folderbase_id,
862        from_protocol_version: intent.from_protocol_version,
863        to_protocol_version: intent.to_protocol_version,
864        changed_paths: vec![PathBuf::from(MANIFEST_PATH)],
865        plan_digest: intent.plan_digest,
866        upgraded_manifest: intent.target_manifest.into_bytes(),
867        attested_manifest: manifest_bytes,
868        attested_manifest_sha256: attestation.manifest_sha256,
869        root_instance_sha256: attestation.root_instance_sha256,
870        attested_ignore_snapshot: Some(intent.ignore_snapshot),
871        exchange_owner: Some(intent.exchange_owner),
872        already_applied: false,
873    })
874}
875
876fn read_protocol_upgrade_intent(
877    state: &FolderbaseState,
878    root: &Path,
879) -> Result<Option<ProtocolUpgradeIntent>> {
880    let Some(encoded) = state.read_bounded_if_present(
881        Path::new(UPGRADE_INTENT_PATH),
882        MAX_PROTOCOL_UPGRADE_INTENT_BYTES,
883    )?
884    else {
885        return Ok(None);
886    };
887    let intent: ProtocolUpgradeIntent = serde_json::from_slice(&encoded).map_err(|source| {
888        FolderbaseError::json(root.join(".folderbase").join(UPGRADE_INTENT_PATH), source)
889    })?;
890    intent.validate(root)?;
891    Ok(Some(intent))
892}
893
894fn prepare_protocol_upgrade_intent(
895    state: &FolderbaseState,
896    root: &Path,
897    intent: &ProtocolUpgradeIntent,
898) -> Result<()> {
899    intent.validate(root)?;
900    let encoded = serde_json::to_string_pretty(intent)
901        .map(|encoded| format!("{encoded}\n").into_bytes())
902        .map_err(|source| {
903            FolderbaseError::json(root.join(".folderbase").join(UPGRADE_INTENT_PATH), source)
904        })?;
905    if u64::try_from(encoded.len()).unwrap_or(u64::MAX) > MAX_PROTOCOL_UPGRADE_INTENT_BYTES {
906        return Err(invalid_upgrade(
907            root,
908            "protocol-upgrade intent exceeds its durable record bound",
909        ));
910    }
911    state.ensure_private_dir(Path::new(UPGRADE_INTENT_DIRECTORY))?;
912    match state.publish_new(Path::new(UPGRADE_INTENT_PATH), &encoded) {
913        Ok(()) => Ok(()),
914        Err(FolderbaseError::WouldOverwrite(_)) => {
915            let existing = state
916                .read_bounded(
917                    Path::new(UPGRADE_INTENT_PATH),
918                    MAX_PROTOCOL_UPGRADE_INTENT_BYTES,
919                )?
920                .ok_or_else(|| invalid_upgrade(root, "protocol-upgrade intent disappeared"))?;
921            if existing == encoded {
922                Ok(())
923            } else {
924                Err(invalid_upgrade(
925                    root,
926                    "another protocol-upgrade intent is already active",
927                ))
928            }
929        }
930        Err(error) => Err(error),
931    }
932}
933
934fn recover_pending_protocol_upgrade(
935    state: &FolderbaseState,
936    root: &Path,
937    expected: &ProtocolUpgradePlanDigest,
938) -> Result<()> {
939    let Some(intent) = read_protocol_upgrade_intent(state, root)? else {
940        return Ok(());
941    };
942    let manifest = state
943        .read_bounded(Path::new("manifest.json"), MAX_FOLDERBASE_MANIFEST_BYTES)?
944        .ok_or_else(|| invalid_upgrade(root, "manifest disappeared during upgrade recovery"))?;
945    attest_protocol_upgrade_recovery_root(state, root, &intent, &manifest)?;
946    state.recover_owned_exchange_artifacts(
947        Path::new(MANIFEST_PATH),
948        &intent.exchange_owner,
949        intent.source_bytes(),
950        intent.target_bytes(),
951    )?;
952    state.verify_still_attached()?;
953    if manifest == intent.target_bytes() {
954        match read_ignore_snapshot(state, root) {
955            Ok(snapshot) if snapshot == intent.ignore_snapshot => {
956                state.verify_still_attached()?;
957                state.remove_durable(Path::new(UPGRADE_INTENT_PATH))?;
958                return Ok(());
959            }
960            _ => {
961                rollback_protocol_upgrade(state, root, &intent)?;
962                return Err(FolderbaseError::ProtocolUpgradePlanChanged {
963                    expected: expected.digest.clone(),
964                    actual: "unvalidated_activation_rolled_back".to_owned(),
965                });
966            }
967        }
968    }
969    if manifest == intent.source_bytes() {
970        if matches!(
971            read_ignore_snapshot(state, root),
972            Ok(ref snapshot) if snapshot == &intent.ignore_snapshot
973        ) {
974            state.verify_still_attached()?;
975            return Ok(());
976        }
977        state.verify_still_attached()?;
978        state.remove_durable(Path::new(UPGRADE_INTENT_PATH))?;
979        return Err(FolderbaseError::ProtocolUpgradePlanChanged {
980            expected: expected.digest.clone(),
981            actual: "source_policy_changed_before_activation".to_owned(),
982        });
983    }
984    Err(invalid_upgrade(
985        root,
986        "pending protocol-upgrade intent matches neither live manifest state",
987    ))
988}
989
990fn rollback_protocol_upgrade(
991    state: &FolderbaseState,
992    root: &Path,
993    intent: &ProtocolUpgradeIntent,
994) -> Result<()> {
995    state.verify_still_attached()?;
996    state
997        .compare_exchange_exact_owned_with_hook(
998            Path::new(MANIFEST_PATH),
999            intent.target_bytes(),
1000            intent.source_bytes(),
1001            &intent.exchange_owner,
1002            || {},
1003        )
1004        .map_err(|source| {
1005            invalid_upgrade(
1006                root,
1007                format!("protocol-upgrade rollback could not restore its source: {source}"),
1008            )
1009        })?;
1010    let source_manifest = state
1011        .read_bounded(Path::new("manifest.json"), MAX_FOLDERBASE_MANIFEST_BYTES)?
1012        .ok_or_else(|| invalid_upgrade(root, "manifest disappeared during upgrade rollback"))?;
1013    if source_manifest != intent.source_bytes() {
1014        return Err(invalid_upgrade(
1015            root,
1016            "protocol-upgrade rollback did not restore its exact source",
1017        ));
1018    }
1019    let _ = attest_protocol_upgrade_recovery_root(state, root, intent, &source_manifest)?;
1020    state.verify_still_attached()?;
1021    state.remove_durable(Path::new(UPGRADE_INTENT_PATH))
1022}
1023
1024fn attest_protocol_upgrade_recovery_root(
1025    state: &FolderbaseState,
1026    root: &Path,
1027    intent: &ProtocolUpgradeIntent,
1028    manifest: &[u8],
1029) -> Result<(crate::FolderbaseRootAttestation, ManifestProtocolProfile)> {
1030    state.verify_still_attached()?;
1031    let (attestation, _, profile) =
1032        attest_folderbase_root_with_profile_allowing_upgrade_recovery(root)
1033            .map_err(|source| invalid_upgrade(root, source.to_string()))?;
1034    state.verify_still_attached()?;
1035    let manifest_sha256 = format!("{:x}", Sha256::digest(manifest));
1036    if attestation.folderbase_id != intent.folderbase_id
1037        || attestation.root_instance_sha256 != intent.root_instance_sha256
1038        || attestation.manifest_sha256 != manifest_sha256
1039        || (manifest != intent.source_bytes() && manifest != intent.target_bytes())
1040    {
1041        return Err(invalid_upgrade(
1042            root,
1043            "pending protocol-upgrade intent does not bind the attached physical root",
1044        ));
1045    }
1046    Ok((attestation, profile))
1047}
1048
1049fn attest_exact_protocol_upgrade_target(
1050    state: &FolderbaseState,
1051    root: &Path,
1052    intent: &ProtocolUpgradeIntent,
1053) -> Result<()> {
1054    let manifest = state
1055        .read_bounded(Path::new("manifest.json"), MAX_FOLDERBASE_MANIFEST_BYTES)?
1056        .ok_or_else(|| invalid_upgrade(root, "manifest disappeared after activation"))?;
1057    let (attestation, profile) =
1058        attest_protocol_upgrade_recovery_root(state, root, intent, &manifest)?;
1059    if attestation.protocol_version != "0.5.0"
1060        || !matches!(profile, ManifestProtocolProfile::OrdinaryV05 { .. })
1061        || manifest != intent.target_bytes()
1062    {
1063        return Err(invalid_upgrade(
1064            root,
1065            "manifest activation did not produce the exact 0.5 profile",
1066        ));
1067    }
1068    Ok(())
1069}
1070
1071fn attest_retired_protocol_upgrade_target(
1072    root: &Path,
1073    intent: &ProtocolUpgradeIntent,
1074) -> Result<()> {
1075    let visible_state = FolderbaseState::open_existing_read_only(root)?;
1076    visible_state.verify_still_attached()?;
1077    let manifest = visible_state
1078        .read_bounded(Path::new("manifest.json"), MAX_FOLDERBASE_MANIFEST_BYTES)?
1079        .ok_or_else(|| invalid_upgrade(root, "manifest disappeared after intent retirement"))?;
1080    let (attestation, _, profile) = attest_folderbase_root_with_profile(root)
1081        .map_err(|source| invalid_upgrade(root, source.to_string()))?;
1082    visible_state.verify_still_attached()?;
1083    let manifest_sha256 = format!("{:x}", Sha256::digest(&manifest));
1084    if attestation.folderbase_id != intent.folderbase_id
1085        || attestation.root_instance_sha256 != intent.root_instance_sha256
1086        || attestation.protocol_version != "0.5.0"
1087        || attestation.manifest_sha256 != manifest_sha256
1088        || !matches!(profile, ManifestProtocolProfile::OrdinaryV05 { .. })
1089        || manifest != intent.target_bytes()
1090    {
1091        return Err(invalid_upgrade(
1092            root,
1093            "retired protocol upgrade does not bind the visible physical root and exact target",
1094        ));
1095    }
1096    Ok(())
1097}
1098
1099fn read_ignore_snapshot(state: &FolderbaseState, root: &Path) -> Result<IgnorePolicySnapshot> {
1100    read_ignore_snapshot_with_hook(state, root, || {})
1101}
1102
1103#[cfg(test)]
1104fn read_ignore_snapshot_sha256_with_hook(
1105    state: &FolderbaseState,
1106    root: &Path,
1107    after_read: impl FnOnce(),
1108) -> Result<String> {
1109    read_ignore_snapshot_with_hook(state, root, after_read)?.binding_sha256()
1110}
1111
1112fn read_ignore_snapshot_with_hook(
1113    state: &FolderbaseState,
1114    root: &Path,
1115    after_read: impl FnOnce(),
1116) -> Result<IgnorePolicySnapshot> {
1117    state.verify_still_attached()?;
1118    if state.workspace_path_is_absent(Path::new(IGNORE_POLICY_PATH))? {
1119        after_read();
1120        if !state.workspace_path_is_absent(Path::new(IGNORE_POLICY_PATH))? {
1121            return Err(invalid_upgrade(
1122                root,
1123                "ignore policy presence changed while it was observed",
1124            ));
1125        }
1126        state.verify_still_attached()?;
1127        return Ok(IgnorePolicySnapshot::Absent);
1128    }
1129
1130    let mut first = state.open_workspace_regular_file(Path::new(IGNORE_POLICY_PATH))?;
1131    let observed = read_open_ignore_snapshot(&mut first, root)?;
1132    after_read();
1133    let mut visible = state.open_workspace_regular_file(Path::new(IGNORE_POLICY_PATH))?;
1134    let revalidated = read_open_ignore_snapshot(&mut visible, root)?;
1135    if observed != revalidated {
1136        return Err(invalid_upgrade(
1137            root,
1138            "visible ignore policy changed after it was read",
1139        ));
1140    }
1141    state.verify_still_attached()?;
1142    Ok(observed)
1143}
1144
1145fn read_open_ignore_snapshot(
1146    file: &mut std::fs::File,
1147    root: &Path,
1148) -> Result<IgnorePolicySnapshot> {
1149    let display = root.join(IGNORE_POLICY_PATH);
1150    let metadata_before = file
1151        .metadata()
1152        .map_err(|source| FolderbaseError::io(&display, source))?;
1153    let identity_before = stable_file_identity_sha256(file)
1154        .map_err(|source| FolderbaseError::io(&display, source))?;
1155    let links_before =
1156        stable_file_link_count(file).map_err(|source| FolderbaseError::io(&display, source))?;
1157    if !metadata_before.is_file()
1158        || metadata_before.len() > MAX_FOLDERBASEIGNORE_BYTES
1159        || links_before != 1
1160    {
1161        return Err(invalid_upgrade(
1162            root,
1163            "ignore policy must be one bounded, singly-linked regular file",
1164        ));
1165    }
1166    let mut bytes = Vec::new();
1167    file.by_ref()
1168        .take(MAX_FOLDERBASEIGNORE_BYTES + 1)
1169        .read_to_end(&mut bytes)
1170        .map_err(|source| FolderbaseError::io(&display, source))?;
1171    let metadata_after = file
1172        .metadata()
1173        .map_err(|source| FolderbaseError::io(&display, source))?;
1174    let identity_after = stable_file_identity_sha256(file)
1175        .map_err(|source| FolderbaseError::io(&display, source))?;
1176    let links_after =
1177        stable_file_link_count(file).map_err(|source| FolderbaseError::io(&display, source))?;
1178    if bytes.len() as u64 > MAX_FOLDERBASEIGNORE_BYTES
1179        || metadata_before.len() != metadata_after.len()
1180        || identity_before != identity_after
1181        || links_before != links_after
1182        || links_after != 1
1183    {
1184        return Err(invalid_upgrade(
1185            root,
1186            "ignore policy changed while its bytes and topology were read",
1187        ));
1188    }
1189    Ok(IgnorePolicySnapshot::Present {
1190        kind: "regular_file".to_owned(),
1191        bytes: bytes.len() as u64,
1192        sha256: format!("{:x}", Sha256::digest(&bytes)),
1193        physical_identity_sha256: identity_after,
1194        link_count: links_after,
1195    })
1196}
1197
1198fn invalid_upgrade(root: &Path, message: impl Into<String>) -> FolderbaseError {
1199    FolderbaseError::InvalidRecord {
1200        path: root.join(MANIFEST_PATH),
1201        message: message.into(),
1202    }
1203}
1204
1205#[cfg(test)]
1206mod tests {
1207    use std::fs;
1208
1209    use tempfile::tempdir;
1210
1211    use super::*;
1212
1213    const LEGACY_MANIFEST: &[u8] = br#"{
1214  "$schema": "https://folderbase.ai/protocol/0.1/folderbase.schema.json",
1215  "protocol_version": "0.1.0",
1216  "folderbase": {
1217    "id": "folderbase_019f9b75-4f42-7f65-a012-2bfecdd8c475",
1218    "name": "Legacy Folderbase",
1219    "kind": "project",
1220    "status": "active",
1221    "created_at": "2026-07-26T00:00:00Z",
1222    "entry": "FOLDERBASE.md"
1223  },
1224  "policies": {
1225    "availability": "keep_local",
1226    "structural_changes": "approve",
1227    "archive": "approve",
1228    "cloud_sync": "disabled"
1229  }
1230}
1231"#;
1232
1233    fn write_legacy_root(root: &Path) {
1234        fs::create_dir_all(root.join(".folderbase")).expect("state");
1235        fs::write(root.join(".folderbase/manifest.json"), LEGACY_MANIFEST).expect("manifest");
1236        fs::write(root.join("FOLDERBASE.md"), b"# User narrative\n").expect("entry");
1237        fs::write(root.join(".folderbaseignore"), b"node_modules/\n").expect("ignore");
1238    }
1239
1240    fn write_legacy_root_with_manifest_bytes(root: &Path, target_bytes: usize) {
1241        let mut manifest: Value =
1242            serde_json::from_slice(LEGACY_MANIFEST).expect("legacy manifest value");
1243        manifest
1244            .as_object_mut()
1245            .expect("legacy manifest object")
1246            .insert("x-padding".to_owned(), Value::String(String::new()));
1247        let encode = |manifest: &Value| {
1248            serde_json::to_string_pretty(manifest)
1249                .map(|encoded| format!("{encoded}\n").into_bytes())
1250                .expect("encoded legacy manifest")
1251        };
1252        let baseline = encode(&manifest);
1253        let padding_bytes = target_bytes
1254            .checked_sub(baseline.len())
1255            .expect("manifest budget");
1256        manifest
1257            .as_object_mut()
1258            .expect("legacy manifest object")
1259            .insert(
1260                "x-padding".to_owned(),
1261                Value::String("x".repeat(padding_bytes)),
1262            );
1263        let encoded = encode(&manifest);
1264        assert_eq!(encoded.len(), target_bytes);
1265
1266        fs::create_dir_all(root.join(".folderbase")).expect("state");
1267        fs::write(root.join(".folderbase/manifest.json"), encoded).expect("large manifest");
1268        fs::write(root.join("FOLDERBASE.md"), b"# User narrative\n").expect("entry");
1269        fs::write(root.join(".folderbaseignore"), b"node_modules/\n").expect("ignore");
1270    }
1271
1272    fn write_near_maximum_legacy_root(root: &Path) {
1273        write_legacy_root_with_manifest_bytes(
1274            root,
1275            MAX_FOLDERBASE_MANIFEST_BYTES as usize - 64 * 1024,
1276        );
1277    }
1278
1279    fn substitute_root_with_recovery_surface(root: &Path, ignore: &[u8]) {
1280        let manifest = fs::read(root.join(".folderbase/manifest.json")).expect("live manifest");
1281        let intent =
1282            fs::read(root.join(".folderbase").join(UPGRADE_INTENT_PATH)).expect("durable intent");
1283        let detached = root.with_extension("detached");
1284        fs::rename(root, &detached).expect("detach original root");
1285        fs::create_dir_all(root.join(".folderbase").join(UPGRADE_INTENT_DIRECTORY))
1286            .expect("replacement state");
1287        fs::write(root.join(".folderbase/manifest.json"), manifest).expect("replacement manifest");
1288        fs::write(root.join(".folderbase").join(UPGRADE_INTENT_PATH), intent)
1289            .expect("replacement intent");
1290        fs::write(root.join("FOLDERBASE.md"), b"# User narrative\n").expect("replacement entry");
1291        fs::write(root.join(".folderbaseignore"), ignore).expect("replacement ignore");
1292    }
1293
1294    #[test]
1295    fn manifest_replacement_is_a_durable_lost_ack_recovery_point() {
1296        let root = tempdir().expect("legacy root");
1297        fs::create_dir(root.path().join(".folderbase")).expect("state");
1298        fs::write(
1299            root.path().join(".folderbase/manifest.json"),
1300            LEGACY_MANIFEST,
1301        )
1302        .expect("manifest");
1303        fs::write(root.path().join("FOLDERBASE.md"), b"# User narrative\n").expect("entry");
1304        fs::write(root.path().join(".folderbaseignore"), b"node_modules/\n").expect("ignore");
1305
1306        let plan = plan_protocol_upgrade(root.path()).expect("upgrade plan");
1307        let expected = plan.plan_digest().clone();
1308        let state = FolderbaseState::open_existing(root.path()).expect("state capability");
1309        state
1310            .replace(Path::new(MANIFEST_PATH), &plan.upgraded_manifest)
1311            .expect("simulate crash after manifest activation");
1312        drop(state);
1313
1314        let retry = plan_protocol_upgrade(root.path()).expect("recover applied receipt");
1315        assert!(retry.already_applied);
1316        assert_eq!(retry.plan_digest(), &expected);
1317        let result =
1318            apply_protocol_upgrade(&retry, &expected).expect("acknowledge exact activation");
1319        assert_eq!(result.applied_plan_digest, expected);
1320    }
1321
1322    #[test]
1323    fn activation_exchange_restores_a_concurrent_manifest_without_clobbering_it() {
1324        let root = tempdir().expect("legacy root");
1325        fs::create_dir(root.path().join(".folderbase")).expect("state");
1326        fs::write(
1327            root.path().join(".folderbase/manifest.json"),
1328            LEGACY_MANIFEST,
1329        )
1330        .expect("manifest");
1331        fs::write(root.path().join("FOLDERBASE.md"), b"# User narrative\n").expect("entry");
1332        fs::write(root.path().join(".folderbaseignore"), b"node_modules/\n").expect("ignore");
1333
1334        let plan = plan_protocol_upgrade(root.path()).expect("upgrade plan");
1335        let expected = plan.plan_digest().clone();
1336        let foreign = [LEGACY_MANIFEST, b" "].concat();
1337        let manifest_path = root.path().join(MANIFEST_PATH);
1338        let result = apply_protocol_upgrade_with_hook(&plan, &expected, || {
1339            fs::write(&manifest_path, &foreign).expect("concurrent manifest edit");
1340        });
1341
1342        assert!(matches!(
1343            result,
1344            Err(FolderbaseError::ProtocolUpgradePlanChanged { .. })
1345        ));
1346        assert_eq!(
1347            fs::read(&manifest_path).expect("foreign manifest retained"),
1348            foreign
1349        );
1350    }
1351
1352    #[test]
1353    fn activation_refuses_concurrent_ignore_policy_presence_and_content_transitions() {
1354        for replacement in [None, Some(b"dist/\n".as_slice())] {
1355            let root = tempdir().expect("legacy root");
1356            fs::create_dir(root.path().join(".folderbase")).expect("state");
1357            fs::write(
1358                root.path().join(".folderbase/manifest.json"),
1359                LEGACY_MANIFEST,
1360            )
1361            .expect("manifest");
1362            fs::write(root.path().join("FOLDERBASE.md"), b"# User narrative\n").expect("entry");
1363            let ignore_path = root.path().join(".folderbaseignore");
1364            fs::write(&ignore_path, b"node_modules/\n").expect("ignore");
1365
1366            let plan = plan_protocol_upgrade(root.path()).expect("upgrade plan");
1367            let expected = plan.plan_digest().clone();
1368            let result = apply_protocol_upgrade_with_hook(&plan, &expected, || {
1369                if let Some(bytes) = replacement {
1370                    fs::write(&ignore_path, bytes).expect("concurrent ignore edit");
1371                } else {
1372                    fs::remove_file(&ignore_path).expect("concurrent ignore delete");
1373                }
1374            });
1375
1376            assert!(matches!(
1377                result,
1378                Err(FolderbaseError::ProtocolUpgradePlanChanged { .. })
1379            ));
1380            assert_eq!(
1381                fs::read(root.path().join(MANIFEST_PATH)).expect("legacy manifest retained"),
1382                LEGACY_MANIFEST
1383            );
1384            assert_eq!(fs::read(&ignore_path).ok().as_deref(), replacement);
1385        }
1386    }
1387
1388    #[test]
1389    fn restart_never_acknowledges_an_unvalidated_policy_transition() {
1390        let root = tempdir().expect("legacy root");
1391        fs::create_dir(root.path().join(".folderbase")).expect("state");
1392        fs::write(
1393            root.path().join(".folderbase/manifest.json"),
1394            LEGACY_MANIFEST,
1395        )
1396        .expect("manifest");
1397        fs::write(root.path().join("FOLDERBASE.md"), b"# User narrative\n").expect("entry");
1398        let ignore_path = root.path().join(".folderbaseignore");
1399        fs::write(&ignore_path, b"node_modules/\n").expect("ignore");
1400
1401        let plan = plan_protocol_upgrade(root.path()).expect("upgrade plan");
1402        let expected = plan.plan_digest().clone();
1403        let interrupted = apply_protocol_upgrade_with_hooks(
1404            &plan,
1405            &expected,
1406            || fs::write(&ignore_path, b"dist/\n").expect("concurrent policy transition"),
1407            || {
1408                Err(FolderbaseError::ProtocolUpgradeBlocked(
1409                    "simulated process interruption",
1410                ))
1411            },
1412        );
1413        assert!(interrupted.is_err());
1414        assert_ne!(
1415            fs::read(root.path().join(MANIFEST_PATH)).expect("activated manifest"),
1416            LEGACY_MANIFEST
1417        );
1418        assert!(
1419            attest_folderbase_root_with_profile(root.path()).is_err(),
1420            "ordinary typed admission must stop at the pending recovery intent"
1421        );
1422        let local = LocalVersionStore::open_read_only(root.path()).expect("local store");
1423        assert!(matches!(
1424            local.acquire_transaction_lock(),
1425            Err(FolderbaseError::ProtocolUpgradeBlocked(
1426                "Folderbase protocol upgrade recovery"
1427            ))
1428        ));
1429
1430        let retry = plan_protocol_upgrade(root.path()).expect("restart plan");
1431        assert!(
1432            apply_protocol_upgrade(&retry, retry.plan_digest()).is_err(),
1433            "a receipt cannot acknowledge activation that crashed before policy validation"
1434        );
1435        assert_eq!(
1436            fs::read(root.path().join(MANIFEST_PATH)).expect("safe rollback"),
1437            LEGACY_MANIFEST
1438        );
1439    }
1440
1441    #[test]
1442    fn restart_validates_an_exact_pending_activation_before_acknowledgement() {
1443        let root = tempdir().expect("legacy root");
1444        fs::create_dir(root.path().join(".folderbase")).expect("state");
1445        fs::write(
1446            root.path().join(".folderbase/manifest.json"),
1447            LEGACY_MANIFEST,
1448        )
1449        .expect("manifest");
1450        fs::write(root.path().join("FOLDERBASE.md"), b"# User narrative\n").expect("entry");
1451        fs::write(root.path().join(".folderbaseignore"), b"node_modules/\n").expect("ignore");
1452
1453        let plan = plan_protocol_upgrade(root.path()).expect("upgrade plan");
1454        let expected = plan.plan_digest().clone();
1455        let interrupted = apply_protocol_upgrade_with_hooks(
1456            &plan,
1457            &expected,
1458            || {},
1459            || {
1460                Err(FolderbaseError::ProtocolUpgradeBlocked(
1461                    "simulated process interruption",
1462                ))
1463            },
1464        );
1465        assert!(interrupted.is_err());
1466        assert!(attest_folderbase_root_with_profile(root.path()).is_err());
1467
1468        let retry = plan_protocol_upgrade(root.path()).expect("restart plan");
1469        let result =
1470            apply_protocol_upgrade(&retry, retry.plan_digest()).expect("validated recovery");
1471        assert_eq!(result.applied_plan_digest, expected);
1472        attest_folderbase_root_with_profile(root.path()).expect("intent retired after validation");
1473    }
1474
1475    #[test]
1476    fn restart_resumes_an_exact_prepared_source_intent() {
1477        let root = tempdir().expect("legacy root");
1478        fs::create_dir(root.path().join(".folderbase")).expect("state");
1479        fs::write(
1480            root.path().join(".folderbase/manifest.json"),
1481            LEGACY_MANIFEST,
1482        )
1483        .expect("manifest");
1484        fs::write(root.path().join("FOLDERBASE.md"), b"# User narrative\n").expect("entry");
1485        fs::write(root.path().join(".folderbaseignore"), b"node_modules/\n").expect("ignore");
1486
1487        let plan = plan_protocol_upgrade(root.path()).expect("upgrade plan");
1488        let intent = ProtocolUpgradeIntent::from_plan(&plan).expect("intent");
1489        let state = FolderbaseState::open_existing(root.path()).expect("state");
1490        prepare_protocol_upgrade_intent(&state, root.path(), &intent).expect("prepared intent");
1491        drop(state);
1492        assert!(attest_folderbase_root_with_profile(root.path()).is_err());
1493
1494        let retry = plan_protocol_upgrade(root.path()).expect("restart plan");
1495        apply_protocol_upgrade(&retry, retry.plan_digest()).expect("resume prepared activation");
1496        attest_folderbase_root_with_profile(root.path()).expect("intent retired after activation");
1497    }
1498
1499    #[test]
1500    fn target_recovery_never_acknowledges_a_copied_replacement_root() {
1501        let parent = tempdir().expect("parent");
1502        let root = parent.path().join("active");
1503        write_legacy_root(&root);
1504        let plan = plan_protocol_upgrade(&root).expect("upgrade plan");
1505        let expected = plan.plan_digest().clone();
1506        apply_protocol_upgrade_with_hooks(
1507            &plan,
1508            &expected,
1509            || {},
1510            || {
1511                Err(FolderbaseError::ProtocolUpgradeBlocked(
1512                    "simulated process interruption",
1513                ))
1514            },
1515        )
1516        .expect_err("simulated interruption");
1517        substitute_root_with_recovery_surface(&root, b"node_modules/\n");
1518
1519        let retry = plan_protocol_upgrade(&root).expect("replacement restart plan");
1520        assert!(
1521            apply_protocol_upgrade(&retry, retry.plan_digest()).is_err(),
1522            "target recovery must bind the intent to the current physical root"
1523        );
1524        assert!(
1525            root.join(".folderbase").join(UPGRADE_INTENT_PATH).exists(),
1526            "foreign-root recovery evidence must remain for explicit repair"
1527        );
1528    }
1529
1530    #[test]
1531    fn source_recovery_never_retires_an_intent_copied_to_a_replacement_root() {
1532        let parent = tempdir().expect("parent");
1533        let root = parent.path().join("active");
1534        write_legacy_root(&root);
1535        let plan = plan_protocol_upgrade(&root).expect("upgrade plan");
1536        let expected = plan.plan_digest().clone();
1537        let intent = ProtocolUpgradeIntent::from_plan(&plan).expect("intent");
1538        let state = FolderbaseState::open_existing(&root).expect("state");
1539        prepare_protocol_upgrade_intent(&state, &root, &intent).expect("prepared intent");
1540        drop(state);
1541        substitute_root_with_recovery_surface(&root, b"dist/\n");
1542
1543        assert!(apply_protocol_upgrade(&plan, &expected).is_err());
1544        assert!(
1545            root.join(".folderbase").join(UPGRADE_INTENT_PATH).exists(),
1546            "source recovery must attest the root before retiring stale intent state"
1547        );
1548    }
1549
1550    #[test]
1551    fn post_activation_ack_never_accepts_a_replacement_physical_root() {
1552        let parent = tempdir().expect("parent");
1553        let root = parent.path().join("active");
1554        let detached = parent.path().join("detached");
1555        write_legacy_root(&root);
1556        let plan = plan_protocol_upgrade(&root).expect("upgrade plan");
1557        let expected = plan.plan_digest().clone();
1558        let replacement_manifest = plan.upgraded_manifest.clone();
1559        let visible_root = root.clone();
1560        let detached_root = detached.clone();
1561
1562        let result = apply_protocol_upgrade_with_hooks(
1563            &plan,
1564            &expected,
1565            || {},
1566            || {
1567                fs::rename(&visible_root, &detached_root).expect("detach activated root");
1568                fs::create_dir_all(visible_root.join(".folderbase")).expect("replacement state");
1569                fs::write(
1570                    visible_root.join(".folderbase/manifest.json"),
1571                    replacement_manifest,
1572                )
1573                .expect("replacement manifest");
1574                Ok(())
1575            },
1576        );
1577
1578        assert!(
1579            result.is_err(),
1580            "activation acknowledgement must bind the visible physical root"
1581        );
1582        assert!(
1583            detached
1584                .join(".folderbase")
1585                .join(UPGRADE_INTENT_PATH)
1586                .exists(),
1587            "detached recovery evidence must remain after root substitution"
1588        );
1589    }
1590
1591    #[test]
1592    fn final_ack_never_accepts_a_root_substituted_after_intent_retirement() {
1593        let parent = tempdir().expect("parent");
1594        let root = parent.path().join("active");
1595        let detached = parent.path().join("detached");
1596        write_legacy_root(&root);
1597        let plan = plan_protocol_upgrade(&root).expect("upgrade plan");
1598        let expected = plan.plan_digest().clone();
1599        let replacement_manifest = plan.upgraded_manifest.clone();
1600        let visible_root = root.clone();
1601        let detached_root = detached.clone();
1602
1603        let result = apply_protocol_upgrade_with_ack_hooks(
1604            &plan,
1605            &expected,
1606            || {},
1607            || Ok(()),
1608            || {},
1609            || {
1610                fs::rename(&visible_root, &detached_root).expect("detach acknowledged root");
1611                fs::create_dir_all(visible_root.join(".folderbase")).expect("replacement state");
1612                fs::write(
1613                    visible_root.join(".folderbase/manifest.json"),
1614                    replacement_manifest,
1615                )
1616                .expect("replacement manifest");
1617                fs::write(visible_root.join(".folderbaseignore"), b"node_modules/\n")
1618                    .expect("replacement ignore");
1619            },
1620            || {},
1621        );
1622
1623        assert!(
1624            result.is_err(),
1625            "final acknowledgement must remain bound to the upgraded physical root"
1626        );
1627        assert!(
1628            detached
1629                .join(".folderbase")
1630                .join(UPGRADE_INTENT_PATH)
1631                .exists(),
1632            "recovery evidence must not retire before final acknowledgement"
1633        );
1634    }
1635
1636    #[test]
1637    fn already_applied_ack_rechecks_the_retained_physical_root() {
1638        let parent = tempdir().expect("parent");
1639        let root = parent.path().join("active");
1640        let detached = parent.path().join("detached");
1641        write_legacy_root(&root);
1642        let initial = plan_protocol_upgrade(&root).expect("upgrade plan");
1643        apply_protocol_upgrade(&initial, initial.plan_digest()).expect("initial upgrade");
1644        let retry = plan_protocol_upgrade(&root).expect("already-applied plan");
1645        let expected = retry.plan_digest().clone();
1646        let replacement_manifest = retry.upgraded_manifest.clone();
1647        let visible_root = root.clone();
1648        let detached_root = detached.clone();
1649
1650        let result = apply_protocol_upgrade_with_ack_hooks(
1651            &retry,
1652            &expected,
1653            || {},
1654            || Ok(()),
1655            || {
1656                fs::rename(&visible_root, &detached_root).expect("detach revalidated root");
1657                fs::create_dir_all(visible_root.join(".folderbase")).expect("replacement state");
1658                fs::write(
1659                    visible_root.join(".folderbase/manifest.json"),
1660                    replacement_manifest,
1661                )
1662                .expect("replacement manifest");
1663            },
1664            || {},
1665            || {},
1666        );
1667
1668        assert!(
1669            result.is_err(),
1670            "an already-applied acknowledgement must bind its retained root"
1671        );
1672    }
1673
1674    #[test]
1675    fn post_retirement_ack_rejects_a_replacement_root_and_preserves_lost_ack_recovery() {
1676        let parent = tempdir().expect("parent");
1677        let root = parent.path().join("active");
1678        let detached = parent.path().join("detached");
1679        write_legacy_root(&root);
1680        let plan = plan_protocol_upgrade(&root).expect("upgrade plan");
1681        let expected = plan.plan_digest().clone();
1682        let replacement_manifest = plan.upgraded_manifest.clone();
1683        let visible_root = root.clone();
1684        let detached_root = detached.clone();
1685
1686        let result = apply_protocol_upgrade_with_ack_hooks(
1687            &plan,
1688            &expected,
1689            || {},
1690            || Ok(()),
1691            || {},
1692            || {},
1693            || {
1694                fs::rename(&visible_root, &detached_root).expect("detach retired root");
1695                fs::create_dir_all(visible_root.join(".folderbase")).expect("replacement state");
1696                fs::write(
1697                    visible_root.join(".folderbase/manifest.json"),
1698                    replacement_manifest,
1699                )
1700                .expect("replacement manifest");
1701            },
1702        );
1703
1704        assert!(
1705            result.is_err(),
1706            "post-retirement acknowledgement must bind the visible physical root"
1707        );
1708        assert_eq!(
1709            fs::read(detached.join(MANIFEST_PATH)).expect("detached upgraded manifest"),
1710            plan.upgraded_manifest,
1711            "the original upgraded bytes remain durable after a lost acknowledgement"
1712        );
1713        assert!(
1714            !detached
1715                .join(".folderbase")
1716                .join(UPGRADE_INTENT_PATH)
1717                .exists(),
1718            "the durable receipt, not a retired intent, is the lost-ack recovery authority"
1719        );
1720
1721        fs::remove_dir_all(&root).expect("remove replacement root");
1722        fs::rename(&detached, &root).expect("restore original root");
1723        let retry = plan_protocol_upgrade(&root).expect("recover receipt-backed upgrade");
1724        assert!(retry.already_applied, "the durable receipt proves lost ack");
1725        apply_protocol_upgrade(&retry, retry.plan_digest())
1726            .expect("already-applied recovery remains idempotent");
1727    }
1728
1729    #[test]
1730    fn near_maximum_manifests_leave_a_restart_readable_durable_intent() {
1731        let root = tempdir().expect("legacy root");
1732        write_near_maximum_legacy_root(root.path());
1733        let plan = plan_protocol_upgrade(root.path()).expect("large upgrade plan");
1734        assert!(plan.attested_manifest.len() as u64 <= MAX_FOLDERBASE_MANIFEST_BYTES);
1735        assert!(plan.upgraded_manifest.len() as u64 <= MAX_FOLDERBASE_MANIFEST_BYTES);
1736        let expected = plan.plan_digest().clone();
1737
1738        apply_protocol_upgrade_with_hooks(
1739            &plan,
1740            &expected,
1741            || {},
1742            || {
1743                Err(FolderbaseError::ProtocolUpgradeBlocked(
1744                    "simulated process interruption",
1745                ))
1746            },
1747        )
1748        .expect_err("simulated interruption");
1749        let intent = root.path().join(".folderbase").join(UPGRADE_INTENT_PATH);
1750        if !intent.exists() {
1751            assert_eq!(
1752                fs::read(root.path().join(MANIFEST_PATH)).expect("source manifest"),
1753                plan.attested_manifest,
1754                "a pre-publication bound refusal must leave the source untouched"
1755            );
1756            return;
1757        }
1758
1759        let retry = plan_protocol_upgrade(root.path())
1760            .expect("every published durable intent must be restart-readable");
1761        apply_protocol_upgrade(&retry, retry.plan_digest()).expect("restart recovery");
1762        assert!(!intent.exists(), "restart retires the durable intent");
1763    }
1764
1765    #[test]
1766    fn an_exact_maximum_source_that_expands_past_the_target_bound_is_never_published() {
1767        let root = tempdir().expect("legacy root");
1768        write_legacy_root_with_manifest_bytes(root.path(), MAX_FOLDERBASE_MANIFEST_BYTES as usize);
1769        let manifest_path = root.path().join(MANIFEST_PATH);
1770        let source_manifest = fs::read(&manifest_path).expect("source manifest");
1771
1772        let result = plan_protocol_upgrade(root.path());
1773
1774        assert!(
1775            result.is_err(),
1776            "planning must reject a generated target above the live manifest bound"
1777        );
1778        assert_eq!(
1779            fs::read(&manifest_path).expect("unchanged source manifest"),
1780            source_manifest
1781        );
1782        assert!(
1783            !root
1784                .path()
1785                .join(".folderbase")
1786                .join(UPGRADE_INTENT_PATH)
1787                .exists(),
1788            "a rejected target must not publish durable intent"
1789        );
1790        let exchange_artifact = fs::read_dir(root.path().join(".folderbase"))
1791            .expect("state directory")
1792            .filter_map(|entry| entry.ok())
1793            .any(|entry| {
1794                entry
1795                    .file_name()
1796                    .to_string_lossy()
1797                    .starts_with(".exchange-")
1798            });
1799        assert!(
1800            !exchange_artifact,
1801            "a rejected target must not begin exchange"
1802        );
1803    }
1804
1805    #[test]
1806    fn ignore_snapshot_rejects_a_post_read_same_byte_path_replacement() {
1807        let root = tempdir().expect("legacy root");
1808        fs::create_dir(root.path().join(".folderbase")).expect("state");
1809        fs::write(
1810            root.path().join(".folderbase/manifest.json"),
1811            LEGACY_MANIFEST,
1812        )
1813        .expect("manifest");
1814        fs::write(root.path().join("FOLDERBASE.md"), b"# User narrative\n").expect("entry");
1815        let ignore_path = root.path().join(".folderbaseignore");
1816        fs::write(&ignore_path, b"node_modules/\n").expect("ignore");
1817        let state = FolderbaseState::open_existing_read_only(root.path()).expect("state");
1818
1819        let result = read_ignore_snapshot_sha256_with_hook(&state, root.path(), || {
1820            fs::remove_file(&ignore_path).expect("remove observed policy");
1821            fs::write(&ignore_path, b"node_modules/\n").expect("same-byte replacement");
1822        });
1823
1824        assert!(
1825            result.is_err(),
1826            "the retained file is not enough; the visible path must be reopened and rebound"
1827        );
1828    }
1829
1830    #[cfg(any(unix, windows))]
1831    #[test]
1832    fn ignore_snapshot_rejects_a_post_read_hard_link_topology_change() {
1833        let root = tempdir().expect("legacy root");
1834        fs::create_dir(root.path().join(".folderbase")).expect("state");
1835        fs::write(
1836            root.path().join(".folderbase/manifest.json"),
1837            LEGACY_MANIFEST,
1838        )
1839        .expect("manifest");
1840        fs::write(root.path().join("FOLDERBASE.md"), b"# User narrative\n").expect("entry");
1841        let ignore_path = root.path().join(".folderbaseignore");
1842        fs::write(&ignore_path, b"node_modules/\n").expect("ignore");
1843        let state = FolderbaseState::open_existing_read_only(root.path()).expect("state");
1844
1845        let result = read_ignore_snapshot_sha256_with_hook(&state, root.path(), || {
1846            fs::hard_link(&ignore_path, root.path().join("ignore.backup"))
1847                .expect("new hard-link authority");
1848        });
1849
1850        assert!(
1851            result.is_err(),
1852            "link topology is part of the approved policy identity"
1853        );
1854    }
1855}