vce-engine 0.1.1

The generic state substrate of the Virtual Computing Engine (VCE)
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
//! The [`Engine`] facade.
//!
//! The Engine owns the object store, the event bus, the authorization policy,
//! and the clock. Every operation follows the same shape:
//!
//! ```text
//! authorize the actor
//!   ↓
//! mutate state atomically (under the store lock)
//!   ↓
//! release the store lock
//!   ↓
//! synchronously dispatch the event chain
//!   ↓
//! return
//! ```
//!
//! Dispatch never holds the store lock, so listeners may re-enter the Engine
//! (for example, to derive state from a mutation) without deadlocking. The
//! store lock is a [`std::sync::Mutex`] even though the Engine is single-user
//! today; this makes the Engine `Send + Sync` so the Shell/runtime layer can
//! run commands concurrently without redesigning the Engine.
//!
//! # Authorization table
//!
//! Each Engine operation checks exactly one operation against the primary
//! target object:
//!
//! | Engine operation                | Checked operation      | Target object          |
//! |---------------------------------|------------------------|------------------------|
//! | `create_file`, `create_directory`, `create_file_with_options`, `create_directory_with_options` | [`Operation::Create`] | the destination directory |
//! | `create_detached_namespace`     | [`Operation::Create`] | the root (pseudo-parent) |
//! | `read`, `lookup`, `metadata`, `list`, `children`, `parent`, `size` | [`Operation::Read`] | the object itself |
//! | `write`                         | [`Operation::Write`]  | the object itself      |
//! | `move_object`                   | [`Operation::Move`] on the object, then [`Operation::Create`] on the destination directory | both |
//! | `detach_object`                 | [`Operation::Move`] | the object itself      |
//! | `attach_object`                 | [`Operation::Move`] on the object, then [`Operation::Create`] on the destination directory | both |
//! | `copy_object`                   | [`Operation::Copy`] on the object, then [`Operation::Create`] on the destination directory | both |
//! | `delete`                        | [`Operation::Delete`] | the object itself      |
//! | `set_owner`                     | [`Operation::ChangeOwner`] | the object itself |
//! | `set_authorization`, `set_permissions`, `set_group`, `update_metadata`, `touch` | [`Operation::ChangeMetadata`] | the object itself |
//!
//! Every request carries the target object's parent context (when it has
//! one), so policies can implement parent-directory semantics (for example
//! Unix write-on-parent rules for move/delete and sticky directories).
//!
//! The default policy is [`PermissivePolicy`]; the OS layer installs a real
//! one.

use std::sync::{Arc, Mutex};

thread_local! {
    /// Identity tokens (the `dispatch_lock` addresses) of the Engines this
    /// thread is currently dispatching on. Keyed per Engine: a listener
    /// re-entering the *same* Engine takes the reentrant path, while a
    /// listener touching a *different* Engine on this thread correctly
    /// acquires that Engine's lock (two Engines must not run concurrent
    /// dispatches just because they share a thread).
    static ACTIVE_DISPATCHES: std::cell::RefCell<std::collections::HashSet<usize>> =
        std::cell::RefCell::new(std::collections::HashSet::new());
    /// One time book per active [`Engine::suspend_time`] scope on this
    /// thread, innermost last: the virtual time each scope has consumed
    /// but not yet published to the shared clock (nanoseconds).
    static SUSPENDED_BOOKS: std::cell::RefCell<Vec<u64>> = const { std::cell::RefCell::new(Vec::new()) };
}

/// Marks the thread as inside [`Engine::dispatch`] *for one specific
/// Engine*, so a listener that re-enters that Engine takes the reentrant
/// path instead of blocking on the dispatch lock it already holds. Clears
/// the mark when dropped, so even a panicking listener cannot leave
/// dispatch silently unlocked.
struct DispatchFlag {
    token: usize,
}

impl DispatchFlag {
    fn enter(token: usize) -> Self {
        ACTIVE_DISPATCHES.with(|active| {
            active.borrow_mut().insert(token);
        });
        Self { token }
    }
}

impl Drop for DispatchFlag {
    fn drop(&mut self) {
        ACTIVE_DISPATCHES.with(|active| {
            active.borrow_mut().remove(&self.token);
        });
    }
}

/// Restores the suspension state when a [`Engine::suspend_time`] scope
/// ends, so a panicking closure cannot leave the thread's timeline
/// suspended (and its consumed time stranded) forever.
struct TimeSuspension {
    finished: std::cell::Cell<bool>,
}

impl TimeSuspension {
    fn enter() -> Self {
        SUSPENDED_BOOKS.with(|books| books.borrow_mut().push(0));
        Self {
            finished: std::cell::Cell::new(false),
        }
    }

    /// Folds this scope's book into the enclosing scope (its time also
    /// passed while the enclosed code ran) and returns the folded value.
    fn take(&self) -> u64 {
        SUSPENDED_BOOKS.with(|books| {
            let mut books = books.borrow_mut();
            let elapsed = books.pop().unwrap_or_default();
            if let Some(outer) = books.last_mut() {
                *outer = outer.saturating_add(elapsed);
            }
            elapsed
        })
    }

    /// Ends the scope normally, reporting its consumed time to the caller.
    fn finish(self) -> Duration {
        self.finished.set(true);
        Duration::from_nanos(self.take())
    }
}

impl Drop for TimeSuspension {
    fn drop(&mut self) {
        if !self.finished.get() {
            // The scope never returned (a panicking closure): fold the
            // consumed time back and discard it.
            self.take();
        }
    }
}
use std::time::Duration;

use crate::core::metadata::{Metadata, MetadataPatch, Name};
use crate::core::object::ObjectKind;
use crate::core::object_id::ObjectId;
use crate::core::time::{Clock, VirtualClock};
use crate::core::timestamp::Timestamp;
use crate::error::Error;
use crate::events::event::{EventData, ObjectEvent};
use crate::events::event_bus::EventBus;
use crate::events::event_type::EventType;
use crate::events::subscription::SubscriptionId;
use crate::filesystem::detached_namespace::DetachedNamespace;
use crate::filesystem::path::VirtualPath;
use crate::filesystem::store::ObjectStore;
use crate::security::actor::ActorId;
use crate::security::authorization::{
    AuthorizationData, AuthorizationPolicy, AuthorizationRequest, AuthorizationResult, Operation,
    PermissivePolicy,
};

/// The event payload key carrying the source object of a copy.
const COPY_SOURCE_KEY: &str = "source";

/// Collects the events of one logical mutation.
///
/// Events are collected while the store lock is held and dispatched after it
/// is released, so listeners never run under the store lock.
struct EventChain {
    actor: Option<ActorId>,
    now: Timestamp,
    events: Vec<ObjectEvent>,
}

