folderbase-core 0.7.1

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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::io::ErrorKind;
use std::path::{Component, Path, PathBuf};

use cap_std::fs::Dir;
use chrono::{DateTime, Utc};
use semver::Version;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use unicode_casefold::UnicodeCaseFold;
use unicode_normalization::UnicodeNormalization;
use uuid::Uuid;

use crate::initialization::{
    canonical_directory, create_directory_no_clobber, ensure_safe_relative,
    install_text_no_clobber, refuse_symlink_root, sha256_reader, validate_template_path_collisions,
};
use crate::model::{AppliedTemplate, TemplateApplicationComparison, TemplateExpansionPrecondition};
use crate::physical_identity::{PhysicalIdentity, RetainedPhysicalIdentity};
use crate::template::{
    render_template_for_capability_destination, template_package_sha256, validate_runtime_package,
};
use crate::{
    FolderbaseError, PlannedTemplateAddition, Result, TemplateAnswerValue,
    TemplateApplicationCreatedPath, TemplateApplicationRecord, TemplateApplicationResult,
    TemplateApplicationState, TemplateArtifactKind, TemplateComparisonSource,
    TemplateExpansionPlan, TemplatePackage, TemplatePlanDigest, TemplateStructuralChange,
    TemplateStructuralChangeKind, attest_folderbase_root,
};
use crate::{
    folderbase_state::{FolderbaseState, WorkspaceTarget},
    local_versions::LocalVersionStore,
};

const MANIFEST: &str = ".folderbase/manifest.json";
const APPLICATIONS: &str = ".folderbase/template-applications";
const APPLICATION_SCHEMA: &str =
    "https://folderbase.ai/protocol/0.2/template-application.schema.json";
const MAX_TEMPLATE_HISTORY_RECORDS: usize = 4096;
const MAX_TEMPLATE_APPLICATION_BYTES: u64 = 4 * 1024 * 1024;
const MAX_TEMPLATE_PATH_ENTRY_WORK: usize = 100_000;
const MAX_TEMPLATE_PRESERVED_HASH_BYTES: u64 = 1024 * 1024;

pub fn plan_template_expansion(
    root: impl AsRef<Path>,
    target: &TemplatePackage,
    answers: &BTreeMap<String, TemplateAnswerValue>,
) -> Result<TemplateExpansionPlan> {
    refuse_symlink_root(root.as_ref())?;
    let root = canonical_directory(root.as_ref())?;
    validate_folderbase_root(&root)?;
    let state = FolderbaseState::open_existing_read_only(&root)?;
    plan_template_expansion_in_state(&state, target, answers)
}

fn plan_template_expansion_in_state(
    state: &FolderbaseState,
    target: &TemplatePackage,
    answers: &BTreeMap<String, TemplateAnswerValue>,
) -> Result<TemplateExpansionPlan> {
    state.classify_attached_root_boundary().map(drop)?;
    let root = state.display_root().to_path_buf();
    validate_runtime_package(&root, target)?;

    let root_identity =
        RetainedPhysicalIdentity::from_file(state.clone_root_capability()?.into_std_file())
            .map_err(|source| FolderbaseError::io(&root, source))?;
    let root_identity_sha256 = root_identity.identity().stable_sha256();
    let manifest_path = root.join(MANIFEST);
    let manifest_bytes = state
        .read_bounded(Path::new(MANIFEST), 2 * 1024 * 1024)?
        .ok_or_else(|| FolderbaseError::InvalidRecord {
            path: manifest_path.clone(),
            message: "Folderbase manifest is missing".to_owned(),
        })?;
    let manifest_sha256 = sha256_bytes(&manifest_bytes);
    let manifest: Value = serde_json::from_slice(&manifest_bytes)
        .map_err(|source| FolderbaseError::json(&manifest_path, source))?;
    let folderbase_id =
        required_string(&manifest, &["folderbase", "id"], &manifest_path)?.to_owned();

    let (history, history_sha256) =
        read_history_with_snapshot_in_state(state, Some(&folderbase_id))?;
    validate_application_history_chain(&manifest, &history, &manifest_path)?;
    let package_digest = TemplatePlanDigest {
        algorithm: "sha256".to_owned(),
        digest: template_package_sha256(target)?,
    };
    let comparison = derive_comparison(&manifest, &history, target.id(), &manifest_path)?;

    if comparison.template_id != target.id() {
        return build_plan(
            root,
            root_identity,
            root_identity_sha256,
            folderbase_id,
            target,
            package_digest,
            comparison,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            vec![TemplateStructuralChange {
                kind: TemplateStructuralChangeKind::Lineage,
                path: None,
                reason: format!(
                    "template lineage changes from {} to {}",
                    manifest
                        .pointer("/folderbase/template_provenance/id")
                        .and_then(Value::as_str)
                        .unwrap_or("unknown"),
                    target.id()
                ),
            }],
            manifest_sha256,
            history_sha256,
        );
    }

    if comparison.version == target.version() {
        if comparison.package_digest.digest != package_digest.digest {
            return Err(FolderbaseError::InvalidRecord {
                path: root,
                message: format!(
                    "same template version {} has a different package digest",
                    target.version()
                ),
            });
        }
        return build_plan(
            root,
            root_identity,
            root_identity_sha256,
            folderbase_id,
            target,
            package_digest,
            comparison,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            Vec::new(),
            manifest_sha256,
            history_sha256,
        );
    }

    let comparison_version =
        Version::parse(&comparison.version).map_err(|_| FolderbaseError::InvalidRecord {
            path: manifest_path.clone(),
            message: format!(
                "invalid comparison template version: {}",
                comparison.version
            ),
        })?;
    let target_version =
        Version::parse(target.version()).map_err(|_| FolderbaseError::InvalidRecord {
            path: root.clone(),
            message: format!("invalid target template version: {}", target.version()),
        })?;

    let mut structural_changes = Vec::new();
    if target_version < comparison_version {
        structural_changes.push(TemplateStructuralChange {
            kind: TemplateStructuralChangeKind::Downgrade,
            path: None,
            reason: format!(
                "template downgrade {} -> {}",
                comparison.version,
                target.version()
            ),
        });
    } else if comparison.source != TemplateComparisonSource::Unmanaged
        && !target
            .upgrade_edges
            .iter()
            .any(|edge| edge.from == comparison.version && edge.to == target.version())
    {
        structural_changes.push(TemplateStructuralChange {
            kind: TemplateStructuralChangeKind::UnsupportedTransition,
            path: None,
            reason: format!(
                "template does not declare an additive edge {} -> {}",
                comparison.version,
                target.version()
            ),
        });
    }

    if !structural_changes.is_empty() {
        return build_plan(
            root,
            root_identity,
            root_identity_sha256,
            folderbase_id,
            target,
            package_digest,
            comparison,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            structural_changes,
            manifest_sha256,
            history_sha256,
        );
    }

    validate_template_paths_against_existing_in_state(
        state,
        target
            .artifacts
            .iter()
            .map(|artifact| artifact.target.as_path()),
        true,
    )?;
    let rendered = render_template_for_capability_destination(target, &root, answers)?;
    let mut rendered = rendered
        .additions
        .into_iter()
        .map(|addition| (addition.path.clone(), addition))
        .collect::<BTreeMap<_, _>>();
    let mut additions = Vec::new();
    let mut preserved_paths = Vec::new();
    let mut preserved_preconditions = Vec::new();
    let mut blocked_paths = Vec::new();
    for artifact in &target.artifacts {
        match open_template_target(state, &artifact.target)? {
            WorkspaceTarget::Absent => additions.push(
                rendered
                    .remove(&artifact.target)
                    .expect("capability renderer returned every validated artifact"),
            ),
            WorkspaceTarget::Directory(directory) => {
                if artifact.kind != TemplateArtifactKind::Directory {
                    blocked_paths.push(artifact.target.clone());
                    continue;
                }
                let identity = RetainedPhysicalIdentity::from_file(directory.into_std_file())
                    .map_err(|source| FolderbaseError::io(root.join(&artifact.target), source))?;
                preserved_paths.push(artifact.target.clone());
                preserved_preconditions.push(TemplateExpansionPrecondition {
                    path: artifact.target.clone(),
                    kind: artifact.kind,
                    sha256: None,
                    identity,
                });
            }
            WorkspaceTarget::RegularFile(file) => {
                if artifact.kind != TemplateArtifactKind::Text {
                    blocked_paths.push(artifact.target.clone());
                    continue;
                }
                let mut file = file.into_std();
                let metadata = file
                    .metadata()
                    .map_err(|source| FolderbaseError::io(root.join(&artifact.target), source))?;
                if metadata.len() > MAX_TEMPLATE_PRESERVED_HASH_BYTES {
                    blocked_paths.push(artifact.target.clone());
                    continue;
                }
                let sha256 = sha256_reader(&mut file)
                    .map_err(|source| FolderbaseError::io(root.join(&artifact.target), source))?;
                let identity = RetainedPhysicalIdentity::from_file(file)
                    .map_err(|source| FolderbaseError::io(root.join(&artifact.target), source))?;
                preserved_paths.push(artifact.target.clone());
                preserved_preconditions.push(TemplateExpansionPrecondition {
                    path: artifact.target.clone(),
                    kind: artifact.kind,
                    sha256: Some(sha256),
                    identity,
                });
            }
        }
    }
    add_missing_parent_directories_in_state(state, &mut additions)?;
    validate_template_path_collisions(
        &root,
        additions.iter().map(|addition| {
            (
                addition.path.as_path(),
                addition.kind == TemplateArtifactKind::Directory,
            )
        }),
    )?;
    additions.sort_by(|left, right| left.path.cmp(&right.path));
    additions.dedup_by(|left, right| left.path == right.path);

    preserved_paths.sort();
    preserved_preconditions.sort_by(|left, right| left.path.cmp(&right.path));
    blocked_paths.sort();
    state.classify_attached_root_boundary().map(drop)?;

    build_plan(
        root,
        root_identity,
        root_identity_sha256,
        folderbase_id,
        target,
        package_digest,
        comparison,
        additions,
        preserved_paths,
        blocked_paths,
        structural_changes,
        manifest_sha256,
        history_sha256,
    )
    .map(|mut plan| {
        plan.preserved_preconditions = preserved_preconditions;
        plan.plan_digest = digest_plan(&plan);
        plan
    })
}

