ostrya 0.2.1

Pure-Rust async reimplementation of the ostree repository library
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
//! Path-addressed tree construction over a transaction (Phase 7f).
//!
//! A [`StagingTree`] builds a directory tree by path rather than by hand-walking
//! a [`MutableTree`](crate::MutableTree). It borrows the transaction it stages
//! into, so `close`, [`write_mtree`](crate::Transaction::write_mtree), commit is
//! the only ordering that compiles. It is a port extension with no `ostree` tool
//! counterpart and no on-disk format impact: every file, symlink, and directory
//! it records flows through the 7a object writers and produces an ordinary 7b
//! tree.
//!
//! Concurrency. The tree sits behind a synchronous mutex held only across the
//! brief map operations that read or mutate its structure. File writes stream
//! outside that lock, so many [`write_file`](StagingTree::write_file) streams
//! progress concurrently through one shared `&StagingTree`; each records its
//! entry under the lock only at [`finish`](StagedFileWriter::finish). The async
//! parts -- hydrating a lazily-loaded committed subdirectory, loading a symlink
//! object during resolution, streaming payloads -- run between lock acquisitions,
//! never across one. [`close`](StagingTree::close) hands back the assembled
//! [`MutableTree`](crate::MutableTree) and fails while any file writer is still
//! outstanding, counted on the tree. A [`merge_at`](StagingTree::merge_at) that
//! drops a directory, a [`remove`](StagingTree::remove) that takes an entry out,
//! a [`clear_dir`](StagingTree::clear_dir) that reaches a directory, and a
//! [`rename`](StagingTree::rename) are refused the same way while any file
//! writer is outstanding, wherever in the tree it sits: a writer records its
//! entry at [`finish`](StagedFileWriter::finish) under the component path it
//! captured, and an entry dropped in between would leave that path stale.
//!
//! Path semantics. Intermediate path components resolve through symlinks; the
//! final component never follows for a write. A relative symlink target resolves
//! from the symlink's parent, an absolute target from the tree root, `..` clamps
//! at the root, chains are capped, and a dangling target is an error. A write's
//! parent directory must exist unless an implied dirmeta is set
//! ([`with_implied_dirmeta`](StagingTree::with_implied_dirmeta)), in which case
//! the write creates its missing ancestors as directories carrying that
//! dirmeta, and a [`merge_at`](StagingTree::merge_at) creates its whole base
//! the same way; resolution for a read never creates a directory. Reads
//! ([`read_file`](StagingTree::read_file), [`read_dir`](StagingTree::read_dir),
//! [`lookup`](StagingTree::lookup)) take a `follow_symlinks` flag governing the
//! final component. The [`merge_at`](StagingTree::merge_at) flag of that name
//! governs the left-side entry names the merge reaches; the base's own final
//! component follows either way. A path with no components -- `.`, `/`, and
//! the empty path -- names the tree root, which
//! [`ensure_dir`](StagingTree::ensure_dir) stamps and
//! [`merge_at`](StagingTree::merge_at) merges into. Objects load from the
//! transaction's staged set before `objects/`, so content staged in the
//! current transaction is visible before it publishes.
//!
//! Refusals. Each condition carries its own [`Error`] variant naming the path
//! resolution stopped at, so a caller branches on the variant:
//! [`PathNotFound`](Error::PathNotFound),
//! [`NotADirectory`](Error::NotADirectory),
//! [`DanglingSymlink`](Error::DanglingSymlink),
//! [`SymlinkLoop`](Error::SymlinkLoop), and
//! [`EntryExists`](Error::EntryExists).
//! [`Staging`](Error::Staging) carries what none of those names. Every typed
//! refusal the staging tree raises reports one path form: the resolved literal
//! component path, unrooted, with the tree root spelled `.`. A path that
//! crosses a symlink reports the target's components, so a write under
//! `opt -> usr/opt` reports `usr/opt`. An absent component reached while a
//! symlink's target components are still queued reports
//! [`DanglingSymlink`](Error::DanglingSymlink) for the innermost such symlink;
//! once a target is spent, an absent component reports
//! [`PathNotFound`](Error::PathNotFound). A `Staging` condition raised before
//! resolution begins -- a path with no final component, a path ending in `..`,
//! a path component that is not UTF-8 -- reports the path as the caller gave
//! it, because no resolved form exists. A symlink target that is not UTF-8
//! names no path. A directory in the way of a write reports
//! [`ReplaceDirWithFile`](Error::ReplaceDirWithFile), whichever moment the
//! directory appeared at; that variant names the entry rather than the
//! resolved path, because the mutable-tree layer raises it, and it is the one
//! carve-out from the path form.

use std::collections::VecDeque;
use std::future::Future;
use std::io;
use std::path::{Component, Path};
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};

use futures_io::AsyncWrite;
use ostrya_core::{Checksum, Commit, DirMeta};

use crate::error::{Error, Result};
use crate::file::{FileKind, FileObject};
use crate::mtree::{ChildKind, ChildRef, MutableTree};
use crate::transaction::Transaction;
use crate::write::{ContentWriter, FileMeta};

/// The maximum number of symlinks a single path resolution follows before it is
/// treated as a loop.
const MAX_SYMLINK_DEPTH: usize = 40;

/// One meaningful path component: a name, or a parent-directory hop.
#[derive(Clone)]
enum Comp {
    Normal(String),
    Parent,
}

/// Where a path resolution ended.
enum WalkEnd {
    /// A directory at the given literal component path (all loaded directories).
    Dir(Vec<String>),
    /// A file or symlink leaf, with the literal component path of its parent,
    /// its entry name, and its content checksum. The parent path and the name
    /// are what a refusal names, so a message reports where resolution actually
    /// ended rather than the path the caller passed.
    Leaf {
        parent: Vec<String>,
        name: String,
        checksum: Checksum,
    },
}

/// How a merge treats the merge root's own directory metadata. Every
/// directory below the root reconciles either way.
#[derive(Debug, Clone, Copy, Default)]
pub enum RootDirmeta {
    /// Reconcile the merge root like any other directory: an equal dirmeta is
    /// silent, and a differing one is a conflict without `allow_overwrite`
    /// and is taken from the right side with it.
    #[default]
    Reconcile,
    /// Keep the left side's root dirmeta, whatever the right root carries. A
    /// left root that carries none keeps none, and a tree whose root has no
    /// dirmeta cannot be written.
    KeepLeft,
}

/// Options for [`StagingTree::merge`] and [`StagingTree::merge_at`].
#[derive(Debug, Clone, Copy, Default)]
pub struct MergeOptions {
    /// Take the right side's version on a conflict instead of failing.
    pub allow_overwrite: bool,
    /// Follow left-side symlinks during the merge: a right-side directory over a
    /// left-side symlink merges into the symlink's target directory.
    pub follow_symlinks: bool,
    /// How the merge treats the merge root's own dirmeta. Governs the root
    /// alone.
    pub root_dirmeta: RootDirmeta,
}

/// One entry in a [`read_dir`](StagingTree::read_dir) listing. A directory under
/// construction has no committed checksum, so it carries only its name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StagingEntry {
    /// A file or symlink, named by its content checksum.
    File {
        /// The entry name.
        name: String,
        /// The content object checksum.
        checksum: Checksum,
    },
    /// A subdirectory; no checksum until it is written.
    Dir {
        /// The entry name.
        name: String,
    },
}

/// What [`lookup`](StagingTree::lookup) found at a path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StagingLookup {
    /// No entry: a component along the path is absent.
    Absent,
    /// A regular file or symlink, named by its content checksum. The kind is
    /// not recorded in the tree, so telling them apart means loading the
    /// object; [`read_file`](StagingTree::read_file) does that.
    File {
        /// The content object checksum.
        checksum: Checksum,
    },
    /// A directory.
    Dir,
}

