Skip to main content

nibkeep_node/
library.rs

1//! A library, as one replica keeps it: its keys, who it belongs to, and its spaces.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::fs;
5use std::io::Read;
6use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind};
7use std::path::{Path, PathBuf};
8use std::time::{Duration, Instant};
9
10use nibkeep_base::{EntityId, Hash, SpaceId, StatementId};
11use nibkeep_crypto::rand_core::CryptoRng;
12use nibkeep_crypto::{DecryptionKey, Key, SigningKey, VerifyingKey};
13use nibkeep_governance::{OWNER, SECRET_FIELD, SIGNING_KEY, SPACE};
14use nibkeep_keys::{CompartmentKey, KeyFile, NewProtection, Protection, ReplicaKeys, Unlocker};
15use nibkeep_log::SpaceKeys;
16use nibkeep_model::schema::{FIELD_DEFINITION, TYPE_DEFINITION};
17use nibkeep_model::storage::Overlay;
18use nibkeep_model::{
19	FieldName, Languages, Operation, State, Statement, TypeDef, Types, Value, fields,
20};
21use nibkeep_store::{StoreError, StoredLog, Ticks, log_path};
22use nibkeep_time::Timestamp;
23
24use crate::engines;
25use crate::info::Info;
26use crate::library::entities::{referred, user_name};
27use crate::place::{self, PLACE, PlaceFile, Verdict};
28use crate::{MemberRole, NodeError};
29
30pub(crate) mod accounts;
31pub(crate) mod agents;
32pub(crate) mod backups;
33pub(crate) mod behind;
34pub(crate) mod checking;
35pub(crate) mod checkouts;
36pub(crate) mod claims;
37pub(crate) mod copies;
38mod deleting_types;
39pub(crate) mod direct;
40pub(crate) mod dropping;
41pub(crate) mod entities;
42pub(crate) mod export;
43pub(crate) mod files;
44pub(crate) mod groups;
45pub(crate) mod history;
46pub(crate) mod holding;
47pub(crate) mod import;
48pub(crate) mod in_use;
49pub(crate) mod json;
50pub(crate) mod languages;
51pub(crate) mod linked_copies;
52pub(crate) mod links;
53pub(crate) mod listing;
54pub(crate) mod media;
55pub(crate) mod members;
56pub(crate) mod merge;
57pub(crate) mod moving;
58pub(crate) mod planner;
59pub(crate) mod policies;
60pub(crate) mod protection;
61pub(crate) mod purge;
62pub(crate) mod recovering;
63pub(crate) mod recovery;
64pub(crate) mod removal;
65pub(crate) mod revocation;
66pub(crate) mod secret_files;
67pub(crate) mod secrets;
68mod secrets_keys;
69pub(crate) mod sources;
70pub(crate) mod spaces;
71pub(crate) mod sync;
72pub(crate) mod taking;
73pub(crate) mod thumbnails;
74pub(crate) mod trees;
75pub(crate) mod verify;
76pub(crate) mod waiting;
77
78/// The file of the library's keys.
79const KEYS: &str = "keys.cbor";
80
81/// The file that says who the library belongs to.
82const INFO: &str = "library.cbor";
83
84/// The file in a library's directory that says that the person asked for its replicas on a
85/// drive without a journal (technical design: drives without a journal).
86const FAT_ALLOWED: &str = "fat-allowed";
87
88/// The folder of a library's replicas, each in a folder of its own, so that two computers
89/// whose libraries a program syncs never write the same file (technical design: copies of a replica).
90const REPLICAS: &str = "replicas";
91
92/// How far ahead of this device's clock a change from another replica may be: ten minutes.
93const MAX_DRIFT_MILLIS: u64 = 600_000;
94
95/// A library, opened: its replica's keys unlocked, and its spaces open.
96pub struct Library {
97	/// The folder of the library's replica that is here.
98	directory: PathBuf,
99	/// The key file, as this library last read or wrote it. A change to it reads it again
100	/// from the disk, under a lock, and so does reading its secrets, as another program may
101	/// have changed it since.
102	key_file: KeyFile,
103	/// The key of the key file's replica compartment, which opens the library again after
104	/// it was closed.
105	compartment: CompartmentKey,
106	/// The key of the key file's secrets compartment, while the secrets are unlocked: it
107	/// unlocks them again when a closed library opens, and protects them anew.
108	secrets_compartment: Option<CompartmentKey>,
109	replica: ReplicaKeys,
110	info: Info,
111	spaces: BTreeMap<SpaceId, Space>,
112	/// The space that the program chose for this session, if it did: new entities go there,
113	/// and entities are looked for there alone ([`Library::choose_space`]).
114	chosen: Option<SpaceId>,
115	/// The types that NibKeep defines in code.
116	code_types: Types,
117	/// The languages that what the library shows is chosen by, read again whenever a
118	/// change may change them.
119	languages: Languages,
120	/// The statements of the personal space that hold the lists of languages.
121	language_statements: BTreeSet<StatementId>,
122	/// The guard of a replica on a drive without a journal, which goes last, once the spaces
123	/// are closed (technical design: drives without a journal).
124	#[expect(dead_code, reason = "held for what it does as it goes")]
125	pub(crate) in_use: Option<in_use::InUse>,
126	/// The latest wall clock time, in milliseconds, that the library was given: the
127	/// computer's when it opened, and each one that a change or a sync was given since. What a
128	/// claim to the admin role gives now depends on it.
129	pub(crate) wall: std::cell::Cell<u64>,
130	/// For each space, the state mark and the wall clock at which this replica last brought
131	/// its account of the space up to date ([`accounts`]).
132	pub(crate) accounts_refreshed: std::cell::RefCell<BTreeMap<SpaceId, (StateMark, u64)>>,
133	/// What reads pictures to make thumbnails, if the program brought it
134	/// ([`Library::make_thumbnails_with`]).
135	pub(crate) thumbnailer: Option<std::sync::Arc<dyn thumbnails::Thumbnailer>>,
136	/// The AI client that the library acts as, if it does ([`Library::act_as_ai_agent`]):
137	/// its key signs the library's changes.
138	pub(crate) acting: Option<agents::Acting>,
139}
140
141/// The computer's wall clock, in milliseconds since the Unix epoch.
142pub(crate) fn wall_clock() -> u64 {
143	std::time::SystemTime::now()
144		.duration_since(std::time::UNIX_EPOCH)
145		.map_or(0, |since| {
146			u64::try_from(since.as_millis()).unwrap_or(u64::MAX)
147		})
148}
149
150/// Who and where a new library starts: the user's name, and the person's, the user's own
151/// entity among the people, if it differs; this device's name, and the name of the app that
152/// keeps the replica; and the languages the user reads, ranked.
153#[derive(Clone, Debug, PartialEq, Eq)]
154pub struct NewLibrary<'a> {
155	/// The user's name.
156	pub user: &'a str,
157	/// The name of the person the user is, if not the user's, such as a full name beside an
158	/// account's name.
159	pub person: Option<&'a str>,
160	/// This device's name.
161	pub device: &'a str,
162	/// The app's name, which the replica gets.
163	pub app: &'a str,
164	/// The languages the user reads, ranked; none if empty.
165	pub languages: Languages,
166}
167
168impl<'a> NewLibrary<'a> {
169	/// A new library for a user on a device, kept by an app, without languages.
170	#[must_use]
171	pub fn new(user: &'a str, device: &'a str, app: &'a str) -> Self {
172		Self {
173			user,
174			person: None,
175			device,
176			app,
177			languages: Languages::default(),
178		}
179	}
180
181	/// The same, with the person the user is named apart from the user, if a name is given.
182	#[must_use]
183	pub fn with_person(mut self, person: Option<&'a str>) -> Self {
184		self.person = person;
185		self
186	}
187
188	/// The same, with the languages the user reads.
189	#[must_use]
190	pub fn with_languages(mut self, languages: Languages) -> Self {
191		self.languages = languages;
192		self
193	}
194}
195
196/// A space of the library, open.
197pub(crate) struct Space {
198	stored: StoredLog,
199	keys: SpaceKeys,
200	/// Whether it is a group, as its first change says, once read.
201	group: std::cell::Cell<Option<bool>>,
202	/// The types of the space: those in code, combined with those that the space defines.
203	/// Read when the space is opened, and again whenever a change touches what defines
204	/// them, as reading them goes through every definition.
205	types: Types,
206}
207
208/// What a library holds, as a person would want to know.
209#[derive(Clone, Debug, PartialEq, Eq)]
210pub struct Status {
211	/// The user the library belongs to, named as history names them: by the person linked
212	/// to the user in the personal space, or else by the user's own name.
213	pub user: Described,
214	/// This device.
215	pub device: Described,
216	/// The replica that the library is.
217	pub replica: Described,
218	/// The spaces, the personal space first, then in the order of their IDs.
219	pub spaces: Vec<SpaceStatus>,
220}
221
222/// Where a space's state stands: [`Library::state_mark`]. Two marks of one library are the
223/// same only while neither space took in anything between them.
224#[derive(Clone, Debug, PartialEq, Eq)]
225pub struct StateMark {
226	space: SpaceId,
227	/// The space's mark and the personal space's: the sequence and tag of the last row of
228	/// the log file that each state file covers.
229	marks: [Option<(i64, Vec<u8>)>; 2],
230}
231
232/// An entity and its name.
233#[derive(Clone, Debug, PartialEq, Eq)]
234pub struct Described {
235	/// The entity.
236	pub id: EntityId,
237	/// Its name, if it has one.
238	pub name: Option<String>,
239}
240
241/// What a space holds.
242#[derive(Clone, Debug, PartialEq, Eq)]
243pub struct SpaceStatus {
244	/// The space.
245	pub id: SpaceId,
246	/// Its name, if it has one.
247	pub name: Option<String>,
248	/// How many entities it holds, deleted ones and those merged into others aside.
249	pub entities: usize,
250	/// How many changes its log holds.
251	pub changes: usize,
252	/// Whether this replica's member left it or was removed: it keeps what it holds there,
253	/// read only.
254	pub left: bool,
255}
256
257/// Who made a change, as far as the space knows.
258#[derive(Clone, Debug, PartialEq, Eq)]
259pub struct Author {
260	/// The user, named as history names them: by the person linked to the user in the
261	/// space, or else by the user's own name.
262	pub user: Described,
263	/// The person linked to the user in the space, if any.
264	pub person: Option<EntityId>,
265	/// The replica that signed the change.
266	pub replica: EntityId,
267	/// If the replica is an AI agent's, the AI agent's name, which is the replica's: history
268	/// names its changes by the user and the AI agent.
269	pub ai_agent: Option<String>,
270}
271
272/// How long opening a library took.
273#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
274pub struct Opening {
275	/// Unlocking the replica's keys, which a passphrase makes slow on purpose.
276	pub unlock: Duration,
277	/// Opening the spaces: reading their logs, and building their indexes.
278	pub spaces: Duration,
279}
280
281/// What a library's directory holds.
282#[derive(Clone, Debug, PartialEq, Eq)]
283enum Found {
284	/// No replica.
285	Nothing,
286	/// The replica that is here, in its folder: whole, or what is left of making it, keys
287	/// without the library file.
288	Here { folder: PathBuf, whole: bool },
289	/// Only copies: replicas that are not here, or that a program may still be bringing in.
290	Copies,
291	/// Two or more replicas that are here.
292	Several(Vec<PathBuf>),
293}
294
295impl Library {
296	/// Starts a library in a directory that holds none: a new replica, named after the
297	/// app that keeps it, with new keys protected as `protection` says, and the user's
298	/// personal space, founded with the user, a person linked to the user, this device, the
299	/// replica and the space itself, as `new` says. If starting fails, what was written is
300	/// removed, keystore keys included.
301	///
302	/// # Errors
303	///
304	/// Returns an error if a name is empty, if the directory holds a library already, or if
305	/// the keys or the space cannot be saved.
306	pub fn create(
307		directory: &Path,
308		new: &NewLibrary<'_>,
309		protection: &NewProtection<'_>,
310		wall_millis: u64,
311		rng: &mut impl CryptoRng,
312	) -> Result<Self, NodeError> {
313		// Every name is written in full, so an empty one is refused before anything is made.
314		if new.user.is_empty()
315			|| new.person.is_some_and(str::is_empty)
316			|| new.device.is_empty()
317			|| new.app.is_empty()
318		{
319			return Err(NodeError::EmptyName);
320		}
321		// Copies of another library's replicas are left alone, and no library is started
322		// among them.
323		if found(directory) == Found::Copies {
324			return Err(NodeError::Copied);
325		}
326		let folder = new_replica_folder(directory, wall_millis, rng)?;
327		let in_use = in_use::InUse::take(&folder)?;
328		let directory = folder.as_path();
329		let keys_path = directory.join(KEYS);
330		let personal = SpaceId::random(rng);
331		let replica = ReplicaKeys {
332			signing: SigningKey::generate(rng),
333			decryption: DecryptionKey::generate(rng),
334			storage: Key::generate(rng),
335			spaces: BTreeMap::from([(personal, BTreeMap::from([(0, Key::generate(rng))]))]),
336		};
337		let (mut key_file, compartment) = match KeyFile::create(&replica, protection, rng) {
338			Ok(created) => created,
339			Err(error) => {
340				drop(in_use);
341				let _ = fs::remove_dir_all(directory);
342				return Err(error.into());
343			}
344		};
345		let code_types = code_types();
346		let started = New {
347			directory,
348			replica: &replica,
349			personal,
350			library: new,
351			code_types: &code_types,
352		};
353		let started = start(&started, &mut key_file, wall_millis, rng).and_then(|(info, space)| {
354			let (settings, statements) = languages::read_lists(space.stored.log().state(), &info)?;
355			Ok((info, space, settings.in_use(), statements))
356		});
357		match started {
358			Ok((info, space, languages, language_statements)) => Ok(Self {
359				directory: directory.to_owned(),
360				key_file,
361				compartment,
362				secrets_compartment: None,
363				replica,
364				info,
365				spaces: BTreeMap::from([(personal, space)]),
366				chosen: None,
367				code_types,
368				languages,
369				language_statements,
370				in_use,
371				wall: std::cell::Cell::new(wall_clock()),
372				accounts_refreshed: std::cell::RefCell::new(BTreeMap::new()),
373				acting: None,
374				thumbnailer: None,
375			})
376			.map(|mut library| {
377				// A phone asks before it takes a space given to it later, as the person may
378				// change there; if saying so fails, it takes them, as a computer does
379				// ([technical design](../../../docs/Technical-design.md#1310-devices-that-choose-their-spaces)).
380				if cfg!(any(target_os = "android", target_os = "ios")) {
381					let _ = library.set_takes_new_spaces(false, wall_millis, rng);
382					library.end_bursts();
383				}
384				library
385			}),
386			Err(error) => {
387				drop(in_use);
388				let _ = fs::remove_file(&keys_path);
389				let _ = fs::remove_dir_all(directory);
390				key_file.discard();
391				Err(error)
392			}
393		}
394	}
395
396	/// Whether the directory holds a library: a replica that is here, what is left of
397	/// starting one, or copies of replicas made elsewhere.
398	#[must_use]
399	pub fn exists(directory: &Path) -> bool {
400		found(directory) != Found::Nothing
401	}
402
403	/// Deletes a library's directory from this device, with the keys of its replicas that
404	/// the platform's keystore keeps: for one that the person replaces, as a phone's app,
405	/// which keeps one library, does as it joins another. No program may have it open.
406	/// What other devices hold of it stays there.
407	///
408	/// # Errors
409	///
410	/// Returns an error if the directory cannot be removed. A key that the keystore does not
411	/// delete stays there.
412	pub fn discard(directory: &Path) -> Result<(), NodeError> {
413		for entry in fs::read_dir(directory.join(REPLICAS))
414			.into_iter()
415			.flatten()
416			.flatten()
417		{
418			if let Ok(key_file) = KeyFile::read(&entry.path().join(KEYS)) {
419				key_file.discard();
420			}
421		}
422		match fs::remove_dir_all(directory) {
423			Err(error) if error.kind() != std::io::ErrorKind::NotFound => {
424				Err(NodeError::file(directory)(error))
425			}
426			_ => Ok(()),
427		}
428	}
429
430	/// The folder, in a library's directory, of its replica that is here, whole or not.
431	///
432	/// # Errors
433	///
434	/// Returns an error if the directory holds no library, only copies, or several
435	/// replicas that are here.
436	pub fn replica_folder(directory: &Path) -> Result<PathBuf, NodeError> {
437		match found(directory) {
438			Found::Nothing => Err(NodeError::NoLibrary),
439			Found::Here { folder, .. } => Ok(folder),
440			Found::Copies => Err(NodeError::Copied),
441			Found::Several(folders) => Err(NodeError::SeveralHere(folders)),
442		}
443	}
444
445	/// Whether a new replica of a library can be made in `directory`, as making, joining or
446	/// adding it from a copy would find, so that a program can tell before it asks the person
447	/// for anything: not on a network drive, nor in a folder that a program takes to the
448	/// cloud, nor on a drive without a journal unless the person allowed it.
449	///
450	/// # Errors
451	///
452	/// Returns [`NodeError::RemoteDrive`], [`NodeError::CloudFolder`] or
453	/// [`NodeError::NoJournal`].
454	pub fn check_place(directory: &Path) -> Result<(), NodeError> {
455		let drive = place::whereabouts(directory).drive;
456		local(&drive)?;
457		journal(&drive, directory)
458	}
459
460	/// Allows the replicas of the library in `directory` on a drive without a journal, as FAT
461	/// and exFAT, where a removal without unmounting can damage them later, as the person
462	/// asked: they are then guarded, and a drive removed while one was open is checked
463	/// before it is used again (technical design: drives without a journal).
464	///
465	/// # Errors
466	///
467	/// Returns [`NodeError::RemoteDrive`] or [`NodeError::CloudFolder`] for a folder that
468	/// holds no library, before anything is written there, or an error if the file that says
469	/// so cannot be written.
470	pub fn allow_fat(directory: &Path) -> Result<(), NodeError> {
471		check_local(directory)?;
472		fs::create_dir_all(directory).map_err(NodeError::file(directory))?;
473		let path = directory.join(FAT_ALLOWED);
474		fs::write(&path, b"").map_err(NodeError::file(&path))
475	}
476
477	/// Says that the drive of the library in `directory` was checked, as by `fsck` or
478	/// Windows' "Scan and fix", after it was removed, or lost its power, while the library
479	/// was open: the library opens again. The caller then verifies it, as
480	/// [`Library::verify`] does, before it is used (technical design: drives without a journal).
481	///
482	/// # Errors
483	///
484	/// Returns an error if the directory holds no replica here, or the guard's files cannot
485	/// be written.
486	pub fn drive_checked(directory: &Path) -> Result<(), NodeError> {
487		let folder = Self::replica_folder(directory)?;
488		// A replica that a later version changed is left as it is.
489		engines::check(&folder)?;
490		in_use::checked(&folder)
491	}
492
493	/// How the library's keys are protected, so that an app knows whether to ask for a
494	/// passphrase before it opens the library.
495	///
496	/// # Errors
497	///
498	/// Returns an error if the directory holds no library, one whose start was cut short,
499	/// or only copies, or its key file is damaged, and [`NodeError::UncleanRemoval`] if its
500	/// drive must be checked before it opens, so that nothing is asked for in vain.
501	pub fn protection(directory: &Path) -> Result<Protection, NodeError> {
502		let (folder, key_file) = read_key_file(directory)?;
503		if in_use::removed(&folder)? {
504			return Err(NodeError::UncleanRemoval);
505		}
506		Ok(key_file.replica_protection().clone())
507	}
508
509	/// Opens a library: unlocks the replica's keys, and opens every space.
510	///
511	/// # Errors
512	///
513	/// Returns an error if the directory holds no library, or one whose start was cut
514	/// short, `unlocker` does not unlock it, or a space cannot be opened.
515	pub fn open(directory: &Path, unlocker: &Unlocker<'_>) -> Result<Self, NodeError> {
516		Self::open_timed(directory, unlocker).map(|(library, _)| library)
517	}
518
519	/// Opens a library as [`Library::open`] does, and tells how long its two parts took.
520	///
521	/// # Errors
522	///
523	/// As [`Library::open`].
524	pub fn open_timed(
525		directory: &Path,
526		unlocker: &Unlocker<'_>,
527	) -> Result<(Self, Opening), NodeError> {
528		let started = Instant::now();
529		check_local(directory)?;
530		let (folder, key_file) = read_key_file(directory)?;
531		let compartment = key_file.unlock_replica(unlocker)?;
532		// What a recovery in place that is done left: the old replica to set aside.
533		recovering::tidy(&folder);
534		let keys_unlocked = Instant::now();
535		let library = Self::open_unlocked(&folder, key_file, compartment)?;
536		Ok((
537			library,
538			Opening {
539				unlock: keys_unlocked - started,
540				spaces: keys_unlocked.elapsed(),
541			},
542		))
543	}
544
545	/// The library's directory, as [`Library::open`] takes it: the folder that holds its
546	/// replicas.
547	#[must_use]
548	pub fn library_directory(&self) -> Option<&Path> {
549		library_directory(&self.directory)
550	}
551
552	/// Closes the library, and keeps its replica's keys unlocked, and its secrets if they
553	/// are, so that it opens again without a passphrase: for a program that waits for other
554	/// replicas, or an app that opens the library for each operation, which should hold no
555	/// lock on the spaces in between.
556	#[must_use]
557	pub fn close(self) -> Closed {
558		Closed {
559			directory: self.directory,
560			compartment: self.compartment,
561			secrets: self.secrets_compartment,
562		}
563	}
564
565	/// Opens a library whose replica compartment `compartment` unlocks.
566	fn open_unlocked(
567		directory: &Path,
568		key_file: KeyFile,
569		compartment: CompartmentKey,
570	) -> Result<Self, NodeError> {
571		let mut library = Self::open_spaces(directory, key_file, compartment, false)?;
572		// Once the replica is marked open, on a drive without a journal. A program that cannot
573		// write the file, as while another program holds it for a moment, opens all the same,
574		// and records itself the next time; a later version or a damaged file do not open.
575		match engines::record(directory, wall_clock()) {
576			Ok(()) | Err(NodeError::File { .. }) => {}
577			Err(error) => return Err(error),
578		}
579		library.finish_opening()?;
580		Ok(library)
581	}
582
583	/// Opens a library's spaces, and with `empty`, makes those whose logs are missing, as
584	/// the private copy of a copy of a replica does before it takes in what the copy holds.
585	/// [`Library::finish_opening`] comes next, once the spaces hold their changes.
586	pub(crate) fn open_spaces(
587		directory: &Path,
588		key_file: KeyFile,
589		compartment: CompartmentKey,
590		empty: bool,
591	) -> Result<Self, NodeError> {
592		let in_use = in_use::InUse::take(directory)?;
593		let info = Info::read(&directory.join(INFO))?;
594		let replica = key_file.replica(&compartment)?;
595		let code_types = code_types();
596		let mut spaces = BTreeMap::new();
597		for (&id, epochs) in &replica.spaces {
598			let log = log_path(directory, id);
599			if !empty && !log.exists() {
600				return Err(NodeError::Damaged(format!(
601					"the log of the space {id} is missing"
602				)));
603			}
604			spaces.insert(
605				id,
606				Space::open(&log, id, epochs, &replica.storage, &code_types)?,
607			);
608		}
609		if !spaces.contains_key(&info.personal) {
610			return Err(NodeError::Damaged(
611				"the keys of the personal space are missing".to_owned(),
612			));
613		}
614		Ok(Self {
615			directory: directory.to_owned(),
616			key_file,
617			compartment,
618			secrets_compartment: None,
619			replica,
620			info,
621			spaces,
622			chosen: None,
623			code_types,
624			languages: Languages::default(),
625			language_statements: BTreeSet::new(),
626			in_use,
627			wall: std::cell::Cell::new(wall_clock()),
628			accounts_refreshed: std::cell::RefCell::new(BTreeMap::new()),
629			acting: None,
630			thumbnailer: None,
631		})
632	}
633
634	/// Reads what opening reads once the spaces hold their changes: the lists of languages,
635	/// and the keys that the replica writes with.
636	pub(crate) fn finish_opening(&mut self) -> Result<(), NodeError> {
637		self.refresh_languages()?;
638		// A device that waits keeps what purges destroy before anything can purge here.
639		let now = wall_clock();
640		self.refresh_wait(now)?;
641		self.expect_space_roots()?;
642		// What a power cut left of the deletion of a dropped space, once its key went.
643		self.finish_cut_short_drops();
644		// Each space follows its groups before it takes or makes a change; one that cannot keeps
645		// the library from opening no more than any unreadable space does, and the next sync
646		// tries again. Then the groups say which first change each space that lacks one takes.
647		let _ = self.follow_all_groups();
648		let _ = self.expect_roots_from_groups();
649		self.choose_writing_keys()?;
650		// What a restore brought back whose giving back a crash cut short.
651		let _ = self.take_back_restored(now, true);
652		Ok(())
653	}
654
655	/// Reads the times that tell bursts of changes apart from `ticks`, in every space it has
656	/// open, instead of the system's monotonic clock, as [`StoredLog::set_ticks`] does: tests
657	/// give a clock of their own, so that the same changes form the same bursts on every
658	/// machine.
659	pub fn set_ticks(&mut self, ticks: &Ticks) {
660		for space in self.spaces.values_mut() {
661			space.stored.set_ticks(ticks.clone());
662		}
663	}
664
665	/// The user's personal space.
666	#[must_use]
667	pub const fn personal_space(&self) -> SpaceId {
668		self.info.personal
669	}
670
671	/// The fields whose values are secret in a space: those that the types of NibKeep, of
672	/// apps or of the space mark as secret, those that statements governing the space make
673	/// secret for good, and those that the standard vocabulary makes secret, in every space
674	/// ([Data model](../../../docs/spec/model.md#9-secret-fields)). Whether a field is
675	/// secret is decided here, not by a type's own definition of it.
676	#[must_use]
677	pub fn secret_fields(&self, space: SpaceId) -> Option<&BTreeSet<FieldName>> {
678		self.spaces
679			.get(&space)
680			.map(|space| space.stored.secret_fields())
681	}
682
683	/// The fields that these types of a space list and that are secret there, as
684	/// [`Library::secret_fields`] says, ordered by name: those whose values an entity of the
685	/// types may hold sealed. A type of the standard vocabulary that the space does not define
686	/// lists its fields as the vocabulary does.
687	///
688	/// # Errors
689	///
690	/// Returns an error if the library has no such space.
691	pub fn secret_fields_of(
692		&self,
693		space: SpaceId,
694		types: &[nibkeep_model::TypeName],
695	) -> Result<Vec<FieldName>, NodeError> {
696		let open = self.space(space)?;
697		let secret = open.stored.secret_fields();
698		let vocabulary = nibkeep_std::types();
699		let listed: BTreeSet<&FieldName> = types
700			.iter()
701			.filter_map(|name| {
702				open.types.get(name).or_else(|| {
703					vocabulary
704						.iter()
705						.find(|definition| definition.name() == name)
706				})
707			})
708			.flat_map(TypeDef::fields)
709			.map(|(field, _)| field)
710			.filter(|field| secret.contains(*field))
711			.collect();
712		Ok(listed.into_iter().cloned().collect())
713	}
714
715	/// The types of a space: those that NibKeep defines, combined with those of the space.
716	///
717	/// # Errors
718	///
719	/// Returns an error if the library has no such space.
720	pub fn types(&self, space: SpaceId) -> Result<Types, NodeError> {
721		Ok(self.space(space)?.types.clone())
722	}
723
724	/// Defines a type in a space, or adds to it what the space's types lack, as
725	/// [`Types::define_in`] says, after [`Types::check`] found nothing wrong with it. Returns
726	/// the space's types afterwards.
727	///
728	/// # Errors
729	///
730	/// Returns an error if the library has no such space, the definition cannot be added as
731	/// it is, or the change cannot be saved.
732	pub fn define_type(
733		&mut self,
734		space: SpaceId,
735		definition: &TypeDef,
736		wall_millis: u64,
737		rng: &mut impl CryptoRng,
738	) -> Result<Types, NodeError> {
739		self.define_lacking(space, definition, wall_millis, rng)?;
740		self.types(space)
741	}
742
743	/// Adds to a space what its types lack of a definition, as [`Library::define_type`] does,
744	/// and returns how many statements of definitions it wrote: none if they lack nothing.
745	pub(crate) fn define_lacking(
746		&mut self,
747		space: SpaceId,
748		definition: &TypeDef,
749		wall_millis: u64,
750		rng: &mut impl CryptoRng,
751	) -> Result<usize, NodeError> {
752		let (operations, defined) = {
753			let open = self.space(space)?;
754			let types = &open.types;
755			types.check(definition)?;
756			let mut operations = types.define_in(definition, open.stored.log().state(), rng)?;
757			if operations.is_empty() {
758				return Ok(0);
759			}
760			let defined = operations.len();
761			// The fields it makes secret are secret for good, which governs the space.
762			let secret = definition
763				.fields()
764				.filter(|(_, field)| field.is_secret())
765				.map(|(name, _)| name.clone());
766			let own = self.own_record(space)?;
767			operations.extend(open.secret_marks(&self.code_types, (own, secret), rng)?);
768			(operations, defined)
769		};
770		self.commit(space, operations, wall_millis, rng)?;
771		Ok(defined)
772	}
773
774	/// States, in a change that governs the space, that the fields its types make secret are
775	/// secret for good, where no counting statement says so yet, as for types that an older
776	/// copy of NibKeep defined.
777	///
778	/// # Errors
779	///
780	/// Returns an error if the library has no such space, or the change cannot be saved.
781	pub(crate) fn mark_secret_fields(
782		&mut self,
783		space: SpaceId,
784		wall_millis: u64,
785		rng: &mut impl CryptoRng,
786	) -> Result<(), NodeError> {
787		let own = self.own_record(space)?;
788		let open = self.space(space)?;
789		let secret = open.types.secret_fields();
790		let operations = open.secret_marks(&self.code_types, (own, secret), rng)?;
791		if operations.is_empty() {
792			return Ok(());
793		}
794		self.commit(space, operations, wall_millis, rng)
795	}
796
797	/// What the library holds.
798	///
799	/// # Errors
800	///
801	/// Returns an error if a space cannot be read.
802	pub fn status(&self) -> Result<Status, NodeError> {
803		let (user, device) = self.user_and_device()?;
804		let mut spaces = Vec::new();
805		for (&id, space) in &self.spaces {
806			spaces.push(space.status(
807				id,
808				&self.languages,
809				&self.replica.signing.verifying_key(),
810			)?);
811		}
812		spaces.sort_by_key(|space| (space.id != self.info.personal, space.id));
813		Ok(Status {
814			user,
815			device,
816			replica: self.described(self.info.replica)?,
817			spaces,
818		})
819	}
820
821	/// The user the library belongs to and this device, named as [`Library::status`] names
822	/// them, without counting what the spaces hold, which costs much more in a large
823	/// library.
824	///
825	/// # Errors
826	///
827	/// Returns an error if the personal space cannot be read.
828	pub fn user_and_device(&self) -> Result<(Described, Described), NodeError> {
829		let personal = &self.spaces[&self.info.personal];
830		let state = personal.stored.log().state();
831		let user = Described {
832			id: self.info.user,
833			name: user_name(state, &personal.types, &self.languages, self.info.user)?.0,
834		};
835		Ok((user, self.described(self.info.device)?))
836	}
837
838	/// An entity of the personal space with the name to show for it.
839	fn described(&self, entity: EntityId) -> Result<Described, NodeError> {
840		let personal = &self.spaces[&self.info.personal];
841		Ok(Described {
842			id: entity,
843			name: entities::display_name(
844				personal.stored.log().state(),
845				&personal.types,
846				&self.languages,
847				entity,
848			)?,
849		})
850	}
851
852	/// Where a space's state stands, and the personal space's, whose lists of languages
853	/// name entities: how far into its log file each state file goes. It moves whenever
854	/// either space takes in anything, here or in another program, so a program may keep
855	/// what it worked out from the space while the mark stays the same, as an app
856	/// keeps a long list while a person pages through it.
857	///
858	/// # Errors
859	///
860	/// Returns an error if the library has no such space, or a state file cannot be read.
861	pub fn state_mark(&self, space: SpaceId) -> Result<StateMark, NodeError> {
862		let mark = |space: SpaceId| -> Result<_, NodeError> {
863			let open = self.space(space)?;
864			Ok(open
865				.stored
866				.log()
867				.state()
868				.storage()
869				.ordinary()
870				.mark()?
871				.map(|mark| (mark.sequence, mark.tag)))
872		};
873		Ok(StateMark {
874			space,
875			marks: [mark(space)?, mark(self.info.personal)?],
876		})
877	}
878
879	/// Who made the change that asserted a statement of a space: the replica whose key
880	/// signed it, and the user it belongs to, as the space says. `None` if the space holds
881	/// no such statement, or no replica of the space that is not deleted has the key that
882	/// signed it now, or that replica has no owner.
883	///
884	/// # Errors
885	///
886	/// Returns an error if the library has no such space, or the space cannot be read.
887	pub fn author_of(
888		&self,
889		space: SpaceId,
890		statement: StatementId,
891	) -> Result<Option<Author>, NodeError> {
892		let open = self.space(space)?;
893		open.stored.reading(|stored| {
894			let Some(key) = stored.log().author_of(statement)? else {
895				return Ok(None);
896			};
897			self.author_with_key(open, stored, &key)
898		})
899	}
900
901	/// Who holds a signing key in a space, as [`Library::author_of`] names them.
902	pub(crate) fn author_with_key(
903		&self,
904		open: &Space,
905		stored: &StoredLog,
906		key: &nibkeep_crypto::VerifyingKey,
907	) -> Result<Option<Author>, NodeError> {
908		let author = Self::author_in(open, stored, stored.log().state(), key, &self.languages)?;
909		if author.is_some() || !stored.log().has_members(&open.keys)? {
910			return Ok(author);
911		}
912		// A member through a group, at any level, is named as the group on their path names
913		// them, where this replica holds its log.
914		let Some((group, user)) = stored.log().group_member_of(key, &open.keys)? else {
915			return Ok(None);
916		};
917		let Some(in_group) = self.spaces.get(&group) else {
918			return Ok(None);
919		};
920		let state = in_group.stored.log().state();
921		let name = entities::display_name(state, &in_group.types, &self.languages, user)?;
922		Ok(Some(Author {
923			user: Described { id: user, name },
924			person: None,
925			replica: nibkeep_governance::replica_record(stored.log().space(), key),
926			ai_agent: None,
927		}))
928	}
929
930	/// Who holds a signing key in a space, named as a state gives them, for a reader of
931	/// `languages`.
932	pub(crate) fn author_in<S: nibkeep_model::storage::Statements>(
933		open: &Space,
934		stored: &StoredLog,
935		state: &State<S>,
936		key: &nibkeep_crypto::VerifyingKey,
937		languages: &Languages,
938	) -> Result<Option<Author>, NodeError>
939	where
940		NodeError: From<S::Error>,
941	{
942		let key_of = key;
943		let key = Value::Text(key.to_text());
944		// Of replicas that claim one key, which only a faulty replica makes, the first by ID
945		// counts, so that every replica names the same author. What the state says of a
946		// replica's key and owner can be taken away, as an AI agent's change may: the
947		// governing changes that count say it all the same.
948		// In a space with members, another member's governing change may state anyone's key
949		// on a record of its own, so only what the counting listings say names the author,
950		// and a link to a person names them only once an admin and they agree on it.
951		if stored.log().has_members(&open.keys)? {
952			let (_, owners) = members::users_and_owners(stored, &open.keys)?;
953			let Some(&user) = owners.get(key_of.as_bytes()) else {
954				return Ok(None);
955			};
956			let replica = nibkeep_governance::replica_record(stored.log().space(), key_of);
957			let roles = stored.log().member_roles(&open.keys)?;
958			let link = members::person_link((stored, state), (&owners, &roles), user)?;
959			let linked = match link.holds {
960				Some(person) => entities::display_name(state, &open.types, languages, person)?,
961				None => None,
962			};
963			let (name, person) = match linked {
964				Some(name) => (Some(name), link.holds),
965				None => (
966					entities::display_name(state, &open.types, languages, user)?,
967					None,
968				),
969			};
970			return Ok(Some(Author {
971				user: Described { id: user, name },
972				person,
973				replica,
974				ai_agent: Self::ai_agent_name(open, stored, state, (key_of, replica), languages)?,
975			}));
976		}
977		let state_replica = stored.find(&SIGNING_KEY, &key)?.first().copied();
978		let state_user = match state_replica {
979			Some(replica) => referred(state, &open.types, languages, replica, &OWNER)?,
980			None => None,
981		};
982		let (replica, user) = match (state_replica, state_user) {
983			(Some(replica), Some(user)) => (replica, user),
984			_ => match governed_record(stored, &open.keys, &key)? {
985				Some(record) => record,
986				None => return Ok(None),
987			},
988		};
989		let (name, person) = user_name(state, &open.types, languages, user)?;
990		let ai_agent = Self::ai_agent_name(open, stored, state, (key_of, replica), languages)?;
991		Ok(Some(Author {
992			user: Described { id: user, name },
993			person,
994			replica,
995			ai_agent,
996		}))
997	}
998}
999
1000impl Library {
1001	/// The AI agent's name, which its replica's is, if a key is an AI agent's.
1002	fn ai_agent_name<S: nibkeep_model::storage::Statements>(
1003		open: &Space,
1004		stored: &StoredLog,
1005		state: &State<S>,
1006		(key, replica): (&nibkeep_crypto::VerifyingKey, EntityId),
1007		languages: &Languages,
1008	) -> Result<Option<String>, NodeError>
1009	where
1010		NodeError: From<S::Error>,
1011	{
1012		if !stored.log().is_ai_agent(key, &open.keys)? {
1013			return Ok(None);
1014		}
1015		let name = entities::display_name(state, &open.types, languages, replica)?;
1016		Ok(Some(name.unwrap_or_else(|| "an AI agent".to_owned())))
1017	}
1018}
1019
1020impl Library {
1021	/// A space of the library.
1022	pub(crate) fn space(&self, space: SpaceId) -> Result<&Space, NodeError> {
1023		self.spaces.get(&space).ok_or(NodeError::NoSpace(space))
1024	}
1025
1026	/// Seals content as a blob of a space, unless the device holds it already, and returns
1027	/// its content hash. Content that another space of the replica holds is not sealed
1028	/// again: the space takes up that copy, once it has read it whole, unless it purged it
1029	/// ([technical design](../../../docs/Technical-design.md#79-blobs)).
1030	///
1031	/// # Errors
1032	///
1033	/// Returns an error if the library has no such space, or reading the content or saving
1034	/// the blob fails.
1035	pub fn import_blob(
1036		&mut self,
1037		space: SpaceId,
1038		content: impl Read,
1039		wall_millis: u64,
1040		rng: &mut impl CryptoRng,
1041	) -> Result<Hash, NodeError> {
1042		self.seal_blob(space, (content, false), wall_millis, rng)
1043	}
1044
1045	/// Seals content as a blob of a space, with a secret key if `secret` says so, unless the
1046	/// space holds it already with a key of that kind; or, if another space of the replica
1047	/// holds a sealed copy with a key of that kind, takes up that copy, the one with the
1048	/// smallest sealed hash first, and wraps its key for the space, once it has read it whole
1049	/// ([technical design: blobs]). A space that purged a copy seals the content anew. An AI
1050	/// agent's replica wraps no keys of other spaces, as it seals nothing.
1051	///
1052	/// [technical design: blobs]: ../../../docs/Technical-design.md#79-blobs
1053	pub(crate) fn seal_blob(
1054		&mut self,
1055		space: SpaceId,
1056		(content, secret): (impl Read, bool),
1057		wall_millis: u64,
1058		rng: &mut impl CryptoRng,
1059	) -> Result<Hash, NodeError> {
1060		// Only with another space is there a copy to take up.
1061		let shares = self.spaces.len() > 1 && !self.is_ai_agent()?;
1062		let mut target = self
1063			.spaces
1064			.remove(&space)
1065			.ok_or(NodeError::NoSpace(space))?;
1066		let others = &self.spaces;
1067		let elsewhere = |content: &Hash| -> Vec<(Hash, Key)> {
1068			if shares {
1069				held_copies_in(others.values(), content, secret)
1070			} else {
1071				Vec::new()
1072			}
1073		};
1074		let sealed = target.stored.import_blob_sharing(
1075			&target.keys,
1076			(content, secret),
1077			&elsewhere,
1078			wall_millis,
1079			rng,
1080		);
1081		self.spaces.insert(space, target);
1082		Ok(sealed?)
1083	}
1084
1085	/// The spaces of the replica besides `space` that keep any of these contents, ordered by
1086	/// ID: those that keep a key, open or not, for a sealed copy that `space` keeps of it
1087	/// with a key of the kind given, secret or ordinary, and those that can read another
1088	/// copy of it with such a key now. A purge in `space` leaves the content to them, as
1089	/// each space destroys only its own keys.
1090	pub(crate) fn spaces_holding(
1091		&self,
1092		space: SpaceId,
1093		contents: &BTreeSet<Hash>,
1094		secret: bool,
1095	) -> Result<Vec<SpaceId>, NodeError> {
1096		let log = self.space(space)?.stored.log();
1097		let sealed: Vec<Hash> = contents
1098			.iter()
1099			.flat_map(|content| log.blob_keys(content))
1100			.filter(|(sealed, _)| log.is_secret_blob(sealed) == secret)
1101			.map(|(sealed, _)| *sealed)
1102			.collect();
1103		Ok(self
1104			.spaces
1105			.iter()
1106			.filter(|(id, open)| {
1107				let other = open.stored.log();
1108				**id != space
1109					&& (sealed
1110						.iter()
1111						.any(|sealed| !other.wrapped_blob_keys_of(sealed).is_empty())
1112						|| contents
1113							.iter()
1114							.any(|content| !open.stored.held_copies(content, secret).is_empty()))
1115			})
1116			.map(|(id, _)| *id)
1117			.collect())
1118	}
1119
1120	/// Runs `run` as a batch of changes to a space, saved together when it returns, which
1121	/// makes many changes quicker to save ([technical design: saving in batches]). Until then, the changes it
1122	/// makes are read as any others, but a crash loses all of them. Whether `run` succeeds or
1123	/// fails, the changes it made to the space that were not refused are saved, and what it
1124	/// returned is returned; if saving fails, none of them is, and that error is returned. If
1125	/// `run` panics, none of them is saved. Changes to other spaces are saved one at a time,
1126	/// unless they are in a batch of their own; a space has one batch open at a time. What
1127	/// writes outside a change, such as importing a blob or a purge, is refused, and so is
1128	/// verifying the library.
1129	/// Each batch holds up the space's other writers until it ends, so it is kept short,
1130	/// such as a thousand changes.
1131	///
1132	/// [technical design: saving in batches]: ../../../docs/Technical-design.md#77-saving-in-batches
1133	///
1134	/// # Errors
1135	///
1136	/// Returns an error if the library has no such space, a batch of the space is open
1137	/// already, or the files fail, and otherwise the error of `run`.
1138	pub fn batch<T>(
1139		&mut self,
1140		space: SpaceId,
1141		run: impl FnOnce(&mut Self) -> Result<T, NodeError>,
1142	) -> Result<T, NodeError> {
1143		self.batch_as(space, false, run)
1144	}
1145
1146	/// Runs `run` as a batch of changes to a space, as [`Library::batch`] does, but saves
1147	/// none of them if `run` fails: for what must be all or nothing, such as a move of files
1148	/// in a tree, whose copies are moved already.
1149	pub(crate) fn batch_whole<T>(
1150		&mut self,
1151		space: SpaceId,
1152		run: impl FnOnce(&mut Self) -> Result<T, NodeError>,
1153	) -> Result<T, NodeError> {
1154		self.batch_as(space, true, run)
1155	}
1156
1157	fn batch_as<T>(
1158		&mut self,
1159		space: SpaceId,
1160		whole: bool,
1161		run: impl FnOnce(&mut Self) -> Result<T, NodeError>,
1162	) -> Result<T, NodeError> {
1163		let open = self
1164			.spaces
1165			.get_mut(&space)
1166			.ok_or(NodeError::NoSpace(space))?;
1167		let reloads = open.stored.reloads();
1168		open.stored.begin_batch(&open.keys)?;
1169		// The batch began on what others wrote, as it caught up: the changes in it are made
1170		// with the space's types as they are now.
1171		if open.stored.reloads() != reloads
1172			&& let Err(error) = self.read_again(space)
1173		{
1174			if let Some(open) = self.spaces.get_mut(&space) {
1175				open.stored.abandon_batch();
1176			}
1177			return Err(error);
1178		}
1179		let ran = catch_unwind(AssertUnwindSafe(|| run(self)));
1180		let ended = match (&ran, self.spaces.get_mut(&space)) {
1181			(Ok(Ok(_)), Some(open)) => open.stored.end_batch(),
1182			(Ok(Err(_)), Some(open)) if !whole => open.stored.end_batch(),
1183			(_, Some(open)) => {
1184				open.stored.abandon_batch();
1185				Err(StoreError::BatchLost)
1186			}
1187			(_, None) => Err(StoreError::BatchLost),
1188		};
1189		if ended.is_err() {
1190			// What was read of the batch's changes went with them. Reading it again fails only
1191			// when the storage does, which the batch's error tells already.
1192			let _ = self.read_again(space);
1193		}
1194		match (ran, ended) {
1195			(Err(panic), _) => resume_unwind(panic),
1196			(Ok(Err(error)), Err(StoreError::BatchLost)) => Err(error),
1197			(Ok(_), Err(error)) => Err(error.into()),
1198			(Ok(result), Ok(())) => result,
1199		}
1200	}
1201
1202	/// Whether this replica is an AI agent's: whether the change that listed its key in the
1203	/// personal space marks it so ([technical design](../../../docs/Technical-design.md#14-ai-agents)).
1204	///
1205	/// # Errors
1206	///
1207	/// Returns an error if the personal space cannot be read.
1208	pub fn is_ai_agent(&self) -> Result<bool, NodeError> {
1209		let open = self.space(self.info.personal)?;
1210		let own = self.author_key().verifying_key();
1211		Ok(open.stored.log().is_ai_agent(&own, &open.keys)?)
1212	}
1213
1214	/// Refuses, with [`NodeError::AiAgentMayNot`] and `what`, if this replica is an AI agent's,
1215	/// before an app asks for more, such as pairing a device.
1216	///
1217	/// # Errors
1218	///
1219	/// Returns [`NodeError::AiAgentMayNot`] if this replica is an AI agent's, and an error if
1220	/// the personal space cannot be read.
1221	pub fn check_not_ai_agent(&self, what: &'static str) -> Result<(), NodeError> {
1222		if self.is_ai_agent()? {
1223			return Err(NodeError::AiAgentMayNot(what));
1224		}
1225		Ok(())
1226	}
1227
1228	/// Returns [`NodeError::Revoked`] if this replica was revoked in a space,
1229	/// [`NodeError::NotListed`] if no counting change lists it, and [`NodeError::Removed`] if
1230	/// its member left the space or was removed, or it is an AI agent's where the space
1231	/// allows none: the space would set aside any change of its.
1232	pub(crate) fn check_not_revoked(&self, space: SpaceId) -> Result<(), NodeError> {
1233		let open = self.space(space)?;
1234		let log = open.stored.log();
1235		let own = self.author_key().verifying_key();
1236		if log.is_revoked(&own, &open.keys)? {
1237			return Err(NodeError::Revoked);
1238		}
1239		if !log.is_listed(&own, &open.keys)? {
1240			return Err(NodeError::NotListed);
1241		}
1242		if log.is_removed(&own, &open.keys)? {
1243			return Err(NodeError::Removed);
1244		}
1245		Ok(())
1246	}
1247
1248	/// Whether this replica's member left a shared space or was removed from it, or, for an
1249	/// AI agent's replica, the space allows AI agents no more: it then keeps what it holds
1250	/// there, read only, and gets nothing added after. Never for the personal space.
1251	///
1252	/// # Errors
1253	///
1254	/// Returns an error if the space cannot be read.
1255	pub fn has_left(&self, space: SpaceId) -> Result<bool, NodeError> {
1256		let open = self.space(space)?;
1257		Ok(open
1258			.stored
1259			.log()
1260			.is_removed(&self.author_key().verifying_key(), &open.keys)?)
1261	}
1262
1263	/// The role that this replica's user has in a space now, which says what they may do
1264	/// there, as an app shows it: admin in the personal space; in a shared space, the role
1265	/// that its counting governing changes give this replica, through its member directly or
1266	/// through groups, or admin by a claim of theirs that took effect by the latest wall clock
1267	/// time the library was given; none while this replica is not listed there or holds
1268	/// nothing of the space yet, and once it is revoked, or its member left or was removed.
1269	///
1270	/// # Errors
1271	///
1272	/// Returns [`NodeError::NoSpace`] if the library holds no such space, and an error if it
1273	/// cannot be read.
1274	pub fn own_role(&self, space: SpaceId) -> Result<MemberRole, NodeError> {
1275		if space == self.info.personal {
1276			return Ok(MemberRole::Admin);
1277		}
1278		let own = self.author_key().verifying_key();
1279		let role = {
1280			let open = self.space(space)?;
1281			let log = open.stored.log();
1282			// A space other than the personal one has members, unless this replica holds
1283			// nothing of it yet.
1284			let Some(role) = log.key_role(&own, &open.keys)? else {
1285				return Ok(MemberRole::None);
1286			};
1287			if log.is_revoked(&own, &open.keys)? || log.is_removed(&own, &open.keys)? {
1288				return Ok(MemberRole::None);
1289			}
1290			role
1291		};
1292		if role == MemberRole::Editor
1293			&& let Some(member) = self.member_in(space)?
1294			&& self.claim_now(space, member)?.is_some()
1295		{
1296			return Ok(MemberRole::Admin);
1297		}
1298		Ok(role)
1299	}
1300
1301	/// Reads again what the library keeps of a space in memory, from what was stored: its
1302	/// types, and for the personal space, the languages.
1303	fn read_again(&mut self, space: SpaceId) -> Result<(), NodeError> {
1304		let open = self
1305			.spaces
1306			.get_mut(&space)
1307			.ok_or(NodeError::NoSpace(space))?;
1308		open.read_types(&self.code_types)?;
1309		if space == self.info.personal {
1310			self.refresh_languages()?;
1311		}
1312		Ok(())
1313	}
1314
1315	/// The folder of the library's replica.
1316	#[must_use]
1317	pub fn directory(&self) -> &Path {
1318		&self.directory
1319	}
1320
1321	/// A key derived from the replica's storage key with `context`, for a file of the
1322	/// replica's own beside its spaces.
1323	pub(crate) fn derived_key(&self, context: &'static str) -> nibkeep_crypto::Key {
1324		self.replica.storage.derive(context)
1325	}
1326
1327	/// How many changes the replica keeps, in all its spaces: what grows when changes come
1328	/// into it, made here or received.
1329	///
1330	/// # Errors
1331	///
1332	/// Returns an error if a log cannot be read.
1333	pub fn changes_kept(&self) -> Result<usize, NodeError> {
1334		self.spaces
1335			.values()
1336			.try_fold(0, |sum, space| Ok(sum + space.stored.log().kept()?))
1337	}
1338
1339	/// Catches up with what other programs, or other libraries of the replica open in this
1340	/// one, wrote to it since this one last read it ([technical design: several programs on one replica]): reads again what
1341	/// it keeps of each space in memory, such as its types, from each space that another
1342	/// wrote to. A change catches up by itself before it is made; a program that keeps the
1343	/// library open catches up before it reads what it keeps. Returns whether another wrote.
1344	///
1345	/// [technical design: several programs on one replica]: ../../../docs/Technical-design.md#78-several-programs-on-one-replica
1346	///
1347	/// # Errors
1348	///
1349	/// Returns [`NodeError::in_use`] errors if a space's state file must be made anew while
1350	/// another program has it open: the library is to be closed, and opened again later.
1351	pub fn catch_up(&mut self) -> Result<bool, NodeError> {
1352		let added = self.catch_up_spaces()?;
1353		let mut caught_up = added;
1354		let spaces: Vec<SpaceId> = self.spaces.keys().copied().collect();
1355		for space in spaces {
1356			caught_up |= self.catch_up_space(space)?;
1357		}
1358		// Once the personal space and the groups hold the entries that gave the spaces another
1359		// program added, as when the library opens.
1360		if added {
1361			let expected = self.expect_space_roots();
1362			let _ = self.expect_roots_from_groups();
1363			expected?;
1364		}
1365		Ok(caught_up)
1366	}
1367
1368	/// Catches up with what others wrote to a space, as [`Library::catch_up`] does.
1369	fn catch_up_space(&mut self, space: SpaceId) -> Result<bool, NodeError> {
1370		let open = self
1371			.spaces
1372			.get_mut(&space)
1373			.ok_or(NodeError::NoSpace(space))?;
1374		let caught_up = open.stored.catch_up(&open.keys)?;
1375		if caught_up {
1376			self.read_again(space)?;
1377		}
1378		Ok(caught_up)
1379	}
1380
1381	/// Commits a change to a space, signed by this replica, as [`Space::commit`] does, once
1382	/// the library has caught up with what others wrote to the space, which may have made
1383	/// more fields secret. If others write while the change is made, which it catches up
1384	/// with too, what the library keeps of the space is read again after it.
1385	///
1386	/// Its ordinary operations are saved as a change for each entity they are about, as every
1387	/// change is ([technical design](../../../docs/Technical-design.md#62-one-entity-per-change)), so
1388	/// that a purge of one entity states again no value of another.
1389	fn commit(
1390		&mut self,
1391		space: SpaceId,
1392		operations: Vec<Operation>,
1393		wall_millis: u64,
1394		rng: &mut impl CryptoRng,
1395	) -> Result<(), NodeError> {
1396		self.observe_wall(wall_millis);
1397		self.catch_up_space(space)?;
1398		let touched = space == self.info.personal && self.touches_languages(&operations);
1399		self.check_not_revoked(space)?;
1400		// A shared space whose secrets this replica does not hold sets them up, if it may.
1401		if space != self.info.personal
1402			&& !self.secrets_unlocked(space)
1403			&& let Some(secret) = self.secret_fields(space)
1404			&& operations.iter().any(|operation| {
1405				matches!(operation, Operation::Assert { statement, .. }
1406					if secret.contains(&statement.field))
1407			}) {
1408			self.set_up_space_secrets(space, wall_millis, rng)?;
1409		}
1410		// What every replica would set aside, an AI agent's does not make; nor does it take
1411		// away or delete the library's own records, which every replica would take.
1412		if self.is_ai_agent()? {
1413			self.check_ai_agents_operations(space, &operations)?;
1414		}
1415		let open = self
1416			.spaces
1417			.get_mut(&space)
1418			.ok_or(NodeError::NoSpace(space))?;
1419		let reloads = open.stored.reloads();
1420		open.commit(
1421			self.acting
1422				.as_ref()
1423				.map_or(&self.replica.signing, |acting| &acting.signing),
1424			&self.code_types,
1425			operations,
1426			wall_millis,
1427			rng,
1428		)?;
1429		// The change is saved by now. Reading the lists again fails only when the storage
1430		// does, which is reported all the same.
1431		if open.stored.reloads() != reloads {
1432			self.read_again(space)?;
1433		} else if touched {
1434			self.refresh_languages()?;
1435		}
1436		// A change to a group takes effect in the spaces it is in at their anchors; the next
1437		// sync anchors it where this fails, as the change is saved by now.
1438		if space != self.info.personal && self.space(space)?.is_group()? {
1439			let _ = self.after_group_change(space, wall_millis, rng);
1440		}
1441		Ok(())
1442	}
1443
1444	/// Refuses, on an AI agent's replica, operations that every replica would set aside, as
1445	/// they govern, take secret values away, or write the library's own records; and those that
1446	/// every replica would take, as it decides from the payload alone, but that change the
1447	/// library's own records or a Git repository's record otherwise: that take their
1448	/// statements away, or delete, restore or merge them, as a clone trusts what remains of a
1449	/// repository's record that a person made, and statements of fields of NibKeep's own on any
1450	/// entity ([technical design](../../../docs/Technical-design.md#14-ai-agents)).
1451	fn check_ai_agents_operations(
1452		&self,
1453		space: SpaceId,
1454		operations: &[Operation],
1455	) -> Result<(), NodeError> {
1456		const RECORDS: &str = "change the library's own records, such as its types, devices, \
1457		                       languages and storage policies, or its Git repositories' records";
1458		let log = self.space(space)?.stored.log();
1459		let state = log.state();
1460		let kept = |entity: EntityId| -> Result<bool, NodeError> {
1461			let types = state.types(entity)?;
1462			Ok(fields::is_library_record(&types) || types.contains(&nibkeep_std::GIT_REPOSITORY))
1463		};
1464		for operation in operations {
1465			if log.governs(operation)? {
1466				return Err(NodeError::AiAgentMayNot(
1467					"change who may write to the library",
1468				));
1469			}
1470			let taken = match operation {
1471				Operation::Assert {
1472					statement,
1473					supersedes,
1474					..
1475				} => {
1476					if !fields::ai_agent_may_write(statement) {
1477						return Err(NodeError::AiAgentMayNot(RECORDS));
1478					}
1479					// What a deletion or a merge ends: the entity, and what it is merged into.
1480					let ended = match &statement.field {
1481						field if *field == fields::DELETED => [
1482							(statement.value == Value::Boolean(true)).then_some(statement.entity),
1483							None,
1484						],
1485						field if *field == fields::MERGED_INTO => {
1486							[Some(statement.entity), statement.value.as_reference()]
1487						}
1488						_ => [None, None],
1489					};
1490					for entity in ended.into_iter().flatten() {
1491						if kept(entity)? {
1492							return Err(NodeError::AiAgentMayNot(RECORDS));
1493						}
1494					}
1495					supersedes
1496				}
1497				Operation::Retract { statements, .. } => statements,
1498				Operation::RetractSecret { .. } => {
1499					return Err(NodeError::AiAgentMayNot("take secret values away"));
1500				}
1501				Operation::Unknown(_) => {
1502					return Err(NodeError::AiAgentMayNot(
1503						"write operations that this version does not know",
1504					));
1505				}
1506			};
1507			for id in taken {
1508				if let Some(statement) = state.statement(*id)?
1509					&& (!fields::ai_agent_may_take_away(&statement) || kept(statement.entity)?)
1510				{
1511					return Err(NodeError::AiAgentMayNot(RECORDS));
1512				}
1513			}
1514		}
1515		Ok(())
1516	}
1517}
1518
1519impl Library {
1520	/// Notes a wall clock time that the library was given, if it is the latest.
1521	pub(crate) fn observe_wall(&self, wall_millis: u64) {
1522		self.wall.set(self.wall.get().max(wall_millis));
1523	}
1524}
1525
1526/// A library that was closed, with its replica's keys still unlocked, and its secrets if
1527/// they were.
1528pub struct Closed {
1529	directory: PathBuf,
1530	compartment: CompartmentKey,
1531	secrets: Option<CompartmentKey>,
1532}
1533
1534impl Closed {
1535	/// Opens the library again, as it is on the disk now. If its secrets were unlocked when
1536	/// it closed, it keeps their key, and [`Library::unlock_kept_secrets`] opens them when an
1537	/// operation needs them.
1538	///
1539	/// # Errors
1540	///
1541	/// Returns the errors of [`Library::open`]; an error of the keys if the key file's
1542	/// protection was changed since.
1543	pub fn open(&self) -> Result<Library, NodeError> {
1544		// A program of a later version may have opened the library since.
1545		engines::check(&self.directory)?;
1546		let key_file = KeyFile::read(&self.directory.join(KEYS))?;
1547		let mut library =
1548			Library::open_unlocked(&self.directory, key_file, self.compartment.clone())?;
1549		library.secrets_compartment.clone_from(&self.secrets);
1550		Ok(library)
1551	}
1552
1553	/// Whether it keeps the key of the secrets, which were unlocked when it closed: another
1554	/// program may have protected them anew since, which only unlocking them tells.
1555	#[must_use]
1556	pub fn secrets_kept(&self) -> bool {
1557		self.secrets.is_some()
1558	}
1559
1560	/// Locks the secrets: forgets their key.
1561	pub fn lock_secrets(&mut self) {
1562		self.secrets = None;
1563	}
1564
1565	/// The library, closed, with its replica's keys but never its secrets', for a part of
1566	/// the program that never needs them, such as the holder of the sync role.
1567	#[must_use]
1568	pub fn without_secrets(&self) -> Self {
1569		Self {
1570			directory: self.directory.clone(),
1571			compartment: self.compartment.clone(),
1572			secrets: None,
1573		}
1574	}
1575
1576	/// The folder of the library's replica.
1577	#[must_use]
1578	pub fn directory(&self) -> &Path {
1579		&self.directory
1580	}
1581
1582	/// The library's directory, as [`Library::open`] takes it.
1583	#[must_use]
1584	pub fn library_directory(&self) -> Option<&Path> {
1585		library_directory(&self.directory)
1586	}
1587}
1588
1589/// The library's directory of the replica in `folder`: the folder that holds its replicas,
1590/// each in `replicas/<name>/`.
1591fn library_directory(folder: &Path) -> Option<&Path> {
1592	let replicas = folder.parent()?;
1593	(replicas.file_name()? == REPLICAS).then_some(replicas.parent()?)
1594}
1595
1596/// What a new library starts with.
1597struct New<'a> {
1598	directory: &'a Path,
1599	replica: &'a ReplicaKeys,
1600	personal: SpaceId,
1601	library: &'a NewLibrary<'a>,
1602	code_types: &'a Types,
1603}
1604
1605/// Saves the keys, founds the personal space and writes the library file, which comes last:
1606/// a library without it was never finished.
1607fn start(
1608	new: &New<'_>,
1609	key_file: &mut KeyFile,
1610	wall_millis: u64,
1611	rng: &mut impl CryptoRng,
1612) -> Result<(Info, Space), NodeError> {
1613	let New {
1614		directory,
1615		replica,
1616		personal,
1617		library,
1618		code_types,
1619	} = *new;
1620	key_file.write(&directory.join(KEYS))?;
1621	#[cfg(test)]
1622	if tests::STARTS_FAIL.get() {
1623		return Err(NodeError::Damaged(
1624			"the start fails, as the test asks".to_owned(),
1625		));
1626	}
1627	let encryption = replica.decryption.encryption_key();
1628	let founding = nibkeep_governance::found(
1629		personal,
1630		(library.user, library.person.unwrap_or(library.user)),
1631		(library.device, library.app),
1632		&library.languages,
1633		(&replica.signing, &encryption),
1634		rng,
1635	);
1636	let mut space = Space::open(
1637		&log_path(directory, personal),
1638		personal,
1639		&replica.spaces[&personal],
1640		&replica.storage,
1641		code_types,
1642	)?;
1643	// The space installs the standard vocabulary as definitions of its own, so that every
1644	// device and app sees it, in the change that founds it.
1645	let mut operations = founding.operations;
1646	for definition in nibkeep_std::types() {
1647		operations.extend(code_types.define(&definition, rng));
1648	}
1649	// The fields it makes secret, such as passwords, are secret for good, which governs the
1650	// space: the first change says so, beside the replica's key.
1651	let secret = nibkeep_std::secret_fields().iter().cloned();
1652	#[cfg(test)]
1653	let secret = secret.filter(|_| !tests::FOUNDED_AS_BEFORE.get());
1654	let mut governing = founding.governing;
1655	governing.extend(space.secret_marks(code_types, (founding.replica, secret), rng)?);
1656	for operations in [governing, operations] {
1657		space.commit(&replica.signing, code_types, operations, wall_millis, rng)?;
1658	}
1659	let info = Info {
1660		user: founding.user,
1661		device: founding.device,
1662		replica: founding.replica,
1663		personal,
1664	};
1665	info.write(&directory.join(INFO))?;
1666	Ok((info, space))
1667}
1668
1669impl Space {
1670	/// Opens a space of the library with its keys, and the types that NibKeep defines in
1671	/// code; the space's own types then decide which fields are secret.
1672	fn open(
1673		log: &Path,
1674		id: SpaceId,
1675		epochs: &BTreeMap<u64, Key>,
1676		storage: &Key,
1677		code_types: &Types,
1678	) -> Result<Self, NodeError> {
1679		let mut epochs = epochs.iter();
1680		let (&first, key) = epochs
1681			.next()
1682			.ok_or_else(|| NodeError::Damaged(format!("the space {id} has no keys")))?;
1683		let mut keys = SpaceKeys::new(first, key.clone());
1684		for (&epoch, key) in epochs {
1685			keys.insert(epoch, key.clone());
1686		}
1687		let mut stored = StoredLog::open(
1688			log,
1689			id,
1690			&keys,
1691			storage,
1692			MAX_DRIFT_MILLIS,
1693			code_types.secret_fields(),
1694		)?;
1695		// Every space of a library is founded by a change that says who may write to it.
1696		stored.expect_governed();
1697		let mut space = Self {
1698			stored,
1699			keys,
1700			group: std::cell::Cell::new(None),
1701			types: Types::new(),
1702		};
1703		space.read_types(code_types)?;
1704		Ok(space)
1705	}
1706
1707	/// Commits what a writer asked for to the space, signed by `signing`: what governs the
1708	/// space, such as a replica's key, first, in a change of its own, as the log requires,
1709	/// which stays if the rest then fails; then a change for each entity, as
1710	/// [`Space::by_entity`] groups them, in one batch, all or none, or, in a batch the writer
1711	/// opened, saved or not as that batch saves its other changes. If the operations define
1712	/// types, the fields they make secret are secret before anything is committed, so that
1713	/// values written with them are sealed too, or refused before any of them is saved, and
1714	/// search treats the fields whose last writer wins as such. After a change that may touch
1715	/// the definitions of types, the types are read again from what was stored.
1716	fn commit(
1717		&mut self,
1718		signing: &SigningKey,
1719		code_types: &Types,
1720		operations: Vec<Operation>,
1721		wall_millis: u64,
1722		rng: &mut impl CryptoRng,
1723	) -> Result<(), NodeError> {
1724		// Each operation changes only the entity it names.
1725		let operations = self.scoped(operations)?;
1726		// Before anything is committed, as far as the fields secret now tell.
1727		self.check_sealed_for_secrets(&operations)?;
1728		// What governs the space makes a change of its own, before the rest.
1729		let mut governing = Vec::new();
1730		let mut operations_left = Vec::new();
1731		for operation in operations {
1732			if self.stored.log().governs(&operation)? {
1733				governing.push(operation);
1734			} else {
1735				operations_left.push(operation);
1736			}
1737		}
1738		if !governing.is_empty() {
1739			// The log wraps a governing change with the space's first key, which every
1740			// replica holds, so that every replica reads it.
1741			self.stored
1742				.commit(signing, &self.keys, governing, wall_millis, rng)?;
1743			if operations_left.is_empty() {
1744				return Ok(());
1745			}
1746		}
1747		// Content that the write's own definitions make secret is refused before any of it is
1748		// saved, as each change checks only what the space knows to be secret when it is made.
1749		if defines_types(&operations_left) {
1750			let types = self.types_with(code_types, &operations_left, wall_millis)?;
1751			self.refresh_fields(&types)?;
1752			let checked = self.check_sealed_for_secrets(&operations_left);
1753			self.read_types(code_types)?;
1754			checked?;
1755		}
1756		let changes = self.one_entity_each(operations_left)?;
1757		if changes.len() == 1 || self.stored.in_batch() {
1758			// One change; or several in the writer's own batch, which saves them, or not, as
1759			// it does its other changes.
1760			for operations in changes {
1761				self.commit_ordinary(signing, code_types, operations, wall_millis, rng)?;
1762			}
1763			return Ok(());
1764		}
1765		self.stored.begin_batch(&self.keys)?;
1766		let ran = catch_unwind(AssertUnwindSafe(|| -> Result<(), NodeError> {
1767			for operations in changes {
1768				self.commit_ordinary(signing, code_types, operations, wall_millis, rng)?;
1769			}
1770			Ok(())
1771		}));
1772		let ended = if matches!(ran, Ok(Ok(()))) {
1773			self.stored.end_batch().map_err(NodeError::from)
1774		} else {
1775			self.stored.abandon_batch();
1776			Ok(())
1777		};
1778		if !matches!((&ran, &ended), (Ok(Ok(())), Ok(()))) {
1779			// What was read of the definitions of the changes left out went with them. Reading
1780			// it again fails only when the storage does, which the error tells already.
1781			let _ = self.read_types(code_types);
1782		}
1783		match ran {
1784			Err(panic) => resume_unwind(panic),
1785			Ok(result) => result.and(ended),
1786		}
1787	}
1788
1789	/// The ordinary operations of what a writer asked for, as changes about one entity each,
1790	/// as every change is ([the technical design's section on
1791	/// one entity per change](../../../docs/Technical-design.md#62-one-entity-per-change)), as [`Space::by_entity`] groups
1792	/// them.
1793	fn one_entity_each(
1794		&self,
1795		operations: Vec<Operation>,
1796	) -> Result<Vec<Vec<Operation>>, NodeError> {
1797		Ok(self
1798			.by_entity(operations)?
1799			.into_iter()
1800			.map(|(_, operations)| operations)
1801			.collect())
1802	}
1803
1804	/// What a writer asked for, as operations that each change only the entity they name,
1805	/// as the log supersedes no statement of another entity ([Data
1806	/// model](../../../docs/spec/model.md#5-operations)): what an assertion replaces of
1807	/// another entity, such as one merged into its own, is retracted from that entity apart,
1808	/// right after it, and a retraction is split by the entities of the statements it names,
1809	/// as the space and the operations before it hold them. A statement that neither holds
1810	/// stays with the entity named, or is dropped from a retraction of the earlier form, which
1811	/// names none. A retraction of secret statements, which names none either, is split by
1812	/// the entities of the secret statements this replica opened, as retractions from each,
1813	/// which the log writes again as a retraction of secret statements; the rest is dropped,
1814	/// as it takes away no ordinary statement.
1815	pub(crate) fn scoped(&self, operations: Vec<Operation>) -> Result<Vec<Operation>, NodeError> {
1816		use nibkeep_model::storage::Statements;
1817		let storage = self.stored.log().state().storage();
1818		let mut placed = Vec::with_capacity(operations.len());
1819		for operation in operations {
1820			let Operation::RetractSecret { statements } = operation else {
1821				placed.push(operation);
1822				continue;
1823			};
1824			let mut by_entity: BTreeMap<EntityId, BTreeSet<StatementId>> = BTreeMap::new();
1825			for id in statements {
1826				if storage.is_secret(id)?
1827					&& let Some(recorded) = storage.get(id)?
1828				{
1829					by_entity
1830						.entry(recorded.statement.entity)
1831						.or_default()
1832						.insert(id);
1833				}
1834			}
1835			placed.extend(
1836				by_entity
1837					.into_iter()
1838					.map(|(entity, ids)| Operation::retract(entity, ids)),
1839			);
1840		}
1841		scope(placed, |id| {
1842			Ok(storage.get(id)?.map(|recorded| recorded.statement.entity))
1843		})
1844	}
1845
1846	/// Ordinary operations, which each name their entity, as [`Space::scoped`] makes them,
1847	/// grouped by the entity each is about, in the order each entity first comes: first
1848	/// every definition of a type or a field, under `None`, which go together and which the
1849	/// rest may need, then the operations of each other entity. An operation that names none,
1850	/// of an unknown kind, goes with the operations before it.
1851	pub(crate) fn by_entity(&self, operations: Vec<Operation>) -> Result<ByEntity, NodeError> {
1852		let state = self.stored.log().state();
1853		// Whether each entity is a definition, found once for each.
1854		let mut definitions: BTreeMap<EntityId, bool> = operations
1855			.iter()
1856			.filter(|operation| defines_types(std::slice::from_ref(*operation)))
1857			.filter_map(|operation| match operation {
1858				Operation::Assert { statement, .. } => Some((statement.entity, true)),
1859				_ => None,
1860			})
1861			.collect();
1862		let mut key_of = |entity: EntityId| -> Result<Option<EntityId>, NodeError> {
1863			if let Some(&definition) = definitions.get(&entity) {
1864				return Ok((!definition).then_some(entity));
1865			}
1866			let types = state.types(entity)?;
1867			let definition = types.contains(&TYPE_DEFINITION) || types.contains(&FIELD_DEFINITION);
1868			definitions.insert(entity, definition);
1869			Ok((!definition).then_some(entity))
1870		};
1871		// `None` stands for the definitions.
1872		let mut groups: ByEntity = Vec::new();
1873		for operation in operations {
1874			let key = match operation.entity() {
1875				Some(entity) => Some(key_of(entity)?),
1876				None => None,
1877			};
1878			let at = match key {
1879				Some(key) => groups.iter().position(|(of, _)| *of == key),
1880				None => groups.len().checked_sub(1),
1881			};
1882			match (at, key) {
1883				(Some(at), _) => groups[at].1.push(operation),
1884				(None, key) => groups.push((key.flatten(), vec![operation])),
1885			}
1886		}
1887		// The definitions first.
1888		groups.sort_by_key(|(key, _)| key.is_some());
1889		Ok(groups)
1890	}
1891
1892	/// Commits an ordinary change, about one entity.
1893	fn commit_ordinary(
1894		&mut self,
1895		signing: &SigningKey,
1896		code_types: &Types,
1897		operations: Vec<Operation>,
1898		wall_millis: u64,
1899		rng: &mut impl CryptoRng,
1900	) -> Result<(), NodeError> {
1901		let defines = defines_types(&operations);
1902		let touches = defines || self.touches_definitions(&operations)?;
1903		if defines {
1904			let types = self.types_with(code_types, &operations, wall_millis)?;
1905			self.refresh_fields(&types)?;
1906		}
1907		// Fields that the change itself makes secret count too.
1908		if let Err(refused) = self.check_sealed_for_secrets(&operations) {
1909			if defines {
1910				self.read_types(code_types)?;
1911			}
1912			return Err(refused);
1913		}
1914		let committed = self
1915			.stored
1916			.commit(signing, &self.keys, operations, wall_millis, rng);
1917		// After a failure, the fields made secret for the change are the types' again.
1918		if (committed.is_ok() && touches) || (committed.is_err() && defines) {
1919			self.read_types(code_types)?;
1920		}
1921		committed?;
1922		Ok(())
1923	}
1924
1925	/// The types of the space as `operations` would leave them, with the fields they make
1926	/// secret, tried on the state without changing it.
1927	fn types_with(
1928		&self,
1929		code_types: &Types,
1930		operations: &[Operation],
1931		wall_millis: u64,
1932	) -> Result<Types, NodeError> {
1933		let mut definitions: BTreeSet<EntityId> = self
1934			.stored
1935			.find(&fields::TYPE, &Value::Text(TYPE_DEFINITION.to_string()))?
1936			.into_iter()
1937			.collect();
1938		let mut state = State::in_storage(Overlay::new(self.stored.log().state().storage()));
1939		for operation in operations {
1940			state.apply(operation, Timestamp::new(wall_millis, 0))?;
1941			if let Operation::Assert { statement, .. } = operation
1942				&& statement.field == fields::TYPE
1943				&& statement.value.as_text() == Some(TYPE_DEFINITION.as_str())
1944			{
1945				definitions.insert(state.canonical(statement.entity)?);
1946			}
1947		}
1948		let mut types = code_types.clone();
1949		types.read_entities(&state, definitions)?;
1950		types.mark_secret(self.secret_for_good()?);
1951		Ok(types)
1952	}
1953
1954	/// Refuses content in a secret field that is not sealed for the secrets, which every
1955	/// replica of the space could read: content of whose secret blob keys this replica has
1956	/// opened none, whether or not it holds the sealed copy yet.
1957	fn check_sealed_for_secrets(&self, operations: &[Operation]) -> Result<(), NodeError> {
1958		for operation in operations {
1959			if let Operation::Assert { statement, .. } = operation
1960				&& let Value::Blob(content) = &statement.value
1961				&& self.stored.secret_fields().contains(&statement.field)
1962				&& !self.stored.has_secret_blob_key(content)
1963			{
1964				return Err(NodeError::NotSealedForSecrets(statement.field.clone()));
1965			}
1966		}
1967		Ok(())
1968	}
1969
1970	/// Reads the types of the space again: those in code, combined with those that the space
1971	/// defines. The fields that they make secret become the secret ones. The definitions are
1972	/// read in one transaction: with a transaction for each query, the 2,400 queries of the
1973	/// 11 types of generated data took the state file's lock 2,400 times, which made opening
1974	/// a library on a Windows laptop take twice as long, 22 ms rather than 10.
1975	fn read_types(&mut self, code_types: &Types) -> Result<(), NodeError> {
1976		let marked = self.secret_for_good()?;
1977		let types = self.stored.reading(|stored| -> Result<Types, NodeError> {
1978			let mut types = code_types.clone();
1979			let definitions =
1980				stored.find(&fields::TYPE, &Value::Text(TYPE_DEFINITION.to_string()))?;
1981			types.read_entities(stored.log().state(), definitions.iter().copied())?;
1982			types.mark_secret(marked);
1983			Ok(types)
1984		})?;
1985		self.refresh_fields(&types)?;
1986		self.types = types;
1987		Ok(())
1988	}
1989
1990	/// The fields that are secret for good: those that counting statements governing the
1991	/// space make so, and the standard vocabulary's secret fields, which are secret in every
1992	/// space, whether it defines their types or not, and are marked in a space that lacks
1993	/// the marks at its next sync ([Data model](../../../docs/spec/model.md#9-secret-fields)).
1994	fn secret_for_good(&self) -> Result<BTreeSet<FieldName>, NodeError> {
1995		let mut secret = self.marked_secret()?;
1996		secret.extend(nibkeep_std::secret_fields().iter().cloned());
1997		Ok(secret)
1998	}
1999
2000	/// The fields that counting statements governing the space make secret for good
2001	/// ([Data model](../../../docs/spec/model.md#9-secret-fields)).
2002	fn marked_secret(&self) -> Result<BTreeSet<FieldName>, NodeError> {
2003		Ok(self
2004			.stored
2005			.log()
2006			.governing_statements(&self.keys)?
2007			.into_iter()
2008			.filter_map(|governing| governing.counting_text(&SECRET_FIELD)?.parse().ok())
2009			.collect())
2010	}
2011
2012	/// The operations that state, for good, that `secret` fields are secret: those of them
2013	/// that NibKeep and apps do not make secret in code, and that no counting statement
2014	/// names yet. They govern the space, and are stated on the record of `replica`, the one
2015	/// that states them, which every replica has, whatever else the state holds.
2016	fn secret_marks(
2017		&self,
2018		code_types: &Types,
2019		(replica, secret): (EntityId, impl IntoIterator<Item = FieldName>),
2020		rng: &mut impl CryptoRng,
2021	) -> Result<Vec<Operation>, NodeError> {
2022		let in_code = code_types.secret_fields();
2023		let marked = self.marked_secret()?;
2024		let missing: Vec<FieldName> = secret
2025			.into_iter()
2026			.filter(|field| {
2027				!in_code.contains(field) && !marked.contains(field) && !fields::is_reserved(field)
2028			})
2029			.collect();
2030		Ok(missing
2031			.into_iter()
2032			.map(|field| {
2033				Operation::assert(Statement::new(
2034					StatementId::random(rng),
2035					replica,
2036					SECRET_FIELD,
2037					Value::Text(field.to_string()),
2038				))
2039			})
2040			.collect())
2041	}
2042
2043	/// Whether operations may change what the space's types are: whether they say anything
2044	/// of an entity that defines a type or a field, or of one merged into it, supersede or
2045	/// retract what one says, or merge an entity into one. A deleted entity still defines
2046	/// its types, so that restoring it brings them back; what is said of other entities,
2047	/// such as deleting or merging them, leaves the types as they are.
2048	fn touches_definitions(&self, operations: &[Operation]) -> Result<bool, NodeError> {
2049		let state = self.stored.log().state();
2050		// Each entity is looked at once: a change mostly says things of one entity.
2051		let mut known: BTreeMap<EntityId, bool> = BTreeMap::new();
2052		let mut defines = |entity: EntityId| -> Result<bool, NodeError> {
2053			if let Some(&defines) = known.get(&entity) {
2054				return Ok(defines);
2055			}
2056			let defines = entities::defines_types(state, entity)?;
2057			known.insert(entity, defines);
2058			Ok(defines)
2059		};
2060		for operation in operations {
2061			let Some(removed) = operation.superseded() else {
2062				continue;
2063			};
2064			if let Operation::Assert { statement, .. } = operation {
2065				if defines(statement.entity)? {
2066					return Ok(true);
2067				}
2068				if statement.field == fields::MERGED_INTO
2069					&& let Some(into) = statement.value.as_reference()
2070					&& defines(into)?
2071				{
2072					return Ok(true);
2073				}
2074			}
2075			for &id in removed {
2076				if let Some(statement) = state.statement(id)?
2077					&& defines(statement.entity)?
2078				{
2079					return Ok(true);
2080				}
2081			}
2082		}
2083		Ok(false)
2084	}
2085
2086	/// Makes the fields that the types mark secret the secret ones, and tells search which
2087	/// fields show only the value written last.
2088	fn refresh_fields(&mut self, types: &Types) -> Result<(), NodeError> {
2089		let secret = types.secret_fields();
2090		let last_writer_wins = types.last_writer_wins_fields();
2091		if secret != *self.stored.secret_fields()
2092			|| last_writer_wins != *self.stored.last_writer_wins_fields()
2093		{
2094			self.stored.set_fields(secret, last_writer_wins)?;
2095		}
2096		Ok(())
2097	}
2098
2099	/// What the space holds, its name as a reader of `languages` sees it, and whether the
2100	/// replica of key `own` left it.
2101	fn status(
2102		&self,
2103		id: SpaceId,
2104		languages: &Languages,
2105		own: &VerifyingKey,
2106	) -> Result<SpaceStatus, NodeError> {
2107		let state = self.stored.log().state();
2108		Ok(SpaceStatus {
2109			id,
2110			name: self.name(languages)?,
2111			entities: entities::things(state)?.len(),
2112			changes: self.stored.log().kept()?,
2113			left: self.stored.log().is_removed(own, &self.keys)?,
2114		})
2115	}
2116
2117	/// The space's name, if it has one, as a reader of `languages` sees it.
2118	pub(crate) fn name(&self, languages: &Languages) -> Result<Option<String>, NodeError> {
2119		let state = self.stored.log().state();
2120		match self.own_entity()? {
2121			Some(entity) => entities::display_name(state, &self.types, languages, entity),
2122			None => Ok(None),
2123		}
2124	}
2125
2126	/// The space's own entity, of the type `org.nibkeep.space`, if it has one: of several,
2127	/// the first by ID.
2128	pub(crate) fn own_entity(&self) -> Result<Option<EntityId>, NodeError> {
2129		for kind in [SPACE, nibkeep_governance::GROUP] {
2130			if let Some(entity) = self
2131				.stored
2132				.find(&fields::TYPE, &Value::Text(kind.to_string()))?
2133				.first()
2134			{
2135				return Ok(Some(*entity));
2136			}
2137		}
2138		Ok(None)
2139	}
2140
2141	/// The hash of the space's first key, if the replica keeps it: the key that the entry
2142	/// which gave it the space held.
2143	pub(crate) fn first_key_hash(&self) -> Option<Hash> {
2144		self.keys
2145			.space_keys()
2146			.find(|(epoch, _)| *epoch == 0)
2147			.map(|(_, key)| nibkeep_crypto::key_hash(key))
2148	}
2149
2150	/// Whether it is a group: a space with members and no data of its own, as its first
2151	/// change says, which only its founder writes; `false` until the replica holds it.
2152	pub(crate) fn is_group(&self) -> Result<bool, NodeError> {
2153		if let Some(group) = self.group.get() {
2154			return Ok(group);
2155		}
2156		let log = self.stored.log();
2157		let Some(root) = log.root()? else {
2158			return Ok(false);
2159		};
2160		let group = log
2161			.governing_statements(&self.keys)?
2162			.iter()
2163			.any(|governing| {
2164				governing.change == root
2165					&& governing.statement.field == fields::SPACE_KIND
2166					&& governing.statement.value.as_text() == Some(nibkeep_governance::GROUP_KIND)
2167			});
2168		self.group.set(Some(group));
2169		Ok(group)
2170	}
2171}
2172
2173/// The replica that the counting governing changes of a space list `key`, in its text form,
2174/// for, and the user they say it belongs to, if they say both: who a key is, whatever the
2175/// state still holds of it.
2176fn governed_record(
2177	stored: &StoredLog,
2178	keys: &SpaceKeys,
2179	key: &Value,
2180) -> Result<Option<(EntityId, EntityId)>, NodeError> {
2181	let statements = stored.log().governing_statements(keys)?;
2182	let mut counting = statements.iter().filter(|governing| governing.counts);
2183	let Some(listing) = counting.clone().find(|governing| {
2184		governing.statement.field == SIGNING_KEY
2185			&& governing.lists
2186			&& governing.statement.value == *key
2187	}) else {
2188		return Ok(None);
2189	};
2190	let replica = listing.statement.entity;
2191	// In a space with members, the owner is the one that the key's own listing names, in
2192	// the change that lists it: another member could state an owner on the record.
2193	if stored.log().has_members(keys)? {
2194		return Ok(counting
2195			.filter(|governing| {
2196				governing.change == listing.change
2197					&& governing.statement.entity == replica
2198					&& governing.statement.field == fields::LISTING
2199			})
2200			.find_map(|governing| {
2201				let signed =
2202					nibkeep_governance::Listing::from_text(governing.statement.value.as_text()?)?;
2203				(signed.verifies() && signed.record == replica).then_some(signed.owner)
2204			})
2205			.map(|owner| (replica, owner)));
2206	}
2207	Ok(counting
2208		.find_map(|governing| {
2209			(governing.statement.entity == replica && governing.statement.field == OWNER)
2210				.then(|| governing.statement.value.as_reference())
2211				.flatten()
2212		})
2213		.map(|user| (replica, user)))
2214}
2215
2216/// Operations grouped by the entity each is about, the definitions of types and fields under
2217/// `None`.
2218pub(crate) type ByEntity = Vec<(Option<EntityId>, Vec<Operation>)>;
2219
2220/// Whether operations define types or fields.
2221fn defines_types(operations: &[Operation]) -> bool {
2222	operations.iter().any(|operation| {
2223		matches!(
2224			operation,
2225			Operation::Assert { statement, .. }
2226				if statement.field == fields::TYPE
2227					&& matches!(
2228						statement.value.as_text(),
2229						Some(name) if name == TYPE_DEFINITION.as_str() || name == FIELD_DEFINITION.as_str()
2230					)
2231		)
2232	})
2233}
2234
2235/// The sealed copies of a content that these spaces hold and can read, with keys of the kind
2236/// given, secret or ordinary, smallest sealed hash first, each once.
2237pub(crate) fn held_copies_in<'a>(
2238	spaces: impl IntoIterator<Item = &'a Space>,
2239	content: &Hash,
2240	secret: bool,
2241) -> Vec<(Hash, Key)> {
2242	let mut copies: Vec<(Hash, Key)> = spaces
2243		.into_iter()
2244		.flat_map(|open| open.stored.held_copies(content, secret))
2245		.collect();
2246	copies.sort_by_key(|(sealed, _)| *sealed);
2247	copies.dedup_by_key(|(sealed, _)| *sealed);
2248	copies
2249}
2250
2251/// The types that NibKeep defines in code.
2252fn code_types() -> Types {
2253	let mut types = Types::new();
2254	for definition in nibkeep_governance::types()
2255		.into_iter()
2256		.chain(policies::types())
2257		.chain(backups::types())
2258	{
2259		types.add(definition);
2260	}
2261	types
2262}
2263
2264/// What a library's directory holds: of its replicas, which is here, as its place file says,
2265/// and which are copies. A library has both its key file and its library file, which is
2266/// written last. A replica's folder without a place file, or with one that does not read, is
2267/// a copy, which a program may still be bringing in, file by file. Folders whose names start
2268/// with a dot are new replicas' that are not finished, or replicas set aside. A replica that
2269/// a recovery brings back in place of the one here, until it is done, hides that one, so
2270/// that the two count as one library.
2271fn found(directory: &Path) -> Found {
2272	let Some(folders) = replica_folders(directory) else {
2273		return Found::Nothing;
2274	};
2275	let copies = folders.iter().any(|(_, here)| !here);
2276	let mut here: Vec<PathBuf> = folders
2277		.into_iter()
2278		.filter_map(|(folder, here)| here.then_some(folder))
2279		.collect();
2280	let replaced: Vec<PathBuf> = here
2281		.iter()
2282		.filter_map(|folder| recovering::replaced_by(folder))
2283		.collect();
2284	here.retain(|folder| !replaced.contains(folder));
2285	match here.len() {
2286		0 if copies => Found::Copies,
2287		0 => Found::Nothing,
2288		1 => {
2289			let folder = here.remove(0);
2290			let whole = folder.join(KEYS).exists() && folder.join(INFO).exists();
2291			Found::Here { folder, whole }
2292		}
2293		_ => Found::Several(here),
2294	}
2295}
2296
2297/// The folders of the replicas in a library's directory, each with whether it is here, as
2298/// its place file says, but those whose names start with a dot: `None` if the directory has
2299/// no folder of replicas.
2300pub(crate) fn replica_folders(directory: &Path) -> Option<Vec<(PathBuf, bool)>> {
2301	let entries = fs::read_dir(directory.join(REPLICAS)).ok()?;
2302	let mut folders = Vec::new();
2303	for entry in entries.flatten() {
2304		let folder = entry.path();
2305		if entry.file_name().to_string_lossy().starts_with('.') || !folder.is_dir() {
2306			continue;
2307		}
2308		let verdict = PlaceFile::read(&folder.join(PLACE))
2309			.ok()
2310			.flatten()
2311			.map(|place| place.verdict(&place::whereabouts(&folder), &folder));
2312		folders.push((folder, verdict == Some(Verdict::Here)));
2313	}
2314	folders.sort();
2315	Some(folders)
2316}
2317
2318/// Reads the key file of a library's replica that is here, and tells its folder.
2319fn read_key_file(directory: &Path) -> Result<(PathBuf, KeyFile), NodeError> {
2320	match found(directory) {
2321		Found::Nothing => Err(NodeError::NoLibrary),
2322		Found::Here { folder, whole } => {
2323			// Before any other file of the replica, which a later version may have changed:
2324			// one without the files of this version is not taken for one whose making was
2325			// cut short, which the apps offer to remove.
2326			engines::check(&folder)?;
2327			if !whole {
2328				return Err(NodeError::Unfinished);
2329			}
2330			// A recovery cut short left a replica that nobody knows, which a recovery run
2331			// again starts over.
2332			if recovering::unfinished(&folder) {
2333				return Err(NodeError::RecoveryCutShort);
2334			}
2335			let key_file = KeyFile::read(&folder.join(KEYS))?;
2336			Ok((folder, key_file))
2337		}
2338		Found::Copies => Err(NodeError::Copied),
2339		Found::Several(folders) => Err(NodeError::SeveralHere(folders)),
2340	}
2341}
2342
2343/// Removes the folders of new replicas whose making this computer started and a crash cut
2344/// short, before they were renamed into place: those whose place file says they are here.
2345/// Another computer's, which a program that syncs the folder may bring, are left alone.
2346fn remove_unfinished_starts(replicas: &Path) {
2347	for entry in fs::read_dir(replicas).into_iter().flatten().flatten() {
2348		let name = entry.file_name().to_string_lossy().into_owned();
2349		let new = Path::new(&name)
2350			.extension()
2351			.is_some_and(|extension| extension == "new");
2352		if !(name.starts_with('.') && new) {
2353			continue;
2354		}
2355		let folder = entry.path();
2356		let ours = PlaceFile::read(&folder.join(PLACE))
2357			.ok()
2358			.flatten()
2359			.is_some_and(|place| {
2360				place.verdict(&place::whereabouts(&folder), &folder) == Verdict::Here
2361			});
2362		if ours {
2363			let _ = fs::remove_dir_all(&folder);
2364		}
2365	}
2366}
2367
2368/// Bytes in lowercase hexadecimal, two digits each.
2369pub(crate) fn hex(bytes: &[u8]) -> String {
2370	use std::fmt::Write as _;
2371	bytes.iter().fold(String::new(), |mut text, byte| {
2372		let _ = write!(text, "{byte:02x}");
2373		text
2374	})
2375}
2376
2377/// Refuses a library's directory on a network drive, or in a folder whose files a program
2378/// may take away to the cloud.
2379pub(crate) fn check_local(directory: &Path) -> Result<(), NodeError> {
2380	local(&place::whereabouts(directory).drive)
2381}
2382
2383/// Refuses a new replica in a library's directory on a drive without a journal, unless the
2384/// person allowed it there (technical design: drives without a journal).
2385fn journal(drive: &place::Drive, directory: &Path) -> Result<(), NodeError> {
2386	if drive.unjournaled && !directory.join(FAT_ALLOWED).exists() {
2387		return Err(NodeError::NoJournal);
2388	}
2389	Ok(())
2390}
2391
2392/// As [`check_local`], on the drive that holds the directory.
2393fn local(drive: &place::Drive) -> Result<(), NodeError> {
2394	if drive.remote {
2395		return Err(NodeError::RemoteDrive);
2396	}
2397	if drive.cloud {
2398		return Err(NodeError::CloudFolder);
2399	}
2400	Ok(())
2401}
2402
2403/// Makes the folder of a new replica in a library's directory that has none here, with its
2404/// place file and its engines file, which records this program as having made it at
2405/// `wall_millis`: under a temporary name first, so that the folder appears with them or not
2406/// at all. Copies of replicas made elsewhere may be there.
2407pub(crate) fn new_replica_folder(
2408	directory: &Path,
2409	wall_millis: u64,
2410	rng: &mut impl CryptoRng,
2411) -> Result<PathBuf, NodeError> {
2412	new_replica_folder_at(directory, (None, None), wall_millis, rng)
2413}
2414
2415/// Makes the folder of a new replica as [`new_replica_folder`] does, at the computer's time,
2416/// with the file `mark` in it too, if given, holding its bytes, so that the folder appears
2417/// with it; beside the replica here in `replacing`, if given, which the mark names, as a
2418/// recovery in place makes it.
2419pub(crate) fn new_replica_folder_marked(
2420	directory: &Path,
2421	mark: Option<(&str, &[u8])>,
2422	replacing: Option<&Path>,
2423	rng: &mut impl CryptoRng,
2424) -> Result<PathBuf, NodeError> {
2425	new_replica_folder_at(directory, (mark, replacing), wall_clock(), rng)
2426}
2427
2428/// Makes the folder of a new replica as [`new_replica_folder_marked`] does, at `wall_millis`.
2429fn new_replica_folder_at(
2430	directory: &Path,
2431	(mark, replacing): (Option<(&str, &[u8])>, Option<&Path>),
2432	wall_millis: u64,
2433	rng: &mut impl CryptoRng,
2434) -> Result<PathBuf, NodeError> {
2435	match found(directory) {
2436		Found::Here { folder, .. } if Some(folder.as_path()) == replacing => {}
2437		Found::Here { .. } | Found::Several(_) => return Err(NodeError::Exists),
2438		Found::Nothing | Found::Copies => {}
2439	}
2440	// Before anything is made, as a program that syncs the folder would take it to the cloud.
2441	let replicas = directory.join(REPLICAS);
2442	let here = place::whereabouts(&replicas);
2443	local(&here.drive)?;
2444	// A phone that gives no ID would make a replica that never opens again.
2445	if here.phone && here.computer.is_none() {
2446		return Err(NodeError::NoPhoneId);
2447	}
2448	journal(&here.drive, directory)?;
2449	fs::create_dir_all(&replicas).map_err(NodeError::file(&replicas))?;
2450	remove_unfinished_starts(&replicas);
2451	let mut name = [0u8; 8];
2452	rng.fill_bytes(&mut name);
2453	let name = hex(&name);
2454	let temporary = replicas.join(format!(".{name}.new"));
2455	fs::create_dir(&temporary).map_err(NodeError::file(&temporary))?;
2456	let folder = replicas.join(&name);
2457	let made = PlaceFile::new(&place::whereabouts_as(&temporary, &folder), rng)
2458		.create(&temporary.join(PLACE))
2459		.and_then(|()| engines::create(&temporary, wall_millis))
2460		.and_then(|()| match mark {
2461			Some((mark, bytes)) => crate::info::write_file(&temporary.join(mark), bytes),
2462			None => Ok(()),
2463		})
2464		.and_then(|()| fs::rename(&temporary, &folder).map_err(NodeError::file(&folder)));
2465	if let Err(error) = made {
2466		let _ = fs::remove_dir_all(&temporary);
2467		return Err(error);
2468	}
2469	#[cfg(unix)]
2470	let _ = fs::File::open(&replicas).and_then(|replicas| replicas.sync_all());
2471	// Another replica made at the same time makes two here: this one gives way. One that
2472	// it replaces counts as none, as its mark names it.
2473	if let Found::Several(_) = found(directory) {
2474		let _ = fs::remove_dir_all(&folder);
2475		return Err(NodeError::Exists);
2476	}
2477	Ok(folder)
2478}
2479
2480/// Operations that each change only the entity they name, as [`Space::scoped`] says, where
2481/// `entity_of` finds the entity of a statement that the operations do not assert themselves.
2482pub(crate) fn scope(
2483	operations: Vec<Operation>,
2484	mut entity_of: impl FnMut(StatementId) -> Result<Option<EntityId>, NodeError>,
2485) -> Result<Vec<Operation>, NodeError> {
2486	// The entity of each statement these operations assert, which a later one may
2487	// supersede.
2488	let mut asserted: BTreeMap<StatementId, EntityId> = BTreeMap::new();
2489	let mut entity_of =
2490		|asserted: &BTreeMap<StatementId, EntityId>, id: StatementId| match asserted.get(&id) {
2491			Some(&entity) => Ok(Some(entity)),
2492			None => entity_of(id),
2493		};
2494	// Statements grouped by entity, in the order each first comes.
2495	let group =
2496		|groups: &mut Vec<(EntityId, BTreeSet<StatementId>)>, entity: EntityId, id: StatementId| {
2497			match groups.iter_mut().find(|(of, _)| *of == entity) {
2498				Some((_, ids)) => {
2499					ids.insert(id);
2500				}
2501				None => groups.push((entity, BTreeSet::from([id]))),
2502			}
2503		};
2504	let mut scoped = Vec::with_capacity(operations.len());
2505	for operation in operations {
2506		match operation {
2507			Operation::Assert {
2508				statement,
2509				supersedes,
2510				any_entity: false,
2511			} => {
2512				let mut own = BTreeSet::new();
2513				let mut others = Vec::new();
2514				for id in supersedes {
2515					match entity_of(&asserted, id)? {
2516						Some(entity) if entity != statement.entity => {
2517							group(&mut others, entity, id);
2518						}
2519						_ => {
2520							own.insert(id);
2521						}
2522					}
2523				}
2524				asserted.insert(statement.id, statement.entity);
2525				scoped.push(Operation::Assert {
2526					statement,
2527					supersedes: own,
2528					any_entity: false,
2529				});
2530				scoped.extend(
2531					others
2532						.into_iter()
2533						.map(|(entity, ids)| Operation::retract(entity, ids)),
2534				);
2535			}
2536			Operation::Retract { entity, statements } => {
2537				let mut groups = Vec::new();
2538				for id in statements {
2539					if let Some(of) = entity_of(&asserted, id)?.or(entity) {
2540						group(&mut groups, of, id);
2541					}
2542				}
2543				scoped.extend(
2544					groups
2545						.into_iter()
2546						.map(|(entity, ids)| Operation::retract(entity, ids)),
2547				);
2548			}
2549			// What a program writes is never of the earlier form; a retraction of secret
2550			// statements, which names none, is placed before.
2551			other @ (Operation::Assert { .. }
2552			| Operation::RetractSecret { .. }
2553			| Operation::Unknown(_)) => scoped.push(other),
2554		}
2555	}
2556	Ok(scoped)
2557}
2558
2559#[cfg(test)]
2560mod tests {
2561	use nibkeep_crypto::PassphraseParams;
2562	use nibkeep_model::{FieldDef, Statement, TypeName, ValueKind};
2563	use nibkeep_testkit::{TestRng, millis_at};
2564
2565	use super::*;
2566
2567	thread_local! {
2568		/// Whether libraries that this thread starts are founded as versions before the
2569		/// vocabulary had secret fields founded them: without their marks.
2570		pub(super) static FOUNDED_AS_BEFORE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2571
2572		/// Whether libraries that this thread starts fail once their keys are saved, as when
2573		/// the disk is full.
2574		pub(super) static STARTS_FAIL: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2575	}
2576
2577	#[test]
2578	fn a_failed_start_leaves_nothing_behind() {
2579		static ONCE: std::sync::Once = std::sync::Once::new();
2580		ONCE.call_once(|| {
2581			let store: std::sync::Arc<keyring_core::CredentialStore> =
2582				keyring_core::mock::Store::new().expect("a mock store");
2583			keyring_core::set_default_store(store);
2584		});
2585		let directory = Removed(nibkeep_testkit::empty_directory(
2586			std::env::temp_dir(),
2587			&format!("nibkeep-node-failed-start-{}", std::process::id()),
2588		));
2589		let mut rng = TestRng::new("failed start");
2590		STARTS_FAIL.set(true);
2591		for protection in [
2592			NewProtection::Passphrase(
2593				"correct horse",
2594				PassphraseParams::new(64, 1, 1).expect("valid"),
2595			),
2596			NewProtection::Keystore {
2597				service: "org.nibkeep.test",
2598			},
2599		] {
2600			assert!(
2601				Library::create(
2602					&directory.0,
2603					&NewLibrary::new("Ada", "laptop", "nib"),
2604					&protection,
2605					millis_at("2026-10-12", 10, 0),
2606					&mut rng
2607				)
2608				.is_err()
2609			);
2610			let left: Vec<_> = fs::read_dir(directory.0.join(REPLICAS))
2611				.expect("lists")
2612				.collect();
2613			assert!(left.is_empty(), "no replica's folder is left");
2614			assert!(!Library::exists(&directory.0));
2615		}
2616		STARTS_FAIL.set(false);
2617		// Neither left a key in the keystore. The mock store lists the entries whose keys were
2618		// deleted, without the keys.
2619		let entries = keyring_core::get_default_store()
2620			.expect("a store")
2621			.search(&std::collections::HashMap::new())
2622			.expect("searches");
2623		assert!(
2624			entries.iter().all(|entry| entry.get_secret().is_err()),
2625			"no key is left in the keystore"
2626		);
2627	}
2628
2629	/// A directory that goes when the test ends, also when it fails.
2630	struct Removed(PathBuf);
2631
2632	impl Drop for Removed {
2633		fn drop(&mut self) {
2634			let _ = fs::remove_dir_all(&self.0);
2635		}
2636	}
2637
2638	/// A library in a directory of its own, protected by a quick passphrase.
2639	fn library(name: &str, now: u64, rng: &mut TestRng) -> (Removed, Library) {
2640		let directory = nibkeep_testkit::empty_directory(
2641			std::env::temp_dir(),
2642			&format!("nibkeep-node-{name}-{}", std::process::id()),
2643		);
2644		let protection = NewProtection::Passphrase(
2645			"correct horse",
2646			PassphraseParams::new(64, 1, 1).expect("valid"),
2647		);
2648		let library = Library::create(
2649			&directory,
2650			&NewLibrary::new("Ada", "laptop", "nib"),
2651			&protection,
2652			now,
2653			rng,
2654		)
2655		.expect("creates");
2656		(Removed(directory), library)
2657	}
2658
2659	/// The entity of a space that defines the type named `name`.
2660	fn definition_of(space: &Space, name: &str) -> EntityId {
2661		let state = space.stored.log().state();
2662		*space
2663			.stored
2664			.find(&fields::TYPE, &Value::Text(TYPE_DEFINITION.to_string()))
2665			.expect("finds")
2666			.iter()
2667			.find(|entity| {
2668				state
2669					.current(**entity, &fields::TYPE_NAME)
2670					.expect("reads")
2671					.iter()
2672					.any(|statement| statement.value.as_text() == Some(name))
2673			})
2674			.expect("the definition")
2675	}
2676
2677	/// The operation that deletes an entity.
2678	fn delete(entity: EntityId, rng: &mut TestRng) -> Operation {
2679		Operation::assert(Statement::new(
2680			StatementId::random(rng),
2681			entity,
2682			fields::DELETED,
2683			Value::Boolean(true),
2684		))
2685	}
2686
2687	/// The operation that merges an entity into another.
2688	fn merge(entity: EntityId, into: EntityId, rng: &mut TestRng) -> Operation {
2689		Operation::assert(Statement::new(
2690			StatementId::random(rng),
2691			entity,
2692			fields::MERGED_INTO,
2693			Value::Reference(into),
2694		))
2695	}
2696
2697	/// A type of books with a title, defined in the personal space, and a book of it.
2698	fn a_book(library: &mut Library, now: u64, rng: &mut TestRng) -> (TypeDef, EntityId) {
2699		let personal = library.personal_space();
2700		let title: FieldName = "local.title".parse().expect("a field name");
2701		let book = TypeDef::new(TypeName::from_static("local.book"), 1)
2702			.with_field(title.clone(), FieldDef::new(ValueKind::Text));
2703		library
2704			.define_type(personal, &book, now, rng)
2705			.expect("defines");
2706		let novel = library
2707			.create_entity(
2708				personal,
2709				&[book.name().clone()],
2710				vec![(title, Value::Text("Lavinia".to_owned()))],
2711				now + 1_000,
2712				rng,
2713			)
2714			.expect("adds");
2715		(book, novel)
2716	}
2717
2718	/// The ID of the statement that an operation asserts.
2719	fn asserted(operation: &Operation) -> StatementId {
2720		match operation {
2721			Operation::Assert { statement, .. } => statement.id,
2722			_ => panic!("an assertion"),
2723		}
2724	}
2725
2726	/// The change that first recorded a statement of the personal space.
2727	fn change_of(library: &Library, id: StatementId) -> Option<Hash> {
2728		let space = library.space(library.personal_space()).expect("a space");
2729		nibkeep_model::storage::Statements::get(space.stored.log().state().storage(), id)
2730			.expect("reads")
2731			.expect("the statement")
2732			.change
2733	}
2734
2735	#[test]
2736	fn what_a_writer_says_of_two_entities_is_saved_as_a_change_for_each() {
2737		let mut rng = TestRng::new("one entity per change");
2738		let now = millis_at("2026-11-03", 10, 0);
2739		let (_directory, mut library) = library("one entity per change", now, &mut rng);
2740		let personal = library.personal_space();
2741		let changes =
2742			|library: &Library| library.status().expect("reads the status").spaces[0].changes;
2743		let (a, b) = (EntityId::random(&mut rng), EntityId::random(&mut rng));
2744		let operations = vec![
2745			delete(a, &mut rng),
2746			delete(b, &mut rng),
2747			merge(a, b, &mut rng),
2748		];
2749		let ids: Vec<StatementId> = operations.iter().map(asserted).collect();
2750		let before = changes(&library);
2751		library
2752			.commit(personal, operations, now + 1_000, &mut rng)
2753			.expect("commits");
2754		assert_eq!(changes(&library), before + 2, "a change for each entity");
2755		assert_eq!(
2756			change_of(&library, ids[0]),
2757			change_of(&library, ids[2]),
2758			"both of A's"
2759		);
2760		assert_ne!(
2761			change_of(&library, ids[0]),
2762			change_of(&library, ids[1]),
2763			"B's apart"
2764		);
2765		// A retraction of statements of both is split too.
2766		library
2767			.commit(
2768				personal,
2769				vec![Operation::retract(a, [ids[0], ids[1]])],
2770				now + 2_000,
2771				&mut rng,
2772			)
2773			.expect("commits");
2774		assert_eq!(
2775			changes(&library),
2776			before + 4,
2777			"a retraction for each entity"
2778		);
2779		let space = library.space(personal).expect("a space");
2780		let storage = space.stored.log().state().storage();
2781		for id in [ids[0], ids[1]] {
2782			assert!(nibkeep_model::storage::Statements::is_superseded(storage, id).expect("reads"));
2783		}
2784	}
2785
2786	#[test]
2787	fn content_refused_with_the_definition_of_its_secret_field_leaves_the_fields_as_they_were() {
2788		let mut rng = TestRng::new("content refused with its definition");
2789		let now = millis_at("2026-10-12", 10, 0);
2790		let (_directory, mut library) = library("refused with definition", now, &mut rng);
2791		let personal = library.personal_space();
2792		library
2793			.set_up_secrets(
2794				&NewProtection::Passphrase(
2795					"tr0ub4dor",
2796					PassphraseParams::new(64, 1, 1).expect("valid"),
2797				),
2798				now + 500,
2799				&mut rng,
2800			)
2801			.expect("sets up");
2802		let scan: FieldName = "local.scan".parse().expect("a field name");
2803		let document = TypeDef::new(TypeName::from_static("local.document"), 1)
2804			.with_field(scan.clone(), FieldDef::new(ValueKind::Blob).secret());
2805		// Content sealed as every blob is, which every replica of the space reads.
2806		let plain = library
2807			.import_blob(personal, &b"a scan"[..], now + 600, &mut rng)
2808			.expect("imports");
2809		let mut operations = library
2810			.types(personal)
2811			.expect("a space")
2812			.define(&document, &mut rng);
2813		operations.push(Operation::assert(Statement::new(
2814			nibkeep_base::StatementId::random(&mut rng),
2815			EntityId::random(&mut rng),
2816			scan.clone(),
2817			Value::Blob(plain),
2818		)));
2819		let committed = library.commit(personal, operations, now + 1_000, &mut rng);
2820		assert!(
2821			matches!(committed, Err(NodeError::NotSealedForSecrets(ref field)) if *field == scan),
2822			"{committed:?}"
2823		);
2824		// Nothing of the change counts: the type is not defined, nor its field secret.
2825		assert!(
2826			!library
2827				.secret_fields(personal)
2828				.expect("a space")
2829				.contains(&scan)
2830		);
2831		assert!(
2832			library
2833				.types(personal)
2834				.expect("a space")
2835				.get(document.name())
2836				.is_none()
2837		);
2838		drop(library);
2839	}
2840
2841	#[test]
2842	fn content_refused_with_its_secret_field_in_a_batch_saves_none_of_the_write() {
2843		let mut rng = TestRng::new("refused in a batch");
2844		let now = millis_at("2026-11-04", 10, 0);
2845		let (_directory, mut library) = library("refused in a batch", now, &mut rng);
2846		let personal = library.personal_space();
2847		library
2848			.set_up_secrets(
2849				&NewProtection::Passphrase(
2850					"tr0ub4dor",
2851					PassphraseParams::new(64, 1, 1).expect("valid"),
2852				),
2853				now + 500,
2854				&mut rng,
2855			)
2856			.expect("sets up");
2857		let scan: FieldName = "local.scan".parse().expect("a field name");
2858		let document = TypeDef::new(TypeName::from_static("local.document"), 1)
2859			.with_field(scan.clone(), FieldDef::new(ValueKind::Blob).secret());
2860		let plain = library
2861			.import_blob(personal, &b"a scan"[..], now + 600, &mut rng)
2862			.expect("imports");
2863		let mut operations = library
2864			.types(personal)
2865			.expect("a space")
2866			.define(&document, &mut rng);
2867		operations.push(Operation::assert(Statement::new(
2868			StatementId::random(&mut rng),
2869			EntityId::random(&mut rng),
2870			scan.clone(),
2871			Value::Blob(plain),
2872		)));
2873		let changes =
2874			|library: &Library| library.status().expect("reads the status").spaces[0].changes;
2875		let before = changes(&library);
2876		// In a batch of the writer's, which saves what was made before a failure, the write
2877		// is refused before any of its changes is made.
2878		let committed = library.batch(personal, |library| {
2879			library.commit(personal, operations, now + 1_000, &mut rng)
2880		});
2881		assert!(
2882			matches!(committed, Err(NodeError::NotSealedForSecrets(ref field)) if *field == scan),
2883			"{committed:?}"
2884		);
2885		assert_eq!(changes(&library), before);
2886		assert!(
2887			library
2888				.types(personal)
2889				.expect("a space")
2890				.get(document.name())
2891				.is_none()
2892		);
2893	}
2894
2895	#[test]
2896	fn a_retraction_of_what_the_same_write_asserts_goes_with_its_entity() {
2897		let mut rng = TestRng::new("retracted in the same write");
2898		let now = millis_at("2026-11-04", 10, 0);
2899		let (_directory, library) = library("retracted in the same write", now, &mut rng);
2900		let personal = library.personal_space();
2901		let a = EntityId::random(&mut rng);
2902		let deleting = delete(a, &mut rng);
2903		let id = asserted(&deleting);
2904		let title: FieldName = "local.title".parse().expect("a field name");
2905		let book = TypeDef::new(TypeName::from_static("local.book"), 1)
2906			.with_field(title, FieldDef::new(ValueKind::Text));
2907		let mut operations = vec![deleting];
2908		operations.extend(
2909			library
2910				.types(personal)
2911				.expect("a space")
2912				.define(&book, &mut rng),
2913		);
2914		operations.push(Operation::retract(a, [id]));
2915		let groups = library
2916			.space(personal)
2917			.expect("a space")
2918			.by_entity(operations)
2919			.expect("groups");
2920		// The definitions first, with no retraction; then the entity, with both.
2921		assert_eq!(groups.len(), 2);
2922		assert_eq!(groups[0].0, None);
2923		assert!(
2924			groups[0]
2925				.1
2926				.iter()
2927				.all(|operation| matches!(operation, Operation::Assert { .. }))
2928		);
2929		assert_eq!(groups[1].0, Some(a));
2930		assert_eq!(groups[1].1.len(), 2);
2931	}
2932
2933	#[test]
2934	fn values_committed_with_their_secret_field_are_sealed() {
2935		let mut rng = TestRng::new("sealed with the definition");
2936		let now = millis_at("2026-10-12", 10, 0);
2937		let (_directory, mut library) = library("sealed", now, &mut rng);
2938		let personal = library.personal_space();
2939		let password: FieldName = "local.password".parse().expect("a field name");
2940		let login = TypeDef::new(TypeName::from_static("local.login"), 1)
2941			.with_field(password.clone(), FieldDef::new(ValueKind::Text).secret());
2942		let mut operations = library
2943			.types(personal)
2944			.expect("a space")
2945			.define(&login, &mut rng);
2946		operations.push(Operation::assert(Statement::new(
2947			nibkeep_base::StatementId::random(&mut rng),
2948			EntityId::random(&mut rng),
2949			password,
2950			Value::Text("hunter2".to_owned()),
2951		)));
2952		// The value must be sealed with the space's secrets key, which there is none of yet:
2953		// committed as an ordinary value, it would have been stored in plain.
2954		let committed = library.commit(personal, operations, now + 1_000, &mut rng);
2955		assert!(
2956			matches!(
2957				committed,
2958				Err(NodeError::Store(nibkeep_store::StoreError::Log(
2959					nibkeep_log::LogError::SecretsLocked
2960				)))
2961			),
2962			"{committed:?}"
2963		);
2964		drop(library);
2965	}
2966
2967	/// A retraction of secret statements, which names no entity, goes with the entity of each
2968	/// secret statement it takes away, and the log writes it again as such a retraction; it
2969	/// takes away no ordinary statement.
2970	#[test]
2971	fn a_retraction_of_secret_statements_goes_with_the_entity_of_each() {
2972		let mut rng = TestRng::new("secret retraction placed");
2973		let now = millis_at("2026-10-12", 10, 0);
2974		let (_directory, mut library) = library("placed", now, &mut rng);
2975		let personal = library.personal_space();
2976		library
2977			.set_up_secrets(
2978				&NewProtection::Passphrase(
2979					"tr0ub4dor",
2980					PassphraseParams::new(64, 1, 1).expect("valid"),
2981				),
2982				now + 500,
2983				&mut rng,
2984			)
2985			.expect("sets up");
2986		let (login, pin) = a_login();
2987		let mut operations = library
2988			.types(personal)
2989			.expect("a space")
2990			.define(&login, &mut rng);
2991		let (first, second) = (EntityId::random(&mut rng), EntityId::random(&mut rng));
2992		let mut pins = Vec::new();
2993		for (entity, value) in [(first, "1234"), (second, "5678")] {
2994			let statement = Statement::new(
2995				StatementId::random(&mut rng),
2996				entity,
2997				pin.clone(),
2998				Value::Text(value.to_owned()),
2999			);
3000			pins.push(statement.id);
3001			operations.push(Operation::assert(statement));
3002		}
3003		let note = Operation::assert(Statement::new(
3004			StatementId::random(&mut rng),
3005			first,
3006			"local.note".parse().expect("a field name"),
3007			Value::Text("a note".to_owned()),
3008		));
3009		let note_id = asserted(&note);
3010		operations.push(note);
3011		library
3012			.commit(personal, operations, now + 1_000, &mut rng)
3013			.expect("commits");
3014		let mut taking = pins.clone();
3015		taking.push(note_id);
3016		let space = library.space(personal).expect("a space");
3017		let scoped = space
3018			.scoped(vec![Operation::retract_secret(taking.clone())])
3019			.expect("scopes");
3020		let mut expected = vec![
3021			Operation::retract(first, [pins[0]]),
3022			Operation::retract(second, [pins[1]]),
3023		];
3024		expected.sort_by_key(Operation::entity);
3025		assert_eq!(scoped, expected);
3026		library
3027			.commit(
3028				personal,
3029				vec![Operation::retract_secret(taking)],
3030				now + 2_000,
3031				&mut rng,
3032			)
3033			.expect("commits");
3034		let state = library
3035			.space(personal)
3036			.expect("a space")
3037			.stored
3038			.log()
3039			.state();
3040		for id in pins {
3041			assert!(!state.is_current(id).expect("reads"));
3042		}
3043		assert!(state.is_current(note_id).expect("reads"));
3044	}
3045
3046	#[test]
3047	fn only_what_touches_definitions_has_the_types_read_again() {
3048		let mut rng = TestRng::new("touches definitions");
3049		let now = millis_at("2026-10-12", 10, 0);
3050		let (_directory, mut library) = library("definitions", now, &mut rng);
3051		let personal = library.personal_space();
3052		let (book, novel) = a_book(&mut library, now, &mut rng);
3053		let space = library.space(personal).expect("a space");
3054		let definition = definition_of(space, "local.book");
3055		assert!(
3056			!space
3057				.touches_definitions(&[delete(novel, &mut rng)])
3058				.expect("reads"),
3059			"deleting an entity of a type leaves the types"
3060		);
3061		let deleting = delete(definition, &mut rng);
3062		assert!(
3063			space
3064				.touches_definitions(std::slice::from_ref(&deleting))
3065				.expect("reads"),
3066			"deleting a definition"
3067		);
3068		let Operation::Assert {
3069			statement: deleted, ..
3070		} = &deleting
3071		else {
3072			unreachable!("an assertion");
3073		};
3074		let restoring = Operation::retract(deleted.entity, [deleted.id]);
3075		library
3076			.commit(personal, vec![deleting.clone()], now + 2_000, &mut rng)
3077			.expect("deletes the definition");
3078		assert!(
3079			library
3080				.types(personal)
3081				.expect("a space")
3082				.get(book.name())
3083				.is_none(),
3084			"a deleted definition defines nothing"
3085		);
3086		// The deleted definition is found among none of the definitions, and still defines the
3087		// type once it is restored.
3088		let space = library.space(personal).expect("a space");
3089		assert!(
3090			space
3091				.touches_definitions(std::slice::from_ref(&restoring))
3092				.expect("reads"),
3093			"restoring a definition"
3094		);
3095		library
3096			.commit(personal, vec![restoring], now + 3_000, &mut rng)
3097			.expect("restores the definition");
3098		assert_eq!(
3099			library.types(personal).expect("a space").get(book.name()),
3100			Some(&book)
3101		);
3102		drop(library);
3103	}
3104
3105	#[test]
3106	fn saying_something_of_an_entity_merged_into_a_definition_touches_it() {
3107		let mut rng = TestRng::new("merged into a definition");
3108		let now = millis_at("2026-10-12", 10, 0);
3109		let (_directory, mut library) = library("merged-definition", now, &mut rng);
3110		let personal = library.personal_space();
3111		let (_, novel) = a_book(&mut library, now, &mut rng);
3112		let title: FieldName = "local.title".parse().expect("a field name");
3113		let space = library.space(personal).expect("a space");
3114		let state = space.stored.log().state();
3115		let field = *space
3116			.stored
3117			.find(&fields::TYPE, &Value::Text(FIELD_DEFINITION.to_string()))
3118			.expect("finds")
3119			.iter()
3120			.find(|entity| {
3121				state
3122					.current(**entity, &fields::FIELD_NAME)
3123					.expect("reads")
3124					.iter()
3125					.any(|statement| statement.value.as_text() == Some(title.as_str()))
3126			})
3127			.expect("the field's definition");
3128		library
3129			.commit(
3130				personal,
3131				vec![merge(novel, field, &mut rng)],
3132				now + 2_000,
3133				&mut rng,
3134			)
3135			.expect("merges");
3136		let secret = Operation::assert(Statement::new(
3137			StatementId::random(&mut rng),
3138			novel,
3139			fields::FIELD_SECRET,
3140			Value::Boolean(true),
3141		));
3142		library
3143			.commit(personal, vec![secret], now + 3_000, &mut rng)
3144			.expect("makes the field secret");
3145		assert!(
3146			library
3147				.types(personal)
3148				.expect("a space")
3149				.secret_fields()
3150				.contains(&title),
3151			"the field is secret as soon as its definition says so"
3152		);
3153		drop(library);
3154	}
3155
3156	#[test]
3157	fn merging_into_a_definition_touches_it() {
3158		let mut rng = TestRng::new("merging into a definition");
3159		let now = millis_at("2026-10-12", 10, 0);
3160		let (_directory, mut library) = library("merging", now, &mut rng);
3161		let personal = library.personal_space();
3162		let (book, novel) = a_book(&mut library, now, &mut rng);
3163		let other = library
3164			.create_entity(
3165				personal,
3166				&[book.name().clone()],
3167				Vec::new(),
3168				now + 2_000,
3169				&mut rng,
3170			)
3171			.expect("adds");
3172		let space = library.space(personal).expect("a space");
3173		let definition = definition_of(space, "local.book");
3174		assert!(
3175			!space
3176				.touches_definitions(&[merge(novel, other, &mut rng)])
3177				.expect("reads"),
3178			"merging two things leaves the types"
3179		);
3180		let merging = merge(novel, definition, &mut rng);
3181		assert!(
3182			space
3183				.touches_definitions(std::slice::from_ref(&merging))
3184				.expect("reads"),
3185			"merging into a definition"
3186		);
3187		let Operation::Assert {
3188			statement: merged, ..
3189		} = &merging
3190		else {
3191			unreachable!("an assertion");
3192		};
3193		let undoing = Operation::retract(merged.entity, [merged.id]);
3194		library
3195			.commit(personal, vec![merging], now + 3_000, &mut rng)
3196			.expect("merges");
3197		let space = library.space(personal).expect("a space");
3198		assert!(
3199			space
3200				.touches_definitions(std::slice::from_ref(&undoing))
3201				.expect("reads"),
3202			"undoing a merge into a definition"
3203		);
3204		drop(library);
3205	}
3206
3207	/// A type of logins with a secret PIN.
3208	fn a_login() -> (TypeDef, FieldName) {
3209		let pin: FieldName = "local.pin".parse().expect("a field name");
3210		let login = TypeDef::new(TypeName::from_static("local.login"), 1)
3211			.with_field(pin.clone(), FieldDef::new(ValueKind::Text).secret());
3212		(login, pin)
3213	}
3214
3215	#[test]
3216	fn a_field_once_secret_stays_secret_whatever_its_definition_says_later() {
3217		let mut rng = TestRng::new("secret for good");
3218		let now = millis_at("2026-10-26", 10, 0);
3219		let (_directory, mut library) = library("secret for good", now, &mut rng);
3220		let personal = library.personal_space();
3221		let (login, pin) = a_login();
3222		library
3223			.define_type(personal, &login, now + 1_000, &mut rng)
3224			.expect("defines");
3225		// The type's definition is deleted, and its field's mark taken away, as a change
3226		// that another replica forged could do.
3227		let space = library.space(personal).expect("a space");
3228		let definition = definition_of(space, "local.login");
3229		let state = space.stored.log().state();
3230		let fields_of_it: Vec<EntityId> = state
3231			.referrers(definition)
3232			.expect("reads")
3233			.into_iter()
3234			.map(|statement| statement.entity)
3235			.collect();
3236		let mut marks = Vec::new();
3237		for field in &fields_of_it {
3238			marks.extend(
3239				state
3240					.current(*field, &fields::FIELD_SECRET)
3241					.expect("reads")
3242					.iter()
3243					.map(|statement| statement.id),
3244			);
3245		}
3246		assert!(!marks.is_empty(), "the definition marks the field secret");
3247		library
3248			.commit(
3249				personal,
3250				vec![
3251					delete(definition, &mut rng),
3252					Operation::retract(fields_of_it[0], marks),
3253				],
3254				now + 2_000,
3255				&mut rng,
3256			)
3257			.expect("commits");
3258		let types = library.types(personal).expect("a space");
3259		assert!(types.get(login.name()).is_none(), "the type is gone");
3260		assert!(
3261			library
3262				.secret_fields(personal)
3263				.expect("a space")
3264				.contains(&pin),
3265			"its field stays secret"
3266		);
3267	}
3268
3269	#[test]
3270	fn settling_marks_a_secret_field_that_an_older_copy_defined() {
3271		let mut rng = TestRng::new("secret marked later");
3272		let now = millis_at("2026-10-26", 10, 0);
3273		let (_directory, mut library) = library("secret marked later", now, &mut rng);
3274		let personal = library.personal_space();
3275		let (login, pin) = a_login();
3276		// An older copy of NibKeep defines the type without marking its field.
3277		let operations = library
3278			.space(personal)
3279			.expect("a space")
3280			.types
3281			.define(&login, &mut rng);
3282		library
3283			.commit(personal, operations, now + 1_000, &mut rng)
3284			.expect("defines");
3285		let marked = |library: &Library| {
3286			library
3287				.space(personal)
3288				.expect("a space")
3289				.marked_secret()
3290				.expect("reads")
3291		};
3292		// A new library marks the vocabulary's secret fields, and not the older copy's.
3293		let mut before = marked(&library);
3294		assert!(before.contains(&nibkeep_std::PASSWORD));
3295		assert!(!before.contains(&pin));
3296		library.settle_keys(now + 2_000, &mut rng).expect("settles");
3297		before.insert(pin.clone());
3298		assert_eq!(marked(&library), before);
3299		// Settling again marks nothing more.
3300		let changes = library.status().expect("a status").spaces[0].changes;
3301		library.settle_keys(now + 3_000, &mut rng).expect("settles");
3302		assert_eq!(
3303			library.status().expect("a status").spaces[0].changes,
3304			changes
3305		);
3306	}
3307
3308	#[test]
3309	fn a_space_made_before_the_vocabulary_had_secrets_keeps_them_secret_and_marks_them() {
3310		let mut rng = TestRng::new("vocabulary secret");
3311		let now = millis_at("2026-10-26", 10, 0);
3312		FOUNDED_AS_BEFORE.set(true);
3313		let made = library("vocabulary secret", now, &mut rng);
3314		FOUNDED_AS_BEFORE.set(false);
3315		let (_directory, mut library) = made;
3316		let personal = library.personal_space();
3317		let vocabulary = nibkeep_std::secret_fields();
3318		let marked = |library: &Library| {
3319			library
3320				.space(personal)
3321				.expect("a space")
3322				.marked_secret()
3323				.expect("reads")
3324		};
3325		assert!(
3326			vocabulary
3327				.iter()
3328				.all(|field| !marked(&library).contains(field))
3329		);
3330		// Without the definition of logins either, as in a space made before them.
3331		let login = library
3332			.entities(personal, Some(&TYPE_DEFINITION))
3333			.expect("lists")
3334			.into_iter()
3335			.find(|listed| {
3336				let state = library
3337					.space(personal)
3338					.expect("a space")
3339					.stored
3340					.log()
3341					.state();
3342				state
3343					.current(listed.id, &fields::TYPE_NAME)
3344					.expect("reads")
3345					.iter()
3346					.any(|statement| statement.value == Value::Text(nibkeep_std::LOGIN.to_string()))
3347			})
3348			.expect("the definition of logins");
3349		// Deleted as an older copy could, which no app does.
3350		let deleted = Operation::assert(Statement::new(
3351			StatementId::random(&mut rng),
3352			login.id,
3353			fields::DELETED,
3354			Value::Boolean(true),
3355		));
3356		library
3357			.commit(personal, vec![deleted], now + 1_000, &mut rng)
3358			.expect("deletes");
3359		assert!(
3360			library
3361				.types(personal)
3362				.expect("types")
3363				.get(&nibkeep_std::LOGIN)
3364				.is_none()
3365		);
3366
3367		// The vocabulary's secret fields are secret all the same: a password is sealed, an
3368		// entity of logins names it as secret, and purging it needs the secrets.
3369		let secret = library.secret_fields(personal).expect("a space");
3370		assert!(vocabulary.iter().all(|field| secret.contains(field)));
3371		let password = |text: &str| (nibkeep_std::PASSWORD, Value::Text(text.to_owned()));
3372		let refused = library.create_entity(
3373			personal,
3374			&[nibkeep_std::LOGIN],
3375			vec![password("hunter2")],
3376			now + 2_000,
3377			&mut rng,
3378		);
3379		assert!(refused.is_err(), "no secrets to seal it with");
3380		let quick = PassphraseParams::new(64, 1, 1).expect("valid");
3381		let secrets = NewProtection::Passphrase("tr0ub4dor", quick);
3382		library
3383			.set_up_secrets(&secrets, now + 1_500, &mut rng)
3384			.expect("sets up");
3385		let entity = library
3386			.create_entity(
3387				personal,
3388				&[nibkeep_std::LOGIN],
3389				vec![password("hunter2")],
3390				now + 3_000,
3391				&mut rng,
3392			)
3393			.expect("creates");
3394		// Of logins, every one but the content of secret files.
3395		let mut of_logins = vocabulary.to_vec();
3396		of_logins.retain(|field| *field != nibkeep_std::SECRET_CONTENT);
3397		assert_eq!(
3398			library
3399				.secret_fields_of(personal, &[nibkeep_std::LOGIN])
3400				.expect("lists"),
3401			of_logins
3402		);
3403		library.lock_secrets();
3404		assert!(matches!(
3405			library.purgeable(personal, entity, &nibkeep_std::PASSWORD, None),
3406			Err(NodeError::SecretsLocked)
3407		));
3408
3409		// Settling marks them, for replicas of other versions.
3410		library.settle_keys(now + 4_000, &mut rng).expect("settles");
3411		assert!(
3412			vocabulary
3413				.iter()
3414				.all(|field| marked(&library).contains(field))
3415		);
3416	}
3417
3418	#[test]
3419	fn entities_that_define_types_are_never_found() {
3420		let mut rng = TestRng::new("definitions unfound");
3421		let now = millis_at("2026-10-26", 10, 0);
3422		let (_directory, mut library) = library("definitions unfound", now, &mut rng);
3423		let personal = library.personal_space();
3424		let definition = library
3425			.entities(personal, Some(&TYPE_DEFINITION))
3426			.expect("lists")[0]
3427			.id;
3428		// Words on a definition, as a version that did not reserve labels indexed them.
3429		let words = Operation::assert(Statement::new(
3430			StatementId::random(&mut rng),
3431			definition,
3432			"local.note".parse().expect("a field"),
3433			Value::Text("zebra crossing".to_owned()),
3434		));
3435		library
3436			.commit(personal, vec![words], now + 1_000, &mut rng)
3437			.expect("says");
3438		nibkeep_testkit::assert_empty!(library.search(personal, "zebra").expect("searches"));
3439	}
3440
3441	#[test]
3442	fn an_author_is_named_after_its_records_key_and_owner_are_taken_away() {
3443		let mut rng = TestRng::new("author taken away");
3444		let now = millis_at("2026-10-26", 10, 0);
3445		let (_directory, mut library) = library("author taken away", now, &mut rng);
3446		let personal = library.personal_space();
3447		let (_, book) = a_book(&mut library, now + 1_000, &mut rng);
3448		let title: FieldName = "local.title".parse().expect("a field name");
3449		let statement = {
3450			let state = library
3451				.space(personal)
3452				.expect("a space")
3453				.stored
3454				.log()
3455				.state();
3456			state.current(book, &title).expect("reads")[0].id
3457		};
3458		let named = |library: &Library| {
3459			library
3460				.author_of(personal, statement)
3461				.expect("reads")
3462				.and_then(|author| author.user.name)
3463		};
3464		assert_eq!(named(&library).as_deref(), Some("Ada"));
3465		// The record of this replica loses its key and owner, as an AI agent's change that
3466		// takes them away would make it.
3467		let replica = library.info.replica;
3468		let taken: Vec<StatementId> = {
3469			let state = library
3470				.space(personal)
3471				.expect("a space")
3472				.stored
3473				.log()
3474				.state();
3475			[SIGNING_KEY, OWNER]
3476				.iter()
3477				.flat_map(|field| state.current(replica, field).expect("reads"))
3478				.map(|statement| statement.id)
3479				.collect()
3480		};
3481		assert_eq!(taken.len(), 2);
3482		library
3483			.commit(
3484				personal,
3485				vec![Operation::retract(replica, taken)],
3486				now + 2_000,
3487				&mut rng,
3488			)
3489			.expect("commits");
3490		assert_eq!(named(&library).as_deref(), Some("Ada"));
3491	}
3492}