ailloli_ui_fs/
tree.rs

1//! Persistent, I/O-free filesystem tree state, reconciliation, and cache eviction.
2
3use std::collections::{HashMap, HashSet, VecDeque};
4use std::time::{Duration, Instant};
5
6use crate::{FileEntry, FileError, FileMetadata, FileUri, WatchEvent, WatchEventKind};
7
8/// Default soft cache limit of 100,000 retained nodes.
9///
10/// This is an eviction threshold, not an insertion limit.
11///
12/// # Examples
13///
14/// ```
15/// use ailloli_ui_fs::DEFAULT_FILE_TREE_MAX_NODES;
16/// assert_eq!(DEFAULT_FILE_TREE_MAX_NODES, 100_000);
17/// ```
18pub const DEFAULT_FILE_TREE_MAX_NODES: usize = 100_000;
19
20/// Default soft estimate limit of 128 MiB of retained node payload.
21///
22/// The estimate excludes allocator/hash-table overhead and file contents.
23///
24/// # Examples
25///
26/// ```
27/// use ailloli_ui_fs::DEFAULT_FILE_TREE_MAX_PAYLOAD_BYTES;
28/// assert_eq!(DEFAULT_FILE_TREE_MAX_PAYLOAD_BYTES, 128 * 1024 * 1024);
29/// ```
30pub const DEFAULT_FILE_TREE_MAX_PAYLOAD_BYTES: usize = 128 * 1024 * 1024;
31
32/// Default five-minute retention time for descendants of collapsed directories.
33///
34/// # Examples
35///
36/// ```
37/// use ailloli_ui_fs::DEFAULT_FILE_TREE_COLLAPSED_TTL;
38/// use std::time::Duration;
39/// assert_eq!(DEFAULT_FILE_TREE_COLLAPSED_TTL, Duration::from_secs(300));
40/// ```
41pub const DEFAULT_FILE_TREE_COLLAPSED_TTL: Duration = Duration::from_secs(5 * 60);
42
43/// Session cache policy. Cache maintenance is explicit and never performs
44/// hidden I/O: coordinators call [`FileTreeStore::evict_expired`] at the
45/// instant returned by [`FileTreeStore::next_cache_maintenance_due`].
46///
47/// Limits are soft eviction triggers and are not validated or enforced during
48/// insertion. Zero node/byte limits and a zero TTL are valid and request
49/// immediate eligible eviction.
50///
51/// # Examples
52///
53/// ```
54/// use ailloli_ui_fs::{FileTreeStoreLimits, DEFAULT_FILE_TREE_MAX_NODES};
55/// assert_eq!(FileTreeStoreLimits::default().max_nodes, DEFAULT_FILE_TREE_MAX_NODES);
56/// ```
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub struct FileTreeStoreLimits {
59    /// Soft maximum number of retained nodes, including the root.
60    pub max_nodes: usize,
61    /// Soft maximum estimated payload in bytes.
62    pub max_payload_bytes: usize,
63    /// Retention time after a directory becomes collapsed.
64    pub collapsed_ttl: Duration,
65}
66
67impl Default for FileTreeStoreLimits {
68    fn default() -> Self {
69        Self {
70            max_nodes: DEFAULT_FILE_TREE_MAX_NODES,
71            max_payload_bytes: DEFAULT_FILE_TREE_MAX_PAYLOAD_BYTES,
72            collapsed_ttl: DEFAULT_FILE_TREE_COLLAPSED_TTL,
73        }
74    }
75}
76
77/// Permanent structural counters for one live filesystem store.
78///
79/// `nodes` and `estimated_payload_bytes` are live values recomputed for each
80/// snapshot. All other counters accumulate with saturation and never wrap.
81///
82/// # Examples
83///
84/// ```
85/// use ailloli_ui_fs::FileTreeStoreDiagnostics;
86/// let diagnostics = FileTreeStoreDiagnostics::default();
87/// assert_eq!((diagnostics.nodes, diagnostics.watch_events), (0, 0));
88/// ```
89#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
90pub struct FileTreeStoreDiagnostics {
91    /// Current retained node count.
92    pub nodes: usize,
93    /// Approximate current node payload bytes, excluding map/allocator overhead.
94    pub estimated_payload_bytes: usize,
95    /// Directory load requests successfully started.
96    pub directory_loads_started: u64,
97    /// Non-stale directory results accepted, including provider errors.
98    pub directory_results_applied: u64,
99    /// Accepted directory results that contained a provider error.
100    pub directory_errors: u64,
101    /// Rejected directory responses whose request/generation was stale.
102    pub stale_responses: u64,
103    /// Watch events presented to the store, including duplicates.
104    pub watch_events: u64,
105    /// Old, repeated, or attested-operation echo events ignored.
106    pub duplicate_watch_events: u64,
107    /// Forward sequence gaps detected after a nonzero prior sequence.
108    pub watch_sequence_gaps: u64,
109    /// Nodes removed by eviction, reconciliation, watch, or attested removal.
110    pub evicted_nodes: u64,
111    /// Non-empty revision deltas successfully emitted.
112    pub emitted_deltas: u64,
113}
114
115/// Per-node timestamps used only by explicit cache maintenance.
116#[derive(Debug, Clone, Copy)]
117struct FileTreeCacheState {
118    /// Most recent explicit/UI state touch.
119    last_used: Instant,
120    /// Instant the node most recently became collapsed, or `None` while expanded.
121    collapsed_at: Option<Instant>,
122}
123
124/// Maximum number of attested-operation watcher echoes retained for deduplication.
125const WATCH_ECHO_CAPACITY: usize = 256;
126
127/// Mutation signature expected to be echoed later by a native watcher.
128#[derive(Debug, Clone, PartialEq, Eq)]
129enum WatchEcho {
130    /// Echo of an attested create.
131    Created(FileUri),
132    /// Echo of an attested removal.
133    Removed(FileUri),
134    /// Echo of an attested rename or move.
135    Moved {
136        /// Previous URI.
137        from: FileUri,
138        /// New URI.
139        to: FileUri,
140    },
141}
142
143/// Stable identity supplied by a filesystem backend when available.
144///
145/// `provider` namespaces opaque identity bytes. Empty provider/value components
146/// are accepted, and multiple nodes may intentionally share an identity (for
147/// example hard links).
148///
149/// # Examples
150///
151/// ```
152/// use ailloli_ui_fs::FileIdentity;
153/// let identity = FileIdentity::new("local", 42_u64.to_le_bytes());
154/// assert_eq!(identity.provider(), "local");
155/// ```
156#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
157pub struct FileIdentity {
158    /// Backend namespace that gives `value` provider-local meaning.
159    provider: String,
160    /// Opaque backend bytes; equality is byte-for-byte within `provider`.
161    value: Vec<u8>,
162}
163
164impl FileIdentity {
165    /// Stores a provider namespace and opaque bytes verbatim.
166    ///
167    /// # Examples
168    ///
169    /// ```
170    /// use ailloli_ui_fs::FileIdentity;
171    /// let identity = FileIdentity::new("", Vec::<u8>::new());
172    /// assert!(identity.provider().is_empty() && identity.value().is_empty());
173    /// ```
174    pub fn new(provider: impl Into<String>, value: impl Into<Vec<u8>>) -> Self {
175        Self {
176            provider: provider.into(),
177            value: value.into(),
178        }
179    }
180
181    /// Borrows the provider namespace; it may be empty.
182    ///
183    /// # Examples
184    ///
185    /// ```
186    /// use ailloli_ui_fs::FileIdentity;
187    /// assert_eq!(FileIdentity::new("sftp", [1]).provider(), "sftp");
188    /// ```
189    pub fn provider(&self) -> &str {
190        &self.provider
191    }
192
193    /// Borrows the opaque identity bytes; the slice may be empty.
194    ///
195    /// # Examples
196    ///
197    /// ```
198    /// use ailloli_ui_fs::FileIdentity;
199    /// assert_eq!(FileIdentity::new("local", [1, 2]).value(), &[1, 2]);
200    /// ```
201    pub fn value(&self) -> &[u8] {
202        &self.value
203    }
204}
205
206/// Opaque, monotone identity allocated by one [`FileTreeStore`].
207///
208/// IDs are meaningful only within the store that allocated them, are never
209/// reused, and may refer to a removed/reserved node. The initial root is `1`.
210/// Derived deserialization accepts every `u64`, including `0` and IDs no store
211/// allocated; always validate a deserialized ID by querying its intended store.
212///
213/// # Examples
214///
215/// ```
216/// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
217/// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
218/// assert_eq!(store.root().get(), 1);
219/// # Ok::<(), Box<dyn std::error::Error>>(())
220/// ```
221#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
222pub struct FileTreeNodeId(
223    /// Raw store-local numeric representation.
224    u64,
225);
226
227impl FileTreeNodeId {
228    /// Returns the store-local numeric representation.
229    ///
230    /// # Examples
231    ///
232    /// ```
233    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
234    /// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
235    /// let raw: u64 = store.root().get();
236    /// assert_eq!(raw, 1);
237    /// # Ok::<(), Box<dyn std::error::Error>>(())
238    /// ```
239    pub const fn get(self) -> u64 {
240        self.0
241    }
242}
243
244/// Retained load state of a directory node.
245///
246/// # Examples
247///
248/// ```
249/// use ailloli_ui_fs::DirectoryLoadState;
250/// assert!(matches!(DirectoryLoadState::Unloaded, DirectoryLoadState::Unloaded));
251/// ```
252#[non_exhaustive]
253#[derive(Debug, Clone, PartialEq, Eq)]
254pub enum DirectoryLoadState {
255    /// Children have not been loaded or were explicitly evicted.
256    Unloaded,
257    /// A provider request is active for the store generation.
258    Loading {
259        /// [`FileTreeStore::generation`] captured when the request began.
260        generation: u64,
261    },
262    /// A provider result was reconciled successfully.
263    Loaded {
264        /// Store revision assigned to the result delta.
265        revision: u64,
266    },
267    /// Retained children may be outdated and should be refreshed.
268    Stale,
269    /// The last accepted provider result failed; existing children are retained.
270    Error(
271        /// Most recent accepted provider listing failure.
272        FileError,
273    ),
274}
275
276/// Provider-owned result correlation. Presentation generations deliberately do
277/// not appear here, so a load survives native surface suspend/resume.
278///
279/// Requests are constructed only by [`FileTreeStore::begin_directory_load`].
280/// Their ID and store generation must both match when a result is applied.
281///
282/// # Examples
283///
284/// ```
285/// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
286/// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
287/// let (request, _) = store.begin_directory_load(store.root())?;
288/// assert_eq!(request.node_id(), store.root());
289/// # Ok::<(), Box<dyn std::error::Error>>(())
290/// ```
291#[derive(Debug, Clone, PartialEq, Eq)]
292pub struct DirectoryLoadRequest {
293    /// Monotone correlation allocated by the originating store.
294    request_id: u64,
295    /// Directory that was live when the request began.
296    node_id: FileTreeNodeId,
297    /// Store generation that must still match at response time.
298    store_generation: u64,
299    /// Directory URI snapshot sent to the provider worker.
300    uri: FileUri,
301}
302
303impl DirectoryLoadRequest {
304    /// Returns the monotone request correlation ID.
305    ///
306    /// # Examples
307    ///
308    /// ```
309    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
310    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
311    /// assert_eq!(store.begin_directory_load(store.root())?.0.request_id(), 1);
312    /// # Ok::<(), Box<dyn std::error::Error>>(())
313    /// ```
314    pub const fn request_id(&self) -> u64 {
315        self.request_id
316    }
317
318    /// Returns the directory node whose children were requested.
319    ///
320    /// # Examples
321    ///
322    /// ```
323    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
324    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
325    /// let (request, _) = store.begin_directory_load(store.root())?;
326    /// assert_eq!(request.node_id(), store.root());
327    /// # Ok::<(), Box<dyn std::error::Error>>(())
328    /// ```
329    pub const fn node_id(&self) -> FileTreeNodeId {
330        self.node_id
331    }
332
333    /// Returns the store generation captured at request creation.
334    ///
335    /// # Examples
336    ///
337    /// ```
338    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
339    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
340    /// let (request, _) = store.begin_directory_load(store.root())?;
341    /// assert_eq!(request.store_generation(), 1);
342    /// # Ok::<(), Box<dyn std::error::Error>>(())
343    /// ```
344    pub const fn store_generation(&self) -> u64 {
345        self.store_generation
346    }
347
348    /// Borrows the directory URI captured when loading began.
349    ///
350    /// # Examples
351    ///
352    /// ```
353    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
354    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
355    /// let (request, _) = store.begin_directory_load(store.root())?;
356    /// assert_eq!(request.uri().path(), "/");
357    /// # Ok::<(), Box<dyn std::error::Error>>(())
358    /// ```
359    pub fn uri(&self) -> &FileUri {
360        &self.uri
361    }
362}
363
364/// Retained node in a [`FileTreeStore`].
365///
366/// Nodes expose immutable snapshots; all mutation goes through the store so its
367/// URI/identity indexes and deltas remain coherent.
368///
369/// # Examples
370///
371/// ```
372/// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
373/// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
374/// assert_eq!(store.node(store.root()).unwrap().id(), store.root());
375/// # Ok::<(), Box<dyn std::error::Error>>(())
376/// ```
377#[derive(Debug, Clone)]
378pub struct FileTreeNode {
379    /// Stable, store-local identity.
380    id: FileTreeNodeId,
381    /// Retained structural parent, or `None` for the initial root.
382    parent: Option<FileTreeNodeId>,
383    /// Current provider URI, mirrored in the store URI index.
384    uri: FileUri,
385    /// Optional provider identity, mirrored in the non-unique identity index.
386    identity: Option<FileIdentity>,
387    /// Latest provider metadata snapshot.
388    metadata: FileMetadata,
389    /// Ordered retained direct children.
390    children: Vec<FileTreeNodeId>,
391    /// Directory listing lifecycle; also initialized on non-directory nodes.
392    directory_state: DirectoryLoadState,
393    /// UI expansion flag and an eviction pin when `true`.
394    expanded: bool,
395    /// UI selection flag and an eviction pin when `true`.
396    selected: bool,
397    /// UI focus flag and an eviction pin when `true`.
398    focused: bool,
399    /// Provider-mutation flag and an eviction pin when `true`.
400    pending_operation: bool,
401}
402
403impl FileTreeNode {
404    /// Returns the opaque store-local node ID.
405    ///
406    /// # Examples
407    ///
408    /// ```
409    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
410    /// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
411    /// assert_eq!(store.node(store.root()).unwrap().id().get(), 1);
412    /// # Ok::<(), Box<dyn std::error::Error>>(())
413    /// ```
414    pub const fn id(&self) -> FileTreeNodeId {
415        self.id
416    }
417
418    /// Returns the parent ID, or `None` for the root.
419    ///
420    /// # Examples
421    ///
422    /// ```
423    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
424    /// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
425    /// assert_eq!(store.node(store.root()).unwrap().parent(), None);
426    /// # Ok::<(), Box<dyn std::error::Error>>(())
427    /// ```
428    pub const fn parent(&self) -> Option<FileTreeNodeId> {
429        self.parent
430    }
431
432    /// Borrows the node's current URI.
433    ///
434    /// # Examples
435    ///
436    /// ```
437    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
438    /// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
439    /// assert_eq!(store.node(store.root()).unwrap().uri().path(), "/");
440    /// # Ok::<(), Box<dyn std::error::Error>>(())
441    /// ```
442    pub fn uri(&self) -> &FileUri {
443        &self.uri
444    }
445
446    /// Borrows the provider identity, or `None` when unavailable.
447    ///
448    /// # Examples
449    ///
450    /// ```
451    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
452    /// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
453    /// assert!(store.node(store.root()).unwrap().identity().is_none());
454    /// # Ok::<(), Box<dyn std::error::Error>>(())
455    /// ```
456    pub fn identity(&self) -> Option<&FileIdentity> {
457        self.identity.as_ref()
458    }
459
460    /// Borrows the latest metadata snapshot.
461    ///
462    /// # Examples
463    ///
464    /// ```
465    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
466    /// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
467    /// assert_eq!(store.node(store.root()).unwrap().metadata().kind, FileKind::Directory);
468    /// # Ok::<(), Box<dyn std::error::Error>>(())
469    /// ```
470    pub const fn metadata(&self) -> &FileMetadata {
471        &self.metadata
472    }
473
474    /// Borrows child IDs in provider/reconciliation order.
475    ///
476    /// # Examples
477    ///
478    /// ```
479    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
480    /// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
481    /// assert!(store.node(store.root()).unwrap().children().is_empty());
482    /// # Ok::<(), Box<dyn std::error::Error>>(())
483    /// ```
484    pub fn children(&self) -> &[FileTreeNodeId] {
485        &self.children
486    }
487
488    /// Borrows the retained directory-load state.
489    ///
490    /// Non-directory nodes also begin as [`DirectoryLoadState::Unloaded`]; a
491    /// load request still rejects them.
492    ///
493    /// # Examples
494    ///
495    /// ```
496    /// use ailloli_ui_fs::{DirectoryLoadState, FileKind, FileMetadata, FileTreeStore, FileUri};
497    /// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
498    /// assert!(matches!(store.node(store.root()).unwrap().directory_state(), DirectoryLoadState::Unloaded));
499    /// # Ok::<(), Box<dyn std::error::Error>>(())
500    /// ```
501    pub const fn directory_state(&self) -> &DirectoryLoadState {
502        &self.directory_state
503    }
504
505    /// Returns whether UI expansion currently pins and displays the node.
506    ///
507    /// # Examples
508    ///
509    /// ```
510    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
511    /// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
512    /// assert!(!store.node(store.root()).unwrap().is_expanded());
513    /// # Ok::<(), Box<dyn std::error::Error>>(())
514    /// ```
515    pub const fn is_expanded(&self) -> bool {
516        self.expanded
517    }
518
519    /// Returns whether the node participates in the current selection.
520    ///
521    /// # Examples
522    ///
523    /// ```
524    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
525    /// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
526    /// assert!(!store.node(store.root()).unwrap().is_selected());
527    /// # Ok::<(), Box<dyn std::error::Error>>(())
528    /// ```
529    pub const fn is_selected(&self) -> bool {
530        self.selected
531    }
532
533    /// Returns whether the node owns keyboard/navigation focus.
534    ///
535    /// # Examples
536    ///
537    /// ```
538    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
539    /// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
540    /// assert!(!store.node(store.root()).unwrap().is_focused());
541    /// # Ok::<(), Box<dyn std::error::Error>>(())
542    /// ```
543    pub const fn is_focused(&self) -> bool {
544        self.focused
545    }
546
547    /// Returns whether provider mutation is pending for this node.
548    ///
549    /// # Examples
550    ///
551    /// ```
552    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
553    /// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
554    /// assert!(!store.node(store.root()).unwrap().has_pending_operation());
555    /// # Ok::<(), Box<dyn std::error::Error>>(())
556    /// ```
557    pub const fn has_pending_operation(&self) -> bool {
558        self.pending_operation
559    }
560
561    /// Returns whether any expansion, selection, focus, or pending-operation flag is set.
562    ///
563    /// Pinned nodes prevent eviction of their containing candidate subtree.
564    ///
565    /// # Examples
566    ///
567    /// ```
568    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
569    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
570    /// store.set_selected(store.root(), true)?;
571    /// assert!(store.node(store.root()).unwrap().is_pinned());
572    /// # Ok::<(), Box<dyn std::error::Error>>(())
573    /// ```
574    pub const fn is_pinned(&self) -> bool {
575        self.expanded || self.selected || self.focused || self.pending_operation
576    }
577}
578
579/// Incremental change emitted by [`FileTreeStore`].
580///
581/// Changes in one [`FileTreeStoreDelta`] are ordered as produced by the
582/// mutation/reconciliation and should be applied in slice order.
583///
584/// # Examples
585///
586/// ```
587/// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeDelta, FileTreeStore, FileUri};
588/// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
589/// let delta = store.set_expanded(store.root(), true)?;
590/// assert!(matches!(delta.changes(), [FileTreeDelta::Updated { .. }]));
591/// # Ok::<(), Box<dyn std::error::Error>>(())
592/// ```
593#[non_exhaustive]
594#[derive(Debug, Clone)]
595pub enum FileTreeDelta {
596    /// A newly retained node was inserted into a parent's ordered children.
597    Inserted {
598        /// Parent receiving the new child.
599        parent: FileTreeNodeId,
600        /// Zero-based child index after the mutation.
601        index: usize,
602        /// Complete inserted node snapshot.
603        node: Box<FileTreeNode>,
604    },
605    /// A node and, when applicable, its subtree were removed.
606    Removed {
607        /// Removed store-local node ID.
608        id: FileTreeNodeId,
609    },
610    /// Metadata, URI, identity, or UI flags changed for an existing node.
611    Updated {
612        /// Updated node ID; query the store for its current snapshot.
613        id: FileTreeNodeId,
614    },
615    /// An existing node changed parent or ordered child index.
616    Moved {
617        /// Moved node ID.
618        id: FileTreeNodeId,
619        /// Parent after the move.
620        new_parent: FileTreeNodeId,
621        /// Zero-based index under the new parent.
622        index: usize,
623    },
624    /// A directory's retained load state changed.
625    DirectoryState {
626        /// Directory node ID.
627        id: FileTreeNodeId,
628        /// New load state.
629        state: DirectoryLoadState,
630    },
631}
632
633/// One monotone store revision and its precise changes.
634///
635/// Empty deltas retain the current revision; a non-empty successful commit
636/// increments it once regardless of the number of changes.
637///
638/// # Examples
639///
640/// ```
641/// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
642/// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
643/// let delta = store.set_expanded(store.root(), false)?;
644/// assert!(delta.is_empty());
645/// assert_eq!(delta.revision(), 0);
646/// # Ok::<(), Box<dyn std::error::Error>>(())
647/// ```
648#[derive(Debug, Clone)]
649pub struct FileTreeStoreDelta {
650    /// Store revision after packaging these changes.
651    revision: u64,
652    /// Ordered changes; empty means the revision did not advance.
653    changes: Vec<FileTreeDelta>,
654}
655
656impl FileTreeStoreDelta {
657    /// Returns the store revision after this delta.
658    ///
659    /// # Examples
660    ///
661    /// ```
662    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
663    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
664    /// assert_eq!(store.set_expanded(store.root(), true)?.revision(), 1);
665    /// # Ok::<(), Box<dyn std::error::Error>>(())
666    /// ```
667    pub const fn revision(&self) -> u64 {
668        self.revision
669    }
670
671    /// Borrows ordered incremental changes.
672    ///
673    /// # Examples
674    ///
675    /// ```
676    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
677    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
678    /// assert_eq!(store.set_expanded(store.root(), true)?.changes().len(), 1);
679    /// # Ok::<(), Box<dyn std::error::Error>>(())
680    /// ```
681    pub fn changes(&self) -> &[FileTreeDelta] {
682        &self.changes
683    }
684
685    /// Returns whether the mutation produced no observable tree change.
686    ///
687    /// # Examples
688    ///
689    /// ```
690    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
691    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
692    /// assert!(store.set_expanded(store.root(), false)?.is_empty());
693    /// # Ok::<(), Box<dyn std::error::Error>>(())
694    /// ```
695    pub fn is_empty(&self) -> bool {
696        self.changes.is_empty()
697    }
698}
699
700/// Structural/correlation failure returned by [`FileTreeStore`] mutations.
701///
702/// # Examples
703///
704/// ```
705/// use ailloli_ui_fs::FileTreeStoreError;
706/// assert!(matches!(FileTreeStoreError::IdentifierExhausted, FileTreeStoreError::IdentifierExhausted));
707/// ```
708#[non_exhaustive]
709#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
710pub enum FileTreeStoreError {
711    /// A node ID is absent from the live store.
712    #[error("filesystem tree node does not exist: {0:?}")]
713    MissingNode(FileTreeNodeId),
714    /// A directory-only operation targeted a non-directory-like node.
715    #[error("filesystem tree node is not a directory: {0:?}")]
716    NotDirectory(FileTreeNodeId),
717    /// A second load was requested while one remains active for the node.
718    #[error("directory already has an active request: {0:?}")]
719    AlreadyLoading(FileTreeNodeId),
720    /// A provider result no longer matches the active request/generation.
721    #[error("stale filesystem response for request {request_id}")]
722    StaleResponse {
723        /// Rejected provider request ID.
724        request_id: u64,
725    },
726    /// Monotone node or request IDs reached `u64::MAX`.
727    #[error("filesystem tree identifier space is exhausted")]
728    IdentifierExhausted,
729    /// A reserved-ID commit/discard referenced an absent or already consumed reservation.
730    #[error("filesystem tree identifier is not reserved: {0:?}")]
731    InvalidReservedNodeId(FileTreeNodeId),
732    /// The store revision or generation reached `u64::MAX`.
733    #[error("filesystem tree revision space is exhausted")]
734    RevisionExhausted,
735    /// The destination URI's parent is not retained in the store.
736    #[error("destination parent is not loaded in the filesystem tree: {0}")]
737    MissingDestinationParent(FileUri),
738}
739
740/// UI-independent, session-persistent filesystem tree cache.
741///
742/// The store performs no filesystem I/O. Provider results and watch events are
743/// applied explicitly, while stable IDs retain UI state across reconciliation.
744/// It is not internally synchronized; coordinators own mutation ordering.
745///
746/// # Examples
747///
748/// ```
749/// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
750/// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
751/// assert_eq!((store.len(), store.revision(), store.generation()), (1, 0, 1));
752/// # Ok::<(), Box<dyn std::error::Error>>(())
753/// ```
754pub struct FileTreeStore {
755    /// Live node storage keyed by stable ID.
756    nodes: HashMap<FileTreeNodeId, FileTreeNode>,
757    /// Exact normalized URI-to-node lookup.
758    uri_index: HashMap<FileUri, FileTreeNodeId>,
759    /// Provider identities to all matching nodes, including hard links.
760    identity_index: HashMap<FileIdentity, HashSet<FileTreeNodeId>>,
761    /// Original root ID, retained even if its node is removed.
762    root: FileTreeNodeId,
763    /// Monotone revision advanced by each successful non-empty delta.
764    revision: u64,
765    /// Correlation generation for asynchronous directory requests.
766    generation: u64,
767    /// Next monotone node/reservation ID candidate.
768    next_node_id: u64,
769    /// Allocated IDs held by uncommitted inline create drafts.
770    reserved_node_ids: HashSet<FileTreeNodeId>,
771    /// Next monotone directory request ID candidate.
772    next_request_id: u64,
773    /// One active request ID per directory node.
774    active_requests: HashMap<FileTreeNodeId, u64>,
775    /// Explicit eviction timing state for live nodes.
776    cache: HashMap<FileTreeNodeId, FileTreeCacheState>,
777    /// Caller-selected soft eviction policy.
778    limits: FileTreeStoreLimits,
779    /// Live/cumulative operational counters.
780    diagnostics: FileTreeStoreDiagnostics,
781    /// Highest provider watch generation accepted so far.
782    last_watch_generation: u64,
783    /// Highest sequence accepted within `last_watch_generation`.
784    last_watch_sequence: u64,
785    /// Bounded expected echoes of already-applied provider mutations.
786    watch_echoes: VecDeque<WatchEcho>,
787}
788
789impl FileTreeStore {
790    /// Creates a one-node store with default cache limits.
791    ///
792    /// The root receives ID `1`, revision starts at `0`, generation at `1`, and
793    /// directory state at [`DirectoryLoadState::Unloaded`]. Metadata is stored
794    /// verbatim; a non-directory root is accepted but cannot be loaded.
795    ///
796    /// # Errors
797    ///
798    /// Construction is currently infallible; the result type reserves future
799    /// initialization/exhaustion checks.
800    ///
801    /// # Examples
802    ///
803    /// ```
804    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
805    /// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
806    /// assert_eq!(store.root().get(), 1);
807    /// # Ok::<(), Box<dyn std::error::Error>>(())
808    /// ```
809    pub fn new(root_uri: FileUri, root_metadata: FileMetadata) -> Result<Self, FileTreeStoreError> {
810        Self::with_limits(root_uri, root_metadata, FileTreeStoreLimits::default())
811    }
812
813    /// Creates a one-node store with caller-supplied soft eviction limits.
814    ///
815    /// Limits are stored verbatim, including zeros or extremely large durations;
816    /// they do not reject or trim the root.
817    ///
818    /// # Errors
819    ///
820    /// Construction is currently infallible; the result type reserves future
821    /// initialization/exhaustion checks.
822    ///
823    /// # Examples
824    ///
825    /// ```
826    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileTreeStoreLimits, FileUri};
827    /// use std::time::Duration;
828    /// let limits = FileTreeStoreLimits { max_nodes: 0, max_payload_bytes: 0, collapsed_ttl: Duration::ZERO };
829    /// let store = FileTreeStore::with_limits(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory), limits)?;
830    /// assert_eq!(store.limits(), limits);
831    /// # Ok::<(), Box<dyn std::error::Error>>(())
832    /// ```
833    pub fn with_limits(
834        root_uri: FileUri,
835        root_metadata: FileMetadata,
836        limits: FileTreeStoreLimits,
837    ) -> Result<Self, FileTreeStoreError> {
838        let root = FileTreeNodeId(1);
839        let root_node = FileTreeNode {
840            id: root,
841            parent: None,
842            uri: root_uri.clone(),
843            identity: None,
844            metadata: root_metadata,
845            children: Vec::new(),
846            directory_state: DirectoryLoadState::Unloaded,
847            expanded: false,
848            selected: false,
849            focused: false,
850            pending_operation: false,
851        };
852        let now = Instant::now();
853        Ok(Self {
854            nodes: HashMap::from([(root, root_node)]),
855            uri_index: HashMap::from([(root_uri, root)]),
856            identity_index: HashMap::new(),
857            root,
858            revision: 0,
859            generation: 1,
860            next_node_id: 2,
861            reserved_node_ids: HashSet::new(),
862            next_request_id: 1,
863            active_requests: HashMap::new(),
864            cache: HashMap::from([(
865                root,
866                FileTreeCacheState {
867                    last_used: now,
868                    collapsed_at: Some(now),
869                },
870            )]),
871            limits,
872            diagnostics: FileTreeStoreDiagnostics::default(),
873            last_watch_generation: 0,
874            last_watch_sequence: 0,
875            watch_echoes: VecDeque::new(),
876        })
877    }
878
879    /// Returns the original root ID, even if the root node was later removed.
880    ///
881    /// # Examples
882    ///
883    /// ```
884    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
885    /// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
886    /// assert_eq!(store.root().get(), 1);
887    /// # Ok::<(), Box<dyn std::error::Error>>(())
888    /// ```
889    pub const fn root(&self) -> FileTreeNodeId {
890        self.root
891    }
892
893    /// Returns the current monotone revision.
894    ///
895    /// Only non-empty successful commits increment it; it never wraps.
896    ///
897    /// # Examples
898    ///
899    /// ```
900    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
901    /// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
902    /// assert_eq!(store.revision(), 0);
903    /// # Ok::<(), Box<dyn std::error::Error>>(())
904    /// ```
905    pub const fn revision(&self) -> u64 {
906        self.revision
907    }
908
909    /// Returns the correlation generation for directory requests.
910    ///
911    /// It starts at `1` and changes only through [`Self::invalidate_generation`].
912    ///
913    /// # Examples
914    ///
915    /// ```
916    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
917    /// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
918    /// assert_eq!(store.generation(), 1);
919    /// # Ok::<(), Box<dyn std::error::Error>>(())
920    /// ```
921    pub const fn generation(&self) -> u64 {
922        self.generation
923    }
924
925    /// Returns the number of currently retained nodes.
926    ///
927    /// # Examples
928    ///
929    /// ```
930    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
931    /// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
932    /// assert_eq!(store.len(), 1);
933    /// # Ok::<(), Box<dyn std::error::Error>>(())
934    /// ```
935    pub fn len(&self) -> usize {
936        self.nodes.len()
937    }
938
939    /// Returns whether no nodes remain.
940    ///
941    /// A new store is never empty, but public attested removal can remove the root.
942    ///
943    /// # Examples
944    ///
945    /// ```
946    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
947    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
948    /// store.apply_attested_remove(store.root())?;
949    /// assert!(store.is_empty());
950    /// # Ok::<(), Box<dyn std::error::Error>>(())
951    /// ```
952    pub fn is_empty(&self) -> bool {
953        self.nodes.is_empty()
954    }
955
956    /// Borrows a live node by ID, or returns `None` for missing/reserved/removed IDs.
957    ///
958    /// # Examples
959    ///
960    /// ```
961    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
962    /// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
963    /// assert!(store.node(store.root()).is_some());
964    /// # Ok::<(), Box<dyn std::error::Error>>(())
965    /// ```
966    pub fn node(&self, id: FileTreeNodeId) -> Option<&FileTreeNode> {
967        self.nodes.get(&id)
968    }
969
970    /// Returns the live node ID indexed by an exactly equal URI.
971    ///
972    /// # Examples
973    ///
974    /// ```
975    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
976    /// let uri = FileUri::parse("file:///")?;
977    /// let store = FileTreeStore::new(uri.clone(), FileMetadata::new(FileKind::Directory))?;
978    /// assert_eq!(store.node_id(&uri), Some(store.root()));
979    /// # Ok::<(), Box<dyn std::error::Error>>(())
980    /// ```
981    pub fn node_id(&self, uri: &FileUri) -> Option<FileTreeNodeId> {
982        self.uri_index.get(uri).copied()
983    }
984
985    /// Reserves an opaque identity for an inline create draft. Cancelling the
986    /// draft consumes the identity permanently; successful provider I/O must
987    /// commit it with [`Self::apply_attested_insert_reserved`].
988    ///
989    /// Reservation changes no revision and creates no node.
990    ///
991    /// # Errors
992    ///
993    /// Returns [`FileTreeStoreError::IdentifierExhausted`] when the monotone ID
994    /// counter has no successor.
995    ///
996    /// # Examples
997    ///
998    /// ```
999    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
1000    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
1001    /// let id = store.reserve_node_id()?;
1002    /// assert_eq!(id.get(), 2);
1003    /// assert!(store.node(id).is_none());
1004    /// # Ok::<(), Box<dyn std::error::Error>>(())
1005    /// ```
1006    pub fn reserve_node_id(&mut self) -> Result<FileTreeNodeId, FileTreeStoreError> {
1007        let id = self.allocate_node_id()?;
1008        self.reserved_node_ids.insert(id);
1009        Ok(id)
1010    }
1011
1012    /// Releases a draft reservation without making its identity reusable.
1013    ///
1014    /// # Errors
1015    ///
1016    /// Returns [`FileTreeStoreError::InvalidReservedNodeId`] if `id` is not an
1017    /// active reservation or was already discarded/committed.
1018    ///
1019    /// # Examples
1020    ///
1021    /// ```
1022    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
1023    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
1024    /// let id = store.reserve_node_id()?;
1025    /// store.discard_reserved_node_id(id)?;
1026    /// assert!(store.discard_reserved_node_id(id).is_err());
1027    /// # Ok::<(), Box<dyn std::error::Error>>(())
1028    /// ```
1029    pub fn discard_reserved_node_id(
1030        &mut self,
1031        id: FileTreeNodeId,
1032    ) -> Result<(), FileTreeStoreError> {
1033        if !self.reserved_node_ids.remove(&id) {
1034            return Err(FileTreeStoreError::InvalidReservedNodeId(id));
1035        }
1036        Ok(())
1037    }
1038
1039    /// Returns the soft cache limits stored at construction.
1040    ///
1041    /// # Examples
1042    ///
1043    /// ```
1044    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileTreeStoreLimits, FileUri};
1045    /// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
1046    /// assert_eq!(store.limits(), FileTreeStoreLimits::default());
1047    /// # Ok::<(), Box<dyn std::error::Error>>(())
1048    /// ```
1049    pub const fn limits(&self) -> FileTreeStoreLimits {
1050        self.limits
1051    }
1052
1053    /// Returns cumulative counters plus freshly computed live size estimates.
1054    ///
1055    /// Computing the payload estimate is linear in retained node count. It sums
1056    /// node struct size, rendered URI length, identity bytes, and child-vector
1057    /// capacity; it excludes maps, file contents, and allocator overhead.
1058    /// Component accumulation is saturating, but the final cross-node sum and
1059    /// the provider/value identity-length sum use ordinary `usize` addition.
1060    ///
1061    /// # Panics
1062    ///
1063    /// In debug builds, theoretical `usize` overflow in either ordinary sum
1064    /// panics; optimized builds wrap. Reaching that bound normally requires
1065    /// more allocated memory than the process can address.
1066    ///
1067    /// # Examples
1068    ///
1069    /// ```
1070    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
1071    /// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
1072    /// assert_eq!(store.diagnostics().nodes, 1);
1073    /// # Ok::<(), Box<dyn std::error::Error>>(())
1074    /// ```
1075    pub fn diagnostics(&self) -> FileTreeStoreDiagnostics {
1076        FileTreeStoreDiagnostics {
1077            nodes: self.nodes.len(),
1078            estimated_payload_bytes: self.estimated_payload_bytes(),
1079            ..self.diagnostics
1080        }
1081    }
1082
1083    /// Updates a node's cache recency to the caller-supplied instant.
1084    ///
1085    /// This emits no delta, changes no revision, and does not change the instant
1086    /// at which a collapsed node became collapsed.
1087    ///
1088    /// # Errors
1089    ///
1090    /// Returns [`FileTreeStoreError::MissingNode`] for an absent ID.
1091    ///
1092    /// # Examples
1093    ///
1094    /// ```
1095    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
1096    /// use std::time::Instant;
1097    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
1098    /// store.touch(store.root(), Instant::now())?;
1099    /// assert_eq!(store.revision(), 0);
1100    /// # Ok::<(), Box<dyn std::error::Error>>(())
1101    /// ```
1102    pub fn touch(&mut self, id: FileTreeNodeId, now: Instant) -> Result<(), FileTreeStoreError> {
1103        if !self.nodes.contains_key(&id) {
1104            return Err(FileTreeStoreError::MissingNode(id));
1105        }
1106        self.cache
1107            .entry(id)
1108            .and_modify(|cache| cache.last_used = now)
1109            .or_insert(FileTreeCacheState {
1110                last_used: now,
1111                collapsed_at: None,
1112            });
1113        Ok(())
1114    }
1115
1116    /// Sets expansion and updates collapse/recency cache timestamps.
1117    ///
1118    /// A repeated value returns an empty delta at the current revision. A change
1119    /// emits one [`FileTreeDelta::Updated`]. Expanding clears `collapsed_at`;
1120    /// collapsing records [`Instant::now`].
1121    ///
1122    /// # Errors
1123    ///
1124    /// Returns [`FileTreeStoreError::MissingNode`] or, after state mutation,
1125    /// [`FileTreeStoreError::RevisionExhausted`] if revision cannot advance.
1126    ///
1127    /// # Examples
1128    ///
1129    /// ```
1130    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
1131    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
1132    /// assert_eq!(store.set_expanded(store.root(), true)?.revision(), 1);
1133    /// assert!(store.node(store.root()).unwrap().is_expanded());
1134    /// # Ok::<(), Box<dyn std::error::Error>>(())
1135    /// ```
1136    pub fn set_expanded(
1137        &mut self,
1138        id: FileTreeNodeId,
1139        expanded: bool,
1140    ) -> Result<FileTreeStoreDelta, FileTreeStoreError> {
1141        let node = self
1142            .nodes
1143            .get_mut(&id)
1144            .ok_or(FileTreeStoreError::MissingNode(id))?;
1145        if node.expanded == expanded {
1146            return self.commit(Vec::new());
1147        }
1148        node.expanded = expanded;
1149        let now = Instant::now();
1150        self.cache
1151            .entry(id)
1152            .and_modify(|cache| {
1153                cache.last_used = now;
1154                cache.collapsed_at = (!expanded).then_some(now);
1155            })
1156            .or_insert(FileTreeCacheState {
1157                last_used: now,
1158                collapsed_at: (!expanded).then_some(now),
1159            });
1160        self.commit(vec![FileTreeDelta::Updated { id }])
1161    }
1162
1163    /// Sets selection, touches cache recency, and emits an update when changed.
1164    ///
1165    /// # Errors
1166    ///
1167    /// Returns [`FileTreeStoreError::MissingNode`] or, after state mutation,
1168    /// [`FileTreeStoreError::RevisionExhausted`].
1169    ///
1170    /// # Examples
1171    ///
1172    /// ```
1173    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
1174    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
1175    /// store.set_selected(store.root(), true)?;
1176    /// assert!(store.node(store.root()).unwrap().is_selected());
1177    /// # Ok::<(), Box<dyn std::error::Error>>(())
1178    /// ```
1179    pub fn set_selected(
1180        &mut self,
1181        id: FileTreeNodeId,
1182        selected: bool,
1183    ) -> Result<FileTreeStoreDelta, FileTreeStoreError> {
1184        let node = self
1185            .nodes
1186            .get_mut(&id)
1187            .ok_or(FileTreeStoreError::MissingNode(id))?;
1188        if node.selected == selected {
1189            return self.commit(Vec::new());
1190        }
1191        node.selected = selected;
1192        self.touch(id, Instant::now())?;
1193        self.commit(vec![FileTreeDelta::Updated { id }])
1194    }
1195
1196    /// Sets focus, touches cache recency, and emits an update when changed.
1197    ///
1198    /// # Errors
1199    ///
1200    /// Returns [`FileTreeStoreError::MissingNode`] or, after state mutation,
1201    /// [`FileTreeStoreError::RevisionExhausted`].
1202    ///
1203    /// # Examples
1204    ///
1205    /// ```
1206    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
1207    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
1208    /// store.set_focused(store.root(), true)?;
1209    /// assert!(store.node(store.root()).unwrap().is_focused());
1210    /// # Ok::<(), Box<dyn std::error::Error>>(())
1211    /// ```
1212    pub fn set_focused(
1213        &mut self,
1214        id: FileTreeNodeId,
1215        focused: bool,
1216    ) -> Result<FileTreeStoreDelta, FileTreeStoreError> {
1217        let node = self
1218            .nodes
1219            .get_mut(&id)
1220            .ok_or(FileTreeStoreError::MissingNode(id))?;
1221        if node.focused == focused {
1222            return self.commit(Vec::new());
1223        }
1224        node.focused = focused;
1225        self.touch(id, Instant::now())?;
1226        self.commit(vec![FileTreeDelta::Updated { id }])
1227    }
1228
1229    /// Sets provider-operation pending state and emits an update when changed.
1230    ///
1231    /// Pending nodes are pinned against subtree eviction. A repeated value is a
1232    /// revision-preserving no-op.
1233    ///
1234    /// # Errors
1235    ///
1236    /// Returns [`FileTreeStoreError::MissingNode`] or, after state mutation,
1237    /// [`FileTreeStoreError::RevisionExhausted`].
1238    ///
1239    /// # Examples
1240    ///
1241    /// ```
1242    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
1243    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
1244    /// store.set_pending_operation(store.root(), true)?;
1245    /// assert!(store.node(store.root()).unwrap().has_pending_operation());
1246    /// # Ok::<(), Box<dyn std::error::Error>>(())
1247    /// ```
1248    pub fn set_pending_operation(
1249        &mut self,
1250        id: FileTreeNodeId,
1251        pending: bool,
1252    ) -> Result<FileTreeStoreDelta, FileTreeStoreError> {
1253        let node = self
1254            .nodes
1255            .get_mut(&id)
1256            .ok_or(FileTreeStoreError::MissingNode(id))?;
1257        if node.pending_operation == pending {
1258            return self.commit(Vec::new());
1259        }
1260        node.pending_operation = pending;
1261        self.touch(id, Instant::now())?;
1262        self.commit(vec![FileTreeDelta::Updated { id }])
1263    }
1264
1265    /// Evicts descendants of expired collapsed directories while retaining the
1266    /// collapsed directory node and its minimal metadata. Pinned descendants
1267    /// make the whole candidate ineligible.
1268    ///
1269    /// Candidates are processed oldest-collapse first. While over a soft node
1270    /// or payload limit, eligible subtrees may be evicted before their TTL;
1271    /// otherwise only expired candidates are removed. Removal is iterative and
1272    /// emits descendant [`FileTreeDelta::Removed`] changes followed by a retained
1273    /// parent's [`DirectoryLoadState::Unloaded`] change. No I/O occurs.
1274    ///
1275    /// # Errors
1276    ///
1277    /// Returns [`FileTreeStoreError::RevisionExhausted`] after eviction state
1278    /// has changed if a non-empty delta cannot advance the revision.
1279    ///
1280    /// # Panics
1281    ///
1282    /// Panics only if the internal cache/node index becomes inconsistent while
1283    /// an eligible candidate is being evicted.
1284    ///
1285    /// # Examples
1286    ///
1287    /// ```
1288    /// use ailloli_ui_fs::{FileEntry, FileKind, FileMetadata, FileTreeStore, FileTreeStoreLimits, FileUri};
1289    /// use std::time::{Duration, Instant};
1290    /// let limits = FileTreeStoreLimits { max_nodes: 1, max_payload_bytes: usize::MAX, collapsed_ttl: Duration::from_secs(300) };
1291    /// let mut store = FileTreeStore::with_limits(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory), limits)?;
1292    /// store.apply_attested_insert(store.root(), FileEntry::new(FileUri::parse("file:///a")?, FileMetadata::new(FileKind::File)), None)?;
1293    /// store.evict_expired(Instant::now())?;
1294    /// assert_eq!(store.len(), 1);
1295    /// # Ok::<(), Box<dyn std::error::Error>>(())
1296    /// ```
1297    pub fn evict_expired(
1298        &mut self,
1299        now: Instant,
1300    ) -> Result<FileTreeStoreDelta, FileTreeStoreError> {
1301        let mut candidates = self
1302            .cache
1303            .iter()
1304            .filter_map(|(id, cache)| {
1305                let collapsed_at = cache.collapsed_at?;
1306                let node = self.nodes.get(id)?;
1307                (!node.expanded && !node.children.is_empty()).then_some((*id, collapsed_at))
1308            })
1309            .collect::<Vec<_>>();
1310        candidates.sort_by_key(|(_, collapsed_at)| *collapsed_at);
1311
1312        let mut changes = Vec::new();
1313        let mut remaining_nodes = self.nodes.len();
1314        let mut remaining_payload_bytes = self.estimated_payload_bytes();
1315        let mut over_limits = remaining_nodes > self.limits.max_nodes
1316            || remaining_payload_bytes > self.limits.max_payload_bytes;
1317        for (id, collapsed_at) in candidates {
1318            let expired = now.saturating_duration_since(collapsed_at) >= self.limits.collapsed_ttl;
1319            if !expired && !over_limits {
1320                break;
1321            }
1322            let children = self
1323                .nodes
1324                .get(&id)
1325                .map(|node| node.children.clone())
1326                .unwrap_or_default();
1327            if children.is_empty() || self.subtrees_contain_pin(&children) {
1328                continue;
1329            }
1330            let (removed_nodes, removed_payload_bytes) = self.subtree_footprint(&children);
1331            self.nodes
1332                .get_mut(&id)
1333                .expect("candidate exists")
1334                .children
1335                .clear();
1336            for child in children {
1337                self.remove_subtree(child, &mut changes);
1338            }
1339            let node = self.nodes.get_mut(&id).expect("candidate exists");
1340            node.directory_state = DirectoryLoadState::Unloaded;
1341            changes.push(FileTreeDelta::DirectoryState {
1342                id,
1343                state: DirectoryLoadState::Unloaded,
1344            });
1345            remaining_nodes = remaining_nodes.saturating_sub(removed_nodes);
1346            remaining_payload_bytes = remaining_payload_bytes.saturating_sub(removed_payload_bytes);
1347            over_limits = remaining_nodes > self.limits.max_nodes
1348                || remaining_payload_bytes > self.limits.max_payload_bytes;
1349        }
1350        self.commit(changes)
1351    }
1352
1353    /// Earliest time at which an evictable collapsed subtree needs cache
1354    /// maintenance. Capacity pressure is immediate; ordinary cache entries
1355    /// use their configured TTL. Pinned subtrees are excluded so a host timer
1356    /// cannot spin on work that is forbidden to evict.
1357    ///
1358    /// Returns `None` when there is no collapsed, non-empty, unpinned candidate.
1359    /// Under capacity pressure the returned instant is exactly `now`; otherwise
1360    /// it is the earliest collapse instant plus the configured TTL.
1361    ///
1362    /// # Panics
1363    ///
1364    /// May panic if adding an extremely large [`FileTreeStoreLimits::collapsed_ttl`]
1365    /// to an [`Instant`] exceeds the platform instant range.
1366    ///
1367    /// # Examples
1368    ///
1369    /// ```
1370    /// use ailloli_ui_fs::{FileEntry, FileKind, FileMetadata, FileTreeStore, FileTreeStoreLimits, FileUri};
1371    /// use std::time::{Duration, Instant};
1372    /// let limits = FileTreeStoreLimits { max_nodes: 1, max_payload_bytes: usize::MAX, collapsed_ttl: Duration::from_secs(300) };
1373    /// let mut store = FileTreeStore::with_limits(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory), limits)?;
1374    /// store.apply_attested_insert(store.root(), FileEntry::new(FileUri::parse("file:///a")?, FileMetadata::new(FileKind::File)), None)?;
1375    /// let now = Instant::now();
1376    /// assert_eq!(store.next_cache_maintenance_due(now), Some(now));
1377    /// # Ok::<(), Box<dyn std::error::Error>>(())
1378    /// ```
1379    pub fn next_cache_maintenance_due(&self, now: Instant) -> Option<Instant> {
1380        let over_limits = self.cache_limits_exceeded();
1381        self.cache
1382            .iter()
1383            .filter_map(|(id, cache)| {
1384                let collapsed_at = cache.collapsed_at?;
1385                let node = self.nodes.get(id)?;
1386                if node.expanded
1387                    || node.children.is_empty()
1388                    || self.subtrees_contain_pin(&node.children)
1389                {
1390                    return None;
1391                }
1392                Some(if over_limits {
1393                    now
1394                } else {
1395                    collapsed_at + self.limits.collapsed_ttl
1396                })
1397            })
1398            .min()
1399    }
1400
1401    /// Applies a successful provider-side create without rescanning its parent.
1402    ///
1403    /// A new node is appended with unloaded directory state and no UI flags.
1404    /// `parent` need only exist; directory kind/load state is a caller contract.
1405    /// If the URI already exists anywhere, only that node's metadata is updated:
1406    /// `parent` and the supplied identity are ignored. A matching watcher echo
1407    /// is remembered in a bounded 256-entry queue.
1408    ///
1409    /// # Errors
1410    ///
1411    /// Returns [`FileTreeStoreError::IdentifierExhausted`],
1412    /// [`FileTreeStoreError::MissingNode`], or
1413    /// [`FileTreeStoreError::RevisionExhausted`]. An allocated ID is consumed
1414    /// even if parent validation fails; revision exhaustion can follow mutation.
1415    ///
1416    /// # Examples
1417    ///
1418    /// ```
1419    /// use ailloli_ui_fs::{FileEntry, FileKind, FileMetadata, FileTreeStore, FileUri};
1420    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
1421    /// let uri = FileUri::parse("file:///new.txt")?;
1422    /// store.apply_attested_insert(store.root(), FileEntry::new(uri.clone(), FileMetadata::new(FileKind::File)), None)?;
1423    /// assert!(store.node_id(&uri).is_some());
1424    /// # Ok::<(), Box<dyn std::error::Error>>(())
1425    /// ```
1426    pub fn apply_attested_insert(
1427        &mut self,
1428        parent: FileTreeNodeId,
1429        entry: FileEntry,
1430        identity: Option<FileIdentity>,
1431    ) -> Result<FileTreeStoreDelta, FileTreeStoreError> {
1432        let id = self.allocate_node_id()?;
1433        self.apply_attested_insert_with_id(parent, id, entry, identity)
1434    }
1435
1436    /// Applies a successful provider-side create using the identity reserved
1437    /// for its inline UI draft.
1438    ///
1439    /// The reservation is consumed before parent/URI processing and is never
1440    /// restored on a later error. Existing-URI behavior matches
1441    /// [`Self::apply_attested_insert`] and can consume the reserved ID without
1442    /// creating a new node.
1443    ///
1444    /// # Errors
1445    ///
1446    /// Returns [`FileTreeStoreError::InvalidReservedNodeId`],
1447    /// [`FileTreeStoreError::MissingNode`], or
1448    /// [`FileTreeStoreError::RevisionExhausted`].
1449    ///
1450    /// # Examples
1451    ///
1452    /// ```
1453    /// use ailloli_ui_fs::{FileEntry, FileKind, FileMetadata, FileTreeStore, FileUri};
1454    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
1455    /// let id = store.reserve_node_id()?;
1456    /// let uri = FileUri::parse("file:///draft.txt")?;
1457    /// store.apply_attested_insert_reserved(store.root(), id, FileEntry::new(uri, FileMetadata::new(FileKind::File)), None)?;
1458    /// assert!(store.node(id).is_some());
1459    /// # Ok::<(), Box<dyn std::error::Error>>(())
1460    /// ```
1461    pub fn apply_attested_insert_reserved(
1462        &mut self,
1463        parent: FileTreeNodeId,
1464        id: FileTreeNodeId,
1465        entry: FileEntry,
1466        identity: Option<FileIdentity>,
1467    ) -> Result<FileTreeStoreDelta, FileTreeStoreError> {
1468        if !self.reserved_node_ids.remove(&id) {
1469            return Err(FileTreeStoreError::InvalidReservedNodeId(id));
1470        }
1471        self.apply_attested_insert_with_id(parent, id, entry, identity)
1472    }
1473
1474    /// Implements attested insertion with an already consumed monotone ID.
1475    ///
1476    /// # Errors
1477    ///
1478    /// Returns [`FileTreeStoreError::MissingNode`] when `parent` is absent, or
1479    /// [`FileTreeStoreError::RevisionExhausted`] when committing the resulting
1480    /// delta cannot advance the revision.
1481    ///
1482    /// # Panics
1483    ///
1484    /// Panics only if the URI or parent-child indexes violate the store's
1485    /// internal consistency invariant after the initial parent check.
1486    fn apply_attested_insert_with_id(
1487        &mut self,
1488        parent: FileTreeNodeId,
1489        id: FileTreeNodeId,
1490        entry: FileEntry,
1491        identity: Option<FileIdentity>,
1492    ) -> Result<FileTreeStoreDelta, FileTreeStoreError> {
1493        if !self.nodes.contains_key(&parent) {
1494            return Err(FileTreeStoreError::MissingNode(parent));
1495        }
1496        if let Some(existing) = self.node_id(&entry.uri) {
1497            let node = self.nodes.get_mut(&existing).expect("indexed node exists");
1498            node.metadata = entry.metadata;
1499            self.record_watch_echo(WatchEcho::Created(entry.uri));
1500            return self.commit(vec![FileTreeDelta::Updated { id: existing }]);
1501        }
1502        let index = self
1503            .nodes
1504            .get(&parent)
1505            .map_or(0, |node| node.children.len());
1506        let node = FileTreeNode {
1507            id,
1508            parent: Some(parent),
1509            uri: entry.uri.clone(),
1510            identity: identity.clone(),
1511            metadata: entry.metadata,
1512            children: Vec::new(),
1513            directory_state: DirectoryLoadState::Unloaded,
1514            expanded: false,
1515            selected: false,
1516            focused: false,
1517            pending_operation: false,
1518        };
1519        self.nodes
1520            .get_mut(&parent)
1521            .expect("validated parent")
1522            .children
1523            .push(id);
1524        self.uri_index.insert(entry.uri.clone(), id);
1525        if let Some(identity) = identity {
1526            self.index_identity(identity, id);
1527        }
1528        self.nodes.insert(id, node.clone());
1529        let now = Instant::now();
1530        self.cache.insert(
1531            id,
1532            FileTreeCacheState {
1533                last_used: now,
1534                collapsed_at: Some(now),
1535            },
1536        );
1537        self.record_watch_echo(WatchEcho::Created(entry.uri));
1538        self.commit(vec![FileTreeDelta::Inserted {
1539            parent,
1540            index,
1541            node: Box::new(node),
1542        }])
1543    }
1544
1545    /// Applies a successful provider-side removal immediately.
1546    ///
1547    /// The node is detached and its full subtree is removed iteratively in
1548    /// descendant-before-parent delta order. Active requests/cache/URI/identity
1549    /// indexes are cleared. Removing the root is allowed and leaves the store
1550    /// empty while [`Self::root`] still returns its old ID. One watcher echo is
1551    /// retained for deduplication.
1552    ///
1553    /// # Errors
1554    ///
1555    /// Returns [`FileTreeStoreError::MissingNode`] or, after removal,
1556    /// [`FileTreeStoreError::RevisionExhausted`].
1557    ///
1558    /// # Examples
1559    ///
1560    /// ```
1561    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
1562    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
1563    /// store.apply_attested_remove(store.root())?;
1564    /// assert!(store.is_empty());
1565    /// # Ok::<(), Box<dyn std::error::Error>>(())
1566    /// ```
1567    pub fn apply_attested_remove(
1568        &mut self,
1569        id: FileTreeNodeId,
1570    ) -> Result<FileTreeStoreDelta, FileTreeStoreError> {
1571        let uri = self
1572            .nodes
1573            .get(&id)
1574            .ok_or(FileTreeStoreError::MissingNode(id))?
1575            .uri
1576            .clone();
1577        self.detach_from_parent(id);
1578        let mut changes = Vec::new();
1579        self.remove_subtree(id, &mut changes);
1580        self.record_watch_echo(WatchEcho::Removed(uri));
1581        self.commit(changes)
1582    }
1583
1584    /// Applies a successful provider-side rename/move while preserving the
1585    /// logical node ID and all retained UI state.
1586    ///
1587    /// The destination parent URI must already be retained. A supplied identity
1588    /// replaces the old one; `None` preserves it. Descendant URIs are rebased
1589    /// lexically. Moves within one parent do not reorder the child. Callers must
1590    /// ensure the destination is non-conflicting, its parent is a directory, and
1591    /// the move does not create a cycle; these invariants are not validated.
1592    ///
1593    /// # Errors
1594    ///
1595    /// Returns [`FileTreeStoreError::MissingNode`],
1596    /// [`FileTreeStoreError::MissingDestinationParent`], or, after mutation,
1597    /// [`FileTreeStoreError::RevisionExhausted`].
1598    ///
1599    /// # Panics
1600    ///
1601    /// Panics if the internal node index loses either the validated source node
1602    /// or destination parent while the move is applied.
1603    ///
1604    /// # Examples
1605    ///
1606    /// ```
1607    /// use ailloli_ui_fs::{FileEntry, FileKind, FileMetadata, FileTreeStore, FileUri};
1608    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
1609    /// let old = FileUri::parse("file:///old")?;
1610    /// store.apply_attested_insert(store.root(), FileEntry::new(old.clone(), FileMetadata::new(FileKind::File)), None)?;
1611    /// let id = store.node_id(&old).unwrap();
1612    /// let new = FileUri::parse("file:///new")?;
1613    /// store.apply_attested_move(id, new.clone(), None)?;
1614    /// assert_eq!(store.node_id(&new), Some(id));
1615    /// # Ok::<(), Box<dyn std::error::Error>>(())
1616    /// ```
1617    pub fn apply_attested_move(
1618        &mut self,
1619        id: FileTreeNodeId,
1620        to: FileUri,
1621        identity: Option<FileIdentity>,
1622    ) -> Result<FileTreeStoreDelta, FileTreeStoreError> {
1623        let (from, previous_parent) = self
1624            .nodes
1625            .get(&id)
1626            .map(|node| (node.uri.clone(), node.parent))
1627            .ok_or(FileTreeStoreError::MissingNode(id))?;
1628        let next_parent = to
1629            .parent()
1630            .and_then(|uri| self.node_id(&uri))
1631            .ok_or_else(|| FileTreeStoreError::MissingDestinationParent(to.clone()))?;
1632        self.rebase_subtree_uri(id, to.clone());
1633        if let Some(identity) = identity {
1634            let previous = self
1635                .nodes
1636                .get_mut(&id)
1637                .expect("validated node")
1638                .identity
1639                .replace(identity.clone());
1640            if let Some(previous) = previous {
1641                self.unindex_identity(&previous, id);
1642            }
1643            self.index_identity(identity, id);
1644        }
1645        let mut changes = Vec::new();
1646        if previous_parent != Some(next_parent) {
1647            self.detach_from_parent(id);
1648            let index = self
1649                .nodes
1650                .get(&next_parent)
1651                .map_or(0, |node| node.children.len());
1652            self.nodes
1653                .get_mut(&next_parent)
1654                .expect("destination parent exists")
1655                .children
1656                .push(id);
1657            self.nodes.get_mut(&id).expect("validated node").parent = Some(next_parent);
1658            changes.push(FileTreeDelta::Moved {
1659                id,
1660                new_parent: next_parent,
1661                index,
1662            });
1663        }
1664        changes.push(FileTreeDelta::Updated { id });
1665        self.record_watch_echo(WatchEcho::Moved { from, to });
1666        self.commit(changes)
1667    }
1668
1669    /// Marks a retained directory stale without discarding its children.
1670    ///
1671    /// Repeating the operation is a revision-preserving no-op.
1672    ///
1673    /// # Errors
1674    ///
1675    /// Returns [`FileTreeStoreError::MissingNode`],
1676    /// [`FileTreeStoreError::NotDirectory`], or
1677    /// [`FileTreeStoreError::RevisionExhausted`].
1678    ///
1679    /// # Examples
1680    ///
1681    /// ```
1682    /// use ailloli_ui_fs::{DirectoryLoadState, FileKind, FileMetadata, FileTreeStore, FileUri};
1683    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
1684    /// store.mark_stale(store.root())?;
1685    /// assert!(matches!(store.node(store.root()).unwrap().directory_state(), DirectoryLoadState::Stale));
1686    /// # Ok::<(), Box<dyn std::error::Error>>(())
1687    /// ```
1688    pub fn mark_stale(
1689        &mut self,
1690        id: FileTreeNodeId,
1691    ) -> Result<FileTreeStoreDelta, FileTreeStoreError> {
1692        let mut changes = Vec::new();
1693        self.mark_directory_stale_into(id, &mut changes)?;
1694        self.commit(changes)
1695    }
1696
1697    /// Applies one normalized provider watch event without performing I/O.
1698    ///
1699    /// Sequence numbers must increase within a generation. Events from older
1700    /// generations, repeated sequences, and matching echoes of the last 256
1701    /// attested creates/removals/moves are revision-preserving no-ops. A newer
1702    /// generation resets sequence comparison; sequence zero is still a
1703    /// duplicate until a positive sequence arrives. Counters saturate at
1704    /// [`u64::MAX`].
1705    ///
1706    /// Created/modified events stale the retained parent, removals delete a
1707    /// known subtree, and overflow stales the named directory or its parent.
1708    /// Rename/move retention prefers the old URI and otherwise requires a
1709    /// unique identity so hard links are not conflated. If its destination
1710    /// parent is not retained, a known moved node is detached but keeps its
1711    /// former `parent` field until reconciliation; callers should normally
1712    /// watch loaded parents and schedule a refresh after gaps or ambiguity.
1713    ///
1714    /// # Errors
1715    ///
1716    /// Returns [`FileTreeStoreError::NotDirectory`] if an event resolves a
1717    /// non-directory as the parent to stale, or
1718    /// [`FileTreeStoreError::RevisionExhausted`] after mutation when a non-empty
1719    /// delta cannot advance the revision. Missing event parents are ignored.
1720    ///
1721    /// # Panics
1722    ///
1723    /// Panics if the internal URI/node indexes become inconsistent after a watch
1724    /// move resolves an existing node or destination parent.
1725    ///
1726    /// # Examples
1727    ///
1728    /// ```
1729    /// use ailloli_ui_fs::{DirectoryLoadState, FileKind, FileMetadata, FileTreeStore, FileUri, WatchEvent, WatchEventKind};
1730    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
1731    /// let event = WatchEvent::new(WatchEventKind::Created, FileUri::parse("file:///new")?, 1, 0);
1732    /// store.apply_watch_event(&event)?;
1733    /// assert!(matches!(store.node(store.root()).unwrap().directory_state(), DirectoryLoadState::Stale));
1734    /// # Ok::<(), Box<dyn std::error::Error>>(())
1735    /// ```
1736    pub fn apply_watch_event(
1737        &mut self,
1738        event: &WatchEvent,
1739    ) -> Result<FileTreeStoreDelta, FileTreeStoreError> {
1740        self.diagnostics.watch_events = self.diagnostics.watch_events.saturating_add(1);
1741        if event.generation() < self.last_watch_generation {
1742            self.diagnostics.duplicate_watch_events =
1743                self.diagnostics.duplicate_watch_events.saturating_add(1);
1744            return self.commit(Vec::new());
1745        }
1746        if event.generation() > self.last_watch_generation {
1747            self.last_watch_generation = event.generation();
1748            self.last_watch_sequence = 0;
1749        }
1750        if event.sequence() <= self.last_watch_sequence {
1751            self.diagnostics.duplicate_watch_events =
1752                self.diagnostics.duplicate_watch_events.saturating_add(1);
1753            return self.commit(Vec::new());
1754        }
1755        let sequence_gap = self.last_watch_sequence != 0
1756            && event.sequence() > self.last_watch_sequence.saturating_add(1);
1757        self.last_watch_sequence = event.sequence();
1758        if self.consume_watch_echo(event) {
1759            self.diagnostics.duplicate_watch_events =
1760                self.diagnostics.duplicate_watch_events.saturating_add(1);
1761            return self.commit(Vec::new());
1762        }
1763        let mut changes = Vec::new();
1764        if sequence_gap {
1765            self.diagnostics.watch_sequence_gaps =
1766                self.diagnostics.watch_sequence_gaps.saturating_add(1);
1767            self.mark_event_parent_stale(event.uri(), &mut changes)?;
1768        }
1769        match event.kind() {
1770            WatchEventKind::Created | WatchEventKind::Modified => {
1771                self.mark_event_parent_stale(event.uri(), &mut changes)?;
1772                if let Some(id) = self.node_id(event.uri()) {
1773                    changes.push(FileTreeDelta::Updated { id });
1774                }
1775            }
1776            WatchEventKind::Removed => {
1777                if let Some(id) = self.node_id(event.uri()) {
1778                    self.detach_from_parent(id);
1779                    self.remove_subtree(id, &mut changes);
1780                } else {
1781                    self.mark_event_parent_stale(event.uri(), &mut changes)?;
1782                }
1783            }
1784            WatchEventKind::Renamed | WatchEventKind::Moved => {
1785                let Some(previous_uri) = event.previous_uri() else {
1786                    self.mark_event_parent_stale(event.uri(), &mut changes)?;
1787                    return self.commit(changes);
1788                };
1789                let id = self.node_id(previous_uri).or_else(|| {
1790                    event
1791                        .identity()
1792                        .and_then(|identity| self.unique_identity_node(identity))
1793                });
1794                let Some(id) = id else {
1795                    self.mark_event_parent_stale(previous_uri, &mut changes)?;
1796                    self.mark_event_parent_stale(event.uri(), &mut changes)?;
1797                    return self.commit(changes);
1798                };
1799                let old_parent = self.nodes.get(&id).and_then(|node| node.parent);
1800                let new_parent = event.uri().parent().and_then(|uri| self.node_id(&uri));
1801                self.rebase_subtree_uri(id, event.uri().clone());
1802                if let Some(identity) = event.identity().cloned() {
1803                    let old_identity = self
1804                        .nodes
1805                        .get_mut(&id)
1806                        .expect("watch node exists")
1807                        .identity
1808                        .replace(identity.clone());
1809                    if let Some(old_identity) = old_identity {
1810                        self.unindex_identity(&old_identity, id);
1811                    }
1812                    self.index_identity(identity, id);
1813                }
1814                if new_parent != old_parent {
1815                    self.detach_from_parent(id);
1816                    if let Some(parent) = new_parent {
1817                        let index = self
1818                            .nodes
1819                            .get(&parent)
1820                            .map_or(0, |node| node.children.len());
1821                        self.nodes
1822                            .get_mut(&parent)
1823                            .expect("new parent exists")
1824                            .children
1825                            .push(id);
1826                        self.nodes.get_mut(&id).expect("watch node exists").parent = Some(parent);
1827                        changes.push(FileTreeDelta::Moved {
1828                            id,
1829                            new_parent: parent,
1830                            index,
1831                        });
1832                    }
1833                }
1834                changes.push(FileTreeDelta::Updated { id });
1835            }
1836            WatchEventKind::Overflow => {
1837                let target = self
1838                    .node_id(event.uri())
1839                    .filter(|id| {
1840                        self.node(*id)
1841                            .is_some_and(|node| node.metadata.is_directory_like())
1842                    })
1843                    .or_else(|| event.uri().parent().and_then(|uri| self.node_id(&uri)));
1844                if let Some(target) = target {
1845                    self.mark_directory_stale_into(target, &mut changes)?;
1846                }
1847            }
1848        }
1849        self.commit(changes)
1850    }
1851
1852    /// Starts one provider-owned directory listing request.
1853    ///
1854    /// The node must be directory-like and have no active request. Request IDs
1855    /// are monotone and never reused. The returned owned request captures the
1856    /// current store generation and URI; the caller performs I/O elsewhere and
1857    /// later passes both request and result to [`Self::apply_directory_result`].
1858    /// The node is touched and transitions to [`DirectoryLoadState::Loading`].
1859    ///
1860    /// # Errors
1861    ///
1862    /// Returns [`FileTreeStoreError::MissingNode`],
1863    /// [`FileTreeStoreError::NotDirectory`],
1864    /// [`FileTreeStoreError::AlreadyLoading`], or
1865    /// [`FileTreeStoreError::IdentifierExhausted`]. A
1866    /// [`FileTreeStoreError::RevisionExhausted`] error occurs after the request
1867    /// and loading state have been installed.
1868    ///
1869    /// # Panics
1870    ///
1871    /// Panics if the validated directory node disappears from the internal node
1872    /// index before its loading state is installed.
1873    ///
1874    /// # Examples
1875    ///
1876    /// ```
1877    /// use ailloli_ui_fs::{DirectoryLoadState, FileKind, FileMetadata, FileTreeStore, FileUri};
1878    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
1879    /// let (request, delta) = store.begin_directory_load(store.root())?;
1880    /// assert_eq!((request.request_id(), delta.revision()), (1, 1));
1881    /// assert!(matches!(store.node(store.root()).unwrap().directory_state(), DirectoryLoadState::Loading { generation: 1 }));
1882    /// # Ok::<(), Box<dyn std::error::Error>>(())
1883    /// ```
1884    pub fn begin_directory_load(
1885        &mut self,
1886        id: FileTreeNodeId,
1887    ) -> Result<(DirectoryLoadRequest, FileTreeStoreDelta), FileTreeStoreError> {
1888        let uri = {
1889            let node = self
1890                .nodes
1891                .get(&id)
1892                .ok_or(FileTreeStoreError::MissingNode(id))?;
1893            if !node.metadata.is_directory_like() {
1894                return Err(FileTreeStoreError::NotDirectory(id));
1895            }
1896            node.uri.clone()
1897        };
1898        if self.active_requests.contains_key(&id) {
1899            return Err(FileTreeStoreError::AlreadyLoading(id));
1900        }
1901        let request_id = self.next_request_id;
1902        self.next_request_id = self
1903            .next_request_id
1904            .checked_add(1)
1905            .ok_or(FileTreeStoreError::IdentifierExhausted)?;
1906        self.active_requests.insert(id, request_id);
1907        self.diagnostics.directory_loads_started =
1908            self.diagnostics.directory_loads_started.saturating_add(1);
1909        self.touch(id, Instant::now())?;
1910        let state = DirectoryLoadState::Loading {
1911            generation: self.generation,
1912        };
1913        self.nodes
1914            .get_mut(&id)
1915            .expect("validated node")
1916            .directory_state = state.clone();
1917        let request = DirectoryLoadRequest {
1918            request_id,
1919            node_id: id,
1920            store_generation: self.generation,
1921            uri,
1922        };
1923        let delta = self.commit(vec![FileTreeDelta::DirectoryState { id, state }])?;
1924        Ok((request, delta))
1925    }
1926
1927    /// Cancels the currently active load for one directory.
1928    ///
1929    /// The worker may still finish the owned request. Its response is then
1930    /// rejected as stale because the request identifier is no longer active.
1931    /// This keeps collapse and root replacement UI-local and never blocks on
1932    /// filesystem I/O.
1933    ///
1934    /// If no request is active, this is a revision-preserving no-op. If an
1935    /// active request exists but the node is no longer in `Loading`, only the
1936    /// correlation is removed and no delta is emitted.
1937    ///
1938    /// # Errors
1939    ///
1940    /// Returns [`FileTreeStoreError::MissingNode`] for an absent ID or, after
1941    /// cancellation/state mutation, [`FileTreeStoreError::RevisionExhausted`].
1942    ///
1943    /// # Examples
1944    ///
1945    /// ```
1946    /// use ailloli_ui_fs::{DirectoryLoadState, FileKind, FileMetadata, FileTreeStore, FileUri};
1947    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
1948    /// store.begin_directory_load(store.root())?;
1949    /// store.cancel_directory_load(store.root())?;
1950    /// assert!(matches!(store.node(store.root()).unwrap().directory_state(), DirectoryLoadState::Stale));
1951    /// # Ok::<(), Box<dyn std::error::Error>>(())
1952    /// ```
1953    pub fn cancel_directory_load(
1954        &mut self,
1955        id: FileTreeNodeId,
1956    ) -> Result<FileTreeStoreDelta, FileTreeStoreError> {
1957        let node = self
1958            .nodes
1959            .get_mut(&id)
1960            .ok_or(FileTreeStoreError::MissingNode(id))?;
1961        if self.active_requests.remove(&id).is_none() {
1962            return self.commit(Vec::new());
1963        }
1964        if matches!(node.directory_state, DirectoryLoadState::Loading { .. }) {
1965            node.directory_state = DirectoryLoadState::Stale;
1966            return self.commit(vec![FileTreeDelta::DirectoryState {
1967                id,
1968                state: DirectoryLoadState::Stale,
1969            }]);
1970        }
1971        self.commit(Vec::new())
1972    }
1973
1974    /// Applies a provider listing result only when its request is still active.
1975    ///
1976    /// A successful list is reconciled in input order. Entries must be unique,
1977    /// direct children of the requested directory; this structural contract is
1978    /// not validated. Exact URIs preserve IDs, while an identity preserves an
1979    /// ID only when unique in both the incoming list and live store. Existing
1980    /// children absent from the list are removed. A provider error records
1981    /// [`DirectoryLoadState::Error`] and retains existing children.
1982    ///
1983    /// The matching active request is consumed before processing either result.
1984    /// A stale result increments diagnostics but does not consume a newer active
1985    /// request for the same node.
1986    ///
1987    /// # Errors
1988    ///
1989    /// Returns [`FileTreeStoreError::StaleResponse`] for a canceled, superseded,
1990    /// or previous-generation request. Reconciliation may return
1991    /// [`FileTreeStoreError::MissingNode`],
1992    /// [`FileTreeStoreError::IdentifierExhausted`], or
1993    /// [`FileTreeStoreError::RevisionExhausted`]. These failures are not
1994    /// transactional: IDs, indexes, nodes, or state may already have changed.
1995    ///
1996    /// # Examples
1997    ///
1998    /// ```
1999    /// use ailloli_ui_fs::{DirectoryLoadState, FileEntry, FileKind, FileMetadata, FileTreeStore, FileUri};
2000    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
2001    /// let (request, _) = store.begin_directory_load(store.root())?;
2002    /// let entry = FileEntry::new(FileUri::parse("file:///a")?, FileMetadata::new(FileKind::File));
2003    /// store.apply_directory_result(&request, Ok(vec![(entry, None)]))?;
2004    /// assert_eq!(store.node(store.root()).unwrap().children().len(), 1);
2005    /// assert!(matches!(store.node(store.root()).unwrap().directory_state(), DirectoryLoadState::Loaded { .. }));
2006    /// # Ok::<(), Box<dyn std::error::Error>>(())
2007    /// ```
2008    pub fn apply_directory_result(
2009        &mut self,
2010        request: &DirectoryLoadRequest,
2011        result: Result<Vec<(FileEntry, Option<FileIdentity>)>, FileError>,
2012    ) -> Result<FileTreeStoreDelta, FileTreeStoreError> {
2013        if request.store_generation != self.generation
2014            || self.active_requests.get(&request.node_id) != Some(&request.request_id)
2015        {
2016            self.diagnostics.stale_responses = self.diagnostics.stale_responses.saturating_add(1);
2017            return Err(FileTreeStoreError::StaleResponse {
2018                request_id: request.request_id,
2019            });
2020        }
2021        self.active_requests.remove(&request.node_id);
2022        self.diagnostics.directory_results_applied =
2023            self.diagnostics.directory_results_applied.saturating_add(1);
2024        match result {
2025            Ok(entries) => self.reconcile_directory(request.node_id, entries),
2026            Err(error) => {
2027                self.diagnostics.directory_errors =
2028                    self.diagnostics.directory_errors.saturating_add(1);
2029                let state = DirectoryLoadState::Error(error);
2030                self.nodes
2031                    .get_mut(&request.node_id)
2032                    .ok_or(FileTreeStoreError::MissingNode(request.node_id))?
2033                    .directory_state = state.clone();
2034                self.commit(vec![FileTreeDelta::DirectoryState {
2035                    id: request.node_id,
2036                    state,
2037                }])
2038            }
2039        }
2040    }
2041
2042    /// Invalidates all active loads and advances the store generation.
2043    ///
2044    /// Every node in [`DirectoryLoadState::Loading`] becomes stale and every
2045    /// active correlation is removed. If none were loading, the generation
2046    /// still advances while the returned delta keeps the current revision.
2047    /// Watch generation/sequence tracking is independent and is not reset.
2048    ///
2049    /// # Errors
2050    ///
2051    /// Returns [`FileTreeStoreError::RevisionExhausted`] if either generation
2052    /// or a required revision cannot advance. In the latter case generation,
2053    /// requests, and loading states have already changed.
2054    ///
2055    /// # Examples
2056    ///
2057    /// ```
2058    /// use ailloli_ui_fs::{DirectoryLoadState, FileKind, FileMetadata, FileTreeStore, FileUri};
2059    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
2060    /// store.begin_directory_load(store.root())?;
2061    /// store.invalidate_generation()?;
2062    /// assert_eq!(store.generation(), 2);
2063    /// assert!(matches!(store.node(store.root()).unwrap().directory_state(), DirectoryLoadState::Stale));
2064    /// # Ok::<(), Box<dyn std::error::Error>>(())
2065    /// ```
2066    pub fn invalidate_generation(&mut self) -> Result<FileTreeStoreDelta, FileTreeStoreError> {
2067        self.generation = self
2068            .generation
2069            .checked_add(1)
2070            .ok_or(FileTreeStoreError::RevisionExhausted)?;
2071        self.active_requests.clear();
2072        let mut changes = Vec::new();
2073        for node in self.nodes.values_mut() {
2074            if matches!(node.directory_state, DirectoryLoadState::Loading { .. }) {
2075                node.directory_state = DirectoryLoadState::Stale;
2076                changes.push(FileTreeDelta::DirectoryState {
2077                    id: node.id,
2078                    state: DirectoryLoadState::Stale,
2079                });
2080            }
2081        }
2082        self.commit(changes)
2083    }
2084
2085    /// Reconciles one complete, caller-validated direct-child snapshot.
2086    ///
2087    /// Incoming order becomes child order. Exact URI retention wins; identity
2088    /// retention is allowed only for a single incoming occurrence and one live
2089    /// indexed node. Duplicate URIs or non-child entries can corrupt structural
2090    /// assumptions because this private primitive deliberately does not validate
2091    /// the provider contract. Mutation is incremental and not rolled back if ID
2092    /// or revision exhaustion occurs.
2093    ///
2094    /// # Errors
2095    ///
2096    /// Returns [`FileTreeStoreError::MissingNode`] when `parent` is absent,
2097    /// [`FileTreeStoreError::IdentifierExhausted`] while allocating a new child,
2098    /// or [`FileTreeStoreError::RevisionExhausted`] while committing the delta.
2099    ///
2100    /// # Panics
2101    ///
2102    /// Panics if the URI, identity, or parent-child indexes are internally
2103    /// inconsistent. Callers must supply the validated direct-child snapshot
2104    /// described above to preserve those invariants.
2105    fn reconcile_directory(
2106        &mut self,
2107        parent: FileTreeNodeId,
2108        entries: Vec<(FileEntry, Option<FileIdentity>)>,
2109    ) -> Result<FileTreeStoreDelta, FileTreeStoreError> {
2110        let old_children = self
2111            .nodes
2112            .get(&parent)
2113            .ok_or(FileTreeStoreError::MissingNode(parent))?
2114            .children
2115            .clone();
2116        let incoming_uris = entries
2117            .iter()
2118            .map(|(entry, _)| entry.uri.clone())
2119            .collect::<HashSet<_>>();
2120        let mut incoming_identity_counts = HashMap::<FileIdentity, usize>::new();
2121        for (_, identity) in &entries {
2122            if let Some(identity) = identity {
2123                *incoming_identity_counts
2124                    .entry(identity.clone())
2125                    .or_default() += 1;
2126            }
2127        }
2128        let mut retained = HashSet::new();
2129        let mut claimed = HashSet::new();
2130        let mut next_children = Vec::with_capacity(entries.len());
2131        let mut changes = Vec::new();
2132
2133        for (index, (entry, identity)) in entries.into_iter().enumerate() {
2134            // A filesystem identity is not necessarily unique: hard links
2135            // intentionally share one inode while remaining distinct tree
2136            // entries. Prefer the exact URI and use identity-based retention
2137            // only when both the old store and this directory snapshot make
2138            // the identity unambiguous. This preserves IDs for attested
2139            // renames without collapsing `/bin` hard links into one row.
2140            let existing = self
2141                .uri_index
2142                .get(&entry.uri)
2143                .copied()
2144                .filter(|id| !claimed.contains(id))
2145                .or_else(|| {
2146                    let identity = identity.as_ref()?;
2147                    if incoming_identity_counts.get(identity).copied() != Some(1) {
2148                        return None;
2149                    }
2150                    let id = self.unique_identity_node(identity)?;
2151                    let old_uri = self.nodes.get(&id)?.uri.clone();
2152                    (!claimed.contains(&id) && !incoming_uris.contains(&old_uri)).then_some(id)
2153                })
2154                .filter(|id| self.nodes.contains_key(id));
2155            let id = match existing {
2156                Some(id) => {
2157                    claimed.insert(id);
2158                    let previous_parent = self.nodes.get(&id).and_then(|node| node.parent);
2159                    if previous_parent != Some(parent) {
2160                        self.detach_from_parent(id);
2161                        self.nodes.get_mut(&id).expect("indexed node").parent = Some(parent);
2162                        changes.push(FileTreeDelta::Moved {
2163                            id,
2164                            new_parent: parent,
2165                            index,
2166                        });
2167                    } else {
2168                        retained.insert(id);
2169                        if old_children.iter().position(|child| *child == id) != Some(index) {
2170                            changes.push(FileTreeDelta::Moved {
2171                                id,
2172                                new_parent: parent,
2173                                index,
2174                            });
2175                        }
2176                    }
2177                    if self
2178                        .nodes
2179                        .get(&id)
2180                        .is_some_and(|node| node.uri != entry.uri)
2181                    {
2182                        self.rebase_subtree_uri(id, entry.uri.clone());
2183                    }
2184                    let (previous_identity, identity_changed) = {
2185                        let node = self.nodes.get_mut(&id).expect("indexed node");
2186                        node.metadata = entry.metadata;
2187                        if node.identity != identity {
2188                            let previous = node.identity.take();
2189                            node.identity = identity.clone();
2190                            (previous, true)
2191                        } else {
2192                            (None, false)
2193                        }
2194                    };
2195                    if let Some(previous) = previous_identity {
2196                        self.unindex_identity(&previous, id);
2197                    }
2198                    if identity_changed {
2199                        if let Some(identity) = identity {
2200                            self.index_identity(identity, id);
2201                        }
2202                    }
2203                    changes.push(FileTreeDelta::Updated { id });
2204                    id
2205                }
2206                None => {
2207                    let id = self.allocate_node_id()?;
2208                    let node = FileTreeNode {
2209                        id,
2210                        parent: Some(parent),
2211                        uri: entry.uri.clone(),
2212                        identity: identity.clone(),
2213                        metadata: entry.metadata,
2214                        children: Vec::new(),
2215                        directory_state: DirectoryLoadState::Unloaded,
2216                        expanded: false,
2217                        selected: false,
2218                        focused: false,
2219                        pending_operation: false,
2220                    };
2221                    self.uri_index.insert(entry.uri, id);
2222                    if let Some(identity) = identity {
2223                        self.index_identity(identity, id);
2224                    }
2225                    self.nodes.insert(id, node.clone());
2226                    self.cache.insert(
2227                        id,
2228                        FileTreeCacheState {
2229                            last_used: Instant::now(),
2230                            collapsed_at: Some(Instant::now()),
2231                        },
2232                    );
2233                    changes.push(FileTreeDelta::Inserted {
2234                        parent,
2235                        index,
2236                        node: Box::new(node),
2237                    });
2238                    id
2239                }
2240            };
2241            next_children.push(id);
2242        }
2243
2244        for child in old_children {
2245            if !retained.contains(&child) && !next_children.contains(&child) {
2246                self.remove_subtree(child, &mut changes);
2247            }
2248        }
2249        self.nodes
2250            .get_mut(&parent)
2251            .expect("validated parent")
2252            .children = next_children;
2253        let state = DirectoryLoadState::Loaded {
2254            revision: self.revision.saturating_add(1),
2255        };
2256        self.nodes
2257            .get_mut(&parent)
2258            .expect("validated parent")
2259            .directory_state = state.clone();
2260        changes.push(FileTreeDelta::DirectoryState { id: parent, state });
2261        self.commit(changes)
2262    }
2263
2264    /// Removes a subtree iteratively in descendant-before-parent delta order.
2265    ///
2266    /// Missing roots/descendants are skipped. Indexes, active requests, and
2267    /// cache entries are removed, and the eviction counter saturates.
2268    fn remove_subtree(&mut self, id: FileTreeNodeId, changes: &mut Vec<FileTreeDelta>) {
2269        let mut pending = vec![(id, false)];
2270        while let Some((current, visited)) = pending.pop() {
2271            if !visited {
2272                let Some(node) = self.nodes.get(&current) else {
2273                    continue;
2274                };
2275                pending.push((current, true));
2276                pending.extend(node.children.iter().copied().map(|child| (child, false)));
2277                continue;
2278            }
2279            let Some(node) = self.nodes.remove(&current) else {
2280                continue;
2281            };
2282            self.uri_index.remove(&node.uri);
2283            if let Some(identity) = node.identity {
2284                self.unindex_identity(&identity, current);
2285            }
2286            self.active_requests.remove(&current);
2287            self.cache.remove(&current);
2288            self.diagnostics.evicted_nodes = self.diagnostics.evicted_nodes.saturating_add(1);
2289            changes.push(FileTreeDelta::Removed { id: current });
2290        }
2291    }
2292
2293    /// Removes every occurrence of `id` from its retained parent's child list.
2294    ///
2295    /// The node's own `parent` field is intentionally unchanged.
2296    fn detach_from_parent(&mut self, id: FileTreeNodeId) {
2297        let parent = self.nodes.get(&id).and_then(|node| node.parent);
2298        if let Some(parent) = parent.and_then(|parent| self.nodes.get_mut(&parent)) {
2299            parent.children.retain(|child| *child != id);
2300        }
2301    }
2302
2303    /// Adds a node to the potentially non-unique provider-identity index.
2304    fn index_identity(&mut self, identity: FileIdentity, id: FileTreeNodeId) {
2305        self.identity_index.entry(identity).or_default().insert(id);
2306    }
2307
2308    /// Removes a node from an identity bucket and drops empty buckets.
2309    fn unindex_identity(&mut self, identity: &FileIdentity, id: FileTreeNodeId) {
2310        let remove_entry = self.identity_index.get_mut(identity).is_some_and(|ids| {
2311            ids.remove(&id);
2312            ids.is_empty()
2313        });
2314        if remove_entry {
2315            self.identity_index.remove(identity);
2316        }
2317    }
2318
2319    /// Returns the sole indexed node, or `None` for absent/ambiguous identities.
2320    fn unique_identity_node(&self, identity: &FileIdentity) -> Option<FileTreeNodeId> {
2321        let ids = self.identity_index.get(identity)?;
2322        (ids.len() == 1).then(|| *ids.iter().next().expect("one identity candidate"))
2323    }
2324
2325    /// Marks a retained lexical parent stale; absent parents are ignored.
2326    ///
2327    /// # Errors
2328    ///
2329    /// Propagates [`FileTreeStoreError::MissingNode`] or
2330    /// [`FileTreeStoreError::NotDirectory`] if a retained parent index resolves
2331    /// to an invalid node.
2332    fn mark_event_parent_stale(
2333        &mut self,
2334        uri: &FileUri,
2335        changes: &mut Vec<FileTreeDelta>,
2336    ) -> Result<(), FileTreeStoreError> {
2337        if let Some(parent) = uri.parent().and_then(|parent| self.node_id(&parent)) {
2338            self.mark_directory_stale_into(parent, changes)?;
2339        }
2340        Ok(())
2341    }
2342
2343    /// Marks a directory stale once and appends its state delta.
2344    ///
2345    /// Returns `MissingNode` or `NotDirectory` without appending a change.
2346    ///
2347    /// # Errors
2348    ///
2349    /// Returns [`FileTreeStoreError::MissingNode`] when `id` is absent, or
2350    /// [`FileTreeStoreError::NotDirectory`] when it is not directory-like.
2351    fn mark_directory_stale_into(
2352        &mut self,
2353        id: FileTreeNodeId,
2354        changes: &mut Vec<FileTreeDelta>,
2355    ) -> Result<(), FileTreeStoreError> {
2356        let node = self
2357            .nodes
2358            .get_mut(&id)
2359            .ok_or(FileTreeStoreError::MissingNode(id))?;
2360        if !node.metadata.is_directory_like() {
2361            return Err(FileTreeStoreError::NotDirectory(id));
2362        }
2363        if !matches!(node.directory_state, DirectoryLoadState::Stale) {
2364            node.directory_state = DirectoryLoadState::Stale;
2365            changes.push(FileTreeDelta::DirectoryState {
2366                id,
2367                state: DirectoryLoadState::Stale,
2368            });
2369        }
2370        Ok(())
2371    }
2372
2373    /// Rewrites a subtree's URI prefix iteratively and updates the URI index.
2374    ///
2375    /// Descendants use lexical path suffixes. A descendant whose rebased URI
2376    /// cannot be constructed is silently left at its previous URI, as is a
2377    /// missing node; callers provide normalized compatible URIs in normal use.
2378    fn rebase_subtree_uri(&mut self, id: FileTreeNodeId, next_uri: FileUri) {
2379        let mut pending = vec![(id, next_uri)];
2380        while let Some((current, next_uri)) = pending.pop() {
2381            let Some(node) = self.nodes.get(&current) else {
2382                continue;
2383            };
2384            let previous_uri = node.uri.clone();
2385            let children = node.children.clone();
2386            self.uri_index.remove(&previous_uri);
2387            self.nodes.get_mut(&current).expect("node exists").uri = next_uri.clone();
2388            self.uri_index.insert(next_uri.clone(), current);
2389            for child in children {
2390                let child_uri = self.nodes.get(&child).expect("child exists").uri.clone();
2391                let suffix = child_uri
2392                    .path()
2393                    .strip_prefix(previous_uri.path().trim_end_matches('/'))
2394                    .unwrap_or(child_uri.path());
2395                let next_path = format!("{}{}", next_uri.path().trim_end_matches('/'), suffix);
2396                if let Ok(rebased) = FileUri::new(
2397                    next_uri.scheme().to_string(),
2398                    next_uri.authority().map(str::to_string),
2399                    next_path,
2400                ) {
2401                    pending.push((child, rebased));
2402                }
2403            }
2404        }
2405    }
2406
2407    /// Returns whether any reachable retained node is pinned, without recursion.
2408    fn subtrees_contain_pin(&self, roots: &[FileTreeNodeId]) -> bool {
2409        let mut pending = roots.to_vec();
2410        while let Some(id) = pending.pop() {
2411            let Some(node) = self.nodes.get(&id) else {
2412                continue;
2413            };
2414            if node.is_pinned() {
2415                return true;
2416            }
2417            pending.extend(node.children.iter().copied());
2418        }
2419        false
2420    }
2421
2422    /// Retains an expected watcher echo, dropping the oldest at capacity 256.
2423    fn record_watch_echo(&mut self, echo: WatchEcho) {
2424        if self.watch_echoes.len() == WATCH_ECHO_CAPACITY {
2425            self.watch_echoes.pop_front();
2426        }
2427        self.watch_echoes.push_back(echo);
2428    }
2429
2430    /// Removes and reports the first matching attested-operation echo.
2431    ///
2432    /// Modified/overflow events and moves without a previous URI never match.
2433    fn consume_watch_echo(&mut self, event: &WatchEvent) -> bool {
2434        let expected = match event.kind() {
2435            WatchEventKind::Created => WatchEcho::Created(event.uri().clone()),
2436            WatchEventKind::Removed => WatchEcho::Removed(event.uri().clone()),
2437            WatchEventKind::Renamed | WatchEventKind::Moved => {
2438                let Some(from) = event.previous_uri() else {
2439                    return false;
2440                };
2441                WatchEcho::Moved {
2442                    from: from.clone(),
2443                    to: event.uri().clone(),
2444                }
2445            }
2446            WatchEventKind::Modified | WatchEventKind::Overflow => return false,
2447        };
2448        let Some(index) = self.watch_echoes.iter().position(|echo| *echo == expected) else {
2449            return false;
2450        };
2451        self.watch_echoes.remove(index);
2452        true
2453    }
2454
2455    /// Sums approximate node payloads for cache policy.
2456    ///
2457    /// The final iterator sum uses ordinary `usize` addition (debug panic and
2458    /// release wrap on theoretical total overflow), though retaining enough
2459    /// in-memory nodes to reach that bound is generally impossible.
2460    fn estimated_payload_bytes(&self) -> usize {
2461        self.nodes.values().map(Self::node_payload_bytes).sum()
2462    }
2463
2464    /// Tests strict soft-limit pressure; equality is within the limit.
2465    fn cache_limits_exceeded(&self) -> bool {
2466        self.nodes.len() > self.limits.max_nodes
2467            || self.estimated_payload_bytes() > self.limits.max_payload_bytes
2468    }
2469
2470    /// Estimates one node using saturating component accumulation.
2471    ///
2472    /// Includes inline struct size, rendered URI bytes, identity lengths, and
2473    /// child-vector capacity. It excludes map/deque overhead, file contents,
2474    /// string excess capacity, and heap payloads in retained error state. The
2475    /// identity provider/value lengths are first combined with ordinary `usize`
2476    /// addition, which can theoretically panic in debug or wrap in release.
2477    fn node_payload_bytes(node: &FileTreeNode) -> usize {
2478        std::mem::size_of::<FileTreeNode>()
2479            .saturating_add(node.uri.to_string().len())
2480            .saturating_add(
2481                node.identity
2482                    .as_ref()
2483                    .map_or(0, |identity| identity.provider.len() + identity.value.len()),
2484            )
2485            .saturating_add(
2486                node.children
2487                    .capacity()
2488                    .saturating_mul(std::mem::size_of::<FileTreeNodeId>()),
2489            )
2490    }
2491
2492    /// Iteratively estimates reachable node count and payload, both saturating.
2493    ///
2494    /// Missing IDs are ignored. Duplicate/cyclic structural references would
2495    /// be counted repeatedly, so callers rely on the store's tree invariant.
2496    fn subtree_footprint(&self, roots: &[FileTreeNodeId]) -> (usize, usize) {
2497        let mut nodes = 0_usize;
2498        let mut payload_bytes = 0_usize;
2499        let mut pending = roots.to_vec();
2500        while let Some(id) = pending.pop() {
2501            let Some(node) = self.nodes.get(&id) else {
2502                continue;
2503            };
2504            nodes = nodes.saturating_add(1);
2505            payload_bytes = payload_bytes.saturating_add(Self::node_payload_bytes(node));
2506            pending.extend(node.children.iter().copied());
2507        }
2508        (nodes, payload_bytes)
2509    }
2510
2511    /// Allocates the next monotone ID; `u64::MAX` itself is never returned.
2512    ///
2513    /// # Errors
2514    ///
2515    /// Returns [`FileTreeStoreError::IdentifierExhausted`] when incrementing the
2516    /// next `u64` identifier would overflow.
2517    fn allocate_node_id(&mut self) -> Result<FileTreeNodeId, FileTreeStoreError> {
2518        let id = FileTreeNodeId(self.next_node_id);
2519        self.next_node_id = self
2520            .next_node_id
2521            .checked_add(1)
2522            .ok_or(FileTreeStoreError::IdentifierExhausted)?;
2523        Ok(id)
2524    }
2525
2526    /// Packages changes and advances revision only for a non-empty delta.
2527    ///
2528    /// Revision exhaustion does not roll back earlier caller mutation. The
2529    /// emitted-delta diagnostic counter saturates.
2530    ///
2531    /// # Errors
2532    ///
2533    /// Returns [`FileTreeStoreError::RevisionExhausted`] when a non-empty delta
2534    /// would advance the revision beyond `u64::MAX`.
2535    fn commit(
2536        &mut self,
2537        changes: Vec<FileTreeDelta>,
2538    ) -> Result<FileTreeStoreDelta, FileTreeStoreError> {
2539        if changes.is_empty() {
2540            return Ok(FileTreeStoreDelta {
2541                revision: self.revision,
2542                changes,
2543            });
2544        }
2545        self.revision = self
2546            .revision
2547            .checked_add(1)
2548            .ok_or(FileTreeStoreError::RevisionExhausted)?;
2549        self.diagnostics.emitted_deltas = self.diagnostics.emitted_deltas.saturating_add(1);
2550        Ok(FileTreeStoreDelta {
2551            revision: self.revision,
2552            changes,
2553        })
2554    }
2555}