/// Path-addressed construction over a transaction.
///
/// Constructed with [`Transaction::staging_tree`] or
/// [`Transaction::staging_tree_from_mutable_tree`]. `&StagingTree` is
/// `Send + Sync`, so file writes may run concurrently.
///
/// The tree and the outstanding-writer count are `Arc`-shared with the
/// [`StagedFileWriter`]s handed out by [`write_file`](StagingTree::write_file),
/// so a writer does not borrow the tree: [`close`](StagingTree::close) can be
/// called with a writer still live and fails on the count rather than being
/// rejected at compile time.
pub struct StagingTree<'txn> {
    txn: &'txn Transaction,
    tree: Arc<Mutex<MutableTree>>,
    /// Outstanding [`StagedFileWriter`] count; [`close`](StagingTree::close)
    /// and a [`merge_at`](StagingTree::merge_at) that drops a directory both
    /// fail while it is nonzero.
    /// [`write_file`](StagingTree::write_file) increments it under the tree
    /// lock and the merge check reads it under the same lock, so a
    /// registration and a directory drop cannot miss each other.
    writers: Arc<AtomicUsize>,
    /// The dirmeta applied to ancestors a write creates; `None` keeps a
    /// missing parent an error.
    implied_dirmeta: Option<DirMeta>,
}

impl Transaction {
    /// A staging tree over this transaction, empty or lazily hydrated from a
    /// commit's root. Hydrating reads the commit's root dirtree, so this departs
    /// from the synchronous API sketch (which is explicitly not final code) the
    /// same way [`MutableTree::ensure_dir`](crate::MutableTree::ensure_dir) does.
    pub async fn staging_tree(&self, source: Option<&Commit>) -> Result<StagingTree<'_>> {
        let tree = match source {
            None => MutableTree::new(),
            Some(commit) => {
                MutableTree::hydrate(self.repo(), commit.root_dirtree, commit.root_dirmeta).await?
            }
        };
        Ok(StagingTree::from_tree(self, tree))
    }

    /// A staging tree over this transaction wrapping an existing mutable tree.
    pub fn staging_tree_from_mutable_tree(&self, source: MutableTree) -> StagingTree<'_> {
        StagingTree::from_tree(self, source)
    }
}

impl<'txn> StagingTree<'txn> {
    fn from_tree(txn: &'txn Transaction, tree: MutableTree) -> StagingTree<'txn> {
        StagingTree {
            txn,
            tree: Arc::new(Mutex::new(tree)),
            writers: Arc::new(AtomicUsize::new(0)),
            implied_dirmeta: None,
        }
    }

    /// The dirmeta applied to ancestors a write creates. Set once, at
    /// construction; consuming the tree keeps the type free of interior
    /// mutability. Left unset, a missing parent stays an error.
    ///
    /// The policy applies to [`write_file`](StagingTree::write_file),
    /// [`write_file_content`](StagingTree::write_file_content),
    /// [`symlink`](StagingTree::symlink), [`hardlink`](StagingTree::hardlink),
    /// [`place_object`](StagingTree::place_object),
    /// [`ensure_dir`](StagingTree::ensure_dir), and the destination side of a
    /// [`rename`](StagingTree::rename): ancestors the operation
    /// creates take the policy dirmeta, and the leaf takes whatever the
    /// operation itself supplies. A [`merge_at`](StagingTree::merge_at) base
    /// is created under the same policy, its own final component included,
    /// since the base names a directory rather than a leaf. Path resolution
    /// for a read, a [`lookup`](StagingTree::lookup), a
    /// [`remove`](StagingTree::remove), a
    /// [`clear_dir`](StagingTree::clear_dir), the source side of a
    /// [`hardlink`](StagingTree::hardlink), or the `from` side of a
    /// [`rename`](StagingTree::rename) never creates a directory and never
    /// stages a dirmeta object. [`make_dir`](StagingTree::make_dir) and
    /// [`make_dir_all`](StagingTree::make_dir_all) keep their own rules.
    ///
    /// Ancestors created before a refused leaf stay in the tree, and a
    /// component a later `..` steps back out of is created like any other
    /// ancestor.
    pub fn with_implied_dirmeta(mut self, meta: DirMeta) -> StagingTree<'txn> {
        self.implied_dirmeta = Some(meta);
        self
    }

    /// Hand the assembled tree to the caller, for
    /// [`write_mtree`](crate::Transaction::write_mtree). Fails while any
    /// [`write_file`](StagingTree::write_file) writer is still outstanding.
    pub fn close(self) -> Result<MutableTree> {
        let outstanding = self.writers.load(Ordering::Acquire);
        if outstanding != 0 {
            return Err(Error::Staging(format!(
                "cannot close the staging tree: {outstanding} file writer(s) still outstanding"
            )));
        }
        // The counter is authoritative: at zero, every writer has recorded its
        // entry (finish takes the tree lock before it decrements) or was
        // abandoned. A finishing writer may still hold a tree Arc clone for the
        // moment between its decrement and its drop, so take the tree out through
        // the mutex rather than requiring sole Arc ownership. The Acquire load
        // above pairs with the AcqRel decrement in finish, so that writer's
        // replace_file is visible here. mem::take leaves an empty tree behind
        // that is never observed, since the counter guarantees no writer records
        // again.
        let mut guard = self.tree.lock().unwrap();
        Ok(std::mem::take(&mut *guard))
    }

    // --- write operations ---

