folderbase-core 0.7.2

Local-first Folderbase protocol and filesystem primitives for humans and agents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
use std::{fs, path::Path};

use folderbase_core::{
    CaptureEntryKind, CaptureExclusionKind, CaptureExclusionReason, CapturePlanLimitKind,
    FolderbaseCaptureError, FolderbaseVersionStore, MAX_CAPTURE_PLAN_RECORDS, RootAttestationError,
    attest_folderbase_root,
};
use tempfile::{TempDir, tempdir};

const FOLDERBASE_ID: &str = "folderbase_019f9b75-4f42-7f65-a012-2bfecdd8c473";
const MANIFEST: &[u8] = br#"{
  "protocol_version": "0.1.0",
  "folderbase": {
    "id": "folderbase_019f9b75-4f42-7f65-a012-2bfecdd8c473"
  }
}
"#;

fn folderbase() -> TempDir {
    let root = tempdir().expect("temporary Folderbase");
    fs::create_dir(root.path().join(".folderbase")).expect("state directory");
    fs::write(root.path().join(".folderbase/manifest.json"), MANIFEST).expect("manifest");
    fs::write(root.path().join(".folderbaseignore"), "").expect("ignore policy");
    fs::write(root.path().join("FOLDERBASE.md"), "# Folderbase\n").expect("entry");
    root
}

fn entry_paths(plan: &folderbase_core::CapturePlan) -> Vec<(&str, CaptureEntryKind, Option<u64>)> {
    plan.entries()
        .iter()
        .map(|entry| (entry.path(), entry.kind(), entry.bytes()))
        .collect()
}

#[test]
fn open_and_plan_bind_metadata_to_one_attested_root_without_writing() {
    let root = folderbase();
    fs::create_dir(root.path().join("docs")).expect("docs");
    fs::write(root.path().join("docs/notes.md"), "ordinary content\n").expect("notes");
    let state_before = state_paths(root.path());

    let store = FolderbaseVersionStore::open(root.path()).expect("open exact Folderbase");
    let plan = store.plan_capture().expect("metadata plan");

    assert_eq!(plan.root(), root.path().canonicalize().unwrap());
    assert_eq!(plan.folderbase_id(), FOLDERBASE_ID);
    assert_eq!(plan.root_instance_sha256().len(), 64);
    assert_eq!(plan.root_manifest_sha256().len(), 64);
    assert_eq!(plan.root_manifest_bytes(), MANIFEST.len() as u64);
    assert_eq!(plan.current_local_head(), None);
    assert_eq!(plan.ignore_policy_sha256().len(), 64);
    assert_eq!(
        entry_paths(&plan),
        vec![
            (".folderbaseignore", CaptureEntryKind::RegularFile, Some(0)),
            ("FOLDERBASE.md", CaptureEntryKind::RegularFile, Some(13)),
            ("docs", CaptureEntryKind::Directory, None),
            ("docs/notes.md", CaptureEntryKind::RegularFile, Some(17)),
        ]
    );
    assert_eq!(plan.exclusions().len(), 0);
    assert_eq!(plan.ignored_paths().len(), 0);
    assert_eq!(state_paths(root.path()), state_before);
}

#[cfg(unix)]
#[test]
fn open_rejects_a_supplied_symlink_root_before_canonicalizing_it() {
    let root = folderbase();
    let links = tempdir().expect("link parent");
    let linked_root = links.path().join("linked-folderbase");
    std::os::unix::fs::symlink(root.path(), &linked_root).expect("root symlink");

    assert!(matches!(
        FolderbaseVersionStore::open(&linked_root),
        Err(FolderbaseCaptureError::RootAttestation(
            RootAttestationError::RootSymlink { root }
        )) if root == linked_root
    ));
}

#[cfg(windows)]
#[test]
fn open_rejects_a_supplied_windows_directory_reparse_root() {
    let root = folderbase();
    let links = tempdir().expect("link parent");
    let linked_root = links.path().join("linked-folderbase");
    if let Err(source) = std::os::windows::fs::symlink_dir(root.path(), &linked_root) {
        if source.kind() == std::io::ErrorKind::PermissionDenied {
            return;
        }
        panic!("directory reparse point: {source}");
    }

    assert!(matches!(
        FolderbaseVersionStore::open(&linked_root),
        Err(FolderbaseCaptureError::RootAttestation(
            RootAttestationError::RootSymlink { root }
        )) if root == linked_root
    ));
}

