Skip to main content

nibkeep_node/library/
groups.rs

1//! Groups in spaces ([technical design: groups]): a group is a space with members and no data
2//! of its own. An admin of a space who is a member of a group adds it there, as an editor or
3//! a viewer, and asks in the group that it join; an admin of the group agrees. Every replica
4//! of the space then keeps the group's log, follows it, and anchors its changes, which take
5//! effect in the space at those anchors; the group's members' replicas get the space from
6//! a replica of an admin of the group that holds it, through entries in the group. A group
7//! may be in another group the same way: the spaces the outer group is in follow and anchor
8//! both, and the inner group's members get them through the outer group's entries.
9//!
10//! [technical design: groups]: ../../../../docs/Technical-design.md#138-groups
11
12use std::collections::{BTreeMap, BTreeSet};
13
14use nibkeep_base::{EntityId, Hash, SpaceId};
15use nibkeep_crypto::rand_core::CryptoRng;
16use nibkeep_crypto::{EncryptionKey, key_hash};
17use nibkeep_governance::{
18	Anchor, GroupKey, GroupRef, GroupRequest, Joining, SpaceEntry, give_space_entry, replica_record,
19};
20use nibkeep_log::ChangeId;
21use nibkeep_model::{FieldName, Operation, fields};
22
23use super::Library;
24use crate::{MemberRole, NodeError};
25
26/// A group that a space's governing changes add, as a program shows it.
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct GroupInSpace {
29	/// The group's record in the space.
30	pub record: EntityId,
31	/// The group.
32	pub group: SpaceId,
33	/// The group's name, where this replica holds its log.
34	pub name: Option<String>,
35	/// The group's role in the space now: `none` once an admin took it out.
36	pub role: MemberRole,
37	/// Whether the group agreed to join, and has not withdrawn, as the space knows it.
38	pub agreed: bool,
39	/// The group's members, with their roles in the group, where this replica holds its log.
40	pub members: Vec<GroupMember>,
41	/// The groups inside the group, as its log says, where this replica holds it.
42	pub groups: Vec<GroupInSpace>,
43}
44
45/// A member of a group, with their role in the group.
46#[derive(Clone, Debug, PartialEq, Eq)]
47pub struct GroupMember {
48	/// Their record in the group.
49	pub record: EntityId,
50	/// Their name there.
51	pub name: Option<String>,
52	/// Their role in the group.
53	pub role: MemberRole,
54}
55
56/// A request, in a group, that the group join a space.
57#[derive(Clone, Debug, PartialEq, Eq)]
58pub struct GroupJoinRequest {
59	/// The space.
60	pub space: SpaceId,
61	/// The space's name, where it is sealed to this replica, as to the group's admins.
62	pub name: Option<String>,
63	/// Whether an admin of the group agreed.
64	pub agreed: bool,
65	/// Whether an admin withdrew that agreement, for good.
66	pub withdrawn: bool,
67}
68
69impl Library {
70	/// Whether a space this library holds is a group.
71	///
72	/// # Errors
73	///
74	/// Returns [`NodeError::NoSpace`] if the library holds no such space, and an error if it
75	/// cannot be read.
76	pub fn is_group(&self, space: SpaceId) -> Result<bool, NodeError> {
77		self.space(space)?.is_group()
78	}
79
80	/// Refuses entities of its own in a group, which every member of the spaces it is in
81	/// reads.
82	pub(crate) fn check_not_group(&self, space: SpaceId) -> Result<(), NodeError> {
83		if self.is_group(space)? {
84			return Err(NodeError::GroupHoldsNoData);
85		}
86		Ok(())
87	}
88
89	/// Adds a group to a space, as an admin of the space who is a member of the group, with
90	/// `role`, an editor's or a viewer's: a record of the group in the space, and a request in
91	/// the group that it join, with the space's name sealed to the group's admins. As an admin
92	/// of the group too, this replica agrees at once, and anchors the agreement in the space,
93	/// which gives the space the group's first key. Returns the group's record in the space.
94	///
95	/// # Errors
96	///
97	/// Returns [`NodeError::AdminsOnly`] if this replica's member is no admin of the space,
98	/// [`NodeError::GroupAsAdmin`] for the role of admin, [`NodeError::NotAGroup`] if the
99	/// library holds no such group, [`NodeError::NotInGroup`] if this replica is no member of
100	/// it, [`NodeError::GroupCycle`] if the space is the group or a group inside it, at any
101	/// level, and an error if a change cannot be saved.
102	pub fn add_group(
103		&mut self,
104		space: SpaceId,
105		group: SpaceId,
106		role: MemberRole,
107		wall_millis: u64,
108		rng: &mut impl CryptoRng,
109	) -> Result<EntityId, NodeError> {
110		self.observe_wall(wall_millis);
111		self.check_admin(space, "add groups")?;
112		if !matches!(role, MemberRole::Editor | MemberRole::Viewer) {
113			return Err(NodeError::GroupAsAdmin);
114		}
115		if !self.spaces.contains_key(&group) || !self.is_group(group)? {
116			return Err(NodeError::NotAGroup(group));
117		}
118		if space == group || self.inner_groups(group)?.contains(&space) {
119			return Err(NodeError::GroupCycle);
120		}
121		self.check_not_revoked(group)
122			.map_err(|_| NodeError::NotInGroup)?;
123		let member = self.member_in(group)?.ok_or(NodeError::NotInGroup)?;
124		// Everything that may fail is read before anything is written.
125		let (group_root, space_root) = (self.root_of(group)?, self.root_of(space)?);
126		let first_key = self
127			.first_key(group)?
128			.ok_or_else(|| NodeError::Damaged(format!("the group {group} has no first key")))?;
129		let name = self.space_name(space)?.unwrap_or_default();
130		let admins = self.admins_replicas(group)?;
131		let entity = self.group_entity(group)?;
132		let open = self.space(group)?;
133		let agrees =
134			open.stored.log().member_roles(&open.keys)?.get(&member) == Some(&MemberRole::Admin);
135		let record = EntityId::random(rng);
136		let (operations, addition) = nibkeep_governance::add_group(
137			record,
138			GroupRef {
139				group,
140				root: group_root,
141				key: key_hash(&first_key),
142			},
143			role.as_text(),
144			rng,
145		);
146		self.commit(space, operations, wall_millis, rng)?;
147		let joining = Joining {
148			space,
149			root: space_root,
150			addition,
151		};
152		let request = GroupRequest::new(joining, &name, &admins, rng);
153		let mut operations = vec![nibkeep_governance::ask_to_join(entity, &request, rng)];
154		if agrees {
155			operations.push(nibkeep_governance::agree_to_join(entity, &joining, rng));
156		}
157		self.commit(group, operations, wall_millis, rng)?;
158		Ok(record)
159	}
160
161	/// Takes a group out of a space, as an admin of the space, with the role none on its
162	/// record there: its members leave the space, unless they are members there some other
163	/// way, and it joins again only by a new addition.
164	///
165	/// # Errors
166	///
167	/// Returns [`NodeError::AdminsOnly`] if this replica's member is no admin of the space,
168	/// [`NodeError::NotAGroup`] if the space adds no such group, and an error if the change
169	/// cannot be saved.
170	pub fn remove_group(
171		&mut self,
172		space: SpaceId,
173		group: SpaceId,
174		wall_millis: u64,
175		rng: &mut impl CryptoRng,
176	) -> Result<(), NodeError> {
177		self.observe_wall(wall_millis);
178		self.check_admin(space, "take groups out")?;
179		let open = self.space(space)?;
180		let records: Vec<EntityId> = open
181			.stored
182			.log()
183			.groups(&open.keys)?
184			.into_iter()
185			.filter(|found| {
186				found.group.group == group
187					&& found.role.is_some_and(|role| role != MemberRole::None)
188			})
189			.map(|found| found.record)
190			.collect();
191		if records.is_empty() {
192			return Err(NodeError::NotAGroup(group));
193		}
194		for record in records {
195			self.set_role(space, record, MemberRole::None, wall_millis, rng)?;
196		}
197		Ok(())
198	}
199
200	/// The requests in a group that it join spaces, with the spaces' names where they are
201	/// sealed to this replica, and whether an admin agreed or withdrew.
202	///
203	/// # Errors
204	///
205	/// Returns [`NodeError::NotAGroup`] if the space is no group, and an error if it cannot be
206	/// read.
207	pub fn join_requests(&self, group: SpaceId) -> Result<Vec<GroupJoinRequest>, NodeError> {
208		if !self.is_group(group)? {
209			return Err(NodeError::NotAGroup(group));
210		}
211		let own = replica_record(group, &self.replica.signing.verifying_key());
212		let (agreements, withdrawals) = self.joinings(group)?;
213		// Of the joinings of each space, whether one stands, agreed and not withdrawn, and
214		// whether one was withdrawn.
215		let mut standing: BTreeMap<SpaceId, (bool, bool)> = BTreeMap::new();
216		let mut requests: BTreeMap<SpaceId, GroupJoinRequest> = BTreeMap::new();
217		let open = self.space(group)?;
218		for governing in open.stored.log().governing_statements(&open.keys)? {
219			let Some(request) = governing
220				.counting_text(&fields::JOIN_REQUEST)
221				.and_then(GroupRequest::from_text)
222			else {
223				continue;
224			};
225			let joining = request.joining;
226			let found = requests.entry(joining.space).or_insert(GroupJoinRequest {
227				space: joining.space,
228				name: None,
229				agreed: false,
230				withdrawn: false,
231			});
232			if found.name.is_none() {
233				found.name = request.name_for(own, &self.replica.decryption);
234			}
235			let state = standing.entry(joining.space).or_default();
236			let withdrawn = withdrawals.contains(&joining);
237			state.0 |= agreements.contains(&joining) && !withdrawn;
238			state.1 |= withdrawn;
239		}
240		for (space, (stands, withdrawn)) in standing {
241			if let Some(request) = requests.get_mut(&space) {
242				request.agreed = stands;
243				request.withdrawn = withdrawn && !stands;
244			}
245		}
246		Ok(requests.into_values().collect())
247	}
248
249	/// Agrees, as an admin of a group, to the requests that it join a space, and anchors the
250	/// agreement there if this replica holds the space.
251	///
252	/// # Errors
253	///
254	/// Returns [`NodeError::AdminsOnly`] if this replica's member is no admin of the group,
255	/// [`NodeError::NoGroupRequest`] if no request names the space, and an error if a change
256	/// cannot be saved.
257	pub fn agree_to_join(
258		&mut self,
259		group: SpaceId,
260		space: SpaceId,
261		wall_millis: u64,
262		rng: &mut impl CryptoRng,
263	) -> Result<(), NodeError> {
264		self.state_joinings(group, space, false, wall_millis, rng)
265	}
266
267	/// Withdraws, as an admin of a group, its agreement to join a space, for good: the group
268	/// leaves the space as a removal does, and joins it again only by a new addition and a
269	/// new agreement.
270	///
271	/// # Errors
272	///
273	/// As [`Library::agree_to_join`].
274	pub fn withdraw_group(
275		&mut self,
276		group: SpaceId,
277		space: SpaceId,
278		wall_millis: u64,
279		rng: &mut impl CryptoRng,
280	) -> Result<(), NodeError> {
281		self.state_joinings(group, space, true, wall_millis, rng)
282	}
283
284	/// Agrees to, or with `withdraw` withdraws, every joining of a space that the group's
285	/// requests name and that is not stated so already.
286	fn state_joinings(
287		&mut self,
288		group: SpaceId,
289		space: SpaceId,
290		withdraw: bool,
291		wall_millis: u64,
292		rng: &mut impl CryptoRng,
293	) -> Result<(), NodeError> {
294		if !self.is_group(group)? {
295			return Err(NodeError::NotAGroup(group));
296		}
297		self.check_admin(group, if withdraw { "withdraw" } else { "agree" })?;
298		let (agreements, withdrawals) = self.joinings(group)?;
299		let mut joinings = BTreeSet::new();
300		let open = self.space(group)?;
301		for governing in open.stored.log().governing_statements(&open.keys)? {
302			if let Some(request) = governing
303				.counting_text(&fields::JOIN_REQUEST)
304				.and_then(GroupRequest::from_text)
305				&& request.joining.space == space
306			{
307				joinings.insert(request.joining);
308			}
309		}
310		if joinings.is_empty() {
311			return Err(NodeError::NoGroupRequest);
312		}
313		let entity = self.group_entity(group)?;
314		let operations: Vec<_> = joinings
315			.iter()
316			.filter(|joining| {
317				if withdraw {
318					agreements.contains(joining) && !withdrawals.contains(joining)
319				} else {
320					!agreements.contains(joining) && !withdrawals.contains(joining)
321				}
322			})
323			.map(|joining| {
324				if withdraw {
325					nibkeep_governance::withdraw_from(entity, joining, rng)
326				} else {
327					nibkeep_governance::agree_to_join(entity, joining, rng)
328				}
329			})
330			.collect();
331		if !operations.is_empty() {
332			self.commit(group, operations, wall_millis, rng)?;
333		}
334		Ok(())
335	}
336
337	/// The groups that a space's governing changes add, with their roles, whether they agreed,
338	/// and, where this replica holds a group's log, its name and members.
339	///
340	/// # Errors
341	///
342	/// Returns [`NodeError::NeverShared`] for the personal space, and an error if a space
343	/// cannot be read.
344	pub fn space_groups(&self, space: SpaceId) -> Result<Vec<GroupInSpace>, NodeError> {
345		self.check_shared(space)?;
346		self.groups_of(space, &mut BTreeSet::from([space]))
347	}
348
349	/// The groups that a space's or a group's governing changes add, as
350	/// [`Library::space_groups`] gives them, with those inside each, at every level, but the
351	/// groups on the way there, `path`, which hold it.
352	fn groups_of(
353		&self,
354		space: SpaceId,
355		path: &mut BTreeSet<SpaceId>,
356	) -> Result<Vec<GroupInSpace>, NodeError> {
357		let open = self.space(space)?;
358		let mut groups = Vec::new();
359		for found in open.stored.log().groups(&open.keys)? {
360			let group = found.group.group;
361			let (name, members, inner) = if self.spaces.contains_key(&group) {
362				let inner = if path.insert(group) {
363					let inner = self.groups_of(group, path)?;
364					path.remove(&group);
365					inner
366				} else {
367					Vec::new()
368				};
369				(self.space_name(group)?, self.group_members(group)?, inner)
370			} else {
371				(None, Vec::new(), Vec::new())
372			};
373			groups.push(GroupInSpace {
374				record: found.record,
375				group,
376				name,
377				role: found.role.unwrap_or(MemberRole::None),
378				agreed: found.agreed,
379				members,
380				groups: inner,
381			});
382		}
383		Ok(groups)
384	}
385
386	/// The groups that a space's governing changes add, and, at every level, those that the
387	/// governing changes of each of them whose log this replica holds add, but the space
388	/// itself: what the space follows.
389	pub(crate) fn inner_groups(&self, space: SpaceId) -> Result<BTreeSet<SpaceId>, NodeError> {
390		let mut found = BTreeSet::new();
391		let mut to_visit = vec![space];
392		while let Some(at) = to_visit.pop() {
393			let Some(open) = self.spaces.get(&at) else {
394				continue;
395			};
396			for group in open.stored.log().groups(&open.keys)? {
397				let group = group.group.group;
398				if group != space && found.insert(group) {
399					to_visit.push(group);
400				}
401			}
402		}
403		Ok(found)
404	}
405
406	/// A group's members, with their roles and names there, but the groups inside it.
407	fn group_members(&self, group: SpaceId) -> Result<Vec<GroupMember>, NodeError> {
408		let open = self.space(group)?;
409		let state = open.stored.log().state();
410		let groups: BTreeSet<EntityId> = open
411			.stored
412			.log()
413			.groups(&open.keys)?
414			.iter()
415			.map(|found| found.record)
416			.collect();
417		let mut members = Vec::new();
418		for (record, role) in open.stored.log().member_roles(&open.keys)? {
419			if groups.contains(&record) {
420				continue;
421			}
422			members.push(GroupMember {
423				record,
424				name: super::entities::display_name(state, &open.types, &self.languages, record)?,
425				role,
426			});
427		}
428		Ok(members)
429	}
430
431	/// Settles the groups after a sync: takes the first keys of the groups that the spaces it
432	/// holds give, and the spaces that the groups it is in give it, follows each space's
433	/// groups, anchors the group changes that no anchor names yet, and gives the spaces it
434	/// holds to the members of the groups in them that lack them.
435	pub(crate) fn settle_groups(
436		&mut self,
437		wall_millis: u64,
438		rng: &mut impl CryptoRng,
439	) -> Result<(), NodeError> {
440		if self.is_ai_agent()? {
441			return Ok(());
442		}
443		// Each step goes on whatever another's error; the first is told at the end.
444		let results = [
445			self.take_group_keys(rng),
446			self.take_group_entries(wall_millis, rng),
447			self.follow_all_groups(),
448			self.anchor_all_groups(wall_millis, rng),
449			self.give_group_entries(wall_millis, rng),
450			self.settle_direct(wall_millis, rng),
451		];
452		results.into_iter().collect()
453	}
454
455	/// Follows the groups of every space it holds, as its copies of their logs say: done when
456	/// the library opens, before it takes or makes changes, and after each sync.
457	pub(crate) fn follow_all_groups(&mut self) -> Result<(), NodeError> {
458		let spaces: Vec<SpaceId> = self.spaces.keys().copied().collect();
459		for space in spaces {
460			if space != self.info.personal {
461				self.follow_groups(space)?;
462			}
463		}
464		Ok(())
465	}
466
467	/// Follows the groups that a space's governing changes add, and those inside them at every
468	/// level, as this replica's copies of their logs say; a group whose log it lacks is
469	/// followed with nothing.
470	fn follow_groups(&mut self, space: SpaceId) -> Result<(), NodeError> {
471		let groups = self.inner_groups(space)?;
472		if groups.is_empty() {
473			return Ok(());
474		}
475		let mut followed = Vec::new();
476		for group in groups {
477			if let Some(open) = self.spaces.get(&group) {
478				followed.push(open.stored.log().followed(&open.keys)?);
479			}
480		}
481		let open = self
482			.spaces
483			.get_mut(&space)
484			.ok_or(NodeError::NoSpace(space))?;
485		let keys = open.keys.clone();
486		open.stored.follow(&followed, &keys)?;
487		self.read_again(space)
488	}
489
490	/// After a change to a group that this replica made: follows it in each space it holds
491	/// that the group is in, at any level, and anchors the change there.
492	pub(crate) fn after_group_change(
493		&mut self,
494		group: SpaceId,
495		wall_millis: u64,
496		rng: &mut impl CryptoRng,
497	) -> Result<(), NodeError> {
498		let spaces: Vec<SpaceId> = self.spaces.keys().copied().collect();
499		for space in spaces {
500			if space == self.info.personal || space == group {
501				continue;
502			}
503			if self.inner_groups(space)?.contains(&group) {
504				self.follow_groups(space)?;
505				self.anchor_groups(space, wall_millis, rng)?;
506			}
507		}
508		Ok(())
509	}
510
511	/// Anchors, in every space it holds, the group changes that no anchor names yet.
512	fn anchor_all_groups(
513		&mut self,
514		wall_millis: u64,
515		rng: &mut impl CryptoRng,
516	) -> Result<(), NodeError> {
517		let spaces: Vec<SpaceId> = self.spaces.keys().copied().collect();
518		let mut first_error = Ok(());
519		for space in spaces {
520			if space == self.info.personal {
521				continue;
522			}
523			let anchored = self.anchor_groups(space, wall_millis, rng);
524			if first_error.is_ok() {
525				first_error = anchored;
526			}
527		}
528		first_error
529	}
530
531	/// Anchors, in a space or a group this replica is in, the changes of each group that
532	/// reaches it, at any level, whose log it holds, and whose governing changes that no other
533	/// builds on no counting anchor names yet, with the group's first key where no counting
534	/// change gives it: so the group's changes take effect there. It anchors no group that
535	/// holds the space at some level, which gives nothing through the cycle, and whose
536	/// anchors would answer each other's for ever.
537	fn anchor_groups(
538		&mut self,
539		space: SpaceId,
540		wall_millis: u64,
541		rng: &mut impl CryptoRng,
542	) -> Result<(), NodeError> {
543		if self.check_not_revoked(space).is_err() {
544			return Ok(());
545		}
546		let operations = self.anchoring(space, rng)?;
547		if !operations.is_empty() {
548			self.commit(space, operations, wall_millis, rng)?;
549		}
550		Ok(())
551	}
552
553	/// The operations that anchor in a space the groups that reach it, as
554	/// [`Library::anchor_groups`] says, whether or not this replica is listed there yet: a
555	/// replica that a group lists, and that the space lists through no anchor yet, is listed
556	/// there by its own anchor, as one that a recovery code brings back is.
557	pub(crate) fn anchoring(
558		&self,
559		space: SpaceId,
560		rng: &mut impl CryptoRng,
561	) -> Result<Vec<Operation>, NodeError> {
562		// A space it has nothing of yet anchors nothing.
563		let Some(space_root) = self.space(space)?.stored.log().root()? else {
564			return Ok(Vec::new());
565		};
566		let open = self.space(space)?;
567		let anchored = open.stored.log().anchored(&open.keys)?;
568		let given = self.given_group_keys(space)?;
569		// Only a group can be inside a group that it holds.
570		let cycles = self.is_group(space)?;
571		let mut operations = Vec::new();
572		for (record, found) in self.reaching_groups(space, space_root)? {
573			let group = found.group;
574			if cycles && self.inner_groups(group)?.contains(&space) {
575				continue;
576			}
577			let open_group = self.space(group)?;
578			let heads = open_group.stored.log().followed(&open_group.keys)?.heads();
579			let known = anchored.get(&group);
580			if heads
581				.iter()
582				.all(|head| known.is_some_and(|known| known.contains(head)))
583			{
584				continue;
585			}
586			let key = if given.contains(&found) {
587				None
588			} else {
589				open_group
590					.keys
591					.space_keys()
592					.find(|(epoch, _)| *epoch == 0)
593					.map(|(_, key)| GroupKey {
594						group: found,
595						key: key.clone(),
596					})
597			};
598			operations.extend(nibkeep_governance::anchor(
599				record,
600				&Anchor {
601					group,
602					changes: heads,
603				},
604				key.as_ref(),
605				rng,
606			));
607		}
608		Ok(operations)
609	}
610
611	/// The groups that reach a space, as this replica's copies of their logs say: each group
612	/// that the space adds with a role, whose log it holds, naming that log's first change,
613	/// and that agreed to that addition, once only, also once it withdrew, as an anchor of a
614	/// withdrawal is needed too; and, the same way, each group inside one of those that has not
615	/// withdrawn, at every level. Each comes with its record in the space, or that of the group
616	/// in the space it reaches it through.
617	pub(crate) fn reaching_groups(
618		&self,
619		space: SpaceId,
620		root: ChangeId,
621	) -> Result<Vec<(EntityId, GroupRef)>, NodeError> {
622		let mut reaching = Vec::new();
623		let mut seen = BTreeSet::from([space]);
624		let mut joinings: BTreeMap<SpaceId, (BTreeSet<Joining>, BTreeSet<Joining>)> =
625			BTreeMap::new();
626		let mut to_visit: Vec<(SpaceId, ChangeId, Option<EntityId>)> = vec![(space, root, None)];
627		while let Some((container, container_root, through)) = to_visit.pop() {
628			let open = self.space(container)?;
629			for found in open.stored.log().groups(&open.keys)? {
630				let group = found.group.group;
631				if seen.contains(&group)
632					|| !matches!(found.role, Some(MemberRole::Editor | MemberRole::Viewer))
633				{
634					continue;
635				}
636				let Some(open_group) = self.spaces.get(&group) else {
637					continue;
638				};
639				if open_group.stored.log().root()? != Some(found.group.root) {
640					continue;
641				}
642				if let std::collections::btree_map::Entry::Vacant(entry) = joinings.entry(group) {
643					entry.insert(self.joinings(group)?);
644				}
645				let joining = Joining {
646					space: container,
647					root: container_root,
648					addition: found.addition,
649				};
650				let Some((agreed, withdrawn)) = joinings.get(&group) else {
651					continue;
652				};
653				if !agreed.contains(&joining) {
654					continue;
655				}
656				seen.insert(group);
657				let record = through.unwrap_or(found.record);
658				reaching.push((record, found.group));
659				if !withdrawn.contains(&joining) {
660					to_visit.push((group, found.group.root, Some(record)));
661				}
662			}
663		}
664		Ok(reaching)
665	}
666
667	/// The groups, with their first changes, whose first keys a counting governing change of a
668	/// space gives.
669	fn given_group_keys(&self, space: SpaceId) -> Result<BTreeSet<GroupRef>, NodeError> {
670		let open = self.space(space)?;
671		Ok(open
672			.stored
673			.log()
674			.governing_statements(&open.keys)?
675			.into_iter()
676			.filter_map(|governing| {
677				GroupKey::from_text(governing.counting_text(&fields::GROUP_KEY)?)
678			})
679			.map(|key| key.group)
680			.collect())
681	}
682
683	/// Takes the first key of each group that a space it holds gives the key of, and whose log
684	/// it lacks: only the key whose hash a record of the group names, in a space or a group it
685	/// holds, as the spaces a group is in give the keys of the groups inside it too; keeps the
686	/// group's log, empty until it syncs it, taking as its first change only the one that the
687	/// record names.
688	pub(crate) fn take_group_keys(&mut self, rng: &mut impl CryptoRng) -> Result<(), NodeError> {
689		let mut records: BTreeSet<GroupRef> = BTreeSet::new();
690		for (&space, open) in &self.spaces {
691			if space != self.info.personal {
692				records.extend(
693					open.stored
694						.log()
695						.groups(&open.keys)?
696						.iter()
697						.map(|group| group.group),
698				);
699			}
700		}
701		if records.is_empty() {
702			return self.expect_group_roots();
703		}
704		let mut found: BTreeMap<GroupRef, (bool, nibkeep_crypto::Key)> = BTreeMap::new();
705		for (&space, open) in &self.spaces {
706			if space == self.info.personal {
707				continue;
708			}
709			let log = open.stored.log();
710			for governing in log.governing_statements(&open.keys)? {
711				if governing.statement.field != fields::GROUP_KEY {
712					continue;
713				}
714				let Some(key) = governing
715					.statement
716					.value
717					.as_text()
718					.and_then(GroupKey::from_text)
719				else {
720					continue;
721				};
722				// Only the key whose hash the record of the group names.
723				if !records.contains(&key.group)
724					|| key_hash(&key.key) != key.group.key
725					|| self.spaces.contains_key(&key.group.group)
726				{
727					continue;
728				}
729				found
730					.entry(key.group)
731					.or_insert((governing.counts, key.key));
732			}
733		}
734		for (group, (_, key)) in found {
735			self.add_space(group.group, &key, rng)?;
736			if let Some(open) = self.spaces.get_mut(&group.group) {
737				open.stored.expect_roots([group.root]);
738			}
739		}
740		self.expect_group_roots()
741	}
742
743	/// Has each group's log that has no first change yet take as its first change only one
744	/// that a space's record of the group names, besides any that another source names.
745	pub(crate) fn expect_group_roots(&mut self) -> Result<(), NodeError> {
746		let mut roots: BTreeMap<SpaceId, BTreeSet<ChangeId>> = BTreeMap::new();
747		for open in self.spaces.values() {
748			for found in open.stored.log().groups(&open.keys)? {
749				roots
750					.entry(found.group.group)
751					.or_default()
752					.insert(found.group.root);
753			}
754		}
755		for (group, roots) in roots {
756			if let Some(open) = self.spaces.get_mut(&group)
757				&& open.stored.log().root()?.is_none()
758			{
759				open.stored.expect_roots_too(roots);
760			}
761		}
762		Ok(())
763	}
764
765	/// Gives, in each group this replica's member is an admin of, the spaces it holds that the
766	/// group is in to the group's members' replicas that lack them, but AI agents', and to
767	/// their recovery codes that stand: an entry for each, sealed to the replica or the code,
768	/// with the space's first key, naming its first change.
769	/// Only for a space whose record of the group has a role, and that the group agreed to
770	/// join and has not withdrawn from. Only as an admin, as an entry counts from no other
771	/// member: another's would be set aside, and made again after every sync.
772	fn give_group_entries(
773		&mut self,
774		wall_millis: u64,
775		rng: &mut impl CryptoRng,
776	) -> Result<(), NodeError> {
777		let groups: Vec<SpaceId> = self
778			.spaces
779			.keys()
780			.copied()
781			.filter(|&space| self.is_group(space).unwrap_or(false))
782			.collect();
783		for group in groups {
784			if self.check_admin(group, "give a space").is_err() {
785				continue;
786			}
787			let (agreements, withdrawals) = self.joinings(group)?;
788			let (given, remaining) = self.group_recipients(group)?;
789			let mut operations = Vec::new();
790			let spaces: Vec<SpaceId> = self.spaces.keys().copied().collect();
791			for space in spaces {
792				if space == self.info.personal
793					|| space == group
794					|| self.check_not_revoked(space).is_err()
795				{
796					continue;
797				}
798				let open = self.space(space)?;
799				let in_space = open
800					.stored
801					.log()
802					.groups(&open.keys)?
803					.into_iter()
804					.find(|found| {
805						found.group.group == group
806							&& found.agreed
807							&& matches!(found.role, Some(MemberRole::Editor | MemberRole::Viewer))
808					});
809				let Some(found) = in_space else { continue };
810				let Some(root) = self.space(space)?.stored.log().root()? else {
811					continue;
812				};
813				let joining = Joining {
814					space,
815					root,
816					addition: found.addition,
817				};
818				if !agreements.contains(&joining) || withdrawals.contains(&joining) {
819					continue;
820				}
821				let Some(first) = self
822					.space(space)?
823					.keys
824					.space_keys()
825					.find(|(epoch, _)| *epoch == 0)
826					.map(|(_, key)| key.clone())
827				else {
828					continue;
829				};
830				let hash = key_hash(&first);
831				for (record, member, encryption) in &remaining {
832					if given.contains(&(*record, space)) {
833						continue;
834					}
835					let entry = SpaceEntry::seal(
836						encryption,
837						(space, *member, *root.hash()),
838						*record,
839						(&first, hash),
840						rng,
841					);
842					operations.push(give_space_entry(*record, &entry, rng));
843				}
844			}
845			if !operations.is_empty() {
846				self.commit(group, operations, wall_millis, rng)?;
847			}
848		}
849		Ok(())
850	}
851
852	/// The spaces that a group's counting entries give each replica or code, as
853	/// `(record, space)`, and the group's members' replicas that remain, but AI agents' and
854	/// this one, and their recovery codes that the group's keys are given to: each record,
855	/// its member and its encryption key.
856	#[expect(
857		clippy::type_complexity,
858		reason = "a pair of what is given and to whom, each read once"
859	)]
860	fn group_recipients(
861		&self,
862		group: SpaceId,
863	) -> Result<
864		(
865			BTreeSet<(EntityId, SpaceId)>,
866			Vec<(EntityId, EntityId, EncryptionKey)>,
867		),
868		NodeError,
869	> {
870		let own = self.replica.signing.verifying_key();
871		let roster = self.roster(group)?;
872		let open = self.space(group)?;
873		let log = open.stored.log();
874		let given = log
875			.governing_statements(&open.keys)?
876			.into_iter()
877			.filter_map(|governing| {
878				let entry = SpaceEntry::from_text(governing.counting_text(&fields::SPACE_ENTRY)?)?;
879				Some((governing.statement.entity, entry.space))
880			})
881			.collect();
882		// The members of keys that groups inside the group list are in those groups.
883		let (_, mut owners) = self.users_and_owners(group)?;
884		for inner in self.inner_groups(group)? {
885			if self.spaces.contains_key(&inner) {
886				for (key, owner) in self.users_and_owners(inner)?.1 {
887					owners.entry(key).or_insert(owner);
888				}
889			}
890		}
891		let mut remaining = Vec::new();
892		for record in roster.replicas() {
893			let Some(key) = roster.keys_of(record).first() else {
894				continue;
895			};
896			if *key == own
897				|| log.is_revoked(key, &open.keys)?
898				|| log.is_removed(key, &open.keys)?
899				|| log.is_ai_agent(key, &open.keys)?
900			{
901				continue;
902			}
903			if let (Some(owner), Some(encryption)) =
904				(owners.get(key.as_bytes()), roster.encryption_of(record))
905			{
906				remaining.push((record, *owner, encryption.clone()));
907			}
908		}
909		// A code is given the group's spaces as its member's replicas are, so that a device
910		// that it brings back finds them: while it stands and its member is in the group.
911		for code in self.code_recipients(group, &roster, &[])? {
912			remaining.push((
913				code.record,
914				code.statement.member,
915				code.statement.encryption.clone(),
916			));
917		}
918		Ok((given, remaining))
919	}
920
921	/// Takes the spaces that the groups this replica is in give it, on its record there, and
922	/// that it lacks, as [`Library::agreed_entries`] lists them, as spaces made elsewhere: as
923	/// [`Library::takes_entry`] says, by its newest choice of each and its mark for new
924	/// spaces; opens each first key, keeps it if its hash is the one named, and keeps the
925	/// space, empty until it syncs it, taking as its first change only the one named; and
926	/// states, in one change, that it holds those it took.
927	fn take_group_entries(
928		&mut self,
929		wall_millis: u64,
930		rng: &mut impl CryptoRng,
931	) -> Result<(), NodeError> {
932		let own = self.replica.signing.verifying_key();
933		let groups: Vec<SpaceId> = self
934			.spaces
935			.keys()
936			.copied()
937			.filter(|&space| self.is_group(space).unwrap_or(false))
938			.collect();
939		if groups.is_empty() {
940			return Ok(());
941		}
942		let read = self.read_personal()?;
943		let choices = self.own_choices(&read);
944		let takes_new = self.own_mark(&read);
945		let mut taking = Vec::new();
946		for group in groups {
947			if self.check_not_revoked(group).is_err() {
948				continue;
949			}
950			let record = replica_record(group, &own);
951			for (entry, root) in self.agreed_entries(group, record)? {
952				if self.spaces.contains_key(&entry.space)
953					|| !Self::takes_entry(choices.get(&entry.space).copied(), takes_new)
954				{
955					continue;
956				}
957				if let Some(key) = entry.open(&self.replica.decryption, record)
958					&& key_hash(&key) == entry.hash
959				{
960					taking.push((entry.space, root, key));
961				}
962			}
963		}
964		let mut taken = Vec::new();
965		for (space, root, key) in taking {
966			if self.spaces.contains_key(&space) {
967				continue;
968			}
969			self.add_space(space, &key, rng)?;
970			if let Some(open) = self.spaces.get_mut(&space) {
971				open.stored.expect_roots([root]);
972			}
973			taken.push(space);
974		}
975		if taken.is_empty() {
976			return Ok(());
977		}
978		self.state_holding(&taken, wall_millis, rng)
979	}
980
981	/// The entries that a group gives on `record`, this replica's record there, each with the
982	/// first change it names: only for a space that the group agreed to join, naming that
983	/// first change, and has not withdrawn from.
984	pub(crate) fn agreed_entries(
985		&self,
986		group: SpaceId,
987		record: EntityId,
988	) -> Result<Vec<(SpaceEntry, ChangeId)>, NodeError> {
989		let (agreements, withdrawals) = self.joinings(group)?;
990		let open = self.space(group)?;
991		let mut entries = Vec::new();
992		for governing in open.stored.log().governing_statements(&open.keys)? {
993			let Some(entry) = governing
994				.counting_text(&fields::SPACE_ENTRY)
995				.filter(|_| governing.statement.entity == record)
996				.and_then(SpaceEntry::from_text)
997			else {
998				continue;
999			};
1000			let root = ChangeId::from_hash(entry.root);
1001			let agreed = agreements.iter().any(|joining| {
1002				joining.space == entry.space
1003					&& joining.root == root
1004					&& !withdrawals.contains(joining)
1005			});
1006			if agreed {
1007				entries.push((entry, root));
1008			}
1009		}
1010		Ok(entries)
1011	}
1012
1013	/// Has each space that this replica holds but has no first change of take as its first
1014	/// change only one that the groups name: a group's log, as
1015	/// [`Library::expect_group_roots`] says, and a space that a group gave it, as
1016	/// [`Library::expect_group_entry_roots`] says; each whatever the other's error. The log
1017	/// expects a first change only while the library is open, so this is done when it opens,
1018	/// and when it opens a space that another program took. Where a group cannot be read,
1019	/// each such space that nothing named a first change for takes none until the library
1020	/// opens again, rather than any.
1021	pub(crate) fn expect_roots_from_groups(&mut self) -> Result<(), NodeError> {
1022		let logs = self.expect_group_roots();
1023		let entries = self.expect_group_entry_roots();
1024		if logs.is_err() || entries.is_err() {
1025			for (&space, open) in &mut self.spaces {
1026				if space != self.info.personal {
1027					open.stored.expect_roots_too([]);
1028				}
1029			}
1030		}
1031		logs.and(entries)
1032	}
1033
1034	/// Has each space that this replica holds but has no first change of take as its first
1035	/// change only one that an entry a group gave it names, as [`Library::agreed_entries`]
1036	/// lists them, with the hash of the first key it keeps, besides any that another source
1037	/// names: so that a device of the group cannot have it take one of its own making. A
1038	/// group it cannot read is passed over, and the first error told once the others are
1039	/// read.
1040	fn expect_group_entry_roots(&mut self) -> Result<(), NodeError> {
1041		let mut waiting: BTreeMap<SpaceId, Hash> = BTreeMap::new();
1042		for (&space, open) in &self.spaces {
1043			if space != self.info.personal
1044				&& matches!(open.stored.log().root(), Ok(None))
1045				&& let Some(hash) = open.first_key_hash()
1046			{
1047				waiting.insert(space, hash);
1048			}
1049		}
1050		// Nothing to read where every space has its first change, as is usual.
1051		if waiting.is_empty() {
1052			return Ok(());
1053		}
1054		let own = self.replica.signing.verifying_key();
1055		let mut roots: BTreeMap<SpaceId, BTreeSet<ChangeId>> = BTreeMap::new();
1056		let mut failed = None;
1057		for (&group, open) in &self.spaces {
1058			let entries = open.is_group().and_then(|is_group| {
1059				if is_group {
1060					self.agreed_entries(group, replica_record(group, &own))
1061				} else {
1062					Ok(Vec::new())
1063				}
1064			});
1065			match entries {
1066				Ok(entries) => {
1067					for (entry, root) in entries {
1068						if waiting.get(&entry.space) == Some(&entry.hash) {
1069							roots.entry(entry.space).or_default().insert(root);
1070						}
1071					}
1072				}
1073				Err(error) => {
1074					failed.get_or_insert(error);
1075				}
1076			}
1077		}
1078		for (space, roots) in roots {
1079			if let Some(open) = self.spaces.get_mut(&space) {
1080				open.stored.expect_roots_too(roots);
1081			}
1082		}
1083		failed.map_or(Ok(()), Err)
1084	}
1085
1086	/// The joinings that a group's counting governing changes agree to, and those they
1087	/// withdraw.
1088	fn joinings(
1089		&self,
1090		group: SpaceId,
1091	) -> Result<(BTreeSet<Joining>, BTreeSet<Joining>), NodeError> {
1092		let open = self.space(group)?;
1093		let mut agreements = BTreeSet::new();
1094		let mut withdrawals = BTreeSet::new();
1095		for governing in open.stored.log().governing_statements(&open.keys)? {
1096			let joining =
1097				|field: &FieldName| governing.counting_text(field).and_then(Joining::from_text);
1098			if let Some(joining) = joining(&fields::JOINED) {
1099				agreements.insert(joining);
1100			} else if let Some(joining) = joining(&fields::WITHDRAWN) {
1101				withdrawals.insert(joining);
1102			}
1103		}
1104		Ok((agreements, withdrawals))
1105	}
1106
1107	/// The records and encryption keys of the replicas of a group's admins, but revoked ones.
1108	fn admins_replicas(&self, group: SpaceId) -> Result<Vec<(EntityId, EncryptionKey)>, NodeError> {
1109		let roster = self.roster(group)?;
1110		let (_, owners) = self.users_and_owners(group)?;
1111		let open = self.space(group)?;
1112		let log = open.stored.log();
1113		let roles = log.member_roles(&open.keys)?;
1114		let mut admins = Vec::new();
1115		for record in roster.replicas() {
1116			let Some(key) = roster.keys_of(record).first() else {
1117				continue;
1118			};
1119			let admin = owners
1120				.get(key.as_bytes())
1121				.is_some_and(|owner| roles.get(owner) == Some(&MemberRole::Admin));
1122			if admin
1123				&& !log.is_revoked(key, &open.keys)?
1124				&& let Some(encryption) = roster.encryption_of(record)
1125			{
1126				admins.push((record, encryption.clone()));
1127			}
1128		}
1129		Ok(admins)
1130	}
1131
1132	/// A group's own entity, which its requests and agreements are stated on.
1133	fn group_entity(&self, group: SpaceId) -> Result<EntityId, NodeError> {
1134		self.space(group)?
1135			.own_entity()?
1136			.ok_or_else(|| NodeError::Damaged(format!("the group {group} has no record")))
1137	}
1138
1139	/// A space's first key, if this replica holds it.
1140	fn first_key(&self, space: SpaceId) -> Result<Option<nibkeep_crypto::Key>, NodeError> {
1141		Ok(self
1142			.space(space)?
1143			.keys
1144			.space_keys()
1145			.find(|(epoch, _)| *epoch == 0)
1146			.map(|(_, key)| key.clone()))
1147	}
1148
1149	/// A space's first change.
1150	fn root_of(&self, space: SpaceId) -> Result<ChangeId, NodeError> {
1151		self.space(space)?
1152			.stored
1153			.log()
1154			.root()?
1155			.ok_or_else(|| NodeError::Damaged(format!("the space {space} has no first change")))
1156	}
1157}