Skip to main content

nibkeep_node/library/
spaces.rs

1//! Spaces of one's own besides the personal one: making, naming and finding them, finding
2//! entities in any of them, and how a space reaches every replica of the user but AI
3//! agents': the personal space gives each its first key, each asks to be listed with a
4//! listing its own key signed, and a replica listed there lists it
5//! ([Identity](../../../../docs/spec/identity.md#8-spaces-of-ones-own),
6//! [technical design](../../../../docs/Technical-design.md#13-sharing)).
7
8use std::collections::{BTreeMap, BTreeSet};
9use std::fs;
10
11use nibkeep_base::{EntityId, SpaceId};
12use nibkeep_crypto::rand_core::CryptoRng;
13use nibkeep_crypto::{Key, VerifyingKey, key_hash};
14use nibkeep_governance::{
15	Choice, Code, LISTING, Listing, NewSpace, RecoveryListing, Roster, SPACE, SPACE_ENTRY,
16	SpaceEntry, SpaceReplica, ask_to_be_listed, found_space, list_replica, replica_record,
17	state_choice, state_recovery_code,
18};
19use nibkeep_model::{Operation, fields};
20use nibkeep_store::log_path;
21
22use super::entities::{Listed, display_name};
23use super::{Library, Space, code_types};
24use crate::NodeError;
25
26/// What the personal space says of the user's spaces: the entries that give them, the
27/// listings that ask to be listed in them, and the devices' choices of them, each as
28/// `(record, text)`; and what the devices say of the spaces given to them later, each as
29/// `(record, author, takes)`, in the order of the changes.
30#[derive(Default)]
31pub(super) struct Personal {
32	pub(super) entries: Vec<(EntityId, String)>,
33	pub(super) listings: Vec<(EntityId, String)>,
34	pub(super) choices: Vec<(EntityId, String)>,
35	pub(super) marks: Vec<(EntityId, VerifyingKey, bool)>,
36}
37
38impl Personal {
39	/// The spaces that the entries give each replica or code, as `(record, space)`.
40	pub(super) fn given(&self) -> BTreeSet<(EntityId, SpaceId)> {
41		self.entries
42			.iter()
43			.filter_map(|(record, text)| Some((*record, SpaceEntry::from_text(text)?.space)))
44			.collect()
45	}
46}
47
48/// The names of a replica's device and app, and its endpoint, as the personal space has
49/// them.
50type ReplicaNames = (Option<String>, Option<String>, Option<[u8; 32]>);
51
52impl Library {
53	/// The spaces this replica holds: the personal space first, then the others by ID.
54	#[must_use]
55	pub fn spaces(&self) -> Vec<SpaceId> {
56		let personal = self.info.personal;
57		std::iter::once(personal)
58			.chain(
59				self.spaces
60					.keys()
61					.copied()
62					.filter(|&space| space != personal),
63			)
64			.collect()
65	}
66
67	/// Chooses the space that new entities go to for as long as the library is open, and
68	/// the only one that [`Library::locate`] looks in; with none, new entities go to the
69	/// personal space, and every space is looked in.
70	///
71	/// # Errors
72	///
73	/// Returns [`NodeError::NoSpace`] if this library holds no such space.
74	pub fn choose_space(&mut self, space: Option<SpaceId>) -> Result<(), NodeError> {
75		if let Some(space) = space {
76			self.space(space)?;
77		}
78		self.chosen = space;
79		Ok(())
80	}
81
82	/// This replica's record in a space: in a space with members, the one derived from the
83	/// space and its key; in the personal space, the one the library file names.
84	pub(crate) fn own_record(&self, space: SpaceId) -> Result<EntityId, NodeError> {
85		if self.has_members(space)? {
86			Ok(replica_record(space, &self.replica.signing.verifying_key()))
87		} else {
88			Ok(self.info.replica)
89		}
90	}
91
92	/// Whether a space has members, as every space but the personal one does.
93	pub(crate) fn has_members(&self, space: SpaceId) -> Result<bool, NodeError> {
94		let open = self.space(space)?;
95		Ok(space != self.info.personal && open.stored.log().has_members(&open.keys)?)
96	}
97
98	/// The spaces that may hold secret values: every space, the personal one first.
99	pub(crate) fn secret_spaces(&self) -> Result<Vec<SpaceId>, NodeError> {
100		self.space(self.info.personal)?;
101		Ok(self.spaces())
102	}
103
104	/// The space chosen for this session, if one is.
105	#[must_use]
106	pub const fn chosen_space(&self) -> Option<SpaceId> {
107		self.chosen
108	}
109
110	/// The space that holds an entity, of those this replica holds: the first, the personal
111	/// space first, where the entity has a statement, or was merged into another.
112	///
113	/// # Errors
114	///
115	/// Returns an error if a space cannot be read.
116	pub fn space_of(&self, entity: EntityId) -> Result<Option<SpaceId>, NodeError> {
117		for space in self.spaces() {
118			let state = self.space(space)?.stored.log().state();
119			let canonical = state.canonical(entity)?;
120			if canonical != entity || !state.fields(entity)?.is_empty() {
121				return Ok(Some(space));
122			}
123		}
124		Ok(None)
125	}
126
127	/// The space that new entities go to: the one chosen, or else the personal space.
128	#[must_use]
129	pub fn default_space(&self) -> SpaceId {
130		self.chosen.unwrap_or(self.info.personal)
131	}
132
133	/// A space's name, as this library's languages show it, if it has one: the name kept
134	/// for it in the personal space where its own has not come yet, as on a device that took
135	/// the space and has not synced it since.
136	///
137	/// # Errors
138	///
139	/// Returns an error if the library has no such space, or it cannot be read.
140	pub fn space_name(&self, space: SpaceId) -> Result<Option<String>, NodeError> {
141		if let Some(name) = self.space(space)?.name(&self.languages)? {
142			return Ok(Some(name));
143		}
144		if space == self.info.personal {
145			return Ok(None);
146		}
147		Ok(self.kept_space_names()?.remove(&space).flatten())
148	}
149
150	/// Finds a space by its name, in any case, by its ID, or by the start of its ID.
151	///
152	/// # Errors
153	///
154	/// Returns [`NodeError::NoSpaceNamed`] if no space matches, and
155	/// [`NodeError::Ambiguous`]-like [`NodeError::SpacesNamed`] if several do.
156	pub fn find_space(&self, reference: &str) -> Result<SpaceId, NodeError> {
157		let lowered = reference.to_lowercase();
158		let mut by_name = Vec::new();
159		let mut by_id = Vec::new();
160		for space in self.spaces() {
161			if self
162				.space_name(space)?
163				.is_some_and(|name| name.to_lowercase() == lowered)
164			{
165				by_name.push(space);
166			}
167			if lowered.len() >= 4 && space.to_string().starts_with(&lowered) {
168				by_id.push(space);
169			}
170		}
171		let found = if by_name.is_empty() { by_id } else { by_name };
172		match found.as_slice() {
173			[] => Err(NodeError::NoSpaceNamed(reference.to_owned())),
174			[space] => Ok(*space),
175			_ => Err(NodeError::SpacesNamed(reference.to_owned())),
176		}
177	}
178
179	/// Makes a space besides the personal one, named `name`: this replica founds it, with
180	/// the user as its member and first admin, states that it holds it, and lists it in the
181	/// personal space with its first key sealed to each of the user's devices that take new
182	/// spaces, as computers do, so that they hold it too, and returns its ID
183	/// ([technical design](../../../../docs/Technical-design.md#1310-devices-that-choose-their-spaces)).
184	///
185	/// # Errors
186	///
187	/// Returns an error if the name is empty, this replica is an AI agent's or revoked, or
188	/// the keys or the changes cannot be saved.
189	pub fn create_space(
190		&mut self,
191		name: &str,
192		wall_millis: u64,
193		rng: &mut impl CryptoRng,
194	) -> Result<SpaceId, NodeError> {
195		self.make_space(name, (false, &[]), wall_millis, rng)
196	}
197
198	/// Makes a space as [`Library::create_space`] does, and gives it too to the devices of
199	/// the user's that the person chose, `also`, by their records in the personal space,
200	/// besides those that take new spaces
201	/// ([technical design](../../../../docs/Technical-design.md#1310-devices-that-choose-their-spaces)).
202	///
203	/// # Errors
204	///
205	/// The errors of [`Library::create_space`].
206	pub fn create_space_on(
207		&mut self,
208		name: &str,
209		also: &[EntityId],
210		wall_millis: u64,
211		rng: &mut impl CryptoRng,
212	) -> Result<SpaceId, NodeError> {
213		self.make_space(name, (false, also), wall_millis, rng)
214	}
215
216	/// Makes a group, named `name`: a space with members and no data of its own, which can be
217	/// a member of spaces, as an editor or a viewer, so that whoever joins the group joins
218	/// each of them ([technical design](../../../../docs/Technical-design.md#138-groups)).
219	/// This replica founds it, with the user as its first admin, as [`Library::create_space`]
220	/// founds a space, and returns its ID.
221	///
222	/// # Errors
223	///
224	/// The errors of [`Library::create_space`].
225	pub fn create_group(
226		&mut self,
227		name: &str,
228		wall_millis: u64,
229		rng: &mut impl CryptoRng,
230	) -> Result<SpaceId, NodeError> {
231		self.make_space(name, (true, &[]), wall_millis, rng)
232	}
233
234	/// Makes a group as [`Library::create_group`] does, and gives it too to the devices of
235	/// the user's that the person chose, as [`Library::create_space_on`] does.
236	///
237	/// # Errors
238	///
239	/// The errors of [`Library::create_space`].
240	pub fn create_group_on(
241		&mut self,
242		name: &str,
243		also: &[EntityId],
244		wall_millis: u64,
245		rng: &mut impl CryptoRng,
246	) -> Result<SpaceId, NodeError> {
247		self.make_space(name, (true, also), wall_millis, rng)
248	}
249
250	/// Makes a space, or with `group` a group, as [`Library::create_space`] says, giving it
251	/// to the devices that take new spaces and to those of `also`.
252	fn make_space(
253		&mut self,
254		name: &str,
255		(group, also): (bool, &[EntityId]),
256		wall_millis: u64,
257		rng: &mut impl CryptoRng,
258	) -> Result<SpaceId, NodeError> {
259		if name.trim().is_empty() {
260			return Err(NodeError::EmptyName);
261		}
262		let personal = self.info.personal;
263		self.check_not_revoked(personal)?;
264		if self.is_ai_agent()? {
265			return Err(NodeError::AiAgentMayNot("make spaces"));
266		}
267		let space = SpaceId::random(rng);
268		let first = Key::generate(rng);
269		let member = EntityId::random(rng);
270		let signing = &self.replica.signing;
271		let encryption = self.replica.decryption.encryption_key();
272		let listing = Listing::sign(signing, &encryption, space, (member, false));
273		let user_name = self.own_name(self.info.user)?.unwrap_or_default();
274		let (device_name, app_name) = self.own_names()?;
275		let endpoint = self.endpoint();
276		let founded = found_space(
277			&NewSpace {
278				name,
279				user: self.info.user,
280				user_name: &user_name,
281				member,
282				replica: SpaceReplica {
283					record: listing.record,
284					device_record: nibkeep_governance::device_record(
285						space,
286						&signing.verifying_key(),
287					),
288					member,
289					signing: &signing.verifying_key(),
290					encryption: &encryption,
291					listing: &listing.to_text(),
292					endpoint: Some(&endpoint),
293					device: &device_name,
294					app: &app_name,
295					ai_agent: false,
296				},
297				group,
298			},
299			rng,
300		);
301		self.add_space(space, &first, rng)?;
302		if let Err(error) = self.found(space, founded, listing.record, wall_millis, rng) {
303			// A space whose first change was not made would be no space at all.
304			if self
305				.space(space)
306				.is_ok_and(|open| open.stored.log().root().ok().flatten().is_none())
307			{
308				self.remove_space(space, rng);
309			}
310			return Err(error);
311		}
312		// The devices that take new spaces get it now, and those that the person chose; one
313		// that misses it, as the change fails, asks for it. Each knows it by name, or after
314		// the next sync.
315		let _ = self.give_new_space(space, also, wall_millis, rng);
316		let _ = self.settle_space_names(wall_millis, rng);
317		self.end_bursts();
318		Ok(space)
319	}
320
321	/// Commits the changes of a burst in each space, as closing the library does: after
322	/// several changes made at once, so that another program can open the library at once.
323	pub(crate) fn end_bursts(&mut self) {
324		for open in self.spaces.values_mut() {
325			open.stored.end_burst();
326		}
327	}
328
329	/// Commits a new space's first changes: the one that governs it, then the rest, each
330	/// about one thing.
331	fn found(
332		&mut self,
333		space: SpaceId,
334		founded: nibkeep_governance::FoundedSpace,
335		record: EntityId,
336		wall_millis: u64,
337		rng: &mut impl CryptoRng,
338	) -> Result<(), NodeError> {
339		let code_types = code_types();
340		let mut operations = founded.operations;
341		for definition in nibkeep_std::types() {
342			operations.extend(code_types.define(&definition, rng));
343		}
344		let open = self
345			.spaces
346			.get_mut(&space)
347			.ok_or(NodeError::NoSpace(space))?;
348		let secret = nibkeep_std::secret_fields().iter().cloned();
349		let mut governing = founded.governing;
350		governing.extend(open.secret_marks(&code_types, (record, secret), rng)?);
351		for operations in [governing, operations] {
352			open.commit(
353				&self.replica.signing,
354				&code_types,
355				operations,
356				wall_millis,
357				rng,
358			)?;
359		}
360		self.read_again(space)
361	}
362
363	/// Renames a space besides the personal one, whose name stays.
364	///
365	/// # Errors
366	///
367	/// Returns an error if the space is the personal one or this library has none such, the
368	/// name is empty, or the change cannot be saved.
369	pub fn rename_space(
370		&mut self,
371		space: SpaceId,
372		name: &str,
373		wall_millis: u64,
374		rng: &mut impl CryptoRng,
375	) -> Result<(), NodeError> {
376		if name.trim().is_empty() {
377			return Err(NodeError::EmptyName);
378		}
379		if space == self.info.personal {
380			return Err(NodeError::PersonalSpace);
381		}
382		let open = self.space(space)?;
383		let Some(entity) = open.own_entity()? else {
384			return Err(NodeError::Damaged(format!(
385				"the space {space} has no record"
386			)));
387		};
388		let current: Vec<_> = open
389			.stored
390			.log()
391			.state()
392			.current(entity, &fields::NAME)?
393			.iter()
394			.map(|statement| statement.id)
395			.collect();
396		let operation = nibkeep_governance::rename_space(entity, name, current, rng);
397		self.commit(space, vec![operation], wall_millis, rng)?;
398		// The other devices show the new name, or after the next sync.
399		let _ = self.settle_space_names(wall_millis, rng);
400		Ok(())
401	}
402
403	/// Searches every space for what holds the words, as [`Library::search`] does in one:
404	/// what each finds, with the space, the personal space first.
405	///
406	/// # Errors
407	///
408	/// Returns an error if a space cannot be read.
409	pub fn search_everywhere(&self, query: &str) -> Result<Vec<(SpaceId, Listed)>, NodeError> {
410		let mut found = Vec::new();
411		for space in self.spaces() {
412			found.extend(
413				self.search(space, query)?
414					.into_iter()
415					.map(|listed| (space, listed)),
416			);
417		}
418		Ok(found)
419	}
420
421	/// Finds an entity in whichever space holds it, or in the space chosen, if one is, by its
422	/// ID, the start of its ID, or its name, as [`Library::find_entity`] does in one space.
423	///
424	/// # Errors
425	///
426	/// Returns [`NodeError::NoEntity`] if no space has it, and [`NodeError::Ambiguous`] if
427	/// several entities match, in one space or in several.
428	pub fn locate(&self, reference: &str) -> Result<(SpaceId, EntityId), NodeError> {
429		self.locate_with(reference, |library, space| {
430			library.find_entity(space, reference)
431		})
432	}
433
434	/// Finds an entity as [`Library::locate`] does, except that a name that finds no entity
435	/// that is not deleted finds deleted ones, as [`Library::find_entity_or_deleted`] does.
436	///
437	/// # Errors
438	///
439	/// As [`Library::locate`].
440	pub fn locate_or_deleted(&self, reference: &str) -> Result<(SpaceId, EntityId), NodeError> {
441		self.locate_with(reference, |library, space| {
442			library.find_entity_or_deleted(space, reference)
443		})
444	}
445
446	fn locate_with(
447		&self,
448		reference: &str,
449		find: impl Fn(&Self, SpaceId) -> Result<EntityId, NodeError>,
450	) -> Result<(SpaceId, EntityId), NodeError> {
451		let mut found = Vec::new();
452		let mut candidates = Vec::new();
453		let spaces = match self.chosen {
454			Some(chosen) => vec![chosen],
455			None => self.spaces(),
456		};
457		for space in spaces {
458			// Of several that a name finds in one space, those moved away, where this replica
459			// holds where they went, are found there instead.
460			let result = match find(self, space) {
461				Err(NodeError::Ambiguous {
462					reference: named,
463					candidates: more,
464				}) if self.chosen.is_none() => {
465					let mut staying = Vec::new();
466					for candidate in more {
467						if self.moved_into(space, candidate)?.is_none() {
468							staying.push(candidate);
469						}
470					}
471					match staying.as_slice() {
472						[] => Err(NodeError::NoEntity(named)),
473						[only] => Ok(*only),
474						_ => Err(NodeError::Ambiguous {
475							reference: named,
476							candidates: staying,
477						}),
478					}
479				}
480				other => other,
481			};
482			match result {
483				// An entity moved into a space this replica holds is found there, by its ID;
484				// by a name, it is found as it is named there, if it is. With a space chosen,
485				// the entity there is found, as it stays to be shown or purged.
486				Ok(entity) => {
487					let found_here = match self.moved_into(space, entity)? {
488						Some(moved) if self.chosen.is_none() => {
489							if !reference.parse::<EntityId>().is_ok_and(|id| id == entity) {
490								continue;
491							}
492							moved
493						}
494						_ => (space, entity),
495					};
496					if !found.contains(&found_here) {
497						found.push(found_here);
498					}
499				}
500				Err(NodeError::NoEntity(_)) => {}
501				Err(NodeError::Ambiguous {
502					candidates: more, ..
503				}) => candidates.extend(more),
504				Err(error) => return Err(error),
505			}
506		}
507		if candidates.is_empty() && found.len() == 1 {
508			return Ok(found[0]);
509		}
510		// A user, device, replica or space by its name is the personal space's, where other
511		// spaces hold records of them too, by the same names.
512		if candidates.is_empty() && self.chosen.is_none() {
513			let personal: Vec<_> = found
514				.iter()
515				.filter(|(space, _)| *space == self.info.personal)
516				.collect();
517			let elsewhere_records = found
518				.iter()
519				.filter(|(space, _)| *space != self.info.personal)
520				.try_fold(true, |all, &(space, entity)| {
521					Ok::<_, NodeError>(all && self.is_library_record(space, entity)?)
522				})?;
523			if let [only] = personal.as_slice()
524				&& elsewhere_records
525				&& self.is_library_record(only.0, only.1)?
526			{
527				return Ok(**only);
528			}
529		}
530		if candidates.is_empty() && found.is_empty() {
531			return Err(NodeError::NoEntity(reference.to_owned()));
532		}
533		candidates.extend(found.iter().map(|(_, entity)| *entity));
534		Err(NodeError::Ambiguous {
535			reference: reference.to_owned(),
536			candidates,
537		})
538	}
539
540	/// Whether an entity is one of the library's own records of who and where: a user, a
541	/// device, a replica or a space.
542	fn is_library_record(&self, space: SpaceId, entity: EntityId) -> Result<bool, NodeError> {
543		let records = [
544			nibkeep_governance::USER,
545			nibkeep_governance::DEVICE,
546			nibkeep_governance::REPLICA,
547			SPACE,
548		];
549		Ok(self
550			.own_types(space, entity)?
551			.iter()
552			.any(|kind| records.contains(kind)))
553	}
554
555	/// Settles the spaces besides the personal one after a sync: it takes the spaces the
556	/// personal space gives it, as its choices and its mark for new spaces say, asks to be
557	/// listed in those it is not listed in, lists the replicas of its user that asked in
558	/// those it is listed in, carries its user's devices' drops there, gives the spaces it
559	/// holds to the recovery codes that lack them, and brings their names up to date in the
560	/// personal space. An AI agent's replica only takes the spaces given it, those chosen
561	/// for it, and asks, lists and gives nothing.
562	pub(crate) fn settle_spaces(
563		&mut self,
564		wall_millis: u64,
565		rng: &mut impl CryptoRng,
566	) -> Result<(), NodeError> {
567		let personal = self.info.personal;
568		let own = self.replica.signing.verifying_key();
569		let ai_agent = {
570			let open = self.space(personal)?;
571			let log = open.stored.log();
572			if !log.is_listed(&own, &open.keys)? || log.is_revoked(&own, &open.keys)? {
573				return Ok(());
574			}
575			log.is_ai_agent(&own, &open.keys)?
576		};
577		// An AI agent's replica only takes the spaces chosen for it, as the replica that
578		// paired it gave them, and lists, asks and gives nothing.
579		if ai_agent {
580			let read = self.read_personal()?;
581			return self.take_space_entries(&read, wall_millis, rng);
582		}
583		// What the personal space says is read once: what the steps add to it, the requests
584		// of this replica, is nothing the later steps take.
585		let read = self.read_personal()?;
586		if read.entries.is_empty() && self.spaces.len() == 1 {
587			return Ok(());
588		}
589		let roster = self.roster(personal)?;
590		// Each step goes on whatever another's error; the first is told at the end.
591		let results = [
592			self.take_space_entries(&read, wall_millis, rng),
593			self.ask_to_be_listed(&read, wall_millis, rng),
594			self.revoke_in_spaces(wall_millis, rng),
595			self.carry_codes_of(&roster, wall_millis, rng),
596			self.list_who_asked(&read, &roster, wall_millis, rng),
597			self.carry_choices(&read, &roster, wall_millis, rng),
598			self.give_space_entries_with(&read, &roster, wall_millis, rng),
599			self.settle_space_names(wall_millis, rng),
600		];
601		results.into_iter().collect()
602	}
603
604	/// Revokes, in each space besides the personal one that this replica is listed in, the
605	/// keys of its member's replicas that the personal space revokes, each space with a new
606	/// key, as a revocation there does: a lost device is revoked in every space of its user.
607	/// So are the devices that a revoked one added there and that the personal space does
608	/// not list, as [`Library::revoke_in_spaces_telling`] says.
609	pub(crate) fn revoke_in_spaces(
610		&mut self,
611		wall_millis: u64,
612		rng: &mut impl CryptoRng,
613	) -> Result<(), NodeError> {
614		self.revoke_in_spaces_telling(wall_millis, rng).1
615	}
616
617	/// Revokes in each space as [`Library::revoke_in_spaces`] says, with the replicas of this
618	/// replica's member there that the personal space does not list, and that a replica it
619	/// revokes added, there or in another space or group, or one so added in turn, once every
620	/// other device of the person's that remains has told this one of all it held after it
621	/// learned of the revocations: the personal space no longer counts what a revoked
622	/// replica listed that its revocation does not build on, so nothing tells such a device
623	/// from one that a thief paired on the lost one, and no device of the person's could name
624	/// it to revoke it. One that a replica the personal space lists and does not revoke added
625	/// too stays, as do those that it added in turn; so does one added by itself alone, as on
626	/// a record made for it, as nothing tells whose it is. Returns the spaces and groups
627	/// where it revoked such a replica, and the first error, as a space where it fails is
628	/// left until the next sync.
629	pub(crate) fn revoke_in_spaces_telling(
630		&mut self,
631		wall_millis: u64,
632		rng: &mut impl CryptoRng,
633	) -> (Vec<SpaceId>, Result<(), NodeError>) {
634		let personal = self.info.personal;
635		// What cannot be read now is decided after a later sync, and told.
636		let (ended, mut first_error) = match self.ended_by_revocations() {
637			Ok(ended) => (ended, Ok(())),
638			Err(error) => (BTreeSet::new(), Err(error)),
639		};
640		let mut elsewhere = Vec::new();
641		for space in self.spaces() {
642			if space == personal {
643				continue;
644			}
645			match self.revoke_in_space(space, &ended, wall_millis, rng) {
646				Ok(true) => elsewhere.push(space),
647				Ok(false) => {}
648				Err(error) => {
649					if first_error.is_ok() {
650						first_error = Err(error);
651					}
652				}
653			}
654		}
655		(elsewhere, first_error)
656	}
657
658	/// The keys, of this replica's member in a space or group of its own and of no replica
659	/// that the personal space lists, that a replica it revokes added, as
660	/// [`Library::revoke_in_spaces_telling`] says: none while the personal space revokes
661	/// nothing, while no space lists such a key, and while another device of the person's,
662	/// but an AI agent's, has not told yet of all it held after it learned of every
663	/// revocation, as its latest account in the personal space says.
664	///
665	/// # Errors
666	///
667	/// Returns an error if a space cannot be read.
668	fn ended_by_revocations(&self) -> Result<BTreeSet<[u8; 32]>, NodeError> {
669		let personal = self.info.personal;
670		let (mut standing, mut revoked) = (BTreeSet::new(), BTreeSet::new());
671		// The keys of each other replica that remains, but AI agents', which add no device.
672		let mut others: Vec<Vec<VerifyingKey>> = Vec::new();
673		{
674			let roster = self.roster(personal)?;
675			let open = self.space(personal)?;
676			let log = open.stored.log();
677			for record in roster.replicas() {
678				let keys = roster.keys_of(record);
679				let (mut stands, mut ai_agent) = (false, false);
680				for key in keys {
681					if log.is_revoked(key, &open.keys)? {
682						revoked.insert(*key.as_bytes());
683					} else {
684						standing.insert(*key.as_bytes());
685						stands = true;
686					}
687					ai_agent |= log.is_ai_agent(key, &open.keys)?;
688				}
689				if stands && !ai_agent && record != self.info.replica {
690					others.push(keys.to_vec());
691				}
692			}
693		}
694		if revoked.is_empty() {
695			return Ok(BTreeSet::new());
696		}
697		let known = |key: &[u8; 32]| standing.contains(key) || revoked.contains(key);
698		let (listers, waiting) = self.own_listers(&known)?;
699		if !waiting {
700			return Ok(BTreeSet::new());
701		}
702		if !self.told_since_revoked(&others, &revoked)? {
703			return Ok(BTreeSet::new());
704		}
705		Ok(ended_by_revoked(&listers, &standing, &revoked))
706	}
707
708	/// In each space and group of this replica's but the personal space, the keys that added
709	/// each key of this replica's member there, by the counting changes that list it, or, for
710	/// a key listed by a recovery code, the replica that named the code there; and whether a
711	/// key that `known` leaves out, of no replica that the personal space lists, is listed
712	/// there and not revoked.
713	///
714	/// # Errors
715	///
716	/// Returns an error if a space cannot be read.
717	fn own_listers(&self, known: &dyn Fn(&[u8; 32]) -> bool) -> Result<(Listers, bool), NodeError> {
718		let personal = self.info.personal;
719		let mut listers = Listers::new();
720		let mut waiting = false;
721		for space in self.spaces() {
722			if space == personal {
723				continue;
724			}
725			let Some(member) = self.member_in(space)? else {
726				continue;
727			};
728			let roster = self.roster(space)?;
729			let open = self.space(space)?;
730			let log = open.stored.log();
731			let mut added: Vec<(VerifyingKey, [u8; 32])> = Vec::new();
732			for governing in log.governing_statements(&open.keys)? {
733				if !governing.counts {
734					continue;
735				}
736				let text = governing.statement.value.as_text();
737				if governing.lists
738					&& governing.statement.field == fields::SIGNING_KEY
739					&& let Some(key) = text.and_then(VerifyingKey::from_text)
740				{
741					added.push((key, *governing.author.as_bytes()));
742				} else if governing.statement.field == fields::RECOVERY_LISTING
743					&& let Some(listing) = text.and_then(RecoveryListing::from_text)
744					&& listing.space == space
745					&& listing.verifies()
746					&& let Some(code) = roster.code(listing.code_record())
747				{
748					// Listed by a code: added by whoever named the code there.
749					added.push((listing.key, *code.author.as_bytes()));
750				}
751			}
752			for (key, by) in added {
753				if self.listing_owner(space, &key)? != Some(member) {
754					continue;
755				}
756				listers.entry(*key.as_bytes()).or_default().insert(by);
757				waiting |= !known(key.as_bytes()) && !log.is_revoked(&key, &open.keys)?;
758			}
759		}
760		Ok((listers, waiting))
761	}
762
763	/// Whether each of `others`, the keys of each other replica of the person's that remains,
764	/// has told this one of all it held after it learned of the revocations of the keys of
765	/// `revoked`: whether its latest account in the personal space names heads that this
766	/// replica holds, and that build on each of those revocations.
767	///
768	/// # Errors
769	///
770	/// Returns an error if the personal space cannot be read.
771	fn told_since_revoked(
772		&self,
773		others: &[Vec<VerifyingKey>],
774		revoked: &BTreeSet<[u8; 32]>,
775	) -> Result<bool, NodeError> {
776		let personal = self.info.personal;
777		let open = self.space(personal)?;
778		let log = open.stored.log();
779		let mut revocations: BTreeSet<nibkeep_log::ChangeId> = BTreeSet::new();
780		for bytes in revoked {
781			if let Some(key) = VerifyingKey::from_bytes(bytes) {
782				revocations.extend(log.revocations_of(Some(&key), &open.keys)?);
783			}
784		}
785		let heads = self.other_heads(personal)?;
786		for keys in others {
787			let mut told = false;
788			for (author, head) in &heads {
789				if told || !keys.iter().any(|key| key.as_bytes() == author) {
790					continue;
791				}
792				// Held here and applied, as a change whose payload is still to come lists
793				// nothing yet.
794				let mut all = true;
795				for &held in &head.heads {
796					all = all && log.is_complete(held)?;
797				}
798				for &revocation in &revocations {
799					if !all {
800						break;
801					}
802					let mut known = false;
803					for &held in &head.heads {
804						if log.builds_on_all(held, &[revocation])? {
805							known = true;
806							break;
807						}
808					}
809					all = known;
810				}
811				told = all;
812			}
813			if !told {
814				return Ok(false);
815			}
816		}
817		Ok(true)
818	}
819
820	/// Carries the person's recovery codes into each space besides the personal one that this
821	/// replica is listed in, a group too: it names there, on its member's record for each,
822	/// the codes that stand in the personal space and that the space lacks, and revokes
823	/// there, with a new key, those that the personal space revokes. Only a member's own
824	/// replicas name or revoke their codes, so each user's replicas carry their own
825	/// ([technical design](../../../../docs/Technical-design.md#111-recovery-codes)).
826	pub(crate) fn carry_codes(
827		&mut self,
828		wall_millis: u64,
829		rng: &mut impl CryptoRng,
830	) -> Result<(), NodeError> {
831		let roster = self.roster(self.info.personal)?;
832		self.carry_codes_of(&roster, wall_millis, rng)
833	}
834
835	/// Carries the codes that the personal space's roster `roster` names, as
836	/// [`Library::carry_codes`] does.
837	fn carry_codes_of(
838		&mut self,
839		roster: &Roster,
840		wall_millis: u64,
841		rng: &mut impl CryptoRng,
842	) -> Result<(), NodeError> {
843		let personal = self.info.personal;
844		let codes: Vec<Code> = roster.codes().cloned().collect();
845		if codes.is_empty() {
846			return Ok(());
847		}
848		let mut first_error = Ok(());
849		for space in self.spaces() {
850			if space == personal {
851				continue;
852			}
853			let carried = self.carry_codes_into(space, &codes, wall_millis, rng);
854			if first_error.is_ok() {
855				first_error = carried;
856			}
857		}
858		first_error
859	}
860
861	/// Carries the codes into one space, as [`Library::carry_codes`] does.
862	fn carry_codes_into(
863		&mut self,
864		space: SpaceId,
865		codes: &[Code],
866		wall_millis: u64,
867		rng: &mut impl CryptoRng,
868	) -> Result<(), NodeError> {
869		// Only where this replica is listed for a member, of the space itself or of a group
870		// that gives it a role there, whose record the code's record there is derived from,
871		// and who did not leave.
872		let Some(member) = self.code_member_in(space)? else {
873			return Ok(());
874		};
875		if self.has_left(space)? {
876			return Ok(());
877		}
878		let roster = self.roster(space)?;
879		// The codes to name there, on that member's record, unless another record of the
880		// member's that gives them a role names it already, as one named before its member
881		// was made direct; and those to revoke, on each record of the member's that names
882		// them. The member's records are read only where a code needs them.
883		let mut own_members = None;
884		let mut naming = Vec::new();
885		let mut revoking = Vec::new();
886		for code in codes {
887			let stated = code.statement.for_member(member);
888			let record = stated.record(space);
889			if code.stands() && roster.code(record).is_some() {
890				continue;
891			}
892			if own_members.is_none() {
893				own_members = Some(self.own_code_members(space)?);
894			}
895			let own_members = own_members.as_deref().unwrap_or_default();
896			if code.stands() {
897				let named_elsewhere = own_members.iter().any(|&own| {
898					roster
899						.code(code.statement.for_member(own).record(space))
900						.is_some_and(Code::stands)
901				});
902				if !named_elsewhere {
903					naming.push((record, stated));
904				}
905				continue;
906			}
907			for &own in own_members {
908				let record = code.statement.for_member(own).record(space);
909				if roster.code(record).is_some_and(Code::stands)
910					&& !revoking.contains(&(record, code.statement.key))
911				{
912					revoking.push((record, code.statement.key));
913				}
914			}
915		}
916		if naming.is_empty() && revoking.is_empty() {
917			return Ok(());
918		}
919		// But what this replica stated there before, whether it counts or not: it names and
920		// revokes each code once, so that a statement set aside is not made at every sync.
921		let own = self.replica.signing.verifying_key();
922		let stated_before: BTreeSet<(EntityId, bool)> = {
923			let open = self.space(space)?;
924			open.stored
925				.log()
926				.governing_statements(&open.keys)?
927				.into_iter()
928				.filter(|governing| governing.author == own)
929				.filter_map(|governing| {
930					let field = &governing.statement.field;
931					(*field == fields::RECOVERY_KEY || *field == fields::RECOVERY_REVOKED).then(
932						|| {
933							(
934								governing.statement.entity,
935								*field == fields::RECOVERY_REVOKED,
936							)
937						},
938					)
939				})
940				.collect()
941		};
942		let naming: Vec<Operation> = naming
943			.into_iter()
944			.filter(|(record, _)| !stated_before.contains(&(*record, false)))
945			.map(|(_, stated)| state_recovery_code(space, &stated, rng))
946			.collect();
947		revoking.retain(|(record, _)| !stated_before.contains(&(*record, true)));
948		if !naming.is_empty() {
949			self.commit(space, naming, wall_millis, rng)?;
950			// The keys given out there so far, as a replica that lacks them is given them.
951			self.give_keys(space, wall_millis, rng)?;
952		}
953		// Each record in a change of its own, with a new key: a revocation that the log sets
954		// aside on one record, as on a record in a group that a removal from the group took
955		// the member's path through, leaves those on the others standing.
956		for revoked in revoking {
957			let roster = self.roster(space)?;
958			self.rotate_revoking(space, &[], &[revoked], &roster, wall_millis, rng)?;
959		}
960		Ok(())
961	}
962
963	/// This replica's member in a space, for the codes it names there: its member in the
964	/// space itself; or else, for a member through a group alone that has a role there, its
965	/// member in the group that the space's rules name for its key, as history names it.
966	fn code_member_in(&self, space: SpaceId) -> Result<Option<EntityId>, NodeError> {
967		if let Some(member) = self.member_in(space)? {
968			return Ok(Some(member));
969		}
970		if self.own_role(space)? == crate::MemberRole::None {
971			return Ok(None);
972		}
973		let open = self.space(space)?;
974		let own = self.replica.signing.verifying_key();
975		Ok(open
976			.stored
977			.log()
978			.group_member_of(&own, &open.keys)?
979			.map(|(_, member)| member))
980	}
981
982	/// Each record of this replica's member in a space that its codes there may be named
983	/// on: its member in the space itself, and its member in each group that the space
984	/// follows, lists its key, and gives that member a role there now.
985	pub(crate) fn own_code_members(&self, space: SpaceId) -> Result<Vec<EntityId>, NodeError> {
986		let mut members: Vec<EntityId> = self.member_in(space)?.into_iter().collect();
987		let open = self.space(space)?;
988		let log = open.stored.log();
989		let roles = log.group_member_roles(&open.keys)?;
990		let own = self.replica.signing.verifying_key();
991		for (_, member) in log.group_members_of(&own, &open.keys)? {
992			let has_role = roles
993				.get(&member)
994				.is_some_and(|role| *role != crate::MemberRole::None);
995			if has_role && !members.contains(&member) {
996				members.push(member);
997			}
998		}
999		Ok(members)
1000	}
1001
1002	/// Revokes in one space, as [`Library::revoke_in_spaces_telling`] does, with the keys of
1003	/// `ended` too, which [`Library::ended_by_revocations`] gives. Returns whether it revoked
1004	/// one of those.
1005	fn revoke_in_space(
1006		&mut self,
1007		space: SpaceId,
1008		ended: &BTreeSet<[u8; 32]>,
1009		wall_millis: u64,
1010		rng: &mut impl CryptoRng,
1011	) -> Result<bool, NodeError> {
1012		let personal = self.info.personal;
1013		let Some(member) = self.member_in(space)? else {
1014			return Ok(false);
1015		};
1016		// A replica whose member left changes nothing there.
1017		if self.has_left(space)? {
1018			return Ok(false);
1019		}
1020		let roster = self.roster(space)?;
1021		let mut revoking = Vec::new();
1022		let mut unknown = false;
1023		{
1024			let open = self.space(space)?;
1025			let log = open.stored.log();
1026			let personal_open = self.space(personal)?;
1027			let personal_log = personal_open.stored.log();
1028			for record in roster.replicas() {
1029				for key in roster.keys_of(record) {
1030					let added_by_revoked = ended.contains(key.as_bytes());
1031					if log.is_revoked(key, &open.keys)?
1032						|| !(added_by_revoked
1033							|| personal_log.is_revoked(key, &personal_open.keys)?)
1034						|| self.listing_owner(space, key)? != Some(member)
1035					{
1036						continue;
1037					}
1038					unknown |= added_by_revoked;
1039					revoking.push((record, *key));
1040				}
1041			}
1042		}
1043		if !revoking.is_empty() {
1044			self.rotate(space, &revoking, &roster, wall_millis, rng)?;
1045		}
1046		Ok(unknown)
1047	}
1048
1049	/// The owner that a key's latest counting listing in a space with members names.
1050	fn listing_owner(
1051		&self,
1052		space: SpaceId,
1053		key: &nibkeep_crypto::VerifyingKey,
1054	) -> Result<Option<EntityId>, NodeError> {
1055		let open = self.space(space)?;
1056		let record = replica_record(space, key);
1057		Ok(open
1058			.stored
1059			.log()
1060			.governing_statements(&open.keys)?
1061			.into_iter()
1062			.filter(|governing| governing.statement.entity == record)
1063			.filter_map(|governing| Listing::from_text(governing.counting_text(&LISTING)?))
1064			// The latest, as a device that came back is listed again for its new member.
1065			.rfind(|listing| listing.key == *key && listing.verifies())
1066			.map(|listing| listing.owner))
1067	}
1068
1069	/// What the counting governing changes of the personal space say of the user's spaces:
1070	/// the entries that give them, and the listings that ask to be listed in them, each as
1071	/// `(record, text)`. Read once for each settling, as reading them goes through every
1072	/// governing change.
1073	pub(super) fn read_personal(&self) -> Result<Personal, NodeError> {
1074		let open = self.space(self.info.personal)?;
1075		let mut personal = Personal::default();
1076		for governing in open.stored.log().governing_statements(&open.keys)? {
1077			let entity = governing.statement.entity;
1078			if let Some(text) = governing.counting_text(&SPACE_ENTRY) {
1079				personal.entries.push((entity, text.to_owned()));
1080			} else if let Some(text) = governing.counting_text(&LISTING) {
1081				personal.listings.push((entity, text.to_owned()));
1082			} else if let Some(text) = governing.counting_text(&fields::SPACE_CHOICE) {
1083				personal.choices.push((entity, text.to_owned()));
1084			} else if governing.counts
1085				&& governing.statement.field == fields::NEW_SPACES
1086				&& let nibkeep_model::Value::Boolean(takes) = governing.statement.value
1087			{
1088				personal.marks.push((entity, governing.author, takes));
1089			}
1090		}
1091		Ok(personal)
1092	}
1093
1094	/// The spaces that the personal space gives this replica, and the member it is in each.
1095	pub(super) fn own_entries(&self, personal: &Personal) -> Vec<SpaceEntry> {
1096		let own = self.info.replica;
1097		personal
1098			.entries
1099			.iter()
1100			.filter(|(record, _)| *record == own)
1101			.filter_map(|(_, text)| SpaceEntry::from_text(text))
1102			.collect()
1103	}
1104
1105	/// Takes the spaces that the personal space gives this replica and that it lacks, as
1106	/// [`Library::takes_entry`] says: where its newest choice of the space holds it, as when
1107	/// it asked, or it chose none and takes new spaces, never where it declined or dropped
1108	/// the space; opens each first key, keeps it if its hash is the one named, makes the
1109	/// space, empty until it syncs it, and states, in one change, that it holds those it
1110	/// took. An AI agent's replica takes every space given it, those chosen for it.
1111	fn take_space_entries(
1112		&mut self,
1113		personal: &Personal,
1114		wall_millis: u64,
1115		rng: &mut impl CryptoRng,
1116	) -> Result<(), NodeError> {
1117		let takes_new = self.own_mark(personal);
1118		self.take_space_entries_as(personal, takes_new, wall_millis, rng)
1119	}
1120
1121	/// Takes the spaces given to this replica that it lacks, as
1122	/// [`Library::take_space_entries`] does, where it chose none of them as `takes_new`
1123	/// says: as its mark says, or, after pairing, every one, as the person chose them there.
1124	pub(super) fn take_space_entries_as(
1125		&mut self,
1126		personal: &Personal,
1127		takes_new: bool,
1128		wall_millis: u64,
1129		rng: &mut impl CryptoRng,
1130	) -> Result<(), NodeError> {
1131		let ai_agent = self.is_ai_agent()?;
1132		let own = self.own_choices(personal);
1133		let takes_new = ai_agent || takes_new;
1134		let mut taken = Vec::new();
1135		for entry in self.own_entries(personal) {
1136			if self.spaces.contains_key(&entry.space)
1137				|| !(ai_agent || Self::takes_entry(own.get(&entry.space).copied(), takes_new))
1138			{
1139				continue;
1140			}
1141			let Some(key) = entry.open(&self.replica.decryption, self.info.replica) else {
1142				continue;
1143			};
1144			if key_hash(&key) == entry.hash {
1145				self.add_space(entry.space, &key, rng)?;
1146				taken.push(entry.space);
1147			}
1148		}
1149		self.expect_roots_of(personal)?;
1150		if ai_agent || taken.is_empty() {
1151			return Ok(());
1152		}
1153		self.state_holding(&taken, wall_millis, rng)
1154	}
1155
1156	/// Has each space that this replica holds, but has not taken the first change of yet,
1157	/// take as its first change only one that an entry of the personal space names: so that
1158	/// another replica cannot have it take one of its own making.
1159	pub(crate) fn expect_space_roots(&mut self) -> Result<(), NodeError> {
1160		// Nothing to read where every space has its first change, as is usual.
1161		let mut waiting = false;
1162		for open in self.spaces.values() {
1163			waiting |= open.stored.log().root()?.is_none();
1164		}
1165		if !waiting {
1166			return Ok(());
1167		}
1168		let read = self.read_personal()?;
1169		self.expect_roots_of(&read)
1170	}
1171
1172	/// Pins the first change of each space that lacks one to the root that the entry which
1173	/// gave this replica its first key names: the first entry, in the order of the personal
1174	/// space's statements, with that key's hash, as the entry taken was. Besides any that a
1175	/// group names, so that the order in which each source is read does not matter.
1176	fn expect_roots_of(&mut self, personal: &Personal) -> Result<(), NodeError> {
1177		let entries = self.own_entries(personal);
1178		for (&space, open) in &mut self.spaces {
1179			if open.stored.log().root()?.is_some() {
1180				continue;
1181			}
1182			let Some(hash) = open.first_key_hash() else {
1183				continue;
1184			};
1185			if let Some(entry) = entries
1186				.iter()
1187				.find(|entry| entry.space == space && entry.hash == hash)
1188			{
1189				open.stored
1190					.expect_roots_too([nibkeep_log::ChangeId::from_hash(entry.root)]);
1191			}
1192		}
1193		Ok(())
1194	}
1195
1196	/// Asks to be listed in each space this replica holds but is not listed in, and has not
1197	/// asked to be listed in yet, with the listing its key signed, owned by the member that
1198	/// the space's entry names.
1199	fn ask_to_be_listed(
1200		&mut self,
1201		personal: &Personal,
1202		wall_millis: u64,
1203		rng: &mut impl CryptoRng,
1204	) -> Result<(), NodeError> {
1205		let own = self.replica.signing.verifying_key();
1206		let asked: BTreeSet<SpaceId> = personal
1207			.listings
1208			.iter()
1209			.filter(|(record, _)| *record == self.info.replica)
1210			.filter_map(|(_, text)| Listing::from_text(text))
1211			.filter(|listing| listing.key == own)
1212			.map(|listing| listing.space)
1213			.collect();
1214		let mut operations = Vec::new();
1215		for entry in self.own_entries(personal) {
1216			if asked.contains(&entry.space)
1217				|| operations.iter().any(|(space, _)| *space == entry.space)
1218			{
1219				continue;
1220			}
1221			let Ok(open) = self.space(entry.space) else {
1222				continue;
1223			};
1224			if open.stored.log().is_listed(&own, &open.keys)?
1225				&& open.stored.log().is_governed(&open.keys)?
1226			{
1227				continue;
1228			}
1229			let listing = Listing::sign(
1230				&self.replica.signing,
1231				&self.replica.decryption.encryption_key(),
1232				entry.space,
1233				(entry.member, false),
1234			);
1235			operations.push((
1236				entry.space,
1237				ask_to_be_listed(self.info.replica, &listing.to_text(), rng),
1238			));
1239		}
1240		if operations.is_empty() {
1241			return Ok(());
1242		}
1243		let personal = self.info.personal;
1244		let operations = operations
1245			.into_iter()
1246			.map(|(_, operation)| operation)
1247			.collect();
1248		self.commit(personal, operations, wall_millis, rng)
1249	}
1250
1251	/// Lists, in each space this replica is listed in, the replicas of its user that asked to
1252	/// be: those whose records in the personal space hold a listing of their own key for the
1253	/// space, owned by this replica's member there, that is not listed yet, and that are not
1254	/// revoked or AI agents', nor declined or dropped the space by their newest choice of it
1255	/// there.
1256	fn list_who_asked(
1257		&mut self,
1258		asks: &Personal,
1259		roster: &Roster,
1260		wall_millis: u64,
1261		rng: &mut impl CryptoRng,
1262	) -> Result<(), NodeError> {
1263		let personal = self.info.personal;
1264		let own = self.replica.signing.verifying_key();
1265		let newest = Self::newest_choices(asks, roster);
1266		for space in self.spaces() {
1267			if space == personal {
1268				continue;
1269			}
1270			let Some(member) = self.member_in(space)? else {
1271				continue;
1272			};
1273			// Nobody lists a replica of a member who left.
1274			if self.has_left(space)? {
1275				continue;
1276			}
1277			let mut operations = Vec::new();
1278			let mut listed_now = BTreeSet::new();
1279			for (asker, text) in &asks.listings {
1280				let Some(listing) = Listing::from_text(text) else {
1281					continue;
1282				};
1283				// The cheap checks first: a listing is checked only if it may be listed.
1284				if listing.space != space
1285					|| listing.owner != member
1286					|| listing.ai_agent
1287					|| listing.key == own
1288					|| !roster.keys_of(*asker).contains(&listing.key)
1289					|| listed_now.contains(listing.key.as_bytes())
1290					|| newest
1291						.get(&(space, *listing.key.as_bytes()))
1292						.is_some_and(|(_, choice)| !choice.holds)
1293				{
1294					continue;
1295				}
1296				{
1297					let open = self.space(space)?;
1298					if open.stored.log().is_listed(&listing.key, &open.keys)? {
1299						continue;
1300					}
1301					let personal_open = self.space(personal)?;
1302					let log = personal_open.stored.log();
1303					if log.is_revoked(&listing.key, &personal_open.keys)?
1304						|| log.is_ai_agent(&listing.key, &personal_open.keys)?
1305						|| !listing.verifies()
1306					{
1307						continue;
1308					}
1309				}
1310				// The encryption key that the listing signed, or the listing would not count.
1311				let Some(encryption) = roster.encryption_of(*asker).cloned() else {
1312					continue;
1313				};
1314				if nibkeep_governance::encryption_hash(&encryption.to_bytes()) != listing.encryption
1315				{
1316					continue;
1317				}
1318				let (device, app, endpoint) = self.replica_names(*asker)?;
1319				let listed = list_replica(
1320					&SpaceReplica {
1321						record: listing.record,
1322						device_record: nibkeep_governance::device_record(space, &listing.key),
1323						member,
1324						signing: &listing.key,
1325						encryption: &encryption,
1326						listing: text,
1327						endpoint: endpoint.as_ref(),
1328						device: device.as_deref().unwrap_or_default(),
1329						app: app.as_deref().unwrap_or_default(),
1330						ai_agent: false,
1331					},
1332					rng,
1333				);
1334				listed_now.insert(*listing.key.as_bytes());
1335				operations.push(listed);
1336			}
1337			if operations.is_empty() {
1338				continue;
1339			}
1340			// The listings govern the space, and go in a change of their own first.
1341			let operations: Vec<Operation> = operations
1342				.into_iter()
1343				.flat_map(|listed| listed.governing.into_iter().chain(listed.operations))
1344				.collect();
1345			self.commit(space, operations, wall_millis, rng)?;
1346			self.give_keys(space, wall_millis, rng)?;
1347		}
1348		Ok(())
1349	}
1350
1351	/// Gives each space this replica holds and is listed in, other than the personal one, to
1352	/// every recovery code that stands in the personal space and has no entry of it yet: its
1353	/// first key, sealed to that code, with the user's member there, in one change of the
1354	/// personal space. A code is given every space of the user's, as a device that it brings
1355	/// back takes those it holds; a device of the user's is given a space only with the
1356	/// person's consent ([`Library::give_space`]).
1357	pub(crate) fn give_space_entries(
1358		&mut self,
1359		wall_millis: u64,
1360		rng: &mut impl CryptoRng,
1361	) -> Result<(), NodeError> {
1362		let personal = self.read_personal()?;
1363		let roster = self.roster(self.info.personal)?;
1364		self.give_space_entries_with(&personal, &roster, wall_millis, rng)
1365	}
1366
1367	/// Gives the spaces as [`Library::give_space_entries`] does, from what the personal
1368	/// space says, read before.
1369	fn give_space_entries_with(
1370		&mut self,
1371		read: &Personal,
1372		roster: &Roster,
1373		wall_millis: u64,
1374		rng: &mut impl CryptoRng,
1375	) -> Result<(), NodeError> {
1376		let personal = self.info.personal;
1377		let given = read.given();
1378		// The recovery codes that stand, each on its record, so that a device that a code
1379		// brings back finds the user's spaces.
1380		let remaining: Vec<(EntityId, nibkeep_crypto::EncryptionKey)> = roster
1381			.codes()
1382			.filter(|code| code.stands())
1383			.map(|code| (code.record, code.statement.encryption.clone()))
1384			.collect();
1385		if remaining.is_empty() {
1386			return Ok(());
1387		}
1388		let mut operations = Vec::new();
1389		for space in self.spaces() {
1390			// A space that the user left reaches none of their codes that lack it.
1391			if space == personal || self.member_in(space)?.is_none() || self.has_left(space)? {
1392				continue;
1393			}
1394			for (code, encryption) in &remaining {
1395				if !given.contains(&(*code, space)) {
1396					operations.extend(self.entry_for(space, (*code, encryption), rng)?);
1397				}
1398			}
1399		}
1400		if operations.is_empty() {
1401			return Ok(());
1402		}
1403		self.commit(personal, operations, wall_millis, rng)
1404	}
1405
1406	/// States this replica's choice of a space: whether it holds it, signed by its key, with a
1407	/// number one above the highest of its choices of that space that the personal space and
1408	/// the space state; on its own record in the personal space, where its user's other
1409	/// devices read it, and, where this replica holds the space, by its choices too, and is
1410	/// listed there, on its record there, where a choice not to hold it ends this replica,
1411	/// as a removal does
1412	/// ([technical design](../../../../docs/Technical-design.md#1310-devices-that-choose-their-spaces)).
1413	///
1414	/// # Errors
1415	///
1416	/// Returns [`NodeError::PersonalSpaceHeld`] for the personal space, and an error if this
1417	/// replica is an AI agent's, or a change cannot be saved.
1418	pub fn state_space_choice(
1419		&mut self,
1420		space: SpaceId,
1421		holds: bool,
1422		wall_millis: u64,
1423		rng: &mut impl CryptoRng,
1424	) -> Result<Choice, NodeError> {
1425		let personal = self.info.personal;
1426		if space == personal {
1427			return Err(NodeError::PersonalSpaceHeld);
1428		}
1429		let own = self.replica.signing.verifying_key();
1430		{
1431			let open = self.space(personal)?;
1432			if open.stored.log().is_ai_agent(&own, &open.keys)? {
1433				return Err(NodeError::AiAgentMayNot("choose the spaces it holds"));
1434			}
1435		}
1436		let number = self
1437			.highest_choice(space, &self.read_personal()?)?
1438			.map_or(1, |number| number + 1);
1439		let choice = Choice::sign(&self.replica.signing, space, number, holds);
1440		let operation = state_choice(self.info.replica, &choice, rng);
1441		self.commit(personal, vec![operation], wall_millis, rng)?;
1442		// Where it dropped the space, it changes nothing there: a device of its user carries
1443		// a choice to hold it there, once the person approves.
1444		if self.spaces.contains_key(&space) && self.changes_there(space)? {
1445			let operation = state_choice(choice.record, &choice, rng);
1446			self.commit(space, vec![operation], wall_millis, rng)?;
1447		}
1448		Ok(choice)
1449	}
1450
1451	/// The number of the highest of this replica's choices of a space that the personal space
1452	/// states, `personal`, or that the space states, where this replica holds it.
1453	pub(super) fn highest_choice(
1454		&self,
1455		space: SpaceId,
1456		personal: &Personal,
1457	) -> Result<Option<u64>, NodeError> {
1458		let own = self.replica.signing.verifying_key();
1459		let mut highest = personal
1460			.choices
1461			.iter()
1462			.filter(|(record, _)| *record == self.info.replica)
1463			.filter_map(|(_, text)| Choice::from_text(text))
1464			.filter(|choice| choice.space == space && choice.key == own && choice.verifies())
1465			.map(|choice| choice.number)
1466			.max();
1467		if self.spaces.contains_key(&space) {
1468			let open = self.space(space)?;
1469			if let Some((number, _)) = open.stored.log().standing_choice(&own, &open.keys)? {
1470				highest = highest.max(Some(number));
1471			}
1472		}
1473		Ok(highest)
1474	}
1475
1476	/// Of the choices that the personal space, `personal`, states for the replicas of its user
1477	/// that `roster` lists, each on that replica's own record, signed by its key of its own,
1478	/// and that verify, the newest of each replica's for each space: by space and key, the
1479	/// replica's record and the choice with the highest number, a drop winning a tie.
1480	pub(super) fn newest_choices(
1481		personal: &Personal,
1482		roster: &Roster,
1483	) -> BTreeMap<(SpaceId, [u8; 32]), (EntityId, Choice)> {
1484		let mut newest: BTreeMap<(SpaceId, [u8; 32]), (EntityId, Choice)> = BTreeMap::new();
1485		for (record, text) in &personal.choices {
1486			let Some(choice) = Choice::from_text(text) else {
1487				continue;
1488			};
1489			if !roster.keys_of(*record).contains(&choice.key) || !choice.verifies() {
1490				continue;
1491			}
1492			let rank = |choice: &Choice| (choice.number, !choice.holds);
1493			let slot = (choice.space, *choice.key.as_bytes());
1494			if newest
1495				.get(&slot)
1496				.is_none_or(|(_, kept)| rank(&choice) > rank(kept))
1497			{
1498				newest.insert(slot, (*record, choice));
1499			}
1500		}
1501		newest
1502	}
1503
1504	/// Whether this replica may change a space with members by its role and choices: it is
1505	/// listed there, not revoked, holds the space by its choices, and its member did not
1506	/// leave.
1507	pub(super) fn changes_there(&self, space: SpaceId) -> Result<bool, NodeError> {
1508		if self.member_in(space)?.is_none() || self.has_left(space)? {
1509			return Ok(false);
1510		}
1511		let open = self.space(space)?;
1512		let own = self.replica.signing.verifying_key();
1513		Ok(open.stored.log().holds_space(&own, &open.keys)?)
1514	}
1515
1516	/// Whether this replica may carry its user's devices' choices into a space: it changes
1517	/// it as [`Library::changes_there`] says, or it is a member there through a group alone,
1518	/// with a role, holds the space by its choices, and is not revoked; so that a device's
1519	/// decline of a group's space reaches the space through a device of its user that holds
1520	/// it.
1521	fn carries_there(&self, space: SpaceId) -> Result<bool, NodeError> {
1522		if self.changes_there(space)? {
1523			return Ok(true);
1524		}
1525		if self.member_in(space)?.is_some()
1526			|| self.has_left(space)?
1527			|| self.own_role(space)? == crate::MemberRole::None
1528			|| self.check_not_revoked(space).is_err()
1529		{
1530			return Ok(false);
1531		}
1532		let open = self.space(space)?;
1533		let own = self.replica.signing.verifying_key();
1534		Ok(open.stored.log().holds_space(&own, &open.keys)?)
1535	}
1536
1537	/// Carries into each space that this replica holds and may change each newest choice of
1538	/// a replica of its user that the personal space, `personal`, states, where it is a drop
1539	/// that outranks the choice of that replica's that stands there, while that replica is
1540	/// listed there: so a device's drop reaches the space through any of its user's devices
1541	/// that holds it, also one stated while that device held nothing of the space, and never
1542	/// one that a newer choice to hold replaced. A space where this fails is left until the
1543	/// next sync, and the first error is told at the end.
1544	fn carry_choices(
1545		&mut self,
1546		personal: &Personal,
1547		roster: &Roster,
1548		wall_millis: u64,
1549		rng: &mut impl CryptoRng,
1550	) -> Result<(), NodeError> {
1551		let personal_space = self.info.personal;
1552		// The newest drops of the replicas that the personal space neither revokes nor
1553		// counts as AI agents', by space.
1554		let mut drops: BTreeMap<SpaceId, Vec<Choice>> = BTreeMap::new();
1555		{
1556			let open = self.space(personal_space)?;
1557			let log = open.stored.log();
1558			for ((space, _), (_, choice)) in Self::newest_choices(personal, roster) {
1559				if choice.holds
1560					|| log.is_revoked(&choice.key, &open.keys)?
1561					|| log.is_ai_agent(&choice.key, &open.keys)?
1562				{
1563					continue;
1564				}
1565				drops.entry(space).or_default().push(choice);
1566			}
1567		}
1568		let mut first = Ok(());
1569		for (space, choices) in drops {
1570			let carried = self.carry_into(space, &choices, wall_millis, rng);
1571			if first.is_ok() {
1572				first = carried;
1573			}
1574		}
1575		first
1576	}
1577
1578	/// Carries `choices`, newest drops of replicas of the user, into `space`, as
1579	/// [`Library::carry_choices`] says.
1580	fn carry_into(
1581		&mut self,
1582		space: SpaceId,
1583		choices: &[Choice],
1584		wall_millis: u64,
1585		rng: &mut impl CryptoRng,
1586	) -> Result<(), NodeError> {
1587		if space == self.info.personal
1588			|| !self.spaces.contains_key(&space)
1589			|| !self.carries_there(space)?
1590		{
1591			return Ok(());
1592		}
1593		let mut operations = Vec::new();
1594		{
1595			let open = self.space(space)?;
1596			let log = open.stored.log();
1597			for choice in choices {
1598				if !log.is_listed(&choice.key, &open.keys)?
1599					|| log.is_revoked(&choice.key, &open.keys)?
1600				{
1601					continue;
1602				}
1603				let stood = log.standing_choice(&choice.key, &open.keys)?;
1604				if stood.is_some_and(|(number, _)| number >= choice.number) {
1605					continue;
1606				}
1607				operations.push(state_choice(choice.record, choice, rng));
1608			}
1609		}
1610		if operations.is_empty() {
1611			return Ok(());
1612		}
1613		self.commit(space, operations, wall_millis, rng)
1614	}
1615
1616	/// Lists again, in `space`, the replica of this replica's user whose record in the
1617	/// personal space is `replica`, after it dropped the space, once it asked for the space
1618	/// again: carries there its newest choice of the space that the personal space states,
1619	/// where that is one to hold it that outranks the one that stands there, which brings it
1620	/// back, and gives it the space's keys. Step 2 calls it once the person approves on this
1621	/// device.
1622	///
1623	/// # Errors
1624	///
1625	/// Returns [`NodeError::NoNewerChoice`] if that replica's newest choice of the space is
1626	/// none, a drop, or one that does not outrank the one that stands there;
1627	/// [`NodeError::Removed`] if this replica may not change the space; and an error if a
1628	/// change cannot be saved.
1629	pub fn list_again(
1630		&mut self,
1631		space: SpaceId,
1632		replica: EntityId,
1633		wall_millis: u64,
1634		rng: &mut impl CryptoRng,
1635	) -> Result<(), NodeError> {
1636		if space == self.info.personal || !self.changes_there(space)? {
1637			return Err(NodeError::Removed);
1638		}
1639		let personal = self.read_personal()?;
1640		let roster = self.roster(self.info.personal)?;
1641		let newest = Self::newest_choices(&personal, &roster)
1642			.into_iter()
1643			.filter(|((chosen, _), (record, _))| *chosen == space && *record == replica)
1644			.map(|(_, (_, choice))| choice)
1645			.max_by_key(|choice| (choice.number, !choice.holds))
1646			.filter(|choice| choice.holds)
1647			.ok_or(NodeError::NoNewerChoice)?;
1648		{
1649			let open = self.space(space)?;
1650			let stood = open.stored.log().standing_choice(&newest.key, &open.keys)?;
1651			if stood.is_none_or(|(number, holds)| holds || number >= newest.number) {
1652				return Err(NodeError::NoNewerChoice);
1653			}
1654		}
1655		let operation = state_choice(newest.record, &newest, rng);
1656		self.commit(space, vec![operation], wall_millis, rng)?;
1657		self.give_keys(space, wall_millis, rng)
1658	}
1659
1660	/// This replica's member in a space with members, as its counting listing there names
1661	/// it, if it is listed.
1662	pub(crate) fn member_in(&self, space: SpaceId) -> Result<Option<EntityId>, NodeError> {
1663		let open = self.space(space)?;
1664		let log = open.stored.log();
1665		let own = self.replica.signing.verifying_key();
1666		if !log.has_members(&open.keys)?
1667			|| !log.is_listed(&own, &open.keys)?
1668			|| log.is_revoked(&own, &open.keys)?
1669		{
1670			return Ok(None);
1671		}
1672		self.listing_owner(space, &own)
1673	}
1674
1675	/// The names of the device and the app of a replica of the user, and its endpoint, as
1676	/// the personal space has them.
1677	pub(super) fn replica_names(&self, replica: EntityId) -> Result<ReplicaNames, NodeError> {
1678		let open = self.space(self.info.personal)?;
1679		let state = open.stored.log().state();
1680		let record = nibkeep_governance::replica(state, replica)?;
1681		let device = match record.as_ref().and_then(|record| record.device) {
1682			Some(device) => display_name(state, &open.types, &self.languages, device)?,
1683			None => None,
1684		};
1685		let app = display_name(state, &open.types, &self.languages, replica)?;
1686		Ok((device, app, record.and_then(|record| record.endpoint)))
1687	}
1688
1689	/// The names of this replica's device and app.
1690	pub(crate) fn own_names(&self) -> Result<(String, String), NodeError> {
1691		let (device, app, _) = self.replica_names(self.info.replica)?;
1692		Ok((device.unwrap_or_default(), app.unwrap_or_default()))
1693	}
1694
1695	/// An entity's name in the personal space.
1696	pub(crate) fn own_name(&self, entity: EntityId) -> Result<Option<String>, NodeError> {
1697		let open = self.space(self.info.personal)?;
1698		display_name(
1699			open.stored.log().state(),
1700			&open.types,
1701			&self.languages,
1702			entity,
1703		)
1704	}
1705
1706	/// Adds a space this replica now holds, with its first key: opens the space, empty
1707	/// until it syncs it or is founded, and then saves the key with the others, under the key
1708	/// file's lock. The log comes first, as a key without its log would keep the library
1709	/// from opening; a log without its key is passed over, and opened again when the key
1710	/// comes.
1711	pub(crate) fn add_space(
1712		&mut self,
1713		space: SpaceId,
1714		first: &Key,
1715		rng: &mut impl CryptoRng,
1716	) -> Result<(), NodeError> {
1717		let log = log_path(&self.directory, space);
1718		if let Some(folder) = log.parent() {
1719			fs::create_dir_all(folder).map_err(NodeError::file(folder))?;
1720		}
1721		let epochs = std::collections::BTreeMap::from([(0, first.clone())]);
1722		let opened = Space::open(
1723			&log,
1724			space,
1725			&epochs,
1726			&self.replica.storage,
1727			&self.code_types,
1728		)?;
1729		let compartment = self.compartment.clone();
1730		let mut saved = None;
1731		self.update_key_file(|key_file| {
1732			let mut replica = key_file.replica(&compartment)?;
1733			replica
1734				.spaces
1735				.entry(space)
1736				.or_default()
1737				.entry(0)
1738				.or_insert_with(|| first.clone());
1739			key_file.set_replica(&replica, &compartment, rng)?;
1740			saved = Some(replica.spaces);
1741			Ok(())
1742		})?;
1743		if let Some(spaces) = saved {
1744			self.replica.spaces = spaces;
1745		}
1746		self.spaces.insert(space, opened);
1747		self.keep_in(space);
1748		self.choose_writing_keys()?;
1749		Ok(())
1750	}
1751
1752	/// Takes away a space this replica added and could not found: its key, then its folder.
1753	pub(crate) fn remove_space(&mut self, space: SpaceId, rng: &mut impl CryptoRng) {
1754		self.spaces.remove(&space);
1755		let compartment = self.compartment.clone();
1756		let mut saved = None;
1757		let removed = self.update_key_file(|key_file| {
1758			let mut replica = key_file.replica(&compartment)?;
1759			replica.spaces.remove(&space);
1760			key_file.set_replica(&replica, &compartment, rng)?;
1761			saved = Some(replica.spaces);
1762			Ok(())
1763		});
1764		if let Some(spaces) = saved {
1765			self.replica.spaces = spaces;
1766		}
1767		if removed.is_ok()
1768			&& let Some(folder) = log_path(&self.directory, space).parent()
1769		{
1770			let _ = fs::remove_dir_all(folder);
1771		}
1772	}
1773
1774	/// Opens the spaces that another program of this replica added since this one opened
1775	/// the library, as their folders show, from the key file.
1776	pub(crate) fn catch_up_spaces(&mut self) -> Result<bool, NodeError> {
1777		let folder = self.directory.join("spaces");
1778		let Ok(entries) = fs::read_dir(&folder) else {
1779			return Ok(false);
1780		};
1781		let new: Vec<SpaceId> = entries
1782			.filter_map(Result::ok)
1783			.filter_map(|entry| entry.file_name().to_str()?.parse::<SpaceId>().ok())
1784			.filter(|space| !self.spaces.contains_key(space))
1785			.collect();
1786		if new.is_empty() {
1787			return Ok(false);
1788		}
1789		let replica = nibkeep_keys::KeyFile::read(&self.directory.join(super::KEYS))?
1790			.replica(&self.compartment)?;
1791		let mut opened = false;
1792		for space in new {
1793			let (Some(epochs), log) =
1794				(replica.spaces.get(&space), log_path(&self.directory, space))
1795			else {
1796				continue;
1797			};
1798			if !log.exists() {
1799				continue;
1800			}
1801			let open = Space::open(&log, space, epochs, &replica.storage, &self.code_types)?;
1802			self.spaces.insert(space, open);
1803			self.keep_in(space);
1804			opened = true;
1805		}
1806		if opened {
1807			self.replica.spaces = replica.spaces;
1808			self.choose_writing_keys()?;
1809		}
1810		Ok(opened)
1811	}
1812}
1813
1814/// The keys that added each key, by the bytes of each.
1815type Listers = BTreeMap<[u8; 32], BTreeSet<[u8; 32]>>;
1816
1817/// The keys that a revocation ends of those that the personal space does not list, as
1818/// [`Library::revoke_in_spaces_telling`] says: each that a key of `revoked`, or one of these,
1819/// listed, as `listers` gives the keys that listed each, but those that a key of `standing`
1820/// listed, or one so kept in turn. A key listed by itself alone is in neither.
1821fn ended_by_revoked(
1822	listers: &Listers,
1823	standing: &BTreeSet<[u8; 32]>,
1824	revoked: &BTreeSet<[u8; 32]>,
1825) -> BTreeSet<[u8; 32]> {
1826	// Each grows from its seeds by the keys they listed, until it takes no more.
1827	let grown = |seeds: &BTreeSet<[u8; 32]>, but: &BTreeSet<[u8; 32]>| {
1828		let mut grown: BTreeSet<[u8; 32]> = BTreeSet::new();
1829		loop {
1830			let before = grown.len();
1831			for (key, by) in listers {
1832				if !seeds.contains(key)
1833					&& !but.contains(key)
1834					&& by.iter().any(|lister| {
1835						lister != key && (seeds.contains(lister) || grown.contains(lister))
1836					}) {
1837					grown.insert(*key);
1838				}
1839			}
1840			if grown.len() == before {
1841				return grown;
1842			}
1843		}
1844	};
1845	let mut known: BTreeSet<[u8; 32]> = standing.union(revoked).copied().collect();
1846	let kept = grown(standing, &known);
1847	known.extend(kept);
1848	grown(revoked, &known)
1849}
1850
1851#[cfg(test)]
1852mod tests {
1853	use super::*;
1854
1855	fn keys(names: &[u8]) -> BTreeSet<[u8; 32]> {
1856		names.iter().map(|&name| [name; 32]).collect()
1857	}
1858
1859	fn listed(pairs: &[(u8, &[u8])]) -> BTreeMap<[u8; 32], BTreeSet<[u8; 32]>> {
1860		pairs
1861			.iter()
1862			.map(|&(key, by)| ([key; 32], keys(by)))
1863			.collect()
1864	}
1865
1866	#[test]
1867	fn a_revocation_ends_what_revoked_devices_added_but_what_devices_at_hand_added_too() {
1868		// 1 is this device, 2 a laptop at hand, 3 a lost desk, revoked, that the personal
1869		// space lists; the others it does not list.
1870		let (standing, revoked) = (keys(&[1, 2]), keys(&[3]));
1871		let listers = listed(&[
1872			// Listed by the lost desk, and in turn by what it listed.
1873			(4, &[3]),
1874			(5, &[4]),
1875			// Listed by the kept laptop, and by the lost desk too, and what it listed.
1876			(6, &[2, 3]),
1877			(7, &[6]),
1878			// Listed by itself alone, as on a record made for it, and by itself and the desk.
1879			(8, &[8]),
1880			(9, &[9, 3]),
1881			// The keys that the personal space lists stay as they are.
1882			(2, &[1]),
1883			(3, &[2]),
1884		]);
1885		assert_eq!(
1886			ended_by_revoked(&listers, &standing, &revoked),
1887			keys(&[4, 5, 9])
1888		);
1889	}
1890}