pub fn apply_template_expansion(plan: &TemplateExpansionPlan) -> Result<TemplateApplicationResult> {
    let state = FolderbaseState::open_existing(&plan.root)?;
    let _lease = LocalVersionStore::acquire_transaction_lock_for_state(&plan.root, &state)?;
    apply_template_expansion_in_state(&state, plan)
}

fn apply_template_expansion_in_state(
    state: &FolderbaseState,
    plan: &TemplateExpansionPlan,
) -> Result<TemplateApplicationResult> {
    if !plan.structural_changes.is_empty() {
        return Err(FolderbaseError::StructuralTemplateChangeRequiresApproval);
    }
    if !plan.blocked_paths.is_empty() {
        return Err(FolderbaseError::TemplateExpansionBlocked);
    }

    let root = state.display_root().to_path_buf();
    state
        .verify_root_identity(&plan.root_identity.identity())
        .map_err(|_| FolderbaseError::PlanRootIdentityChanged(root.clone()))?;

    let manifest_bytes = state
        .read_bounded(Path::new(MANIFEST), 2 * 1024 * 1024)?
        .ok_or_else(|| FolderbaseError::PlanPreconditionChanged(PathBuf::from(MANIFEST)))?;
    if sha256_bytes(&manifest_bytes) != plan.manifest_sha256 {
        return Err(FolderbaseError::PlanPreconditionChanged(PathBuf::from(
            MANIFEST,
        )));
    }
    let (_, history_sha256) =
        read_history_with_snapshot_in_state(state, Some(&plan.folderbase_id))?;
    if history_sha256 != plan.history_sha256 {
        return Err(FolderbaseError::PlanPreconditionChanged(PathBuf::from(
            APPLICATIONS,
        )));
    }
    validate_template_paths_against_existing_in_state(
        state,
        plan.additions
            .iter()
            .map(|addition| addition.path.as_path())
            .chain(plan.preserved_paths.iter().map(PathBuf::as_path)),
        true,
    )?;
    verify_preserved_preconditions_in_state(state, plan)?;
    verify_additions_absent_in_state(state, plan)?;

    if plan.is_noop() {
        return Ok(TemplateApplicationResult {
            created_paths: Vec::new(),
            preserved_paths: Vec::new(),
            application_record: None,
        });
    }

    let root_dir = state.clone_root_capability()?;
    let mut ordered = plan.additions.iter().collect::<Vec<_>>();
    ordered.sort_by(|left, right| {
        let left_directory = left.kind == TemplateArtifactKind::Directory;
        let right_directory = right.kind == TemplateArtifactKind::Directory;
        right_directory
            .cmp(&left_directory)
            .then_with(|| {
                left.path
                    .components()
                    .count()
                    .cmp(&right.path.components().count())
            })
            .then_with(|| left.path.cmp(&right.path))
    });

    for addition in &ordered {
        match addition.kind {
            TemplateArtifactKind::Directory => {
                create_directory_no_clobber(&root_dir, &root, &addition.path)?;
            }
            TemplateArtifactKind::Text => {
                install_text_no_clobber(
                    &root_dir,
                    &root,
                    &addition.path,
                    addition.content.as_deref().unwrap_or_default().as_bytes(),
                    "template-expansion",
                )?;
            }
        }
    }

    let created_paths = verify_created_additions_in_state(state, &plan.additions)?;
    verify_preserved_preconditions_in_state(state, plan)?;
    let preserved_targets = materialize_preserved_targets_in_state(state, plan)?;

    let application_id = format!("template_application_{}", Uuid::now_v7());
    let mut record = TemplateApplicationRecord {
        schema: APPLICATION_SCHEMA.to_owned(),
        protocol_version: "0.2.0".to_owned(),
        id: application_id.clone(),
        folderbase_id: plan.folderbase_id.clone(),
        state: TemplateApplicationState::Verified,
        template: AppliedTemplate {
            id: plan.template_id.clone(),
            version: plan.template_version.clone(),
            package_digest: plan.template_package_digest.clone(),
        },
        comparison: TemplateApplicationComparison {
            source: plan.comparison_source,
            version: plan.comparison_version.clone(),
            application_id: plan.comparison_application_id.clone(),
        },
        applied_at: Utc::now().to_rfc3339(),
        created_paths,
        preserved_targets,
        plan_digest: plan.plan_digest.clone(),
        record_digest: TemplatePlanDigest {
            algorithm: "sha256".to_owned(),
            digest: String::new(),
        },
    };
    record.record_digest = digest_application_record(&record);
    validate_application_record(&record, Some(&plan.folderbase_id), &root)?;

    ensure_history_directory_in_state(state, &root_dir)?;
    let record_path = PathBuf::from(APPLICATIONS).join(format!("{application_id}.json"));
    let mut bytes = serde_json::to_vec_pretty(&record)
        .map_err(|source| FolderbaseError::json(root.join(&record_path), source))?;
    bytes.push(b'\n');
    install_text_no_clobber(
        &root_dir,
        &root,
        &record_path,
        &bytes,
        "template-application",
    )?;
    let installed_bytes = state
        .read_bounded(&record_path, MAX_TEMPLATE_APPLICATION_BYTES)?
        .ok_or_else(|| FolderbaseError::InvalidRecord {
            path: root.join(&record_path),
            message: "installed template application record is missing".to_owned(),
        })?;
    let installed: TemplateApplicationRecord = serde_json::from_slice(&installed_bytes)
        .map_err(|source| FolderbaseError::json(root.join(&record_path), source))?;
    validate_application_record(&installed, Some(&plan.folderbase_id), &root)?;
    if installed != record {
        return Err(FolderbaseError::InvalidRecord {
            path: root.join(&record_path),
            message: "installed template application record failed verification".to_owned(),
        });
    }

    Ok(TemplateApplicationResult {
        created_paths: plan
            .additions
            .iter()
            .map(|addition| addition.path.clone())
            .collect(),
        preserved_paths: plan.preserved_paths.clone(),
        application_record: Some(record_path),
    })
}

