Skip to main content

nibkeep_log/log/
governance.rs

1//! Which changes count, as the rules of [`nibkeep_governance::rules`] decide from the
2//! governing changes that the replica can read
3//! ([Log](../../../../docs/spec/log.md#8-which-changes-count)): what the log reads for them
4//! from its history, and how it takes in or sets aside the changes whose decision changed.
5
6use std::borrow::Cow;
7use std::collections::{BTreeMap, BTreeSet};
8
9use nibkeep_base::{EntityId, Hash, SpaceId, StatementId};
10use nibkeep_crypto::VerifyingKey;
11use nibkeep_governance::rules::{
12	Fact, Followed, Governance, Header, Reach, Role, Standing, View, decide,
13};
14use nibkeep_governance::{Claim, GoverningStatement, RecoveryListing, Roster, SpaceGroup};
15use nibkeep_model::storage::Statements;
16use nibkeep_model::{Operation, Statement, fields};
17use nibkeep_time::Timestamp;
18
19use super::{Log, PurgedBy, fits_an_ai_agent, holds_only_governing, read_payload};
20use crate::history::{Accepted, History, Status};
21use crate::{Change, ChangeId, Kind, LogError, Payload, Purges, Restores, SpaceKeys};
22
23impl Header for Change {
24	fn id(&self) -> ChangeId {
25		Change::id(self)
26	}
27
28	fn author(&self) -> &VerifyingKey {
29		Change::author(self)
30	}
31
32	fn timestamp(&self) -> Timestamp {
33		Change::timestamp(self)
34	}
35
36	fn is_root(&self) -> bool {
37		self.parents().is_empty()
38	}
39
40	fn space(&self) -> SpaceId {
41		Change::space(self)
42	}
43
44	fn purges_or_seals(&self) -> bool {
45		// A new kind of change that destroys or hides content must count here too, and so does
46		// one that brings back what purges destroyed.
47		self.purges_or_restores() || !self.sealed().is_empty()
48	}
49}
50
51/// Whether the space's first change governs it, the governing changes that the replica can
52/// read, in their order, and their statuses.
53type Facts = (bool, Vec<Fact>, BTreeMap<ChangeId, Status>);
54
55/// The latest governing changes that each change builds on, which no other of them builds
56/// on, with the governing changes they were found among.
57#[derive(Debug, Default)]
58pub(super) struct Frontiers {
59	among: BTreeSet<ChangeId>,
60	latest: BTreeMap<ChangeId, Vec<ChangeId>>,
61}
62
63/// What a governing change says: what decides which changes count, its author, and its
64/// statements.
65#[derive(Clone, Debug)]
66pub(super) struct ReadGoverning {
67	fact: Fact,
68	author: VerifyingKey,
69	statements: Vec<Statement>,
70}
71
72/// What an admin reviews of a change that was set aside, as [`Log::review`] gives it.
73#[derive(Clone, Debug)]
74pub struct Review {
75	/// In a space with members, the member whose replica made it, by the listings that it
76	/// builds on.
77	pub member: Option<EntityId>,
78	/// Its payload, if the replica can read it.
79	pub payload: Option<Payload>,
80	/// Whether accepting it would make it count.
81	pub acceptable: bool,
82}
83
84/// The ancestors of revocations, as far down as needed, so that each revocation's history is
85/// walked once.
86struct Ancestors {
87	/// How deep the walks go: as deep as the shallowest change they are asked about.
88	floor: u64,
89	/// For each revocation, how deep its walk went, and the changes it found.
90	walked: BTreeMap<ChangeId, (u64, BTreeSet<ChangeId>)>,
91}
92impl<S: Statements, H: History<Error = S::Error>> Log<S, H> {
93	/// What the governing changes that count say, read from them and their statuses unless
94	/// known already.
95	pub(super) fn governance(
96		&self,
97		keys: &SpaceKeys,
98	) -> Result<std::cell::Ref<'_, Governance>, LogError> {
99		if self.governance.borrow().is_none() {
100			let (governed, facts, statuses) = self.read_facts(keys)?;
101			let counting = facts
102				.iter()
103				.filter(|fact| statuses.get(&fact.id()) == Some(&Status::Applied))
104				.map(Fact::id)
105				.collect();
106			let ancestry = self.fact_ancestry(&facts)?;
107			*self.governance.borrow_mut() = Some(Governance::of(
108				(self.space, governed),
109				&facts,
110				ancestry.as_deref(),
111				&counting,
112				&self.following,
113			));
114		}
115		Ok(std::cell::Ref::map(
116			self.governance.borrow(),
117			|governance| {
118				governance
119					.as_ref()
120					.unwrap_or_else(|| unreachable!("read just now"))
121			},
122		))
123	}
124
125	/// What a space needs of this log, a group's, to follow it: the governing changes that the
126	/// replica can read, in their order, and those each builds on.
127	///
128	/// # Errors
129	///
130	/// Returns [`LogError::Storage`] if the history cannot be read.
131	pub fn followed(&self, keys: &SpaceKeys) -> Result<Followed, LogError> {
132		let (_, facts, _) = self.read_facts(keys)?;
133		let ancestry = self
134			.fact_ancestry(&facts)?
135			.unwrap_or_else(|| vec![BTreeSet::new(); facts.len()]);
136		Ok(Followed::new(self.space, facts, ancestry))
137	}
138
139	/// Follows the groups in this space, as the replica's copies of their logs say
140	/// ([`Log::followed`]): their changes take effect here at the anchors that name them. The
141	/// groups it followed before and leaves out are no longer followed. Decides again which
142	/// changes count, if the groups' changes are not those it followed before.
143	///
144	/// The log keeps what it follows in memory alone: a program follows the groups again each
145	/// time it opens the space, before it takes or makes changes there, and again whenever a
146	/// group's log changes, as a space that follows none decides without them.
147	///
148	/// # Errors
149	///
150	/// Returns [`LogError::Storage`] if the history cannot be read or written.
151	pub fn follow(&mut self, groups: Vec<Followed>, keys: &SpaceKeys) -> Result<(), LogError> {
152		// A space never follows itself, as groups that hold each other would have it.
153		let following: BTreeMap<SpaceId, Followed> = groups
154			.into_iter()
155			.filter(|followed| followed.group() != self.space)
156			.map(|followed| (followed.group(), followed))
157			.collect();
158		let same = following.len() == self.following.len()
159			&& following
160				.iter()
161				.zip(&self.following)
162				.all(|((group, new), (old_group, old))| {
163					group == old_group && new.same_changes(old)
164				});
165		if same {
166			return Ok(());
167		}
168		// What it decided before, by the groups it followed then.
169		self.governance(keys)?;
170		self.following = following;
171		self.govern(keys)
172	}
173
174	/// For each of `facts`, in their order, the facts it builds on, by index, if the space
175	/// has members, whose first change gives a role. The history is walked once: each change
176	/// below a fact is walked down to the facts it builds on through no other, and what it
177	/// found is kept for the walks that reach it again.
178	fn fact_ancestry(&self, facts: &[Fact]) -> Result<Option<Vec<BTreeSet<usize>>>, LogError> {
179		if !facts.iter().any(Fact::founds_members) {
180			return Ok(None);
181		}
182		let index: BTreeMap<ChangeId, usize> = facts
183			.iter()
184			.enumerate()
185			.map(|(at, fact)| (fact.id(), at))
186			.collect();
187		let mut nearest: BTreeMap<ChangeId, BTreeSet<usize>> = BTreeMap::new();
188		let mut ancestry: Vec<BTreeSet<usize>> = Vec::with_capacity(facts.len());
189		for fact in facts {
190			let mut found = BTreeSet::new();
191			for parent in self.parents_of(fact.id())? {
192				for earlier in self.nearest_facts(parent, &index, &mut nearest)? {
193					found.insert(earlier);
194					// A change's ancestors are earlier than it, so theirs are found already.
195					if let Some(theirs) = ancestry.get(earlier) {
196						found.extend(theirs.iter().copied());
197					}
198				}
199			}
200			ancestry.push(found);
201		}
202		Ok(Some(ancestry))
203	}
204
205	/// The facts, by their indexes in `index`, that a change is or builds on through no other
206	/// fact, as `nearest` keeps them for the changes walked before.
207	fn nearest_facts(
208		&self,
209		id: ChangeId,
210		index: &BTreeMap<ChangeId, usize>,
211		nearest: &mut BTreeMap<ChangeId, BTreeSet<usize>>,
212	) -> Result<BTreeSet<usize>, LogError> {
213		if let Some(&at) = index.get(&id) {
214			return Ok(BTreeSet::from([at]));
215		}
216		let mut to_visit = vec![(id, false)];
217		while let Some((at, expanded)) = to_visit.pop() {
218			if nearest.contains_key(&at) {
219				continue;
220			}
221			let parents = self.parents_of(at)?;
222			if !expanded {
223				to_visit.push((at, true));
224				to_visit.extend(
225					parents
226						.iter()
227						.filter(|parent| {
228							!index.contains_key(parent) && !nearest.contains_key(parent)
229						})
230						.map(|parent| (*parent, false)),
231				);
232				continue;
233			}
234			let mut found = BTreeSet::new();
235			for parent in &parents {
236				match index.get(parent) {
237					Some(&fact) => {
238						found.insert(fact);
239					}
240					None => found.extend(nearest.get(parent).into_iter().flatten().copied()),
241				}
242			}
243			nearest.insert(at, found);
244		}
245		Ok(nearest.get(&id).cloned().unwrap_or_default())
246	}
247
248	/// The parents of an accepted change.
249	fn parents_of(&self, id: ChangeId) -> Result<Vec<ChangeId>, LogError> {
250		Ok(self
251			.read(self.history.change(id))?
252			.map_or_default(|change| change.parents().iter().copied().collect()))
253	}
254
255	/// The governing changes, of those that `view` knows, that a change that is not one of
256	/// them builds on.
257	pub(super) fn known_by(
258		&self,
259		change: &Change,
260		view: &View,
261	) -> Result<BTreeSet<ChangeId>, LogError> {
262		let mut known = BTreeSet::new();
263		for parent in change.parents() {
264			for fact in self.frontier(*parent, view)? {
265				known.insert(fact);
266				if let Some(ancestors) = view.ancestors_of(&fact) {
267					known.extend(ancestors.iter().copied());
268				}
269			}
270		}
271		Ok(known)
272	}
273
274	/// The latest governing changes that a change is or builds on, which no other of them
275	/// builds on: found once for each change, from its parents', while the governing changes
276	/// that `view` knows are the same.
277	fn frontier(&self, id: ChangeId, view: &View) -> Result<Vec<ChangeId>, LogError> {
278		if view.is_fact(&id) {
279			return Ok(vec![id]);
280		}
281		{
282			let mut frontiers = self.frontiers.borrow_mut();
283			if !frontiers.among.iter().eq(view.facts()) {
284				frontiers.among = view.facts().copied().collect();
285				frontiers.latest.clear();
286			}
287			if let Some(latest) = frontiers.latest.get(&id) {
288				return Ok(latest.clone());
289			}
290		}
291		let mut to_visit = vec![(id, false)];
292		while let Some((at, expanded)) = to_visit.pop() {
293			if self.frontiers.borrow().latest.contains_key(&at) {
294				continue;
295			}
296			let parents = self.parents_of(at)?;
297			if !expanded {
298				to_visit.push((at, true));
299				let frontiers = self.frontiers.borrow();
300				to_visit.extend(
301					parents
302						.iter()
303						.filter(|parent| {
304							!view.is_fact(parent) && !frontiers.latest.contains_key(parent)
305						})
306						.map(|parent| (*parent, false)),
307				);
308				continue;
309			}
310			let mut found = BTreeSet::new();
311			{
312				let frontiers = self.frontiers.borrow();
313				for parent in &parents {
314					if view.is_fact(parent) {
315						found.insert(*parent);
316					} else if let Some(theirs) = frontiers.latest.get(parent) {
317						found.extend(theirs.iter().copied());
318					}
319				}
320			}
321			let latest = found
322				.iter()
323				.filter(|fact| {
324					!found.iter().any(|other| {
325						view.ancestors_of(other)
326							.is_some_and(|ancestors| ancestors.contains(fact))
327					})
328				})
329				.copied()
330				.collect();
331			self.frontiers.borrow_mut().latest.insert(at, latest);
332		}
333		Ok(self
334			.frontiers
335			.borrow()
336			.latest
337			.get(&id)
338			.cloned()
339			.unwrap_or_default())
340	}
341
342	/// Whether an ordinary change counts by what the counting governing changes say: as
343	/// [`Governance::counts`] decides, and, in a space with members, as
344	/// [`Log::counts_by_role`] does, from its payload too if given. `had(other)` says whether
345	/// a governing change builds on it.
346	pub(super) fn counts_now(
347		&self,
348		change: &Change,
349		payload: Option<&Payload>,
350		governance: &Governance,
351		had: impl FnMut(ChangeId) -> bool,
352	) -> Result<bool, LogError> {
353		match governance.view() {
354			Some(view) if governance.governed() => {
355				self.counts_by_role(change, payload, (governance, view), had)
356			}
357			_ => Ok(governance.counts(change, had)),
358		}
359	}
360
361	/// Whether an ordinary change counts in a space with members, whose `view` the
362	/// governance holds: if its author's member's role at it allows what its header purges,
363	/// and what its payload changes, if it can be read; and if its author is listed and not
364	/// revoked, or an admin accepted it, which lifts only what a lower role, a removal or a
365	/// revocation that it did not know of set aside. `had(other)` says whether a governing
366	/// change builds on it.
367	pub(super) fn counts_by_role(
368		&self,
369		change: &Change,
370		payload: Option<&Payload>,
371		(governance, view): (&Governance, &View),
372		mut had: impl FnMut(ChangeId) -> bool,
373	) -> Result<bool, LogError> {
374		let author = change.author().as_bytes();
375		// What an AI agent's change purges or seals is never accepted.
376		if governance.is_ai_agent(author) && change.purges_or_seals() {
377			return Ok(false);
378		}
379		let known = self.known_by(change, view)?;
380		let moment = (change.timestamp(), change.purges_or_restores());
381		let Some(standing) = view.standing(author, &known, moment, &mut had) else {
382			return Ok(false);
383		};
384		let need = self.need_of(change, payload, &standing, (view, &known))?;
385		let (by_ancestors, lowered) = (standing.by_ancestors, standing.lowered);
386		// An AI agent's change counts only where the space allows AI agents at it, and stops
387		// counting as a removal does once the admins stop allowing them.
388		let (ai_by_ancestors, ai_lowered) = if governance.is_ai_agent(author) {
389			view.ai_allowed(&known, |sayer| !had(sayer))
390		} else {
391			(true, true)
392		};
393		// A device's change counts only where it holds the space at it, and stops counting
394		// as a removal does once a choice to drop it outranks the one it knew.
395		let (holds_by_ancestors, holds_lowered) = view.holds(author, &known, |sayer| !had(sayer));
396		if governance.is_accepted(change, &mut had)
397			&& need <= by_ancestors
398			&& ai_by_ancestors
399			&& holds_by_ancestors
400		{
401			return Ok(true);
402		}
403		let listed = governance.is_listed(author) || governance.listed_in_groups().contains(author);
404		Ok(listed
405			&& governance.unrevoked(change, had)
406			&& need <= lowered
407			&& ai_lowered
408			&& holds_lowered)
409	}
410
411	/// What an admin reviews of a change that was set aside, if the replica has it: the member
412	/// whose replica made it, in a space with members, by the counting listings among the
413	/// governing changes it builds on; its payload, if the replica can read it; and whether
414	/// accepting it would make it count: an ordinary change, which no rule but those that
415	/// acceptance lifts sets aside. In a space with members, it must be readable here, so that
416	/// an admin reviews what it does, and the role that its author's member had by the
417	/// governing changes it builds on must allow it, as an AI agent's must have been allowed
418	/// there: acceptance lifts only what a lowered role, a removal or a revocation set aside.
419	/// What an AI agent's change purges or seals is never accepted, nor what writes a value
420	/// plainly that its author knew to be secret.
421	///
422	/// # Errors
423	///
424	/// Returns [`LogError::Storage`] if the history cannot be read.
425	pub fn review(&self, id: ChangeId, keys: &SpaceKeys) -> Result<Option<Review>, LogError> {
426		let Some(accepted) = self.read(self.history.get(id))?.map(Cow::into_owned) else {
427			return Ok(None);
428		};
429		let change = &accepted.change;
430		let payload = read_payload(&accepted, keys).ok().flatten();
431		let governance = self.governance(keys)?;
432		let author = change.author().as_bytes();
433		let known = match governance.view() {
434			Some(view) => Some((view, self.known_by(change, view)?)),
435			None => None,
436		};
437		let standing = known.as_ref().and_then(|(view, known)| {
438			let moment = (change.timestamp(), change.purges_or_restores());
439			view.standing(author, known, moment, |_| true)
440		});
441		let member = standing.as_ref().map(|standing| standing.member);
442		let ai_agent = governance.is_ai_agent(author);
443		let acceptable = if change.kind() == Kind::Governing {
444			false
445		} else if !governance.governed() {
446			true
447		} else if ai_agent && change.purges_or_seals() {
448			false
449		} else if let Some(payload) = &payload
450			&& ((ai_agent && !fits_an_ai_agent(payload))
451				|| self.writes_secret_plainly(change, payload, &governance)?)
452		{
453			false
454		} else {
455			match (&known, &standing, &payload) {
456				(None, ..) => true,
457				(Some((view, known)), Some(standing), Some(payload)) => {
458					let need = self.need_of(change, Some(payload), standing, (view, known))?;
459					let by_ancestors = standing.by_ancestors;
460					let (allowed, _) = if ai_agent {
461						view.ai_allowed(known, |_| false)
462					} else {
463						(true, true)
464					};
465					let (holds, _) = view.holds(author, known, |_| false);
466					need <= by_ancestors && allowed && holds
467				}
468				_ => false,
469			}
470		};
471		Ok(Some(Review {
472			member,
473			payload,
474			acceptable,
475		}))
476	}
477
478	/// Whether every one of `others` is `change` or one of its ancestors: the history is
479	/// walked once, down to the shallowest of them.
480	///
481	/// # Errors
482	///
483	/// Returns [`LogError::Storage`] if the history cannot be read.
484	pub fn builds_on_all(&self, change: ChangeId, others: &[ChangeId]) -> Result<bool, LogError> {
485		let left: BTreeSet<ChangeId> = others
486			.iter()
487			.copied()
488			.filter(|other| *other != change)
489			.collect();
490		let mut floor = u64::MAX;
491		for &other in &left {
492			match self.read(self.history.depth(other))? {
493				Some(depth) => floor = floor.min(depth),
494				None => return Ok(false),
495			}
496		}
497		if left.is_empty() {
498			return Ok(true);
499		}
500		let found = self.ancestors_down_to(change, floor)?;
501		Ok(left.iter().all(|other| found.contains(other)))
502	}
503
504	/// In a space with members, the counting governing changes that end a key's replica there,
505	/// if they do: the latest that give its member the role none, by which they left or were
506	/// removed, while that is the member's role now; and, for an AI agent's key, the latest
507	/// that say the space allows no AI agents, while it allows none. Ordered by ID; empty
508	/// elsewhere.
509	///
510	/// # Errors
511	///
512	/// Returns [`LogError::Storage`] if the history cannot be read.
513	pub fn removals_of(
514		&self,
515		key: &VerifyingKey,
516		keys: &SpaceKeys,
517	) -> Result<Vec<ChangeId>, LogError> {
518		let governance = self.governance(keys)?;
519		let Some(view) = governance.view().filter(|_| governance.governed()) else {
520			return Ok(Vec::new());
521		};
522		let mut removals = BTreeSet::new();
523		// A member removed from the space whom a group still gives a role is not ended.
524		if let Some(member) = view.owner_now(key.as_bytes())
525			&& view.role_now(member) == Some(Role::None)
526			&& !view.has_role_now(key.as_bytes())
527		{
528			removals.extend(view.removals_of_member(member));
529		}
530		if governance.is_ai_agent(key.as_bytes()) && !view.allows_ai_agents() {
531			removals.extend(view.disallowing_now());
532		}
533		// A key that only groups list, whose paths through them have all ended.
534		removals.extend(view.group_removals_of(key.as_bytes()));
535		// A device whose standing choice drops the space.
536		removals.extend(view.drops_of(key.as_bytes()));
537		Ok(removals.into_iter().collect())
538	}
539
540	/// Whether a key's replica is ended in a space with members, as
541	/// [`Log::removals_of`] says: its member left or was removed, or it is an AI agent's and
542	/// the space allows none. It changes nothing there after, and no replica gives it keys.
543	///
544	/// # Errors
545	///
546	/// Returns [`LogError::Storage`] if the history cannot be read.
547	pub fn is_removed(&self, key: &VerifyingKey, keys: &SpaceKeys) -> Result<bool, LogError> {
548		Ok(!self.removals_of(key, keys)?.is_empty())
549	}
550
551	/// In a space with members, every counting governing change that ends replicas there:
552	/// that gives a member the role none, and, where a counting listing is an AI agent's, that
553	/// says the space allows no AI agents. A key is written with only if its making builds on
554	/// each ([technical design](../../../../docs/Technical-design.md#13-sharing)). Ordered by
555	/// ID; empty elsewhere.
556	///
557	/// # Errors
558	///
559	/// Returns [`LogError::Storage`] if the history cannot be read.
560	pub fn removals(&self, keys: &SpaceKeys) -> Result<Vec<ChangeId>, LogError> {
561		let governance = self.governance(keys)?;
562		let Some(view) = governance.view().filter(|_| governance.governed()) else {
563			return Ok(Vec::new());
564		};
565		let mut removals: BTreeSet<ChangeId> = view.all_removals().collect();
566		if governance.lists_ai_agents() {
567			removals.extend(view.disallowing());
568		}
569		removals.extend(view.all_drops());
570		// What ends paths through a group takes effect at its first anchors, and keeping
571		// out a person whom nothing else gives a role at once.
572		removals.extend(view.departure_anchors());
573		for key in governance.listed_in_groups() {
574			removals.extend(view.keep_outs_ending(key));
575		}
576		Ok(removals.into_iter().collect())
577	}
578
579	/// The groups that the space's governing changes add, each with its record there, the
580	/// group and its first change, the statement that adds it, its role now, and whether it
581	/// is in the space: whether, by every group change that the counting anchors name, the
582	/// group agrees to that addition and has not withdrawn. Empty in a space without members.
583	///
584	/// # Errors
585	///
586	/// Returns [`LogError::Storage`] if the history cannot be read.
587	pub fn groups(&self, keys: &SpaceKeys) -> Result<Vec<SpaceGroup>, LogError> {
588		let governance = self.governance(keys)?;
589		let Some(view) = governance.view() else {
590			return Ok(Vec::new());
591		};
592		let Some(reach) = view.reach() else {
593			return Ok(Vec::new());
594		};
595		let knowledge = reach.knowledge(reach.counting(), None);
596		let agreed: BTreeSet<EntityId> = reach
597			.groups_in(&knowledge, |_| true)
598			.into_iter()
599			.map(|(_, record, _)| record)
600			.collect();
601		Ok(reach
602			.group_records()
603			.into_iter()
604			.map(|(record, group, addition)| SpaceGroup {
605				record,
606				group,
607				addition,
608				role: view.role_now(record),
609				agreed: agreed.contains(&record),
610			})
611			.collect())
612	}
613
614	/// The keys that the groups in the space list now, by every group change that its
615	/// counting anchors name, but AI agents' and revoked ones: replicas that count as listed
616	/// there, which a replica syncs with and gives keys to.
617	///
618	/// # Errors
619	///
620	/// Returns [`LogError::Storage`] if the history cannot be read.
621	pub fn listed_through_groups(&self, keys: &SpaceKeys) -> Result<Vec<VerifyingKey>, LogError> {
622		let governance = self.governance(keys)?;
623		Ok(governance
624			.view()
625			.map_or_default(View::listed_through_groups_now)
626			.iter()
627			.filter_map(VerifyingKey::from_bytes)
628			.collect())
629	}
630
631	/// The claims to the admin role that count in a space with members, in their order, with
632	/// when another member first saw each, when each takes effect and is settled, and whether
633	/// a rejection voids it. Empty elsewhere.
634	///
635	/// # Errors
636	///
637	/// Returns [`LogError::Storage`] if the history cannot be read.
638	pub fn claims(&self, keys: &SpaceKeys) -> Result<Vec<Claim>, LogError> {
639		let governance = self.governance(keys)?;
640		Ok(governance.view().map_or_default(|view| {
641			view.claims()
642				.iter()
643				.map(|effect| Claim {
644					claim: effect.claim,
645					claimant: effect.claimant,
646					made: effect.made,
647					seen: effect.seen(),
648					effective: effect.effective(),
649					settled: effect.settled(),
650					rejected: effect.void,
651				})
652				.collect()
653		}))
654	}
655
656	/// The role that a key's changes have in a space with members now, as its counting
657	/// governing changes give it: through its listing's member, directly or through groups;
658	/// [`Role::None`] for a key that no counting listing names, or whose member left or was
659	/// removed. `None` for a space without members. Neither a claim, which takes effect by
660	/// the wall clock, nor a revocation is taken into account.
661	///
662	/// # Errors
663	///
664	/// Returns [`LogError::Storage`] if the history cannot be read.
665	pub fn key_role(&self, key: &VerifyingKey, keys: &SpaceKeys) -> Result<Option<Role>, LogError> {
666		let governance = self.governance(keys)?;
667		if !governance.members() {
668			return Ok(None);
669		}
670		Ok(Some(governance.view().map_or(Role::None, |view| {
671			view.key_role_now(key.as_bytes())
672		})))
673	}
674
675	/// For a key that a group the space follows lists, at any level, the group and the key's
676	/// member there, by which history names the key's changes: the first path's that gives it
677	/// a role now, by every group change that the counting anchors name, or else the first
678	/// group's by ID that lists it. `None` for any other key.
679	///
680	/// # Errors
681	///
682	/// Returns [`LogError::Storage`] if the history cannot be read.
683	pub fn group_member_of(
684		&self,
685		key: &VerifyingKey,
686		keys: &SpaceKeys,
687	) -> Result<Option<(SpaceId, EntityId)>, LogError> {
688		let governance = self.governance(keys)?;
689		Ok(governance
690			.view()
691			.and_then(|view| view.group_member_of(key.as_bytes())))
692	}
693
694	/// The members of the groups that the space follows, at any level, whose keys those
695	/// groups give a role in the space now, each with the highest role that one of their keys
696	/// has now; empty for a space that follows no group.
697	///
698	/// # Errors
699	///
700	/// Returns [`LogError::Storage`] if the history cannot be read.
701	pub fn group_member_roles(
702		&self,
703		keys: &SpaceKeys,
704	) -> Result<BTreeMap<EntityId, Role>, LogError> {
705		let governance = self.governance(keys)?;
706		Ok(governance
707			.view()
708			.map_or_default(View::group_member_roles_now))
709	}
710
711	/// Each group that the space follows, at any level, that lists a key now, with the key's
712	/// member there, but for AI agents' keys.
713	///
714	/// # Errors
715	///
716	/// Returns [`LogError::Storage`] if the history cannot be read.
717	pub fn group_members_of(
718		&self,
719		key: &VerifyingKey,
720		keys: &SpaceKeys,
721	) -> Result<Vec<(SpaceId, EntityId)>, LogError> {
722		let governance = self.governance(keys)?;
723		Ok(governance
724			.view()
725			.map_or_default(|view| view.group_members_of(key.as_bytes())))
726	}
727
728	/// Each group's changes that the space's counting anchors name, with every one they
729	/// build on: a replica that changed a group, or holds a change of it that none of these
730	/// holds, anchors it.
731	///
732	/// # Errors
733	///
734	/// Returns [`LogError::Storage`] if the history cannot be read.
735	pub fn anchored(
736		&self,
737		keys: &SpaceKeys,
738	) -> Result<BTreeMap<SpaceId, BTreeSet<ChangeId>>, LogError> {
739		let governance = self.governance(keys)?;
740		Ok(governance
741			.view()
742			.and_then(View::reach)
743			.map_or_default(Reach::anchored))
744	}
745
746	/// Whether a change's author was, by the governing changes it builds on, a replica that a
747	/// counting change listed and none revoked, and in a space with members a replica of a
748	/// member whose role there was not none: as a change that counts was. A key made by such a
749	/// replica is given out, whatever later sets its making aside, so that what was written
750	/// with it stays readable ([technical design](../../../../docs/Technical-design.md#13-sharing)).
751	/// An AI agent's replica makes no key.
752	///
753	/// # Errors
754	///
755	/// Returns [`LogError::Storage`] if the history cannot be read.
756	pub fn author_was_a_member(&self, id: ChangeId, keys: &SpaceKeys) -> Result<bool, LogError> {
757		let Some(change) = self.read(self.history.change(id))?.map(Cow::into_owned) else {
758			return Ok(false);
759		};
760		let governance = self.governance(keys)?;
761		let author = change.author().as_bytes();
762		// The governing changes it builds on, found once, where they are needed.
763		let mut known = None;
764		// A device that dropped the space, by the change itself or what it builds on, makes
765		// nothing given out there: a key it made as it dropped the space is never safe.
766		if let Some(view) = governance.view().filter(|_| governance.governed())
767			&& view.standing_choice(author).is_some()
768		{
769			let mut with_itself = self.known_by(&change, view)?;
770			with_itself.insert(id);
771			if !view.holds(author, &with_itself, |_| false).0 {
772				return Ok(false);
773			}
774			with_itself.remove(&id);
775			known = Some(with_itself);
776		}
777		if self.read(self.history.status(id))? == Some(Status::Applied) {
778			return Ok(true);
779		}
780		if !governance.governed() {
781			return Ok(true);
782		}
783		if governance.is_ai_agent(author) {
784			return Ok(false);
785		}
786		for &revocation in governance.revocations_of(author).into_iter().flatten() {
787			if self.had(revocation, id)? {
788				return Ok(false);
789			}
790		}
791		if let Some(view) = governance.view() {
792			let known = match known {
793				Some(known) => known,
794				None => self.known_by(&change, view)?,
795			};
796			let moment = (change.timestamp(), change.purges_or_restores());
797			return Ok(view
798				.standing(author, &known, moment, |_| true)
799				.is_some_and(|standing| standing.by_ancestors != Role::None));
800		}
801		for &listing in governance.listings_of(author).into_iter().flatten() {
802			// A change that lists its own author counts only as the space's first.
803			if listing != id && self.had(listing, id)? {
804				return Ok(true);
805			}
806		}
807		Ok(false)
808	}
809
810	/// What an ordinary change by a replica of `member` needs of the member's role: an
811	/// editor's to purge the changes, and the statements sealed in changes, that the
812	/// member's replicas signed, and an admin's to purge anything else and content; an
813	/// editor's to change any entity, a viewer's for the member's own records, and an
814	/// admin's for those of other members, their replicas and their devices, as each
815	/// operation names its entity, and for one that names none, of an unknown kind or of the
816	/// earlier form; and an editor's for secret statements, whose entities only those who can
817	/// open them see, and for retractions of secret statements, which take away nothing
818	/// else.
819	fn need_of(
820		&self,
821		change: &Change,
822		payload: Option<&Payload>,
823		standing: &Standing,
824		(view, known): (&View, &BTreeSet<ChangeId>),
825	) -> Result<Role, LogError> {
826		let mut need = Role::Viewer;
827		// Who may purge something may restore it, and nobody else.
828		let mut signers = Vec::new();
829		for named in [change.purges(), change.restores()] {
830			if !named.blobs.is_empty() {
831				return Ok(Role::Admin);
832			}
833			for &purged in &named.changes {
834				signers.push(Some(purged));
835			}
836			for &statement in &named.statements {
837				signers.push(self.read(self.history.holder(statement))?);
838			}
839		}
840		for signer in signers {
841			let signer = match signer {
842				Some(signer) => self.read(self.history.change(signer))?.map(Cow::into_owned),
843				None => None,
844			};
845			let Some(signer) = signer else {
846				return Ok(Role::Admin);
847			};
848			let theirs = self.known_by(&signer, view)?;
849			let moment = (signer.timestamp(), signer.purges_or_restores());
850			let signers = view.standing(signer.author().as_bytes(), &theirs, moment, |_| true);
851			if !signers.is_some_and(|signers| signers.is_same_person(standing)) {
852				return Ok(Role::Admin);
853			}
854			need = need.max(Role::Editor);
855		}
856		let Some(payload) = payload else {
857			return Ok(need);
858		};
859		let records = &standing.records;
860		let restated = payload.restated.values();
861		let operations = payload
862			.operations
863			.iter()
864			.chain(restated.clone().flat_map(|restated| &restated.operations));
865		for operation in operations {
866			// What takes away secret statements names no entity, as theirs are sealed with
867			// them: an editor's, as for a secret statement itself.
868			if let Operation::RetractSecret { .. } = operation {
869				need = need.max(Role::Editor);
870				continue;
871			}
872			// What an operation of an unknown kind, or of the earlier form, changes is not
873			// told by an entity it names.
874			if operation.supersedes_any_entity() {
875				return Ok(Role::Admin);
876			}
877			match operation.entity() {
878				Some(entity) if records.contains(&entity) => {}
879				Some(entity) if !view.is_any_record(&entity, known, &standing.knowledge) => {
880					need = need.max(Role::Editor);
881				}
882				_ => return Ok(Role::Admin),
883			}
884		}
885		if !payload.sealed.is_empty()
886			|| restated
887				.into_iter()
888				.any(|restated| !restated.sealed.is_empty())
889		{
890			need = need.max(Role::Editor);
891		}
892		Ok(need)
893	}
894
895	/// Whether the space's first change governs it, the governing changes that the replica
896	/// can read and that have the form a governing change must, in their order, and their
897	/// statuses. What a change says is read once, and kept.
898	fn read_facts(&self, keys: &SpaceKeys) -> Result<Facts, LogError> {
899		let mut governed = false;
900		let mut facts = Vec::new();
901		let mut statuses = BTreeMap::new();
902		for id in self.read(self.history.governing())? {
903			let Some((status, read)) = self.governing_change(id, keys, &mut governed)? else {
904				continue;
905			};
906			facts.push(read.fact);
907			statuses.insert(id, status);
908		}
909		facts.sort_by_key(Fact::order);
910		// In a space whose first change governs it, as every space of NibKeep, only the
911		// listings that the listed keys signed count for anything.
912		if governed {
913			for fact in &mut facts {
914				fact.keep_signed();
915			}
916		}
917		Ok((governed, facts, statuses))
918	}
919
920	/// A governing change's status and what it says, if the replica can read it and it has
921	/// the form it must; `governed` notes whether it is a change without parents. A change
922	/// read before is not read again, but for its status.
923	fn governing_change(
924		&self,
925		id: ChangeId,
926		keys: &SpaceKeys,
927		governed: &mut bool,
928	) -> Result<Option<(Status, ReadGoverning)>, LogError> {
929		let Some(status) = self.read(self.history.status(id))? else {
930			return Ok(None);
931		};
932		let cached = self.facts.borrow().get(&id).cloned();
933		let read = match cached {
934			Some(Some(read)) => {
935				*governed |= read.fact.is_root();
936				Some(read)
937			}
938			Some(None) => {
939				*governed |= self
940					.read(self.history.change(id))?
941					.is_some_and(|change| change.parents().is_empty());
942				None
943			}
944			None => {
945				let Some(accepted) = self.read(self.history.get(id))?.map(Cow::into_owned) else {
946					return Ok(None);
947				};
948				*governed |= accepted.change.parents().is_empty();
949				self.read_governing(&accepted, keys)
950			}
951		};
952		if status == Status::Ignored {
953			return Ok(None);
954		}
955		Ok(read.map(|read| (status, read)))
956	}
957
958	/// What a governing change says, if the replica can read it and it has the form a
959	/// governing change must: statements of fields that govern and retractions alone, and
960	/// nothing stated again. Whatever order changes arrive in, every replica reads the
961	/// same of it.
962	fn read_governing(&self, accepted: &Accepted, keys: &SpaceKeys) -> Option<ReadGoverning> {
963		let id = accepted.change.id();
964		if let Some(read) = self.facts.borrow().get(&id) {
965			return read.clone();
966		}
967		let Ok(Some(payload)) = read_payload(accepted, keys) else {
968			// Not readable yet: it is read again when it may be.
969			return None;
970		};
971		let read =
972			(holds_only_governing(&payload.operations) && payload.restated.is_empty()).then(|| {
973				ReadGoverning {
974					fact: Fact::read(&accepted.change, &payload.operations),
975					author: *accepted.change.author(),
976					statements: payload
977						.operations
978						.iter()
979						.filter_map(|operation| match operation {
980							Operation::Assert { statement, .. } => Some(statement.clone()),
981							_ => None,
982						})
983						.collect(),
984				}
985			});
986		self.facts.borrow_mut().insert(id, read.clone());
987		read
988	}
989
990	/// The statements of the governing changes that the replica can read, in the order of
991	/// their changes, by timestamp and then by ID, each with its change, whether that counts,
992	/// and its author: what says who the replicas are. Retractions are left out, as
993	/// revoking is the only way out.
994	///
995	/// # Errors
996	///
997	/// Returns [`LogError::Storage`] if the history cannot be read.
998	pub fn governing_statements(
999		&self,
1000		keys: &SpaceKeys,
1001	) -> Result<Vec<GoverningStatement>, LogError> {
1002		let signed = self.governance(keys)?.governed();
1003		let mut statements = Vec::new();
1004		let mut governed = false;
1005		for id in self.read(self.history.governing())? {
1006			let Some((status, read)) = self.governing_change(id, keys, &mut governed)? else {
1007				continue;
1008			};
1009			let counts = status == Status::Applied;
1010			let (author, timestamp) = (read.author, read.fact.order().0);
1011			let fact = &read.fact;
1012			statements.extend(read.statements.iter().map(|statement| {
1013				let lists = statement.field == fields::SIGNING_KEY
1014					&& statement
1015						.value
1016						.as_text()
1017						.and_then(VerifyingKey::from_text)
1018						.is_some_and(|key| fact.lists_on(statement.entity, key.as_bytes(), signed));
1019				GoverningStatement {
1020					change: id,
1021					author,
1022					timestamp,
1023					counts,
1024					statement: statement.clone(),
1025					lists,
1026				}
1027			}));
1028		}
1029		statements.sort_by_key(|statement| (statement.timestamp, statement.change));
1030		Ok(statements)
1031	}
1032
1033	/// The listings of `key` by a recovery code, in the counting governing changes that list
1034	/// it and that it made itself, as a device that recovered with a code lists itself: what
1035	/// it shows a peer that does not know it yet
1036	/// ([Sync](../../../../docs/spec/sync.md#3-syncing)).
1037	///
1038	/// # Errors
1039	///
1040	/// Returns [`LogError::Storage`] if the history cannot be read.
1041	pub fn listings_by_code(
1042		&self,
1043		key: &VerifyingKey,
1044		keys: &SpaceKeys,
1045	) -> Result<Vec<RecoveryListing>, LogError> {
1046		let governance = self.governance(keys)?;
1047		let mut listings = Vec::new();
1048		for &id in governance.listings_of(key.as_bytes()).into_iter().flatten() {
1049			let mut governed = false;
1050			let Some((_, read)) = self.governing_change(id, keys, &mut governed)? else {
1051				continue;
1052			};
1053			if read.author != *key {
1054				continue;
1055			}
1056			listings.extend(read.statements.iter().filter_map(|statement| {
1057				(statement.field == fields::RECOVERY_LISTING)
1058					.then(|| statement.value.as_text())
1059					.flatten()
1060					.and_then(RecoveryListing::from_text)
1061					.filter(|listing| {
1062						listing.key == *key
1063							&& listing.space == self.space
1064							&& listing.record == statement.entity
1065					})
1066			}));
1067		}
1068		Ok(listings)
1069	}
1070
1071	/// Who the replicas of the space are, as its governing changes that count say.
1072	///
1073	/// # Errors
1074	///
1075	/// Returns [`LogError::Storage`] if the history cannot be read.
1076	pub fn roster(&self, keys: &SpaceKeys) -> Result<Roster, LogError> {
1077		Ok(Roster::new(self.space, &self.governing_statements(keys)?))
1078	}
1079
1080	/// Decides again which changes count, after a governing change could be read, and takes
1081	/// in or sets aside every change whose decision changed. A change that counted and is set
1082	/// aside leaves the state stale; what it purged is no longer purged, unless a change that
1083	/// counts purges it too.
1084	pub(super) fn govern(&mut self, keys: &SpaceKeys) -> Result<(), LogError> {
1085		let before = self.governance(keys)?.clone();
1086		let (governed, facts, statuses) = self.read_facts(keys)?;
1087		let ancestry = self.fact_ancestry(&facts)?;
1088		let counting = if governed {
1089			decide(
1090				&facts,
1091				ancestry.as_deref(),
1092				(self.space, Some(&self.following)),
1093				|ancestor, of| self.had(ancestor, of),
1094			)?
1095		} else {
1096			facts.iter().map(Fact::id).collect()
1097		};
1098		let after = Governance::of(
1099			(self.space, governed),
1100			&facts,
1101			ancestry.as_deref(),
1102			&counting,
1103			&self.following,
1104		);
1105		*self.governance.borrow_mut() = Some(after.clone());
1106		let unchanged = before == after;
1107		for fact in &facts {
1108			match (counting.contains(&fact.id()), statuses[&fact.id()]) {
1109				(true, Status::Pending | Status::SetAside) => {
1110					self.set_status(fact.id(), Status::Pending)?;
1111					self.complete_now(fact.id(), keys)?;
1112				}
1113				(false, Status::Applied) => {
1114					self.set_status(fact.id(), Status::SetAside)?;
1115					self.stale = true;
1116				}
1117				(false, Status::Pending) => self.set_status(fact.id(), Status::SetAside)?,
1118				_ => {}
1119			}
1120		}
1121		// Whether an ordinary change counts depends on what the counting governing changes
1122		// say alone.
1123		if !unchanged {
1124			self.decide_again(&before, &after, keys)?;
1125		}
1126		if self.stale
1127			&& let Some(fresh) = self.state.storage().ordinary().empty_like()
1128		{
1129			self.rebuild(fresh, keys)?;
1130		}
1131		Ok(())
1132	}
1133
1134	/// Decides again which ordinary changes count, of those that `after` may decide
1135	/// otherwise than `before`: those set aside, those accepted or no longer, and those of the
1136	/// keys that may count less, or of every key when the space came to be governed.
1137	fn decide_again(
1138		&mut self,
1139		before: &Governance,
1140		after: &Governance,
1141		keys: &SpaceKeys,
1142	) -> Result<(), LogError> {
1143		let mut candidates: BTreeSet<ChangeId> =
1144			self.read(self.history.set_aside())?.into_iter().collect();
1145		candidates.extend(before.accepted().symmetric_difference(&after.accepted()));
1146		let losing = after.losing(before);
1147		// In a space that follows groups, what they give, or a role, may change the standing
1148		// of any key, of a member through a group or of one joined to them: every change is
1149		// decided again.
1150		let roles_changed = match (before.view(), after.view()) {
1151			(Some(before), Some(after)) => after.roles_differ(before),
1152			_ => false,
1153		};
1154		let groups_changed = match (before.reach(), after.reach()) {
1155			(None, None) => false,
1156			(Some(earlier), Some(later)) => {
1157				!losing.is_empty() || roles_changed || !earlier.gives_same(later)
1158			}
1159			_ => true,
1160		};
1161		let newly_governed = before.governed() != after.governed() || groups_changed;
1162		// In a space with members, a purge's signer's member is found through the signer's
1163		// listing: once one stops counting, every purge is decided again.
1164		let purges_again = after
1165			.view()
1166			.is_some_and(|view| view.lost_listings(before.view().unwrap_or(&View::default())));
1167		// A change that makes a field secret for good, which counts now: the ordinary changes
1168		// that it does not build on may have written the field in plain since, or at the same
1169		// time, and then no longer count. What it builds on stays as it was.
1170		let mut built_on: Vec<BTreeSet<ChangeId>> = Vec::new();
1171		for (field, marks) in after.secret_fields() {
1172			for &mark in marks {
1173				if !before
1174					.made_secret(field)
1175					.is_some_and(|had| had.contains(&mark))
1176				{
1177					built_on.push(self.ancestors_of(mark)?);
1178				}
1179			}
1180		}
1181		if newly_governed || !losing.is_empty() || !built_on.is_empty() || purges_again {
1182			for id in self.read(self.history.ids())? {
1183				let Some(change) = self.read(self.history.change(id))? else {
1184					continue;
1185				};
1186				let unseen = change.kind() == Kind::Ordinary
1187					&& built_on.iter().any(|ancestors| !ancestors.contains(&id));
1188				if newly_governed
1189					|| losing.contains(change.author().as_bytes())
1190					|| (purges_again && change.purges_or_restores())
1191					|| unseen
1192				{
1193					candidates.insert(id);
1194				}
1195			}
1196		}
1197		// Each revocation's history is walked once, down to the shallowest candidate.
1198		let mut floor = u64::MAX;
1199		for &id in &candidates {
1200			if let Some(depth) = self.read(self.history.depth(id))? {
1201				floor = floor.min(depth);
1202			}
1203		}
1204		let mut ancestors = Ancestors {
1205			floor,
1206			walked: BTreeMap::new(),
1207		};
1208		let mut recount = false;
1209		let read_payloads = !built_on.is_empty();
1210		for id in candidates {
1211			recount |= self.decide_change(id, (after, read_payloads), &mut ancestors, keys)?;
1212		}
1213		// Changes that come to count, or no longer, as what restores comes to count too, are
1214		// counted again until none does.
1215		while recount {
1216			recount = false;
1217			for id in self.recount_purges(keys)? {
1218				recount |= self.decide_change(id, (after, read_payloads), &mut ancestors, keys)?;
1219			}
1220		}
1221		Ok(())
1222	}
1223
1224	/// Decides again whether an accepted ordinary change counts, and takes it in or sets it
1225	/// aside; from what its payload writes too if it was set aside, or, with
1226	/// `read_payloads`, as a field became secret for good. Returns whether it was set aside after its header was acted on, so
1227	/// that what it purged is to be counted again.
1228	fn decide_change(
1229		&mut self,
1230		id: ChangeId,
1231		(governance, read_payloads): (&Governance, bool),
1232		ancestors: &mut Ancestors,
1233		keys: &SpaceKeys,
1234	) -> Result<bool, LogError> {
1235		let Some(accepted) = self.read(self.history.get(id))?.map(Cow::into_owned) else {
1236			return Ok(false);
1237		};
1238		if accepted.change.kind() == Kind::Governing {
1239			return Ok(false);
1240		}
1241		let depth = accepted.depth;
1242		// In a space with members, what its author's role allows of what it writes, if it can
1243		// be read.
1244		let payload = if governance.view().is_some() {
1245			read_payload(&accepted, keys).ok().flatten()
1246		} else {
1247			None
1248		};
1249		let mut failed = None;
1250		let mut counts = self.counts_now(
1251			&accepted.change,
1252			payload.as_ref(),
1253			governance,
1254			|other| match self.descends(other, id, depth, ancestors) {
1255				Ok(had) => had,
1256				Err(error) => {
1257					failed = Some(error);
1258					false
1259				}
1260			},
1261		)?;
1262		if let Some(error) = failed {
1263			return Err(error);
1264		}
1265		// An AI agent's change that writes what an AI agent may not is set aside, once its
1266		// payload can be read, and so is one that writes plainly what its author knew to be
1267		// secret; one that cannot be read yet is decided when it is completed, as is one set
1268		// aside that comes to count.
1269		let ai_agent = governance.is_ai_agent(accepted.change.author().as_bytes());
1270		let payload = match payload {
1271			Some(payload) => Some(payload),
1272			None if counts
1273				&& (ai_agent || read_payloads || accepted.status == Status::SetAside) =>
1274			{
1275				read_payload(&accepted, keys).ok().flatten()
1276			}
1277			None => None,
1278		};
1279		if counts
1280			&& (ai_agent || read_payloads || accepted.status == Status::SetAside)
1281			&& let Some(payload) = payload
1282		{
1283			counts = (!ai_agent || fits_an_ai_agent(&payload))
1284				&& !self.writes_secret_plainly(&accepted.change, &payload, governance)?;
1285		}
1286		match (counts, accepted.status) {
1287			(true, Status::SetAside) => {
1288				let status = if self.read(self.history.is_change_purged(id))? {
1289					Status::Ignored
1290				} else {
1291					Status::Pending
1292				};
1293				self.set_status(id, status)?;
1294				let recount = self.take_in_header(&accepted.change, false)?;
1295				self.hold_sealed(&accepted.change)?;
1296				self.complete(id, keys)?;
1297				Ok(recount)
1298			}
1299			(false, Status::SetAside) | (true, _) => Ok(false),
1300			(false, status) => {
1301				self.set_status(id, Status::SetAside)?;
1302				if status == Status::Applied {
1303					self.stale = true;
1304				}
1305				let header = &accepted.change;
1306				Ok(header.purges_or_seals())
1307			}
1308		}
1309	}
1310
1311	/// Whether `change`, at `depth`, is `revocation` or one of its ancestors.
1312	fn descends(
1313		&self,
1314		revocation: ChangeId,
1315		change: ChangeId,
1316		depth: u64,
1317		ancestors: &mut Ancestors,
1318	) -> Result<bool, LogError> {
1319		if revocation == change {
1320			return Ok(true);
1321		}
1322		if let Some((walked, found)) = ancestors.walked.get(&revocation)
1323			&& *walked <= depth
1324		{
1325			return Ok(found.contains(&change));
1326		}
1327		let depth = depth.min(ancestors.floor);
1328		let found = self.ancestors_down_to(revocation, depth)?;
1329		let had = found.contains(&change);
1330		ancestors.walked.insert(revocation, (depth, found));
1331		Ok(had)
1332	}
1333
1334	/// The ancestors of a change that are at least `depth` deep.
1335	pub(super) fn ancestors_down_to(
1336		&self,
1337		of: ChangeId,
1338		depth: u64,
1339	) -> Result<BTreeSet<ChangeId>, LogError> {
1340		let mut found = BTreeSet::new();
1341		let mut to_visit: Vec<ChangeId> = self
1342			.read(self.history.change(of))?
1343			.map_or_default(|change| change.parents().iter().copied().collect());
1344		while let Some(id) = to_visit.pop() {
1345			if found.contains(&id) {
1346				continue;
1347			}
1348			let Some(visiting) = self.read(self.history.depth(id))? else {
1349				continue;
1350			};
1351			if visiting < depth {
1352				continue;
1353			}
1354			found.insert(id);
1355			if let Some(change) = self.read(self.history.change(id))? {
1356				to_visit.extend(change.parents().iter().copied());
1357			}
1358		}
1359		Ok(found)
1360	}
1361
1362	/// The changes `of`, and every accepted change that one of them builds on.
1363	///
1364	/// # Errors
1365	///
1366	/// Returns [`LogError::Storage`] if the history cannot be read.
1367	pub fn with_ancestors(&self, of: &[ChangeId]) -> Result<BTreeSet<ChangeId>, LogError> {
1368		let mut found: BTreeSet<ChangeId> = BTreeSet::new();
1369		for &change in of {
1370			if found.contains(&change) || self.read(self.history.change(change))?.is_none() {
1371				continue;
1372			}
1373			found.insert(change);
1374			found.extend(self.ancestors_down_to(change, 0)?);
1375		}
1376		Ok(found)
1377	}
1378
1379	/// Whether `ancestor` is `of` or one of its ancestors.
1380	pub(super) fn had(&self, ancestor: ChangeId, of: ChangeId) -> Result<bool, LogError> {
1381		if ancestor == of {
1382			return Ok(true);
1383		}
1384		match self.read(self.history.change(of))? {
1385			Some(change) => self.is_ancestor(ancestor, &change),
1386			None => Ok(false),
1387		}
1388	}
1389
1390	/// Counts again what purges that count destroyed, after a change whose header was acted
1391	/// on was set aside as its payload was read, or one that restores came to count, and
1392	/// decides again the changes that this brings back, until none comes to count or stops.
1393	pub(super) fn recount_purges_and_decide(&mut self, keys: &SpaceKeys) -> Result<(), LogError> {
1394		let governance = self.governance(keys)?.clone();
1395		let mut ancestors = Ancestors {
1396			floor: u64::MAX,
1397			walked: BTreeMap::new(),
1398		};
1399		let mut recount = true;
1400		while recount {
1401			recount = false;
1402			for id in self.recount_purges(keys)? {
1403				recount |= self.decide_change(id, (&governance, false), &mut ancestors, keys)?;
1404			}
1405		}
1406		Ok(())
1407	}
1408
1409	/// Which purge keeps each purged item purged, of the changes, secret statements and sealed
1410	/// blobs that counting purges destroyed: the first that purges it and that no counting
1411	/// change that restores it builds on. A copy that waits counts its wait by it
1412	/// ([technical design](../../../../docs/Technical-design.md#911-copies-that-wait)).
1413	///
1414	/// # Errors
1415	///
1416	/// Returns [`LogError::Storage`] if the history cannot be read.
1417	pub fn purged_by(&self) -> Result<PurgedBy, LogError> {
1418		// A space that purged nothing needs no look through its history.
1419		if self.read(self.history.purged_changes())?.is_empty()
1420			&& self.read(self.history.purged_statements())?.is_empty()
1421			&& self.read(self.history.purged_blobs())?.is_empty()
1422		{
1423			return Ok(PurgedBy::default());
1424		}
1425		let mut purging: Vec<(ChangeId, Purges)> = Vec::new();
1426		let mut restoring: Vec<(ChangeId, Restores)> = Vec::new();
1427		for id in self.read(self.history.ids())? {
1428			let (Some(change), Some(status)) = (
1429				self.read(self.history.change(id))?.map(Cow::into_owned),
1430				self.read(self.history.status(id))?,
1431			) else {
1432				continue;
1433			};
1434			if status == Status::SetAside {
1435				continue;
1436			}
1437			if !change.purges().is_empty() {
1438				purging.push((id, change.purges().clone()));
1439			}
1440			if !change.restores().is_empty() {
1441				restoring.push((id, change.restores().clone()));
1442			}
1443		}
1444		let (changes, statements, blobs) = self.still_purged(&purging, &restoring)?;
1445		Ok(PurgedBy {
1446			changes,
1447			statements,
1448			blobs,
1449		})
1450	}
1451
1452	/// Counts again what the changes that count purge, after one that purged was set aside,
1453	/// or one that restores came to count or stopped: what a counting change purges stays
1454	/// purged unless a counting change that builds on it restores it, what none of them
1455	/// purges so is no longer purged, and which change holds each sealed statement is
1456	/// decided again among those that count. What comes to be purged again, as after a
1457	/// change that restored it was set aside, is destroyed again. Returns the changes that
1458	/// are no longer purged, which may count or not.
1459	fn recount_purges(&mut self, keys: &SpaceKeys) -> Result<Vec<ChangeId>, LogError> {
1460		let mut purging: Vec<(ChangeId, Purges)> = Vec::new();
1461		let mut all_restoring = BTreeSet::new();
1462		let mut restoring: Vec<(ChangeId, Restores)> = Vec::new();
1463		let mut sealing: Vec<(ChangeId, bool, Timestamp, Vec<StatementId>)> = Vec::new();
1464		for id in self.read(self.history.ids())? {
1465			// The header and the status are enough: the payload is not read.
1466			let (Some(change), Some(status)) = (
1467				self.read(self.history.change(id))?.map(Cow::into_owned),
1468				self.read(self.history.status(id))?,
1469			) else {
1470				continue;
1471			};
1472			let set_aside = status == Status::SetAside;
1473			if !change.restores().is_empty() {
1474				all_restoring.insert(id);
1475			}
1476			if !change.sealed().is_empty() {
1477				sealing.push((
1478					id,
1479					set_aside,
1480					change.timestamp(),
1481					change.sealed().keys().copied().collect(),
1482				));
1483			}
1484			if set_aside {
1485				continue;
1486			}
1487			if !change.purges().is_empty() {
1488				purging.push((id, change.purges().clone()));
1489			}
1490			if !change.restores().is_empty() {
1491				restoring.push((id, change.restores().clone()));
1492			}
1493		}
1494		*self.restoring.get_mut() = Some(all_restoring);
1495		let (changes, statements, blobs) = self.still_purged(&purging, &restoring)?;
1496		let mut unpurged = Vec::new();
1497		for id in self.read(self.history.purged_changes())? {
1498			if !changes.contains_key(&id) {
1499				let forgot = self.history.unpurge_change(id);
1500				self.read(forgot)?;
1501				unpurged.push(id);
1502				self.destroyed.restored.changes.insert(id);
1503			}
1504		}
1505		for statement in self.read(self.history.purged_statements())? {
1506			if !statements.contains_key(&statement) {
1507				let forgot = self.history.unpurge_statement(statement);
1508				self.read(forgot)?;
1509				self.destroyed.restored.statements.insert(statement);
1510			}
1511		}
1512		for sealed in self.read(self.history.purged_blobs())? {
1513			if !blobs.contains_key(&sealed) {
1514				let forgot = self.history.unpurge_blob(sealed);
1515				self.read(forgot)?;
1516				self.destroyed.restored.blobs.insert(sealed);
1517			}
1518		}
1519		// What is purged again, as a change that restored it no longer counts, is destroyed
1520		// again.
1521		for (&change, &by) in &changes {
1522			if !self.read(self.history.is_change_purged(change))? {
1523				self.destroy_change(change, by)?;
1524				self.destroyed.restored.changes.remove(&change);
1525			}
1526		}
1527		for (&statement, &by) in &statements {
1528			if !self.read(self.history.is_statement_purged(statement))? {
1529				self.destroy_statement(statement, by)?;
1530				self.destroyed.restored.statements.remove(&statement);
1531			}
1532		}
1533		for (&sealed, &by) in &blobs {
1534			if !self.read(self.history.is_blob_purged(&sealed))? {
1535				self.destroy_blob_key(sealed, by)?;
1536				self.destroyed.restored.blobs.remove(&sealed);
1537			}
1538		}
1539		// Of the changes that seal a statement, whether they count or not, one that counts and
1540		// was not purged comes first, then the earliest, then the smallest, as when they
1541		// arrive.
1542		let mut holders: BTreeMap<StatementId, (bool, Timestamp, ChangeId)> = BTreeMap::new();
1543		for (id, set_aside, timestamp, sealed) in sealing {
1544			let order = (set_aside || changes.contains_key(&id), timestamp, id);
1545			for statement in sealed {
1546				let best = holders.entry(statement).or_insert(order);
1547				if order < *best {
1548					*best = order;
1549				}
1550			}
1551		}
1552		for (statement, (_, _, holder)) in holders {
1553			if self.read(self.history.holder(statement))? != Some(holder) {
1554				let held = self.history.set_holder(statement, holder);
1555				self.read(held)?;
1556				self.state.storage_mut().forget(statement);
1557				self.open(statement, keys, &mut BTreeMap::new())?;
1558			}
1559		}
1560		Ok(unpurged)
1561	}
1562
1563	/// What the counting changes that purge, `purging`, keep purged, each item by the first
1564	/// purge that purges it so: all they name but what a counting change that restores it,
1565	/// of `restoring`, restores after the purge, building on it.
1566	#[expect(
1567		clippy::type_complexity,
1568		reason = "three maps, as the history keeps them"
1569	)]
1570	fn still_purged(
1571		&self,
1572		purging: &[(ChangeId, Purges)],
1573		restoring: &[(ChangeId, Restores)],
1574	) -> Result<
1575		(
1576			BTreeMap<ChangeId, ChangeId>,
1577			BTreeMap<StatementId, ChangeId>,
1578			BTreeMap<Hash, ChangeId>,
1579		),
1580		LogError,
1581	> {
1582		let mut changes: BTreeMap<ChangeId, ChangeId> = BTreeMap::new();
1583		let mut statements: BTreeMap<StatementId, ChangeId> = BTreeMap::new();
1584		let mut blobs: BTreeMap<Hash, ChangeId> = BTreeMap::new();
1585		// Whether a counting change that builds on the purge restores the item.
1586		for (purge, purges) in purging {
1587			for &change in &purges.changes {
1588				if !changes.contains_key(&change)
1589					&& !self.restored_after(*purge, restoring, &|named| {
1590						named.changes.contains(&change)
1591					})? {
1592					changes.insert(change, *purge);
1593				}
1594			}
1595			for &statement in &purges.statements {
1596				if !statements.contains_key(&statement)
1597					&& !self.restored_after(*purge, restoring, &|named| {
1598						named.statements.contains(&statement)
1599					})? {
1600					statements.insert(statement, *purge);
1601				}
1602			}
1603			for &sealed in &purges.blobs {
1604				if !blobs.contains_key(&sealed)
1605					&& !self
1606						.restored_after(*purge, restoring, &|named| named.blobs.contains(&sealed))?
1607				{
1608					blobs.insert(sealed, *purge);
1609				}
1610			}
1611		}
1612		Ok((changes, statements, blobs))
1613	}
1614
1615	/// Changes the status of an accepted change, keeping what the log has of it.
1616	pub(super) fn set_status(&mut self, id: ChangeId, status: Status) -> Result<(), LogError> {
1617		let Some(mut accepted) = self.read(self.history.get(id))?.map(Cow::into_owned) else {
1618			return Ok(());
1619		};
1620		if accepted.status == status {
1621			return Ok(());
1622		}
1623		accepted.status = status;
1624		self.store(&accepted)
1625	}
1626}