#[test]
fn ordered_ignore_policy_applies_defaults_negation_required_overrides_and_prunes_directories() {
    let root = folderbase();
    fs::write(
        root.path().join(".folderbaseignore"),
        include_str!("fixtures/capture/ordered.folderbaseignore"),
    )
    .expect("ordered policy");
    fs::write(root.path().join("drop.tmp"), "ignored").expect("temporary file");
    fs::write(root.path().join("keep.tmp"), "included").expect("negated temporary");
    fs::write(root.path().join("important.log"), "last rule wins").expect("ordered file");
    fs::create_dir_all(root.path().join("node_modules/pkg")).expect("reincluded generated tree");
    fs::write(
        root.path().join("node_modules/pkg/index.js"),
        "opaque generated bytes",
    )
    .expect("reincluded generated file");
    fs::create_dir_all(root.path().join("dist/deep")).expect("default excluded directory");

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;

        fs::write(root.path().join("dist/deep/CON"), "must never be visited")
            .expect("nonportable descendant");
        fs::set_permissions(root.path().join("dist"), fs::Permissions::from_mode(0o0))
            .expect("excluded directory cannot be opened");
    }

    let planned = FolderbaseVersionStore::open(root.path())
        .expect("open")
        .plan_capture();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;

        fs::set_permissions(root.path().join("dist"), fs::Permissions::from_mode(0o700))
            .expect("restore cleanup access");
    }
    let plan = planned.expect("ignored directory is pruned before opening or traversing it");
    let paths = plan
        .entries()
        .iter()
        .map(|entry| entry.path())
        .collect::<Vec<_>>();
    let ignored = plan
        .ignored_paths()
        .iter()
        .map(|entry| entry.path())
        .collect::<Vec<_>>();

    assert!(paths.contains(&".folderbaseignore"));
    assert!(paths.contains(&"FOLDERBASE.md"));
    assert!(paths.contains(&"keep.tmp"));
    assert!(paths.contains(&"node_modules"));
    assert!(paths.contains(&"node_modules/pkg/index.js"));
    assert!(!paths.contains(&"drop.tmp"));
    assert!(!paths.contains(&"important.log"));
    assert!(!paths.iter().any(|path| path.starts_with("dist/")));
    assert_eq!(ignored, vec!["dist", "drop.tmp", "important.log"]);
}

#[test]
fn nested_folderbases_are_typed_boundaries_and_all_regular_file_formats_remain_opaque() {
    let root = folderbase();
    for (path, contents) in [
        ("reference.pdf", b"%PDF opaque".as_slice()),
        ("movie.mov", b"opaque video".as_slice()),
        ("data.csv", b"a,b\n1,2\n".as_slice()),
        ("database.sqlite", b"SQLite format 3\0opaque".as_slice()),
        ("archive.unknown", b"unknown opaque".as_slice()),
        (
            ".git/objects/pack/pack-test.pack",
            b"git pack opaque".as_slice(),
        ),
    ] {
        let path = root.path().join(path);
        fs::create_dir_all(path.parent().unwrap()).expect("opaque parent");
        fs::write(path, contents).expect("opaque regular file");
    }
    let child = root.path().join("Clients/Prosperna");
    fs::create_dir_all(child.join(".folderbase")).expect("nested state");
    fs::write(
        child.join(".folderbase/manifest.json"),
        b"{not-json and still opaque",
    )
    .expect("opaque nested manifest");
    fs::write(child.join("FOLDERBASE.md"), "# Child\n").expect("nested entry");
    #[cfg(unix)]
    fs::write(child.join("CON"), "must not be traversed").expect("unsafe nested descendant");
    #[cfg(windows)]
    fs::write(child.join("private.bin"), "must not be traversed").expect("nested descendant");

    let plan = FolderbaseVersionStore::open(root.path())
        .expect("open")
        .plan_capture()
        .expect("plan with opaque boundary");

    for expected in [
        "reference.pdf",
        "movie.mov",
        "data.csv",
        "database.sqlite",
        "archive.unknown",
        ".git/objects/pack/pack-test.pack",
    ] {
        let entry = plan
            .entries()
            .iter()
            .find(|entry| entry.path() == expected)
            .unwrap_or_else(|| panic!("missing opaque regular file {expected}"));
        assert_eq!(entry.kind(), CaptureEntryKind::RegularFile);
        assert!(entry.bytes().is_some());
    }
    assert!(
        !plan
            .entries()
            .iter()
            .any(|entry| entry.path().starts_with("Clients/Prosperna/"))
    );
    let boundary = plan
        .exclusions()
        .iter()
        .find(|exclusion| exclusion.path() == "Clients/Prosperna")
        .expect("typed nested boundary");
    assert_eq!(boundary.kind(), CaptureExclusionKind::NestedFolderbase);
    assert_eq!(
        boundary.reason(),
        CaptureExclusionReason::NestedFolderbaseBoundary
    );
}