/// Re-plan and apply one exact data-only template package under Folderbase's
/// shared transaction lease.
///
/// The caller supplies only the reviewed digest, never a deserialized plan.
/// Core derives the live plan again after the lease is held and fails before
/// any template write when it no longer matches the approval.
pub fn apply_template_expansion_with_expected_plan_digest(
    root: impl AsRef<Path>,
    target: &TemplatePackage,
    answers: &BTreeMap<String, TemplateAnswerValue>,
    expected_plan_digest: &str,
) -> Result<(TemplateExpansionPlan, TemplateApplicationResult)> {
    apply_template_expansion_with_expected_plan_digest_and_hook(
        root,
        target,
        answers,
        expected_plan_digest,
        || {},
    )
}

fn apply_template_expansion_with_expected_plan_digest_and_hook(
    root: impl AsRef<Path>,
    target: &TemplatePackage,
    answers: &BTreeMap<String, TemplateAnswerValue>,
    expected_plan_digest: &str,
    after_lease: impl FnOnce(),
) -> Result<(TemplateExpansionPlan, TemplateApplicationResult)> {
    if expected_plan_digest.len() != 64
        || !expected_plan_digest
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
    {
        return Err(FolderbaseError::InvalidTemplateExpansionPlanDigest);
    }

    let state = FolderbaseState::open_existing(root.as_ref())?;
    let _lease = LocalVersionStore::acquire_transaction_lock_for_state(root.as_ref(), &state)?;
    after_lease();
    state.classify_attached_root_boundary().map(drop)?;
    let plan = plan_template_expansion_in_state(&state, target, answers)?;
    state.classify_attached_root_boundary().map(drop)?;
    if plan.plan_digest.digest != expected_plan_digest {
        return Err(FolderbaseError::TemplateExpansionPlanChanged {
            expected: expected_plan_digest.to_owned(),
            actual: plan.plan_digest.digest.clone(),
        });
    }
    let result = apply_template_expansion_in_state(&state, &plan)?;
    Ok((plan, result))
}

pub fn template_application_history(
    root: impl AsRef<Path>,
) -> Result<Vec<TemplateApplicationRecord>> {
    refuse_symlink_root(root.as_ref())?;
    let root = canonical_directory(root.as_ref())?;
    validate_folderbase_root(&root)?;
    let manifest_path = root.join(MANIFEST);
    let manifest: Value = serde_json::from_slice(
        &fs::read(&manifest_path).map_err(|source| FolderbaseError::io(&manifest_path, source))?,
    )
    .map_err(|source| FolderbaseError::json(&manifest_path, source))?;
    let folderbase_id = required_string(&manifest, &["folderbase", "id"], &manifest_path)?;
    let (history, _) = read_history_with_snapshot(&root, Some(folderbase_id))?;
    validate_application_history_chain(&manifest, &history, &manifest_path)?;
    Ok(history)
}

struct Comparison {
    template_id: String,
    version: String,
    package_digest: TemplatePlanDigest,
    source: TemplateComparisonSource,
    application_id: Option<String>,
}

fn derive_comparison(
    manifest: &Value,
    history: &[TemplateApplicationRecord],
    template_id: &str,
    manifest_path: &Path,
) -> Result<Comparison> {
    let predecessor_ids = history
        .iter()
        .filter_map(|record| record.comparison.application_id.as_deref())
        .collect::<BTreeSet<_>>();
    let terminals = history
        .iter()
        .filter(|record| {
            record.template.id == template_id && !predecessor_ids.contains(record.id.as_str())
        })
        .collect::<Vec<_>>();
    match terminals.as_slice() {
        [record] => {
            return Ok(Comparison {
                template_id: record.template.id.clone(),
                version: record.template.version.clone(),
                package_digest: record.template.package_digest.clone(),
                source: TemplateComparisonSource::Application,
                application_id: Some(record.id.clone()),
            });
        }
        [] if history
            .iter()
            .all(|record| record.template.id != template_id) => {}
        _ => {
            return Err(FolderbaseError::InvalidRecord {
                path: manifest_path.to_path_buf(),
                message: format!(
                    "template application history does not have one terminal for {template_id}"
                ),
            });
        }
    }

    let Some(provenance) = manifest
        .pointer("/folderbase/template_provenance")
        .and_then(Value::as_object)
    else {
        if history.is_empty() {
            require_native_unmanaged_lineage(manifest, manifest_path)?;
            return Ok(Comparison {
                template_id: template_id.to_owned(),
                version: "0.0.0".to_owned(),
                package_digest: TemplatePlanDigest {
                    algorithm: "sha256".to_owned(),
                    digest: format!(
                        "{:x}",
                        Sha256::digest(b"folderbase-unmanaged-template-origin-v1\0")
                    ),
                },
                source: TemplateComparisonSource::Unmanaged,
                application_id: None,
            });
        }
        let predecessor_ids = history
            .iter()
            .filter_map(|record| record.comparison.application_id.as_deref())
            .collect::<BTreeSet<_>>();
        let terminals = history
            .iter()
            .filter(|record| !predecessor_ids.contains(record.id.as_str()))
            .collect::<Vec<_>>();
        if let [record] = terminals.as_slice() {
            return Ok(Comparison {
                template_id: record.template.id.clone(),
                version: record.template.version.clone(),
                package_digest: record.template.package_digest.clone(),
                source: TemplateComparisonSource::Application,
                application_id: Some(record.id.clone()),
            });
        }
        return Err(FolderbaseError::InvalidRecord {
            path: manifest_path.to_path_buf(),
            message: "template history has no immutable origin".to_owned(),
        });
    };
    let origin_id = provenance
        .get("id")
        .and_then(Value::as_str)
        .ok_or_else(|| FolderbaseError::InvalidRecord {
            path: manifest_path.to_path_buf(),
            message: "template origin is missing id".to_owned(),
        })?;
    let version = provenance
        .get("version")
        .and_then(Value::as_str)
        .ok_or_else(|| FolderbaseError::InvalidRecord {
            path: manifest_path.to_path_buf(),
            message: "template origin is missing version".to_owned(),
        })?;
    let package_digest =
        provenance
            .get("package_digest")
            .ok_or_else(|| FolderbaseError::InvalidRecord {
                path: manifest_path.to_path_buf(),
                message: "template origin is missing package digest".to_owned(),
            })?;
    let package_digest: TemplatePlanDigest = serde_json::from_value(package_digest.clone())
        .map_err(|source| FolderbaseError::json(manifest_path, source))?;
    validate_digest(&package_digest, manifest_path)?;
    Ok(Comparison {
        template_id: origin_id.to_owned(),
        version: version.to_owned(),
        package_digest,
        source: TemplateComparisonSource::Origin,
        application_id: None,
    })
}

