Skip to main content

nibkeep_node/library/
taking.rs

1//! Devices that choose their spaces: consent and taking
2//! ([technical design](../../../../docs/Technical-design.md#1310-devices-that-choose-their-spaces)).
3//!
4//! A space reaches a device of the user's only with the person's consent: the personal
5//! space's entry of the space, its first key sealed to the device, is given to the devices
6//! the person chooses as they make or join a space, or pair a device, and to a device whose
7//! request they approve on a device that holds the space. Each device says, as its own,
8//! whether it takes a space given to it later or asks first: computers take them, phones
9//! ask. A device that asks takes an entry only when the person says so there, and asks for a
10//! space it has no entry of with a choice of its own to hold it. The devices that hold a
11//! space keep its names in the personal space, so that every device shows each space of the
12//! user's by name.
13
14use std::collections::{BTreeMap, BTreeSet};
15
16use nibkeep_base::{EntityId, SpaceId, StatementId};
17use nibkeep_crypto::rand_core::CryptoRng;
18use nibkeep_crypto::{EncryptionKey, key_hash};
19use nibkeep_governance::{
20	Choice, OF_SPACE, SPACE_NAMES, SpaceEntry, give_space_entry, replica_record,
21	space_names_record, state_choice,
22};
23use nibkeep_model::{Operation, Statement, Value, fields};
24
25use super::Library;
26use super::entities::display_name;
27use super::spaces::Personal;
28use crate::NodeError;
29
30/// What the person chose for a new device of theirs, on the device that shows the code: a
31/// computer takes every space of this device's, and the spaces given to it later; a phone
32/// takes the personal space alone, and asks before it takes a space given to it later.
33#[derive(Clone, Debug, Default, PartialEq, Eq)]
34pub struct NewDevice {
35	/// Whether it is a phone, which asks before it takes a space given to it later.
36	pub phone: bool,
37	/// The spaces besides the personal one that it gets, of those this device holds; `None`
38	/// for the default: every space for a computer, none for a phone.
39	pub spaces: Option<Vec<SpaceId>>,
40}
41
42impl NewDevice {
43	/// A computer, which gets every space of this device's.
44	#[must_use]
45	pub fn computer() -> Self {
46		Self::default()
47	}
48
49	/// A phone, which gets the personal space alone.
50	#[must_use]
51	pub fn phone() -> Self {
52		Self {
53			phone: true,
54			spaces: None,
55		}
56	}
57
58	/// The same, getting `spaces` besides the personal one instead.
59	#[must_use]
60	pub fn with_spaces(mut self, spaces: Vec<SpaceId>) -> Self {
61		self.spaces = Some(spaces);
62		self
63	}
64}
65
66/// What taking a space did.
67#[derive(Clone, Copy, Debug, PartialEq, Eq)]
68pub enum Taking {
69	/// This device took the space, given to it before: it fills as it syncs.
70	Took,
71	/// This device asked for the space, which the person approves on a device that holds
72	/// it.
73	Asked,
74}
75
76/// A device of the user's that asks for a space this device holds, which the person
77/// approves here with [`Library::allow_space`].
78#[derive(Clone, Debug, PartialEq, Eq)]
79pub struct SpaceRequest {
80	/// The space.
81	pub space: SpaceId,
82	/// The space's name.
83	pub name: Option<String>,
84	/// The replica that asks, by its record in the personal space.
85	pub replica: EntityId,
86	/// The name of its device.
87	pub device: Option<String>,
88	/// The name of its app.
89	pub app: Option<String>,
90	/// Whether it held the space before, and dropped it.
91	pub back: bool,
92}
93
94/// A space of the user's, whether this device holds it or not, as the personal space
95/// knows it.
96#[derive(Clone, Debug, PartialEq, Eq)]
97pub struct KnownSpace {
98	/// The space.
99	pub space: SpaceId,
100	/// Its name.
101	pub name: Option<String>,
102	/// What this device did with it.
103	pub here: Here,
104	/// The devices of the user's that hold it, as their choices say, and this one.
105	pub holders: Vec<SpaceHolder>,
106	/// Whether this device drops it, and has not deleted it yet
107	/// ([`Library::drop_space`]).
108	pub dropping: bool,
109}
110
111impl KnownSpace {
112	/// Whether this device holds it.
113	#[must_use]
114	pub fn held(&self) -> bool {
115		self.here == Here::Held
116	}
117}
118
119/// What a device did with a space of the user's.
120#[derive(Clone, Copy, Debug, PartialEq, Eq)]
121pub enum Here {
122	/// It holds the space.
123	Held,
124	/// It was given the space, which it takes once the person says so there.
125	Given,
126	/// It asked for the space, and has not been given it yet.
127	Asked,
128	/// It declined or dropped the space, and has not asked for it again.
129	Declined,
130	/// None of these: it may ask for the space.
131	Elsewhere,
132}
133
134/// A device of the user's that holds a space.
135#[derive(Clone, Debug, PartialEq, Eq)]
136pub struct SpaceHolder {
137	/// The replica, by its record in the personal space.
138	pub replica: EntityId,
139	/// The name of its device.
140	pub device: Option<String>,
141	/// The name of its app.
142	pub app: Option<String>,
143	/// Whether it is this replica.
144	pub this: bool,
145}
146
147impl Library {
148	/// Whether this device takes the spaces given to it later, or asks first, as it said
149	/// itself: a device that said nothing takes them.
150	///
151	/// # Errors
152	///
153	/// Returns an error if the personal space cannot be read.
154	pub fn takes_new_spaces(&self) -> Result<bool, NodeError> {
155		Ok(self.own_mark(&self.read_personal()?))
156	}
157
158	/// What this replica said itself of the spaces given to it later, as the personal space,
159	/// `personal`, states it on its own record with its own key: whether it takes them.
160	pub(super) fn own_mark(&self, personal: &Personal) -> bool {
161		let own = self.replica.signing.verifying_key();
162		personal
163			.marks
164			.iter()
165			.rfind(|(record, author, _)| *record == self.info.replica && *author == own)
166			.is_none_or(|(_, _, takes)| *takes)
167	}
168
169	/// What each replica of the user's said, itself, of the spaces given to it later: by its
170	/// record in the personal space, whether it takes them; one that said nothing takes them.
171	/// A statement counts only where one of the record's own keys made it, the last of those
172	/// by the order of the changes; so that no other device can have it take what it was
173	/// given.
174	///
175	/// # Errors
176	///
177	/// Returns an error if the personal space cannot be read.
178	pub fn new_space_marks(&self) -> Result<BTreeMap<EntityId, bool>, NodeError> {
179		let personal = self.read_personal()?;
180		let roster = self.roster(self.info.personal)?;
181		Ok(personal
182			.marks
183			.into_iter()
184			.filter(|(record, author, _)| roster.keys_of(*record).contains(author))
185			.map(|(record, _, takes)| (record, takes))
186			.collect())
187	}
188
189	/// Takes the spaces given to this replica as it paired, every one but those it declined,
190	/// whatever it says of the spaces given to it later: the person chose them on the device
191	/// that paired it
192	/// ([technical design](../../../../docs/Technical-design.md#1310-devices-that-choose-their-spaces)).
193	pub(crate) fn take_paired_spaces(
194		&mut self,
195		wall_millis: u64,
196		rng: &mut impl CryptoRng,
197	) -> Result<(), NodeError> {
198		let read = self.read_personal()?;
199		self.take_space_entries_as(&read, true, wall_millis, rng)
200	}
201
202	/// Says, on this device, whether it takes the spaces given to it later, or asks first,
203	/// as its own statement in the personal space, which no other device can make for it.
204	///
205	/// # Errors
206	///
207	/// Returns an error if this replica is an AI agent's or revoked, or the change cannot be
208	/// saved.
209	pub fn set_takes_new_spaces(
210		&mut self,
211		takes: bool,
212		wall_millis: u64,
213		rng: &mut impl CryptoRng,
214	) -> Result<(), NodeError> {
215		let personal = self.info.personal;
216		self.check_not_revoked(personal)?;
217		self.check_not_ai_agent("choose the spaces it holds")?;
218		if self.takes_new_spaces()? == takes {
219			return Ok(());
220		}
221		let operation = Operation::assert(Statement::new(
222			StatementId::random(rng),
223			self.info.replica,
224			fields::NEW_SPACES,
225			Value::Boolean(takes),
226		));
227		self.commit(personal, vec![operation], wall_millis, rng)
228	}
229
230	/// Gives a space that this device holds to the devices of the user's that the person
231	/// chose, by their records in the personal space: its first key sealed to each, with the
232	/// user's member there, in one change of the personal space. Each takes it as its own
233	/// choice says: a computer at once, a phone once the person says so there. A device that
234	/// has it already, or declined or dropped it, an AI agent's, and one revoked are passed
235	/// over.
236	///
237	/// # Errors
238	///
239	/// Returns [`NodeError::NeverShared`] for the personal space, [`NodeError::Removed`] if
240	/// this device may not give the space, and an error if the change cannot be saved.
241	pub fn give_space(
242		&mut self,
243		space: SpaceId,
244		replicas: &[EntityId],
245		wall_millis: u64,
246		rng: &mut impl CryptoRng,
247	) -> Result<(), NodeError> {
248		if space == self.info.personal {
249			return Err(NodeError::NeverShared);
250		}
251		if self.member_in(space)?.is_none() || self.has_left(space)? {
252			return Err(NodeError::Removed);
253		}
254		let read = self.read_personal()?;
255		let roster = self.roster(self.info.personal)?;
256		let given = read.given();
257		let newest = Self::newest_choices(&read, &roster);
258		let mut operations = Vec::new();
259		for (replica, encryption) in self.remaining(self.info.personal, &roster, &[])? {
260			if !replicas.contains(&replica)
261				|| replica == self.info.replica
262				|| given.contains(&(replica, space))
263				|| self.is_ai_agent_record(&roster, replica)?
264			{
265				continue;
266			}
267			// One that declined or dropped it takes no entry: it asks again, itself.
268			let declined = roster.keys_of(replica).iter().any(|key| {
269				newest
270					.get(&(space, *key.as_bytes()))
271					.is_some_and(|(_, choice)| !choice.holds)
272			});
273			if declined {
274				continue;
275			}
276			if let Some(operation) = self.entry_for(space, (replica, &encryption), rng)? {
277				operations.push(operation);
278			}
279		}
280		if operations.is_empty() {
281			return Ok(());
282		}
283		self.commit(self.info.personal, operations, wall_millis, rng)
284	}
285
286	/// Gives a space that this device made or joined, as the person chose: to the devices of
287	/// the user's that take new spaces and to those of `also`, as [`Library::give_space`]
288	/// does, after stating that this one holds it; and to the recovery codes that stand.
289	pub(crate) fn give_new_space(
290		&mut self,
291		space: SpaceId,
292		also: &[EntityId],
293		wall_millis: u64,
294		rng: &mut impl CryptoRng,
295	) -> Result<(), NodeError> {
296		self.state_holding(&[space], wall_millis, rng)?;
297		// Those that take them: every replica that said so, or said nothing.
298		let marks = self.new_space_marks()?;
299		let roster = self.roster(self.info.personal)?;
300		let mut chosen: Vec<EntityId> = roster
301			.replicas()
302			.filter(|replica| marks.get(replica).copied().unwrap_or(true))
303			.collect();
304		chosen.extend_from_slice(also);
305		self.give_space(space, &chosen, wall_millis, rng)?;
306		self.give_space_entries(wall_millis, rng)
307	}
308
309	/// The entry that gives `space`, which this replica holds, to the replica `replica` of
310	/// the user's, whose encryption key is `encryption`: the space's first key sealed to it,
311	/// with the user's member there and the space's first change; none where this replica
312	/// holds no first key or first change of it yet.
313	pub(crate) fn entry_for(
314		&self,
315		space: SpaceId,
316		(replica, encryption): (EntityId, &EncryptionKey),
317		rng: &mut impl CryptoRng,
318	) -> Result<Option<Operation>, NodeError> {
319		let Some(member) = self.member_in(space)? else {
320			return Ok(None);
321		};
322		let open = self.space(space)?;
323		let Some(first) = open
324			.keys
325			.space_keys()
326			.find(|(epoch, _)| *epoch == 0)
327			.map(|(_, key)| key.clone())
328		else {
329			return Ok(None);
330		};
331		let Some(root) = open.stored.log().root()? else {
332			return Ok(None);
333		};
334		let entry = SpaceEntry::seal(
335			encryption,
336			(space, member, *root.hash()),
337			replica,
338			(&first, key_hash(&first)),
339			rng,
340		);
341		Ok(Some(give_space_entry(replica, &entry, rng)))
342	}
343
344	/// The entries that give a new replica of the user's, whose record pairing draws as
345	/// `replica` and whose encryption key is `encryption`, the spaces that the person chose
346	/// for it, of those this device holds: as [`NewDevice`] says, the spaces it may give,
347	/// but groups, which reach a device as spaces do.
348	pub(crate) fn entries_for_new(
349		&self,
350		(replica, encryption): (EntityId, &EncryptionKey),
351		device: &NewDevice,
352		rng: &mut impl CryptoRng,
353	) -> Result<Vec<Operation>, NodeError> {
354		let chosen: Vec<SpaceId> = match &device.spaces {
355			Some(spaces) => spaces.clone(),
356			None if device.phone => Vec::new(),
357			None => self.spaces(),
358		};
359		let mut entries = Vec::new();
360		for space in chosen {
361			// Not one it has dropped, whose drop it has stated, and still has.
362			if space == self.info.personal || !self.holds_here(space)? || self.has_left(space)? {
363				continue;
364			}
365			entries.extend(self.entry_for(space, (replica, encryption), rng)?);
366		}
367		Ok(entries)
368	}
369
370	/// Checks, before the code is shown, that this device can give a new device each space
371	/// chosen for it: one it holds, besides the personal one, and is listed in.
372	///
373	/// # Errors
374	///
375	/// Returns [`NodeError::NoSpace`] for a space that this device does not hold, and
376	/// [`NodeError::NotListed`] for one it is not listed in, or whose member left.
377	pub fn check_new_device(&self, device: &NewDevice) -> Result<(), NodeError> {
378		for &space in device.spaces.iter().flatten() {
379			if space == self.info.personal {
380				continue;
381			}
382			self.space(space)?;
383			if self.member_in(space)?.is_none() || self.has_left(space)? {
384				return Err(NodeError::NotListed);
385			}
386		}
387		Ok(())
388	}
389
390	/// Whether a replica of the user's, by its record in the personal space, is an AI
391	/// agent's, as a key of it is marked.
392	fn is_ai_agent_record(
393		&self,
394		roster: &nibkeep_governance::Roster,
395		replica: EntityId,
396	) -> Result<bool, NodeError> {
397		let open = self.space(self.info.personal)?;
398		for key in roster.keys_of(replica) {
399			if open.stored.log().is_ai_agent(key, &open.keys)? {
400				return Ok(true);
401			}
402		}
403		Ok(false)
404	}
405
406	/// This replica's newest choice of each space, of those that the personal space,
407	/// `personal`, states on its own record: by space, its number and whether it holds the
408	/// space.
409	pub(super) fn own_choices(&self, personal: &Personal) -> BTreeMap<SpaceId, (u64, bool)> {
410		let own = self.replica.signing.verifying_key();
411		let mut choices: BTreeMap<SpaceId, (u64, bool)> = BTreeMap::new();
412		for (record, text) in &personal.choices {
413			if *record != self.info.replica {
414				continue;
415			}
416			let Some(choice) = Choice::from_text(text) else {
417				continue;
418			};
419			if choice.key != own || !choice.verifies() {
420				continue;
421			}
422			let rank = |(number, holds): (u64, bool)| (number, !holds);
423			let stated = (choice.number, choice.holds);
424			if choices
425				.get(&choice.space)
426				.is_none_or(|kept| rank(stated) > rank(*kept))
427			{
428				choices.insert(choice.space, stated);
429			}
430		}
431		choices
432	}
433
434	/// Whether this replica takes an entry of a space that it does not hold, by its newest
435	/// choice of the space, `choice`: one that holds it, as when it asked; none, where it
436	/// takes new spaces, `takes`; never one that declined or dropped it.
437	pub(super) const fn takes_entry(choice: Option<(u64, bool)>, takes: bool) -> bool {
438		match choice {
439			Some((_, holds)) => holds,
440			None => takes,
441		}
442	}
443
444	/// States, in the personal space, that this replica holds each of `spaces` that its
445	/// newest choice there does not say it holds already, as it takes them: each a choice
446	/// numbered one above the highest of its own of that space, in one change.
447	pub(crate) fn state_holding(
448		&mut self,
449		spaces: &[SpaceId],
450		wall_millis: u64,
451		rng: &mut impl CryptoRng,
452	) -> Result<(), NodeError> {
453		if self.is_ai_agent()? {
454			return Ok(());
455		}
456		let read = self.read_personal()?;
457		let own = self.own_choices(&read);
458		let mut operations = Vec::new();
459		for &space in spaces {
460			if space == self.info.personal || own.get(&space).is_some_and(|(_, holds)| *holds) {
461				continue;
462			}
463			let number = self
464				.highest_choice(space, &read)?
465				.map_or(1, |number| number + 1);
466			let choice = Choice::sign(&self.replica.signing, space, number, true);
467			operations.push(state_choice(self.info.replica, &choice, rng));
468		}
469		if operations.is_empty() {
470			return Ok(());
471		}
472		self.commit(self.info.personal, operations, wall_millis, rng)
473	}
474
475	/// Takes a space on this device, as the person says here: one given to it, through the
476	/// personal space or a group, at once, stating that it holds it; one it drops, before its
477	/// choice is stated, at once too, as it holds it still; one it was not given, or dropped,
478	/// by asking for it with a choice of its own to hold it, which the person approves on a
479	/// device that holds it.
480	///
481	/// # Errors
482	///
483	/// Returns [`NodeError::PersonalSpaceHeld`] for the personal space,
484	/// [`NodeError::HoldsSpace`] if this device holds the space already, and an error if this
485	/// replica is an AI agent's or revoked, or a change cannot be saved.
486	pub fn take_space(
487		&mut self,
488		space: SpaceId,
489		wall_millis: u64,
490		rng: &mut impl CryptoRng,
491	) -> Result<Taking, NodeError> {
492		let personal = self.info.personal;
493		if space == personal {
494			return Err(NodeError::PersonalSpaceHeld);
495		}
496		self.check_not_revoked(personal)?;
497		self.check_not_ai_agent("choose the spaces it holds")?;
498		let read = self.read_personal()?;
499		let choice = self.own_choices(&read).get(&space).copied();
500		// Dropped, not declined: it held the space before, so its drop may be there.
501		let dropped = choice.is_some_and(|(_, holds)| !holds) && self.held_before(space, &read);
502		let asked = choice.is_some_and(|(_, holds)| holds);
503		if self.spaces.contains_key(&space) {
504			// Dropped here before its choice was stated: taken back as it is.
505			if self.take_back_drop(space)? {
506				return Ok(Taking::Took);
507			}
508			// Held here and still listed: nothing to take. Dropped there: it asks again, once,
509			// and drops it no longer.
510			let open = self.space(space)?;
511			let own = self.replica.signing.verifying_key();
512			if open.stored.log().holds_space(&own, &open.keys)? && !dropped {
513				return Err(NodeError::HoldsSpace(space));
514			}
515			if !asked {
516				self.state_space_choice(space, true, wall_millis, rng)?;
517			}
518			self.end_drop(space)?;
519			return Ok(Taking::Asked);
520		}
521		// Given before and never dropped: taken now. A device that dropped it asks first,
522		// as only a device that holds it brings it back there.
523		if !dropped && let Some((key, root)) = self.given_key(space, &read)? {
524			self.add_space(space, &key, rng)?;
525			if let Some(open) = self.spaces.get_mut(&space) {
526				open.stored.expect_roots_too([root]);
527			}
528			self.state_holding(&[space], wall_millis, rng)?;
529			return Ok(Taking::Took);
530		}
531		// Asked already, it asks no more.
532		if !asked {
533			self.state_space_choice(space, true, wall_millis, rng)?;
534		}
535		Ok(Taking::Asked)
536	}
537
538	/// Whether this replica held a space before, as one of its choices of the space that the
539	/// personal space, `personal`, states says: a device that dropped a space held it, and
540	/// one that declined it never did.
541	fn held_before(&self, space: SpaceId, personal: &Personal) -> bool {
542		let own = self.replica.signing.verifying_key();
543		personal
544			.choices
545			.iter()
546			.filter(|(record, _)| *record == self.info.replica)
547			.filter_map(|(_, text)| Choice::from_text(text))
548			.any(|choice| {
549				choice.space == space && choice.key == own && choice.holds && choice.verifies()
550			})
551	}
552
553	/// The first key of a space that an entry gives this replica, through the personal space,
554	/// `personal`, or a group it holds, whose hash the entry names, with the space's first
555	/// change that the entry names.
556	fn given_key(
557		&self,
558		space: SpaceId,
559		personal: &Personal,
560	) -> Result<Option<(nibkeep_crypto::Key, nibkeep_log::ChangeId)>, NodeError> {
561		for entry in self.own_entries(personal) {
562			if entry.space != space {
563				continue;
564			}
565			if let Some(key) = entry.open(&self.replica.decryption, self.info.replica)
566				&& key_hash(&key) == entry.hash
567			{
568				return Ok(Some((key, nibkeep_log::ChangeId::from_hash(entry.root))));
569			}
570		}
571		let own = self.replica.signing.verifying_key();
572		for group in self.held_groups() {
573			if self.check_not_revoked(group).is_err() {
574				continue;
575			}
576			let record = replica_record(group, &own);
577			for (entry, root) in self.agreed_entries(group, record)? {
578				if entry.space != space {
579					continue;
580				}
581				if let Some(key) = entry.open(&self.replica.decryption, record)
582					&& key_hash(&key) == entry.hash
583				{
584					return Ok(Some((key, root)));
585				}
586			}
587		}
588		Ok(None)
589	}
590
591	/// The groups that this replica holds.
592	pub(super) fn held_groups(&self) -> Vec<SpaceId> {
593		self.spaces
594			.keys()
595			.copied()
596			.filter(|&space| space != self.info.personal && self.is_group(space).unwrap_or(false))
597			.collect()
598	}
599
600	/// The requests of the user's other devices for the spaces that this device holds and
601	/// may give: a device's newest choice of the space, in the personal space, holds it, and
602	/// it was never given the space, nor is listed there; or the choice that stands there is
603	/// a drop that its newer choice outranks. Shown only on a device that holds the space.
604	///
605	/// # Errors
606	///
607	/// Returns an error if a space cannot be read.
608	pub fn space_requests(&self) -> Result<Vec<SpaceRequest>, NodeError> {
609		let personal = self.info.personal;
610		let read = self.read_personal()?;
611		let roster = self.roster(personal)?;
612		let given = read.given();
613		let mut requests = Vec::new();
614		let personal_open = self.space(personal)?;
615		let personal_log = personal_open.stored.log();
616		// Whether this replica may give each space, found once for each.
617		let mut may_give_each: BTreeMap<SpaceId, bool> = BTreeMap::new();
618		for ((space, _), (record, choice)) in Self::newest_choices(&read, &roster) {
619			if !choice.holds
620				|| record == self.info.replica
621				|| space == personal
622				|| !self.spaces.contains_key(&space)
623			{
624				continue;
625			}
626			let may_give = if let Some(may_give) = may_give_each.get(&space) {
627				*may_give
628			} else {
629				let may_give = self.changes_there(space)?;
630				may_give_each.insert(space, may_give);
631				may_give
632			};
633			if !may_give
634				|| personal_log.is_revoked(&choice.key, &personal_open.keys)?
635				|| personal_log.is_ai_agent(&choice.key, &personal_open.keys)?
636			{
637				continue;
638			}
639			let open = self.space(space)?;
640			let log = open.stored.log();
641			let back =
642				if let Some((number, false)) = log.standing_choice(&choice.key, &open.keys)? {
643					if number >= choice.number {
644						continue;
645					}
646					true
647				} else {
648					if given.contains(&(record, space)) || log.is_listed(&choice.key, &open.keys)? {
649						continue;
650					}
651					false
652				};
653			let (device, app, _) = self.replica_names(record)?;
654			requests.push(SpaceRequest {
655				space,
656				name: self.space_name(space)?,
657				replica: record,
658				device,
659				app,
660				back,
661			});
662		}
663		Ok(requests)
664	}
665
666	/// Approves, on this device, the request of the device of the user's whose record in the
667	/// personal space is `replica` for `space`, as [`Library::space_requests`] shows it: gives
668	/// it the space, or, where it dropped the space, lists it there again, with every key
669	/// made meanwhile, and gives it the space too where it was never given it, as the device
670	/// that made it.
671	///
672	/// # Errors
673	///
674	/// Returns [`NodeError::NoRequest`] if that device asks for no such space here, and an
675	/// error if a change cannot be saved.
676	pub fn allow_space(
677		&mut self,
678		space: SpaceId,
679		replica: EntityId,
680		wall_millis: u64,
681		rng: &mut impl CryptoRng,
682	) -> Result<(), NodeError> {
683		let request = self
684			.space_requests()?
685			.into_iter()
686			.find(|request| request.space == space && request.replica == replica)
687			.ok_or(NodeError::NoRequest)?;
688		let given = self.read_personal()?.given().contains(&(replica, space));
689		if request.back {
690			self.list_again(space, replica, wall_millis, rng)?;
691			// A device that deleted the space, as after a drop, takes it again by its entry,
692			// which the device that made the space never had.
693			if given {
694				return Ok(());
695			}
696		}
697		let roster = self.roster(self.info.personal)?;
698		let encryption = roster
699			.encryption_of(replica)
700			.cloned()
701			.ok_or(NodeError::NoRequest)?;
702		let operation = self
703			.entry_for(space, (replica, &encryption), rng)?
704			.ok_or(NodeError::NoSpace(space))?;
705		self.commit(self.info.personal, vec![operation], wall_millis, rng)
706	}
707
708	/// Brings the names of each space that this replica holds up to date in the personal
709	/// space, on the record derived from the personal space and the space, so that every
710	/// device of the user's shows it by name: in one change, for those whose names there
711	/// differ from the space's own.
712	pub(crate) fn settle_space_names(
713		&mut self,
714		wall_millis: u64,
715		rng: &mut impl CryptoRng,
716	) -> Result<(), NodeError> {
717		let personal = self.info.personal;
718		let mut operations = Vec::new();
719		for space in self.spaces() {
720			// Only a space or group of the user's: not one whose member left, nor a group
721			// whose log it keeps read only, to follow it in a space.
722			if space == personal
723				|| self.has_left(space)?
724				|| self.own_role(space)? == crate::MemberRole::None
725			{
726				continue;
727			}
728			let open = self.space(space)?;
729			let Some(entity) = open.own_entity()? else {
730				continue;
731			};
732			let names: Vec<Value> = open
733				.stored
734				.log()
735				.state()
736				.current(entity, &fields::NAME)?
737				.into_iter()
738				.map(|statement| statement.value.clone())
739				.collect();
740			if names.is_empty() {
741				continue;
742			}
743			let record = space_names_record(personal, space);
744			let personal_open = self.space(personal)?;
745			let state = personal_open.stored.log().state();
746			let kept = state.current(record, &fields::NAME)?;
747			// The same names, whatever their order or how many statements hold each, as two
748			// devices that write them at once each write them once.
749			let same = names
750				.iter()
751				.all(|name| kept.iter().any(|statement| statement.value == *name))
752				&& kept
753					.iter()
754					.all(|statement| names.contains(&statement.value));
755			if same {
756				continue;
757			}
758			if !state.types(record)?.contains(&SPACE_NAMES) {
759				for (field, value) in [
760					(fields::TYPE, Value::Text(SPACE_NAMES.to_string())),
761					(OF_SPACE, Value::Text(space.to_string())),
762				] {
763					operations.push(Operation::assert(Statement::new(
764						StatementId::random(rng),
765						record,
766						field,
767						value,
768					)));
769				}
770			}
771			let replaced: Vec<StatementId> = kept.iter().map(|statement| statement.id).collect();
772			for (at, name) in names.into_iter().enumerate() {
773				let statement =
774					Statement::new(StatementId::random(rng), record, fields::NAME, name);
775				operations.push(if at == 0 {
776					Operation::replace(statement, replaced.clone())
777				} else {
778					Operation::assert(statement)
779				});
780			}
781		}
782		if operations.is_empty() {
783			return Ok(());
784		}
785		self.commit(personal, operations, wall_millis, rng)
786	}
787
788	/// The names that the personal space keeps of the user's spaces: by space, its name as
789	/// this library's languages show it.
790	pub(super) fn kept_space_names(&self) -> Result<BTreeMap<SpaceId, Option<String>>, NodeError> {
791		let personal = self.info.personal;
792		let open = self.space(personal)?;
793		let state = open.stored.log().state();
794		let mut names = BTreeMap::new();
795		for record in open
796			.stored
797			.find(&fields::TYPE, &Value::Text(SPACE_NAMES.to_string()))?
798		{
799			if state.is_deleted(record)? {
800				continue;
801			}
802			let Some(space) = state
803				.current(record, &OF_SPACE)?
804				.iter()
805				.find_map(|statement| statement.value.as_text()?.parse::<SpaceId>().ok())
806			else {
807				continue;
808			};
809			// Only on the record derived for the space, which no other space shares.
810			if record != space_names_record(personal, space) {
811				continue;
812			}
813			names.insert(
814				space,
815				display_name(state, &open.types, &self.languages, record)?,
816			);
817		}
818		Ok(names)
819	}
820
821	/// Every space of the user's but the personal one, whether this device holds it or not,
822	/// as the personal space knows them: those it holds, those given to any device of the
823	/// user's, those whose names it keeps, and those that a device chose; each with its
824	/// name, what this device did with it, and the devices that hold it. A space that the
825	/// user left is left out. By name, then by ID.
826	///
827	/// # Errors
828	///
829	/// Returns an error if a space cannot be read.
830	pub fn known_spaces(&self) -> Result<Vec<KnownSpace>, NodeError> {
831		let personal = self.info.personal;
832		let read = self.read_personal()?;
833		let roster = self.roster(personal)?;
834		let names = self.kept_space_names()?;
835		let own = self.own_choices(&read);
836		let newest = Self::newest_choices(&read, &roster);
837		// What the personal space knows of: the spaces given to any device or code, named,
838		// or chosen.
839		let mut spaces: BTreeSet<SpaceId> = read
840			.entries
841			.iter()
842			.filter_map(|(_, text)| Some(SpaceEntry::from_text(text)?.space))
843			.collect();
844		spaces.extend(names.keys().copied());
845		spaces.extend(newest.keys().map(|(space, _)| *space));
846		// An AI agent's replica knows only those it holds, so that no AI agent reads the names
847		// of the spaces not chosen for it.
848		if self.is_ai_agent()? {
849			spaces.clear();
850		}
851		// And those held here where this replica's user has a role, but no group whose log it
852		// keeps read only, to follow it in a space.
853		for &space in self.spaces.keys() {
854			if !spaces.contains(&space) && self.own_role(space)? != crate::MemberRole::None {
855				spaces.insert(space);
856			}
857		}
858		spaces.remove(&personal);
859		let given = self.given_here(&read)?;
860		let mut known = Vec::new();
861		for space in spaces {
862			// On this device, and not dropped there; a space whose member left, or was
863			// removed, is no longer the user's.
864			let on_device = self.spaces.contains_key(&space);
865			let held = self.holds_here(space)?;
866			if held && self.has_left(space)? {
867				continue;
868			}
869			let holders = self.space_holders((space, held), &newest)?;
870			let name = if on_device {
871				self.space_name(space)?
872			} else {
873				names.get(&space).cloned().flatten()
874			};
875			let here = match own.get(&space).copied() {
876				_ if held => Here::Held,
877				Some((_, false)) => Here::Declined,
878				_ if given.contains(&space) => Here::Given,
879				Some((_, true)) => Here::Asked,
880				None => Here::Elsewhere,
881			};
882			known.push(KnownSpace {
883				space,
884				name,
885				here,
886				holders,
887				dropping: on_device && self.is_dropping(space),
888			});
889		}
890		known.sort_by_key(|known| by_name(known.name.as_deref(), known.space));
891		Ok(known)
892	}
893
894	/// The spaces given to this replica, through the personal space, `personal`, or a group
895	/// that it holds.
896	fn given_here(&self, personal: &Personal) -> Result<BTreeSet<SpaceId>, NodeError> {
897		let mut given: BTreeSet<SpaceId> = self
898			.own_entries(personal)
899			.into_iter()
900			.map(|entry| entry.space)
901			.collect();
902		let own_key = self.replica.signing.verifying_key();
903		for group in self.held_groups() {
904			let record = replica_record(group, &own_key);
905			given.extend(
906				self.agreed_entries(group, record)?
907					.into_iter()
908					.map(|(entry, _)| entry.space),
909			);
910		}
911		Ok(given)
912	}
913
914	/// The devices of the user's that hold `space`, as their newest choices, `newest`, say,
915	/// but those revoked, and this one first where it holds it, `held`.
916	pub(super) fn space_holders(
917		&self,
918		(space, held): (SpaceId, bool),
919		newest: &BTreeMap<(SpaceId, [u8; 32]), (EntityId, Choice)>,
920	) -> Result<Vec<SpaceHolder>, NodeError> {
921		let personal_open = self.space(self.info.personal)?;
922		let personal_log = personal_open.stored.log();
923		let mut holders = Vec::new();
924		if held {
925			let (device, app, _) = self.replica_names(self.info.replica)?;
926			holders.push(SpaceHolder {
927				replica: self.info.replica,
928				device,
929				app,
930				this: true,
931			});
932		}
933		for ((chosen, _), (record, choice)) in newest {
934			if *chosen != space
935				|| !choice.holds
936				|| *record == self.info.replica
937				|| personal_log.is_revoked(&choice.key, &personal_open.keys)?
938				|| holders.iter().any(|holder| holder.replica == *record)
939			{
940				continue;
941			}
942			let (device, app, _) = self.replica_names(*record)?;
943			holders.push(SpaceHolder {
944				replica: *record,
945				device,
946				app,
947				this: false,
948			});
949		}
950		Ok(holders)
951	}
952
953	/// Finds a space of the user's, held here or not, by its name, in any case, by its ID,
954	/// or by the start of its ID, as [`Library::known_spaces`] knows them, and as
955	/// [`Library::find_space`] finds those held here.
956	///
957	/// # Errors
958	///
959	/// Returns [`NodeError::NoSpaceNamed`] if no space matches, and
960	/// [`NodeError::SpacesNamed`] if several do.
961	pub fn find_known_space(&self, reference: &str) -> Result<SpaceId, NodeError> {
962		match self.find_space(reference) {
963			Err(NodeError::NoSpaceNamed(_)) => {}
964			found => return found,
965		}
966		let lowered = reference.to_lowercase();
967		let known = self.known_spaces()?;
968		let by_name: Vec<SpaceId> = known
969			.iter()
970			.filter(|known| {
971				known
972					.name
973					.as_ref()
974					.is_some_and(|name| name.to_lowercase() == lowered)
975			})
976			.map(|known| known.space)
977			.collect();
978		let by_id: Vec<SpaceId> = known
979			.iter()
980			.filter(|known| lowered.len() >= 4 && known.space.to_string().starts_with(&lowered))
981			.map(|known| known.space)
982			.collect();
983		let found = if by_name.is_empty() { by_id } else { by_name };
984		match found.as_slice() {
985			[] => Err(NodeError::NoSpaceNamed(reference.to_owned())),
986			[space] => Ok(*space),
987			_ => Err(NodeError::SpacesNamed(reference.to_owned())),
988		}
989	}
990}
991
992/// What orders spaces for people: by name, in any case, those without one last, then by ID.
993pub(super) fn by_name(name: Option<&str>, space: SpaceId) -> (bool, Option<String>, SpaceId) {
994	(name.is_none(), name.map(str::to_lowercase), space)
995}