impl EventChain {
    fn new(actor: Option<ActorId>, now: Timestamp) -> Self {
        Self {
            actor,
            now,
            events: Vec::new(),
        }
    }
}

/// Initial owner and authorization data for a newly created object.
///
/// Creation is a single atomic mutation: the object appears with its owner
/// and authorization data already set, so no intermediate state exists in
/// which the object is owned by nobody.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CreateOptions {
    /// The owning principal, if any.
    pub owner: Option<ActorId>,
    /// The opaque authorization data.
    pub authorization: AuthorizationData,
}

/// The virtual computing Engine: state, events, authorization, and time.
pub struct Engine {
    store: Arc<Mutex<ObjectStore>>,
    bus: Arc<Mutex<EventBus>>,
    /// Serializes event dispatch. Dispatch runs listeners with the listener
    /// list taken out of the bus, so two concurrent dispatches would hand
    /// one of them an empty list and silently drop its event chain; the
    /// dispatch lock keeps every chain total and ordered. Listeners still
    /// run outside every other lock (they may re-enter the Engine). The
    /// lock is shared by all clones of an Engine (like the store and bus).
    dispatch_lock: Arc<Mutex<()>>,
    policy: Arc<dyn AuthorizationPolicy>,
    clock: Arc<dyn Clock>,
}

impl Clone for Engine {
    fn clone(&self) -> Self {
        Self {
            store: Arc::clone(&self.store),
            bus: Arc::clone(&self.bus),
            dispatch_lock: Arc::clone(&self.dispatch_lock),
            policy: Arc::clone(&self.policy),
            clock: Arc::clone(&self.clock),
        }
    }
}

impl Engine {
    /// Creates an Engine with the given authorization policy and clock.
    pub fn new(policy: Box<dyn AuthorizationPolicy>, clock: Box<dyn Clock>) -> Self {
        Self {
            store: Arc::new(Mutex::new(ObjectStore::new())),
            bus: Arc::new(Mutex::new(EventBus::new())),
            dispatch_lock: Arc::new(Mutex::new(())),
            policy: Arc::from(policy),
            clock: Arc::from(clock),
        }
    }

    /// Creates an Engine with a fresh [`VirtualClock`] and the given policy.
    pub fn with_virtual_clock(policy: Box<dyn AuthorizationPolicy>) -> Self {
        Self::new(policy, Box::new(VirtualClock::new()))
    }

    // ------------------------------------------------------------------
    // Time
    // ------------------------------------------------------------------