fn validate_application_history_chain(
    manifest: &Value,
    history: &[TemplateApplicationRecord],
    manifest_path: &Path,
) -> Result<()> {
    if history.is_empty() {
        return Ok(());
    }

    let provenance = manifest
        .pointer("/folderbase/template_provenance")
        .and_then(Value::as_object);
    let origin = provenance
        .map(|_| {
            Ok::<_, FolderbaseError>((
                required_string(
                    manifest,
                    &["folderbase", "template_provenance", "id"],
                    manifest_path,
                )?,
                required_string(
                    manifest,
                    &["folderbase", "template_provenance", "version"],
                    manifest_path,
                )?,
            ))
        })
        .transpose()?;
    let records_by_id = history
        .iter()
        .map(|record| (record.id.as_str(), record))
        .collect::<BTreeMap<_, _>>();
    let mut origin_roots = BTreeSet::new();
    let mut predecessor_ids = BTreeSet::new();

    for record in history {
        let target_version =
            Version::parse(&record.template.version).expect("validated application version");
        let comparison_version =
            Version::parse(&record.comparison.version).expect("validated comparison version");
        if target_version <= comparison_version {
            return Err(FolderbaseError::InvalidRecord {
                path: manifest_path.to_path_buf(),
                message: format!(
                    "template application {} does not advance its comparison version",
                    record.id
                ),
            });
        }

        match record.comparison.source {
            TemplateComparisonSource::Unmanaged => {
                if !manifest_is_native_v05(manifest)
                    || provenance.is_some()
                    || record.comparison.version != "0.0.0"
                    || !origin_roots.insert(record.template.id.as_str())
                {
                    return Err(FolderbaseError::InvalidRecord {
                        path: manifest_path.to_path_buf(),
                        message: if !manifest_is_native_v05(manifest) {
                            "unmanaged template lineage requires native protocol 0.5.0".to_owned()
                        } else {
                            format!(
                                "template application {} has invalid unmanaged origin",
                                record.id
                            )
                        },
                    });
                }
            }
            TemplateComparisonSource::Origin => {
                if let Some((origin_id, origin_version)) = origin {
                    if record.template.id != origin_id
                        || record.comparison.version != origin_version
                    {
                        return Err(FolderbaseError::InvalidRecord {
                            path: manifest_path.to_path_buf(),
                            message: format!(
                                "template application {} does not extend the active template origin",
                                record.id
                            ),
                        });
                    }
                } else {
                    return Err(FolderbaseError::InvalidRecord {
                        path: manifest_path.to_path_buf(),
                        message: format!(
                            "template application {} claims a missing manifest origin",
                            record.id
                        ),
                    });
                }
                if !origin_roots.insert(record.template.id.as_str()) {
                    return Err(FolderbaseError::InvalidRecord {
                        path: manifest_path.to_path_buf(),
                        message: format!(
                            "template application history has multiple origin roots for {}",
                            record.template.id
                        ),
                    });
                }
            }
            TemplateComparisonSource::Application => {
                let predecessor_id = record
                    .comparison
                    .application_id
                    .as_deref()
                    .expect("validated application comparison id");
                let predecessor = records_by_id.get(predecessor_id).ok_or_else(|| {
                    FolderbaseError::InvalidRecord {
                        path: manifest_path.to_path_buf(),
                        message: format!("comparison application does not exist: {predecessor_id}"),
                    }
                })?;
                if predecessor.folderbase_id != record.folderbase_id
                    || predecessor.template.id != record.template.id
                    || predecessor.template.version != record.comparison.version
                {
                    return Err(FolderbaseError::InvalidRecord {
                        path: manifest_path.to_path_buf(),
                        message: format!(
                            "comparison application does not match {} template lineage and version",
                            record.id
                        ),
                    });
                }
                if parsed_application_time(predecessor) > parsed_application_time(record) {
                    return Err(FolderbaseError::InvalidRecord {
                        path: manifest_path.to_path_buf(),
                        message: format!("comparison application does not precede {}", record.id),
                    });
                }
                if !predecessor_ids.insert(predecessor_id) {
                    return Err(FolderbaseError::InvalidRecord {
                        path: manifest_path.to_path_buf(),
                        message: format!("template application history forks at {predecessor_id}"),
                    });
                }
            }
        }
    }

    Ok(())
}

fn require_native_unmanaged_lineage(manifest: &Value, manifest_path: &Path) -> Result<()> {
    if manifest_is_native_v05(manifest) {
        return Ok(());
    }
    Err(FolderbaseError::InvalidRecord {
        path: manifest_path.to_path_buf(),
        message: "unmanaged template lineage requires native protocol 0.5.0".to_owned(),
    })
}

fn manifest_is_native_v05(manifest: &Value) -> bool {
    manifest.get("protocol_version").and_then(Value::as_str) == Some("0.5.0")
}

#[allow(clippy::too_many_arguments)]
fn build_plan(
    root: PathBuf,
    root_identity: RetainedPhysicalIdentity,
    root_identity_sha256: String,
    folderbase_id: String,
    target: &TemplatePackage,
    template_package_digest: TemplatePlanDigest,
    comparison: Comparison,
    additions: Vec<PlannedTemplateAddition>,
    preserved_paths: Vec<PathBuf>,
    blocked_paths: Vec<PathBuf>,
    mut structural_changes: Vec<TemplateStructuralChange>,
    manifest_sha256: String,
    history_sha256: String,
) -> Result<TemplateExpansionPlan> {
    structural_changes.sort_by(|left, right| {
        left.kind
            .cmp(&right.kind)
            .then_with(|| left.path.cmp(&right.path))
    });
    let mut plan = TemplateExpansionPlan {
        root,
        folderbase_id,
        template_id: target.id().to_owned(),
        comparison_version: comparison.version,
        comparison_source: comparison.source,
        comparison_application_id: comparison.application_id,
        comparison_package_digest: comparison.package_digest,
        template_version: target.version().to_owned(),
        template_package_digest,
        additions,
        preserved_paths,
        blocked_paths,
        structural_changes,
        plan_digest: TemplatePlanDigest {
            algorithm: "sha256".to_owned(),
            digest: String::new(),
        },
        manifest_sha256,
        history_sha256,
        preserved_preconditions: Vec::new(),
        root_identity_sha256,
        root_identity,
    };
    plan.plan_digest = digest_plan(&plan);
    Ok(plan)
}