#[cfg(unix)]
#[test]
fn malformed_nested_entry_marker_still_closes_the_nested_boundary() {
    let root = folderbase();
    let child = root.path().join("Clients/Malformed");
    fs::create_dir_all(child.join(".folderbase")).expect("nested state");
    fs::write(child.join(".folderbase/manifest.json"), MANIFEST).expect("nested manifest");
    std::os::unix::fs::symlink("missing-entry", child.join("FOLDERBASE.md"))
        .expect("malformed nested entry marker");
    fs::write(child.join("CON"), "must not be traversed").expect("unsafe nested descendant");

    let plan = FolderbaseVersionStore::open(root.path())
        .expect("open")
        .plan_capture()
        .expect("malformed child is still an opaque nested boundary");

    let boundary = plan
        .exclusions()
        .iter()
        .find(|exclusion| exclusion.path() == "Clients/Malformed")
        .expect("typed nested boundary");
    assert_eq!(boundary.kind(), CaptureExclusionKind::NestedFolderbase);
    assert_eq!(
        boundary.reason(),
        CaptureExclusionReason::NestedFolderbaseBoundary
    );
}

#[test]
fn capture_refuses_case_folded_marker_aliases_without_granting_them_authority() {
    let root = folderbase();
    let child = root.path().join("Clients/Alias");
    fs::create_dir_all(child.join(".FOLDERBASE")).expect("nested alias state");
    fs::write(child.join(".FOLDERBASE/MANIFEST.JSON"), b"opaque").expect("nested alias manifest");
    fs::write(child.join("private.bin"), b"must not be captured").expect("private descendant");

    assert!(
        FolderbaseVersionStore::open(root.path())
            .expect("open")
            .plan_capture()
            .is_err(),
        "an alias-shaped marker fails closed but never becomes protocol authority"
    );
}

#[cfg(unix)]
#[test]
fn capture_refuses_a_symlink_shaped_marker_without_following_it() {
    let root = folderbase();
    let child = root.path().join("Clients/Symlink");
    fs::create_dir_all(&child).expect("child");
    std::os::unix::fs::symlink(root.path().join("missing-state"), child.join(".folderbase"))
        .expect("state symlink");
    fs::write(child.join("private.bin"), b"must not be captured").expect("private descendant");

    assert!(
        FolderbaseVersionStore::open(root.path())
            .expect("open")
            .plan_capture()
            .is_err()
    );
}

#[cfg(unix)]
#[test]
fn sparse_ten_gibibyte_file_is_planned_by_metadata_and_v1_object_size_is_bounded() {
    let root = folderbase();
    let movie = root.path().join("feature.mov");
    let file = fs::File::create(&movie).expect("sparse movie");
    file.set_len(10 * 1024 * 1024 * 1024)
        .expect("10 GiB sparse length");

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;

        fs::set_permissions(&movie, fs::Permissions::from_mode(0o0))
            .expect("ordinary file contents are unreadable");
    }

    let plan = FolderbaseVersionStore::open(root.path())
        .expect("open")
        .plan_capture()
        .expect("metadata-only planning never opens ordinary bytes");
    let planned = plan
        .entries()
        .iter()
        .find(|entry| entry.path() == "feature.mov")
        .expect("movie metadata");
    assert_eq!(planned.kind(), CaptureEntryKind::RegularFile);
    assert_eq!(planned.bytes(), Some(10 * 1024 * 1024 * 1024));

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;

        fs::set_permissions(&movie, fs::Permissions::from_mode(0o600))
            .expect("restore test cleanup permissions");
    }

    let oversized = root.path().join("too-large.bin");
    let file = fs::File::create(&oversized).expect("oversized sparse file");
    file.set_len(1024 * 1024 * 1024 * 1024 + 1)
        .expect("v1 boundary probe");
    assert!(matches!(
        FolderbaseVersionStore::open(root.path())
            .expect("reopen")
            .plan_capture(),
        Err(FolderbaseCaptureError::InventoryLimitExceeded {
            limit,
            maximum,
            ..
        }) if limit == CapturePlanLimitKind::ObjectBytes
            && maximum == 1024 * 1024 * 1024 * 1024
    ));
}