    /// A streaming writer for one regular-file payload at `path`. The parent
    /// directory must exist (intermediate components resolve through symlinks)
    /// unless an implied dirmeta is set
    /// ([`with_implied_dirmeta`](StagingTree::with_implied_dirmeta)); the final
    /// component never follows a symlink. Replaces an existing file or
    /// symlink; a directory at `path` is refused with
    /// [`ReplaceDirWithFile`](Error::ReplaceDirWithFile). A parent directory
    /// dropped between path resolution and the writer's registration is
    /// refused with [`Staging`](Error::Staging): the writer is not counted yet
    /// in that window, so the writer guard holds off no concurrent operation,
    /// and the registration re-check is what catches it.
    pub async fn write_file(&self, path: &Path, meta: &FileMeta) -> Result<StagedFileWriter<'txn>> {
        let (parent, name) = self.resolve_write_parent(path).await?;
        self.check_writable_leaf(&parent, &name)?;
        let writer = self.txn.content_writer(None, meta).await?;
        {
            // Register under the tree lock, re-checking the parent: every
            // merge arm that drops a directory reads a zero count under this
            // same lock before it drops, so a writer registered against a
            // parent that still exists keeps its captured path valid for its
            // whole life, and a parent a concurrent merge already dropped is
            // refused here rather than surfacing at finish.
            let tree = self.tree.lock().unwrap();
            if tree.dir_at(&parent).is_none() {
                return Err(Error::Staging(dir_gone(&parent)));
            }
            self.writers.fetch_add(1, Ordering::AcqRel);
        }
        Ok(StagedFileWriter {
            tree: self.tree.clone(),
            writers: self.writers.clone(),
            writer: Some(writer),
            parent,
            name,
        })
    }

    /// Write a regular file at `path` whose content the caller already holds.
    /// Replaces an existing file or symlink; a directory at `path` is refused
    /// with [`ReplaceDirWithFile`](Error::ReplaceDirWithFile).
    pub async fn write_file_content(
        &self,
        path: &Path,
        meta: &FileMeta,
        content: &[u8],
    ) -> Result<()> {
        let (parent, name) = self.resolve_write_parent(path).await?;
        self.check_writable_leaf(&parent, &name)?;
        let checksum = self.txn.write_regfile_inline(None, meta, content).await?;
        self.with_dir_mut(&parent, |dir| dir.replace_file(&name, checksum))
    }

    /// Create the directory `path`, whose parent must exist. Fails on any
    /// existing entry.
    pub async fn make_dir(&self, path: &Path, meta: &DirMeta) -> Result<()> {
        let (parent, name) = self.resolve_parent(path).await?;
        if !matches!(self.peek(&parent, &name)?, ChildKind::Absent) {
            return Err(entry_exists(&parent, &name));
        }
        let dirmeta = self.stage_dirmeta(meta).await?;
        self.with_dir_mut(&parent, |dir| {
            if !matches!(dir.child_kind(&name), ChildKind::Absent) {
                return Err(entry_exists(&parent, &name));
            }
            dir.insert_empty_dir(&name, Some(dirmeta));
            Ok(())
        })
    }

    /// Create `path` and any missing ancestors, applying `meta` to the
    /// directories it creates and leaving existing ones untouched.
    pub async fn make_dir_all(&self, path: &Path, meta: &DirMeta) -> Result<()> {
        self.walk_creating(components_of(path)?, meta).await?;
        Ok(())
    }

    /// Walk `comps` from the tree root, creating each absent component as a
    /// directory carrying `meta` and following symlinks to directories.
    /// Returns the literal component path the walk reached.
    async fn walk_creating(&self, comps: Vec<Comp>, meta: &DirMeta) -> Result<Vec<String>> {
        // Stage `meta` at most once, and only when a directory is actually
        // created. A walk whose every component already exists creates
        // nothing and must not materialize an orphan dirmeta into `objects/`.
        let mut dirmeta: Option<Checksum> = None;
        let mut cur: Vec<String> = Vec::new();
        for comp in comps {
            let name = match comp {
                Comp::Parent => {
                    cur.pop();
                    continue;
                }
                Comp::Normal(name) => name,
            };
            match self.peek(&cur, &name)? {
                ChildKind::Dir | ChildKind::LazyDir { .. } => {
                    self.ensure_child_dir(&cur, &name).await?;
                    cur.push(name);
                }
                ChildKind::Absent => {
                    let dm = match dirmeta {
                        Some(dm) => dm,
                        None => {
                            let dm = self.stage_dirmeta(meta).await?;
                            dirmeta = Some(dm);
                            dm
                        }
                    };
                    self.with_dir_mut(&cur, |dir| {
                        match dir.child_kind(&name) {
                            // A concurrent op may have created it; only create if
                            // still absent, and reject a non-directory in the way.
                            ChildKind::Absent => dir.insert_empty_dir(&name, Some(dm)),
                            ChildKind::File(_) => {
                                return Err(Error::NotADirectory {
                                    path: join(&cur, &name),
                                });
                            }
                            ChildKind::Dir | ChildKind::LazyDir { .. } => {}
                        }
                        Ok(())
                    })?;
                    self.ensure_child_dir(&cur, &name).await?;
                    cur.push(name);
                }
                ChildKind::File(checksum) => {
                    // Follow a symlink to a directory; a regular file is an error.
                    let obj = self.txn.load_file_staged_first(&checksum).await?;
                    match obj.kind {
                        FileKind::Symlink { target } => {
                            // An absent component the target walk reaches
                            // belongs to this symlink: the walk consumes the
                            // target alone, so its `PathNotFound` is never one
                            // of the caller's own components. An inner
                            // symlink's own dangling report passes through, so
                            // the innermost open symlink is the one named,
                            // matching `walk_from`.
                            let link = join(&cur, &name);
                            cur = match self.resolve_symlink_dir(&cur, &target).await {
                                Ok(dir) => dir,
                                Err(Error::PathNotFound { .. }) => {
                                    return Err(Error::DanglingSymlink { path: link, target });
                                }
                                Err(e) => return Err(e),
                            };
                        }
                        FileKind::Regular { .. } => {
                            return Err(Error::NotADirectory {
                                path: join(&cur, &name),
                            });
                        }
                    }
                }
            }
        }
        Ok(cur)
    }

    /// Create the directory at `path`, or reuse an existing one and stamp
    /// `meta` onto it. A file or symlink at `path` is
    /// [`NotADirectory`](Error::NotADirectory). The dirmeta object is staged
    /// only when the directory is created or its recorded dirmeta differs, so
    /// an unchanged call materializes no object. A lazily-loaded committed
    /// directory is never hydrated: its recorded dirmeta is compared, and a
    /// differing one is rewritten in place, because the child's contents do
    /// not change.
    ///
    /// A `path` with no components -- `.`, `/`, and the empty path -- names
    /// the tree root, which takes the same comparison and the same stamp. No
    /// parent directory holds the root, so the root is a directory in every
    /// call. [`close`](StagingTree::close) hands back a tree whose root
    /// carries the stamped dirmeta, and
    /// [`write_mtree`](crate::Transaction::write_mtree) records it as the
    /// root dirmeta of the tree it returns.
    pub async fn ensure_dir(&self, path: &Path, meta: &DirMeta) -> Result<()> {
        if components_of(path)?.is_empty() {
            // The tree root, which no parent directory holds: the comparison
            // reads the root's own recorded dirmeta and the stamp sets it
            // there. Staging is async and runs outside the lock, and the root
            // is a directory in every acquisition, so the mutating
            // acquisition repeats no decision: it stamps what the comparison
            // read. Two stamps of differing dirmetas leave the last one
            // recorded, the last-writer-wins rule a raced staging write
            // follows.
            let new_dirmeta = self.txn.dirmeta_checksum(meta)?;
            if self.with_dir(&[], |dir| dir.metadata_checksum())? == Some(new_dirmeta) {
                return Ok(());
            }
            let dirmeta = self.stage_dirmeta(meta).await?;
            return self.with_dir_mut(&[], |dir| {
                dir.set_metadata_checksum(dirmeta);
                Ok(())
            });
        }
        let (parent, name) = self.resolve_write_parent(path).await?;
        let new_dirmeta = self.txn.dirmeta_checksum(meta)?;
        let unchanged = match self.peek(&parent, &name)? {
            ChildKind::File(_) => {
                return Err(Error::NotADirectory {
                    path: join(&parent, &name),
                });
            }
            ChildKind::Absent => false,
            ChildKind::LazyDir { dirmeta, .. } => dirmeta == new_dirmeta,
            ChildKind::Dir => {
                let mut child = parent.clone();
                child.push(name.clone());
                self.with_dir(&child, |dir| dir.metadata_checksum())? == Some(new_dirmeta)
            }
        };
        if unchanged {
            return Ok(());
        }
        // Staging is async and runs outside the lock, so the mutating
        // acquisition repeats the decision: still absent inserts, a directory
        // takes the new dirmeta, and a file that appeared in the way is
        // rejected.
        let dirmeta = self.stage_dirmeta(meta).await?;
        self.with_dir_mut(&parent, |dir| match dir.child_kind(&name) {
            ChildKind::Absent => {
                dir.insert_empty_dir(&name, Some(dirmeta));
                Ok(())
            }
            ChildKind::Dir | ChildKind::LazyDir { .. } => dir.set_child_dirmeta(&name, dirmeta),
            ChildKind::File(_) => Err(Error::NotADirectory {
                path: join(&parent, &name),
            }),
        })
    }

    /// Create a symlink at `path` pointing at `target`. The mode is fixed by the
    /// object model, so only `meta`'s owner and xattrs are used. Replaces an
    /// existing file or symlink; a directory at `path` is refused with
    /// [`ReplaceDirWithFile`](Error::ReplaceDirWithFile).
    pub async fn symlink(&self, path: &Path, target: &Path, meta: &FileMeta) -> Result<()> {
        let (parent, name) = self.resolve_write_parent(path).await?;
        self.check_writable_leaf(&parent, &name)?;
        let target = target
            .to_str()
            .ok_or_else(|| Error::Staging("symlink target is not valid UTF-8".into()))?;
        let checksum = self.txn.write_symlink(target, meta, None).await?;
        self.with_dir_mut(&parent, |dir| dir.replace_file(&name, checksum))
    }

    /// Record a second tree entry at `path` for the content object found at
    /// `target`. The object carries all metadata, so none is taken. The final
    /// component of `target` is not followed, so a symlink is hardlinked as the
    /// symlink object. Replaces an existing file or symlink at `path`; a
    /// directory there is refused with
    /// [`ReplaceDirWithFile`](Error::ReplaceDirWithFile).
    pub async fn hardlink(&self, path: &Path, target: &Path) -> Result<()> {
        let checksum = match self
            .walk_from(Vec::new(), components_of(target)?, false)
            .await?
        {
            WalkEnd::Leaf { checksum, .. } => checksum,
            WalkEnd::Dir(dir) => {
                return Err(Error::Staging(format!(
                    "cannot hardlink from {}: the source is a directory",
                    spell_path(&dir)
                )));
            }
        };
        let (parent, name) = self.resolve_write_parent(path).await?;
        self.check_writable_leaf(&parent, &name)?;
        self.with_dir_mut(&parent, |dir| dir.replace_file(&name, checksum))
    }

    /// Record `checksum` as the file entry at `path`. An identical checksum
    /// already there is silent; a differing entry or a directory is
    /// [`MergeConflict`](Error::MergeConflict). The rule is decided and applied
    /// under one lock acquisition, so concurrent placements of differing
    /// checksums at one path resolve to one recorded winner and a conflict for
    /// each losing call, never a silent overwrite. The object's presence in
    /// the store is not checked, the same as
    /// [`write_mtree`](crate::Transaction::write_mtree).
    pub async fn place_object(&self, path: &Path, checksum: &Checksum) -> Result<()> {
        let (parent, name) = self.resolve_write_parent(path).await?;
        self.with_dir_mut(&parent, |dir| match dir.child_kind(&name) {
            ChildKind::Absent => dir.replace_file(&name, *checksum),
            ChildKind::File(existing) if existing == *checksum => Ok(()),
            ChildKind::File(_) => Err(Error::MergeConflict(format!(
                "placed object differs at {}",
                join(&parent, &name)
            ))),
            ChildKind::Dir | ChildKind::LazyDir { .. } => Err(Error::MergeConflict(format!(
                "an object cannot overwrite the directory at {}",
                join(&parent, &name)
            ))),
        })
    }

    /// Remove the entry at `path`, subtree and all. The final component is
    /// never followed, so removing a symlink removes the symlink. With
    /// `allow_noent`, an absent entry, an absent ancestor, and a dangling
    /// intermediate symlink are all `Ok`; without it, an absent entry is
    /// [`PathNotFound`](Error::PathNotFound) and the other two stay the
    /// errors the walk types. A call that takes an entry out is refused with
    /// [`Staging`](Error::Staging) while any
    /// [`write_file`](StagingTree::write_file) writer is outstanding, wherever
    /// in the tree it sits; a call that removes nothing is not.
    pub async fn remove(&self, path: &Path, allow_noent: bool) -> Result<()> {
        let (parent, name) = match self.resolve_parent(path).await {
            Ok(resolved) => resolved,
            Err(Error::PathNotFound { .. } | Error::DanglingSymlink { .. }) if allow_noent => {
                return Ok(());
            }
            Err(e) => return Err(e),
        };
        // The absent-entry outcome is decided under the same acquisition that
        // removes the entry, so an entry appearing in between cannot be
        // missed; the mutable-tree refusal is never the answer a caller sees.
        // A call that removes nothing consults no writer guard, matching the
        // merge arms, which ask only where they are about to drop.
        self.with_dir_mut(&parent, |dir| match dir.child_kind(&name) {
            ChildKind::Absent if allow_noent => Ok(()),
            ChildKind::Absent => Err(Error::PathNotFound {
                path: join(&parent, &name),
            }),
            _ => {
                self.check_no_live_writers(&format!("remove {}", join(&parent, &name)))?;
                dir.remove(&name, true)
            }
        })
    }

    /// Remove every entry under `path`, keeping the directory and its
    /// dirmeta. The final component is never followed, so a file at `path`,
    /// and a symlink there even where it points at a directory, is
    /// [`NotADirectory`](Error::NotADirectory). `path` names a directory
    /// below the root, so the root itself cannot be cleared. With
    /// `allow_noent`, an absent directory -- an absent ancestor and a
    /// dangling intermediate symlink included -- is `Ok`. A lazily-loaded
    /// committed directory is never hydrated: its entry is replaced by an
    /// empty loaded directory keeping the recorded dirmeta checksum, so no
    /// dirtree is read. A call that reaches a directory is refused with
    /// [`Staging`](Error::Staging) while any
    /// [`write_file`](StagingTree::write_file) writer is outstanding,
    /// wherever in the tree it sits, whether or not that directory holds
    /// entries; a call over an absent directory under `allow_noent` is not.
    pub async fn clear_dir(&self, path: &Path, allow_noent: bool) -> Result<()> {
        let (parent, name) = match self.resolve_parent(path).await {
            Ok(resolved) => resolved,
            Err(Error::PathNotFound { .. } | Error::DanglingSymlink { .. }) if allow_noent => {
                return Ok(());
            }
            Err(e) => return Err(e),
        };
        self.with_dir_mut(&parent, |dir| match dir.child_kind(&name) {
            ChildKind::Absent if allow_noent => Ok(()),
            ChildKind::Absent => Err(Error::PathNotFound {
                path: join(&parent, &name),
            }),
            ChildKind::File(_) => Err(Error::NotADirectory {
                path: join(&parent, &name),
            }),
            ChildKind::Dir => {
                self.check_no_live_writers(&format!(
                    "clear the directory at {}",
                    join(&parent, &name)
                ))?;
                let child = dir
                    .dir_at_mut(std::slice::from_ref(&name))
                    .expect("a loaded child under the same lock acquisition");
                child.clear_children();
                Ok(())
            }
            ChildKind::LazyDir { dirmeta, .. } => {
                self.check_no_live_writers(&format!(
                    "clear the directory at {}",
                    join(&parent, &name)
                ))?;
                dir.insert_empty_dir(&name, Some(dirmeta));
                Ok(())
            }
        })
    }

    /// Move the entry at `from` to `to`, subtree and dirmeta included.
    /// Neither final component is followed, so renaming a symlink moves the
    /// symlink. An existing entry at `to` is
    /// [`EntryExists`](Error::EntryExists), and a destination at or under
    /// the moved entry is refused with [`Staging`](Error::Staging), because
    /// the move would detach the directory that must receive it. A missing
    /// destination parent is created under an implied dirmeta
    /// ([`with_implied_dirmeta`](StagingTree::with_implied_dirmeta)) and is
    /// an error without one; the `from` side never creates a directory. The
    /// moved node is carried as it is, so a lazily-loaded committed
    /// directory stays lazy and no dirtree is read for the moved subtree.
    /// The call is refused with [`Staging`](Error::Staging) while any
    /// [`write_file`](StagingTree::write_file) writer is outstanding,
    /// wherever in the tree it sits.
    ///
    /// The destination is resolved before any refusal is decided, so a
    /// refused call keeps the ancestors the policy created for it, the rule
    /// every write follows. Where the destination is under the moved entry,
    /// those ancestors sit inside that entry, and a lazily-loaded source is
    /// hydrated to reach them; the refusal reports whatever that resolution
    /// raises.
    pub async fn rename(&self, from: &Path, to: &Path) -> Result<()> {
        let (from_parent, from_name) = self.resolve_parent(from).await?;
        let (to_parent, to_name) = self.resolve_write_parent(to).await?;
        let mut from_path = from_parent.clone();
        from_path.push(from_name.clone());
        // Both sides are resolved literal component paths, so the prefix
        // comparison is exact: a destination parent at or under the moved
        // entry would be detached by the take and could never receive it.
        if to_parent.starts_with(&from_path) {
            return Err(Error::Staging(format!(
                "cannot rename {} to {}: the destination is under the moved entry",
                spell_path(&from_path),
                join(&to_parent, &to_name)
            )));
        }
        // Decide and move under one lock acquisition: the destination and
        // the source are re-read and the writer guard is consulted where
        // the entry is about to move, so no concurrent operation slots in
        // between the checks and the two mutations.
        let mut tree = self.tree.lock().unwrap();
        let to_dir = tree
            .dir_at(&to_parent)
            .ok_or_else(|| Error::Staging(dir_gone(&to_parent)))?;
        if !matches!(to_dir.child_kind(&to_name), ChildKind::Absent) {
            return Err(entry_exists(&to_parent, &to_name));
        }
        let from_dir = tree
            .dir_at_mut(&from_parent)
            .ok_or_else(|| Error::Staging(dir_gone(&from_parent)))?;
        if matches!(from_dir.child_kind(&from_name), ChildKind::Absent) {
            return Err(Error::PathNotFound {
                path: join(&from_parent, &from_name),
            });
        }
        self.check_no_live_writers(&format!(
            "rename {} to {}",
            join(&from_parent, &from_name),
            join(&to_parent, &to_name)
        ))?;
        let entry = from_dir
            .take_child(&from_name)
            .expect("an entry present under the same lock acquisition");
        // The entry is out of the tree here, so a failed insertion would drop
        // it. Neither of the two refusals can fire: the name comes from a
        // `Component::Normal`, which `validate_name` accepts, and the
        // destination was read absent under this same acquisition.
        tree.dir_at_mut(&to_parent)
            .expect("a destination parent present under the same lock acquisition")
            .insert_child(&to_name, entry)
            .expect("a fresh name in a present directory under the same lock acquisition");
        Ok(())
    }

    // --- reads (staged-first) ---

    /// Resolve `path` and report what sits there. Intermediate components
    /// follow symlinks; the final component follows only with
    /// `follow_symlinks`. An absent component anywhere along the path is
    /// [`StagingLookup::Absent`], so probing a path whose ancestors do not
    /// exist is not an error. A non-directory intermediate component and a
    /// dangling symlink stay the errors the walk types for them.
    pub async fn lookup(&self, path: &Path, follow_symlinks: bool) -> Result<StagingLookup> {
        match self
            .walk_from(Vec::new(), components_of(path)?, follow_symlinks)
            .await
        {
            Ok(WalkEnd::Dir(_)) => Ok(StagingLookup::Dir),
            Ok(WalkEnd::Leaf { checksum, .. }) => Ok(StagingLookup::File { checksum }),
            Err(Error::PathNotFound { .. }) => Ok(StagingLookup::Absent),
            Err(e) => Err(e),
        }
    }

    /// Read the file object at `path`, resolving through the staged tree and
    /// loading its bytes from the transaction's staged set before `objects/`.
    /// With `follow_symlinks`, a final symlink is resolved to its target.
    pub async fn read_file(&self, path: &Path, follow_symlinks: bool) -> Result<FileObject> {
        match self
            .walk_from(Vec::new(), components_of(path)?, follow_symlinks)
            .await?
        {
            WalkEnd::Leaf { checksum, .. } => self.txn.load_file_staged_first(&checksum).await,
            WalkEnd::Dir(dir) => Err(Error::Staging(format!(
                "{} is a directory, not a file",
                spell_path(&dir)
            ))),
        }
    }

    /// List the entries of the directory at `path`, files first then
    /// subdirectories, each group name-sorted. With `follow_symlinks`, a final
    /// symlink is resolved to its target directory.
    pub async fn read_dir(&self, path: &Path, follow_symlinks: bool) -> Result<Vec<StagingEntry>> {
        let dir_path = match self
            .walk_from(Vec::new(), components_of(path)?, follow_symlinks)
            .await?
        {
            WalkEnd::Dir(p) => p,
            WalkEnd::Leaf {
                parent: dir, name, ..
            } => {
                return Err(Error::NotADirectory {
                    path: join(&dir, &name),
                });
            }
        };
        self.with_dir(&dir_path, |dir| {
            let mut entries = Vec::new();
            for (name, checksum) in dir.file_entries() {
                entries.push(StagingEntry::File {
                    name: name.to_owned(),
                    checksum,
                });
            }
            for (name, _child) in dir.dir_entries() {
                entries.push(StagingEntry::Dir {
                    name: name.to_owned(),
                });
            }
            entries
        })
    }

    /// Merge `other` into this tree at its root, which is
    /// [`merge_at`](StagingTree::merge_at) with a base of `.`.
    pub async fn merge(&self, other: &MutableTree, opts: MergeOptions) -> Result<()> {
        self.merge_at(Path::new("."), other, opts).await
    }

    /// Merge `other` into the directory at `base` per `opts`. Equal entries
    /// merge silently; differing files, file-versus-directory clashes, and
    /// differing directory metadata are conflicts without `allow_overwrite` and
    /// take the right side with it. With `follow_symlinks`, a right-side
    /// directory over a left-side symlink merges into the symlink's target
    /// directory; right-side files and symlinks replace the left entry and
    /// never write through. A merge that fails keeps the entries it applied
    /// before the failure.
    ///
    /// `root_dirmeta` governs the merge root alone: under
    /// [`Reconcile`](RootDirmeta::Reconcile) the directory at `base`
    /// reconciles its own dirmeta against the right root's, and under
    /// [`KeepLeft`](RootDirmeta::KeepLeft) it keeps the dirmeta it has. Every
    /// directory below the root reconciles either way.
    ///
    /// A missing `base` is created under an implied dirmeta
    /// ([`with_implied_dirmeta`](StagingTree::with_implied_dirmeta)) and is
    /// the error the walk types without one. `base` resolves through
    /// symlinks, its final component included, so a file there and a symlink
    /// to a file are both [`NotADirectory`](Error::NotADirectory). A `base`
    /// with no components -- `.`, `/`, and the empty path -- names the tree
    /// root.
    ///
    /// A merge that drops a directory is refused with
    /// [`Staging`](Error::Staging) while any
    /// [`write_file`](StagingTree::write_file) writer is outstanding, wherever
    /// in the tree it sits, and leaves that directory and its subtree in
    /// place. Two cases drop one: an overwrite that replaces a directory with
    /// a file, and a right-side directory arriving at a name that a
    /// concurrent operation turned into a directory after the merge read it.
    /// The second case is a conflict without `allow_overwrite`, the answer the
    /// same clash gets when the merge reads the directory itself.
    ///
    /// A leaf a concurrent operation puts at a name the merge already read is
    /// taken whatever `allow_overwrite` says, the last-writer-wins rule the
    /// other staging writes follow on a raced name. Only a raced directory is
    /// re-read, because dropping one loses a subtree.
    pub async fn merge_at(
        &self,
        base: &Path,
        other: &MutableTree,
        opts: MergeOptions,
    ) -> Result<()> {
        let base_path = self.resolve_merge_base(base).await?;
        merge_into(
            self,
            base_path,
            RightDir::Mutable(other),
            &opts,
            opts.root_dirmeta,
        )
        .await
    }

    // --- internal helpers ---

    /// Stage a directory-metadata object and return its checksum.
    async fn stage_dirmeta(&self, meta: &DirMeta) -> Result<Checksum> {
        self.txn.write_dirmeta(meta).await
    }

    /// Refuse a structural change -- dropping a directory, removing an
    /// entry, clearing a directory's children, moving an entry -- while any
    /// file writer is live. A writer records its entry at
    /// [`finish`](StagedFileWriter::finish) under the component path it
    /// captured, and a directory dropped in between would leave that path
    /// stale, or pointing at a different directory created there later. A
    /// removed file entry cannot stale a captured path; it is refused
    /// because the guard is the whole-tree form, which reads a count and no
    /// paths. `action` spells the refused change and the path it targets. Call
    /// this under the tree lock, where
    /// [`write_file`](StagingTree::write_file) registers its writers, so the
    /// count read here cannot race a registration. Deregistration cannot be
    /// missed either: [`finish`](StagedFileWriter::finish) records its entry
    /// under this same lock before it decrements, so a zero count read here
    /// means every departed writer has already recorded.
    /// [`close`](StagingTree::close) states the full argument.
    fn check_no_live_writers(&self, action: &str) -> Result<()> {
        let outstanding = self.writers.load(Ordering::Acquire);
        if outstanding != 0 {
            return Err(Error::Staging(format!(
                "cannot {action}: {outstanding} file writer(s) still outstanding"
            )));
        }
        Ok(())
    }

    /// Fail if a write to a leaf at `parent/name` would clobber a directory. A
    /// file or symlink is replaced; an absent entry is created.
    fn check_writable_leaf(&self, parent: &[String], name: &str) -> Result<()> {
        match self.peek(parent, name)? {
            ChildKind::Dir | ChildKind::LazyDir { .. } => {
                Err(Error::ReplaceDirWithFile(name.to_owned()))
            }
            _ => Ok(()),
        }
    }

    /// Resolve a merge base to its literal component path. With an implied
    /// dirmeta set, absent components are created as directories carrying it;
    /// without one, an absent component is the error the walk types. Both
    /// walks follow symlinks to directories, the final component included,
    /// both report a file in the way as
    /// [`NotADirectory`](Error::NotADirectory), and both report an absent
    /// component inside a symlink target as
    /// [`DanglingSymlink`](Error::DanglingSymlink).
    async fn resolve_merge_base(&self, base: &Path) -> Result<Vec<String>> {
        let comps = components_of(base)?;
        let Some(meta) = &self.implied_dirmeta else {
            return match self.walk_from(Vec::new(), comps, true).await? {
                WalkEnd::Dir(dir) => Ok(dir),
                WalkEnd::Leaf { parent, name, .. } => Err(Error::NotADirectory {
                    path: join(&parent, &name),
                }),
            };
        };
        self.walk_creating(comps, meta).await
    }

    /// Put a fresh empty directory carrying `dirmeta` at `parent/name` for a
    /// merge. The entry is re-read inside the mutating acquisition, because
    /// the merge read it in an earlier one: a directory a concurrent operation
    /// put there since would be dropped with its subtree. That branch takes
    /// the two answers a directory clash takes anywhere in the merge, in the
    /// order the merge asks them: a conflict without `allow_overwrite`, and
    /// the writer guard with it. A file the re-read finds is taken whatever
    /// `allow_overwrite` says: the re-read exists to keep a subtree, and a
    /// raced leaf follows the last-writer-wins rule the merge's other arms
    /// follow on a name they already read.
    fn insert_merged_dir(
        &self,
        parent: &[String],
        name: &str,
        dirmeta: Option<Checksum>,
        allow_overwrite: bool,
    ) -> Result<()> {
        self.with_dir_mut(parent, |dir| {
            if matches!(
                dir.child_kind(name),
                ChildKind::Dir | ChildKind::LazyDir { .. }
            ) {
                if !allow_overwrite {
                    return Err(Error::MergeConflict(format!(
                        "a directory appeared at {} after the merge read the name",
                        join(parent, name)
                    )));
                }
                self.check_no_live_writers(&format!(
                    "drop the directory at {}",
                    join(parent, name)
                ))?;
            }
            dir.insert_empty_dir(name, dirmeta);
            Ok(())
        })
    }

    /// Resolve a path's parent directory for a write. With an implied dirmeta
    /// set, absent ancestors are created as directories carrying it; without
    /// one, an absent ancestor is the error the walk types.
    async fn resolve_write_parent(&self, path: &Path) -> Result<(Vec<String>, String)> {
        let Some(meta) = &self.implied_dirmeta else {
            return self.resolve_parent(path).await;
        };
        let (init, name) = split_final(path)?;
        let parent = self.walk_creating(init, meta).await?;
        Ok((parent, name))
    }

    /// Resolve a path's parent directory (following symlinks on intermediate
    /// components) and return its literal component path plus the final name.
    async fn resolve_parent(&self, path: &Path) -> Result<(Vec<String>, String)> {
        let (init, name) = split_final(path)?;
        let parent = match self.walk_from(Vec::new(), init, true).await? {
            WalkEnd::Dir(dir) => dir,
            WalkEnd::Leaf {
                parent: dir, name, ..
            } => {
                return Err(Error::NotADirectory {
                    path: join(&dir, &name),
                });
            }
        };
        Ok((parent, name))
    }

    /// Resolve a symlink `target` found in directory `base` to a directory.
    async fn resolve_symlink_dir(&self, base: &[String], target: &str) -> Result<Vec<String>> {
        let (absolute, comps) = split_target(target)?;
        let start = if absolute { Vec::new() } else { base.to_vec() };
        match self.walk_from(start, comps, true).await? {
            WalkEnd::Dir(dir) => Ok(dir),
            WalkEnd::Leaf {
                parent: dir, name, ..
            } => Err(Error::NotADirectory {
                path: join(&dir, &name),
            }),
        }
    }

    /// Walk `comps` from the loaded directory `start`, resolving symlinks. With
    /// `follow_final`, a final symlink is followed too. Returns the directory or
    /// leaf the path names.
    async fn walk_from(
        &self,
        start: Vec<String>,
        comps: Vec<Comp>,
        follow_final: bool,
    ) -> Result<WalkEnd> {
        let mut cur = start;
        let mut pending: VecDeque<Comp> = comps.into();
        let mut symlink_depth = 0usize;
        // Each entry is a symlink whose target components are still being
        // consumed: its path, its target, and the pending length the walk returns
        // to once the target is spent. A failure belongs to the innermost open
        // entry.
        let mut open_symlinks: Vec<(String, String, usize)> = Vec::new();

        while let Some(comp) = pending.pop_front() {
            // Drop every symlink whose target is spent: the walk is back on the
            // caller's own components, so an absent entry is not a dangling
            // target.
            while open_symlinks
                .last()
                .is_some_and(|(_, _, mark)| pending.len() < *mark)
            {
                open_symlinks.pop();
            }
            let is_final = pending.is_empty();
            let name = match comp {
                Comp::Parent => {
                    cur.pop();
                    continue;
                }
                Comp::Normal(name) => name,
            };

            match self.peek(&cur, &name)? {
                ChildKind::Absent => {
                    return Err(match open_symlinks.last() {
                        Some((path, target, _)) => Error::DanglingSymlink {
                            path: path.clone(),
                            target: target.clone(),
                        },
                        None => Error::PathNotFound {
                            path: join(&cur, &name),
                        },
                    });
                }
                ChildKind::Dir | ChildKind::LazyDir { .. } => {
                    self.ensure_child_dir(&cur, &name).await?;
                    cur.push(name);
                }
                ChildKind::File(checksum) => {
                    if is_final && !follow_final {
                        return Ok(WalkEnd::Leaf {
                            parent: cur,
                            name,
                            checksum,
                        });
                    }
                    let obj = self.txn.load_file_staged_first(&checksum).await?;
                    match obj.kind {
                        FileKind::Symlink { target } => {
                            symlink_depth += 1;
                            if symlink_depth > MAX_SYMLINK_DEPTH {
                                return Err(Error::SymlinkLoop {
                                    path: join(&cur, &name),
                                });
                            }
                            let (absolute, target_comps) = split_target(&target)?;
                            // The mark is the count of the components queued
                            // behind this target: the caller's own, plus any
                            // outer symlink's target remainder.
                            let mark = pending.len();
                            open_symlinks.push((join(&cur, &name), target.clone(), mark));
                            if absolute {
                                cur.clear();
                            }
                            for comp in target_comps.into_iter().rev() {
                                pending.push_front(comp);
                            }
                        }
                        FileKind::Regular { .. } => {
                            if is_final {
                                return Ok(WalkEnd::Leaf {
                                    parent: cur,
                                    name,
                                    checksum,
                                });
                            }
                            return Err(Error::NotADirectory {
                                path: join(&cur, &name),
                            });
                        }
                    }
                }
            }
        }
        Ok(WalkEnd::Dir(cur))
    }

    /// Ensure the child `name` under the loaded directory `path` is a loaded
    /// directory, hydrating a lazily-loaded committed subdirectory. Errors if
    /// the child is absent or is not a directory.
    async fn ensure_child_dir(&self, path: &[String], name: &str) -> Result<()> {
        loop {
            let (kind, repo) = {
                let tree = self.tree.lock().unwrap();
                let dir = tree
                    .dir_at(path)
                    .ok_or_else(|| Error::Staging(dir_gone(path)))?;
                (dir.child_kind(name), dir.repo())
            };
            match kind {
                ChildKind::Dir => return Ok(()),
                ChildKind::LazyDir { dirtree, dirmeta } => {
                    let repo = repo.ok_or_else(|| {
                        Error::Staging(format!(
                            "cannot hydrate {}: no repository handle",
                            join(path, name)
                        ))
                    })?;
                    let loaded = MutableTree::hydrate(&repo, dirtree, dirmeta).await?;
                    let mut tree = self.tree.lock().unwrap();
                    if let Some(dir) = tree.dir_at_mut(path)
                        && matches!(dir.child_kind(name), ChildKind::LazyDir { .. })
                    {
                        dir.install_hydrated_child(name, loaded);
                    }
                    // Loop to re-read; the child is a loaded directory now.
                }
                ChildKind::File(_) => {
                    return Err(Error::NotADirectory {
                        path: join(path, name),
                    });
                }
                ChildKind::Absent => {
                    return Err(Error::PathNotFound {
                        path: join(path, name),
                    });
                }
            }
        }
    }

    /// The kind of `name` under the loaded directory `path`, under the lock.
    fn peek(&self, path: &[String], name: &str) -> Result<ChildKind> {
        let tree = self.tree.lock().unwrap();
        let dir = tree
            .dir_at(path)
            .ok_or_else(|| Error::Staging(dir_gone(path)))?;
        Ok(dir.child_kind(name))
    }

    /// Run `f` against the loaded directory at `path` under the lock.
    fn with_dir<R>(&self, path: &[String], f: impl FnOnce(&MutableTree) -> R) -> Result<R> {
        let tree = self.tree.lock().unwrap();
        let dir = tree
            .dir_at(path)
            .ok_or_else(|| Error::Staging(dir_gone(path)))?;
        Ok(f(dir))
    }

    /// Run `f` against the mutable loaded directory at `path` under the lock.
    fn with_dir_mut<R>(
        &self,
        path: &[String],
        f: impl FnOnce(&mut MutableTree) -> Result<R>,
    ) -> Result<R> {
        let mut tree = self.tree.lock().unwrap();
        let dir = tree
            .dir_at_mut(path)
            .ok_or_else(|| Error::Staging(dir_gone(path)))?;
        f(dir)
    }
}