fn digest_plan(plan: &TemplateExpansionPlan) -> TemplatePlanDigest {
    let additions = plan
        .additions
        .iter()
        .map(|addition| {
            let bytes = addition.content.as_deref().map(str::as_bytes);
            json!({
                "path": path_text(&addition.path),
                "kind": addition.kind,
                "bytes": bytes.map(|bytes| bytes.len() as u64),
                "sha256": bytes.map(sha256_bytes),
            })
        })
        .collect::<Vec<_>>();
    let preserved = plan
        .preserved_preconditions
        .iter()
        .map(|precondition| {
            json!({
                "path": path_text(&precondition.path),
                "kind": precondition.kind,
                "sha256": precondition.sha256,
            })
        })
        .collect::<Vec<_>>();
    let structural = plan
        .structural_changes
        .iter()
        .map(|change| {
            json!({
                "kind": change.kind,
                "path": change.path.as_ref().map(|path| path_text(path)),
                "reason": change.reason,
            })
        })
        .collect::<Vec<_>>();
    let dto = json!({
        "folderbase_id": plan.folderbase_id,
        "root_identity_sha256": plan.root_identity_sha256,
        "manifest_sha256": plan.manifest_sha256,
        "history_sha256": plan.history_sha256,
        "comparison": {
            "source": plan.comparison_source,
            "version": plan.comparison_version,
            "application_id": plan.comparison_application_id,
            "package_digest": plan.comparison_package_digest,
        },
        "target": {
            "id": plan.template_id,
            "version": plan.template_version,
            "package_digest": plan.template_package_digest,
        },
        "additions": additions,
        "preserved": preserved,
        "blocked": plan.blocked_paths.iter().map(|path| path_text(path)).collect::<Vec<_>>(),
        "structural": structural,
    });
    TemplatePlanDigest {
        algorithm: "sha256".to_owned(),
        digest: sha256_bytes(
            &serde_json::to_vec(&dto).expect("canonical expansion plan DTO serializes"),
        ),
    }
}

fn open_template_target(state: &FolderbaseState, path: &Path) -> Result<WorkspaceTarget> {
    if path
        .components()
        .next()
        .is_some_and(|component| component.as_os_str() == ".folderbase")
    {
        state.open_private_target_nofollow(path)
    } else {
        state.open_workspace_target_nofollow(path)
    }
}

fn template_directory_names(
    state: &FolderbaseState,
    path: &Path,
    maximum_entries: usize,
) -> Result<Vec<std::ffi::OsString>> {
    if path
        .components()
        .next()
        .is_some_and(|component| component.as_os_str() == ".folderbase")
    {
        state.private_directory_names(path, maximum_entries)
    } else {
        state.workspace_directory_names(path, maximum_entries)
    }
}

fn template_path_key(value: &str) -> String {
    value
        .nfc()
        .collect::<String>()
        .case_fold()
        .collect::<String>()
        .nfc()
        .collect()
}

fn validate_template_paths_against_existing_in_state<'a>(
    state: &FolderbaseState,
    planned_paths: impl IntoIterator<Item = &'a Path>,
    allow_exact_target: bool,
) -> Result<()> {
    let mut remaining_work = MAX_TEMPLATE_PATH_ENTRY_WORK;
    for planned in planned_paths {
        let mut parent = PathBuf::new();
        let component_count = planned.components().count();
        for (index, component) in planned.components().enumerate() {
            let Component::Normal(component) = component else {
                return Err(FolderbaseError::UnsafePath(planned.to_path_buf()));
            };
            let component_text = component
                .to_str()
                .ok_or_else(|| FolderbaseError::UnsafePath(planned.to_path_buf()))?;
            let folded = template_path_key(component_text);
            let names = template_directory_names(state, &parent, remaining_work.saturating_add(1))?;
            if names.len() > remaining_work {
                return Err(FolderbaseError::InvalidRecord {
                    path: state.display_root().to_path_buf(),
                    message: format!(
                        "template path inspection exceeds {MAX_TEMPLATE_PATH_ENTRY_WORK} directory entries"
                    ),
                });
            }
            remaining_work -= names.len();
            let mut exact = false;
            for name in names {
                let Some(name_text) = name.to_str() else {
                    continue;
                };
                if template_path_key(name_text) != folded {
                    continue;
                }
                if name == component {
                    exact = true;
                } else {
                    return Err(FolderbaseError::InvalidRecord {
                        path: state.display_root().to_path_buf(),
                        message: format!(
                            "planned path collision: {} aliases existing {}",
                            planned.display(),
                            state.display_root().join(&parent).join(name).display()
                        ),
                    });
                }
            }
            if !exact {
                break;
            }
            parent.push(component);
            if index + 1 == component_count {
                if allow_exact_target {
                    break;
                }
                return Err(FolderbaseError::WouldOverwrite(
                    state.display_root().join(planned),
                ));
            }
            if parent != Path::new(".folderbase")
                && !matches!(
                    open_template_target(state, &parent)?,
                    WorkspaceTarget::Directory(_)
                )
            {
                return Err(FolderbaseError::InvalidRecord {
                    path: state.display_root().join(&parent),
                    message: format!(
                        "planned path collision: ancestor {} is not a safe directory",
                        parent.display()
                    ),
                });
            }
        }
    }
    Ok(())
}

fn add_missing_parent_directories_in_state(
    state: &FolderbaseState,
    additions: &mut Vec<PlannedTemplateAddition>,
) -> Result<()> {
    let planned = additions
        .iter()
        .map(|addition| addition.path.clone())
        .collect::<Vec<_>>();
    let mut extra = BTreeSet::new();
    for path in planned {
        let Some(parent) = path.parent() else {
            continue;
        };
        let mut relative = PathBuf::new();
        for component in parent.components() {
            let Component::Normal(component) = component else {
                return Err(FolderbaseError::UnsafePath(path));
            };
            relative.push(component);
            if relative == Path::new(".folderbase") {
                continue;
            }
            match open_template_target(state, &relative)? {
                WorkspaceTarget::Absent => {
                    extra.insert(relative.clone());
                }
                WorkspaceTarget::Directory(_) => {}
                WorkspaceTarget::RegularFile(_) => {
                    return Err(FolderbaseError::UnsafePath(
                        state.display_root().join(&relative),
                    ));
                }
            }
        }
    }
    for path in extra {
        if additions.iter().all(|addition| addition.path != path) {
            additions.push(PlannedTemplateAddition {
                path,
                kind: TemplateArtifactKind::Directory,
                content: None,
            });
        }
    }
    Ok(())
}

fn validate_folderbase_root(root: &Path) -> Result<()> {
    attest_folderbase_root(root)
        .map(drop)
        .map_err(|source| FolderbaseError::InvalidRecord {
            path: root.join(MANIFEST),
            message: source.to_string(),
        })
}