#[cfg(windows)]
#[test]
fn windows_hard_links_are_typed_exclusions() {
    let root = folderbase();
    fs::write(root.path().join("original.bin"), "same inode").expect("regular file");
    fs::hard_link(
        root.path().join("original.bin"),
        root.path().join("alias.bin"),
    )
    .expect("hard link");

    let plan = FolderbaseVersionStore::open(root.path())
        .expect("open")
        .plan_capture()
        .expect("typed hard links");
    assert_eq!(
        plan.exclusions()
            .iter()
            .filter(|entry| entry.kind() == CaptureExclusionKind::HardLink)
            .count(),
        2
    );
}

#[test]
fn plan_is_bound_to_the_current_optional_device_local_head() {
    let root = folderbase();
    let receipt = attest_folderbase_root(root.path()).expect("root receipt");
    fs::create_dir_all(root.path().join(".folderbase/local")).expect("local state");
    fs::write(
        root.path().join(".folderbase/local/head.json"),
        serde_json::to_vec_pretty(&serde_json::json!({
            "format": "folderbase-local-head-v1",
            "folderbase_id": FOLDERBASE_ID,
            "root_instance_sha256": receipt.root_instance_sha256,
            "version_id": "fbversion_0198ee40-a111-7aaa-8000-000000000001",
            "version_sha256": "a".repeat(64),
            "transaction_sha256": "d".repeat(64)
        }))
        .expect("head JSON"),
    )
    .expect("local head");

    let plan = FolderbaseVersionStore::open(root.path())
        .expect("open")
        .plan_capture()
        .expect("plan with current local head");
    let head = plan.current_local_head().expect("observed head");
    assert_eq!(
        head.version_id(),
        "fbversion_0198ee40-a111-7aaa-8000-000000000001"
    );
    assert_eq!(head.version_sha256(), "a".repeat(64));
}

#[cfg(unix)]
#[test]
fn local_head_never_follows_an_intermediate_state_symlink() {
    let root = folderbase();
    let receipt = attest_folderbase_root(root.path()).expect("root receipt");
    let outside = tempdir().expect("outside local state");
    fs::write(
        outside.path().join("head.json"),
        serde_json::to_vec(&serde_json::json!({
            "format": "folderbase-local-head-v1",
            "folderbase_id": FOLDERBASE_ID,
            "root_instance_sha256": receipt.root_instance_sha256,
            "version_id": "fbversion_0198ee40-a111-7aaa-8000-000000000001",
            "version_sha256": "c".repeat(64),
            "transaction_sha256": "e".repeat(64)
        }))
        .expect("head JSON"),
    )
    .expect("outside head");
    std::os::unix::fs::symlink(outside.path(), root.path().join(".folderbase/local"))
        .expect("intermediate state symlink");

    assert!(FolderbaseVersionStore::open(root.path()).is_err());
}

#[test]
fn capture_inventory_enforces_the_folderbase_version_entry_bound() {
    let root = folderbase();
    for index in 0..(MAX_CAPTURE_PLAN_RECORDS - 1) {
        fs::create_dir(root.path().join(format!("d{index:05}"))).expect("bounded directory");
    }

    assert!(matches!(
        FolderbaseVersionStore::open(root.path())
            .expect("open")
            .plan_capture(),
        Err(FolderbaseCaptureError::InventoryLimitExceeded {
            limit: CapturePlanLimitKind::Entries,
            maximum,
            ..
        }) if maximum == MAX_CAPTURE_PLAN_RECORDS as u64
    ));
}