/// A read-only directory view for the right side of a merge: an in-memory
/// mutable tree node, or a committed subtree loaded through the transaction on
/// demand. A committed subtree resolves staged-first, so a dirtree staged in
/// the current transaction is visible before it publishes, matching the left.
enum RightDir<'a> {
    Mutable(&'a MutableTree),
    Committed {
        txn: &'a Transaction,
        dirtree: Checksum,
        dirmeta: Checksum,
    },
}

impl<'a> RightDir<'a> {
    /// This directory's dirmeta checksum, if it has one.
    fn dirmeta(&self) -> Option<Checksum> {
        match self {
            RightDir::Mutable(tree) => tree.metadata_checksum(),
            RightDir::Committed { dirmeta, .. } => Some(*dirmeta),
        }
    }

    /// This directory's files and subdirectories. A committed directory is read
    /// through `txn` (staged-first); an in-memory node is read directly. The
    /// `txn` supplies the transaction a lazy child's committed view resolves
    /// through.
    async fn entries(
        &self,
        txn: &'a Transaction,
    ) -> Result<(Vec<(String, Checksum)>, Vec<(String, RightDir<'a>)>)> {
        match self {
            RightDir::Mutable(tree) => {
                let tree: &'a MutableTree = tree;
                let files = tree
                    .file_entries()
                    .map(|(name, checksum)| (name.to_owned(), checksum))
                    .collect();
                let dirs = tree
                    .dir_entries()
                    .map(|(name, child)| {
                        let view = match child {
                            ChildRef::Loaded(sub) => RightDir::Mutable(sub),
                            ChildRef::Lazy { dirtree, dirmeta } => RightDir::Committed {
                                txn,
                                dirtree,
                                dirmeta,
                            },
                        };
                        (name.to_owned(), view)
                    })
                    .collect();
                Ok((files, dirs))
            }
            RightDir::Committed { txn, dirtree, .. } => {
                let txn: &'a Transaction = txn;
                let dt = txn.load_dirtree_staged_first(dirtree).await?;
                let files = dt.files.into_iter().collect();
                let dirs = dt
                    .dirs
                    .into_iter()
                    .map(|(name, child_dirtree, child_dirmeta)| {
                        (
                            name,
                            RightDir::Committed {
                                txn,
                                dirtree: child_dirtree,
                                dirmeta: child_dirmeta,
                            },
                        )
                    })
                    .collect();
                Ok((files, dirs))
            }
        }
    }
}

/// The boxed future for the recursive merge; async recursion needs indirection.
type MergeFuture<'a> = Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;

/// Merge the right-side directory `right` into the left staging tree at
/// `left_path`. `root_dirmeta` is the policy for `left_path`'s own metadata,
/// which the caller takes from the options; each descendant reconciles, so the
/// recursion passes [`RootDirmeta::Reconcile`].
fn merge_into<'a>(
    st: &'a StagingTree<'_>,
    left_path: Vec<String>,
    right: RightDir<'a>,
    opts: &'a MergeOptions,
    root_dirmeta: RootDirmeta,
) -> MergeFuture<'a> {
    Box::pin(async move {
        // Reconcile this directory's own metadata. A right dirmeta that is unset
        // makes no change; one that equals the left is silent; a differing one is
        // a conflict without `allow_overwrite`, and is taken with it. Under
        // `KeepLeft` the merge root skips this and keeps the dirmeta it has.
        if matches!(root_dirmeta, RootDirmeta::Reconcile)
            && let Some(right_dm) = right.dirmeta()
        {
            let left_dm = {
                let tree = st.tree.lock().unwrap();
                match tree.dir_at(&left_path) {
                    Some(dir) => dir.metadata_checksum(),
                    None => return Err(Error::Staging(dir_gone(&left_path))),
                }
            };
            match left_dm {
                Some(left) if left == right_dm => {}
                Some(_) if !opts.allow_overwrite => {
                    return Err(Error::MergeConflict(format!(
                        "directory metadata differs at {}",
                        spell_path(&left_path)
                    )));
                }
                _ => {
                    st.with_dir_mut(&left_path, |dir| {
                        dir.set_metadata_checksum(right_dm);
                        Ok(())
                    })?;
                }
            }
        }

        let (rfiles, rdirs) = right.entries(st.txn).await?;

        for (name, right_csum) in rfiles {
            match st.peek(&left_path, &name)? {
                ChildKind::Absent => {
                    st.with_dir_mut(&left_path, |dir| dir.replace_file(&name, right_csum))?;
                }
                ChildKind::File(left_csum) if left_csum == right_csum => {}
                ChildKind::File(_) => {
                    if !opts.allow_overwrite {
                        return Err(Error::MergeConflict(format!(
                            "file differs at {}",
                            join(&left_path, &name)
                        )));
                    }
                    st.with_dir_mut(&left_path, |dir| dir.replace_file(&name, right_csum))?;
                }
                ChildKind::Dir | ChildKind::LazyDir { .. } => {
                    if !opts.allow_overwrite {
                        return Err(Error::MergeConflict(format!(
                            "a file cannot overwrite the directory at {}",
                            join(&left_path, &name)
                        )));
                    }
                    st.with_dir_mut(&left_path, |dir| {
                        st.check_no_live_writers(&format!(
                            "drop the directory at {}",
                            join(&left_path, &name)
                        ))?;
                        dir.remove(&name, true)?;
                        dir.replace_file(&name, right_csum)
                    })?;
                }
            }
        }

        for (name, right_child) in rdirs {
            match st.peek(&left_path, &name)? {
                ChildKind::Absent => {
                    st.insert_merged_dir(
                        &left_path,
                        &name,
                        right_child.dirmeta(),
                        opts.allow_overwrite,
                    )?;
                    let mut child_path = left_path.clone();
                    child_path.push(name);
                    merge_into(st, child_path, right_child, opts, RootDirmeta::Reconcile).await?;
                }
                ChildKind::Dir | ChildKind::LazyDir { .. } => {
                    st.ensure_child_dir(&left_path, &name).await?;
                    let mut child_path = left_path.clone();
                    child_path.push(name);
                    merge_into(st, child_path, right_child, opts, RootDirmeta::Reconcile).await?;
                }
                ChildKind::File(left_csum) => {
                    if opts.follow_symlinks {
                        let obj = st.txn.load_file_staged_first(&left_csum).await?;
                        if let FileKind::Symlink { target } = obj.kind {
                            let target_dir = st.resolve_symlink_dir(&left_path, &target).await?;
                            merge_into(st, target_dir, right_child, opts, RootDirmeta::Reconcile)
                                .await?;
                            continue;
                        }
                    }
                    if !opts.allow_overwrite {
                        return Err(Error::MergeConflict(format!(
                            "a directory cannot overwrite the file at {}",
                            join(&left_path, &name)
                        )));
                    }
                    st.insert_merged_dir(
                        &left_path,
                        &name,
                        right_child.dirmeta(),
                        opts.allow_overwrite,
                    )?;
                    let mut child_path = left_path.clone();
                    child_path.push(name);
                    merge_into(st, child_path, right_child, opts, RootDirmeta::Reconcile).await?;
                }
            }
        }
        Ok(())
    })
}