fn verify_preserved_preconditions_in_state(
    state: &FolderbaseState,
    plan: &TemplateExpansionPlan,
) -> Result<()> {
    for precondition in &plan.preserved_preconditions {
        match open_template_target(state, &precondition.path) {
            Ok(WorkspaceTarget::Directory(directory))
                if precondition.kind == TemplateArtifactKind::Directory =>
            {
                let file = directory.into_std_file();
                let identity = PhysicalIdentity::from_file(&file).map_err(|_| {
                    FolderbaseError::PlanPreconditionChanged(precondition.path.clone())
                })?;
                if identity != precondition.identity.identity() {
                    return Err(FolderbaseError::PlanPreconditionChanged(
                        precondition.path.clone(),
                    ));
                }
            }
            Ok(WorkspaceTarget::RegularFile(file))
                if precondition.kind == TemplateArtifactKind::Text =>
            {
                let mut file = file.into_std();
                let identity = PhysicalIdentity::from_file(&file).map_err(|_| {
                    FolderbaseError::PlanPreconditionChanged(precondition.path.clone())
                })?;
                if identity != precondition.identity.identity() {
                    return Err(FolderbaseError::PlanPreconditionChanged(
                        precondition.path.clone(),
                    ));
                }
                if let Some(expected) = &precondition.sha256
                    && sha256_reader(&mut file).map_err(|_| {
                        FolderbaseError::PlanPreconditionChanged(precondition.path.clone())
                    })? != *expected
                {
                    return Err(FolderbaseError::PlanPreconditionChanged(
                        precondition.path.clone(),
                    ));
                }
            }
            _ => {
                return Err(FolderbaseError::PlanPreconditionChanged(
                    precondition.path.clone(),
                ));
            }
        }
    }
    Ok(())
}

fn verify_additions_absent_in_state(
    state: &FolderbaseState,
    plan: &TemplateExpansionPlan,
) -> Result<()> {
    for addition in &plan.additions {
        ensure_safe_relative(&addition.path)?;
        if !matches!(
            open_template_target(state, &addition.path)?,
            WorkspaceTarget::Absent
        ) {
            return Err(FolderbaseError::WouldOverwrite(
                state.display_root().join(&addition.path),
            ));
        }
    }
    Ok(())
}

fn verify_created_additions_in_state(
    state: &FolderbaseState,
    additions: &[PlannedTemplateAddition],
) -> Result<Vec<TemplateApplicationCreatedPath>> {
    let mut created = Vec::new();
    for addition in additions {
        let (bytes, sha256) = match (addition.kind, open_template_target(state, &addition.path)?) {
            (TemplateArtifactKind::Directory, WorkspaceTarget::Directory(_)) => (None, None),
            (TemplateArtifactKind::Text, WorkspaceTarget::RegularFile(file)) => {
                let mut file = file.into_std();
                let metadata = file.metadata().map_err(|source| {
                    FolderbaseError::io(state.display_root().join(&addition.path), source)
                })?;
                let digest = sha256_reader(&mut file).map_err(|source| {
                    FolderbaseError::io(state.display_root().join(&addition.path), source)
                })?;
                let expected =
                    sha256_bytes(addition.content.as_deref().unwrap_or_default().as_bytes());
                if digest != expected {
                    return Err(FolderbaseError::InvalidRecord {
                        path: state.display_root().join(&addition.path),
                        message: "template addition content digest mismatch".to_owned(),
                    });
                }
                (Some(metadata.len()), Some(digest))
            }
            _ => {
                return Err(FolderbaseError::InvalidRecord {
                    path: state.display_root().join(&addition.path),
                    message: "template addition failed post-write verification".to_owned(),
                });
            }
        };
        created.push(TemplateApplicationCreatedPath {
            path: addition.path.clone(),
            kind: addition.kind,
            bytes,
            sha256,
        });
    }
    created.sort_by(|left, right| left.path.cmp(&right.path));
    Ok(created)
}

fn materialize_preserved_targets_in_state(
    state: &FolderbaseState,
    plan: &TemplateExpansionPlan,
) -> Result<Vec<crate::TemplateApplicationPreservedTarget>> {
    let mut preserved = Vec::new();
    for precondition in &plan.preserved_preconditions {
        let (bytes, sha256) = match open_template_target(state, &precondition.path)? {
            WorkspaceTarget::Directory(_)
                if precondition.kind == TemplateArtifactKind::Directory =>
            {
                (None, None)
            }
            WorkspaceTarget::RegularFile(file)
                if precondition.kind == TemplateArtifactKind::Text =>
            {
                let mut file = file.into_std();
                let metadata = file.metadata().map_err(|source| {
                    FolderbaseError::io(state.display_root().join(&precondition.path), source)
                })?;
                let digest = sha256_reader(&mut file).map_err(|source| {
                    FolderbaseError::io(state.display_root().join(&precondition.path), source)
                })?;
                if precondition.sha256.as_ref() != Some(&digest) {
                    return Err(FolderbaseError::PlanPreconditionChanged(
                        precondition.path.clone(),
                    ));
                }
                (Some(metadata.len()), Some(digest))
            }
            _ => {
                return Err(FolderbaseError::PlanPreconditionChanged(
                    precondition.path.clone(),
                ));
            }
        };
        preserved.push(crate::TemplateApplicationPreservedTarget {
            path: precondition.path.clone(),
            kind: precondition.kind,
            bytes,
            sha256,
        });
    }
    preserved.sort_by(|left, right| left.path.cmp(&right.path));
    Ok(preserved)
}

fn ensure_history_directory_in_state(state: &FolderbaseState, root_dir: &Dir) -> Result<()> {
    match state.open_private_target_nofollow(Path::new(APPLICATIONS))? {
        WorkspaceTarget::Directory(_) => Ok(()),
        WorkspaceTarget::Absent => {
            create_directory_no_clobber(root_dir, state.display_root(), Path::new(APPLICATIONS))
        }
        WorkspaceTarget::RegularFile(_) => Err(FolderbaseError::UnsafePath(
            state.display_root().join(APPLICATIONS),
        )),
    }
}

fn validate_history_path(root: &Path) -> Result<()> {
    let protocol_dir = root.join(".folderbase");
    let metadata = fs::symlink_metadata(&protocol_dir)
        .map_err(|source| FolderbaseError::io(&protocol_dir, source))?;
    if metadata.file_type().is_symlink() || !metadata.is_dir() {
        return Err(FolderbaseError::UnsafePath(protocol_dir));
    }
    let expected = "template-applications".case_fold().collect::<String>();
    for entry in
        fs::read_dir(&protocol_dir).map_err(|source| FolderbaseError::io(&protocol_dir, source))?
    {
        let entry = entry.map_err(|source| FolderbaseError::io(&protocol_dir, source))?;
        let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
            continue;
        };
        if name.case_fold().collect::<String>() == expected && name != "template-applications" {
            return Err(FolderbaseError::UnsafePath(entry.path()));
        }
    }
    let history = root.join(APPLICATIONS);
    match fs::symlink_metadata(&history) {
        Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => Ok(()),
        Ok(_) => Err(FolderbaseError::UnsafePath(history)),
        Err(source) if source.kind() == ErrorKind::NotFound => Ok(()),
        Err(source) => Err(FolderbaseError::io(history, source)),
    }
}

