Skip to main content

nibkeep_node/library/trees/
update.rs

1//! Updating a tree's copy: bringing it to the tree as other devices left it, with new
2//! versions, moves, additions and deletions written, and competing values written out:
3//! text merged three ways, from the version both started from, with Git's conflict markers
4//! where edits clash, and anything else left as it is, with the other version beside it as
5//! `NAME.conflict-DEVICE`. An edited copy never loses its edits, nor are changes made here
6//! and not committed undone ([technical design: trees]).
7//!
8//! [technical design: trees]: ../../../../../docs/Technical-design.md#15-trees
9
10use std::collections::{BTreeMap, BTreeSet};
11use std::fs;
12use std::io;
13use std::path::Path;
14use std::time::SystemTime;
15
16use nibkeep_base::{EntityId, SpaceId, StatementId};
17use nibkeep_log::ChangeId;
18use nibkeep_model::storage::Statements as _;
19use nibkeep_model::{Operation, Value};
20use nibkeep_std::{CONTENT, LINK_TARGET, SECRET_CONTENT};
21
22use super::compare::{same_content, still_competes};
23use super::history::READ_LIMIT;
24use super::index::{Conflict, Entry, Index, Version};
25use super::locate::{Located, located};
26use super::secrecy::{NIBSECRET, lines};
27use super::walk::{Found, FoundKind, look, nanos, open_found};
28use super::write::{Content, Place, copy_version, same_version, undo_moves_at};
29use super::{CutShort, TreeState, settle_tree, version_of};
30use crate::NodeError;
31use crate::library::Library;
32use crate::library::checkouts::sync_folder_of;
33
34/// What updating a tree's copy did.
35#[derive(Clone, Debug, Default, PartialEq, Eq)]
36pub struct Updated {
37	/// The paths written: new versions, and files added elsewhere.
38	pub written: Vec<String>,
39	/// The copies moved, from where to where.
40	pub moved: Vec<(String, String)>,
41	/// The copies deleted, of files deleted elsewhere.
42	pub deleted: Vec<String>,
43	/// The copies edited here, or whose versions competed, merged cleanly: what a commit
44	/// records next.
45	pub merged: Vec<String>,
46	/// The paths where versions clash: text with Git's conflict markers, or another file with
47	/// the other version beside it, as `NAME.conflict-DEVICE`.
48	pub conflicts: Vec<String>,
49	/// The copies kept as they are, with why, such as one edited here of a file deleted
50	/// elsewhere.
51	pub kept: Vec<(String, String)>,
52	/// The files deleted on one device while another gave them a new version, before either
53	/// saw the other, whose copies hold that version now: a commit keeps them, unless they
54	/// are deleted first.
55	pub contested: Vec<String>,
56	/// The paths not written, with why.
57	pub skipped: Vec<(String, String)>,
58	/// The commits of other devices whose parts have not all arrived, which are left out
59	/// until they have.
60	pub waiting: Vec<CutShort>,
61	/// What changed elsewhere that waits for the person to agree before it is written: moves
62	/// of secret files, as `FROM -> TO`, which could put a plain copy where something
63	/// publishes it, and `.nibsecret` files that lose lines, by path, which could make new
64	/// files ordinary ([technical design: secrets in trees]).
65	///
66	/// [technical design: secrets in trees]: ../../../docs/Technical-design.md#151-secrets-in-trees
67	pub held: Vec<String>,
68	/// The secret files not written, as this replica cannot read them: its secrets are
69	/// locked, or not on this device.
70	pub sealed: Vec<String>,
71}
72
73/// A version to write at a path where a copy may be.
74#[derive(Clone)]
75struct Arriving {
76	path: String,
77	entity: EntityId,
78	/// The version the copy was written or committed at, if this copy had the file.
79	base: Option<Version>,
80	/// The version to write.
81	version: Version,
82	/// All the versions of the file, of one that competes with itself, this one among them.
83	competing: Vec<Version>,
84	/// The competing versions that an update wrote out into the copy already, by their
85	/// [`Version::key`].
86	written: BTreeSet<String>,
87	/// The keys of the deletions that compete with this version, where one device deleted
88	/// the file while another gave it the version, before either saw the other.
89	deletions: Vec<String>,
90	/// Whether it is a secret file's.
91	secret: bool,
92}
93
94impl Arriving {
95	/// Whether nothing came that the copy lacks: no newer version, and no competing one
96	/// that was not written out into it.
97	fn nothing_new(&self) -> bool {
98		let versions = if self.competing.is_empty() {
99			self.base.as_ref() == Some(&self.version)
100		} else {
101			self.competing
102				.iter()
103				.all(|version| self.written.contains(&version.key()))
104		};
105		versions && self.deletions.iter().all(|key| self.written.contains(key))
106	}
107
108	/// Whether other values compete with this version: versions, or deletions.
109	fn competes(&self) -> bool {
110		!self.competing.is_empty() || !self.deletions.is_empty()
111	}
112
113	/// Notes that the copy holds every value of the file that competes now, if any do, as an
114	/// update wrote them out into it, which a commit then settles; and the file among the
115	/// contested, if deletions compete with its version.
116	fn wrote_out(&self, updated: &mut Updated, changes: &mut Changes) {
117		if !self.competes() {
118			return;
119		}
120		let mut keys: BTreeSet<String> = self.competing.iter().map(Version::key).collect();
121		keys.insert(self.version.key());
122		keys.extend(self.deletions.iter().cloned());
123		changes.written_out.push((self.entity, keys));
124		if !self.deletions.is_empty() {
125			updated.contested.push(self.path.clone());
126		}
127	}
128}
129
130/// What an update works with: the tree and its copy, and the index.
131struct Here<'a> {
132	space: SpaceId,
133	tree: EntityId,
134	place: Place<'a>,
135	index: &'a Index,
136	/// Whether the index holds the whole copy: else a copy that it has no entry of may be
137	/// any version of its file.
138	whole: bool,
139	/// The copies of other files written beside paths, by path.
140	conflicts: BTreeMap<String, Conflict>,
141	read_at: i64,
142}
143
144/// What an update changes in the index as it goes, written once it is done.
145#[derive(Default)]
146struct Changes {
147	set: Vec<(String, Entry)>,
148	removed: Vec<String>,
149	/// The competing versions written out into each copy, by their keys.
150	written_out: Vec<(EntityId, BTreeSet<String>)>,
151	/// Whether a copy was left whose version the index does not know.
152	unknown: bool,
153}
154
155impl Library {
156	/// Brings the copy of a tree on this device to the tree as the library has it, as other
157	/// devices left it: writes new versions, moves, additions and deletions, merges edits made
158	/// here with newer versions, and writes out competing values. What was deleted or moved
159	/// here and not committed stays so. A commit of another device in several parts is left
160	/// out until all its parts have arrived, unless `partial`, after which this copy keeps
161	/// what it took. Nothing is recorded: committing what it wrote settles what competed.
162	///
163	/// # Errors
164	///
165	/// Returns [`NodeError::NoTreeHere`] if the tree has no folder on this device,
166	/// [`NodeError::TreeEmptied`] if the copy holds none of its files, as a drive that is not
167	/// there leaves it, and an error if the space or the index cannot be read.
168	pub fn update_tree(
169		&self,
170		space: SpaceId,
171		tree: EntityId,
172		partial: bool,
173	) -> Result<Updated, NodeError> {
174		self.update_tree_with(space, tree, (partial, false), None)
175	}
176
177	/// Brings the copy of a tree on this device to the tree, as [`Library::update_tree`]
178	/// does, with what waits for the person's agreement too: moves of secret files, and
179	/// `.nibsecret` files that lose lines, which [`Updated::held`] lists.
180	///
181	/// # Errors
182	///
183	/// As [`Library::update_tree`].
184	pub fn update_tree_agreeing(
185		&self,
186		space: SpaceId,
187		tree: EntityId,
188		partial: bool,
189	) -> Result<Updated, NodeError> {
190		self.update_tree_with(space, tree, (partial, true), None)
191	}
192
193	/// Updates the copy of a tree as [`Library::update_tree_agreeing`] does, but stops once
194	/// it has written `written` copies, after its moves and deletions, before it records
195	/// anything, as a crash would: for trying what an update cut short leaves.
196	///
197	/// # Errors
198	///
199	/// As [`Library::update_tree`].
200	pub fn update_tree_cut_after(
201		&self,
202		space: SpaceId,
203		tree: EntityId,
204		written: usize,
205	) -> Result<Updated, NodeError> {
206		self.update_tree_with(space, tree, (false, true), Some(written))
207	}
208
209	/// Brings the copy of a tree on this device to the tree, with what waits for the
210	/// person's agreement if `agreed` says so; stops before it records anything, once it has
211	/// written as many copies as `cut` says, if it says.
212	fn update_tree_with(
213		&self,
214		space: SpaceId,
215		tree: EntityId,
216		(partial, agreed): (bool, bool),
217		cut: Option<usize>,
218	) -> Result<Updated, NodeError> {
219		let _locked = self.lock_trees()?;
220		let root = self.root_here(space, tree)?;
221		let mut index = self.index()?;
222		let purged = self.learn_purges(space, &index)?;
223		let apart = self.apart();
224		let place = Place {
225			root: &root,
226			apart: &apart,
227		};
228		let now = self.tree_state(space, tree)?;
229		settle_tree((tree, &root, &apart), &mut index, (&purged, &now))?;
230		self.follow_cut_short(space, (tree, &root, &apart), &mut index, &now)?;
231		let entries = index.entries(tree)?;
232		// A copy with none of its files is more likely a drive that is not there than one
233		// to write the whole tree into.
234		if !entries.is_empty()
235			&& entries
236				.keys()
237				.all(|path| located(&root, path, &apart) == Located::Absent)
238		{
239			return Err(NodeError::TreeEmptied(root));
240		}
241		let mut updated = Updated::default();
242		let in_full: BTreeSet<EntityId> = now.by_entity.keys().copied().collect();
243		// What this copy lacks of the secret files, as the tree is now, with the copies it
244		// holds standing in.
245		let sealed: Vec<String> = now.sealed.keys().cloned().collect();
246		let (state, taken) =
247			self.state_to_update(space, tree, (now, partial), (&index, &mut updated))?;
248		let here = Here {
249			space,
250			tree,
251			place,
252			index: &index,
253			whole: index.knows(tree)?,
254			conflicts: index.conflicts(tree)?,
255			read_at: nanos(SystemTime::now()).unwrap_or(0),
256		};
257		let by_entity: BTreeMap<EntityId, (String, Entry)> = entries
258			.iter()
259			.map(|(path, entry)| (entry.entity, (path.clone(), entry.clone())))
260			.collect();
261		let mut changes = Changes::default();
262		let written = index.written_out(tree)?;
263		let (mut deleted, mut moves, mut arriving) =
264			plan_update((&state, &in_full), &by_entity, &written);
265		updated.sealed = sealed;
266		if !agreed {
267			self.hold_back(
268				space,
269				(&state, &entries),
270				(&mut deleted, &mut moves, &mut arriving),
271				&mut updated,
272			)?;
273		}
274		tell_moved_apart(&state, &by_entity, &mut updated);
275		let noted = note_writing(&index, tree, &arriving)?;
276		for (path, entry) in &deleted {
277			// Deleted elsewhere: the copy goes, unless it was edited here.
278			delete_copy(place, (path, entry), &mut updated, &mut changes.removed);
279		}
280		// Moves, all at once; then what arrives at each path, the index as the deletions
281		// and moves left it.
282		let failed = carry_out_moves(place, (&entries, &moves), (&mut updated, &mut changes));
283		let held = held_paths(&entries, &changes);
284		self.arrive_all(
285			&here,
286			(&arriving, &failed, &held),
287			cut,
288			(&mut updated, &mut changes),
289		);
290		if cut.is_some() {
291			return Ok(updated);
292		}
293		let whole = here.whole;
294		index.change(tree, &changes.removed, &changes.set)?;
295		self.note_secrets(space, (tree, &index), &state, &changes.set)?;
296		for (entity, keys) in &changes.written_out {
297			index.write_out(tree, *entity, keys)?;
298		}
299		clear_obsolete((tree, place, &index), &state, &mut updated)?;
300		self.settle_repositories(space, (tree, &index), &mut updated)?;
301		if partial {
302			index.take_parts(tree, &taken)?;
303		}
304		// A lost index holds the whole copy again only once every copy was looked at.
305		if whole || (!changes.unknown && updated.skipped.is_empty()) {
306			index.know(tree)?;
307		}
308		if noted {
309			index.forget_writing(tree)?;
310		}
311		updated.written.sort();
312		updated.merged.sort();
313		updated.contested.sort();
314		updated.conflicts.sort();
315		updated.conflicts.dedup();
316		Ok(updated)
317	}
318
319	/// Writes what arrives at each path, or beside it, of the arrivals that the deletions and
320	/// moves left, all but those whose moves `failed`; stops once it has written as many
321	/// copies as `cut` says, if it says.
322	fn arrive_all(
323		&self,
324		here: &Here<'_>,
325		(arriving, failed, held): (
326			&[Arriving],
327			&BTreeSet<EntityId>,
328			&BTreeMap<String, EntityId>,
329		),
330		cut: Option<usize>,
331		(updated, changes): (&mut Updated, &mut Changes),
332	) {
333		for arrival in arriving {
334			if cut.is_some_and(|cut| updated.written.len() >= cut) {
335				return;
336			}
337			if failed.contains(&arrival.entity) {
338				let why = "it could not be moved where the tree has it".to_owned();
339				updated.skipped.push((arrival.path.clone(), why));
340				continue;
341			}
342			if goes_beside(held, here, arrival) {
343				self.write_beside(here, arrival, updated);
344				continue;
345			}
346			// One file that fails leaves the others to update.
347			if let Err(error) = self.arrive(here, arrival, (updated, changes)) {
348				updated
349					.skipped
350					.push((arrival.path.clone(), error.to_string()));
351			}
352		}
353	}
354
355	/// The tree to bring the copy to: as the library has it, without the commits of other
356	/// devices whose parts have not all arrived, unless `partial`, which go in `updated`.
357	/// This replica's own commits cut short stay in, as its copy holds what they recorded,
358	/// and so do those whose parts this copy took. Returns the state, and the commits cut
359	/// short, by their revisions.
360	fn state_to_update(
361		&self,
362		space: SpaceId,
363		tree: EntityId,
364		(now, partial): (TreeState, bool),
365		(index, updated): (&Index, &mut Updated),
366	) -> Result<(TreeState, Vec<EntityId>), NodeError> {
367		let cut = self.cut_short(space, tree)?;
368		let revisions = cut.iter().map(|cut| cut.revision).collect();
369		if partial {
370			return Ok((now, revisions));
371		}
372		let this_replica = self.replica.signing.verifying_key();
373		let taken = index.taken_parts(tree)?;
374		let mut without = BTreeSet::new();
375		for cut in cut {
376			if taken.contains(&cut.revision) {
377				continue;
378			}
379			let changes = self.revision_changes(space, tree, cut.revision)?;
380			let log = self.space(space)?.stored.log();
381			let own = match changes.first() {
382				Some(first) => log
383					.change(*first)?
384					.is_some_and(|change| *change.author() == this_replica),
385				None => true,
386			};
387			if !own {
388				without.extend(changes);
389				updated.waiting.push(cut);
390			}
391		}
392		if without.is_empty() {
393			return Ok((now, revisions));
394		}
395		Ok((self.tree_state_without(space, tree, &without)?, revisions))
396	}
397
398	/// Writes a version that arrived at its path: where no copy is, as it is, unless the copy
399	/// was deleted or moved here, which stays so; over a copy that holds the version it was
400	/// written at; or merged three ways with a copy edited here, and with versions that
401	/// compete with it. A copy that the index has no entry of, once the index was lost,
402	/// stays as it is.
403	fn arrive(
404		&self,
405		here: &Here<'_>,
406		arrival: &Arriving,
407		(updated, changes): (&mut Updated, &mut Changes),
408	) -> Result<(), NodeError> {
409		let path = &arrival.path;
410		let nothing_new = arrival.nothing_new();
411		let entry = |found: &Found, version: &Version, known: bool| {
412			entry_for(arrival.entity, (found, version, known), here.read_at)
413		};
414		let on_disk = match located(here.place.root, path, here.place.apart) {
415			Located::Here(on_disk) => on_disk,
416			// Deleted or moved here, and not committed: it stays so.
417			// Deleted or moved here from the version that deletions elsewhere compete with:
418			// seen, so that a commit deletes or moves it.
419			Located::Absent
420				if !arrival.deletions.is_empty()
421					&& arrival.competing.is_empty()
422					&& arrival.base.as_ref() == Some(&arrival.version) =>
423			{
424				arrival.wrote_out(updated, changes);
425				return Ok(());
426			}
427			Located::Absent if arrival.base.is_some() => {
428				if !nothing_new {
429					let why = "deleted or moved here, and changed elsewhere: restore it, or \
430					           commit with force to delete it"
431						.to_owned();
432					updated.kept.push((path.clone(), why));
433				}
434				return Ok(());
435			}
436			Located::Absent => {
437				let content = Content::of(&arrival.version, arrival.secret);
438				match self.write_new(here.space, here.place, path, &content) {
439					Ok(found) if arrival.competing.is_empty() => {
440						updated.written.push(path.clone());
441						let written = entry(&found, &arrival.version, true);
442						changes.set.push((path.clone(), written));
443						arrival.wrote_out(updated, changes);
444					}
445					// The versions that compete with it, merged into it.
446					Ok(found) => {
447						updated.written.push(path.clone());
448						let written = Arriving {
449							base: Some(arrival.version.clone()),
450							..arrival.clone()
451						};
452						return self.arrive_at_copy(
453							here,
454							&written,
455							&found.on_disk,
456							(updated, changes),
457						);
458					}
459					Err(why) => updated.skipped.push((path.clone(), why)),
460				}
461				return Ok(());
462			}
463			Located::Unknown(why) => {
464				updated.skipped.push((path.clone(), why));
465				return Ok(());
466			}
467		};
468		if nothing_new {
469			return Ok(());
470		}
471		self.arrive_at_copy(here, arrival, &on_disk, (updated, changes))
472	}
473
474	/// Writes a version that arrived where a copy of its file is: over it, if it holds the
475	/// version it was written at, or merged with it; or, once the index was lost, leaves it.
476	fn arrive_at_copy(
477		&self,
478		here: &Here<'_>,
479		arrival: &Arriving,
480		on_disk: &Path,
481		(updated, changes): (&mut Updated, &mut Changes),
482	) -> Result<(), NodeError> {
483		let path = &arrival.path;
484		let entry = |found: &Found, version: &Version, known: bool| {
485			entry_for(arrival.entity, (found, version, known), here.read_at)
486		};
487		// Read whatever its size and time say, as an edit may keep both.
488		let found = look(on_disk).ok();
489		let Some((found, holds)) =
490			found.and_then(|found| copy_version(&found).map(|holds| (found, holds)))
491		else {
492			updated
493				.skipped
494				.push((path.clone(), "it cannot be read".to_owned()));
495			return Ok(());
496		};
497		if arrival.base.is_none() {
498			// Only a lost index leaves a copy here that it has no entry of.
499			if same_version(&found, &holds, &arrival.version) {
500				changes
501					.set
502					.push((path.clone(), entry(&found, &arrival.version, true)));
503			} else {
504				changes.unknown = true;
505				let why = "which version it holds is not known, as the index of copies was \
506				           lost: commit it, or restore it"
507					.to_owned();
508				updated.kept.push((path.clone(), why));
509			}
510			return Ok(());
511		}
512		// The other versions to bring in: those that compete and were not written out, or
513		// the one that arrived.
514		let candidates: Vec<&Version> = if arrival.competing.is_empty() {
515			vec![&arrival.version]
516		} else {
517			arrival
518				.competing
519				.iter()
520				.filter(|version| !arrival.written.contains(&version.key()))
521				.collect()
522		};
523		let others: Vec<&Version> = candidates
524			.into_iter()
525			.filter(|other| !same_version(&found, &holds, other))
526			.filter(|other| arrival.base.as_ref() != Some(*other))
527			.collect();
528		let unedited = arrival
529			.base
530			.as_ref()
531			.is_some_and(|base| same_version(&found, &holds, base));
532		if others.is_empty() {
533			let known = arrival.competing.is_empty() && unedited;
534			changes
535				.set
536				.push((path.clone(), entry(&found, &arrival.version, known)));
537			arrival.wrote_out(updated, changes);
538			return Ok(());
539		}
540		if unedited && arrival.competing.is_empty() {
541			let content = Content::of(&arrival.version, arrival.secret);
542			match self.write_over(here.space, &found, &content) {
543				Ok(()) => {
544					updated.written.push(path.clone());
545					if let Ok(now) = look(on_disk) {
546						let written = entry(&now, &arrival.version, true);
547						changes.set.push((path.clone(), written));
548						arrival.wrote_out(updated, changes);
549					}
550				}
551				Err(why) => updated.skipped.push((path.clone(), why)),
552			}
553			return Ok(());
554		}
555		let Some(clashed) = self.merge_arrival(here, (arrival, &found), others, updated)? else {
556			return Ok(());
557		};
558		if clashed {
559			updated.conflicts.push(path.clone());
560		} else {
561			updated.merged.push(path.clone());
562		}
563		// The copy now builds on the version that arrived; what it holds is to commit.
564		if let Ok(now) = look(on_disk) {
565			changes
566				.set
567				.push((path.clone(), entry(&now, &arrival.version, false)));
568			arrival.wrote_out(updated, changes);
569		}
570		Ok(())
571	}
572
573	/// Merges into the copy that `found` is, edited here or competing, each of `others` in
574	/// turn, from the version both started from: text three ways, with Git's conflict
575	/// markers where edits clash, and what is no text beside it, marked before it is
576	/// written. Returns whether anything clashed, or `None` if the copy, or a version
577	/// beside it, could not be written, which leaves the copy's base as it was.
578	fn merge_arrival(
579		&self,
580		here: &Here<'_>,
581		(arrival, found): (&Arriving, &Found),
582		others: Vec<&Version>,
583		updated: &mut Updated,
584	) -> Result<Option<bool>, NodeError> {
585		let path = &arrival.path;
586		let space = here.space;
587		// A newer version builds on the one this copy was written at; competing versions
588		// build on the last one they all superseded.
589		let base = if arrival.competing.is_empty() {
590			arrival.base.clone()
591		} else {
592			// Its content, with the executable bit this copy was written with.
593			let written = matches!(
594				arrival.base,
595				Some(Version::File {
596					executable: true,
597					..
598				})
599			);
600			self.common_base(space, arrival.entity)?
601				.map(|base| match base {
602					Version::File { content, .. } => Version::File {
603						content,
604						executable: written,
605					},
606					link @ Version::Link { .. } => link,
607				})
608		};
609		let mut ours = match &found.kind {
610			FoundKind::File => {
611				let mut bytes = Vec::new();
612				let read = open_found(found)
613					.and_then(|file| {
614						io::Read::read_to_end(&mut io::Read::take(file, READ_LIMIT + 1), &mut bytes)
615					})
616					.map_err(NodeError::file(&found.on_disk))?;
617				(read as u64 <= READ_LIMIT).then_some(bytes)
618			}
619			FoundKind::Link(_) => None,
620		};
621		let secret = arrival.secret;
622		let base_bytes = match &base {
623			Some(Version::File { content, .. }) => self.version_bytes(space, content, secret)?,
624			Some(Version::Link { .. }) => None,
625			None => Some(Vec::new()),
626		};
627		let mut clashed = false;
628		let mut merged_any = false;
629		for other in others {
630			let other_bytes = match other {
631				Version::File { content, .. } => self.version_bytes(space, content, secret)?,
632				Version::Link { .. } => None,
633			};
634			let text = match (&ours, &base_bytes, &other_bytes) {
635				(Some(ours), Some(base), Some(other)) => [ours, base, other]
636					.iter()
637					.all(|bytes| super::diff::is_text(bytes))
638					.then(|| (ours.clone(), base.clone(), other.clone())),
639				_ => None,
640			};
641			if let Some((mine, from, theirs)) = text {
642				match diffy::merge_bytes(&from, &mine, &theirs) {
643					Ok(merged) => ours = Some(merged),
644					Err(marked) => {
645						ours = Some(marked);
646						clashed = true;
647					}
648				}
649				merged_any = true;
650				continue;
651			}
652			let device = self.device_of(space, arrival.entity, other);
653			let Some((beside, there)) = place_beside(here, (path, &device), other) else {
654				let why = format!("{path}.conflict-{device} and the names after it are taken");
655				updated.skipped.push((path.clone(), why));
656				return Ok(None);
657			};
658			clashed = true;
659			if there {
660				continue;
661			}
662			// Marked first, so that no commit takes it in, whatever stops the update.
663			here.index.mark(
664				here.tree,
665				&beside,
666				"NibKeep wrote it, the other version of a file, from another device",
667			)?;
668			if let Err(why) =
669				self.write_new(space, here.place, &beside, &Content::of(other, secret))
670			{
671				here.index
672					.unmark(here.tree, std::slice::from_ref(&beside))?;
673				updated.skipped.push((path.clone(), why));
674				return Ok(None);
675			}
676		}
677		if merged_any && let Some(bytes) = &ours {
678			let executable = merged_executable(found, base.as_ref(), &arrival.version);
679			let merged = Content::bytes(bytes, executable, secret);
680			if let Err(why) = self.write_over(space, found, &merged) {
681				updated.skipped.push((path.clone(), why));
682				return Ok(None);
683			}
684		}
685		Ok(Some(clashed))
686	}
687
688	/// Writes beside its path the version of another file that competes for it, as two
689	/// devices that add one path give it two files, as `NAME.conflict-DEVICE`, marked first,
690	/// and then with the file and the version written: what the person does with it settles
691	/// that file at the next commit. A copy beside written before gets a newer version
692	/// unless the person changed it.
693	fn write_beside(&self, here: &Here<'_>, arrival: &Arriving, updated: &mut Updated) {
694		let device = self.device_of(here.space, arrival.entity, &arrival.version);
695		// The name of this file's copy beside, or a free one: never another's, which may be
696		// a settlement still to commit.
697		let named = (1..=99)
698			.map(|number| match number {
699				1 => format!("{}.conflict-{device}", arrival.path),
700				_ => format!("{}.conflict-{device}-{number}", arrival.path),
701			})
702			.find(|beside| match here.conflicts.get(beside) {
703				Some(conflict) => conflict.entity == arrival.entity,
704				None => located(here.place.root, beside, here.place.apart) == Located::Absent,
705			});
706		let Some(beside) = named else {
707			let why = format!(
708				"{}.conflict-{device} and the names after it are taken",
709				arrival.path
710			);
711			updated.skipped.push((arrival.path.clone(), why));
712			return;
713		};
714		let content = Content::of(&arrival.version, arrival.secret);
715		let written = match located(here.place.root, &beside, here.place.apart) {
716			// Renamed or deleted, as written: settled here, which the next commit records.
717			Located::Absent
718				if here.conflicts.get(&beside).is_some_and(|conflict| {
719					conflict.entity == arrival.entity
720						&& conflict
721							.written
722							.as_ref()
723							.is_some_and(|written| same_content(written, &arrival.version))
724				}) =>
725			{
726				let why = "the other file at this path, settled here: commit to record it";
727				updated.kept.push((beside, why.to_owned()));
728				return;
729			}
730			Located::Absent => {
731				let why = "NibKeep wrote it, the file of another device at the same path";
732				match here.index.mark(here.tree, &beside, why) {
733					Ok(()) => match self.write_new(here.space, here.place, &beside, &content) {
734						Ok(_) => Ok(()),
735						Err(why) => {
736							let _ = here.index.unmark(here.tree, std::slice::from_ref(&beside));
737							Err(why)
738						}
739					},
740					Err(error) => Err(error.to_string()),
741				}
742			}
743			Located::Here(on_disk) => match look(&on_disk) {
744				Ok(found) => {
745					let holds = copy_version(&found);
746					let before = here
747						.conflicts
748						.get(&beside)
749						.filter(|conflict| conflict.entity == arrival.entity)
750						.and_then(|conflict| conflict.written.clone());
751					let holding = |version: &Version| {
752						holds
753							.as_ref()
754							.is_some_and(|holds| same_content(holds, version))
755					};
756					if holding(&arrival.version) {
757						Ok(())
758					} else if before.as_ref().is_some_and(holding) {
759						self.write_over(here.space, &found, &content)
760					} else {
761						Err(format!("{beside} is in the way"))
762					}
763				}
764				Err(why) => Err(why),
765			},
766			Located::Unknown(why) => Err(why),
767		};
768		let marked = written.and_then(|()| {
769			here.index
770				.mark_conflict(
771					here.tree,
772					(&beside, &arrival.path),
773					(arrival.entity, &arrival.version),
774				)
775				.map_err(|error| error.to_string())
776		});
777		match marked {
778			Ok(()) => updated.conflicts.push(arrival.path.clone()),
779			Err(why) => updated.skipped.push((arrival.path.clone(), why)),
780		}
781	}
782
783	/// Settles the Git repositories that this copy holds and that changed elsewhere: one
784	/// deleted elsewhere keeps its folder, with the work it may hold, marked so that commits
785	/// leave it out until the person deletes it or renames it to keep it; one moved
786	/// elsewhere stays, listed, for the person to move.
787	fn settle_repositories(
788		&self,
789		space: SpaceId,
790		(tree, index): (EntityId, &Index),
791		updated: &mut Updated,
792	) -> Result<(), NodeError> {
793		let recorded: BTreeMap<EntityId, String> = self
794			.recorded_repositories(space, tree)?
795			.into_iter()
796			.map(|recorded| (recorded.entity, recorded.path))
797			.collect();
798		let mut gone = Vec::new();
799		for (path, (entity, _)) in index.repositories(tree)? {
800			match recorded.get(&entity) {
801				Some(now) if *now == path => {}
802				Some(now) => {
803					let why =
804						format!("a Git repository moved elsewhere to {now}: move its folder there");
805					updated.kept.push((path, why));
806				}
807				None => {
808					let why = "a Git repository deleted from the tree elsewhere, whose folder stays \
809					           with its work until you delete it";
810					index.mark(tree, &path, why)?;
811					updated.kept.push((path.clone(), why.to_owned()));
812					gone.push(path);
813				}
814			}
815		}
816		index.forget_repositories(tree, &gone)
817	}
818
819	/// The name of the device whose replica made a version of a file, for the name of a copy
820	/// written beside another, with what no file name holds left out; `elsewhere` if the
821	/// space does not say.
822	fn device_of(&self, space: SpaceId, entity: EntityId, version: &Version) -> String {
823		let (fields, value) = match version {
824			Version::File { content, .. } => {
825				(&[CONTENT, SECRET_CONTENT][..], Value::Blob(*content))
826			}
827			Version::Link { target } => (&[LINK_TARGET][..], Value::Text(target.clone())),
828		};
829		let name = {
830			let open = self.space(space).ok();
831			let statement = open.and_then(|open| {
832				let state = open.stored.log().state();
833				fields.iter().find_map(|field| {
834					state
835						.current(entity, field)
836						.ok()?
837						.into_iter()
838						.find(|statement| statement.value == value)
839						.map(|statement| statement.id)
840				})
841			});
842			statement
843				.and_then(|statement| self.device_name_of(space, statement))
844				.unwrap_or_else(|| "elsewhere".to_owned())
845		};
846		let kept: String = name
847			.chars()
848			.take(40)
849			.map(|character| {
850				if character.is_alphanumeric() || matches!(character, '-' | '_') {
851					character
852				} else {
853					'-'
854				}
855			})
856			.collect();
857		if kept.trim_matches('-').is_empty() {
858			"elsewhere".to_owned()
859		} else {
860			kept
861		}
862	}
863
864	/// The version of a file that its competing versions all started from: of the versions
865	/// that each superseded, directly or through the versions before it, the one recorded
866	/// last, as their payloads say.
867	fn common_base(&self, space: SpaceId, entity: EntityId) -> Result<Option<Version>, NodeError> {
868		let open = self.space(space)?;
869		let state = open.stored.log().state();
870		let storage = state.storage();
871		let mut competing = Vec::new();
872		for field in [CONTENT, SECRET_CONTENT, LINK_TARGET] {
873			for id in storage.of_field(entity, &field)? {
874				if state.is_current(id)? {
875					competing.push(id);
876				}
877			}
878		}
879		let mut common: Option<BTreeSet<StatementId>> = None;
880		for id in competing {
881			let before = self.superseded_through(space, id)?;
882			common = Some(match common {
883				Some(common) => common.intersection(&before).copied().collect(),
884				None => before,
885			});
886		}
887		let mut last: Option<(nibkeep_time::Timestamp, Version)> = None;
888		for id in common.unwrap_or_default() {
889			let Some(recorded) = storage.get(id)? else {
890				continue;
891			};
892			let version = match recorded.statement.value.clone() {
893				Value::Blob(content) => Version::File {
894					content,
895					executable: false,
896				},
897				Value::Text(target) => Version::Link { target },
898				_ => continue,
899			};
900			if last.as_ref().is_none_or(|(at, _)| recorded.at > *at) {
901				last = Some((recorded.at, version));
902			}
903		}
904		Ok(last.map(|(_, version)| version))
905	}
906
907	/// The statements that a statement superseded, directly or through those it superseded
908	/// in turn, as the payloads of their changes say.
909	fn superseded_through(
910		&self,
911		space: SpaceId,
912		statement: StatementId,
913	) -> Result<BTreeSet<StatementId>, NodeError> {
914		let open = self.space(space)?;
915		let log = open.stored.log();
916		let mut seen = BTreeSet::new();
917		let mut waiting = vec![statement];
918		while let Some(id) = waiting.pop() {
919			let change = log
920				.state()
921				.storage()
922				.get(id)?
923				.and_then(|recorded| recorded.change);
924			let Some(change) = change else {
925				continue;
926			};
927			let Some(payload) = log.payload(ChangeId::from_hash(change), &open.keys)? else {
928				continue;
929			};
930			for operation in &payload.operations {
931				if let Operation::Assert {
932					statement,
933					supersedes,
934					..
935				} = operation
936					&& statement.id == id
937				{
938					for before in supersedes {
939						if seen.insert(*before) {
940							waiting.push(*before);
941						}
942					}
943				}
944			}
945		}
946		Ok(seen)
947	}
948
949	/// Holds back, until the person agrees, what changed elsewhere that could expose a
950	/// secret: a move of a secret file, which could put its plain copy where a web server or
951	/// a sync program publishes it; and a `.nibsecret` file that loses lines, by an edit, a
952	/// move or a deletion, which could make new files ordinary. Any replica of the space can
953	/// make such changes, an AI agent's too. What it holds back stays as the copy has it.
954	#[allow(
955		clippy::type_complexity,
956		reason = "the three lists of an update, changed in place"
957	)]
958	fn hold_back(
959		&self,
960		space: SpaceId,
961		(state, entries): (&TreeState, &BTreeMap<String, Entry>),
962		(deleted, moves, arriving): (
963			&mut Vec<(String, Entry)>,
964			&mut Vec<(String, String)>,
965			&mut Vec<Arriving>,
966		),
967		updated: &mut Updated,
968	) -> Result<(), NodeError> {
969		let is_nibsecret =
970			|path: &str| path == NIBSECRET || path.ends_with(&format!("/{NIBSECRET}"));
971		let mut held: BTreeSet<EntityId> = BTreeSet::new();
972		moves.retain(|(from, to)| {
973			let Some(entry) = entries.get(from) else {
974				return true;
975			};
976			if state.is_secret(entry.entity) || is_nibsecret(from) {
977				updated.held.push(format!("{from} -> {to}"));
978				held.insert(entry.entity);
979				return false;
980			}
981			true
982		});
983		deleted.retain(|(path, entry)| {
984			if is_nibsecret(path) {
985				updated.held.push(path.clone());
986				held.insert(entry.entity);
987				return false;
988			}
989			true
990		});
991		for arrival in arriving.iter() {
992			if held.contains(&arrival.entity) || !is_nibsecret(&arrival.path) {
993				continue;
994			}
995			let (
996				Some(Version::File { content: was, .. }),
997				Version::File {
998					content: becomes, ..
999				},
1000			) = (&arrival.base, &arrival.version)
1001			else {
1002				continue;
1003			};
1004			if was == becomes {
1005				continue;
1006			}
1007			let was = self.content_bytes(space, was)?.unwrap_or_default();
1008			let becomes = self.content_bytes(space, becomes)?.unwrap_or_default();
1009			let was = String::from_utf8_lossy(&was);
1010			let becomes = String::from_utf8_lossy(&becomes);
1011			if !lines(&was).is_subset(&lines(&becomes)) {
1012				updated.held.push(arrival.path.clone());
1013				held.insert(arrival.entity);
1014			}
1015		}
1016		arriving.retain(|arrival| !held.contains(&arrival.entity));
1017		updated.held.sort();
1018		Ok(())
1019	}
1020}
1021
1022/// Which file holds each path of the copy, as the index holds it with what an update's
1023/// deletions and moves changed.
1024fn held_paths(entries: &BTreeMap<String, Entry>, changes: &Changes) -> BTreeMap<String, EntityId> {
1025	let mut held: BTreeMap<String, EntityId> = entries
1026		.iter()
1027		.filter(|(path, _)| !changes.removed.contains(path))
1028		.map(|(path, entry)| (path.clone(), entry.entity))
1029		.collect();
1030	held.extend(
1031		changes
1032			.set
1033			.iter()
1034			.map(|(path, entry)| (path.clone(), entry.entity)),
1035	);
1036	held
1037}
1038
1039/// Lists the copies of files moved apart on two devices, which stay where they are here,
1040/// for a commit to keep them there.
1041fn tell_moved_apart(
1042	state: &TreeState,
1043	by_entity: &BTreeMap<EntityId, (String, Entry)>,
1044	updated: &mut Updated,
1045) {
1046	for (entity, paths) in &state.paths {
1047		if let Some((here_at, _)) = by_entity.get(entity)
1048			&& paths.contains(here_at)
1049		{
1050			let elsewhere: Vec<&str> = paths
1051				.iter()
1052				.filter(|path| *path != here_at)
1053				.map(String::as_str)
1054				.collect();
1055			let why = format!(
1056				"moved apart, also to {}: commit to keep it here",
1057				elsewhere.join(", ")
1058			);
1059			updated.kept.push((here_at.clone(), why));
1060		}
1061	}
1062}
1063
1064/// Where to write beside `path` another version, `other`, of its file, made on `device`:
1065/// `NAME.conflict-DEVICE`, or with `-2` and on after it where those names are taken by
1066/// something else; and whether the version is there already, as an update that stopped
1067/// left it.
1068fn place_beside(
1069	here: &Here<'_>,
1070	(path, device): (&str, &str),
1071	other: &Version,
1072) -> Option<(String, bool)> {
1073	for number in 1..=99 {
1074		let beside = if number == 1 {
1075			format!("{path}.conflict-{device}")
1076		} else {
1077			format!("{path}.conflict-{device}-{number}")
1078		};
1079		match located(here.place.root, &beside, here.place.apart) {
1080			Located::Absent => return Some((beside, false)),
1081			Located::Here(on_disk) => {
1082				let holds = look(&on_disk).ok().and_then(|found| copy_version(&found));
1083				if holds.is_some_and(|holds| same_content(&holds, other)) {
1084					return Some((beside, true));
1085				}
1086			}
1087			Located::Unknown(_) => {}
1088		}
1089	}
1090	None
1091}
1092
1093/// The index's entry of a copy of `entity` found holding `version`, or built on it, if not
1094/// `known`: then its time is not kept, so that the next status reads it, and finds the edit
1095/// to commit.
1096fn entry_for(
1097	entity: EntityId,
1098	(found, version, known): (&Found, &Version, bool),
1099	read_at: i64,
1100) -> Entry {
1101	Entry {
1102		entity,
1103		version: version.clone(),
1104		size: found.size,
1105		modified: if known { found.modified } else { None },
1106		read_at,
1107	}
1108}
1109
1110/// The executable bit of a merge: the copy's, if this copy changed it from the version both
1111/// started from, and else the one that arrived.
1112fn merged_executable(found: &Found, base: Option<&Version>, arrived: &Version) -> bool {
1113	let is = |version: Option<&Version>| {
1114		matches!(
1115			version,
1116			Some(Version::File {
1117				executable: true,
1118				..
1119			})
1120		)
1121	};
1122	match found.executable {
1123		Some(here) if here != is(base) => here,
1124		_ => is(Some(arrived)),
1125	}
1126}
1127
1128/// Deletes the copy at `path` of a file deleted elsewhere, if it holds the version it was
1129/// written or committed at, and is still the file read; an edited copy stays, and is
1130/// listed.
1131fn delete_copy(
1132	place: Place<'_>,
1133	(path, entry): (&String, &Entry),
1134	updated: &mut Updated,
1135	removed: &mut Vec<String>,
1136) {
1137	let on_disk = match located(place.root, path, place.apart) {
1138		Located::Here(on_disk) => on_disk,
1139		Located::Absent => {
1140			removed.push(path.clone());
1141			return;
1142		}
1143		Located::Unknown(why) => {
1144			updated.skipped.push((path.clone(), why));
1145			return;
1146		}
1147	};
1148	let Ok(found) = look(&on_disk) else {
1149		updated
1150			.skipped
1151			.push((path.clone(), "it cannot be read".to_owned()));
1152		return;
1153	};
1154	let unedited =
1155		copy_version(&found).is_some_and(|holds| same_version(&found, &holds, &entry.version));
1156	if !unedited {
1157		let why = "deleted elsewhere, and edited here".to_owned();
1158		updated.kept.push((path.clone(), why));
1159		return;
1160	}
1161	// Deleted only if it is still the file read, as a save made meanwhile replaces it.
1162	if !super::write::still_the_copy(&found) {
1163		updated
1164			.kept
1165			.push((path.clone(), "it changed meanwhile".to_owned()));
1166		return;
1167	}
1168	match fs::remove_file(&on_disk) {
1169		Ok(()) => {
1170			sync_folder_of(&on_disk);
1171			updated.deleted.push(path.clone());
1172			removed.push(path.clone());
1173		}
1174		Err(error) => updated.skipped.push((path.clone(), error.to_string())),
1175	}
1176}
1177
1178/// Moves the copies of files moved elsewhere, all at once, so that swaps and chains
1179/// work, and returns the files whose copies could not be moved.
1180fn carry_out_moves(
1181	place: Place<'_>,
1182	(entries, moves): (&BTreeMap<String, Entry>, &[(String, String)]),
1183	(updated, changes): (&mut Updated, &mut Changes),
1184) -> BTreeSet<EntityId> {
1185	let at = undo_moves_at(place, moves, &mut updated.skipped);
1186	let mut failed = BTreeSet::new();
1187	for (from, to) in moves {
1188		let Some(entry) = entries.get(from) else {
1189			continue;
1190		};
1191		if at.get(from) == Some(to) {
1192			updated.moved.push((from.clone(), to.clone()));
1193			changes.removed.push(from.clone());
1194			changes.set.push((to.clone(), entry.clone()));
1195		} else {
1196			failed.insert(entry.entity);
1197		}
1198	}
1199	failed
1200}
1201
1202/// Notes in the index the versions of secret files that an update is about to write: with
1203/// the secrets locked, only this tells a copy written here, before a crash cut the update
1204/// short, from one edited here. Returns whether it noted any.
1205fn note_writing(index: &Index, tree: EntityId, arriving: &[Arriving]) -> Result<bool, NodeError> {
1206	let secrets: Vec<(String, EntityId, Version)> = arriving
1207		.iter()
1208		.filter(|arrival| arrival.secret && !arrival.nothing_new())
1209		.map(|arrival| {
1210			(
1211				arrival.path.clone(),
1212				arrival.entity,
1213				arrival.version.clone(),
1214			)
1215		})
1216		.collect();
1217	if secrets.is_empty() {
1218		return Ok(false);
1219	}
1220	index.about_to_write(tree, &secrets)?;
1221	Ok(true)
1222}
1223
1224/// What changed elsewhere, file by file: the copies of files deleted elsewhere, with their
1225/// entries; the moves; and the versions that arrive at each path.
1226#[allow(clippy::type_complexity, reason = "three lists, made once")]
1227fn plan_update(
1228	(state, in_full): (&TreeState, &BTreeSet<EntityId>),
1229	by_entity: &BTreeMap<EntityId, (String, Entry)>,
1230	written: &BTreeMap<EntityId, BTreeSet<String>>,
1231) -> (Vec<(String, Entry)>, Vec<(String, String)>, Vec<Arriving>) {
1232	let mut deleted = Vec::new();
1233	let mut moves = Vec::new();
1234	let mut arriving = Vec::new();
1235	let entities: BTreeSet<EntityId> = state
1236		.by_entity
1237		.keys()
1238		.chain(by_entity.keys())
1239		.copied()
1240		.collect();
1241	for entity in entities {
1242		match (by_entity.get(&entity), version_of(state, entity)) {
1243			// Only left out, with a commit not yet whole: neither deleted nor written.
1244			(Some(_), None) if in_full.contains(&entity) => {}
1245			(Some((path, entry)), None) => deleted.push((path.clone(), entry.clone())),
1246			(ours, Some((path, version))) => {
1247				// A file whose content was purged has nothing to write: settling deletes it.
1248				let Some(version) = version else {
1249					continue;
1250				};
1251				// A file moved apart stays at the path of its copy, which a commit keeps.
1252				let path = match ours {
1253					Some((from, _)) if state.at(entity, from) => from.clone(),
1254					_ => path,
1255				};
1256				if let Some((from, _)) = ours
1257					&& *from != path
1258				{
1259					moves.push((from.clone(), path.clone()));
1260				}
1261				arriving.push(Arriving {
1262					path,
1263					entity,
1264					base: ours.map(|(_, entry)| entry.version.clone()),
1265					version,
1266					competing: state.versions.get(&entity).cloned().unwrap_or_default(),
1267					written: written.get(&entity).cloned().unwrap_or_default(),
1268					deletions: state.contested.get(&entity).cloned().unwrap_or_default(),
1269					secret: state.is_secret(entity),
1270				});
1271			}
1272			(None, None) => {}
1273		}
1274	}
1275	(deleted, moves, arriving)
1276}
1277
1278/// Whether the version that arrives at a path goes beside what is there: where another file
1279/// of this copy holds the path, as the deletions and moves of this update left the index,
1280/// or, where the index holds the whole copy, a copy that is none of the tree's is there,
1281/// which is never written over.
1282fn goes_beside(held: &BTreeMap<String, EntityId>, here: &Here<'_>, arrival: &Arriving) -> bool {
1283	match held.get(&arrival.path) {
1284		Some(entity) => *entity != arrival.entity,
1285		None if arrival.base.is_some() || !here.whole => false,
1286		None => match located(here.place.root, &arrival.path, here.place.apart) {
1287			Located::Here(on_disk) => look(&on_disk)
1288				.ok()
1289				.and_then(|found| copy_version(&found).map(|holds| (found, holds)))
1290				.is_none_or(|(found, holds)| !same_version(&found, &holds, &arrival.version)),
1291			Located::Absent | Located::Unknown(_) => false,
1292		},
1293	}
1294}
1295
1296/// Clears the copies written beside paths whose files no longer compete for them, as the
1297/// person settled it elsewhere: one gone, or as it was written, which the tree holds, goes,
1298/// and its mark with it; one the person changed stays marked, as their own.
1299fn clear_obsolete(
1300	(tree, place, index): (EntityId, Place<'_>, &Index),
1301	state: &TreeState,
1302	updated: &mut Updated,
1303) -> Result<(), NodeError> {
1304	let placed: BTreeSet<EntityId> = index
1305		.entries(tree)?
1306		.values()
1307		.map(|entry| entry.entity)
1308		.collect();
1309	for (beside, conflict) in index.conflicts(tree)? {
1310		if still_competes(state, &placed, &conflict) {
1311			continue;
1312		}
1313		let on_disk = match located(place.root, &beside, place.apart) {
1314			Located::Here(on_disk) => on_disk,
1315			Located::Absent => {
1316				index.unmark(tree, std::slice::from_ref(&beside))?;
1317				continue;
1318			}
1319			Located::Unknown(_) => continue,
1320		};
1321		let found = look(&on_disk).ok();
1322		let as_written = found.as_ref().is_some_and(|found| {
1323			copy_version(found)
1324				.zip(conflict.written.as_ref())
1325				.is_some_and(|(holds, written)| same_content(&holds, written))
1326		});
1327		let still = found.is_some_and(|found| {
1328			look(&on_disk).is_ok_and(|now| {
1329				now.identity == found.identity
1330					&& now.size == found.size
1331					&& now.modified == found.modified
1332			})
1333		});
1334		if as_written && still && fs::remove_file(&on_disk).is_ok() {
1335			sync_folder_of(&on_disk);
1336			index.unmark(tree, std::slice::from_ref(&beside))?;
1337			updated.deleted.push(beside);
1338		} else {
1339			index.forget_conflict(tree, &beside)?;
1340		}
1341	}
1342	Ok(())
1343}