/// A streaming writer for one regular-file payload recorded into a staging tree
/// at [`finish`](StagedFileWriter::finish). It shares the tree and writer count
/// with its [`StagingTree`] through `Arc`, so it does not borrow the tree.
/// Implements [`futures_io::AsyncWrite`] unconditionally and the tokio
/// `AsyncWrite` under the `tokio` feature. Dropping it without `finish` abandons
/// the staged temporary (reaped by the transaction) and releases its writer
/// slot.
pub struct StagedFileWriter<'txn> {
    tree: Arc<Mutex<MutableTree>>,
    writers: Arc<AtomicUsize>,
    writer: Option<ContentWriter<'txn>>,
    parent: Vec<String>,
    name: String,
}

impl StagedFileWriter<'_> {
    /// Complete the content object and record it at the path. Releases the
    /// writer slot on every path. A directory at the path is refused with
    /// [`ReplaceDirWithFile`](Error::ReplaceDirWithFile).
    pub async fn finish(mut self) -> Result<()> {
        let writer = self.writer.take().expect("writer present until finish");
        let outcome = match writer.finish().await {
            Ok(checksum) => {
                let mut tree = self.tree.lock().unwrap();
                match tree.dir_at_mut(&self.parent) {
                    Some(dir) => dir.replace_file(&self.name, checksum),
                    None => Err(Error::Staging(dir_gone(&self.parent))),
                }
            }
            Err(e) => Err(e),
        };
        self.writers.fetch_sub(1, Ordering::AcqRel);
        outcome
    }
}