fn read_history_with_snapshot_in_state(
    state: &FolderbaseState,
    expected_folderbase_id: Option<&str>,
) -> Result<(Vec<TemplateApplicationRecord>, String)> {
    let expected_name = template_path_key("template-applications");
    for name in state.private_directory_names(Path::new(".folderbase"), 4097)? {
        let Some(text) = name.to_str() else {
            continue;
        };
        if template_path_key(text) == expected_name && text != "template-applications" {
            return Err(FolderbaseError::UnsafePath(
                state.display_root().join(".folderbase").join(name),
            ));
        }
    }

    let names = match state.open_private_target_nofollow(Path::new(APPLICATIONS))? {
        WorkspaceTarget::Absent => return Ok((Vec::new(), sha256_bytes(b"absent"))),
        WorkspaceTarget::Directory(_) => state
            .private_directory_names(Path::new(APPLICATIONS), MAX_TEMPLATE_HISTORY_RECORDS + 1)?,
        WorkspaceTarget::RegularFile(_) => {
            return Err(FolderbaseError::UnsafePath(
                state.display_root().join(APPLICATIONS),
            ));
        }
    };
    if names.len() > MAX_TEMPLATE_HISTORY_RECORDS {
        return Err(FolderbaseError::InvalidRecord {
            path: state.display_root().join(APPLICATIONS),
            message: format!(
                "template application history exceeds {MAX_TEMPLATE_HISTORY_RECORDS} records"
            ),
        });
    }
    let mut names = names;
    names.sort_by(|left, right| left.as_encoded_bytes().cmp(right.as_encoded_bytes()));
    let mut snapshot = Sha256::new();
    let mut history = Vec::new();
    let mut ids = BTreeSet::new();
    for name in names {
        let Some(name_text) = name.to_str() else {
            return Err(FolderbaseError::InvalidRecord {
                path: state.display_root().join(APPLICATIONS),
                message: "template application history filename is not UTF-8".to_owned(),
            });
        };
        if Path::new(name_text)
            .extension()
            .and_then(|extension| extension.to_str())
            != Some("json")
        {
            return Err(FolderbaseError::InvalidRecord {
                path: state.display_root().join(APPLICATIONS).join(&name),
                message: "template application history contains a non-JSON entry".to_owned(),
            });
        }
        let relative = Path::new(APPLICATIONS).join(&name);
        let bytes = state
            .read_bounded(&relative, MAX_TEMPLATE_APPLICATION_BYTES)?
            .ok_or_else(|| FolderbaseError::InvalidRecord {
                path: state.display_root().join(&relative),
                message: "template application disappeared during planning".to_owned(),
            })?;
        snapshot.update(name.as_encoded_bytes());
        snapshot.update([0]);
        snapshot.update(&bytes);
        snapshot.update([0]);
        let path = state.display_root().join(&relative);
        let record: TemplateApplicationRecord = serde_json::from_slice(&bytes)
            .map_err(|source| FolderbaseError::json(&path, source))?;
        validate_application_record(&record, expected_folderbase_id, &path)?;
        if Path::new(name_text)
            .file_stem()
            .and_then(|stem| stem.to_str())
            != Some(record.id.as_str())
        {
            return Err(FolderbaseError::InvalidRecord {
                path,
                message: "template application filename does not match record id".to_owned(),
            });
        }
        if !ids.insert(record.id.clone()) {
            return Err(FolderbaseError::InvalidRecord {
                path,
                message: "duplicate template application id".to_owned(),
            });
        }
        history.push(record);
    }
    history.sort_by(|left, right| {
        parsed_application_time(left)
            .cmp(&parsed_application_time(right))
            .then_with(|| left.id.cmp(&right.id))
    });
    Ok((history, format!("{:x}", snapshot.finalize())))
}

fn read_history_with_snapshot(
    root: &Path,
    expected_folderbase_id: Option<&str>,
) -> Result<(Vec<TemplateApplicationRecord>, String)> {
    validate_history_path(root)?;
    let history_dir = root.join(APPLICATIONS);
    if !history_dir.exists() {
        return Ok((Vec::new(), sha256_bytes(b"absent")));
    }

    let mut paths = fs::read_dir(&history_dir)
        .map_err(|source| FolderbaseError::io(&history_dir, source))?
        .map(|entry| {
            entry
                .map(|entry| entry.path())
                .map_err(|source| FolderbaseError::io(&history_dir, source))
        })
        .collect::<Result<Vec<_>>>()?;
    paths.sort();
    let mut snapshot = Sha256::new();
    let mut history = Vec::new();
    let mut ids = BTreeSet::new();
    for path in paths {
        let metadata =
            fs::symlink_metadata(&path).map_err(|source| FolderbaseError::io(&path, source))?;
        if metadata.file_type().is_symlink() || !metadata.is_file() {
            return Err(FolderbaseError::UnsafePath(path));
        }
        if path.extension().and_then(|extension| extension.to_str()) != Some("json") {
            return Err(FolderbaseError::InvalidRecord {
                path,
                message: "template application history contains a non-JSON entry".to_owned(),
            });
        }
        let bytes = fs::read(&path).map_err(|source| FolderbaseError::io(&path, source))?;
        snapshot.update(
            path.file_name()
                .expect("history entry name")
                .as_encoded_bytes(),
        );
        snapshot.update([0]);
        snapshot.update(&bytes);
        snapshot.update([0]);
        let record: TemplateApplicationRecord = serde_json::from_slice(&bytes)
            .map_err(|source| FolderbaseError::json(&path, source))?;
        validate_application_record(&record, expected_folderbase_id, &path)?;
        if path.file_stem().and_then(|stem| stem.to_str()) != Some(record.id.as_str()) {
            return Err(FolderbaseError::InvalidRecord {
                path,
                message: "template application filename does not match record id".to_owned(),
            });
        }
        if !ids.insert(record.id.clone()) {
            return Err(FolderbaseError::InvalidRecord {
                path,
                message: "duplicate template application id".to_owned(),
            });
        }
        history.push(record);
    }
    history.sort_by(|left, right| {
        parsed_application_time(left)
            .cmp(&parsed_application_time(right))
            .then_with(|| left.id.cmp(&right.id))
    });
    Ok((history, format!("{:x}", snapshot.finalize())))
}

fn parsed_application_time(record: &TemplateApplicationRecord) -> DateTime<Utc> {
    DateTime::parse_from_rfc3339(&record.applied_at)
        .expect("application time was validated")
        .with_timezone(&Utc)
}

