Skip to main content

nibkeep_governance/rules/
roles.rs

1//! Roles in a space with members ([technical design: sharing]): which governing changes count by
2//! what their authors' roles allow, never leaving the space without a direct admin; and, for
3//! ordinary changes, the author's member and role at a change.
4//!
5//! A member's role at a change is what the counting governing changes it builds on give the
6//! member, the lowest of those that no other of them builds on, lowered by each counting one
7//! that gives the member a lower role and that it neither builds on nor is built on by:
8//! nobody acts on a role they did not know they had, and what someone did without knowing
9//! that they had lost one is set aside.
10//!
11//! [technical design: sharing]: ../../../../docs/Technical-design.md#13-sharing
12
13use std::cell::RefCell;
14use std::collections::{BTreeMap, BTreeSet};
15use std::rc::Rc;
16
17use nibkeep_base::{EntityId, SpaceId};
18use nibkeep_crypto::VerifyingKey;
19use nibkeep_model::{Operation, Statement, fields};
20use nibkeep_time::Timestamp;
21
22use super::claims::{ClaimEffect, Deciding, Records, WAIT_MILLIS, after, given_at};
23use super::groups::{
24	Ends, GroupMember, Knowledge, Lowering, Person, Reach, Routes, key_records, person_of,
25};
26use super::{Fact, KeyBytes, Label};
27use crate::{RecoveryEntry, RecoveryStatement};
28use nibkeep_base::ChangeId;
29
30/// A member's role in a space with members, lowest first: `none` for a member who left or
31/// was removed.
32#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
33pub enum Role {
34	/// No longer a member.
35	None,
36	/// Sees everything, and changes only their own records.
37	Viewer,
38	/// Also changes everything but other members' records, and purges what they signed.
39	Editor,
40	/// Everything.
41	Admin,
42}
43
44impl Role {
45	/// The role that a statement of [`fields::ROLE`] names, if it names one.
46	#[must_use]
47	pub fn from_text(text: &str) -> Option<Self> {
48		match text {
49			"none" => Some(Self::None),
50			"viewer" => Some(Self::Viewer),
51			"editor" => Some(Self::Editor),
52			"admin" => Some(Self::Admin),
53			_ => None,
54		}
55	}
56
57	/// The role as a statement of [`fields::ROLE`] names it.
58	#[must_use]
59	pub const fn as_text(self) -> &'static str {
60		match self {
61			Self::None => "none",
62			Self::Viewer => "viewer",
63			Self::Editor => "editor",
64			Self::Admin => "admin",
65		}
66	}
67}
68
69impl std::fmt::Display for Role {
70	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71		f.write_str(self.as_text())
72	}
73}
74
75/// What a statement or a retraction of a governing change touches, which its author's role
76/// must allow, besides listings, revocations and roles, which have rules of their own.
77#[derive(Clone, Copy, Debug)]
78pub(super) enum Touch {
79	/// A field of a replica's record that its member states: its key, encryption key, owner,
80	/// listing and mark, and its secrets encryption key and source.
81	Record(EntityId),
82	/// What every member states: a key given to a replica, a space key or a secrets key; an
83	/// anchor of a group's changes, and a group's first key; and, in a group, a request that
84	/// it join a space.
85	Gift,
86	/// What only an admin states: acceptances, fields secret for good, members' user IDs, a
87	/// user's spaces, and that a replica takes the secrets from itself, which sets them up.
88	Admin,
89	/// A retraction of statements of an entity, or of any, of the earlier form.
90	Retraction(Option<EntityId>),
91	/// A claim to the admin role, on a member's record, which only that member makes, as an
92	/// editor.
93	Claim(EntityId),
94	/// A recovery code, or its revocation, on this record, naming this recovery key: only the
95	/// replicas of the member whose record for the code it is state either.
96	Code(EntityId, VerifyingKey),
97	/// A device's choice of the space, on its record there: only the replicas of its member
98	/// carry it, an admin of another member's not even.
99	Choice(EntityId),
100}
101
102impl Touch {
103	/// What an operation of a governing change touches: what its statement does, as
104	/// [`Touch::of`] says, with what it replaces, which is changed as a retraction would
105	/// change it; or what it retracts; or, for an operation of an unknown kind, whatever a
106	/// later version may do with it, which is for an admin alone.
107	pub(super) fn of_operation(operation: &Operation) -> Vec<Self> {
108		match operation {
109			Operation::Assert {
110				statement,
111				supersedes,
112				any_entity,
113			} => {
114				let mut touches: Vec<Self> = Self::of(statement).into_iter().collect();
115				if !supersedes.is_empty() {
116					touches.push(Self::Retraction((!any_entity).then_some(statement.entity)));
117				}
118				touches
119			}
120			Operation::Retract { entity, .. } => vec![Self::Retraction(*entity)],
121			// A governing change holds none, as no statement that governs is secret.
122			Operation::RetractSecret { .. } | Operation::Unknown(_) => vec![Self::Admin],
123		}
124	}
125
126	/// What a statement of a governing change touches, if not a role or a revocation.
127	pub(super) fn of(statement: &Statement) -> Option<Self> {
128		let field = &statement.field;
129		let records = [
130			fields::SIGNING_KEY,
131			fields::ENCRYPTION_KEY,
132			fields::OWNER,
133			fields::LISTING,
134			fields::AI_AGENT,
135			fields::SECRETS_ENCRYPTION_KEY,
136			fields::SECRETS_FROM,
137			fields::RECOVERY_LISTING,
138		];
139		if *field == fields::ROLE || *field == fields::REVOKED {
140			None
141		} else if *field == fields::CLAIM {
142			Some(Self::Claim(statement.entity))
143		} else if *field == fields::RECOVERY_KEY
144			|| *field == fields::RECOVERY_REVOKED
145			|| *field == fields::RECOVERY_ENTRY
146		{
147			// A member's own replicas state their member's codes, revoke them, and state the
148			// entries that they signed, on the records derived for that member; a text that
149			// names no key is for a later version.
150			let text = statement.value.as_text();
151			let key = if *field == fields::RECOVERY_KEY {
152				text.and_then(RecoveryStatement::from_text)
153					.map(|stated| stated.key)
154			} else if *field == fields::RECOVERY_ENTRY {
155				text.and_then(RecoveryEntry::from_text)
156					.map(|entry| entry.key)
157			} else {
158				text.and_then(VerifyingKey::from_text)
159			};
160			Some(key.map_or(Self::Admin, |key| Self::Code(statement.entity, key)))
161		} else if *field == fields::SPACE_CHOICE {
162			Some(Self::Choice(statement.entity))
163		} else if *field == fields::SEEN {
164			// Every member shows, on their own records, that they saw a claim or a rejection.
165			Some(Self::Record(statement.entity))
166		} else if *field == fields::KEPT_OUT {
167			// Every member keeps their own keys out, leaving the space and staying in the
168			// group; only an admin keeps others out, or lets anyone back.
169			Some(if statement.value == nibkeep_model::Value::Boolean(true) {
170				Self::Record(statement.entity)
171			} else {
172				Self::Admin
173			})
174		} else if *field == fields::SECRETS_FROM
175			&& statement.value.as_reference() == Some(statement.entity)
176		{
177			// Taking the secrets from itself sets them up, which only an admin does.
178			Some(Self::Admin)
179		} else if records.contains(field) {
180			Some(Self::Record(statement.entity))
181		} else if *field == fields::SPACE_KEY
182			|| *field == fields::SECRETS_KEY
183			|| *field == fields::ANCHOR
184			|| *field == fields::GROUP_KEY
185			|| *field == fields::JOIN_REQUEST
186		{
187			// Every member gives keys, and anchors the groups' changes it knows.
188			Some(Self::Gift)
189		} else {
190			Some(Self::Admin)
191		}
192	}
193}
194
195/// The member that a key belongs to at a governing change, as far as decided.
196#[derive(Clone, Copy, Debug, PartialEq, Eq)]
197enum Owner {
198	/// Not decided yet, as the listing that decides it is not.
199	Undecided,
200	/// No counting listing that the change builds on names one.
201	Nobody,
202	/// This member.
203	Member(EntityId),
204}
205
206/// The person whose key signed a governing change, as far as decided.
207#[derive(Clone, Debug)]
208enum Who {
209	/// Not decided yet, as a listing or a revocation that decides it is not.
210	Undecided,
211	/// No counting listing that the change builds on names the key, or it is revoked.
212	Nobody,
213	/// This person.
214	Person(Person),
215}
216
217/// Whether what lowers a governing change's author's role, without its knowing, leaves it
218/// as it was, as far as decided.
219#[derive(Clone, Copy, Debug, PartialEq, Eq)]
220pub(super) enum Kept {
221	/// Not decided yet.
222	Undecided,
223	/// Some path still allows it.
224	Yes,
225	/// Every path that allowed it is lowered.
226	No,
227}
228
229/// What a governing change needs of its author's member's role.
230#[derive(Clone, Copy, Debug, PartialEq, Eq)]
231enum Need {
232	/// Not decided yet, as a change it depends on is not.
233	Undecided,
234	/// Nobody's role allows it, such as listing another member's replica.
235	Never,
236	/// At least this role.
237	At(Role),
238}
239
240/// Whether a governing change's author's role allows it, as far as decided.
241#[derive(Clone, Copy, Debug, PartialEq, Eq)]
242pub(super) enum Verdict {
243	/// Not decided yet.
244	Undecided,
245	/// No role of the author's allows it.
246	Refused,
247	/// The role of the author's member allows it, which needs at least `need`.
248	Allowed {
249		/// The author's member.
250		member: EntityId,
251		/// What the change needs of the member's role.
252		need: Role,
253	},
254}
255
256/// What deciding the governing changes of a space with members needs besides their
257/// listings and revocations: which facts each builds on, and who became an admin when.
258pub(super) struct Members<'a> {
259	facts: &'a [Fact],
260	/// For each fact, the facts it builds on, by index: all come before it.
261	ancestors: &'a [BTreeSet<usize>],
262	/// When each member became an admin: the order of the earliest change that made them
263	/// one, whose author was an admin before it, back to the space's first change, whether
264	/// those changes count or not.
265	admin_since: BTreeMap<EntityId, (Timestamp, ChangeId)>,
266	/// What the groups that the space follows give in it, if it follows any.
267	reach: Option<&'a Reach>,
268	/// The space.
269	space: SpaceId,
270	/// For every key that a fact revokes, the facts that revoke it.
271	revoking: BTreeMap<KeyBytes, Vec<usize>>,
272	/// Each fact's index, by its ID.
273	index: BTreeMap<ChangeId, usize>,
274	/// What each fact knows of the groups, and the keys that the groups in the space list
275	/// there, found once for each fact, as they depend on the anchors taken to count alone.
276	groups: RefCell<BTreeMap<usize, Rc<ThroughGroups>>>,
277	/// Each fact's author's person, once decided, while the labels being decided are the
278	/// same ([`Members::forget_decided`]).
279	people: RefCell<BTreeMap<usize, Who>>,
280	/// The facts that claim the admin role for each record.
281	claims: BTreeMap<EntityId, Vec<usize>>,
282	/// The keys whose choices of the space any fact states, so that deciding a fact by its
283	/// author's choices costs nothing where nobody chose.
284	chosen: BTreeSet<KeyBytes>,
285}
286
287/// What a fact knows of the groups, and the routes by which the groups in the space give keys
288/// roles there.
289struct ThroughGroups {
290	knowledge: Knowledge,
291	routes: Routes,
292}
293
294impl<'a> Members<'a> {
295	/// For `facts` in their order, each of which builds on those `ancestors` names, with the
296	/// member that the first listing of each key names, as [`super::listings`] finds it. A
297	/// later listing that names another member, as when a member comes back, changes a key's
298	/// member for seniority only if its author had become an admin before it.
299	pub(super) fn new(
300		facts: &'a [Fact],
301		ancestors: &'a [BTreeSet<usize>],
302		first_owner: &BTreeMap<KeyBytes, EntityId>,
303		(space, reach): (SpaceId, Option<&'a Reach>),
304	) -> Self {
305		let mut admin_since: BTreeMap<EntityId, (Timestamp, ChangeId)> = BTreeMap::new();
306		let mut owner = first_owner.clone();
307		for fact in facts {
308			// A claimant becomes an admin no earlier than 60 days after the claim, when it
309			// may be settled: junior to every admin before, and earlier than those they make.
310			for (record, _) in &fact.claims {
311				let settled = after(fact.order.0, 2 * WAIT_MILLIS);
312				admin_since.entry(*record).or_insert((settled, fact.id));
313			}
314			let author = if fact.root {
315				fact.owner_of(&fact.author)
316			} else {
317				owner.get(&fact.author).copied()
318			};
319			let was_admin = fact.root
320				|| author.is_some_and(|author| {
321					admin_since
322						.get(&author)
323						.is_some_and(|&since| since < fact.order)
324				});
325			if !was_admin {
326				continue;
327			}
328			for (member, role) in &fact.roles {
329				if *role == Role::Admin {
330					admin_since.entry(*member).or_insert(fact.order);
331				}
332			}
333			for (index, (_, key)) in fact.lists.iter().enumerate() {
334				if let Some(listed) = fact.owners[index] {
335					owner.insert(*key, listed);
336				}
337			}
338		}
339		let mut revoking: BTreeMap<KeyBytes, Vec<usize>> = BTreeMap::new();
340		for (at, fact) in facts.iter().enumerate() {
341			for key in &fact.revokes {
342				revoking.entry(*key).or_default().push(at);
343			}
344		}
345		Self {
346			facts,
347			ancestors,
348			admin_since,
349			reach,
350			space,
351			revoking,
352			index: facts
353				.iter()
354				.enumerate()
355				.map(|(at, fact)| (fact.id, at))
356				.collect(),
357			groups: RefCell::default(),
358			people: RefCell::default(),
359			chosen: facts
360				.iter()
361				.flat_map(|fact| fact.choices().iter().map(|(key, ..)| *key))
362				.collect(),
363			claims: {
364				let mut claims: BTreeMap<EntityId, Vec<usize>> = BTreeMap::new();
365				for (at, fact) in facts.iter().enumerate() {
366					for (record, _) in &fact.claims {
367						claims.entry(*record).or_default().push(at);
368					}
369				}
370				claims
371			},
372		}
373	}
374
375	/// When a member became an admin, for comparing two admins: a member with no such time,
376	/// as one made one by a change whose author's member is unknown, comes after every other.
377	fn seniority(&self, member: EntityId) -> (bool, Option<(Timestamp, ChangeId)>) {
378		let since = self.admin_since.get(&member).copied();
379		(since.is_none(), since)
380	}
381
382	/// Forgets the people found for facts, as the labels they were decided by are to be
383	/// decided anew.
384	pub(super) fn forget_decided(&self) {
385		self.people.borrow_mut().clear();
386	}
387
388	/// What fact `at` knows of the groups, and the keys that the groups in the space list
389	/// there: found once.
390	fn through_groups(&self, at: usize) -> Option<Rc<ThroughGroups>> {
391		let reach = self.reach?;
392		if let Some(found) = self.groups.borrow().get(&at) {
393			return Some(Rc::clone(found));
394		}
395		let known: Vec<ChangeId> = self.ancestors[at]
396			.iter()
397			.map(|&earlier| self.facts[earlier].id)
398			.collect();
399		let own = self.facts[at].id;
400		let knowledge = reach.knowledge(&known, reach.is_anchor(&own).then_some(own));
401		let made = |change: &ChangeId| self.builds_on_or_is(at, change);
402		let groups = reach.groups_in(&knowledge, made);
403		let routes = reach.routes(&knowledge, &groups);
404		let found = Rc::new(ThroughGroups { knowledge, routes });
405		self.groups.borrow_mut().insert(at, Rc::clone(&found));
406		Some(found)
407	}
408
409	/// Whether a key joins records at fact `at`, as one revoked by no counting fact that `at`
410	/// builds on, and by no group by what it knows, does; `None` while one of those facts is
411	/// undecided.
412	fn joins(
413		&self,
414		key: &KeyBytes,
415		at: usize,
416		labels: &[Label],
417		knowledge: &Knowledge,
418	) -> Option<bool> {
419		if self
420			.reach
421			.is_some_and(|reach| reach.revoked(key, knowledge))
422		{
423			return Some(false);
424		}
425		let mut joins = true;
426		for &revocation in self.revoking.get(key).into_iter().flatten() {
427			if !self.ancestors[at].contains(&revocation) {
428				continue;
429			}
430			match labels[revocation] {
431				Label::Counts => joins = false,
432				Label::Undecided => return None,
433				Label::SetAside => {}
434			}
435		}
436		Some(joins)
437	}
438
439	/// The person whose key `key` is at fact `at`: by the space's own counting listings
440	/// among the facts it builds on, and, in a space that follows groups, by the groups'
441	/// listings that it knows through its anchors and its own, joined where a key that is
442	/// not revoked is listed on two records. A key that a group revokes, by what it knows,
443	/// is nobody's.
444	fn who(&self, key: &KeyBytes, at: usize, labels: &[Label]) -> Who {
445		if let Some(found) = self.people.borrow().get(&at) {
446			return found.clone();
447		}
448		let who = self.find_who(key, at, labels);
449		if !matches!(who, Who::Undecided) {
450			self.people.borrow_mut().insert(at, who.clone());
451		}
452		who
453	}
454
455	/// The person whose key `key` is at fact `at`, as [`Members::who`] finds it, without
456	/// what it found before. Only the owners of the key and of those that a group lists
457	/// matter, as a key that the space alone lists is on one record, and joins none.
458	fn find_who(&self, key: &KeyBytes, at: usize, labels: &[Label]) -> Who {
459		let Some(through) = self.through_groups(at) else {
460			return match self.owner(key, at, labels) {
461				Owner::Undecided => Who::Undecided,
462				Owner::Nobody => Who::Nobody,
463				Owner::Member(member) => Who::Person(Person {
464					member,
465					direct: BTreeSet::from([member]),
466					keys: BTreeSet::from([*key]),
467					members: Vec::new(),
468				}),
469			};
470		};
471		let knowledge = &through.knowledge;
472		if self
473			.reach
474			.is_some_and(|reach| reach.revoked(key, knowledge))
475		{
476			return Who::Nobody;
477		}
478		let mut direct = BTreeMap::new();
479		let mut joining = BTreeMap::new();
480		for listed in std::iter::once(key).chain(through.routes.listed.keys()) {
481			match self.owner(listed, at, labels) {
482				Owner::Undecided => return Who::Undecided,
483				Owner::Nobody => {}
484				Owner::Member(member) => {
485					direct.insert(*listed, member);
486				}
487			}
488			match self.joins(listed, at, labels, knowledge) {
489				None => return Who::Undecided,
490				Some(joins) => {
491					joining.insert(*listed, joins);
492				}
493			}
494		}
495		let joins = |listed: &KeyBytes| joining.get(listed).copied().unwrap_or(false);
496		match person_of(key, &direct, &through.routes.listed, joins) {
497			Some(person) => Who::Person(person),
498			None => Who::Nobody,
499		}
500	}
501
502	/// Whether a group in the space lists fact `at`'s author's key, by what it knows of the
503	/// groups.
504	pub(super) fn listed_through_groups(&self, at: usize) -> bool {
505		self.through_groups(at)
506			.is_some_and(|through| through.routes.listed.contains_key(&self.facts[at].author))
507	}
508
509	/// Whether fact `at` is the change `change` or builds on it.
510	fn builds_on_or_is(&self, at: usize, change: &ChangeId) -> bool {
511		self.facts[at].id == *change
512			|| self.ancestors[at]
513				.iter()
514				.any(|&earlier| self.facts[earlier].id == *change)
515	}
516
517	/// A person's records at fact `at`: those of each of their records in the space, and
518	/// the records there of their keys' replicas and devices. `None` while a listing they
519	/// depend on is undecided.
520	fn records_of_person(
521		&self,
522		person: &Person,
523		at: usize,
524		labels: &[Label],
525	) -> Option<BTreeSet<EntityId>> {
526		let mut records = BTreeSet::from([person.member]);
527		for &record in &person.direct {
528			records.extend(self.records(record, at, labels)?);
529		}
530		records.extend(key_records(self.space, &person.keys));
531		Some(records)
532	}
533
534	/// The roles of a person's paths at fact `at`, by the facts it builds on: of each of
535	/// their records in the space, and through each group in the space from which a route
536	/// reaches one of their members, the lower of the group's role in the space and the best
537	/// that those routes give, never an admin's. `None` while one is undecided.
538	fn path_roles(&self, person: &Person, at: usize, labels: &[Label]) -> Option<Vec<Role>> {
539		let mut roles = Vec::new();
540		for &record in &person.direct {
541			roles.push(self.record_role(record, at, labels)?);
542		}
543		if person.members.is_empty() {
544			return Some(roles);
545		}
546		// A person kept out of the space has no path through a group.
547		let kept_out = self.kept_out(person, at, labels)?;
548		let through = self.through_groups(at)?;
549		let routes = &through.routes;
550		for (top, best) in routes.tops.iter().zip(routes.best(&person.members, &[])) {
551			let Some(best) = best else {
552				continue;
553			};
554			let group = self.role(top.record, at, labels)?;
555			roles.push(if kept_out {
556				Role::None
557			} else {
558				group.min(best).min(Role::Editor)
559			});
560		}
561		Some(roles)
562	}
563
564	/// A direct record's role at fact `at`: what the counting facts it builds on give it, or
565	/// an admin's by a claim that gives it the role there, while the new admin can only undo
566	/// only for what undoes. `None` while one is undecided.
567	fn record_role(&self, record: EntityId, at: usize, labels: &[Label]) -> Option<Role> {
568		let role = self.role(record, at, labels)?;
569		// A claim gives nothing to a member lowered below an editor, or removed, since.
570		let Some(claims) = self.claims.get(&record) else {
571			return Some(role);
572		};
573		if role == Role::Admin || role < Role::Editor {
574			return Some(role);
575		}
576		let mut deciding = Deciding {
577			facts: self.facts,
578			ancestors: self.ancestors,
579			counts: |fact: usize| match labels[fact] {
580				Label::Counts => Some(true),
581				Label::SetAside => Some(false),
582				Label::Undecided => None,
583			},
584			person_of: |fact: usize| match self.who(&self.facts[fact].author, fact, labels) {
585				Who::Undecided => None,
586				Who::Nobody => Some(None),
587				Who::Person(person) => Some(Some(person_records(&person))),
588			},
589		};
590		let order = self.facts[at].order.0;
591		for &claim in claims {
592			if !self.ancestors[at].contains(&claim) || !(deciding.counts)(claim)? {
593				continue;
594			}
595			let Some(claimant) = (deciding.person_of)(claim)? else {
596				continue;
597			};
598			// The earliest change that `at` builds on and that shows another member saw it.
599			let known = self.ancestors[at].iter().copied();
600			let Some(&seer) = deciding.seers(claim, &claimant, known, 1)?.first() else {
601				continue;
602			};
603			let Some(undoing_only) = given_at(self.facts[seer].order.0, order) else {
604				continue;
605			};
606			// A withdrawal, or a rejection in time, voids it, by when it was first seen of all.
607			let all = (claim + 1)..self.facts.len();
608			let first = deciding
609				.seers(claim, &claimant, all, 1)?
610				.first()
611				.map(|&first| self.facts[first].order.0);
612			if deciding.void(claim, first)? {
613				continue;
614			}
615			if !undoing_only || !self.undoes_not(at, labels)? {
616				return Some(Role::Admin);
617			}
618		}
619		Some(role)
620	}
621
622	/// Whether fact `at` does what a new admin by a claim cannot while they can only undo:
623	/// an acceptance, a rejection of a claim, making an admin, or lowering a member whom the
624	/// facts it builds on make an admin. `None` while one is undecided.
625	fn undoes_not(&self, at: usize, labels: &[Label]) -> Option<bool> {
626		let fact = &self.facts[at];
627		if !fact.accepts.is_empty() || !fact.rejects.is_empty() {
628			return Some(true);
629		}
630		for &(member, role) in &fact.roles {
631			if role == Role::Admin || self.role(member, at, labels)? == Role::Admin {
632				return Some(true);
633			}
634		}
635		Some(false)
636	}
637
638	/// The records in the space, derived from the space and each key of a person, that keep
639	/// them out; none where no fact keeps anyone out.
640	fn keep_out_records(&self, person: &Person) -> BTreeSet<EntityId> {
641		if !self.facts.iter().any(|fact| !fact.keeps_out.is_empty()) {
642			return BTreeSet::new();
643		}
644		keep_out_records(self.space, &person.keys)
645	}
646
647	/// Whether a person is kept out of the space through groups at fact `at`: whether, for
648	/// the record of one of their keys, of the counting facts that `at` builds on and that say
649	/// whether it keeps them out, one of those that no other of them builds on does. `None`
650	/// while one is undecided.
651	fn kept_out(&self, person: &Person, at: usize, labels: &[Label]) -> Option<bool> {
652		let records = self.keep_out_records(person);
653		if records.is_empty() {
654			return Some(false);
655		}
656		let mut sayers: BTreeMap<EntityId, Vec<(usize, bool)>> = BTreeMap::new();
657		for &earlier in &self.ancestors[at] {
658			for (record, keeps) in &self.facts[earlier].keeps_out {
659				if !records.contains(record) {
660					continue;
661				}
662				match labels[earlier] {
663					Label::Undecided => return None,
664					Label::SetAside => {}
665					Label::Counts => sayers.entry(*record).or_default().push((earlier, *keeps)),
666				}
667			}
668		}
669		Some(sayers.values().any(|said| {
670			said.iter().any(|(sayer, keeps)| {
671				*keeps
672					&& !said
673						.iter()
674						.any(|(other, _)| self.ancestors[*other].contains(sayer))
675			})
676		}))
677	}
678
679	/// The facts that keep a person out and that fact `at` neither builds on nor is built on
680	/// by: they set aside what `at` did through a group, as a removal does.
681	fn keeping_out(&self, person: &Person, at: usize) -> Vec<usize> {
682		let records = self.keep_out_records(person);
683		(0..self.facts.len())
684			.filter(|&other| {
685				other != at
686					&& !self.ancestors[at].contains(&other)
687					&& !self.ancestors[other].contains(&at)
688					&& self.facts[other]
689						.keeps_out
690						.iter()
691						.any(|(record, keeps)| *keeps && records.contains(record))
692			})
693			.collect()
694	}
695
696	/// Whether a counting fact that `at` builds on, by an admin, made `record` for a member
697	/// through a group whose keys include one it names: the person then lists their replicas
698	/// on it. `None` while one that would is undecided.
699	fn made_for(
700		&self,
701		record: EntityId,
702		person: &Person,
703		at: usize,
704		labels: &[Label],
705	) -> Option<bool> {
706		let mut undecided = false;
707		for &earlier in &self.ancestors[at] {
708			let fact = &self.facts[earlier];
709			if !fact
710				.made_for
711				.iter()
712				.any(|(made, key)| *made == record && person.keys.contains(key))
713			{
714				continue;
715			}
716			match labels[earlier] {
717				Label::Counts => return Some(true),
718				Label::Undecided => undecided = true,
719				Label::SetAside => {}
720			}
721		}
722		(!undecided).then_some(false)
723	}
724
725	/// The member that a key belongs to at fact `at`: the owner that the latest fact it
726	/// builds on that lists the key names, if that one counts; or, for a key that no such
727	/// fact lists and that lists itself at `at` by a recovery code, the owner that the code
728	/// lists it for, whose role it has at once, as the rules count that listing apart.
729	fn owner(&self, key: &KeyBytes, at: usize, labels: &[Label]) -> Owner {
730		let latest = self.ancestors[at]
731			.iter()
732			.rev()
733			.find(|&&listing| labels[listing] != Label::SetAside && self.facts[listing].lists(key));
734		match latest {
735			None => {
736				let fact = &self.facts[at];
737				match fact.by_code {
738					Some(by_code) if fact.author == *key => Owner::Member(by_code.owner),
739					_ => Owner::Nobody,
740				}
741			}
742			Some(&listing) if labels[listing] == Label::Counts => self.facts[listing]
743				.owner_of(key)
744				.map_or(Owner::Nobody, Owner::Member),
745			Some(_) => Owner::Undecided,
746		}
747	}
748
749	/// The records of a member at fact `at`: the member's own, and those of the replicas,
750	/// and their devices, that the counting facts it builds on, and `at` itself, list for the
751	/// member. `None` while one of those listings is undecided.
752	fn records(&self, member: EntityId, at: usize, labels: &[Label]) -> Option<BTreeSet<EntityId>> {
753		let mut records = BTreeSet::from([member]);
754		for &listing in self.ancestors[at].iter().chain([&at]) {
755			let fact = &self.facts[listing];
756			for (index, (record, _)) in fact.lists.iter().enumerate() {
757				if fact.owners[index] != Some(member) {
758					continue;
759				}
760				match labels[listing] {
761					Label::SetAside if listing != at => {}
762					Label::Undecided if listing != at => return None,
763					_ => {
764						records.insert(*record);
765						records.insert(fact.devices[index]);
766					}
767				}
768			}
769		}
770		Some(records)
771	}
772
773	/// The role that the counting facts that fact `at` builds on give a member: of those
774	/// that no other of them builds on, the lowest. `None` while one is undecided.
775	fn role(&self, member: EntityId, at: usize, labels: &[Label]) -> Option<Role> {
776		let mut givers = Vec::new();
777		for &giver in &self.ancestors[at] {
778			let Some(role) = self.facts[giver].role_of(member) else {
779				continue;
780			};
781			match labels[giver] {
782				Label::Undecided => return None,
783				Label::SetAside => {}
784				Label::Counts => givers.push((giver, role)),
785			}
786		}
787		Some(self.lowest_of_latest(&givers))
788	}
789
790	/// Of facts that give a member roles, the lowest role of those that no other builds on;
791	/// none if there are none.
792	fn lowest_of_latest(&self, givers: &[(usize, Role)]) -> Role {
793		givers
794			.iter()
795			.filter(|(giver, _)| {
796				!givers
797					.iter()
798					.any(|(other, _)| self.ancestors[*other].contains(giver))
799			})
800			.map(|(_, role)| *role)
801			.min()
802			.unwrap_or(Role::None)
803	}
804
805	/// Whether the space allows AI agents at fact `at`: whether, of the counting facts that it
806	/// builds on that say so, and `at` itself, those that no other of them builds on all
807	/// allow them; a space allows none until an admin says it does. `None` while one is
808	/// undecided.
809	fn allows_ai_agents(&self, at: usize, labels: &[Label]) -> Option<bool> {
810		let mut sayers = Vec::new();
811		for &earlier in &self.ancestors[at] {
812			let Some(allows) = self.facts[earlier].allows_ai else {
813				continue;
814			};
815			match labels[earlier] {
816				Label::Undecided => return None,
817				Label::SetAside => {}
818				Label::Counts => sayers.push((earlier, allows)),
819			}
820		}
821		if let Some(allows) = self.facts[at].allows_ai {
822			sayers.push((at, allows));
823		}
824		let latest: Vec<bool> = sayers
825			.iter()
826			.filter(|(sayer, _)| {
827				!sayers.iter().any(|(other, _)| {
828					other != sayer && (*other == at || self.ancestors[*other].contains(sayer))
829				})
830			})
831			.map(|(_, allows)| *allows)
832			.collect();
833		Some(!latest.is_empty() && latest.iter().all(|allows| *allows))
834	}
835
836	/// Whether the device whose key is `key` holds the space at fact `at`: whether, of its
837	/// choices that the counting facts it builds on state, the one with the highest number, a
838	/// drop winning a tie, holds it, or none does. `None` while a fact that states one is
839	/// undecided.
840	fn holds_at(&self, key: &KeyBytes, at: usize, labels: &[Label]) -> Option<bool> {
841		if !self.chosen.contains(key) {
842			return Some(true);
843		}
844		let mut choices = Vec::new();
845		for &earlier in &self.ancestors[at] {
846			let mut of_key = self.facts[earlier]
847				.choices()
848				.iter()
849				.filter(|(chooser, ..)| chooser == key)
850				.peekable();
851			if of_key.peek().is_none() {
852				continue;
853			}
854			match labels[earlier] {
855				Label::Undecided => return None,
856				Label::SetAside => {}
857				Label::Counts => {
858					choices.extend(of_key.map(|(_, number, holds)| (*number, *holds)));
859				}
860			}
861		}
862		Some(standing(choices).is_none_or(|(_, holds)| holds))
863	}
864
865	/// Whether no fact that fact `at` builds on, counting or not, makes `member` a member's
866	/// record, by its user ID or a role.
867	fn is_new(&self, member: EntityId, at: usize) -> bool {
868		!self.ancestors[at].iter().any(|&earlier| {
869			let fact = &self.facts[earlier];
870			fact.users.contains(&member)
871				|| fact.role_of(member).is_some()
872				|| fact.makes_group_record(member)
873		})
874	}
875
876	/// Whether a record is a group's, by fact `at` or a fact it builds on.
877	fn is_group_record(&self, record: EntityId, at: usize) -> bool {
878		self.facts[at].makes_group_record(record)
879			|| self.ancestors[at]
880				.iter()
881				.any(|&earlier| self.facts[earlier].makes_group_record(record))
882	}
883
884	/// What fact `at` needs of its author's role, who is `person`.
885	fn needs(&self, at: usize, person: &Person, labels: &[Label]) -> Need {
886		let Some(records) = self.records_of_person(person, at, labels) else {
887			return Need::Undecided;
888		};
889		let fact = &self.facts[at];
890		let mut need = Role::Viewer;
891		// An anchor that names a change that the replica holds of no group it follows cannot
892		// count yet.
893		if self
894			.reach
895			.is_some_and(|reach| reach.is_incomplete(&fact.id))
896		{
897			return Need::Never;
898		}
899		// Only a member's own replicas list its replicas, but for the one that an admin's
900		// invitation lists, on the record of the member it makes, which no change it builds on
901		// names as a member's.
902		for owner in &fact.owners {
903			match owner {
904				Some(owner) if person.direct.contains(owner) => {}
905				Some(owner) if fact.users.contains(owner) && self.is_new(*owner, at) => {
906					need = Role::Admin;
907				}
908				// A member through a group lists their replicas on the record that an admin
909				// made for them, which makes them a direct member.
910				Some(owner) => match self.made_for(*owner, person, at, labels) {
911					None => return Need::Undecided,
912					Some(true) => {}
913					Some(false) => return Need::Never,
914				},
915				None => return Need::Never,
916			}
917		}
918		// Only a person's own replicas revoke their replicas, whichever path lists them.
919		for key in &fact.revokes {
920			if person.keys.contains(key) {
921				continue;
922			}
923			match self.owner(key, at, labels) {
924				Owner::Undecided => return Need::Undecided,
925				Owner::Member(owner) if person.direct.contains(&owner) => {}
926				_ => return Need::Never,
927			}
928		}
929		// A group is never an admin of a space.
930		for (given, role) in &fact.roles {
931			if *role == Role::Admin && self.is_group_record(*given, at) {
932				return Need::Never;
933			}
934		}
935		// An AI agent's replica is listed only where the space allows AI agents.
936		if !fact.marks.is_empty() {
937			match self.allows_ai_agents(at, labels) {
938				None => return Need::Undecided,
939				Some(false) => return Need::Never,
940				Some(true) => {}
941			}
942		}
943		// Every member may leave; only admins give roles.
944		for (given, role) in &fact.roles {
945			if !(person.direct.contains(given) && *role == Role::None) {
946				need = Role::Admin;
947			}
948		}
949		for touch in &fact.touches {
950			match touch {
951				Touch::Record(entity) | Touch::Retraction(Some(entity))
952					if records.contains(entity) => {}
953				Touch::Gift => {}
954				// Only a direct member claims, on their own record, as an editor.
955				Touch::Claim(entity) if person.direct.contains(entity) => {
956					need = need.max(Role::Editor);
957				}
958				// A device's choice is carried only by its member's replicas.
959				Touch::Choice(entity) if records.contains(entity) => {}
960				Touch::Claim(_) | Touch::Choice(_) => return Need::Never,
961				// A code is its member's own: nobody states or revokes another member's, an
962				// admin included. A member through a group alone has their record in the
963				// group, which the code's record in the space is derived from.
964				Touch::Code(record, key) => {
965					let derived = |member: &EntityId| {
966						crate::recovery_record(self.space, *member, key) == *record
967					};
968					let own = person.direct.iter().any(derived)
969						|| person.members.iter().any(|member| derived(&member.member));
970					if !own {
971						return Need::Never;
972					}
973				}
974				_ => need = Role::Admin,
975			}
976		}
977		Need::At(need)
978	}
979
980	/// Whether fact `at`'s author's role, by the facts it builds on, allows it. The first
981	/// change of the space is decided by its listing alone.
982	pub(super) fn verdict(&self, at: usize, labels: &[Label]) -> Verdict {
983		let fact = &self.facts[at];
984		let person = match self.who(&fact.author, at, labels) {
985			Who::Undecided => return Verdict::Undecided,
986			Who::Nobody => return Verdict::Refused,
987			Who::Person(person) => person,
988		};
989		// A device that dropped the space, by the facts it builds on, governs nothing there.
990		match self.holds_at(&fact.author, at, labels) {
991			None => return Verdict::Undecided,
992			Some(false) => return Verdict::Refused,
993			Some(true) => {}
994		}
995		let need = match self.needs(at, &person, labels) {
996			Need::Undecided => return Verdict::Undecided,
997			Need::Never => return Verdict::Refused,
998			Need::At(need) => need,
999		};
1000		match self.path_roles(&person, at, labels) {
1001			None => Verdict::Undecided,
1002			Some(roles) if roles.iter().any(|role| need <= *role) => Verdict::Allowed {
1003				member: person.member,
1004				need,
1005			},
1006			Some(_) => Verdict::Refused,
1007		}
1008	}
1009
1010	/// Whether what would lower fact `at`'s author's role without its knowing, which its
1011	/// verdict allowed, leaves it as it was: whether some path that allowed it is lowered
1012	/// neither by a counting fact that gives a lower role and that `at` neither builds on nor
1013	/// is built on by, nor by a group change that it does not know and whose first anchors do
1014	/// not build on it. Of two admins who lower each other so, the one who became an admin
1015	/// later sets nothing aside.
1016	pub(super) fn kept(&self, at: usize, labels: &[Label]) -> Kept {
1017		let Verdict::Allowed { need, .. } = self.verdict(at, labels) else {
1018			return Kept::Yes;
1019		};
1020		let fact = &self.facts[at];
1021		let Who::Person(person) = self.who(&fact.author, at, labels) else {
1022			return Kept::Undecided;
1023		};
1024		let tri = |lowering: &[usize]| {
1025			if lowering.iter().any(|&other| labels[other] == Label::Counts) {
1026				Kept::No
1027			} else if lowering
1028				.iter()
1029				.all(|&other| labels[other] == Label::SetAside)
1030			{
1031				Kept::Yes
1032			} else {
1033				Kept::Undecided
1034			}
1035		};
1036		let mut paths: Vec<Kept> = Vec::new();
1037		for &record in &person.direct {
1038			if self
1039				.record_role(record, at, labels)
1040				.is_some_and(|role| need <= role)
1041			{
1042				paths.push(tri(&self.lowering_of(at, record, need, labels, true)));
1043			}
1044		}
1045		let (lowerings, through) = match (self.reach, self.through_groups(at)) {
1046			(Some(reach), Some(through)) => (
1047				reach.lowerings(
1048					&fact.author,
1049					&through.routes,
1050					&person.members,
1051					&through.knowledge,
1052				),
1053				Some(through),
1054			),
1055			_ => (Vec::new(), None),
1056		};
1057		let kept_by_first_anchors = |lowering: &Lowering| {
1058			self.reach.is_none_or(|reach| {
1059				reach.keeps(lowering, |anchor| {
1060					self.index
1061						.get(anchor)
1062						.is_some_and(|&anchor| self.ancestors[anchor].contains(&at))
1063				})
1064			})
1065		};
1066		let unkept: Vec<&Lowering> = lowerings
1067			.iter()
1068			.filter(|lowering| !kept_by_first_anchors(lowering))
1069			.collect();
1070		let keeping_out = self.keeping_out(&person, at);
1071		// A person kept out by what the fact builds on has no path through a group.
1072		let through = match self.kept_out(&person, at, labels) {
1073			Some(false) => through.filter(|_| !person.members.is_empty()),
1074			Some(true) => None,
1075			None => {
1076				paths.push(Kept::Undecided);
1077				None
1078			}
1079		};
1080		if let Some(through) = through {
1081			let routes = &through.routes;
1082			let by = routes.best(&person.members, &[]);
1083			let lowered = routes.best(&person.members, &unkept);
1084			for (top, (by, lowered)) in routes.tops.iter().zip(by.into_iter().zip(lowered)) {
1085				let Some(by) = by else {
1086					continue;
1087				};
1088				let Some(group) = self.role(top.record, at, labels) else {
1089					paths.push(Kept::Undecided);
1090					continue;
1091				};
1092				if group.min(by).min(Role::Editor) < need {
1093					continue;
1094				}
1095				// A route that allowed it and that nothing in the groups lowers below what it
1096				// needs keeps it, unless the space lowers the group's record.
1097				paths.push(if lowered.is_none_or(|lowered| lowered < need) {
1098					Kept::No
1099				} else {
1100					let mut lowering = self.lowering_of(at, top.record, need, labels, false);
1101					lowering.extend(&keeping_out);
1102					tri(&lowering)
1103				});
1104			}
1105		}
1106		let revoked = unkept.iter().any(|lowering| lowering.at.is_none());
1107		if revoked || paths.iter().all(|kept| *kept == Kept::No) {
1108			Kept::No
1109		} else if paths.contains(&Kept::Yes) {
1110			Kept::Yes
1111		} else {
1112			Kept::Undecided
1113		}
1114	}
1115
1116	/// The facts that would set fact `at` aside by lowering a record's role, which its author's
1117	/// path through it needs, below `need`: those that give the record a lower role, and that
1118	/// `at` neither builds on nor is built on by. With `senior`, of two admins who lower each
1119	/// other so, the one who became an admin later sets nothing aside.
1120	fn lowering_of(
1121		&self,
1122		at: usize,
1123		member: EntityId,
1124		need: Role,
1125		labels: &[Label],
1126		senior: bool,
1127	) -> Vec<usize> {
1128		let mut lowering = Vec::new();
1129		for (other, fact) in self.facts.iter().enumerate() {
1130			if other == at
1131				|| self.ancestors[at].contains(&other)
1132				|| self.ancestors[other].contains(&at)
1133				|| fact.role_of(member).is_none_or(|role| role >= need)
1134			{
1135				continue;
1136			}
1137			// Of two that lower each other's authors, the junior admin's sets nothing aside.
1138			if senior
1139				&& let Verdict::Allowed {
1140					member: theirs,
1141					need: they_need,
1142				} = self.verdict(other, labels)
1143				&& self.facts[at]
1144					.role_of(theirs)
1145					.is_some_and(|role| role < they_need)
1146				&& self.seniority(theirs) > self.seniority(member)
1147			{
1148				continue;
1149			}
1150			lowering.push(other);
1151		}
1152		lowering
1153	}
1154
1155	/// Of the counting facts, the first in their order that would leave the space with
1156	/// members and no direct admin, by the facts it builds on and itself; or else, if all
1157	/// of them together leave none, the latest that took the role from an admin. `None` if
1158	/// none does.
1159	pub(super) fn leaving_no_admin(&self, labels: &[Label]) -> Option<usize> {
1160		let counting = |index: &usize| labels[*index] == Label::Counts;
1161		for at in (0..self.facts.len()).filter(counting) {
1162			let fact = &self.facts[at];
1163			if fact.roles.is_empty() {
1164				continue;
1165			}
1166			let mut roles = self.roles_among(self.ancestors[at].iter().copied().filter(counting));
1167			for (member, _) in &fact.roles {
1168				if let Some(role) = fact.role_of(*member) {
1169					roles.insert(*member, role);
1170				}
1171			}
1172			if without_admin(&roles) {
1173				return Some(at);
1174			}
1175		}
1176		if !without_admin(&self.roles_among((0..self.facts.len()).filter(counting))) {
1177			return None;
1178		}
1179		(0..self.facts.len()).rev().filter(counting).find(|&at| {
1180			self.facts[at].roles.iter().any(|(member, role)| {
1181				*role < Role::Admin && self.role(*member, at, labels) == Some(Role::Admin)
1182			})
1183		})
1184	}
1185
1186	/// The role of each member that some of `facts` give one to, as [`Members::role`] reckons
1187	/// it among them.
1188	fn roles_among(&self, facts: impl Iterator<Item = usize>) -> BTreeMap<EntityId, Role> {
1189		let mut givers: BTreeMap<EntityId, Vec<(usize, Role)>> = BTreeMap::new();
1190		for giver in facts {
1191			for (member, _) in &self.facts[giver].roles {
1192				if let Some(role) = self.facts[giver].role_of(*member) {
1193					let of_member = givers.entry(*member).or_default();
1194					if !of_member.contains(&(giver, role)) {
1195						of_member.push((giver, role));
1196					}
1197				}
1198			}
1199		}
1200		givers
1201			.into_iter()
1202			.map(|(member, givers)| (member, self.lowest_of_latest(&givers)))
1203			.collect()
1204	}
1205}
1206
1207/// Whether roles leave a space with members but no admin.
1208fn without_admin(roles: &BTreeMap<EntityId, Role>) -> bool {
1209	roles.values().any(|role| *role != Role::None)
1210		&& !roles.values().any(|role| *role == Role::Admin)
1211}
1212
1213/// What the counting governing changes of a space with members say of members, keys and
1214/// roles, with which governing changes each builds on: what deciding an ordinary change by
1215/// its author's role needs.
1216#[derive(Clone, Debug, Default, PartialEq, Eq)]
1217pub struct View {
1218	/// The signed listings of counting changes, in their order: the change, the key, its
1219	/// owner, its record and its device's record.
1220	listings: Vec<(ChangeId, KeyBytes, EntityId, EntityId, EntityId)>,
1221	/// The roles that counting changes give, in their order: the change, the member and
1222	/// the role.
1223	roles: Vec<(ChangeId, EntityId, Role)>,
1224	/// For each governing change that the replica can read, those it builds on.
1225	ancestors: BTreeMap<ChangeId, BTreeSet<ChangeId>>,
1226	/// For each governing change that the replica can read, counting or not, the records
1227	/// of members and of replicas and their devices that it names: by user IDs, roles and
1228	/// listings.
1229	records: BTreeMap<ChangeId, BTreeSet<EntityId>>,
1230	/// Whether counting changes say that the space allows AI agents, in their order.
1231	ai_allowed: Vec<(ChangeId, bool)>,
1232	/// For each governing change that the replica can read, counting or not, the keys it
1233	/// lists.
1234	listed_keys: BTreeMap<ChangeId, Vec<KeyBytes>>,
1235	/// The keys that counting changes revoke, with the changes, in their order.
1236	revocations: Vec<(ChangeId, KeyBytes)>,
1237	/// What counting changes say of keeping people out, in their order: the change, the
1238	/// record derived from the space and a key, and whether it keeps the key's person out.
1239	keep_outs: Vec<(ChangeId, EntityId, bool)>,
1240	/// What each counting claim to the admin role gives.
1241	claims: Vec<ClaimEffect>,
1242	/// The devices' choices of the space that counting changes state, in their order: the
1243	/// change, the key, the number and whether it holds the space.
1244	choices: Vec<(ChangeId, KeyBytes, u64, bool)>,
1245	/// The space, once known.
1246	space: Option<SpaceId>,
1247	/// What the groups that the space follows give in it, if it follows any.
1248	reach: Option<Reach>,
1249}
1250
1251/// A key's person at a change, with their records and roles: what deciding an ordinary
1252/// change by its author's role needs.
1253#[derive(Clone, Debug, PartialEq, Eq)]
1254pub struct Standing {
1255	/// Their member: the space's own record that lists their key, if one does; or else the
1256	/// smallest of their direct records, or else of their records in groups.
1257	pub member: EntityId,
1258	/// Their records in the space itself.
1259	pub direct: BTreeSet<EntityId>,
1260	/// The keys on their records that groups list too, and the key asked about.
1261	pub keys: BTreeSet<KeyBytes>,
1262	/// Their records: those of their records in the space, and the records there of their
1263	/// keys' replicas and devices.
1264	pub records: BTreeSet<EntityId>,
1265	/// What the change knows of the groups.
1266	pub knowledge: Knowledge,
1267	/// Their role by what the change builds on: the highest over every path.
1268	pub by_ancestors: Role,
1269	/// That, lowered by what lowers each path without the change's knowing.
1270	pub lowered: Role,
1271}
1272
1273impl Standing {
1274	/// Whether it is the same person's as `other`: the same member, or records or keys in
1275	/// common, which join records into one person.
1276	#[must_use]
1277	pub fn is_same_person(&self, other: &Self) -> bool {
1278		self.member == other.member
1279			|| !self.direct.is_disjoint(&other.direct)
1280			|| !self.keys.is_disjoint(&other.keys)
1281	}
1282}
1283
1284impl View {
1285	/// What the counting ones of `facts` say, where each builds on those `ancestors` names.
1286	pub(super) fn of(
1287		facts: &[Fact],
1288		ancestors: &[BTreeSet<usize>],
1289		counting: &BTreeSet<ChangeId>,
1290	) -> Self {
1291		let mut view = Self {
1292			ancestors: facts
1293				.iter()
1294				.zip(ancestors)
1295				.map(|(fact, of)| (fact.id, of.iter().map(|&index| facts[index].id).collect()))
1296				.collect(),
1297			..Self::default()
1298		};
1299		for fact in facts {
1300			let records = view.records.entry(fact.id).or_default();
1301			records.extend(fact.lists.iter().map(|(record, _)| *record));
1302			records.extend(fact.devices.iter().copied());
1303			records.extend(fact.roles.iter().map(|(member, _)| *member));
1304			records.extend(fact.users.iter().copied());
1305			records.extend(fact.group_records.iter().map(|(record, ..)| *record));
1306			view.listed_keys
1307				.insert(fact.id, fact.lists.iter().map(|(_, key)| *key).collect());
1308		}
1309		for fact in facts.iter().filter(|fact| counting.contains(&fact.id)) {
1310			for (index, (record, key)) in fact.lists.iter().enumerate() {
1311				if let Some(owner) = fact.owners[index] {
1312					view.listings
1313						.push((fact.id, *key, owner, *record, fact.devices[index]));
1314				}
1315			}
1316			for (member, role) in &fact.roles {
1317				view.roles.push((fact.id, *member, *role));
1318			}
1319			if let Some(allows) = fact.allows_ai {
1320				view.ai_allowed.push((fact.id, allows));
1321			}
1322			view.revocations
1323				.extend(fact.revokes.iter().map(|key| (fact.id, *key)));
1324			view.keep_outs.extend(
1325				fact.keeps_out
1326					.iter()
1327					.map(|(record, keeps)| (fact.id, *record, *keeps)),
1328			);
1329			view.choices.extend(
1330				fact.choices()
1331					.iter()
1332					.map(|(key, number, holds)| (fact.id, *key, *number, *holds)),
1333			);
1334		}
1335		view
1336	}
1337
1338	/// The same, with what each counting claim to the admin role among `facts` gives, once
1339	/// the view knows the groups the space follows, as whose a change is depends on them.
1340	#[must_use]
1341	pub fn with_claims(
1342		mut self,
1343		facts: &[Fact],
1344		ancestors: &[BTreeSet<usize>],
1345		counting: &BTreeSet<ChangeId>,
1346	) -> Self {
1347		if facts.iter().all(|fact| fact.claims.is_empty()) {
1348			return self;
1349		}
1350		let empty = BTreeSet::new();
1351		let claims = Deciding {
1352			facts,
1353			ancestors,
1354			counts: |fact: usize| Some(counting.contains(&facts[fact].id)),
1355			person_of: |fact: usize| {
1356				let known = self.ancestors.get(&facts[fact].id).unwrap_or(&empty);
1357				Some(
1358					self.standing(&facts[fact].author, known, NOW, |_| true)
1359						.map(|standing| {
1360							standing
1361								.direct
1362								.iter()
1363								.copied()
1364								.chain([standing.member])
1365								.collect()
1366						}),
1367				)
1368			},
1369		}
1370		.effects()
1371		.unwrap_or_default();
1372		self.claims = claims;
1373		self
1374	}
1375
1376	/// What each counting claim to the admin role gives.
1377	#[must_use]
1378	pub fn claims(&self) -> &[ClaimEffect] {
1379		&self.claims
1380	}
1381
1382	/// Whether a claim makes a direct record an admin's at a change timestamped `at` that
1383	/// builds on the governing changes `known`: `Some(true)` while the new admin can only
1384	/// undo.
1385	fn claim_gives(
1386		&self,
1387		record: EntityId,
1388		known: &BTreeSet<ChangeId>,
1389		at: Timestamp,
1390	) -> Option<bool> {
1391		self.claims
1392			.iter()
1393			.filter(|effect| effect.claimant == record && known.contains(&effect.claim))
1394			.filter_map(|effect| effect.gives_at(at, |change| known.contains(change)))
1395			.min()
1396	}
1397
1398	/// The counting changes among `among` that keep out the person whose keys are `keys`:
1399	/// for the record of each key, of the changes that say whether it keeps them out, those
1400	/// that no other of them builds on and that keep them out.
1401	fn keeping_out_among(
1402		&self,
1403		keys: &BTreeSet<KeyBytes>,
1404		mut among: impl FnMut(&ChangeId) -> bool,
1405	) -> Vec<ChangeId> {
1406		let Some(space) = self.space.filter(|_| !self.keep_outs.is_empty()) else {
1407			return Vec::new();
1408		};
1409		let records = keep_out_records(space, keys);
1410		let mut keeping = Vec::new();
1411		for record in &records {
1412			let said: Vec<(ChangeId, bool)> = self
1413				.keep_outs
1414				.iter()
1415				.filter(|(change, of, _)| of == record && among(change))
1416				.map(|(change, _, keeps)| (*change, *keeps))
1417				.collect();
1418			keeping.extend(
1419				self.latest(&said)
1420					.filter(|(_, keeps)| *keeps)
1421					.map(|(change, _)| change),
1422			);
1423		}
1424		keeping
1425	}
1426
1427	/// Whether a counting change that keeps out the person whose keys are `keys` is unknown to
1428	/// a change that builds on the governing changes `known`, and `concurrent` says does not
1429	/// build on it either: it sets aside what the change did through a group.
1430	fn kept_out_unknowing(
1431		&self,
1432		keys: &BTreeSet<KeyBytes>,
1433		known: &BTreeSet<ChangeId>,
1434		mut concurrent: impl FnMut(ChangeId) -> bool,
1435	) -> bool {
1436		let Some(space) = self.space.filter(|_| !self.keep_outs.is_empty()) else {
1437			return false;
1438		};
1439		let records = keep_out_records(space, keys);
1440		self.keep_outs.iter().any(|(change, record, keeps)| {
1441			*keeps && records.contains(record) && !known.contains(change) && concurrent(*change)
1442		})
1443	}
1444
1445	/// The counting changes that keep out a key's person, whom nothing else gives a role now:
1446	/// those that end the key, which a new key is written with only if its making builds on.
1447	#[must_use]
1448	pub fn keep_outs_ending(&self, key: &KeyBytes) -> Vec<ChangeId> {
1449		if self.keep_outs.is_empty() {
1450			return Vec::new();
1451		}
1452		let all: BTreeSet<ChangeId> = self.ancestors.keys().copied().collect();
1453		match self.standing(key, &all, NOW, |_| true) {
1454			Some(standing) if standing.by_ancestors == Role::None => {
1455				self.keeping_out_among(&standing.keys, |_| true)
1456			}
1457			_ => Vec::new(),
1458		}
1459	}
1460
1461	/// Whether a key's person has a role now, by every governing change, over any path.
1462	#[must_use]
1463	pub fn has_role_now(&self, key: &KeyBytes) -> bool {
1464		self.key_role_now(key) > Role::None
1465	}
1466
1467	/// The role that a key's changes have now, by every governing change: through its
1468	/// listing's member, directly or through groups; none for a key that no counting listing
1469	/// names.
1470	#[must_use]
1471	pub fn key_role_now(&self, key: &KeyBytes) -> Role {
1472		let all: BTreeSet<ChangeId> = self.ancestors.keys().copied().collect();
1473		self.standing(key, &all, NOW, |_| true)
1474			.map_or(Role::None, |standing| standing.by_ancestors)
1475	}
1476
1477	/// The same, for a space that follows groups, which `reach` says what they give in.
1478	#[must_use]
1479	pub fn with_reach(mut self, space: SpaceId, reach: Option<Reach>) -> Self {
1480		self.space = Some(space);
1481		self.reach = reach;
1482		self
1483	}
1484
1485	/// What the groups that the space follows give in it, if it follows any.
1486	#[must_use]
1487	pub fn reach(&self) -> Option<&Reach> {
1488		self.reach.as_ref()
1489	}
1490
1491	/// The keys that the counting listings among the governing changes `known` list, each
1492	/// with the owner its latest such listing names.
1493	#[must_use]
1494	pub fn listed_among(&self, known: &BTreeSet<ChangeId>) -> BTreeMap<KeyBytes, EntityId> {
1495		let mut listed = BTreeMap::new();
1496		for (change, key, owner, ..) in &self.listings {
1497			if known.contains(change) {
1498				listed.insert(*key, *owner);
1499			}
1500		}
1501		listed
1502	}
1503
1504	/// The keys that the governing changes `known` list, counting or not.
1505	pub fn listed_any_among<'s>(
1506		&'s self,
1507		known: &'s BTreeSet<ChangeId>,
1508	) -> impl Iterator<Item = KeyBytes> + 's {
1509		known
1510			.iter()
1511			.filter_map(|change| self.listed_keys.get(change))
1512			.flatten()
1513			.copied()
1514	}
1515
1516	/// The roles that counting changes give a member, with the changes.
1517	#[must_use]
1518	pub fn roles_of(&self, member: EntityId) -> Vec<(ChangeId, Role)> {
1519		self.roles
1520			.iter()
1521			.filter(|(_, given, _)| *given == member)
1522			.map(|(change, _, role)| (*change, *role))
1523			.collect()
1524	}
1525
1526	/// A direct record's role at a change that builds on the governing changes `known`, at
1527	/// `at`, as [`View::role`] gives it, or an admin's by a claim that gives it the role
1528	/// there, but for a purge while the new admin can only undo.
1529	fn direct_role(
1530		&self,
1531		record: EntityId,
1532		known: &BTreeSet<ChangeId>,
1533		at: Moment,
1534		concurrent: impl FnMut(ChangeId) -> bool,
1535	) -> (Role, Role) {
1536		let (by_ancestors, lowered) = self.role(record, known, concurrent);
1537		// A claim gives nothing to a member lowered below an editor, or removed, since; and
1538		// one lowered so without the change's knowing loses it there too.
1539		if by_ancestors < Role::Editor {
1540			return (by_ancestors, lowered);
1541		}
1542		let (timestamp, purges) = at;
1543		let claimed = match self.claim_gives(record, known, timestamp) {
1544			Some(false) => true,
1545			Some(true) => !purges,
1546			None => false,
1547		};
1548		if !claimed {
1549			return (by_ancestors, lowered);
1550		}
1551		let lowered = if lowered < Role::Editor {
1552			lowered
1553		} else {
1554			Role::Admin
1555		};
1556		(Role::Admin, lowered)
1557	}
1558
1559	/// A key's person at a change that builds on the governing changes `known`, with their
1560	/// records, their role by what it builds on, and that lowered by what it does not know:
1561	/// the counting changes that lower a path's record and that do not build on it either,
1562	/// and the group changes it does not know, unless one of their first anchors builds on
1563	/// it, where `had(change)` says whether a governing change builds on it. `None` if no
1564	/// counting listing among them names the key, or a group revokes it by what the change
1565	/// knows.
1566	pub fn standing(
1567		&self,
1568		key: &KeyBytes,
1569		known: &BTreeSet<ChangeId>,
1570		at: Moment,
1571		mut had: impl FnMut(ChangeId) -> bool,
1572	) -> Option<Standing> {
1573		let Some(reach) = &self.reach else {
1574			let member = self.owner(key, known)?;
1575			let (by_ancestors, lowered) = self.direct_role(member, known, at, |giver| !had(giver));
1576			return Some(Standing {
1577				member,
1578				direct: BTreeSet::from([member]),
1579				keys: BTreeSet::from([*key]),
1580				records: self.records_of(member, known),
1581				knowledge: Knowledge::new(),
1582				by_ancestors,
1583				lowered,
1584			});
1585		};
1586		let knowledge = reach.knowledge(known, None);
1587		if reach.revoked(key, &knowledge) {
1588			return None;
1589		}
1590		let groups = reach.groups_in(&knowledge, |change| known.contains(change));
1591		let routes = reach.routes(&knowledge, &groups);
1592		let through = &routes.listed;
1593		// Only the owners of the key and of those that a group lists matter, as a key that
1594		// the space alone lists is on one record, and joins none.
1595		let listed = self.listed_among(known);
1596		let direct: BTreeMap<KeyBytes, EntityId> = std::iter::once(key)
1597			.chain(through.keys())
1598			.filter_map(|key| listed.get(key).map(|owner| (*key, *owner)))
1599			.collect();
1600		let joins = |key: &KeyBytes| {
1601			!reach.revoked(key, &knowledge)
1602				&& !self
1603					.revocations
1604					.iter()
1605					.any(|(change, revoked)| revoked == key && known.contains(change))
1606		};
1607		let person = person_of(key, &direct, through, joins)?;
1608		let mut records = BTreeSet::from([person.member]);
1609		let mut by_ancestors = Role::None;
1610		let mut lowered = Role::None;
1611		for &record in &person.direct {
1612			records.extend(self.records_of(record, known));
1613			let (by, low) = self.direct_role(record, known, at, |giver| !had(giver));
1614			by_ancestors = by_ancestors.max(by);
1615			lowered = lowered.max(low);
1616		}
1617		let lowerings = reach.lowerings(key, &routes, &person.members, &knowledge);
1618		let unkept: Vec<&Lowering> = lowerings
1619			.iter()
1620			.filter(|lowering| !reach.keeps(lowering, |anchor| had(*anchor)))
1621			.collect();
1622		let revoked = unkept.iter().any(|lowering| lowering.at.is_none());
1623		// A person kept out has no path through a group; and one kept out unknowingly, none
1624		// for what they did then.
1625		let kept_out = !person.members.is_empty()
1626			&& !self
1627				.keeping_out_among(&person.keys, |change| known.contains(change))
1628				.is_empty();
1629		let kept_out_unknowing = !person.members.is_empty()
1630			&& self.kept_out_unknowing(&person.keys, known, |change| !had(change));
1631		if !kept_out && !person.members.is_empty() {
1632			let by = routes.best(&person.members, &[]);
1633			let low = routes.best(&person.members, &unkept);
1634			for (top, (by, low)) in routes.tops.iter().zip(by.into_iter().zip(low)) {
1635				let (Some(best), Some(in_group)) = (by, low) else {
1636					continue;
1637				};
1638				let (group_by, group_low) = self.role(top.record, known, |giver| !had(giver));
1639				let by = group_by.min(best).min(Role::Editor);
1640				let low = if kept_out_unknowing {
1641					Role::None
1642				} else {
1643					group_low.min(in_group).min(Role::Editor)
1644				};
1645				by_ancestors = by_ancestors.max(by);
1646				lowered = lowered.max(low);
1647			}
1648		}
1649		if revoked {
1650			lowered = Role::None;
1651		}
1652		if let Some(space) = self.space {
1653			records.extend(key_records(space, &person.keys));
1654		}
1655		Some(Standing {
1656			member: person.member,
1657			direct: person.direct,
1658			keys: person.keys,
1659			records,
1660			knowledge,
1661			by_ancestors,
1662			lowered,
1663		})
1664	}
1665
1666	/// Whether an entity is the record of a member, or of a listed replica or its device,
1667	/// by the governing changes `known`, counting or not, or, in a space that follows
1668	/// groups, of a replica that a group change it knows lists, or its device, by what it
1669	/// knows of the groups, `knowledge`.
1670	#[must_use]
1671	pub fn is_any_record(
1672		&self,
1673		entity: &EntityId,
1674		known: &BTreeSet<ChangeId>,
1675		knowledge: &Knowledge,
1676	) -> bool {
1677		self.is_record(entity, known)
1678			|| self
1679				.reach
1680				.as_ref()
1681				.is_some_and(|reach| reach.is_listed_record(entity, knowledge))
1682	}
1683
1684	/// The keys that groups list in the space now, by every group change that its counting
1685	/// anchors name: those of the groups in it whose records have a role there, but AI
1686	/// agents' keys and revoked ones. A replica syncs with them.
1687	#[must_use]
1688	pub fn listed_through_groups_now(&self) -> BTreeSet<KeyBytes> {
1689		self.group_members_now().into_keys().collect()
1690	}
1691
1692	/// The keys that the groups in the space, and those inside them, list now, each with its
1693	/// members there, by every group change that its counting anchors name, through the groups
1694	/// in it whose records have a role there.
1695	fn group_members_now(&self) -> BTreeMap<KeyBytes, Vec<GroupMember>> {
1696		let Some(reach) = &self.reach else {
1697			return BTreeMap::new();
1698		};
1699		let knowledge = reach.knowledge(reach.counting(), None);
1700		let groups: Vec<_> = reach
1701			.groups_in(&knowledge, |_| true)
1702			.into_iter()
1703			.filter(|(_, record, _)| self.role_now(*record).is_some_and(|role| role > Role::None))
1704			.collect();
1705		reach.routes(&knowledge, &groups).listed
1706	}
1707
1708	/// The members of the groups that the space follows, at any level, whose keys those
1709	/// groups give a role in the space now, each with the highest role that one of their keys
1710	/// has now, as [`View::key_role_now`] says, directly or through groups: so that what is
1711	/// given to a member through a group alone, such as their recovery codes, is given while
1712	/// they are in the space.
1713	#[must_use]
1714	pub fn group_member_roles_now(&self) -> BTreeMap<EntityId, Role> {
1715		let mut roles: BTreeMap<EntityId, Role> = BTreeMap::new();
1716		for (key, members) in self.group_members_now() {
1717			let role = self.key_role_now(&key);
1718			for member in members {
1719				let highest = roles.entry(member.member).or_insert(Role::None);
1720				*highest = (*highest).max(role);
1721			}
1722		}
1723		roles
1724	}
1725
1726	/// Each group that the space follows, at any level, that lists a key now, with the key's
1727	/// member there, but for AI agents' keys.
1728	#[must_use]
1729	pub fn group_members_of(&self, key: &KeyBytes) -> Vec<(SpaceId, EntityId)> {
1730		self.reach
1731			.as_ref()
1732			.map_or_default(|reach| reach.members_of_key(key))
1733	}
1734
1735	/// For a key that a group the space follows lists, at any level, the group and the key's
1736	/// member there: of the groups that routes reach now, the first, as a walk level by level
1737	/// reaches them, whose member has a role there, or else the first group's by ID that lists
1738	/// it. `None` for a key that no group lists.
1739	#[must_use]
1740	pub fn group_member_of(&self, key: &KeyBytes) -> Option<(SpaceId, EntityId)> {
1741		let reach = self.reach.as_ref()?;
1742		self.group_members_now()
1743			.remove(key)
1744			.unwrap_or_default()
1745			.iter()
1746			.find(|member| member.role > Role::None)
1747			.map(|member| (member.group, member.member))
1748			.or_else(|| reach.members_of_key(key).first().copied())
1749	}
1750
1751	/// The governing changes that the replica can read.
1752	pub fn facts(&self) -> impl Iterator<Item = &ChangeId> {
1753		self.ancestors.keys()
1754	}
1755
1756	/// Whether a change is a governing change that the replica can read.
1757	#[must_use]
1758	pub fn is_fact(&self, change: &ChangeId) -> bool {
1759		self.ancestors.contains_key(change)
1760	}
1761
1762	/// The governing changes that a governing change builds on.
1763	#[must_use]
1764	pub fn ancestors_of(&self, change: &ChangeId) -> Option<&BTreeSet<ChangeId>> {
1765		self.ancestors.get(change)
1766	}
1767
1768	/// The member that a key belongs to at a change that builds on the governing changes
1769	/// `known`: the owner that the latest counting listing among them names.
1770	#[must_use]
1771	pub fn owner(&self, key: &KeyBytes, known: &BTreeSet<ChangeId>) -> Option<EntityId> {
1772		self.listings
1773			.iter()
1774			.rev()
1775			.find(|(change, listed, ..)| listed == key && known.contains(change))
1776			.map(|(_, _, owner, ..)| *owner)
1777	}
1778
1779	/// A member's records at a change that builds on the governing changes `known`: the
1780	/// member's own, and those of the replicas, and their devices, that counting listings
1781	/// among them list for the member.
1782	#[must_use]
1783	pub fn records_of(&self, member: EntityId, known: &BTreeSet<ChangeId>) -> BTreeSet<EntityId> {
1784		let mut records = BTreeSet::from([member]);
1785		for (change, _, owner, record, device) in &self.listings {
1786			if *owner == member && known.contains(change) {
1787				records.insert(*record);
1788				records.insert(*device);
1789			}
1790		}
1791		records
1792	}
1793
1794	/// Whether an entity is the record of a member, or of a listed replica or its device, by
1795	/// the governing changes `known`, counting or not: so that whose an entity is does not
1796	/// depend on what a change does not build on.
1797	#[must_use]
1798	pub fn is_record(&self, entity: &EntityId, known: &BTreeSet<ChangeId>) -> bool {
1799		known.iter().any(|change| {
1800			self.records
1801				.get(change)
1802				.is_some_and(|records| records.contains(entity))
1803		})
1804	}
1805
1806	/// Each member that the counting governing changes give a role, with the role they have
1807	/// by all of them: the lowest of those that no other of them builds on.
1808	#[must_use]
1809	pub fn roles_now(&self) -> BTreeMap<EntityId, Role> {
1810		let all: BTreeSet<ChangeId> = self.ancestors.keys().copied().collect();
1811		let members: BTreeSet<EntityId> = self.roles.iter().map(|(_, member, _)| *member).collect();
1812		members
1813			.into_iter()
1814			.map(|member| (member, self.role(member, &all, |_| false).0))
1815			.collect()
1816	}
1817
1818	/// A member's role by all the counting governing changes, if one gives them a role: the
1819	/// lowest of those that no other of them builds on.
1820	#[must_use]
1821	pub fn role_now(&self, member: EntityId) -> Option<Role> {
1822		if !self.roles.iter().any(|(_, given, _)| *given == member) {
1823			return None;
1824		}
1825		let all: BTreeSet<ChangeId> = self.ancestors.keys().copied().collect();
1826		Some(self.role(member, &all, |_| false).0)
1827	}
1828
1829	/// Whether the space allows AI agents now: whether, of the counting changes that say so,
1830	/// those that no other of them builds on all allow them.
1831	#[must_use]
1832	pub fn allows_ai_agents(&self) -> bool {
1833		let latest: Vec<bool> = self
1834			.ai_allowed
1835			.iter()
1836			.filter(|(change, _)| {
1837				!self.ai_allowed.iter().any(|(other, _)| {
1838					self.ancestors
1839						.get(other)
1840						.is_some_and(|ancestors| ancestors.contains(change))
1841				})
1842			})
1843			.map(|(_, allows)| *allows)
1844			.collect();
1845		!latest.is_empty() && latest.iter().all(|allows| *allows)
1846	}
1847
1848	/// Whether an AI agent's change that builds on the governing changes `known` may count by
1849	/// whether the space allows AI agents: whether, of the counting changes among them that
1850	/// say so, those that no other of them builds on all allow them; and that, lowered by the
1851	/// counting ones that allow none, that it does not build on, and that `concurrent` says do
1852	/// not build on it either, as a removal sets aside what was done without knowing of it.
1853	pub fn ai_allowed(
1854		&self,
1855		known: &BTreeSet<ChangeId>,
1856		mut concurrent: impl FnMut(ChangeId) -> bool,
1857	) -> (bool, bool) {
1858		let among: Vec<(ChangeId, bool)> = self
1859			.ai_allowed
1860			.iter()
1861			.filter(|(change, _)| known.contains(change))
1862			.copied()
1863			.collect();
1864		let latest: Vec<bool> = among
1865			.iter()
1866			.filter(|(change, _)| {
1867				!among.iter().any(|(other, _)| {
1868					self.ancestors
1869						.get(other)
1870						.is_some_and(|ancestors| ancestors.contains(change))
1871				})
1872			})
1873			.map(|(_, allows)| *allows)
1874			.collect();
1875		let by_ancestors = !latest.is_empty() && latest.iter().all(|allows| *allows);
1876		let mut lowered = by_ancestors;
1877		for (change, allows) in &self.ai_allowed {
1878			if lowered && !allows && !known.contains(change) && concurrent(*change) {
1879				lowered = false;
1880			}
1881		}
1882		(by_ancestors, lowered)
1883	}
1884
1885	/// Whether the counting changes that say whether the space allows AI agents differ from
1886	/// those of `before`.
1887	#[must_use]
1888	pub fn ai_allowed_differs(&self, before: &Self) -> bool {
1889		self.ai_allowed != before.ai_allowed
1890	}
1891
1892	/// The member that a key belongs to now: the owner that its latest counting listing, in
1893	/// the order of the log, names.
1894	#[must_use]
1895	pub fn owner_now(&self, key: &KeyBytes) -> Option<EntityId> {
1896		self.listings
1897			.iter()
1898			.rev()
1899			.find(|(_, listed, ..)| listed == key)
1900			.map(|(_, _, owner, ..)| *owner)
1901	}
1902
1903	/// The counting changes that give a member the role none, of those that give them a role
1904	/// and that no other of those builds on: that removed them, or by which they left, and
1905	/// that no later role undid.
1906	#[must_use]
1907	pub fn removals_of_member(&self, member: EntityId) -> Vec<ChangeId> {
1908		let givers: Vec<(ChangeId, Role)> = self
1909			.roles
1910			.iter()
1911			.filter(|(_, given, _)| *given == member)
1912			.map(|(change, _, role)| (*change, *role))
1913			.collect();
1914		self.latest(&givers)
1915			.filter(|(_, role)| *role == Role::None)
1916			.map(|(change, _)| change)
1917			.collect()
1918	}
1919
1920	/// Of changes that each say something, those that no other of them builds on.
1921	fn latest<'s, T: Copy + 's>(
1922		&'s self,
1923		sayers: &'s [(ChangeId, T)],
1924	) -> impl Iterator<Item = (ChangeId, T)> + 's {
1925		sayers
1926			.iter()
1927			.filter(|(change, _)| {
1928				!sayers.iter().any(|(other, _)| {
1929					self.ancestors
1930						.get(other)
1931						.is_some_and(|ancestors| ancestors.contains(change))
1932				})
1933			})
1934			.copied()
1935	}
1936
1937	/// Every role that counting changes give, with the change and the member.
1938	pub fn all_roles(&self) -> impl Iterator<Item = (ChangeId, EntityId, Role)> + '_ {
1939		self.roles.iter().copied()
1940	}
1941
1942	/// The first anchors of every group change that ends paths through the groups in the
1943	/// space: a new key is written with only if its making builds on each.
1944	#[must_use]
1945	pub fn departure_anchors(&self) -> BTreeSet<ChangeId> {
1946		let Some(reach) = &self.reach else {
1947			return BTreeSet::new();
1948		};
1949		reach
1950			.departures()
1951			.iter()
1952			.flat_map(|departure| reach.first_anchors(&departure.group, &departure.change))
1953			.collect()
1954	}
1955
1956	/// For a key that a group in the space lists, at any level, by what its counting anchors
1957	/// name, and that has no path in the space now: what ended its paths, the first anchors of
1958	/// the group changes that removed its member, took a group on its paths out of the group
1959	/// it was in, revoked it or withdrew a group on its paths, and the space's own changes
1960	/// that took its groups out. Empty for any other key.
1961	#[must_use]
1962	pub fn group_removals_of(&self, key: &KeyBytes) -> Vec<ChangeId> {
1963		let Some(reach) = &self.reach else {
1964			return Vec::new();
1965		};
1966		let members = reach.members_of_key(key);
1967		if members.is_empty() {
1968			return Vec::new();
1969		}
1970		let all: BTreeSet<ChangeId> = self.ancestors.keys().copied().collect();
1971		let standing = self.standing(key, &all, NOW, |_| true);
1972		if standing
1973			.as_ref()
1974			.is_some_and(|standing| standing.by_ancestors > Role::None)
1975		{
1976			return Vec::new();
1977		}
1978		let passes = reach.passes_to(members.iter().map(|(group, _)| *group));
1979		let mut removals = BTreeSet::new();
1980		for departure in reach.departures() {
1981			let ends = match departure.ends {
1982				Ends::Member(member) => {
1983					members.contains(&(departure.group, member))
1984						|| passes.records.contains(&(departure.group, member))
1985				}
1986				Ends::Key(revoked) => revoked == *key,
1987				Ends::Withdrawal(from) => passes.joinings.contains(&(departure.group, from)),
1988			};
1989			if ends {
1990				removals.extend(reach.first_anchors(&departure.group, &departure.change));
1991			}
1992		}
1993		// Keeping the person out ends their paths too.
1994		if let Some(standing) = &standing {
1995			removals.extend(self.keeping_out_among(&standing.keys, |_| true));
1996		}
1997		for group in &passes.tops {
1998			for record in reach.records_of_group(group) {
1999				if self.role_now(record) == Some(Role::None) {
2000					removals.extend(self.removals_of_member(record));
2001				}
2002			}
2003		}
2004		removals.into_iter().collect()
2005	}
2006
2007	/// The counting changes that give anyone the role none.
2008	pub fn all_removals(&self) -> impl Iterator<Item = ChangeId> + '_ {
2009		self.roles
2010			.iter()
2011			.filter(|(_, _, role)| *role == Role::None)
2012			.map(|(change, ..)| *change)
2013	}
2014
2015	/// The counting changes that say that the space allows no AI agents.
2016	pub fn disallowing(&self) -> impl Iterator<Item = ChangeId> + '_ {
2017		self.ai_allowed
2018			.iter()
2019			.filter(|(_, allows)| !allows)
2020			.map(|(change, _)| *change)
2021	}
2022
2023	/// The counting changes that say that the space allows no AI agents, of those that say
2024	/// whether it does and that no other of those builds on: those by which it allows none
2025	/// now.
2026	#[must_use]
2027	pub fn disallowing_now(&self) -> Vec<ChangeId> {
2028		self.latest(&self.ai_allowed)
2029			.filter(|(_, allows)| !allows)
2030			.map(|(change, _)| change)
2031			.collect()
2032	}
2033
2034	/// The choices of `key` that counting changes state, each with its change.
2035	fn choices_of<'s>(
2036		&'s self,
2037		key: &'s KeyBytes,
2038	) -> impl Iterator<Item = (ChangeId, u64, bool)> + 's {
2039		self.choices
2040			.iter()
2041			.filter(move |(_, chooser, ..)| chooser == key)
2042			.map(|(change, _, number, holds)| (*change, *number, *holds))
2043	}
2044
2045	/// Whether the device whose key is `key` holds the space now: whether, of its choices
2046	/// that counting changes state, the one with the highest number, a drop winning a tie,
2047	/// holds it, or none states one
2048	/// ([technical design](../../../../docs/Technical-design.md#1310-devices-that-choose-their-spaces)).
2049	#[must_use]
2050	pub fn holds_now(&self, key: &KeyBytes) -> bool {
2051		self.standing_choice(key).is_none_or(|(_, holds)| holds)
2052	}
2053
2054	/// The choice of the device whose key is `key` that stands, of those that counting
2055	/// changes state: its number and whether it holds the space; none if none states one.
2056	#[must_use]
2057	pub fn standing_choice(&self, key: &KeyBytes) -> Option<(u64, bool)> {
2058		standing(
2059			self.choices_of(key)
2060				.map(|(_, number, holds)| (number, holds)),
2061		)
2062	}
2063
2064	/// While the device whose key is `key` does not hold the space, the counting changes that
2065	/// state its choice that stands, by which it dropped the space; empty while it holds it.
2066	/// Ordered by ID.
2067	#[must_use]
2068	pub fn drops_of(&self, key: &KeyBytes) -> Vec<ChangeId> {
2069		let Some((number, false)) = self.standing_choice(key) else {
2070			return Vec::new();
2071		};
2072		let drops: BTreeSet<ChangeId> = self
2073			.choices_of(key)
2074			.filter(|(_, stated, holds)| *stated == number && !holds)
2075			.map(|(change, ..)| change)
2076			.collect();
2077		drops.into_iter().collect()
2078	}
2079
2080	/// Every counting change that states a device's choice not to hold the space.
2081	pub fn all_drops(&self) -> impl Iterator<Item = ChangeId> + '_ {
2082		self.choices
2083			.iter()
2084			.filter(|(.., holds)| !holds)
2085			.map(|(change, ..)| *change)
2086	}
2087
2088	/// Whether a change by the device whose key is `key`, which builds on the governing
2089	/// changes `known`, may count by the device's choices: whether, of those that counting
2090	/// changes among `known` state, the one that stands holds the space, or none does; and
2091	/// that, lowered by any counting choice not to hold it that outranks that one, is not
2092	/// among `known`, and that `concurrent` says does not build on the change either, as a
2093	/// removal sets aside what was done without knowing of it.
2094	pub fn holds(
2095		&self,
2096		key: &KeyBytes,
2097		known: &BTreeSet<ChangeId>,
2098		mut concurrent: impl FnMut(ChangeId) -> bool,
2099	) -> (bool, bool) {
2100		let stood = standing(
2101			self.choices_of(key)
2102				.filter(|(change, ..)| known.contains(change))
2103				.map(|(_, number, holds)| (number, holds)),
2104		);
2105		let by_ancestors = stood.is_none_or(|(_, holds)| holds);
2106		let mut lowered = by_ancestors;
2107		for (change, number, holds) in self.choices_of(key) {
2108			if lowered
2109				&& !holds
2110				&& !known.contains(&change)
2111				&& outranks((number, holds), stood)
2112				&& concurrent(change)
2113			{
2114				lowered = false;
2115			}
2116		}
2117		(by_ancestors, lowered)
2118	}
2119
2120	/// Whether the roles that counting changes give, what they say of keeping people out, or
2121	/// what claims give, differ from those of `before`.
2122	#[must_use]
2123	pub fn roles_differ(&self, before: &Self) -> bool {
2124		let summaries =
2125			|view: &Self| -> Vec<_> { view.claims.iter().map(ClaimEffect::summary).collect() };
2126		self.roles != before.roles
2127			|| self.keep_outs != before.keep_outs
2128			|| summaries(self) != summaries(before)
2129	}
2130
2131	/// Whether a listing that counted in `before` counts no longer.
2132	#[must_use]
2133	pub fn lost_listings(&self, before: &Self) -> bool {
2134		before
2135			.listings
2136			.iter()
2137			.any(|listing| !self.listings.contains(listing))
2138	}
2139
2140	/// A member's role at a change that builds on the governing changes `known`: what the
2141	/// counting ones among them give, and that lowered by the counting ones that give the
2142	/// member a role, that it does not build on, and that `concurrent` says do not build on
2143	/// it either.
2144	pub fn role(
2145		&self,
2146		member: EntityId,
2147		known: &BTreeSet<ChangeId>,
2148		mut concurrent: impl FnMut(ChangeId) -> bool,
2149	) -> (Role, Role) {
2150		let givers: Vec<(ChangeId, Role)> = self
2151			.roles
2152			.iter()
2153			.filter(|(change, given, _)| *given == member && known.contains(change))
2154			.map(|(change, _, role)| (*change, *role))
2155			.collect();
2156		let by_ancestors = givers
2157			.iter()
2158			.filter(|(giver, _)| {
2159				!givers.iter().any(|(other, _)| {
2160					self.ancestors
2161						.get(other)
2162						.is_some_and(|ancestors| ancestors.contains(giver))
2163				})
2164			})
2165			.map(|(_, role)| *role)
2166			.min()
2167			.unwrap_or(Role::None);
2168		let mut lowered = by_ancestors;
2169		for (change, given, role) in &self.roles {
2170			if *given == member && *role < lowered && !known.contains(change) && concurrent(*change)
2171			{
2172				lowered = *role;
2173			}
2174		}
2175		(by_ancestors, lowered)
2176	}
2177
2178	/// The keys whose changes may count less than before: those of members whose roles
2179	/// changed, and those whose listings did.
2180	#[must_use]
2181	pub fn losing(&self, before: &Self) -> BTreeSet<KeyBytes> {
2182		let roles_of = |view: &Self, member: EntityId| -> Vec<(ChangeId, Role)> {
2183			view.roles
2184				.iter()
2185				.filter(|(_, given, _)| *given == member)
2186				.map(|(change, _, role)| (*change, *role))
2187				.collect()
2188		};
2189		let mut members: BTreeSet<EntityId> = BTreeSet::new();
2190		for (_, member, _) in self.roles.iter().chain(&before.roles) {
2191			if roles_of(self, *member) != roles_of(before, *member) {
2192				members.insert(*member);
2193			}
2194		}
2195		// Those whose claims give otherwise.
2196		let summaries =
2197			|view: &Self| -> Vec<_> { view.claims.iter().map(ClaimEffect::summary).collect() };
2198		let (now, then) = (summaries(self), summaries(before));
2199		for summary in now.iter().chain(&then) {
2200			if !now.contains(summary) || !then.contains(summary) {
2201				members.insert(summary.1);
2202			}
2203		}
2204		let mut losing = BTreeSet::new();
2205		for listing in self.listings.iter().chain(&before.listings) {
2206			let (_, key, owner, ..) = listing;
2207			if members.contains(owner)
2208				|| !self.listings.contains(listing)
2209				|| !before.listings.contains(listing)
2210			{
2211				losing.insert(*key);
2212			}
2213		}
2214		// Those whose choices of the space counting changes state otherwise.
2215		for choice in self.choices.iter().chain(&before.choices) {
2216			if !self.choices.contains(choice) || !before.choices.contains(choice) {
2217				losing.insert(choice.1);
2218			}
2219		}
2220		losing
2221	}
2222}
2223
2224/// Of a key's choices of a space, each its number and whether it holds the space, the one
2225/// that stands: the one with the highest number, a drop winning a tie.
2226fn standing(choices: impl IntoIterator<Item = (u64, bool)>) -> Option<(u64, bool)> {
2227	choices
2228		.into_iter()
2229		.max_by_key(|(number, holds)| (*number, !*holds))
2230}
2231
2232/// Whether a choice outranks the one that stands, `None` for none: by its number, a drop
2233/// winning a tie.
2234fn outranks((number, holds): (u64, bool), standing: Option<(u64, bool)>) -> bool {
2235	standing.is_none_or(|(stood, stood_holds)| (number, !holds) > (stood, !stood_holds))
2236}
2237
2238/// The records in a space, derived from the space and each of `keys`, that keep a person out
2239/// through groups.
2240fn keep_out_records(space: SpaceId, keys: &BTreeSet<KeyBytes>) -> BTreeSet<EntityId> {
2241	keys.iter()
2242		.filter_map(nibkeep_crypto::VerifyingKey::from_bytes)
2243		.map(|key| crate::replica_record(space, &key))
2244		.collect()
2245}
2246
2247/// When a change was made, and whether it purges anything: what a claim to the admin role
2248/// gives depends on both.
2249pub(super) type Moment = (Timestamp, bool);
2250
2251/// The moment for what holds by the records alone, which purges nothing: before any claim to
2252/// the admin role takes effect, so that no claim keeps a member who was removed.
2253pub(super) const NOW: Moment = (Timestamp::new(0, 0), false);
2254
2255/// The records of a person, for telling whether a change is another member's: their member's
2256/// record, and their records in the space.
2257fn person_records(person: &Person) -> Records {
2258	person
2259		.direct
2260		.iter()
2261		.copied()
2262		.chain([person.member])
2263		.collect()
2264}