impl Drop for StagedFileWriter<'_> {
    fn drop(&mut self) {
        // An abandoned writer (dropped without `finish`) still releases its slot,
        // so `close` is never wedged; its staged temporary is reaped by the
        // transaction.
        if self.writer.is_some() {
            self.writers.fetch_sub(1, Ordering::AcqRel);
        }
    }
}

impl AsyncWrite for StagedFileWriter<'_> {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        match &mut self.get_mut().writer {
            Some(writer) => Pin::new(writer).poll_write(cx, buf),
            None => Poll::Ready(Ok(0)),
        }
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        match &mut self.get_mut().writer {
            Some(writer) => Pin::new(writer).poll_flush(cx),
            None => Poll::Ready(Ok(())),
        }
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        self.poll_flush(cx)
    }
}

#[cfg(feature = "tokio")]
impl ostrya_rt::tokio_io::AsyncWrite for StagedFileWriter<'_> {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        AsyncWrite::poll_write(self, cx, buf)
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        AsyncWrite::poll_flush(self, cx)
    }

    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        AsyncWrite::poll_close(self, cx)
    }
}

/// The meaningful components of a path: names and parent-directory hops, with the
/// root, current-directory, and prefix components dropped. A non-UTF-8 component
/// is rejected, since the tree is `String`-keyed and a lossy conversion would
/// silently address the wrong name.
fn components_of(path: &Path) -> Result<Vec<Comp>> {
    path.components()
        .filter_map(|c| match c {
            Component::Normal(part) => Some(
                part.to_str()
                    .map(|s| Comp::Normal(s.to_owned()))
                    .ok_or_else(|| {
                        Error::Staging(format!(
                            "path component is not valid UTF-8: {}",
                            path.display()
                        ))
                    }),
            ),
            Component::ParentDir => Some(Ok(Comp::Parent)),
            Component::RootDir | Component::CurDir | Component::Prefix(_) => None,
        })
        .collect()
}