fn validate_application_record(
    record: &TemplateApplicationRecord,
    expected_folderbase_id: Option<&str>,
    path: &Path,
) -> Result<()> {
    if record.schema != APPLICATION_SCHEMA
        || record.protocol_version != "0.2.0"
        || record.state != TemplateApplicationState::Verified
        || !record.id.starts_with("template_application_")
        || Uuid::parse_str(record.id.trim_start_matches("template_application_"))
            .ok()
            .is_none_or(|id| id.get_version_num() != 7)
    {
        return Err(FolderbaseError::InvalidRecord {
            path: path.to_path_buf(),
            message: "invalid template application identity or state".to_owned(),
        });
    }
    if expected_folderbase_id.is_some_and(|expected| expected != record.folderbase_id) {
        return Err(FolderbaseError::InvalidRecord {
            path: path.to_path_buf(),
            message: "template application folderbase_id does not match active manifest".to_owned(),
        });
    }
    Version::parse(&record.template.version).map_err(|_| FolderbaseError::InvalidRecord {
        path: path.to_path_buf(),
        message: "invalid applied template version".to_owned(),
    })?;
    Version::parse(&record.comparison.version).map_err(|_| FolderbaseError::InvalidRecord {
        path: path.to_path_buf(),
        message: "invalid comparison template version".to_owned(),
    })?;
    DateTime::parse_from_rfc3339(&record.applied_at).map_err(|_| {
        FolderbaseError::InvalidRecord {
            path: path.to_path_buf(),
            message: "invalid template application time".to_owned(),
        }
    })?;
    validate_digest(&record.template.package_digest, path)?;
    validate_digest(&record.plan_digest, path)?;
    validate_digest(&record.record_digest, path)?;
    if digest_application_record(record) != record.record_digest {
        return Err(FolderbaseError::InvalidRecord {
            path: path.to_path_buf(),
            message: "template application record digest mismatch".to_owned(),
        });
    }
    if (record.comparison.source == TemplateComparisonSource::Application)
        != record.comparison.application_id.is_some()
    {
        return Err(FolderbaseError::InvalidRecord {
            path: path.to_path_buf(),
            message: "comparison source and application id disagree".to_owned(),
        });
    }
    let mut seen = BTreeSet::new();
    for created in &record.created_paths {
        validate_record_path(&created.path, &mut seen, path)?;
        match created.kind {
            TemplateArtifactKind::Directory
                if created.bytes.is_none() && created.sha256.is_none() => {}
            TemplateArtifactKind::Text
                if created.bytes.is_some()
                    && created.sha256.as_deref().is_some_and(valid_sha256) => {}
            _ => {
                return Err(FolderbaseError::InvalidRecord {
                    path: path.to_path_buf(),
                    message: "created path metadata does not match its type".to_owned(),
                });
            }
        }
    }
    for preserved in &record.preserved_targets {
        validate_record_path(&preserved.path, &mut seen, path)?;
        match preserved.kind {
            TemplateArtifactKind::Directory
                if preserved.bytes.is_none() && preserved.sha256.is_none() => {}
            TemplateArtifactKind::Text
                if preserved.bytes.is_some()
                    && preserved.sha256.as_deref().is_some_and(valid_sha256) => {}
            _ => {
                return Err(FolderbaseError::InvalidRecord {
                    path: path.to_path_buf(),
                    message: "preserved target metadata does not match its type".to_owned(),
                });
            }
        }
    }
    Ok(())
}

fn validate_record_path(
    relative: &Path,
    seen: &mut BTreeSet<String>,
    record_path: &Path,
) -> Result<()> {
    ensure_safe_relative(relative).map_err(|_| FolderbaseError::InvalidRecord {
        path: record_path.to_path_buf(),
        message: format!("unsafe application path: {}", relative.display()),
    })?;
    let text = path_text(relative);
    if !seen.insert(text.case_fold().collect::<String>()) {
        return Err(FolderbaseError::InvalidRecord {
            path: record_path.to_path_buf(),
            message: format!("duplicate application path: {text}"),
        });
    }
    Ok(())
}

fn validate_digest(digest: &TemplatePlanDigest, path: &Path) -> Result<()> {
    if digest.algorithm != "sha256" || !valid_sha256(&digest.digest) {
        return Err(FolderbaseError::InvalidRecord {
            path: path.to_path_buf(),
            message: "invalid sha256 digest".to_owned(),
        });
    }
    Ok(())
}

fn valid_sha256(digest: &str) -> bool {
    digest.len() == 64
        && digest
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

fn required_string<'a>(value: &'a Value, path: &[&str], source: &Path) -> Result<&'a str> {
    let mut current = value;
    for component in path {
        current = current
            .get(*component)
            .ok_or_else(|| FolderbaseError::InvalidRecord {
                path: source.to_path_buf(),
                message: format!("missing manifest field {}", path.join(".")),
            })?;
    }
    current
        .as_str()
        .ok_or_else(|| FolderbaseError::InvalidRecord {
            path: source.to_path_buf(),
            message: format!("manifest field {} is not a string", path.join(".")),
        })
}

fn sha256_bytes(bytes: &[u8]) -> String {
    format!("{:x}", Sha256::digest(bytes))
}

fn digest_application_record(record: &TemplateApplicationRecord) -> TemplatePlanDigest {
    let dto = json!({
        "$schema": record.schema,
        "protocol_version": record.protocol_version,
        "id": record.id,
        "folderbase_id": record.folderbase_id,
        "state": record.state,
        "template": record.template,
        "comparison": record.comparison,
        "applied_at": record.applied_at,
        "created_paths": record.created_paths,
        "preserved_targets": record.preserved_targets,
        "plan_digest": record.plan_digest,
    });
    TemplatePlanDigest {
        algorithm: "sha256".to_owned(),
        digest: sha256_bytes(
            &serde_json::to_vec(&dto).expect("canonical application record DTO serializes"),
        ),
    }
}

fn path_text(path: &Path) -> String {
    path.to_str()
        .expect("validated template paths are UTF-8")
        .to_owned()
}

#[cfg(test)]
mod capability_security_tests {
    use super::*;
    use crate::{InitializationOptions, initialize, plan_initialization};

    fn package() -> TemplatePackage {
        serde_json::from_value(json!({
            "protocol_version": "0.2.0",
            "id": "example.project",
            "version": "1.0.0",
            "name": "Capability security fixture",
            "suggested_folderbase_kind": "project",
            "questions": [],
            "artifacts": [{
                "target": "Notes/README.md",
                "kind": "text",
                "content": "# Notes\n",
                "install": "create_if_missing"
            }],
            "upgrade_edges": []
        }))
        .expect("template package")
    }

    #[cfg(unix)]
    #[test]
    fn apply_never_reenters_a_replaced_ambient_root_after_acquiring_its_lease() {
        let owner = tempfile::tempdir().expect("fixture owner");
        let root = owner.path().join("root");
        fs::create_dir(&root).expect("root directory");
        initialize(
            &plan_initialization(&root, InitializationOptions::default())
                .expect("initialization plan"),
        )
        .expect("initialize root");
        let package = package();
        let answers = BTreeMap::new();
        let reviewed =
            plan_template_expansion(&root, &package, &answers).expect("reviewed expansion");
        let approved = reviewed.plan_digest().digest().to_owned();
        let moved = owner.path().join("moved-root");

        let result = apply_template_expansion_with_expected_plan_digest_and_hook(
            &root,
            &package,
            &answers,
            &approved,
            || {
                fs::rename(&root, &moved).expect("detach retained root");
                fs::create_dir_all(root.join(".folderbase")).expect("replacement state");
                fs::copy(moved.join(MANIFEST), root.join(MANIFEST))
                    .expect("same manifest in replacement root");
            },
        );

        assert!(result.is_err(), "detached display root must fail closed");
        assert!(
            !root.join("Notes/README.md").exists(),
            "replacement root must never receive template writes"
        );
        assert!(
            !moved.join("Notes/README.md").exists(),
            "a detached retained root is not published through an obsolete display path"
        );
    }
}