    /// Advances the virtual clock by a duration.
    ///
    /// Clocks that do not support manual advancement (such as the host wall
    /// clock) ignore this call. Inside [`Engine::suspend_time`] the duration
    /// is booked against the suspension instead of the shared timeline.
    pub fn advance_time(&self, duration: Duration) {
        let nanos = u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX);
        let suspended = SUSPENDED_BOOKS.with(|books| {
            if let Some(top) = books.borrow_mut().last_mut() {
                *top = top.saturating_add(nanos);
                true
            } else {
                false
            }
        });
        if !suspended {
            self.clock.advance_by(duration);
        }
    }

    /// Sets the virtual clock to an absolute point in time.
    ///
    /// Used to initialize a machine at a deterministic boot date. This is the only
    /// sanctioned use: after seeding, the shared timeline only ever moves
    /// forward ([`VirtualClock::set`] asserts this in debug builds). Clocks
    /// that do not support manual setting ignore this call.
    pub fn set_time(&self, timestamp: Timestamp) {
        self.clock.set(timestamp);
    }

    /// The current virtual time.
    ///
    /// Inside [`Engine::suspend_time`] this includes time consumed within
    /// the suspension, even though that time has not been published to the
    /// shared clock yet.
    pub fn time(&self) -> Timestamp {
        self.now()
    }

    /// Runs `f` with the machine's timeline suspended, and returns what `f`
    /// produced together with the virtual time `f` consumed.
    ///
    /// While suspended, time still advances *locally* — a `sleep` inside
    /// `f` observes its own duration through [`Engine::time`] — but the
    /// advancement is withheld from the shared clock and reported here
    /// instead. The caller books that time where it belongs (a background
    /// job's own completion deadline) rather than onto the
    /// machine-wide timeline, which therefore only ever moves forward.
    ///
    /// Nested suspensions each report the time consumed since they were
    /// entered; every reported duration is subtracted from what enclosing
    /// scopes will see.
    pub fn suspend_time<R>(f: impl FnOnce() -> R) -> (R, Duration) {
        let guard = TimeSuspension::enter();
        let result = f();
        let elapsed = guard.finish();
        (result, elapsed)
    }

    // ------------------------------------------------------------------
    // Event subscriptions
    // ------------------------------------------------------------------

    /// Subscribes an event listener. See [`EventBus::subscribe`].
    pub fn subscribe(
        &self,
        filter: impl Into<Option<EventType>>,
        callback: impl FnMut(&ObjectEvent) + Send + Sync + 'static,
    ) -> SubscriptionId {
        self.bus
            .lock()
            .expect("event bus lock poisoned")
            .subscribe(filter, callback)
    }

    /// Removes a subscription. See [`EventBus::unsubscribe`].
    pub fn unsubscribe(&self, subscription: SubscriptionId) {
        self.bus
            .lock()
            .expect("event bus lock poisoned")
            .unsubscribe(subscription);
    }

    /// The number of active subscriptions.
    pub fn listener_count(&self) -> usize {
        self.bus
            .lock()
            .expect("event bus lock poisoned")
            .listener_count()
    }

    // ------------------------------------------------------------------
    // Queries
    // ------------------------------------------------------------------

    /// The filesystem root object.
    pub fn root(&self) -> ObjectId {
        self.store.lock().expect("store lock poisoned").root()
    }

    /// Returns `true` if the object exists.
    pub fn exists(&self, object: ObjectId) -> bool {
        self.store
            .lock()
            .expect("store lock poisoned")
            .get(object)
            .is_some()
    }

    /// The metadata of an object.
    pub fn metadata(&self, actor: Option<ActorId>, object: ObjectId) -> Result<Metadata, Error> {
        self.authorize(actor, Operation::Read, object)?;
        // A link reports its target's metadata (`stat` semantics).
        let object = self.resolve_links(object)?;
        let store = self.store.lock().expect("store lock poisoned");
        Ok(store
            .get(object)
            .ok_or(Error::ObjectNotFound(object))?
            .metadata
            .clone())
    }

    /// The parent of an object, if any.
    pub fn parent(
        &self,
        actor: Option<ActorId>,
        object: ObjectId,
    ) -> Result<Option<ObjectId>, Error> {
        self.authorize(actor, Operation::Read, object)?;
        let store = self.store.lock().expect("store lock poisoned");
        Ok(store
            .get(object)
            .ok_or(Error::ObjectNotFound(object))?
            .parent)
    }

    /// The child object IDs of a directory, in ID order.
    pub fn children(
        &self,
        actor: Option<ActorId>,
        directory: ObjectId,
    ) -> Result<Vec<ObjectId>, Error> {
        self.authorize(actor, Operation::Read, directory)?;
        // A link lists its target's children.
        let directory = self.resolve_links(directory)?;
        let store = self.store.lock().expect("store lock poisoned");
        let data = store
            .get(directory)
            .ok_or(Error::ObjectNotFound(directory))?;
        if !data.kind.is_directory() {
            return Err(Error::NotADirectory(directory));
        }
        Ok(data.children.iter().copied().collect())
    }

    /// The entries of a directory, sorted by name.
    pub fn list(
        &self,
        actor: Option<ActorId>,
        directory: ObjectId,
    ) -> Result<Vec<(Name, ObjectId)>, Error> {
        self.authorize(actor, Operation::Read, directory)?;
        // A link lists its target's children.
        let directory = self.resolve_links(directory)?;
        let store = self.store.lock().expect("store lock poisoned");
        let data = store
            .get(directory)
            .ok_or(Error::ObjectNotFound(directory))?;
        if !data.kind.is_directory() {
            return Err(Error::NotADirectory(directory));
        }
        let mut entries: Vec<(Name, ObjectId)> = data
            .children
            .iter()
            .map(|child| {
                let child_data = store.get(*child).expect("child of a directory exists");
                (child_data.metadata.name().clone(), *child)
            })
            .collect();
        entries.sort();
        Ok(entries)
    }

    /// The effective size of an object (see `ObjectData` in the filesystem
    /// store).
    pub fn size(&self, actor: Option<ActorId>, object: ObjectId) -> Result<u64, Error> {
        self.authorize(actor, Operation::Read, object)?;
        // A link reports its target's size (`stat` semantics).
        let object = self.resolve_links(object)?;
        let store = self.store.lock().expect("store lock poisoned");
        Ok(store
            .get(object)
            .ok_or(Error::ObjectNotFound(object))?
            .size())
    }

    /// Checks whether an actor may perform an operation on an object.
    ///
    /// This is the authorization-only form of the guarded helpers: it never
    /// mutates state, so callers can decide whether an operation is allowed
    /// before attempting it (for example, whether a session may execute a
    /// command object).
    pub fn check(
        &self,
        actor: Option<ActorId>,
        operation: Operation,
        object: ObjectId,
    ) -> Result<(), Error> {
        self.authorize(actor, operation, object)
    }

    /// Resolves a path from the filesystem root.
    ///
    /// Authorization mirrors real path resolution: every directory
    /// component stepped through is checked with [`Operation::Execute`]
    /// (the search permission), and the final object is checked with
    /// [`Operation::Read`]. What directory-execute means is policy — Unix
    /// maps it to the execute bit, Windows grants it by default (bypass
    /// traversal).
    ///
    /// Symbolic links are followed while walking, like the kernel's path
    /// resolution: an intermediate link resolves to its target and the
    /// walk continues there, and the final component is followed too
    /// (`stat` semantics — the opposite of `lstat`, available through
    /// [`Engine::lookup_no_follow`]). Link loops are bounded by the depth
    /// cap and fail with [`Error::SymlinkLoop`].
    pub fn lookup(&self, actor: Option<ActorId>, path: &VirtualPath) -> Result<ObjectId, Error> {
        let store = self.store.lock().expect("store lock poisoned");
        let (object, traversed) = self.walk(&store, path)?;
        drop(store);
        for directory in traversed {
            self.authorize(actor, Operation::Execute, directory)?;
        }
        self.authorize(actor, Operation::Read, object)?;
        Ok(object)
    }

    /// Resolves a path, returning the final object itself when it is a
    /// symbolic link (`lstat` semantics).
    ///
    /// Intermediate links are still followed; only the last component is
    /// reported as-is, so commands that display the link (`ls -l`, `stat`)
    /// see the link, not what it points to.
    pub fn lookup_no_follow(
        &self,
        actor: Option<ActorId>,
        path: &VirtualPath,
    ) -> Result<ObjectId, Error> {
        let store = self.store.lock().expect("store lock poisoned");
        let mut current = store.root();
        let mut traversed = Vec::new();
        let segments: &[String] = path.segments();
        for (index, segment) in segments.iter().enumerate() {
            traversed.push(current);
            let data = store.get(current).ok_or(Error::ObjectNotFound(current))?;
            let next = data
                .children
                .iter()
                .copied()
                .find(|child| {
                    store
                        .get(*child)
                        .is_some_and(|child_data| child_data.metadata.name().as_str() == segment)
                })
                .ok_or_else(|| Error::PathNotFound(path.clone()))?;
            let is_last = index + 1 == segments.len();
            let is_link = store
                .get(next)
                .is_some_and(|child_data| child_data.kind.is_symlink());
            if is_last && is_link {
                drop(store);
                for directory in traversed {
                    self.authorize(actor, Operation::Execute, directory)?;
                }
                self.authorize(actor, Operation::Read, next)?;
                return Ok(next);
            }
            current = next;
        }
        drop(store);
        for directory in traversed {
            self.authorize(actor, Operation::Execute, directory)?;
        }
        self.authorize(actor, Operation::Read, current)?;
        Ok(current)
    }

    /// Creates a symbolic link: an object whose content is a target path.
    ///
    /// The target is stored as written and may be absolute or relative (a
    /// relative target resolves against the link's parent). The link is
    /// created even when the target does not exist, like `ln -s` on a real
    /// machine. Authorized as [`Operation::Create`] against the parent.
    pub fn create_symlink(
        &self,
        actor: Option<ActorId>,
        parent: ObjectId,
        name: Name,
        target: String,
    ) -> Result<ObjectId, Error> {
        self.create_symlink_with_options(actor, parent, name, target, CreateOptions::default())
    }

    /// Creates a symbolic link with its owner and authorization data applied
    /// atomically, like [`Self::create_file_with_options`] and
    /// [`Self::create_directory_with_options`].
    pub fn create_symlink_with_options(
        &self,
        actor: Option<ActorId>,
        parent: ObjectId,
        name: Name,
        target: String,
        options: CreateOptions,
    ) -> Result<ObjectId, Error> {
        self.create(actor, parent, name, ObjectKind::Symlink { target }, options)
    }

    /// Returns the target text of a symbolic link.
    ///
    /// Returns `None` when the object is not a link.
    pub fn read_link(
        &self,
        actor: Option<ActorId>,
        object: ObjectId,
    ) -> Result<Option<String>, Error> {
        self.authorize(actor, Operation::Read, object)?;
        let store = self.store.lock().expect("store lock poisoned");
        let data = store.get(object).ok_or(Error::ObjectNotFound(object))?;
        match &data.kind {
            ObjectKind::Symlink { target } => Ok(Some(target.clone())),
            _ => Ok(None),
        }
    }

    /// Returns `true` when the object is a symbolic link.
    pub fn is_link(&self, actor: Option<ActorId>, object: ObjectId) -> Result<bool, Error> {
        self.authorize(actor, Operation::Read, object)?;
        let store = self.store.lock().expect("store lock poisoned");
        Ok(store
            .get(object)
            .ok_or(Error::ObjectNotFound(object))?
            .kind
            .is_symlink())
    }

    /// Resolves a symbolic-link chain to its final non-link object.
    ///
    /// Following a link's target may itself be a link; this walks the
    /// chain to the end, bounded by the same depth cap as path resolution.
    /// A non-link object resolves to itself.
    pub fn resolve_links(&self, object: ObjectId) -> Result<ObjectId, Error> {
        let store = self.store.lock().expect("store lock poisoned");
        let mut current = object;
        for _ in 0..=Self::MAX_SYMLINK_DEPTH {
            let data = store.get(current).ok_or(Error::ObjectNotFound(current))?;
            let ObjectKind::Symlink { target } = &data.kind else {
                return Ok(current);
            };
            let target_path = if target.starts_with('/') {
                target
                    .parse()
                    .map_err(|_| Error::InvalidPath(target.clone()))?
            } else {
                let mut base = Self::path_of(&store, current).unwrap_or(VirtualPath::root());
                if let Some(parent) = base.parent() {
                    base = parent.clone();
                }
                for component in target.split('/').filter(|part| !part.is_empty()) {
                    base = base.join(
                        &Name::new(component)
                            .map_err(|_| Error::InvalidPath(component.to_owned()))?,
                    );
                }
                base
            };
            current = self.walk(&store, &target_path)?.0;
        }
        Err(Error::SymlinkLoop(object.get().to_string()))
    }

    /// The maximum number of symbolic links followed during one path
    /// resolution, mirroring the kernel's `ELOOP` bound.
    const MAX_SYMLINK_DEPTH: usize = 40;

    /// The absolute path of an object, by walking its parent chain to the
    /// root.
    fn path_of(store: &ObjectStore, object: ObjectId) -> Option<VirtualPath> {
        let mut names = Vec::new();
        let mut current = object;
        loop {
            let data = store.get(current)?;
            if data.parent.is_none() {
                break;
            }
            names.push(data.metadata.name().clone());
            current = data.parent?;
        }
        let mut path = VirtualPath::root();
        for name in names.into_iter().rev() {
            path = path.join(&name);
        }
        Some(path)
    }

    /// Walks a path through the store, following symbolic links, and
    /// returns the final object and every directory stepped through (for
    /// the caller to authorize).
    ///
    /// Link resolution recurses into the target's own walk and is bounded:
    /// a loop or chain longer than [`Engine::MAX_SYMLINK_DEPTH`] fails
    /// with [`Error::SymlinkLoop`].
    fn walk(
        &self,
        store: &ObjectStore,
        path: &VirtualPath,
    ) -> Result<(ObjectId, Vec<ObjectId>), Error> {
        self.walk_at(store, path, 0)
    }

    /// The depth-tracking body of [`Engine::walk`].
    fn walk_at(
        &self,
        store: &ObjectStore,
        path: &VirtualPath,
        depth: usize,
    ) -> Result<(ObjectId, Vec<ObjectId>), Error> {
        let mut current = store.root();
        let mut traversed = Vec::new();
        let mut current_path = VirtualPath::root();
        for segment in path.segments() {
            traversed.push(current);
            let data = store.get(current).ok_or(Error::ObjectNotFound(current))?;
            let next = data
                .children
                .iter()
                .copied()
                .find(|child| {
                    store
                        .get(*child)
                        .is_some_and(|child_data| child_data.metadata.name().as_str() == segment)
                })
                .ok_or_else(|| Error::PathNotFound(path.clone()))?;
            current_path = current_path
                .join(&Name::new(segment).map_err(|_| Error::InvalidPath(segment.to_owned()))?);
            let is_link = store
                .get(next)
                .is_some_and(|child_data| child_data.kind.is_symlink());
            if !is_link {
                current = next;
                continue;
            }
            if depth + 1 > Self::MAX_SYMLINK_DEPTH {
                return Err(Error::SymlinkLoop(path.to_string()));
            }
            let data = store.get(next).expect("link exists");
            let ObjectKind::Symlink { target } = &data.kind else {
                unreachable!("checked above");
            };
            // The target path: the text itself when absolute, or the
            // link's parent joined with the text when relative.
            let target_path = if target.starts_with('/') {
                target
                    .parse()
                    .map_err(|_| Error::InvalidPath(target.clone()))?
            } else {
                let mut base = current_path.parent().unwrap_or(VirtualPath::root()).clone();
                for component in target.split('/').filter(|part| !part.is_empty()) {
                    base = base.join(
                        &Name::new(component)
                            .map_err(|_| Error::InvalidPath(component.to_owned()))?,
                    );
                }
                base
            };
            // Resolve the target chain (its directories join the
            // authorization walk), then continue the original path from
            // the resolved object.
            let (resolved, target_traversed) = self.walk_at(store, &target_path, depth + 1)?;
            traversed.extend(target_traversed);
            current = resolved;
            current_path = target_path;
        }
        Ok((current, traversed))
    }

    /// Reads a file's content.
    ///
    /// Returns `None` for metadata-only files. Reading does not modify the
    /// object; in particular it does not update the access timestamp, which
    /// keeps reads free of metadata side effects (and therefore of
    /// `MetadataChanged` events).
    pub fn read(&self, actor: Option<ActorId>, file: ObjectId) -> Result<Option<Vec<u8>>, Error> {
        self.authorize(actor, Operation::Read, file)?;
        // A link reads its target; an unresolvable target is an error.
        let file = self.resolve_links(file)?;
        let content = {
            let store = self.store.lock().expect("store lock poisoned");
            let data = store.get(file).ok_or(Error::ObjectNotFound(file))?;
            match &data.kind {
                ObjectKind::File { content } => content.clone(),
                ObjectKind::Directory => return Err(Error::NotAFile(file)),
                ObjectKind::Symlink { .. } => unreachable!("links resolve above"),
            }
        };
        self.dispatch(ObjectEvent::new(
            EventType::ObjectRead,
            file,
            actor,
            self.now(),
        ));
        Ok(content)
    }

    // ------------------------------------------------------------------
    // Mutations
    // ------------------------------------------------------------------

    /// Creates an empty or content-bearing file in a directory.
    pub fn create_file(
        &self,
        actor: Option<ActorId>,
        parent: ObjectId,
        name: Name,
        content: Option<Vec<u8>>,
    ) -> Result<ObjectId, Error> {
        self.create_file_with_options(actor, parent, name, content, CreateOptions::default())
    }

    /// Creates a directory in a directory.
    pub fn create_directory(
        &self,
        actor: Option<ActorId>,
        parent: ObjectId,
        name: Name,
    ) -> Result<ObjectId, Error> {
        self.create_directory_with_options(actor, parent, name, CreateOptions::default())
    }

    /// Creates a file with initial owner and authorization data.
    ///
    /// The object appears with the given metadata already applied, within the
    /// same atomic mutation as the creation itself. This is how the OS layer
    /// creates objects that are owned and secured from the moment they exist.
    pub fn create_file_with_options(
        &self,
        actor: Option<ActorId>,
        parent: ObjectId,
        name: Name,
        content: Option<Vec<u8>>,
        options: CreateOptions,
    ) -> Result<ObjectId, Error> {
        self.create(actor, parent, name, ObjectKind::File { content }, options)
    }

    /// Creates a directory with initial owner and authorization data.
    pub fn create_directory_with_options(
        &self,
        actor: Option<ActorId>,
        parent: ObjectId,
        name: Name,
        options: CreateOptions,
    ) -> Result<ObjectId, Error> {
        self.create(actor, parent, name, ObjectKind::Directory, options)
    }

    /// Creates a detached namespace outside the filesystem tree.
    ///
    /// Authorization checks [`Operation::Create`] against the root object,
    /// which stands in as the pseudo-parent.
    pub fn create_detached_namespace(
        &self,
        actor: Option<ActorId>,
        name: Name,
    ) -> Result<DetachedNamespace, Error> {
        let root = self.root();
        self.authorize(actor, Operation::Create, root)?;
        let now = self.now();
        let id = {
            let mut store = self.store.lock().expect("store lock poisoned");
            store.create_detached(name, now)?
        };
        self.dispatch(ObjectEvent::new(EventType::ObjectCreated, id, actor, now));
        Ok(DetachedNamespace::new(id))
    }

    /// Writes a file's content.
    ///
    /// Replaces any existing content and updates the modified timestamp.
    pub fn write(
        &self,
        actor: Option<ActorId>,
        file: ObjectId,
        content: Vec<u8>,
    ) -> Result<(), Error> {
        let now = self.now();
        // A link writes its target.
        let file = self.resolve_links(file)?;
        let event = {
            let mut store = self.store.lock().expect("store lock poisoned");
            Self::authorize_in_store(&store, &*self.policy, actor, Operation::Write, file)?;
            let data = store.get_mut(file).ok_or(Error::ObjectNotFound(file))?;
            match &mut data.kind {
                ObjectKind::File { content: target } => *target = Some(content),
                ObjectKind::Directory => return Err(Error::NotAFile(file)),
                ObjectKind::Symlink { .. } => unreachable!("links resolve above"),
            }
            data.metadata.set_modified(now);
            ObjectEvent::new(EventType::ObjectWritten, file, actor, now)
        };
        self.dispatch(event);
        Ok(())
    }

    /// Replaces a file's content, owner, and authorization atomically.
    ///
    /// This is the filesystem equivalent of creating a fully described file:
    /// observers can never see the new bytes with stale ownership or access
    /// metadata. The normal write, owner, and metadata authorizations are all
    /// checked before any field changes.
    pub fn replace_file_with_options(
        &self,
        actor: Option<ActorId>,
        file: ObjectId,
        content: Vec<u8>,
        options: CreateOptions,
    ) -> Result<(), Error> {
        let now = self.now();
        let file = self.resolve_links(file)?;
        let mut chain = EventChain::new(actor, now);
        {
            let mut store = self.store.lock().expect("store lock poisoned");
            Self::authorize_in_store(&store, &*self.policy, actor, Operation::Write, file)?;
            Self::authorize_in_store(&store, &*self.policy, actor, Operation::ChangeOwner, file)?;
            Self::authorize_in_store(
                &store,
                &*self.policy,
                actor,
                Operation::ChangeMetadata,
                file,
            )?;
            let data = store.get_mut(file).ok_or(Error::ObjectNotFound(file))?;
            match &mut data.kind {
                ObjectKind::File { content: target } => *target = Some(content),
                ObjectKind::Directory => return Err(Error::NotAFile(file)),
                ObjectKind::Symlink { .. } => unreachable!("links resolve above"),
            }
            data.metadata.set_owner(options.owner);
            data.metadata.set_authorization(options.authorization);
            data.metadata.set_modified(now);
            chain.events.extend([
                ObjectEvent::new(EventType::ObjectWritten, file, actor, now),
                ObjectEvent::new(EventType::OwnerChanged, file, actor, now),
                ObjectEvent::new(EventType::AuthorizationChanged, file, actor, now),
            ]);
        }
        self.dispatch_chain(chain);
        Ok(())
    }

    /// Appends to a file's content.
    ///
    /// If the file is metadata-only, it becomes content-bearing. Appending to
    /// a directory is an error.
    pub fn append(
        &self,
        actor: Option<ActorId>,
        file: ObjectId,
        content: Vec<u8>,
    ) -> Result<(), Error> {
        let now = self.now();
        // A link appends to its target.
        let file = self.resolve_links(file)?;
        let event = {
            let mut store = self.store.lock().expect("store lock poisoned");
            Self::authorize_in_store(&store, &*self.policy, actor, Operation::Write, file)?;
            let data = store.get_mut(file).ok_or(Error::ObjectNotFound(file))?;
            match &mut data.kind {
                ObjectKind::File { content: target } => match target {
                    Some(existing) => existing.extend(content),
                    None => *target = Some(content),
                },
                ObjectKind::Directory => return Err(Error::NotAFile(file)),
                ObjectKind::Symlink { .. } => unreachable!("links resolve above"),
            }
            data.metadata.set_modified(now);
            ObjectEvent::new(EventType::ObjectWritten, file, actor, now)
        };
        self.dispatch(event);
        Ok(())
    }

    /// Updates an object's modified and accessed timestamps.
    pub fn touch(&self, actor: Option<ActorId>, object: ObjectId) -> Result<(), Error> {
        let now = self.now();
        let event = {
            let mut store = self.store.lock().expect("store lock poisoned");
            Self::authorize_in_store(
                &store,
                &*self.policy,
                actor,
                Operation::ChangeMetadata,
                object,
            )?;
            let data = store.get_mut(object).ok_or(Error::ObjectNotFound(object))?;
            data.metadata.set_modified(now);
            data.metadata.set_accessed(now);
            ObjectEvent::new(EventType::MetadataChanged, object, actor, now)
        };
        self.dispatch(event);
        Ok(())
    }

    /// Moves or renames an object.
    ///
    /// `new_name` renames the object; otherwise the name is kept. Moving an
    /// object into itself or one of its descendants is rejected. The root
    /// cannot be moved. The move is authorized twice: [`Operation::Move`]
    /// against the object (so the policy can enforce parent-directory
    /// rules) and [`Operation::Create`] against the destination directory.
    pub fn move_object(
        &self,
        actor: Option<ActorId>,
        object: ObjectId,
        destination: ObjectId,
        new_name: Option<Name>,
    ) -> Result<(), Error> {
        let now = self.now();
        let event = {
            let mut store = self.store.lock().expect("store lock poisoned");
            Self::authorize_in_store(&store, &*self.policy, actor, Operation::Move, object)?;
            Self::authorize_in_store(&store, &*self.policy, actor, Operation::Create, destination)?;
            if object == store.root() {
                return Err(Error::RootMove);
            }
            let old_parent = store
                .get(object)
                .ok_or(Error::ObjectNotFound(object))?
                .parent;
            store.require_directory(destination)?;
            if object == destination || store.is_ancestor_of(object, destination) {
                return Err(Error::CyclicMove(object));
            }
            // POSIX semantics: moving an object onto itself (same parent,
            // same name — whether or not that name was spelled explicitly)
            // succeeds and changes nothing observable, even though a name
            // lookup would find the object itself.
            let current_name = store
                .get(object)
                .expect("object existence checked above")
                .metadata
                .name()
                .clone();
            if old_parent == Some(destination)
                && new_name.as_ref().is_none_or(|new| *new == current_name)
            {
                return Ok(());
            }
            let effective_name = match &new_name {
                Some(name) => name.clone(),
                None => current_name,
            };
            let conflict = store.has_child_named(destination, &effective_name)?;
            if conflict {
                return Err(Error::NameAlreadyExists {
                    name: effective_name,
                    directory: destination,
                });
            }
            let old_parent = store.detach(object)?;
            store.attach(object, destination)?;
            if let Some(name) = new_name {
                store.rename(object, name)?;
            }
            ObjectEvent {
                event_type: EventType::ObjectMoved,
                object,
                source_parent: old_parent,
                destination_parent: Some(destination),
                actor,
                timestamp: now,
                data: EventData::new(),
            }
        };
        self.dispatch(event);
        Ok(())
    }

    /// Detaches an object from its parent, leaving it in the store but
    /// unreachable from the root. The root cannot be detached.
    pub fn detach_object(&self, actor: Option<ActorId>, object: ObjectId) -> Result<(), Error> {
        let now = self.now();
        let event = {
            let mut store = self.store.lock().expect("store lock poisoned");
            Self::authorize_in_store(&store, &*self.policy, actor, Operation::Move, object)?;
            if object == store.root() {
                return Err(Error::RootDetach);
            }
            // Detaching an already-detached object changes nothing and
            // emits nothing.
            if store
                .get(object)
                .ok_or(Error::ObjectNotFound(object))?
                .parent
                .is_none()
            {
                return Ok(());
            }
            let old_parent = store.detach(object)?;
            ObjectEvent {
                event_type: EventType::Detached,
                object,
                source_parent: old_parent,
                destination_parent: None,
                actor,
                timestamp: now,
                data: EventData::new(),
            }
        };
        self.dispatch(event);
        Ok(())
    }

    /// Attaches a detached object as a child of `destination`.
    ///
    /// The object must genuinely be detached (it may not hang in two places
    /// at once), and it may not be attached beneath itself or one of its
    /// descendants — either would corrupt the tree invariant that every
    /// object has exactly one parent. Authorized as [`Operation::Move`]
    /// against the object and [`Operation::Create`] against the destination
    /// directory.
    pub fn attach_object(
        &self,
        actor: Option<ActorId>,
        object: ObjectId,
        destination: ObjectId,
    ) -> Result<(), Error> {
        let now = self.now();
        let event = {
            let mut store = self.store.lock().expect("store lock poisoned");
            Self::authorize_in_store(&store, &*self.policy, actor, Operation::Move, object)?;
            Self::authorize_in_store(&store, &*self.policy, actor, Operation::Create, destination)?;
            store.require_directory(destination)?;
            let data = store.get(object).ok_or(Error::ObjectNotFound(object))?;
            if data.parent.is_some() {
                return Err(Error::AttachedObject(object));
            }
            if object == destination || store.is_ancestor_of(object, destination) {
                return Err(Error::CyclicAttach(object));
            }
            let name = data.metadata.name().clone();
            if store.has_child_named(destination, &name)? {
                return Err(Error::NameAlreadyExists {
                    name,
                    directory: destination,
                });
            }
            store.attach(object, destination)?;
            ObjectEvent {
                event_type: EventType::Attached,
                object,
                source_parent: None,
                destination_parent: Some(destination),
                actor,
                timestamp: now,
                data: EventData::new(),
            }
        };
        self.dispatch(event);
        Ok(())
    }

    /// Copies an object and its subtree into a directory.
    ///
    /// The copy receives a fresh identity and faithfully clones the source's
    /// metadata. Copying an object into itself or one of its descendants is
    /// rejected. The root may be copied. Authorized as [`Operation::Copy`]
    /// against the object and [`Operation::Create`] against the destination
    /// directory.
    pub fn copy_object(
        &self,
        actor: Option<ActorId>,
        object: ObjectId,
        destination: ObjectId,
        name: Name,
    ) -> Result<ObjectId, Error> {
        let mut chain = EventChain::new(actor, self.now());
        let new_id = {
            let mut store = self.store.lock().expect("store lock poisoned");
            Self::authorize_in_store(&store, &*self.policy, actor, Operation::Copy, object)?;
            Self::authorize_in_store(&store, &*self.policy, actor, Operation::Create, destination)?;
            store.require_directory(destination)?;
            if object == destination || store.is_ancestor_of(object, destination) {
                return Err(Error::CyclicCopy(object));
            }
            self.copy_into(&mut store, object, destination, &name, &mut chain)?
        };
        self.dispatch_chain(chain);
        Ok(new_id)
    }

    /// Deletes an object and, for directories, its entire subtree.
    ///
    /// The root cannot be deleted. Events are dispatched deepest-first (a
    /// directory's children are reported deleted before the directory
    /// itself). Each deleted object emits an [`EventType::ObjectDeleted`]
    /// event carrying its former parent.
    pub fn delete(&self, actor: Option<ActorId>, object: ObjectId) -> Result<(), Error> {
        let mut chain = EventChain::new(actor, self.now());
        {
            let mut store = self.store.lock().expect("store lock poisoned");
            Self::authorize_in_store(&store, &*self.policy, actor, Operation::Delete, object)?;
            if object == store.root() {
                return Err(Error::RootDelete);
            }
            self.delete_recursive(&mut store, object, &mut chain)?;
        }
        self.dispatch_chain(chain);
        Ok(())
    }

    /// Sets an object's owner. `None` clears ownership.
    ///
    /// Changing the owner is a distinct operation from other metadata changes
    /// ([`Operation::ChangeOwner`]) so that policies may restrict it further.
    pub fn set_owner(
        &self,
        actor: Option<ActorId>,
        object: ObjectId,
        owner: Option<ActorId>,
    ) -> Result<(), Error> {
        self.set_owner_and_authorization(
            actor,
            object,
            Some(owner),
            None,
            EventType::AuthorizationChanged,
        )
    }

    /// Sets an object's opaque authorization data.
    pub fn set_authorization(
        &self,
        actor: Option<ActorId>,
        object: ObjectId,
        authorization: AuthorizationData,
    ) -> Result<(), Error> {
        self.set_owner_and_authorization(
            actor,
            object,
            None,
            Some(authorization),
            EventType::AuthorizationChanged,
        )
    }

    /// Sets an object's permissions (generic, e.g., Unix mode bits).
    ///
    /// This is a convenience wrapper around [`Self::set_authorization`] that
    /// emits [`EventType::PermissionsChanged`] so observers filtering for
    /// permission changes are notified.
    pub fn set_permissions(
        &self,
        actor: Option<ActorId>,
        object: ObjectId,
        authorization: AuthorizationData,
    ) -> Result<(), Error> {
        self.set_owner_and_authorization(
            actor,
            object,
            None,
            Some(authorization),
            EventType::PermissionsChanged,
        )
    }

    /// Sets an object's group (generic).
    ///
    /// Emits [`EventType::GroupChanged`] for observers filtering for group
    /// changes.
    pub fn set_group(
        &self,
        actor: Option<ActorId>,
        object: ObjectId,
        authorization: AuthorizationData,
    ) -> Result<(), Error> {
        self.set_owner_and_authorization(
            actor,
            object,
            None,
            Some(authorization),
            EventType::GroupChanged,
        )
    }

    /// Atomically sets owner and authorization in one mutation.
    ///
    /// When `owner` is `Some`, [`Operation::ChangeOwner`] is checked; when
    /// `authorization` is `Some`, [`Operation::ChangeMetadata`] is checked.
    /// All changes are applied under one store lock and their events are
    /// dispatched as a single chain before returning.
    ///
    /// The engine does not interpret authorization data, so it cannot choose
    /// the event type; the caller names the semantic ([`EventType::GroupChanged`],
    /// [`EventType::PermissionsChanged`], or [`EventType::AuthorizationChanged`])
    /// and the engine emits exactly that event when authorization data is set.
    pub fn set_owner_and_authorization(
        &self,
        actor: Option<ActorId>,
        object: ObjectId,
        owner: Option<Option<ActorId>>,
        authorization: Option<AuthorizationData>,
        authorization_event: EventType,
    ) -> Result<(), Error> {
        let now = self.now();
        let mut chain = EventChain::new(actor, now);
        {
            let mut store = self.store.lock().expect("store lock poisoned");
            if owner.is_some() {
                Self::authorize_in_store(
                    &store,
                    &*self.policy,
                    actor,
                    Operation::ChangeOwner,
                    object,
                )?;
            }
            if authorization.is_some() {
                Self::authorize_in_store(
                    &store,
                    &*self.policy,
                    actor,
                    Operation::ChangeMetadata,
                    object,
                )?;
            }
            let data = store.get_mut(object).ok_or(Error::ObjectNotFound(object))?;
            if let Some(owner) = owner {
                data.metadata.set_owner(owner);
                chain.events.push(ObjectEvent::new(
                    EventType::OwnerChanged,
                    object,
                    actor,
                    now,
                ));
            }
            if let Some(authorization) = authorization {
                data.metadata.set_authorization(authorization);
                chain
                    .events
                    .push(ObjectEvent::new(authorization_event, object, actor, now));
            }
        }
        self.dispatch_chain(chain);
        Ok(())
    }

    /// Applies a metadata patch atomically.
    pub fn update_metadata(
        &self,
        actor: Option<ActorId>,
        object: ObjectId,
        patch: &MetadataPatch,
    ) -> Result<(), Error> {
        // An empty patch changes nothing and emits nothing.
        if patch.is_empty() {
            return Ok(());
        }
        let now = self.now();
        let event = {
            let mut store = self.store.lock().expect("store lock poisoned");
            Self::authorize_in_store(
                &store,
                &*self.policy,
                actor,
                Operation::ChangeMetadata,
                object,
            )?;
            let data = store.get_mut(object).ok_or(Error::ObjectNotFound(object))?;
            data.metadata.apply(patch)?;
            ObjectEvent::new(EventType::MetadataChanged, object, actor, now)
        };
        self.dispatch(event);
        Ok(())
    }

    // ------------------------------------------------------------------
    // Internal helpers
    // ------------------------------------------------------------------

    fn now(&self) -> Timestamp {
        let mut current = self.clock.now().as_nanos();
        current = current.saturating_add(SUSPENDED_BOOKS.with(|books| {
            books
                .borrow()
                .iter()
                .fold(0u64, |sum, book| sum.saturating_add(*book))
        }));
        Timestamp::from_nanos(current)
    }

    fn dispatch(&self, event: ObjectEvent) {
        // One dispatch at a time per Engine (see `dispatch_lock`): dispatch
        // runs listeners with the listener list taken out of the bus, so
        // two concurrent dispatches would hand one of them an empty list
        // and silently drop its event chain. The guard is reentrant per
        // Engine: a listener that mutates Engine state dispatches again on
        // this thread while the outer dispatch already holds the lock, and
        // must not wait on itself — but a listener touching a
        // different Engine must take that Engine's lock.
        let token = std::sync::Arc::as_ptr(&self.dispatch_lock) as usize;
        let reentrant = ACTIVE_DISPATCHES.with(|active| active.borrow().contains(&token));
        if reentrant {
            self.dispatch_inner(event);
            return;
        }
        // The guard marks this thread as dispatching on this Engine and
        // clears the mark when dropped, so even a panicking listener cannot
        // leave dispatch silently unlocked.
        let _flag = DispatchFlag::enter(token);
        let _dispatching = self.dispatch_lock.lock().expect("dispatch lock poisoned");
        self.dispatch_inner(event);
    }

    fn dispatch_inner(&self, event: ObjectEvent) {
        let mut listeners = self
            .bus
            .lock()
            .expect("event bus lock poisoned")
            .detach_listeners();
        crate::events::event_bus::run_listeners(&mut listeners, &event);
        self.bus
            .lock()
            .expect("event bus lock poisoned")
            .reattach_listeners(listeners);
    }

    /// Dispatches every event in a chain, in order.
    fn dispatch_chain(&self, chain: EventChain) {
        for event in chain.events {
            self.dispatch(event);
        }
    }

    fn authorize(
        &self,
        actor: Option<ActorId>,
        operation: Operation,
        object: ObjectId,
    ) -> Result<(), Error> {
        let store = self.store.lock().expect("store lock poisoned");
        Self::authorize_in_store(&store, &*self.policy, actor, operation, object)
    }

    /// Authorizes against an already-locked store.
    ///
    /// Mutating operations call this *inside* their locked scope, so the
    /// policy decision observes exactly the metadata the mutation will
    /// apply to — there is no window in which a concurrent permission
    /// revocation can be bypassed by an earlier snapshot.
    fn authorize_in_store(
        store: &ObjectStore,
        policy: &dyn AuthorizationPolicy,
        actor: Option<ActorId>,
        operation: Operation,
        object: ObjectId,
    ) -> Result<(), Error> {
        let data = store.get(object).ok_or(Error::ObjectNotFound(object))?;
        let parent = data
            .parent
            .and_then(|parent_id| store.get(parent_id))
            .map(
                |parent_data| crate::security::authorization::ParentReference {
                    object: parent_data.id,
                    metadata: &parent_data.metadata,
                },
            );
        let request = AuthorizationRequest {
            actor,
            operation,
            object,
            metadata: &data.metadata,
            parent,
        };
        match policy.authorize(&request) {
            AuthorizationResult::Allowed => Ok(()),
            AuthorizationResult::Denied { .. } => Err(Error::NotAuthorized {
                object,
                operation,
                actor,
            }),
        }
    }

    fn create(
        &self,
        actor: Option<ActorId>,
        parent: ObjectId,
        name: Name,
        kind: ObjectKind,
        options: CreateOptions,
    ) -> Result<ObjectId, Error> {
        let now = self.now();
        let (id, event) = {
            let mut store = self.store.lock().expect("store lock poisoned");
            Self::authorize_in_store(&store, &*self.policy, actor, Operation::Create, parent)?;
            let id = store.create(parent, name, kind, now)?;
            let data = store.get_mut(id).expect("created object exists");
            data.metadata.set_owner(options.owner);
            data.metadata.set_authorization(options.authorization);
            let event = ObjectEvent {
                source_parent: Some(parent),
                ..ObjectEvent::new(EventType::ObjectCreated, id, actor, now)
            };
            (id, event)
        };
        self.dispatch(event);
        Ok(id)
    }

    fn copy_into(
        &self,
        store: &mut ObjectStore,
        source: ObjectId,
        destination: ObjectId,
        name: &Name,
        chain: &mut EventChain,
    ) -> Result<ObjectId, Error> {
        let new_id = store.clone_into(source, destination, name.clone())?;
        let mut data = EventData::new();
        data.insert(
            COPY_SOURCE_KEY,
            crate::core::metadata::MetadataValue::Unsigned(source.get()),
        );
        chain.events.push(ObjectEvent {
            event_type: EventType::ObjectCopied,
            object: new_id,
            source_parent: Some(destination),
            destination_parent: Some(destination),
            actor: chain.actor,
            timestamp: chain.now,
            data,
        });
        // Each child is announced (Created) *before* its own subtree is
        // copied, so a listener rebuilding the hierarchy from events sees
        // parents arrive first.
        let children: Vec<ObjectId> = store
            .get(source)
            .ok_or(Error::ObjectNotFound(source))?
            .children
            .iter()
            .copied()
            .collect();
        for child in children {
            let child_data = store.get(child).ok_or(Error::ObjectNotFound(child))?;
            let child_name = child_data.metadata.name().clone();
            let child_copy = store.clone_into(child, new_id, child_name)?;
            chain.events.push(ObjectEvent {
                event_type: EventType::ObjectCreated,
                object: child_copy,
                source_parent: Some(new_id),
                destination_parent: Some(new_id),
                actor: chain.actor,
                timestamp: chain.now,
                data: EventData::new(),
            });
            self.copy_children_into(store, child, child_copy, chain)?;
        }
        Ok(new_id)
    }

    /// Copies the children of `source` into the already-created copy
    /// `target`, emitting each child's Created event before its subtree.
    fn copy_children_into(
        &self,
        store: &mut ObjectStore,
        source: ObjectId,
        target: ObjectId,
        chain: &mut EventChain,
    ) -> Result<(), Error> {
        let children: Vec<ObjectId> = store
            .get(source)
            .ok_or(Error::ObjectNotFound(source))?
            .children
            .iter()
            .copied()
            .collect();
        for child in children {
            let child_data = store.get(child).ok_or(Error::ObjectNotFound(child))?;
            let child_name = child_data.metadata.name().clone();
            let child_copy = store.clone_into(child, target, child_name)?;
            chain.events.push(ObjectEvent {
                event_type: EventType::ObjectCreated,
                object: child_copy,
                source_parent: Some(target),
                destination_parent: Some(target),
                actor: chain.actor,
                timestamp: chain.now,
                data: EventData::new(),
            });
            self.copy_children_into(store, child, child_copy, chain)?;
        }
        Ok(())
    }

    fn delete_recursive(
        &self,
        store: &mut ObjectStore,
        object: ObjectId,
        chain: &mut EventChain,
    ) -> Result<(), Error> {
        let children: Vec<ObjectId> = store
            .get(object)
            .ok_or(Error::ObjectNotFound(object))?
            .children
            .iter()
            .copied()
            .collect();
        for child in children {
            self.delete_recursive(store, child, chain)?;
        }
        let old_parent = store.detach(object)?;
        store.remove(object)?;
        chain.events.push(ObjectEvent {
            event_type: EventType::ObjectDeleted,
            object,
            source_parent: old_parent,
            destination_parent: None,
            actor: chain.actor,
            timestamp: chain.now,
            data: EventData::new(),
        });
        Ok(())
    }
}

impl Default for Engine {
    fn default() -> Self {
        Self::with_virtual_clock(Box::new(PermissivePolicy))
    }
}