Skip to main content

nibkeep_node/library/
trees.rs

1//! Trees: folders whose files NibKeep tracks by their paths in them, with every version, as
2//! Git tracks a working tree ([technical design: trees]). A tree is an entity of its own, with a
3//! root on each device that holds a copy of it; each of its files is a file of its own,
4//! whatever its content, with its path; a commit is a change for each of its parts, a first
5//! that makes its revision, with its message, then one for each entity it records
6//! ([technical design: one entity per change]); and each replica keeps the state of its copy in an index of its
7//! own, which tells what to read.
8//!
9//! [technical design: trees]: ../../../../docs/Technical-design.md#15-trees
10//! [technical design: one entity per change]: ../../../../docs/Technical-design.md#62-one-entity-per-change
11
12mod commit;
13mod compare;
14mod diff;
15mod git;
16mod history;
17mod index;
18mod locate;
19mod paths;
20mod repositories;
21mod secrecy;
22mod update;
23mod walk;
24mod write;
25
26use std::cell::RefCell;
27use std::collections::{BTreeMap, BTreeSet};
28use std::fs::{self, File};
29use std::io;
30use std::path::{Path, PathBuf};
31
32use nibkeep_base::{EntityId, Hash, SpaceId};
33use nibkeep_crypto::rand_core::CryptoRng;
34use nibkeep_model::storage::Statements as _;
35use nibkeep_model::{FieldName, Name, Statement, TypeName, Value, fields};
36use nibkeep_std::{
37	COMMITTED_IN, CONTENT, EXECUTABLE, FILE, GIT_REPOSITORY, IN_TREE, LINK_TARGET, ON_DEVICE,
38	PARTS, PATH, REVISION, ROOT_OF, SECRET_CONTENT, SECRET_FILE, SYMBOLIC_LINK, TREE, TREE_PATH,
39	TREE_ROOT,
40};
41
42use nibkeep_log::{ChangeId, Log};
43use nibkeep_store::{LogFile, StateFile};
44
45use self::commit::moving;
46use self::index::{Entry, INDEX_CONTEXT, Index, SecretVersions, Version};
47use self::locate::{Blocked, Listings, Located, located, located_in, place_for_new};
48pub use self::repositories::{CloneFolder, GitRepository, RecordedRepository, ToClone};
49use super::Library;
50use super::entities::NewValue;
51use crate::NodeError;
52
53pub use self::diff::FileDiff;
54pub use self::history::{BlameLine, TreeLogEntry, TreePoint};
55pub use self::paths::is_safe_tree_path;
56pub use self::update::Updated;
57pub use self::write::{CopiesRemoved, Reverted, Written};
58
59/// The file in the replica's folder that commits to its trees lock, so that two programs
60/// never commit to one copy at once.
61const LOCK: &str = "trees.lock";
62
63/// The types that a tree's records need.
64const TREE_TYPES: [TypeName; 7] = [
65	TREE,
66	TREE_ROOT,
67	FILE,
68	SECRET_FILE,
69	SYMBOLIC_LINK,
70	REVISION,
71	GIT_REPOSITORY,
72];
73
74/// A tree of a space, and where its folder is on this device, if it has a root here.
75#[derive(Clone, Debug, PartialEq, Eq)]
76pub struct Tree {
77	/// The tree.
78	pub id: EntityId,
79	/// Its name: that of its folder when it started.
80	pub name: Option<String>,
81	/// Its folder on this device, if it has one.
82	pub root: Option<PathBuf>,
83}
84
85/// A file or a link of a tree, as the library has it now.
86#[derive(Clone, Debug, PartialEq, Eq)]
87pub struct TreeEntry {
88	/// The file or link.
89	pub entity: EntityId,
90	/// Its path in the tree.
91	pub path: String,
92	/// What it holds.
93	pub kind: TreeEntryKind,
94}
95
96/// What a file or a link of a tree holds.
97#[derive(Clone, Debug, PartialEq, Eq)]
98pub enum TreeEntryKind {
99	/// A file: its content, unless a purge took it away, and whether it is executable.
100	File {
101		/// The hash of its content.
102		content: Option<Hash>,
103		/// Whether it is executable.
104		executable: bool,
105	},
106	/// A symbolic link, and what it points to.
107	Link {
108		/// Its target, as it was written.
109		target: String,
110	},
111	/// A secret file whose content this replica cannot read now: its secrets are locked, or
112	/// not on this device ([technical design: secrets in trees]).
113	///
114	/// [technical design: secrets in trees]: ../../../docs/Technical-design.md#151-secrets-in-trees
115	Sealed,
116}
117
118/// What a path of a tree's copy holds that the tree does not, as a commit records it.
119#[derive(Clone, Debug, PartialEq, Eq)]
120pub struct TreeChange {
121	/// The path; of a move, where it went.
122	pub path: String,
123	/// What changed.
124	pub change: Change,
125}
126
127/// What changed at a path of a tree's copy.
128#[derive(Clone, Debug, PartialEq, Eq)]
129pub enum Change {
130	/// A file or a link that the tree does not hold.
131	New,
132	/// A new version: other content, another target, or a file that became a link or the
133	/// other way round.
134	Edited,
135	/// The same content, executable now or no longer.
136	Executable(bool),
137	/// Deleted from the copy.
138	Deleted,
139	/// Moved from another path, with the same content, as Git finds exact renames.
140	Moved {
141		/// Where it was.
142		from: String,
143	},
144	/// Edited from a version that this replica does not know, as after its index was lost:
145	/// a commit records it only with force.
146	Unknown,
147}
148
149/// What a tree's copy on this device holds that the tree does not, and what the tree holds
150/// that the copy does not.
151#[derive(Clone, Debug, PartialEq, Eq)]
152pub struct TreeStatus {
153	/// The tree.
154	pub tree: EntityId,
155	/// Its folder on this device.
156	pub root: PathBuf,
157	/// What a commit would record, by path.
158	pub changes: Vec<TreeChange>,
159	/// The paths that changed in the tree since the copy was written, as by another device,
160	/// which the copy does not have yet: other versions, moves, additions and deletions.
161	pub behind: Vec<String>,
162	/// The paths that have competing values, as when two devices committed one file
163	/// offline: several versions, several paths, or several files at one path.
164	pub competing: Vec<String>,
165	/// What the copy holds that a commit cannot take, by path, with why.
166	pub skipped: Vec<(String, String)>,
167	/// The commits cut short, as by a crash, before all their parts were made: the next
168	/// commit takes in the rest.
169	pub cut_short: Vec<CutShort>,
170	/// How many files were read in full: those whose size or time changed.
171	pub read: usize,
172	/// The folders of the copy that hold Git repositories, by their paths in the tree: what
173	/// `nib` asks Git about, for a commit to record.
174	pub repositories: Vec<String>,
175	/// The paths among the changes that are secret files, or would go in as new ones, which
176	/// a commit seals for the space's secrets ([technical design: secrets in trees]).
177	///
178	/// [technical design: secrets in trees]: ../../../docs/Technical-design.md#151-secrets-in-trees
179	pub secret: Vec<String>,
180	/// The secret files of the tree that this copy lacks, as this replica cannot read them:
181	/// its secrets are locked, or not on this device.
182	pub sealed: Vec<String>,
183}
184
185/// The secret files of a tree, and its ordinary files that look secret
186/// ([technical design: secrets in trees]).
187///
188/// [technical design: secrets in trees]: ../../../docs/Technical-design.md#151-secrets-in-trees
189#[derive(Clone, Debug, Default, PartialEq, Eq)]
190pub struct TreeSecrets {
191	/// The paths of its secret files, ordered.
192	pub secret: Vec<String>,
193	/// The paths of the secret files that this copy lacks, as this replica cannot read them.
194	pub sealed: Vec<String>,
195	/// The paths of its ordinary files that a built-in name or a `.nibsecret` file matches,
196	/// as files committed before one did: they stay ordinary until made secret.
197	pub looking_secret: Vec<String>,
198}
199
200/// Where a secret file of a tree is: the tree whose commit made it, which it belongs to for
201/// good, and its path there ([technical design: secrets in trees]).
202///
203/// [technical design: secrets in trees]: ../../../docs/Technical-design.md#151-secrets-in-trees
204#[derive(Clone, Debug, PartialEq, Eq)]
205pub struct InTree {
206	/// The tree.
207	pub tree: EntityId,
208	/// Its path in the tree, its last if it was deleted from the tree; of competing paths,
209	/// the one in the statement with the smallest ID, as [`Library::tree_entries`] gives it.
210	/// None if no path that a tree may hold.
211	pub path: Option<String>,
212}
213
214/// What purging the versions of an ordinary file that a commit made secret takes, and what
215/// it leaves.
216#[derive(Clone, Debug, Default, PartialEq, Eq)]
217pub struct MadeSecret {
218	/// The contents purged, which no other value holds as an ordinary file's, in the order
219	/// the file had them.
220	pub purged: Vec<Hash>,
221	/// The contents left, which another value holds as an ordinary file's, as they were never
222	/// secret.
223	pub kept: Vec<Hash>,
224}
225
226/// A commit that was cut short.
227#[derive(Clone, Debug, PartialEq, Eq)]
228pub struct CutShort {
229	/// Its revision.
230	pub revision: EntityId,
231	/// How many parts it was to have.
232	pub parts: u64,
233	/// How many it has.
234	pub made: u64,
235}
236
237/// What to commit to a tree.
238#[derive(Clone, Debug, PartialEq, Eq)]
239pub struct Commit<'a> {
240	message: Option<&'a str>,
241	paths: Vec<String>,
242	force: bool,
243	cut_after: Option<usize>,
244	repositories: Option<Repositories<'a>>,
245	secret: Vec<String>,
246	ordinary: Vec<String>,
247	leave_secrets: bool,
248}
249
250/// Where a commit learns what Git says of the repositories in a copy.
251#[derive(Clone, Copy)]
252enum Repositories<'a> {
253	/// As given.
254	Given(&'a [GitRepository]),
255	/// From what reads them, given the folders found.
256	Read(&'a dyn Fn(&[String]) -> Vec<GitRepository>),
257}
258
259impl std::fmt::Debug for Repositories<'_> {
260	fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
261		match self {
262			Self::Given(repositories) => {
263				formatter.debug_tuple("Given").field(repositories).finish()
264			}
265			Self::Read(_) => formatter.write_str("Read"),
266		}
267	}
268}
269
270impl PartialEq for Repositories<'_> {
271	fn eq(&self, other: &Self) -> bool {
272		match (self, other) {
273			(Self::Given(a), Self::Given(b)) => a == b,
274			(Self::Read(a), Self::Read(b)) => std::ptr::addr_eq(*a, *b),
275			_ => false,
276		}
277	}
278}
279
280impl Eq for Repositories<'_> {}
281
282impl<'a> Commit<'a> {
283	/// Everything that changed, with a message or without.
284	#[must_use]
285	pub fn new(message: Option<&'a str>) -> Self {
286		Self {
287			message,
288			paths: Vec::new(),
289			force: false,
290			cut_after: None,
291			repositories: None,
292			secret: Vec::new(),
293			ordinary: Vec::new(),
294			leave_secrets: false,
295		}
296	}
297
298	/// Records the Git repositories in the copy as Git describes them: those found new, and
299	/// what changed of those the tree records, which moved or are gone. Without it, a
300	/// commit leaves repositories as they are.
301	#[must_use]
302	pub fn with_repositories(mut self, repositories: &'a [GitRepository]) -> Self {
303		self.repositories = Some(Repositories::Given(repositories));
304		self
305	}
306
307	/// Records the Git repositories in the copy as `read` describes the folders that the
308	/// commit finds holding them, as with [`Commit::with_repositories`]: for a program that
309	/// asks Git only once the folder is walked.
310	#[must_use]
311	pub fn with_repositories_read_by(
312		mut self,
313		read: &'a dyn Fn(&[String]) -> Vec<GitRepository>,
314	) -> Self {
315		self.repositories = Some(Repositories::Read(read));
316		self
317	}
318
319	/// Only what changed at these paths of the tree, or in these folders of it; a move
320	/// counts if either of its ends does.
321	#[must_use]
322	pub fn with_paths(mut self, paths: Vec<String>) -> Self {
323		self.paths = paths;
324		self
325	}
326
327	/// Records on top what changed from a version that is no longer the tree's, which
328	/// history keeps, and what was edited from a version this replica does not know.
329	#[must_use]
330	pub fn with_force(mut self) -> Self {
331		self.force = true;
332		self
333	}
334
335	/// Takes in as secret files the new files at these paths, which no built-in name or
336	/// `.nibsecret` file makes secret; and makes secret the ordinary files committed there:
337	/// each becomes a new secret file, the old one deleted, whose versions
338	/// [`Library::purge_made_secret`] purges once the person agrees.
339	#[must_use]
340	pub fn with_secret(mut self, paths: Vec<String>) -> Self {
341		self.secret = paths;
342		self
343	}
344
345	/// Takes in as ordinary files the new files at these paths, which would be secret.
346	#[must_use]
347	pub fn with_ordinary(mut self, paths: Vec<String>) -> Self {
348		self.ordinary = paths;
349		self
350	}
351
352	/// Commits the rest where a change of a secret file cannot be sealed, as the secrets are
353	/// locked or not on this device, which leaves those changes for a later commit.
354	#[must_use]
355	pub fn leaving_secrets(mut self) -> Self {
356		self.leave_secrets = true;
357		self
358	}
359
360	/// Stops after this many parts, as a crash would: for trying what devices do with a
361	/// commit cut short.
362	#[must_use]
363	pub fn cut_after(mut self, parts: usize) -> Self {
364		self.cut_after = Some(parts);
365		self
366	}
367}
368
369/// What a commit recorded.
370#[derive(Clone, Debug, Default, PartialEq, Eq)]
371pub struct Committed {
372	/// The commit's revision, which its first part made; none if nothing changed.
373	pub revision: Option<EntityId>,
374	/// How many parts it made, a change for each: the first, with the revision, and one for
375	/// each entity it recorded ([technical design: one entity per change]).
376	///
377	/// [technical design: one entity per change]: ../../../docs/Technical-design.md#62-one-entity-per-change
378	pub parts: usize,
379	/// What it recorded, by path.
380	pub changes: Vec<TreeChange>,
381	/// What it recorded of Git repositories, by path.
382	pub repositories: Vec<TreeChange>,
383	/// The paths of the secret files it recorded, new versions or new files, ordered.
384	pub secret: Vec<String>,
385	/// The paths of the changes of secret files that it left, as the secrets were locked or
386	/// not on this device, which a later commit takes.
387	pub left: Vec<String>,
388	/// The paths of the new ordinary files that hold the content of a secret file of the
389	/// tree, which the secrets do not protect there.
390	pub unprotected: Vec<String>,
391	/// The ordinary files it made secret, each now a new secret file at its path, whose old
392	/// versions [`Library::purge_made_secret`] purges.
393	pub made_secret: Vec<EntityId>,
394}
395
396/// How much a tree would take in if it started in a folder.
397#[derive(Clone, Debug, PartialEq, Eq)]
398pub struct StartPreview {
399	/// How many files and links.
400	pub files: usize,
401	/// How many bytes the files hold.
402	pub bytes: u64,
403	/// The folders that hold Git repositories, by their paths in the tree, which it records
404	/// as references.
405	pub repositories: Vec<String>,
406}
407
408/// What starting a tree did.
409#[derive(Clone, Debug, PartialEq, Eq)]
410pub struct TreeStarted {
411	/// The tree.
412	pub tree: EntityId,
413	/// Its folder on this device, as the file system resolves it.
414	pub root: PathBuf,
415	/// Its first commit, of every file in the folder.
416	pub committed: Committed,
417}
418
419/// A file or a link of a tree, as the state says.
420#[derive(Clone, Debug)]
421struct Current {
422	entity: EntityId,
423	/// Its version, or `None` for a file whose content a purge took away.
424	version: Option<Version>,
425}
426
427/// The files and links of a tree, as the state says.
428#[derive(Debug, Default)]
429struct TreeState {
430	by_path: BTreeMap<String, Current>,
431	by_entity: BTreeMap<EntityId, String>,
432	competing: BTreeSet<String>,
433	/// The deleted files and links, by their last paths: what a file restored at its path
434	/// is again.
435	deleted: BTreeMap<String, Current>,
436	/// The version of each file and link that is not deleted, its own, also of one that
437	/// competes for its path with another.
438	own: BTreeMap<EntityId, Option<Version>>,
439	/// The versions of the files and links that have competing ones, as when two devices
440	/// committed one file apart, each with its statements' order.
441	versions: BTreeMap<EntityId, Vec<Version>>,
442	/// The paths of the files and links whose paths compete, as when two devices moved one
443	/// file apart: each is at its place at any of them.
444	paths: BTreeMap<EntityId, Vec<String>>,
445	/// The files and links deleted on one device while another gave them a new version,
446	/// before either saw the other, with the keys of the deletions that compete with it, as
447	/// competing values: they stay, among the competing, until a commit settles them,
448	/// keeping them, or deleting them again.
449	contested: BTreeMap<EntityId, Vec<String>>,
450	/// The secret files of the tree, whose content only the space's secrets open.
451	secret: BTreeSet<EntityId>,
452	/// The secret files whose versions this replica cannot read now, as its secrets are
453	/// locked or not on this device, and of which its copy holds nothing, by path.
454	sealed: BTreeMap<String, EntityId>,
455	/// Every path that a secret file of the tree has had: a new file there is secret too.
456	secret_paths: BTreeSet<String>,
457}
458
459impl TreeState {
460	/// Stands in, for each secret file that this replica cannot read now, the version that
461	/// its copy here held when it was last written or committed, as the index says, so that
462	/// the copy is neither written over nor deleted, and nothing of it is taken for a change,
463	/// until the secrets open what the tree holds.
464	fn fill_sealed(&mut self, entries: &BTreeMap<String, Entry>) {
465		for (path, entity) in std::mem::take(&mut self.sealed) {
466			let Some(entry) = entries.values().find(|entry| entry.entity == entity) else {
467				self.sealed.insert(path, entity);
468				continue;
469			};
470			let version = Some(entry.version.clone());
471			self.own.insert(entity, version.clone());
472			if self.by_path.contains_key(&path) {
473				self.competing.insert(path.clone());
474			} else {
475				self.by_path
476					.insert(path.clone(), Current { entity, version });
477			}
478			self.by_entity.insert(entity, path);
479		}
480	}
481
482	/// Whether a file of the tree is a secret one.
483	fn is_secret(&self, entity: EntityId) -> bool {
484		self.secret.contains(&entity)
485	}
486
487	/// Whether the state holds `entity` at `path`, at `version`.
488	fn holds(&self, path: &str, entity: EntityId, version: &Version) -> bool {
489		self.at(entity, path) && self.has_version(entity, version)
490	}
491
492	/// Whether `entity` is at `path`: its path, or one of those that compete.
493	fn at(&self, entity: EntityId, path: &str) -> bool {
494		self.by_entity.get(&entity).is_some_and(|at| at == path)
495			|| self
496				.paths
497				.get(&entity)
498				.is_some_and(|paths| paths.iter().any(|at| at == path))
499	}
500
501	/// Whether the state holds `version` of `entity`, wherever it is: its own version, or
502	/// one of those that compete.
503	fn has_version(&self, entity: EntityId, version: &Version) -> bool {
504		// Of a file whose versions compete, any of them: which one shows first follows the
505		// statements' random IDs. An edit of such a file waits for an update all the same
506		// (`compare::settle_competing`).
507		match self.versions.get(&entity) {
508			Some(all) => all.contains(version),
509			None => self
510				.own
511				.get(&entity)
512				.is_some_and(|own| own.as_ref() == Some(version)),
513		}
514	}
515}
516
517impl Library {
518	/// Whether a tree could start in `folder`, and how much it would take in: for asking the
519	/// person first, as [`Library::start_tree`] makes the folder's files the tree's copies.
520	///
521	/// # Errors
522	///
523	/// As [`Library::start_tree`], before it writes anything.
524	pub fn would_start_tree(
525		&self,
526		space: SpaceId,
527		folder: &Path,
528	) -> Result<StartPreview, NodeError> {
529		let root = self.checked_new_root(space, folder)?;
530		let walked = walk::walk(&root, &BTreeSet::new(), &self.apart());
531		Ok(StartPreview {
532			files: walked.found.len(),
533			bytes: walked.found.values().map(|found| found.size).sum(),
534			repositories: walked.repositories,
535		})
536	}
537
538	/// Starts a tree in `folder`: a tree named after the folder, its root on this device,
539	/// and a first commit of every file in it, with `message`, in parts, as every commit is.
540	/// The folder's files become the tree's copies, which a purge of
541	/// their content deletes where they were not edited, so apps ask the person first.
542	///
543	/// # Errors
544	///
545	/// Returns [`NodeError::TreeInTree`] if the folder is in a tree's folder on this device,
546	/// or holds one; [`NodeError::GitRepositoryHere`] if it holds a Git repository, which
547	/// trees record as references; and another error if it is no folder, or reading it or
548	/// saving the changes fails.
549	pub fn start_tree(
550		&mut self,
551		space: SpaceId,
552		folder: &Path,
553		message: Option<&str>,
554		wall_millis: u64,
555		rng: &mut impl CryptoRng,
556	) -> Result<TreeStarted, NodeError> {
557		self.start_tree_with(space, folder, &Commit::new(message), wall_millis, rng)
558	}
559
560	/// Starts a tree in `folder`, as [`Library::start_tree`] does, with the first commit's
561	/// message and the Git repositories in the folder, as Git describes them, from `commit`.
562	///
563	/// # Errors
564	///
565	/// As [`Library::start_tree`].
566	pub fn start_tree_with(
567		&mut self,
568		space: SpaceId,
569		folder: &Path,
570		commit: &Commit<'_>,
571		wall_millis: u64,
572		rng: &mut impl CryptoRng,
573	) -> Result<TreeStarted, NodeError> {
574		self.check_not_revoked(space)?;
575		let _locked = self.lock_trees()?;
576		let root = self.checked_new_root(space, folder)?;
577		self.install_standard(space, &TREE_TYPES, wall_millis, rng)?;
578		let name = root
579			.file_name()
580			.map(|name| name.to_string_lossy().into_owned())
581			.filter(|name| !name.is_empty());
582		let mut values = Vec::new();
583		if let Some(name) = name {
584			values.push(NewValue::new(fields::NAME, Value::Name(Name::new(&name))));
585		}
586		let (tree, founded) = self.new_entity(space, &[TREE], values, rng)?;
587		let (root_entity, rooted) = self.new_entity(
588			space,
589			&[TREE_ROOT],
590			vec![
591				NewValue::new(ROOT_OF, Value::Reference(tree)),
592				NewValue::new(ON_DEVICE, Value::Reference(self.info.device)),
593				NewValue::new(PATH, Value::Text(root.to_string_lossy().into_owned())),
594			],
595			rng,
596		)?;
597		// The root is this device's own record, saved with the commit, which no other device
598		// waits for.
599		let founding = vec![(Some(tree), founded), (None, rooted)];
600		let committed =
601			self.commit_in(space, (tree, &root), commit, founding, (wall_millis, rng))?;
602		self.index()?.set_root(tree, root_entity, &root)?;
603		Ok(TreeStarted {
604			tree,
605			root,
606			committed,
607		})
608	}
609
610	/// The trees of a space that are not deleted, with their folders on this device, ordered
611	/// by name.
612	///
613	/// # Errors
614	///
615	/// Returns an error if the library has no such space, or the space cannot be read.
616	pub fn trees(&self, space: SpaceId) -> Result<Vec<Tree>, NodeError> {
617		let open = self.space(space)?;
618		let state = open.stored.log().state();
619		let roots = self.roots_here(space)?;
620		let mut trees = Vec::new();
621		for tree in super::entities::with_type(&open.stored, &TREE)? {
622			let tree = state.canonical(tree)?;
623			if state.is_deleted(tree)? || trees.iter().any(|known: &Tree| known.id == tree) {
624				continue;
625			}
626			trees.push(Tree {
627				id: tree,
628				name: self.name(space, tree)?,
629				root: roots.get(&tree).cloned(),
630			});
631		}
632		trees.sort_by(|a, b| a.name.cmp(&b.name).then(a.id.cmp(&b.id)));
633		Ok(trees)
634	}
635
636	/// The tree whose folder on this device holds `folder`, or is it, if there is one.
637	///
638	/// # Errors
639	///
640	/// Returns an error if the library has no such space, or the space cannot be read.
641	pub fn tree_at(&self, space: SpaceId, folder: &Path) -> Result<Option<Tree>, NodeError> {
642		let Some(folder) = resolved(folder) else {
643			return Ok(None);
644		};
645		let roots = self.roots_here(space)?;
646		let Some((&tree, root)) = roots.iter().find(|(_, root)| folder.starts_with(root)) else {
647			return Ok(None);
648		};
649		Ok(Some(Tree {
650			id: tree,
651			name: self.name(space, tree)?,
652			root: Some(root.clone()),
653		}))
654	}
655
656	/// The files and links of a tree, as the library has them now, ordered by path. Of
657	/// competing values, the one in the statement with the smallest ID.
658	///
659	/// # Errors
660	///
661	/// Returns an error if the library has no such space, or the space cannot be read.
662	pub fn tree_entries(
663		&self,
664		space: SpaceId,
665		tree: EntityId,
666	) -> Result<Vec<TreeEntry>, NodeError> {
667		let state = self.tree_state(space, tree)?;
668		let mut entries: Vec<TreeEntry> = state
669			.by_path
670			.into_iter()
671			.map(|(path, current)| TreeEntry {
672				entity: current.entity,
673				path,
674				kind: match current.version {
675					Some(Version::Link { target }) => TreeEntryKind::Link { target },
676					Some(Version::File {
677						content,
678						executable,
679					}) => TreeEntryKind::File {
680						content: Some(content),
681						executable,
682					},
683					None => TreeEntryKind::File {
684						content: None,
685						executable: false,
686					},
687				},
688			})
689			.chain(state.sealed.into_iter().map(|(path, entity)| TreeEntry {
690				entity,
691				path,
692				kind: TreeEntryKind::Sealed,
693			}))
694			.collect();
695		entries.sort_by(|a, b| a.path.cmp(&b.path));
696		Ok(entries)
697	}
698
699	/// What the copy of a tree on this device holds that the tree does not, and what the
700	/// tree holds that the copy does not. It reads only the files whose size or
701	/// modification time changed since they were written or committed, and records what it
702	/// found unchanged, so that it is not read again. It waits for a commit to the tree that
703	/// runs, and deletes the copies of content that a purge took away, as
704	/// [`Library::settle_checkouts`] does after a sync.
705	///
706	/// # Errors
707	///
708	/// Returns [`NodeError::NoTreeHere`] if the tree has no folder on this device,
709	/// [`NodeError::TreeFolderGone`] if its folder is gone, and an error if the space or the
710	/// index cannot be read.
711	pub fn tree_status(&self, space: SpaceId, tree: EntityId) -> Result<TreeStatus, NodeError> {
712		let _locked = self.lock_trees()?;
713		let root = self.root_here(space, tree)?;
714		let mut index = self.index()?;
715		let purged = self.learn_purges(space, &index)?;
716		let state = self.tree_state(space, tree)?;
717		let apart = self.apart();
718		settle_tree((tree, &root, &apart), &mut index, (&purged, &state))?;
719		self.follow_cut_short(space, (tree, &root, &apart), &mut index, &state)?;
720		// Where content was purged, new files are read too, as a commit reads them, so that
721		// one holding it is not shown as a change to commit.
722		let read_new = !purged.is_empty();
723		let compared = self.compare(space, (tree, &root), &state, &index, (&purged, read_new))?;
724		index.change(tree, &compared.forgotten, &compared.refreshed)?;
725		self.note_secrets(space, (tree, &index), &state, &compared.refreshed)?;
726		index.unmark(tree, &compared.unmarked)?;
727		if compared.known {
728			index.know(tree)?;
729		}
730		Ok(TreeStatus {
731			tree,
732			root,
733			changes: compared
734				.pending
735				.iter()
736				.map(|pending| TreeChange {
737					path: pending.path.clone(),
738					change: pending.change.clone(),
739				})
740				.collect(),
741			secret: compared
742				.pending
743				.iter()
744				.filter(|pending| pending.secret)
745				.map(|pending| pending.path.clone())
746				.collect(),
747			sealed: state.sealed.keys().cloned().collect(),
748			behind: compared.behind.into_iter().collect(),
749			competing: state.competing.into_iter().collect(),
750			skipped: compared
751				.skipped
752				.into_iter()
753				.chain(compared.marked)
754				.collect(),
755			cut_short: self.cut_short(space, tree)?,
756			read: compared.read,
757			repositories: compared.repositories,
758		})
759	}
760
761	/// Commits what changed in the copy of a tree on this device, or at the paths given: new
762	/// files and links, new versions, moves, deletions and executable bits, in parts made one
763	/// after another ([technical design: one entity per change]): a first that makes the commit's revision, with
764	/// the message and how many parts there are, then a part for each entity it records,
765	/// which names the revision. Every version is sealed into the store, whatever storage
766	/// policies say. Returns nothing if nothing changed.
767	///
768	/// [technical design: one entity per change]: ../../../docs/Technical-design.md#62-one-entity-per-change
769	///
770	/// # Errors
771	///
772	/// Returns [`NodeError::TreeStale`] if a path changed here and in the tree since the
773	/// copy was written, as by another device, [`NodeError::UnknownVersion`] if a copy was
774	/// edited from a version this replica does not know, and [`NodeError::TreeEmptied`] if
775	/// every file of the tree is gone from its copy, unless the commit is forced;
776	/// [`NodeError::NoTreeHere`] if the tree has no folder on this device, and
777	/// [`NodeError::TreeFolderGone`] if its folder is gone; and an error if a file cannot be
778	/// read or the changes saved.
779	pub fn commit_tree(
780		&mut self,
781		space: SpaceId,
782		tree: EntityId,
783		commit: &Commit<'_>,
784		wall_millis: u64,
785		rng: &mut impl CryptoRng,
786	) -> Result<Committed, NodeError> {
787		self.check_not_revoked(space)?;
788		let _locked = self.lock_trees()?;
789		let root = self.root_here(space, tree)?;
790		self.install_standard(space, &TREE_TYPES, wall_millis, rng)?;
791		self.commit_in(space, (tree, &root), commit, Vec::new(), (wall_millis, rng))
792	}
793
794	/// The secret files of a tree, and its ordinary files that a built-in name, or a
795	/// `.nibsecret` file of this device's copy, matches: files committed before one did,
796	/// which stay ordinary until a commit makes them secret.
797	///
798	/// # Errors
799	///
800	/// Returns [`NodeError::NotATree`] if `tree` is none, and an error if the space, the
801	/// index or the copy cannot be read.
802	pub fn tree_secrets(&self, space: SpaceId, tree: EntityId) -> Result<TreeSecrets, NodeError> {
803		let tree = self.check_tree(space, tree)?;
804		let state = self.tree_state(space, tree)?;
805		let rules = match self.root_here(space, tree) {
806			Ok(root) => {
807				let index = self.index()?;
808				let left_out = self.left_out(space, tree, &root, &index)?;
809				secrecy::Rules::of_copy(&walk::walk(&root, &left_out, &self.apart()).found)
810			}
811			Err(_) => secrecy::Rules::built_in(),
812		};
813		let mut listed = TreeSecrets {
814			sealed: state.sealed.keys().cloned().collect(),
815			..TreeSecrets::default()
816		};
817		for (path, current) in &state.by_path {
818			if state.is_secret(current.entity) {
819				listed.secret.push(path.clone());
820			} else if matches!(current.version, Some(Version::File { .. })) && rules.is_secret(path)
821			{
822				listed.looking_secret.push(path.clone());
823			}
824		}
825		listed.secret.extend(listed.sealed.iter().cloned());
826		listed.secret.sort();
827		listed.secret.dedup();
828		Ok(listed)
829	}
830
831	/// The tree that a secret file belongs to, and its path there, if it is a tree's: the
832	/// tree whose commit made it, whatever changes said later of its tree, as any replica of
833	/// the space may say them, an AI agent's too. A secret file that no commit of a tree
834	/// made, as a password record's, is no tree's, whatever its tree and path say. A file
835	/// deleted from its tree is still the tree's. It needs neither the secrets nor a copy of
836	/// the tree on this device.
837	///
838	/// # Errors
839	///
840	/// Returns an error if the library has no such space, or the space cannot be read.
841	pub fn secret_file_in_tree(
842		&self,
843		space: SpaceId,
844		file: EntityId,
845	) -> Result<Option<InTree>, NodeError> {
846		self.space(space)?.stored.reading(|stored| {
847			let state = stored.log().state();
848			let file = state.canonical(file)?;
849			let Secrecy::Of(tree) = secret_file_of(state, file)? else {
850				return Ok(None);
851			};
852			let mut statements = state.current(file, &TREE_PATH)?;
853			statements.sort_by_key(|statement| statement.id);
854			let path = statements
855				.iter()
856				.find_map(|statement| match &statement.value {
857					Value::Text(path) => Some(path.clone()),
858					_ => None,
859				})
860				.filter(|path| is_safe_tree_path(path));
861			Ok(Some(InTree { tree, path }))
862		})
863	}
864
865	/// What purging the versions of an ordinary file that a commit made secret would take:
866	/// the contents its versions held, current or past, that no other value holds as an
867	/// ordinary file's, which [`Library::purge_made_secret`] purges; and those that another
868	/// holds, which were never secret, and stay. A file that is not deleted, as one still in
869	/// its tree, takes nothing.
870	///
871	/// # Errors
872	///
873	/// The errors of [`Library::purgeable`].
874	pub fn would_purge_made_secret(
875		&self,
876		space: SpaceId,
877		file: EntityId,
878	) -> Result<MadeSecret, NodeError> {
879		let mut contents: Vec<(Option<nibkeep_time::Timestamp>, Hash)> = Vec::new();
880		{
881			let state = self.space(space)?.stored.log().state();
882			if !state.is_deleted(state.canonical(file)?)? {
883				return Ok(MadeSecret::default());
884			}
885			for id in state.storage().of_field(file, &CONTENT)? {
886				if let Some(recorded) = state.storage().get(id)?
887					&& let Value::Blob(content) = recorded.statement.value
888					&& contents.iter().all(|(_, known)| *known != content)
889				{
890					contents.push((state.recorded(id)?, content));
891				}
892			}
893		}
894		contents.sort();
895		let mut made = MadeSecret::default();
896		for (_, content) in contents {
897			let purge = self.purgeable(space, file, &CONTENT, Some(&Value::Blob(content)))?;
898			if purge.also.is_empty() {
899				made.purged.push(content);
900			} else {
901				made.kept.push(content);
902			}
903		}
904		Ok(made)
905	}
906
907	/// Purges, for good and everywhere, the contents of the versions of an ordinary file that
908	/// a commit made secret, as [`Library::would_purge_made_secret`] finds them, once the
909	/// person agreed: the secret file at its path keeps its own sealed copy.
910	///
911	/// # Errors
912	///
913	/// The errors of [`Library::purge`].
914	pub fn purge_made_secret(
915		&mut self,
916		space: SpaceId,
917		file: EntityId,
918		wall_millis: u64,
919		rng: &mut impl CryptoRng,
920	) -> Result<MadeSecret, NodeError> {
921		let made = self.would_purge_made_secret(space, file)?;
922		for content in &made.purged {
923			let value = Value::Blob(*content);
924			self.purge(space, file, &CONTENT, Some(&value), wall_millis, rng)?;
925		}
926		Ok(made)
927	}
928
929	/// Moves a file or a link of a tree, or a folder with everything in it, on the disk and
930	/// in the tree at once, as one commit: from the path `from` of the tree to `to`, which
931	/// must be free. Edits not committed move with the copy, and stay to commit.
932	///
933	/// # Errors
934	///
935	/// Returns [`NodeError::NotInTree`] if the tree holds nothing at or under `from`,
936	/// [`NodeError::UnsafePath`] if `to` is no path a tree may hold, would go through a link
937	/// or names what cannot be written here, [`NodeError::PlaceTaken`] if something is at
938	/// `to`, and an error if moving or saving fails.
939	pub fn move_in_tree(
940		&mut self,
941		space: SpaceId,
942		tree: EntityId,
943		(from, to): (&str, &str),
944		wall_millis: u64,
945		rng: &mut impl CryptoRng,
946	) -> Result<Committed, NodeError> {
947		self.check_not_revoked(space)?;
948		let _locked = self.lock_trees()?;
949		let root = self.root_here(space, tree)?;
950		if !is_safe_tree_path(to) || !to.split('/').all(paths::fits_this_system) {
951			return Err(NodeError::UnsafePath(to.to_owned()));
952		}
953		self.install_standard(space, &TREE_TYPES, wall_millis, rng)?;
954		let state = self.tree_state(space, tree)?;
955		let mut index = self.index()?;
956		let entries = index.entries(tree)?;
957		let under = |path: &str| path == from || path.starts_with(&format!("{from}/"));
958		let moved_to = |path: &str| format!("{to}{}", &path[from.len()..]);
959		// Every file and link there, those that compete for one path too.
960		let moved: Vec<(String, String, EntityId)> = state
961			.by_entity
962			.iter()
963			.filter(|(_, path)| under(path))
964			.map(|(entity, path)| (path.clone(), moved_to(path), *entity))
965			.collect();
966		if moved.is_empty() {
967			return Err(NodeError::NotInTree(from.to_owned()));
968		}
969		if to == from || to.starts_with(&format!("{from}/")) {
970			return Err(NodeError::UnsafePath(to.to_owned()));
971		}
972		// The tree holds nothing at `to`, nor in it, nor a file on its way, even where its
973		// copy is gone: one path holds one file.
974		let clashes = |path: &String| {
975			path == to || path.starts_with(&format!("{to}/")) || to.starts_with(&format!("{path}/"))
976		};
977		if state.by_path.keys().chain(entries.keys()).any(clashes) {
978			return Err(NodeError::PlaceTaken(root.join(to)));
979		}
980		let apart = self.apart();
981		let Located::Here(source) = located(&root, from, &apart) else {
982			return Err(NodeError::NotInTree(from.to_owned()));
983		};
984		// Copies that NibKeep wrote there for other reasons, as checkouts, are recorded by
985		// their paths, which a move would leave behind.
986		if self
987			.left_out(space, tree, &root, &index)?
988			.iter()
989			.any(|path| under(path))
990		{
991			return Err(NodeError::HoldsOtherCopies(from.to_owned()));
992		}
993		let blocked = |why| match why {
994			Blocked::Taken => NodeError::PlaceTaken(root.join(to)),
995			Blocked::Unsafe => NodeError::UnsafePath(to.to_owned()),
996		};
997		let target = place_for_new(&root, to, &apart).map_err(blocked)?;
998		if let Some(parent) = target.parent() {
999			write::make_folders(parent).map_err(NodeError::file(parent))?;
1000			// What made the folders may have raced a link into them.
1001			if place_for_new(&root, to, &apart).as_ref() != Ok(&target) {
1002				return Err(NodeError::UnsafePath(to.to_owned()));
1003			}
1004		}
1005		fs::rename(&source, &target).map_err(NodeError::file(&source))?;
1006		save_move(&source, &target);
1007		let mut parts: Vec<(EntityId, Vec<nibkeep_model::Operation>)> = Vec::new();
1008		let mut changes = Vec::new();
1009		let mut removed = Vec::new();
1010		let mut set = Vec::new();
1011		{
1012			let open = self.space(space)?;
1013			let space_state = open.stored.log().state();
1014			for (old, new, entity) in &moved {
1015				parts.push((*entity, moving(space_state, *entity, old, new, rng)?));
1016				changes.push(TreeChange {
1017					path: new.clone(),
1018					change: Change::Moved { from: old.clone() },
1019				});
1020			}
1021			// The index's entries move with the copies, whatever the tree holds.
1022			for (old, entry) in entries.iter().filter(|(path, _)| under(path)) {
1023				removed.push(old.clone());
1024				set.push((moved_to(old), entry.clone()));
1025			}
1026		}
1027		// A move is a commit in parts, a part for each file after one with its revision
1028		// (technical design: one entity per change), saved all or none, as the copy is moved already.
1029		let count = parts.len() + 1;
1030		let saved = self.batch_whole(space, |library| {
1031			let (revision, made) = library.revision_operations(space, tree, None, count, rng)?;
1032			library.commit(space, made, wall_millis, rng)?;
1033			for (entity, operations) in parts {
1034				let operations =
1035					library.part_operations(space, revision, entity, operations, rng)?;
1036				library.commit(space, operations, wall_millis, rng)?;
1037			}
1038			Ok(revision)
1039		});
1040		let revision = match saved {
1041			Ok(revision) => revision,
1042			Err(error) => {
1043				// The copy goes back where the tree has it.
1044				let _ = fs::rename(&target, &source);
1045				return Err(error);
1046			}
1047		};
1048		changes.sort_by(|a, b| a.path.cmp(&b.path));
1049		changes.dedup();
1050		index.change(tree, &removed, &set)?;
1051		Ok(Committed {
1052			revision: Some(revision),
1053			parts: count,
1054			changes,
1055			..Committed::default()
1056		})
1057	}
1058}
1059
1060impl Library {
1061	/// The folder `folder` as the file system resolves it, if a tree may start there: a
1062	/// folder, in no tree's folder on this device and holding none, and holding no Git
1063	/// repository.
1064	fn checked_new_root(&self, space: SpaceId, folder: &Path) -> Result<PathBuf, NodeError> {
1065		let root = fs::canonicalize(folder).map_err(NodeError::file(folder))?;
1066		let root = super::files::plain(root);
1067		if !root.is_dir() {
1068			return Err(NodeError::file(&root)(io::ErrorKind::NotADirectory.into()));
1069		}
1070		// Never in the library's own folder, nor in any folder that a system reads as `.git`
1071		// or `.nib`.
1072		let in_reserved = root.components().any(|component| match component {
1073			std::path::Component::Normal(name) => paths::is_reserved(&name.to_string_lossy()),
1074			_ => false,
1075		});
1076		if in_reserved || self.apart().iter().any(|apart| root.starts_with(apart)) {
1077			return Err(NodeError::NotATreeFolder(root));
1078		}
1079		let _ = space;
1080		for &any in self.spaces.keys() {
1081			for other in self.roots_here(any)?.values() {
1082				if root.starts_with(other) || other.starts_with(&root) {
1083					return Err(NodeError::TreeInTree(root));
1084				}
1085			}
1086		}
1087		if fs::symlink_metadata(root.join(".git")).is_ok() || walk::is_bare(&root) {
1088			return Err(NodeError::GitRepositoryHere(root));
1089		}
1090		Ok(root)
1091	}
1092
1093	/// The folders of the trees of a space on this device, by tree. A root counts only on
1094	/// the replica that recorded it, so that no replica names another's folders: as this
1095	/// replica's index lists it, with its folder, while the root and its tree are not deleted;
1096	/// or else, as after the index was lost, a root on this device whose values this replica
1097	/// wrote, all of them.
1098	fn roots_here(&self, space: SpaceId) -> Result<BTreeMap<EntityId, PathBuf>, NodeError> {
1099		let open = self.space(space)?;
1100		let state = open.stored.log().state();
1101		let alive = |entity: EntityId| -> Result<bool, NodeError> {
1102			Ok(!state.is_deleted(state.canonical(entity)?)?)
1103		};
1104		let mut roots = BTreeMap::new();
1105		let recorded = if self.directory().join(index::INDEX).exists() {
1106			self.index()?.roots()?
1107		} else {
1108			BTreeMap::new()
1109		};
1110		for (tree, (root, folder)) in &recorded {
1111			let in_space = !state.types(*root)?.is_empty();
1112			if in_space && alive(*root)? && alive(*tree)? {
1113				roots.insert(state.canonical(*tree)?, folder.clone());
1114			}
1115		}
1116		let this_replica = self.replica.signing.verifying_key();
1117		for root in open
1118			.stored
1119			.find(&ON_DEVICE, &Value::Reference(self.info.device))?
1120		{
1121			let root = state.canonical(root)?;
1122			if state.is_deleted(root)? || !state.types(root)?.contains(&TREE_ROOT) {
1123				continue;
1124			}
1125			let mut values = BTreeMap::new();
1126			let mut own = true;
1127			for field in [&ROOT_OF, &ON_DEVICE, &PATH] {
1128				let mut current = state.current(root, field)?;
1129				current.sort_by_key(|statement| statement.id);
1130				for statement in &current {
1131					own &= open.stored.log().author_of(statement.id)? == Some(this_replica);
1132				}
1133				let first = current.first().map(|statement| statement.value.clone());
1134				values.insert(field.clone(), first);
1135			}
1136			let (true, Some(Some(Value::Reference(tree))), Some(Some(Value::Text(path)))) =
1137				(own, values.remove(&ROOT_OF), values.remove(&PATH))
1138			else {
1139				continue;
1140			};
1141			let tree = state.canonical(tree)?;
1142			if alive(tree)? {
1143				roots.entry(tree).or_insert_with(|| PathBuf::from(path));
1144			}
1145		}
1146		Ok(roots)
1147	}
1148
1149	/// Whether `folder` is in a tree's folder on this device, of any space.
1150	pub(crate) fn in_any_tree(&self, folder: &Path) -> Result<bool, NodeError> {
1151		let Some(folder) = resolved(folder) else {
1152			return Ok(false);
1153		};
1154		for &space in self.spaces.keys() {
1155			if self
1156				.roots_here(space)?
1157				.values()
1158				.any(|root| folder.starts_with(root))
1159			{
1160				return Ok(true);
1161			}
1162		}
1163		Ok(false)
1164	}
1165
1166	/// A tree of a space, as the entity it is now; [`NodeError::NotATree`] if it is none.
1167	pub(super) fn check_tree(&self, space: SpaceId, tree: EntityId) -> Result<EntityId, NodeError> {
1168		let state = self.space(space)?.stored.log().state();
1169		let tree = state.canonical(tree)?;
1170		if state.is_deleted(tree)? || !state.types(tree)?.contains(&TREE) {
1171			return Err(NodeError::NotATree(tree.to_string()));
1172		}
1173		Ok(tree)
1174	}
1175
1176	/// The folder of a tree on this device, which must be there: a folder that is gone, as
1177	/// when it moved, is never taken for one whose files were all deleted.
1178	fn root_here(&self, space: SpaceId, tree: EntityId) -> Result<PathBuf, NodeError> {
1179		let tree = self.space(space)?.stored.log().state().canonical(tree)?;
1180		let root = self
1181			.roots_here(space)?
1182			.remove(&tree)
1183			.ok_or_else(|| NodeError::NoTreeHere(tree.to_string()))?;
1184		if !fs::symlink_metadata(&root).is_ok_and(|metadata| metadata.is_dir()) {
1185			return Err(NodeError::TreeFolderGone(root));
1186		}
1187		Ok(root)
1188	}
1189
1190	/// The index of this replica's copies of trees.
1191	fn index(&self) -> Result<Index, NodeError> {
1192		Index::open(self.directory(), &self.derived_key(INDEX_CONTEXT))
1193	}
1194
1195	/// The index of this replica's copies of trees, if it has one, as a replica that holds
1196	/// no copy, such as an AI agent's, has not.
1197	fn index_if_any(&self) -> Result<Option<Index>, NodeError> {
1198		if fs::symlink_metadata(self.directory().join(index::INDEX)).is_err() {
1199			return Ok(None);
1200		}
1201		self.index().map(Some)
1202	}
1203
1204	/// The name of the device whose replica made a statement, as the personal space names
1205	/// it, if it says.
1206	fn device_name_of(
1207		&self,
1208		space: SpaceId,
1209		statement: nibkeep_base::StatementId,
1210	) -> Option<String> {
1211		let named = || -> Result<Option<String>, NodeError> {
1212			let Some(author) = self.author_of(space, statement)? else {
1213				return Ok(None);
1214			};
1215			let personal = self.personal_space();
1216			let roster = self.space(personal)?.stored.log().state();
1217			let device = roster
1218				.current(author.replica, &nibkeep_governance::ON_DEVICE)?
1219				.into_iter()
1220				.find_map(|statement| statement.value.as_reference());
1221			match device {
1222				Some(device) => self.name(personal, device),
1223				None => Ok(None),
1224			}
1225		};
1226		named().ok().flatten()
1227	}
1228
1229	/// Takes the lock of this replica's trees if no other program holds it, until what it
1230	/// returns is dropped; `None` if another holds it.
1231	fn try_lock_trees(&self) -> Result<Option<File>, NodeError> {
1232		let path = self.directory().join(LOCK);
1233		let file = File::options()
1234			.create(true)
1235			.truncate(false)
1236			.write(true)
1237			.open(&path)
1238			.map_err(NodeError::file(&path))?;
1239		match file.try_lock() {
1240			Ok(()) => Ok(Some(file)),
1241			Err(std::fs::TryLockError::WouldBlock) => Ok(None),
1242			Err(std::fs::TryLockError::Error(error)) => Err(NodeError::file(&path)(error)),
1243		}
1244	}
1245
1246	/// Takes the lock of commits to this replica's trees, until what it returns is dropped.
1247	fn lock_trees(&self) -> Result<File, NodeError> {
1248		let path = self.directory().join(LOCK);
1249		let file = File::options()
1250			.create(true)
1251			.truncate(false)
1252			.write(true)
1253			.open(&path)
1254			.map_err(NodeError::file(&path))?;
1255		file.lock().map_err(NodeError::file(&path))?;
1256		Ok(file)
1257	}
1258
1259	/// The files and links of a tree, as the state says: of competing values, the one in
1260	/// the statement with the smallest ID, and the path listed among the competing. A path
1261	/// that no tree may hold, as a faulty or hostile replica could record, is left out, so
1262	/// that nothing is ever written there.
1263	fn tree_state(&self, space: SpaceId, tree: EntityId) -> Result<TreeState, NodeError> {
1264		let open = self.space(space)?;
1265		let readable = self.secrets_unlocked(space);
1266		let mut read = open.stored.reading(|stored| {
1267			let log = stored.log();
1268			let state = log.state();
1269			let entities = tree_entities(state, tree)?;
1270			read_tree_state(state, tree, &entities, (Some(&Changes::of(log)), readable))
1271		})?;
1272		if !read.sealed.is_empty()
1273			&& let Some(index) = self.index_if_any()?
1274		{
1275			read.fill_sealed(&index.entries(tree)?);
1276		}
1277		Ok(read)
1278	}
1279
1280	/// Records in the index which of the entries set are of secret files, with the sealed
1281	/// hashes of their content's secret blob keys, which the secrets tell while they are
1282	/// unlocked: what tells a purge of them while they are locked.
1283	fn note_secrets(
1284		&self,
1285		space: SpaceId,
1286		(tree, index): (EntityId, &Index),
1287		state: &TreeState,
1288		set: &[(String, Entry)],
1289	) -> Result<(), NodeError> {
1290		let versions = set.iter().filter_map(|(_, entry)| match entry.version {
1291			Version::File { content, .. } if state.is_secret(entry.entity) => {
1292				Some((entry.entity, content))
1293			}
1294			_ => None,
1295		});
1296		self.note_secret_versions(space, (tree, index), versions)
1297	}
1298
1299	/// Records in the index versions of secret files, as [`Library::note_secrets`] does.
1300	fn note_secret_versions(
1301		&self,
1302		space: SpaceId,
1303		(tree, index): (EntityId, &Index),
1304		versions: impl IntoIterator<Item = (EntityId, Hash)>,
1305	) -> Result<(), NodeError> {
1306		let log = self.space(space)?.stored.log();
1307		for (entity, content) in versions {
1308			let sealed: BTreeSet<Hash> = log
1309				.blob_keys(&content)
1310				.filter(|(sealed, _)| log.is_secret_blob(sealed))
1311				.map(|(sealed, _)| *sealed)
1312				.collect();
1313			index.note_secret(tree, (entity, content), &sealed)?;
1314		}
1315		Ok(())
1316	}
1317
1318	/// The paths that NibKeep wrote into a tree's folder for other reasons, which commits
1319	/// leave out: the copies of checkouts on this device, and those the index marks.
1320	fn left_out(
1321		&self,
1322		space: SpaceId,
1323		tree: EntityId,
1324		root: &Path,
1325		index: &Index,
1326	) -> Result<BTreeSet<String>, NodeError> {
1327		let mut left_out: BTreeSet<String> = index.marked(tree)?.into_keys().collect();
1328		for checkout in self.checkouts(space)? {
1329			if let Ok(relative) = checkout.path.strip_prefix(root)
1330				&& let Ok(path) = paths::tree_path_of(relative)
1331			{
1332				left_out.insert(path);
1333			}
1334		}
1335		Ok(left_out)
1336	}
1337
1338	/// The folders that a tree never takes in: the library's own, whatever its name.
1339	fn apart(&self) -> Vec<PathBuf> {
1340		self.library_directory()
1341			.and_then(|directory| fs::canonicalize(directory).ok())
1342			.map(super::files::plain)
1343			.into_iter()
1344			.collect()
1345	}
1346
1347	/// Whether the content that an entry of the index holds was purged. Of an ordinary file:
1348	/// no key of an ordinary blob opens it any more, and no value of the file, current or
1349	/// past, holds it. Of a secret file: a purge destroyed every secret blob key whose sealed
1350	/// hash its copy was written or committed with, which this replica tells with its secrets
1351	/// locked too; one whose sealed hashes it does not know, it cannot tell, and keeps.
1352	fn is_purged(
1353		&self,
1354		space: SpaceId,
1355		entry: &Entry,
1356		secret_versions: &SecretVersions,
1357	) -> Result<bool, NodeError> {
1358		let Version::File { content, .. } = entry.version else {
1359			return Ok(false);
1360		};
1361		let log = self.space(space)?.stored.log();
1362		if let Some(sealed) = secret_versions.get(&(entry.entity, content)) {
1363			if sealed.is_empty() {
1364				return Ok(false);
1365			}
1366			for sealed in sealed {
1367				if !nibkeep_log::History::is_blob_purged(log.history(), sealed)? {
1368					return Ok(false);
1369				}
1370			}
1371			return Ok(true);
1372		}
1373		let state = log.state();
1374		if secret_file_of(state, entry.entity)? != Secrecy::Ordinary {
1375			return Ok(false);
1376		}
1377		if log
1378			.blob_keys(&content)
1379			.any(|(sealed, _)| !log.is_secret_blob(sealed))
1380		{
1381			return Ok(false);
1382		}
1383		for entity in state.merged(state.canonical(entry.entity)?)? {
1384			for id in state.storage().of_field(entity, &CONTENT)? {
1385				if state
1386					.statement(id)?
1387					.is_some_and(|statement| statement.value == Value::Blob(content))
1388				{
1389					return Ok(false);
1390				}
1391			}
1392		}
1393		Ok(true)
1394	}
1395
1396	/// How many blobs of a space were purged, for telling whether a purge came since its
1397	/// trees' copies were last settled.
1398	fn purges_of(&self, space: SpaceId) -> Result<usize, NodeError> {
1399		let log = self.space(space)?.stored.log();
1400		Ok(nibkeep_log::History::purged_blobs(log.history())?.len())
1401	}
1402
1403	/// The contents that this replica learned were purged, having learned first, if a purge
1404	/// came since it last did, which of the contents of its trees' copies a purge took away.
1405	/// Purges name what they destroy by sealed hashes, so content is learned from the copies
1406	/// that held it, and from the purges made here.
1407	fn learn_purges(&self, space: SpaceId, index: &Index) -> Result<Purged, NodeError> {
1408		let purges = self.purges_of(space)?;
1409		let roots = self.roots_here(space)?;
1410		let mut secret_versions = SecretVersions::new();
1411		for tree in roots.keys() {
1412			secret_versions.extend(index.secret_versions(*tree)?);
1413		}
1414		if index.settled(space)? != Some(purges) {
1415			let mut learned = BTreeSet::new();
1416			let mut learned_secrets = BTreeSet::new();
1417			for tree in roots.keys() {
1418				for entry in index.entries(*tree)?.values() {
1419					if let Version::File { content, .. } = entry.version
1420						&& self.is_purged(space, entry, &secret_versions)?
1421					{
1422						if secret_versions.contains_key(&(entry.entity, content)) {
1423							learned_secrets.insert(content);
1424						} else {
1425							learned.insert(content);
1426						}
1427					}
1428				}
1429			}
1430			index.add_purged(&learned)?;
1431			index.add_purged_secrets(&learned_secrets)?;
1432			index.set_settled(space, purges)?;
1433		}
1434		Ok(Purged {
1435			ordinary: index.purged()?,
1436			secret: index.purged_secrets()?,
1437			secret_versions,
1438		})
1439	}
1440
1441	/// Records contents that a purge made here took away, of ordinary fields or of secret
1442	/// ones, so that no commit seals them again as such, wherever a copy of them is.
1443	pub(crate) fn note_purged(
1444		&self,
1445		space: SpaceId,
1446		(contents, secret): (&BTreeSet<Hash>, bool),
1447	) -> Result<(), NodeError> {
1448		if contents.is_empty() || self.roots_here(space)?.is_empty() {
1449			return Ok(());
1450		}
1451		let _locked = self.lock_trees()?;
1452		let index = self.index()?;
1453		if secret {
1454			index.add_purged_secrets(contents)
1455		} else {
1456			index.add_purged(contents)
1457		}
1458	}
1459
1460	/// The copies of trees' files on this device whose version, as the index says, is one
1461	/// of `contents`, of secret files if `secret` says so and else of ordinary ones, and which
1462	/// are there, each with whether it was edited since, as its hash tells: what a purge of
1463	/// the content deletes, and what it keeps. A purge of one kind leaves the other.
1464	pub(crate) fn tree_copies_holding(
1465		&self,
1466		space: SpaceId,
1467		contents: &BTreeSet<Hash>,
1468		secret: bool,
1469	) -> Result<Vec<(PathBuf, bool)>, NodeError> {
1470		let roots = self.roots_here(space)?;
1471		let mut holding = Vec::new();
1472		if roots.is_empty() || contents.is_empty() {
1473			return Ok(holding);
1474		}
1475		let index = self.index()?;
1476		for (tree, root) in roots {
1477			let secret_versions = index.secret_versions(tree)?;
1478			for (path, entry) in index.entries(tree)? {
1479				let Version::File { content, .. } = entry.version else {
1480					continue;
1481				};
1482				if !contents.contains(&content)
1483					|| secret_versions.contains_key(&(entry.entity, content)) != secret
1484				{
1485					continue;
1486				}
1487				let Located::Here(on_disk) = located(&root, &path, &self.apart()) else {
1488					continue;
1489				};
1490				if let Ok(at) = walk::look(&on_disk)
1491					&& at.kind == walk::FoundKind::File
1492				{
1493					let edited = walk::hash_found(&at).map_or(true, |found| found != content);
1494					holding.push((on_disk, edited));
1495				}
1496			}
1497		}
1498		holding.sort();
1499		Ok(holding)
1500	}
1501
1502	/// Settles the copies of a space's trees on this device after purges, made here or
1503	/// received, as [`settle_tree`] does each tree: only when a purge came since
1504	/// they were last settled, so that a sync that brings none costs nothing here, and only
1505	/// when no other program works on them, as a later status or commit settles them too.
1506	/// Returns the copies it deleted.
1507	pub(crate) fn settle_trees_in(&self, space: SpaceId) -> Result<Vec<PathBuf>, NodeError> {
1508		let roots = self.roots_here(space)?;
1509		if roots.is_empty() {
1510			return Ok(Vec::new());
1511		}
1512		let mut index = self.index()?;
1513		if index.settled(space)? == Some(self.purges_of(space)?) {
1514			return Ok(Vec::new());
1515		}
1516		let Some(_locked) = self.try_lock_trees()? else {
1517			return Ok(Vec::new());
1518		};
1519		let purged = self.learn_purges(space, &index)?;
1520		let apart = self.apart();
1521		let mut deleted = Vec::new();
1522		for (tree, root) in roots {
1523			if fs::symlink_metadata(&root).is_ok_and(|metadata| metadata.is_dir()) {
1524				let state = self.tree_state(space, tree)?;
1525				let settling = (&purged, &state);
1526				let place = (tree, root.as_path(), apart.as_slice());
1527				deleted.extend(settle_tree(place, &mut index, settling)?);
1528			}
1529		}
1530		Ok(deleted)
1531	}
1532
1533	/// The commits to a tree that were cut short: those with fewer parts here than their
1534	/// revisions say, after which the replica that made them made no other commit to the
1535	/// tree, which would have taken in the rest.
1536	fn cut_short(&self, space: SpaceId, tree: EntityId) -> Result<Vec<CutShort>, NodeError> {
1537		let open = self.space(space)?;
1538		let state = open.stored.log().state();
1539		// Each commit, by its revision: who made it, when, and how many parts it has.
1540		let mut commits = Vec::new();
1541		for revision in open.stored.find(&IN_TREE, &Value::Reference(tree))? {
1542			if !state.types(revision)?.contains(&REVISION) {
1543				continue;
1544			}
1545			let first = |field: &FieldName| -> Result<Option<Statement>, NodeError> {
1546				Ok(state
1547					.current(revision, field)?
1548					.into_iter()
1549					.min_by_key(|statement| statement.id)
1550					.map(std::borrow::Cow::into_owned))
1551			};
1552			let Some(in_tree) = first(&IN_TREE)? else {
1553				continue;
1554			};
1555			let parts = match first(&PARTS)?.map(|statement| statement.value) {
1556				Some(Value::Integer(parts)) => u64::try_from(parts).ok(),
1557				_ => None,
1558			};
1559			// By the full time of the change, which orders changes made in one millisecond
1560			// too.
1561			let made_at = state.recorded(in_tree.id)?;
1562			let made_by = open.stored.log().author_of(in_tree.id)?;
1563			commits.push((revision, made_by, made_at, parts));
1564		}
1565		// When each replica made its last commit: only a later commit of the same replica
1566		// takes in the rest, as another device's knows nothing of it.
1567		let mut last: Vec<(
1568			nibkeep_crypto::VerifyingKey,
1569			Option<nibkeep_time::Timestamp>,
1570		)> = Vec::new();
1571		for (_, made_by, made_at, _) in &commits {
1572			let Some(made_by) = made_by else {
1573				continue;
1574			};
1575			match last.iter_mut().find(|(by, _)| by == made_by) {
1576				Some((_, at)) => *at = (*at).max(*made_at),
1577				None => last.push((*made_by, *made_at)),
1578			}
1579		}
1580		let mut cut = Vec::new();
1581		for (revision, made_by, made_at, parts) in commits {
1582			let Some(parts) = parts else {
1583				continue;
1584			};
1585			let later = made_by
1586				.is_some_and(|made_by| last.iter().any(|(by, at)| *by == made_by && *at > made_at));
1587			if later {
1588				continue;
1589			}
1590			let here = history::parts_here(state, revision)?.len() + 1;
1591			let made = u64::try_from(here).unwrap_or(u64::MAX);
1592			if made < parts {
1593				cut.push(CutShort {
1594					revision,
1595					parts,
1596					made,
1597				});
1598			}
1599		}
1600		Ok(cut)
1601	}
1602}
1603
1604/// Settles the copy of a tree after purges: deletes the copies whose version holds
1605/// content in `purged`, where they are as they were written or committed, as their
1606/// hashes tell, and takes that content out of the index, so that it no longer says what
1607/// a purged file was; the content stays in the index's list of what was purged, so that
1608/// no commit seals it again. An edited copy stays. A copy that cannot be reached, read or
1609/// deleted keeps its entry, and is settled later. The caller holds the lock of the
1610/// trees. Returns the copies deleted.
1611fn settle_tree(
1612	(tree, root, apart): (EntityId, &Path, &[PathBuf]),
1613	index: &mut Index,
1614	(purged, state): (&Purged, &TreeState),
1615) -> Result<Vec<PathBuf>, NodeError> {
1616	let mut deleted = Vec::new();
1617	let mut removed = Vec::new();
1618	if purged.is_empty() {
1619		return Ok(deleted);
1620	}
1621	let entries = index.entries(tree)?;
1622	// The copies to settle: those whose entries hold purged content, of their kind, and
1623	// those at the tree's paths whose content is gone, which have none, as when their
1624	// entries went while their drive was away; these are deleted only if they hold purged
1625	// content of their file's kind.
1626	let mut holding: Vec<(String, Option<Hash>, bool)> = entries
1627		.iter()
1628		.filter_map(|(path, entry)| match entry.version {
1629			Version::File { content, .. } if purged.holds(entry) => {
1630				Some((path.clone(), Some(content), purged.is_secret(entry)))
1631			}
1632			_ => None,
1633		})
1634		.collect();
1635	holding.extend(
1636		state
1637			.by_path
1638			.iter()
1639			.filter(|(path, current)| current.version.is_none() && !entries.contains_key(*path))
1640			.map(|(path, current)| (path.clone(), None, state.is_secret(current.entity))),
1641	);
1642	for (path, content, secret) in holding {
1643		let on_disk = match located(root, &path, apart) {
1644			Located::Here(on_disk) => on_disk,
1645			Located::Absent => {
1646				removed.push(path);
1647				continue;
1648			}
1649			Located::Unknown(_) => continue,
1650		};
1651		let Ok(at) = walk::look(&on_disk) else {
1652			continue;
1653		};
1654		if at.kind != walk::FoundKind::File {
1655			// Not the purged content: a link, the person's own.
1656			removed.push(path);
1657			continue;
1658		}
1659		match walk::hash_found(&at) {
1660			Ok(found)
1661				if content.map_or(purged.contains(&found, secret), |content| found == content) =>
1662			{
1663				// Deleted only if it is still the file that was read, as a save made
1664				// meanwhile puts another in its place.
1665				let unchanged = walk::look(&on_disk).is_ok_and(|now| {
1666					now.identity == at.identity
1667						&& now.size == at.size
1668						&& now.modified == at.modified
1669				});
1670				if unchanged && fs::remove_file(&on_disk).is_ok() {
1671					super::checkouts::sync_folder_of(&on_disk);
1672					deleted.push(on_disk);
1673					removed.push(path);
1674				}
1675			}
1676			Ok(_) => removed.push(path),
1677			Err(_) => {}
1678		}
1679	}
1680	index.change(tree, &removed, &[])?;
1681	Ok(deleted)
1682}
1683
1684/// Saves the entries of the folders that a move took a copy from and put it into, before
1685/// what records the move, which a power cut must not keep without them.
1686fn save_move(source: &Path, target: &Path) {
1687	super::checkouts::sync_folder_of(source);
1688	super::checkouts::sync_folder_of(target);
1689}
1690
1691impl Library {
1692	/// Puts the index in line with what an update, a revert or a commit did to the copy of a
1693	/// tree before something cut it short, as a crash, which it had not recorded yet, so that
1694	/// nothing it did looks like a change made here: the copies that moves left aside go
1695	/// back to their paths, where those are free; a copy that holds the version of a secret
1696	/// file that an update noted it was about to write is recorded as written, which with
1697	/// the secrets locked nothing else tells; a file whose version or path this replica's own
1698	/// commit set last, which the index has otherwise, takes the tree's, and its copy is read
1699	/// again; and an entry whose copy is gone from its path, of a file or link that the tree
1700	/// has at another path, where the copy holds the entry's version and the index has
1701	/// nothing, goes there, as the move it was. Otherwise a copy could look deleted at one
1702	/// path and new at the other, which a commit would record as another file, or edited
1703	/// from a version older than the tree's, which a commit would refuse. The caller holds
1704	/// the lock of the trees.
1705	fn follow_cut_short(
1706		&self,
1707		space: SpaceId,
1708		(tree, root, apart): (EntityId, &Path, &[PathBuf]),
1709		index: &mut Index,
1710		state: &TreeState,
1711	) -> Result<(), NodeError> {
1712		let entries = index.entries(tree)?;
1713		write::bring_back_aside(write::Place { root, apart }, entries.keys());
1714		// Before anything is read: a copy changed after this is read again.
1715		let read_at = walk::nanos(std::time::SystemTime::now()).unwrap_or(0);
1716		let listings = Listings::apart(apart);
1717		let at = |path: &str| located_in(&listings, root, path);
1718		let gone = |path: &str| at(path) == Located::Absent;
1719		let holding = |path: &str, (entity, version): (EntityId, &Version)| {
1720			let Located::Here(on_disk) = at(path) else {
1721				return None;
1722			};
1723			let found = walk::look(&on_disk).ok()?;
1724			let holds = write::copy_version(&found)?;
1725			write::same_version(&found, &holds, version).then(|| Entry {
1726				entity,
1727				version: version.clone(),
1728				size: found.size,
1729				modified: found.modified,
1730				read_at,
1731			})
1732		};
1733		let mut removed: Vec<String> = Vec::new();
1734		let mut set: BTreeMap<String, Entry> = BTreeMap::new();
1735		let writing = index.writing(tree)?;
1736		for (path, entity, version) in &writing {
1737			let recorded = entries
1738				.get(path)
1739				.is_some_and(|entry| entry.entity == *entity && entry.version == *version);
1740			if recorded {
1741				continue;
1742			}
1743			let Some(written) = holding(path, (*entity, version)) else {
1744				continue;
1745			};
1746			// The entry at a path that the file moved from, whose copy went.
1747			removed.extend(
1748				entries
1749					.iter()
1750					.filter(|(from, entry)| entry.entity == *entity && *from != path && gone(from))
1751					.map(|(from, _)| from.clone()),
1752			);
1753			set.insert(path.clone(), written);
1754		}
1755		// What a commit of this replica's made of a copy that changed since its entry: only
1756		// such a copy can hold what the commit recorded.
1757		let changed = |path: &str, entry: Option<&Entry>| match (at(path), entry) {
1758			(Located::Here(on_disk), Some(entry)) => {
1759				walk::look(&on_disk).is_ok_and(|found| !entry.untouched(found.size, found.modified))
1760			}
1761			(Located::Here(_), None) => index.knows(tree).unwrap_or(false),
1762			(Located::Absent, Some(_)) => true,
1763			_ => false,
1764		};
1765		for (path, entity, version) in self.committed_here(space, &entries, state, &changed)? {
1766			let from = entries
1767				.iter()
1768				.find(|(_, entry)| entry.entity == entity)
1769				.map(|(from, _)| from.clone());
1770			let moved = from.as_ref().filter(|from| **from != path);
1771			if set.contains_key(&path)
1772				|| moved.is_some_and(|from| !gone(from) || entries.contains_key(&path))
1773			{
1774				continue;
1775			}
1776			removed.extend(moved.cloned());
1777			// Read again, as what the copy holds now the index cannot tell.
1778			let entry = Entry {
1779				entity,
1780				version,
1781				size: 0,
1782				modified: None,
1783				read_at,
1784			};
1785			set.insert(path, entry);
1786		}
1787		for (path, entry) in &entries {
1788			let Some(now_at) = state.by_entity.get(&entry.entity) else {
1789				continue;
1790			};
1791			if now_at == path
1792				|| entries.contains_key(now_at)
1793				|| set.contains_key(now_at)
1794				|| removed.contains(path)
1795				|| !gone(path)
1796			{
1797				continue;
1798			}
1799			let Some(moved) = holding(now_at, (entry.entity, &entry.version)) else {
1800				continue;
1801			};
1802			removed.push(path.clone());
1803			set.insert(now_at.clone(), moved);
1804		}
1805		let set: Vec<(String, Entry)> = set.into_iter().collect();
1806		index.change(tree, &removed, &set)?;
1807		// Which of them are secret files, as the update or the commit would have noted.
1808		self.note_secrets(space, (tree, index), state, &set)?;
1809		if !writing.is_empty() {
1810			index.forget_writing(tree)?;
1811		}
1812		Ok(())
1813	}
1814
1815	/// The files and links of a tree whose version or path the index has otherwise than the
1816	/// tree, or not at all, where the copy `changed` since its entry, of which a part of this
1817	/// replica's own commit set the version and path last, rather than any other change: each
1818	/// with its path and version in the tree. Files whose versions or paths compete are left
1819	/// out.
1820	fn committed_here(
1821		&self,
1822		space: SpaceId,
1823		entries: &BTreeMap<String, Entry>,
1824		state: &TreeState,
1825		changed: &dyn Fn(&str, Option<&Entry>) -> bool,
1826	) -> Result<Vec<(String, EntityId, Version)>, NodeError> {
1827		let indexed: BTreeMap<EntityId, (&String, &Entry)> = entries
1828			.iter()
1829			.map(|(path, entry)| (entry.entity, (path, entry)))
1830			.collect();
1831		let differing: Vec<(String, EntityId, Version)> = state
1832			.by_entity
1833			.iter()
1834			.filter(|(entity, path)| {
1835				!state.competing.contains(*path)
1836					&& !state.paths.contains_key(*entity)
1837					&& state
1838						.versions
1839						.get(*entity)
1840						.is_none_or(|versions| versions.len() < 2)
1841			})
1842			.filter_map(|(entity, path)| {
1843				let version = state.own.get(entity).cloned().flatten()?;
1844				let differs = match indexed.get(entity) {
1845					Some((at, entry)) => {
1846						(*at != path || entry.version != version) && changed(at, Some(entry))
1847					}
1848					None => changed(path, None),
1849				};
1850				differs.then(|| (path.clone(), *entity, version))
1851			})
1852			.collect();
1853		if differing.is_empty() {
1854			return Ok(differing);
1855		}
1856		let open = self.space(space)?;
1857		let log = open.stored.log();
1858		let state_now = log.state();
1859		let me = self.replica.signing.verifying_key();
1860		let change_of = |id| -> Result<Option<Hash>, NodeError> {
1861			Ok(state_now
1862				.storage()
1863				.get(id)?
1864				.and_then(|recorded| recorded.change))
1865		};
1866		let fields = [
1867			&TREE_PATH,
1868			&CONTENT,
1869			&SECRET_CONTENT,
1870			&LINK_TARGET,
1871			&EXECUTABLE,
1872		];
1873		let mut own = Vec::new();
1874		for (path, entity, version) in differing {
1875			// The newest of what makes its path and version, which a part of a commit made
1876			// with the commit's revision: not another change of this replica's.
1877			let mut last = None;
1878			for field in fields {
1879				for statement in state_now.current(entity, field)? {
1880					let at = state_now.recorded(statement.id)?;
1881					if last.as_ref().is_none_or(|(when, _)| at > *when) {
1882						last = Some((at, statement.id));
1883					}
1884				}
1885			}
1886			let Some((_, newest)) = last else {
1887				continue;
1888			};
1889			let change = change_of(newest)?;
1890			let mut in_commit = false;
1891			for part in state_now.current(entity, &COMMITTED_IN)? {
1892				in_commit |= change.is_some() && change_of(part.id)? == change;
1893			}
1894			if in_commit && log.author_of(newest)? == Some(me) {
1895				own.push((path, entity, version));
1896			}
1897		}
1898		Ok(own)
1899	}
1900}
1901
1902/// What this replica learned was purged of the contents of its trees' copies: of ordinary
1903/// files and of secret files apart, as a purge of one kind leaves the same content in the
1904/// other ([technical design: secret files]).
1905///
1906/// [technical design: secret files]: ../../../../docs/Technical-design.md#95-secret-files
1907#[derive(Debug, Default)]
1908struct Purged {
1909	ordinary: BTreeSet<Hash>,
1910	secret: BTreeSet<Hash>,
1911	/// The versions of secret files that this replica's copies were written or committed at,
1912	/// which tell an entry of a secret file from one of an ordinary file.
1913	secret_versions: SecretVersions,
1914}
1915
1916impl Purged {
1917	/// Whether nothing was purged.
1918	fn is_empty(&self) -> bool {
1919		self.ordinary.is_empty() && self.secret.is_empty()
1920	}
1921
1922	/// Whether content was purged from fields of the kind given, secret or ordinary.
1923	fn contains(&self, content: &Hash, secret: bool) -> bool {
1924		if secret {
1925			self.secret.contains(content)
1926		} else {
1927			self.ordinary.contains(content)
1928		}
1929	}
1930
1931	/// Whether an entry of the index is of a secret file's version.
1932	fn is_secret(&self, entry: &Entry) -> bool {
1933		matches!(entry.version, Version::File { content, .. }
1934			if self.secret_versions.contains_key(&(entry.entity, content)))
1935	}
1936
1937	/// Whether the version that an entry of the index holds was purged.
1938	fn holds(&self, entry: &Entry) -> bool {
1939		match entry.version {
1940			Version::File { content, .. } => self.contains(&content, self.is_secret(entry)),
1941			Version::Link { .. } => false,
1942		}
1943	}
1944}
1945
1946/// The path and version of an entity in a state, if the state holds it at a path; of a file
1947/// that competes for its path with another, the version is the path's.
1948fn version_of(state: &TreeState, entity: EntityId) -> Option<(String, Option<Version>)> {
1949	let path = state.by_entity.get(&entity)?;
1950	Some((path.clone(), state.own.get(&entity).cloned().flatten()))
1951}
1952
1953/// The entities that are in a tree, deleted ones too, as the state the space has now
1954/// says: every state of the tree is read for them, as an entity never leaves its tree.
1955fn tree_entities<S: nibkeep_model::storage::Statements>(
1956	state: &nibkeep_model::State<S>,
1957	tree: EntityId,
1958) -> Result<Vec<EntityId>, NodeError>
1959where
1960	NodeError: From<S::Error>,
1961{
1962	let tree = state.canonical(tree)?;
1963	let mut entities = BTreeSet::new();
1964	// The value index leaves deleted entities out, so the statements that refer to the tree
1965	// are read instead, current or past.
1966	for id in state.storage().referring_to(tree)? {
1967		if let Some(recorded) = state.storage().get(id)?
1968			&& recorded.statement.field == IN_TREE
1969		{
1970			entities.insert(state.canonical(recorded.statement.entity)?);
1971		}
1972	}
1973	Ok(entities.into_iter().collect())
1974}
1975
1976/// What the log tells of its changes, for telling a deletion that saw a version from one that
1977/// did not: the changes that each change builds on, found once for each, and whether a purge
1978/// took a change away.
1979pub(super) struct Changes<'a> {
1980	log: &'a Log<StateFile, LogFile>,
1981	built_on: RefCell<BTreeMap<Hash, BTreeSet<Hash>>>,
1982}
1983
1984impl<'a> Changes<'a> {
1985	/// What `log` tells of its changes.
1986	pub(super) fn of(log: &'a Log<StateFile, LogFile>) -> Self {
1987		Self {
1988			log,
1989			built_on: RefCell::default(),
1990		}
1991	}
1992
1993	/// Whether the change whose hash is `later` is the one whose hash is `earlier`, or
1994	/// builds on it.
1995	fn saw(&self, earlier: Hash, later: Hash) -> Result<bool, NodeError> {
1996		if earlier == later {
1997			return Ok(true);
1998		}
1999		if let Some(built_on) = self.built_on.borrow().get(&later) {
2000			return Ok(built_on.contains(&earlier));
2001		}
2002		let mut built_on = BTreeSet::new();
2003		let mut waiting = vec![ChangeId::from_hash(later)];
2004		while let Some(id) = waiting.pop() {
2005			let Some(change) = self.log.change(id)? else {
2006				continue;
2007			};
2008			for parent in change.parents() {
2009				if built_on.insert(*parent.hash()) {
2010					waiting.push(*parent);
2011				}
2012			}
2013		}
2014		let saw = built_on.contains(&earlier);
2015		self.built_on.borrow_mut().insert(later, built_on);
2016		Ok(saw)
2017	}
2018
2019	/// Whether a purge took away the change whose hash is `change`, stating again what of it
2020	/// stays.
2021	fn purged(&self, change: Hash) -> Result<bool, NodeError> {
2022		let status = nibkeep_log::History::status(self.log.history(), ChangeId::from_hash(change))?;
2023		Ok(status == Some(nibkeep_log::Status::Ignored))
2024	}
2025}
2026
2027/// The files and links among `entities`, as `state` says, as [`Library::tree_state`] reads
2028/// them; and the deleted ones, by their last paths. With `changes`, a file deleted while
2029/// another device gave it a new version, moved it or changed its executable bit, before
2030/// either saw the other, stays among the competing. Without `readable`, a secret file whose content shows not is sealed, rather
2031/// than purged.
2032fn read_tree_state<S: nibkeep_model::storage::Statements>(
2033	state: &nibkeep_model::State<S>,
2034	tree: EntityId,
2035	entities: &[EntityId],
2036	(changes, readable): (Option<&Changes<'_>>, bool),
2037) -> Result<TreeState, NodeError>
2038where
2039	NodeError: From<S::Error>,
2040{
2041	let tree = state.canonical(tree)?;
2042	let mut read = TreeState::default();
2043	// Of the deleted at each path, the one deleted last, with when.
2044	let mut deleted_at: BTreeMap<String, nibkeep_time::Timestamp> = BTreeMap::new();
2045	for &entity in entities {
2046		let Some((is_link, is_secret)) = kind_in_tree(state, entity, tree)? else {
2047			continue;
2048		};
2049		let values = |field: &FieldName| -> Result<Vec<Value>, NodeError> {
2050			let mut statements = state.current(entity, field)?;
2051			statements.sort_by_key(|statement| statement.id);
2052			Ok(statements
2053				.into_iter()
2054				.map(|statement| statement.value.clone())
2055				.collect())
2056		};
2057		let texts = |field: &FieldName| -> Result<Vec<String>, NodeError> {
2058			Ok(values(field)?
2059				.into_iter()
2060				.filter_map(|value| match value {
2061					Value::Text(text) => Some(text),
2062					_ => None,
2063				})
2064				.collect())
2065		};
2066		let paths = distinct(texts(&TREE_PATH)?);
2067		if is_secret {
2068			read.secret.insert(entity);
2069			read.secret_paths.extend(all_paths(state, entity)?);
2070		}
2071		let Some(path) = paths.first().cloned() else {
2072			continue;
2073		};
2074		if !is_safe_tree_path(&path) {
2075			continue;
2076		}
2077		let all: Vec<Version> = if is_link {
2078			texts(&LINK_TARGET)?
2079				.into_iter()
2080				.map(|target| Version::Link { target })
2081				.collect()
2082		} else {
2083			let executable = values(&EXECUTABLE)?.contains(&Value::Boolean(true));
2084			let field = if is_secret { &SECRET_CONTENT } else { &CONTENT };
2085			values(field)?
2086				.into_iter()
2087				.filter_map(|value| match value {
2088					Value::Blob(content) => Some(Version::File {
2089						content,
2090						executable,
2091					}),
2092					_ => None,
2093				})
2094				.collect()
2095		};
2096		let all = distinct(all);
2097		let competing = all.len() > 1;
2098		let version = all.first().cloned();
2099		let deleted = state.is_deleted(entity)?;
2100		if is_secret && version.is_none() && !deleted && !readable {
2101			// Sealed, not purged: which version the tree holds, the secrets alone tell.
2102			read.sealed.insert(path, entity);
2103			continue;
2104		}
2105		let unseen = match changes {
2106			// A file whose content was purged has no version to keep.
2107			Some(changes) if deleted && version.is_some() => {
2108				unseen_deletions(state, entity, changes)?
2109			}
2110			_ => None,
2111		};
2112		if let Some(deletions) = unseen {
2113			read.contested.insert(entity, deletions);
2114			read.competing.insert(path.clone());
2115		} else if deleted {
2116			note_deleted(
2117				state,
2118				(&mut read, &mut deleted_at),
2119				path,
2120				Current { entity, version },
2121			)?;
2122			continue;
2123		}
2124		// The paths of a file whose paths compete are all competing, its own among them.
2125		if competing {
2126			read.competing.insert(path.clone());
2127			read.versions.insert(entity, all);
2128		}
2129		read.own.insert(entity, version.clone());
2130		if paths.len() > 1 {
2131			read.competing.extend(paths.iter().cloned());
2132			read.paths.insert(entity, paths.clone());
2133		}
2134		if read.by_path.contains_key(&path) {
2135			read.competing.insert(path.clone());
2136		} else {
2137			read.by_path
2138				.insert(path.clone(), Current { entity, version });
2139		}
2140		read.by_entity.insert(entity, path);
2141	}
2142	Ok(read)
2143}
2144
2145/// The values, each once, in their order: one value stated twice, as by two devices that
2146/// settled one competition apart, is one value, not two that compete.
2147fn distinct<T: PartialEq>(values: Vec<T>) -> Vec<T> {
2148	let mut kept = Vec::new();
2149	for value in values {
2150		if !kept.contains(&value) {
2151			kept.push(value);
2152		}
2153	}
2154	kept
2155}
2156
2157/// Notes a deleted file or link at its last path, unless one deleted later was there.
2158fn note_deleted<S: nibkeep_model::storage::Statements>(
2159	state: &nibkeep_model::State<S>,
2160	(read, deleted_at): (
2161		&mut TreeState,
2162		&mut BTreeMap<String, nibkeep_time::Timestamp>,
2163	),
2164	path: String,
2165	deleted: Current,
2166) -> Result<(), NodeError>
2167where
2168	NodeError: From<S::Error>,
2169{
2170	let when = state
2171		.current(deleted.entity, &fields::DELETED)?
2172		.iter()
2173		.filter_map(|statement| state.recorded(statement.id).ok().flatten())
2174		.max();
2175	let later = match (when, deleted_at.get(&path)) {
2176		(Some(when), Some(known)) => when > *known,
2177		(Some(_) | None, None) => true,
2178		(None, Some(_)) => false,
2179	};
2180	if later {
2181		if let Some(when) = when {
2182			deleted_at.insert(path.clone(), when);
2183		}
2184		read.deleted.insert(path, deleted);
2185	}
2186	Ok(())
2187}
2188
2189/// The keys of the deletions of a deleted file or link, if it has a version, a path or an
2190/// executable bit that none of them saw: one recorded by a change that no change that deleted
2191/// it builds on, as when one device deleted it while another gave it a new version, moved it
2192/// or took its bit away, before either saw the other. A version that a purge stated again
2193/// counts as seen, whichever change it came in.
2194fn unseen_deletions<S: nibkeep_model::storage::Statements>(
2195	state: &nibkeep_model::State<S>,
2196	entity: EntityId,
2197	changes: &Changes<'_>,
2198) -> Result<Option<Vec<String>>, NodeError>
2199where
2200	NodeError: From<S::Error>,
2201{
2202	let mut deletions = Vec::new();
2203	for statement in state.current(entity, &fields::DELETED)? {
2204		if statement.value != Value::Boolean(true) {
2205			continue;
2206		}
2207		// A deletion that came in no change saw everything.
2208		let Some(change) = state
2209			.storage()
2210			.get(statement.id)?
2211			.and_then(|recorded| recorded.change)
2212		else {
2213			return Ok(None);
2214		};
2215		deletions.push((deletion_key(statement.id), change));
2216	}
2217	if deletions.is_empty() {
2218		return Ok(None);
2219	}
2220	for field in [
2221		&CONTENT,
2222		&SECRET_CONTENT,
2223		&LINK_TARGET,
2224		&EXECUTABLE,
2225		&TREE_PATH,
2226	] {
2227		for statement in state.current(entity, field)? {
2228			let Some(recorded) = state.storage().get(statement.id)? else {
2229				continue;
2230			};
2231			let (Some(change), None) = (recorded.change, recorded.restated) else {
2232				continue;
2233			};
2234			if changes.purged(change)? {
2235				continue;
2236			}
2237			let mut seen = false;
2238			for (_, deletion) in &deletions {
2239				if changes.saw(change, *deletion)? {
2240					seen = true;
2241					break;
2242				}
2243			}
2244			if !seen {
2245				return Ok(Some(deletions.into_iter().map(|(key, _)| key).collect()));
2246			}
2247		}
2248	}
2249	Ok(None)
2250}
2251
2252/// What an entity is in a tree, if it is a file or a link of it: whether it is a link, and
2253/// whether it is a secret file. A secret file is the tree's whose commit made it, for good,
2254/// whatever changes said later of its tree or its types, as any replica may say them; an
2255/// entity once in the tree whose tree is another now is the other's.
2256fn kind_in_tree<S: nibkeep_model::storage::Statements>(
2257	state: &nibkeep_model::State<S>,
2258	entity: EntityId,
2259	tree: EntityId,
2260) -> Result<Option<(bool, bool)>, NodeError>
2261where
2262	NodeError: From<S::Error>,
2263{
2264	match secret_file_of(state, entity)? {
2265		Secrecy::Of(of) if of == tree => return Ok(Some((false, true))),
2266		Secrecy::Of(_) | Secrecy::OfNone => return Ok(None),
2267		Secrecy::Ordinary => {}
2268	}
2269	let mut in_tree = false;
2270	for statement in state.current(entity, &IN_TREE)? {
2271		if let Value::Reference(of) = statement.value {
2272			in_tree |= state.canonical(of)? == tree;
2273		}
2274	}
2275	if !in_tree {
2276		return Ok(None);
2277	}
2278	let types = state.types(entity)?;
2279	let is_link = types.contains(&SYMBOLIC_LINK);
2280	Ok((is_link || types.contains(&FILE)).then_some((is_link, false)))
2281}
2282
2283/// The earliest of some statements of an entity, by time and then ID, with its value and
2284/// the change it came in.
2285type Earliest = Option<(
2286	(Option<nibkeep_time::Timestamp>, nibkeep_base::StatementId),
2287	Value,
2288	Option<Hash>,
2289)>;
2290
2291/// Whether an entity is a secret file, and of which tree.
2292#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2293enum Secrecy {
2294	/// It never was a secret file.
2295	Ordinary,
2296	/// A secret file of the tree whose commit made it.
2297	Of(EntityId),
2298	/// A secret file that no commit of a tree made, as a password record's, which a
2299	/// change took into a tree later: never a tree's.
2300	OfNone,
2301}
2302
2303/// Whether an entity is a secret file, as its history says: one that any statement, current
2304/// or past, gave the type of secret files is one for good. It is the tree's that the first
2305/// statement of its tree names, if the change that made the entity stated it too, as a
2306/// commit does; else no tree's. So a file of a tree that a change made secret later stays
2307/// in its tree, and is never sealed as ordinary again.
2308fn secret_file_of<S: nibkeep_model::storage::Statements>(
2309	state: &nibkeep_model::State<S>,
2310	entity: EntityId,
2311) -> Result<Secrecy, NodeError>
2312where
2313	NodeError: From<S::Error>,
2314{
2315	let storage = state.storage();
2316	// The earliest of some statements of the entity, with the change it came in.
2317	let earliest = |field: &FieldName,
2318	                keep: &dyn Fn(&Value) -> bool|
2319	 -> Result<Option<(Value, Option<Hash>)>, NodeError> {
2320		let mut first: Earliest = None;
2321		for id in storage.of_field(entity, field)? {
2322			let Some(recorded) = storage.get(id)? else {
2323				continue;
2324			};
2325			if !keep(&recorded.statement.value) {
2326				continue;
2327			}
2328			let at = (state.recorded(id)?, id);
2329			if first.as_ref().is_none_or(|(known, _, _)| at < *known) {
2330				first = Some((at, recorded.statement.value.clone(), recorded.change));
2331			}
2332		}
2333		Ok(first.map(|(_, value, change)| (value, change)))
2334	};
2335	let secret_type = SECRET_FILE;
2336	if earliest(&fields::TYPE, &|value| {
2337		value.as_text() == Some(secret_type.as_str())
2338	})?
2339	.is_none()
2340	{
2341		return Ok(Secrecy::Ordinary);
2342	}
2343	// The change that made the entity, which gave it its first type.
2344	let Some((_, made_in)) = earliest(&fields::TYPE, &|_| true)? else {
2345		return Ok(Secrecy::OfNone);
2346	};
2347	match earliest(&IN_TREE, &|value| matches!(value, Value::Reference(_)))? {
2348		Some((Value::Reference(tree), Some(change))) if made_in == Some(change) => {
2349			Ok(Secrecy::Of(state.canonical(tree)?))
2350		}
2351		_ => Ok(Secrecy::OfNone),
2352	}
2353}
2354
2355/// Every path that a file of a tree had, current or past.
2356fn all_paths<S: nibkeep_model::storage::Statements>(
2357	state: &nibkeep_model::State<S>,
2358	entity: EntityId,
2359) -> Result<Vec<String>, NodeError>
2360where
2361	NodeError: From<S::Error>,
2362{
2363	let storage = state.storage();
2364	let mut paths = Vec::new();
2365	for id in storage.of_field(entity, &TREE_PATH)? {
2366		if let Some(recorded) = storage.get(id)?
2367			&& let Value::Text(path) = &recorded.statement.value
2368		{
2369			paths.push(path.clone());
2370		}
2371	}
2372	Ok(paths)
2373}
2374
2375/// The key of a deletion of a file among its competing values, as written out: no version's
2376/// key is one.
2377fn deletion_key(statement: nibkeep_base::StatementId) -> String {
2378	format!("deleted {statement}")
2379}
2380
2381/// The path in the tree at `root` of what is at `path`, a full path, whether or not it is
2382/// there: its folder as the file system resolves the part of it that is there, and the rest
2383/// as written, relative to the root; empty for the root itself.
2384///
2385/// # Errors
2386///
2387/// Returns [`NodeError::NotInTree`] if the path is not in the tree's folder, and
2388/// [`NodeError::UnsafePath`] if it is no path a tree may hold.
2389pub fn tree_path_at(root: &Path, path: &Path) -> Result<String, NodeError> {
2390	let shown = || path.display().to_string();
2391	// A link is named as itself, never as what it points to: its folder is resolved, and
2392	// its own name kept.
2393	let mut existing = path;
2394	let mut rest = Vec::new();
2395	if let (Some(std::path::Component::Normal(name)), Some(parent)) =
2396		(path.components().next_back(), path.parent())
2397	{
2398		rest.push(name);
2399		existing = parent;
2400	}
2401	let resolved = loop {
2402		if let Some(resolved) = resolved(existing) {
2403			break resolved;
2404		}
2405		rest.push(
2406			existing
2407				.file_name()
2408				.ok_or_else(|| NodeError::NotInTree(shown()))?,
2409		);
2410		existing = existing
2411			.parent()
2412			.ok_or_else(|| NodeError::NotInTree(shown()))?;
2413	};
2414	let mut full = resolved;
2415	full.extend(rest.iter().rev());
2416	let relative = full
2417		.strip_prefix(root)
2418		.map_err(|_| NodeError::NotInTree(shown()))?;
2419	if relative.as_os_str().is_empty() {
2420		return Ok(String::new());
2421	}
2422	paths::tree_path_of(relative).map_err(|_| NodeError::UnsafePath(shown()))
2423}
2424
2425/// A folder as the file system resolves it, without Windows' prefix of long paths.
2426fn resolved(folder: &Path) -> Option<PathBuf> {
2427	fs::canonicalize(folder).ok().map(super::files::plain)
2428}