#[cfg(unix)]
#[test]
fn hard_links_and_special_nodes_are_typed_exclusions_instead_of_silent_loss() {
    use std::{ffi::CString, os::unix::ffi::OsStrExt};

    let root = folderbase();
    fs::write(root.path().join("original.bin"), "same inode").expect("regular file");
    fs::hard_link(
        root.path().join("original.bin"),
        root.path().join("alias.bin"),
    )
    .expect("hard link");
    let fifo = root.path().join("events.fifo");
    let fifo_path = CString::new(fifo.as_os_str().as_bytes()).expect("FIFO path");
    assert_eq!(unsafe { libc::mkfifo(fifo_path.as_ptr(), 0o600) }, 0);

    let plan = FolderbaseVersionStore::open(root.path())
        .expect("open")
        .plan_capture()
        .expect("typed unsupported nodes");
    assert!(
        !plan
            .entries()
            .iter()
            .any(|entry| matches!(entry.path(), "original.bin" | "alias.bin" | "events.fifo"))
    );
    let observed = plan
        .exclusions()
        .iter()
        .map(|entry| (entry.path(), entry.kind(), entry.reason()))
        .collect::<Vec<_>>();
    assert_eq!(
        observed,
        vec![
            (
                "alias.bin",
                CaptureExclusionKind::HardLink,
                CaptureExclusionReason::UnsupportedV1,
            ),
            (
                "events.fifo",
                CaptureExclusionKind::Fifo,
                CaptureExclusionReason::UnsupportedV1,
            ),
            (
                "original.bin",
                CaptureExclusionKind::HardLink,
                CaptureExclusionReason::UnsupportedV1,
            ),
        ]
    );
}

#[cfg(unix)]
#[test]
fn symlink_metadata_preserves_a_safe_exact_target_and_rejects_escape() {
    use std::os::unix::fs::symlink;

    let root = folderbase();
    fs::create_dir_all(root.path().join("docs")).expect("docs");
    fs::write(root.path().join("docs/readme.md"), "opaque").expect("target");
    fs::create_dir(root.path().join("links")).expect("links");
    symlink("../docs/readme.md", root.path().join("links/readme")).expect("safe link");

    let plan = FolderbaseVersionStore::open(root.path())
        .expect("open")
        .plan_capture()
        .expect("safe link metadata");
    let link = plan
        .entries()
        .iter()
        .find(|entry| entry.path() == "links/readme")
        .expect("link entry");
    assert_eq!(link.kind(), CaptureEntryKind::Symlink);
    assert_eq!(link.symlink_target(), Some("../docs/readme.md"));

    symlink("../../outside", root.path().join("links/escape")).expect("unsafe link");
    assert!(matches!(
        FolderbaseVersionStore::open(root.path())
            .expect("reopen")
            .plan_capture(),
        Err(FolderbaseCaptureError::UnsafeSymlinkTarget(path))
            if path == Path::new("links/escape")
    ));
}

#[test]
fn in_scope_paths_fail_closed_when_the_portable_depth_limit_is_exceeded() {
    let root = folderbase();
    let too_deep = std::iter::repeat_n("d", 129).collect::<Vec<_>>().join("/");
    fs::create_dir_all(root.path().join(&too_deep)).expect("deep tree");

    assert!(matches!(
        FolderbaseVersionStore::open(root.path())
            .expect("open")
            .plan_capture(),
        Err(FolderbaseCaptureError::UnsafePortablePath(path))
            if path.components().count() == 129
    ));
}

#[test]
fn portable_depth_refusal_does_not_depend_on_native_thread_stack_size() {
    let root = folderbase();
    let too_deep = std::iter::repeat_n("d", 129).collect::<Vec<_>>().join("/");
    fs::create_dir_all(root.path().join(&too_deep)).expect("deep tree");
    let root_path = root.path().to_path_buf();

    let result = std::thread::Builder::new()
        .name("bounded-capture-depth".to_owned())
        .stack_size(256 * 1024)
        .spawn(move || {
            FolderbaseVersionStore::open(&root_path)
                .expect("open")
                .plan_capture()
        })
        .expect("spawn bounded-stack capture planner")
        .join()
        .expect("capture planner must return a typed result without stack overflow");

    assert!(matches!(
        result,
        Err(FolderbaseCaptureError::UnsafePortablePath(path))
            if path.components().count() == 129
    ));
}

#[cfg(target_os = "linux")]
#[test]
fn in_scope_paths_fail_closed_on_non_utf8_and_portable_case_collisions() {
    use std::{ffi::OsString, os::unix::ffi::OsStringExt};

    let non_utf8 = folderbase();
    fs::write(
        non_utf8
            .path()
            .join(OsString::from_vec(vec![0xff, b'.', b'b', b'i', b'n'])),
        "opaque",
    )
    .expect("non-UTF-8 path");
    assert!(matches!(
        FolderbaseVersionStore::open(non_utf8.path())
            .expect("open")
            .plan_capture(),
        Err(FolderbaseCaptureError::UnsafePortablePath(_))
    ));

    let collision = folderbase();
    fs::write(collision.path().join("Readme.md"), "one").expect("first case");
    fs::write(collision.path().join("README.md"), "two").expect("second case");
    assert!(matches!(
        FolderbaseVersionStore::open(collision.path())
            .expect("open")
            .plan_capture(),
        Err(FolderbaseCaptureError::PortablePathCollision { .. })
    ));
}