/// Split a path into its parent components and its final name. A path with no
/// final component and a path ending in `..` are refused before resolution
/// begins, so both report the path as the caller gave it.
fn split_final(path: &Path) -> Result<(Vec<Comp>, String)> {
    let mut comps = components_of(path)?;
    let name = match comps.pop() {
        Some(Comp::Normal(name)) => name,
        Some(Comp::Parent) => {
            return Err(Error::Staging(format!("{} ends in `..`", path.display())));
        }
        None => {
            return Err(Error::Staging(format!(
                "{} has no final component",
                path.display()
            )));
        }
    };
    Ok((comps, name))
}

/// Split a symlink target into an absolute flag and its meaningful components.
/// The target is already validated UTF-8, so component decoding never fails.
fn split_target(target: &str) -> Result<(bool, Vec<Comp>)> {
    Ok((target.starts_with('/'), components_of(Path::new(target))?))
}

/// A `parent/name` display path for messages.
fn join(path: &[String], name: &str) -> String {
    if path.is_empty() {
        name.to_owned()
    } else {
        format!("{}/{}", path.join("/"), name)
    }
}

/// A whole component path spelled for a message. The tree root has no
/// components, so it spells as `.`.
fn spell_path(path: &[String]) -> String {
    if path.is_empty() {
        ".".to_owned()
    } else {
        path.join("/")
    }
}

/// The message for a directory that is no longer present under the lock.
fn dir_gone(path: &[String]) -> String {
    format!("directory {} is no longer present", spell_path(path))
}

/// The refusal for an operation that requires a fresh entry at `parent/name`.
fn entry_exists(parent: &[String], name: &str) -> Error {
    Error::EntryExists {
        path: join(parent, name),
    }
}

/// The new staging-tree types move freely across tasks and threads.
const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<StagingTree<'static>>();
    assert_send_sync::<StagedFileWriter<'static>>();
    assert_send_sync::<StagingEntry>();
    assert_send_sync::<StagingLookup>();
    assert_send_sync::<MergeOptions>();
    assert_send_sync::<RootDirmeta>();
};

#[cfg(feature = "tokio")]
const _: fn() = || {
    fn assert_tokio_write<T: ostrya_rt::tokio_io::AsyncWrite>() {}
    assert_tokio_write::<StagedFileWriter<'static>>();
};