#[test]
fn required_ignore_marker_and_capture_policy_validation_fail_closed() {
    let missing = folderbase();
    fs::remove_file(missing.path().join(".folderbaseignore")).expect("remove marker");
    assert!(matches!(
        FolderbaseVersionStore::open(missing.path()),
        Err(FolderbaseCaptureError::RequiredMarker(path))
            if path.ends_with(".folderbaseignore")
    ));

    let oversized = folderbase();
    let policy = fs::File::options()
        .write(true)
        .open(oversized.path().join(".folderbaseignore"))
        .expect("policy");
    policy
        .set_len(folderbase_core::MAX_FOLDERBASEIGNORE_BYTES + 1)
        .expect("oversized policy");
    assert!(matches!(
        FolderbaseVersionStore::open(oversized.path())
            .expect("marker is present")
            .plan_capture(),
        Err(FolderbaseCaptureError::IgnorePolicyTooLarge { maximum_bytes })
            if maximum_bytes == folderbase_core::MAX_FOLDERBASEIGNORE_BYTES
    ));

    let invalid = folderbase();
    fs::write(invalid.path().join(".folderbaseignore"), "{a,b\n").expect("invalid ignore policy");
    assert!(matches!(
        FolderbaseVersionStore::open(invalid.path())
            .expect("marker is present")
            .plan_capture(),
        Err(FolderbaseCaptureError::InvalidIgnorePolicy(_))
    ));
}

#[cfg(unix)]
#[test]
fn required_visible_markers_cannot_be_downgraded_to_hard_link_exclusions() {
    let root = folderbase();
    fs::hard_link(
        root.path().join(".folderbaseignore"),
        root.path().join("ignore-policy.backup"),
    )
    .expect("hard-linked required marker");

    assert!(matches!(
        FolderbaseVersionStore::open(root.path())
            .expect("regular marker opens")
            .plan_capture(),
        Err(FolderbaseCaptureError::RequiredMarker(path))
            if path.ends_with(".folderbaseignore")
    ));
}

#[test]
fn local_head_from_another_physical_root_is_rejected() {
    let source = folderbase();
    let destination = folderbase();
    let receipt = attest_folderbase_root(source.path()).expect("source root");
    fs::create_dir_all(destination.path().join(".folderbase/local")).expect("local state");
    fs::write(
        destination.path().join(".folderbase/local/head.json"),
        serde_json::to_vec(&serde_json::json!({
            "format": "folderbase-local-head-v1",
            "folderbase_id": FOLDERBASE_ID,
            "root_instance_sha256": receipt.root_instance_sha256,
            "version_id": "fbversion_0198ee40-a111-7aaa-8000-000000000001",
            "version_sha256": "b".repeat(64),
            "transaction_sha256": "f".repeat(64)
        }))
        .expect("head JSON"),
    )
    .expect("foreign head");

    assert!(matches!(
        FolderbaseVersionStore::open(destination.path()),
        Err(FolderbaseCaptureError::InvalidLocalHead(message))
            if message.contains("attested physical Folderbase Root")
    ));
}

#[test]
fn public_capture_fails_closed_at_the_shared_boundary_work_ceiling() {
    const EXPECTED_SHARED_WORK_CEILING: usize = 16_384;

    let root = folderbase();
    let crowded = root.path().join("crowded");
    fs::create_dir(&crowded).expect("crowded directory");
    for index in 0..=EXPECTED_SHARED_WORK_CEILING {
        fs::write(crowded.join(format!("entry-{index:05}")), b"").expect("ordinary entry");
    }

    let error = FolderbaseVersionStore::open(root.path())
        .expect("open Folderbase")
        .plan_capture()
        .expect_err("shared classifier work must be bounded");
    assert!(
        error
            .to_string()
            .contains("nested Folderbase boundary inspection exceeded"),
        "public callers must inherit the shared classifier's hard work ceiling, got: {error}"
    );
}

fn state_paths(root: &Path) -> Vec<String> {
    let mut paths = walkdir::WalkDir::new(root.join(".folderbase"))
        .into_iter()
        .map(|entry| {
            entry
                .expect("state entry")
                .path()
                .strip_prefix(root)
                .expect("relative state")
                .to_string_lossy()
                .into_owned()
        })
        .collect::<Vec<_>>();
    paths.sort();
    paths
}