Skip to main content

nibkeep_node/library/
moving.rs

1//! Moving an entity to another space of the user's: sharing means moving
2//! ([technical design](../../../../docs/Technical-design.md#13-sharing)), and giving something
3//! to someone is moving it to their space
4//! ([technical design](../../../../docs/Technical-design.md#131-spaces-and-moves)). A move writes,
5//! in the other space, a new entity for the entity and for each folder, list, membership and
6//! member that it holds, through every level, each once: their values, and, unless the
7//! person chooses otherwise, their history, as the mover's account of it; their secret
8//! values, sealed with the other space's secrets key, unless the person leaves them behind;
9//! the definitions of their types that the other space lacks, in changes of their own; and
10//! their files' content, whose sealed copies the replica's spaces share. Each old entity is
11//! marked as moved into its new one, and keeps its history where it was too.
12
13use std::collections::{BTreeMap, BTreeSet, VecDeque};
14use std::fs::File;
15
16use nibkeep_base::{EntityId, Hash, SpaceId, StatementId};
17use nibkeep_crypto::VerifyingKey;
18use nibkeep_crypto::rand_core::CryptoRng;
19use nibkeep_log::list::MEMBERSHIP;
20use nibkeep_model::storage::Statements as _;
21use nibkeep_model::{FieldName, Operation, Statement, TypeName, Value, fields};
22use nibkeep_std::{
23	ATTACHED_TO, CHECKED_OUT_ON, CHECKOUT_OF, CONTENT, FILE, FOUND_ON, IN_FOLDER, IN_TREE,
24	ORIGIN_OF, THUMBNAIL, THUMBNAIL_OF,
25};
26use nibkeep_time::Timestamp;
27
28use super::export::OWN_RECORDS;
29use super::links::Links;
30use super::{Library, held_copies_in};
31use crate::NodeError;
32
33/// How many moves on a lookup follows, from one space to another.
34const MOST_MOVES: usize = 16;
35
36/// Whether a move brings the history of what it moves ([technical design: spaces and moves]).
37///
38/// [technical design: spaces and moves]: ../../../../docs/Technical-design.md#131-spaces-and-moves
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub enum MoveHistory {
41	/// Its past values too, each replaced as it was, with the mover's note of when the old
42	/// space recorded it, and by whom.
43	Bring,
44	/// Its current values alone, as they are, which leaves its history in the old space.
45	Leave,
46}
47
48/// Whether a move purges what it leaves behind in the old space ([technical design: spaces and moves]).
49///
50/// [technical design: spaces and moves]: ../../../../docs/Technical-design.md#131-spaces-and-moves
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum Behind {
53	/// Purges it, once the new entity counts and another device holds it: what the mover's
54	/// role lets them purge, and a mark asks the old space's admins for the rest.
55	Purge,
56	/// Keeps it, as it was.
57	Keep,
58}
59
60/// Whether a move takes the secret values of what it moves ([technical design: sharing]): the
61/// values of fields secret in the old space.
62///
63/// [technical design: sharing]: ../../../../docs/Technical-design.md#13-sharing
64#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65pub enum MoveSecrets {
66	/// Takes them, current and past alike, sealed with the other space's secrets key, which
67	/// needs the secrets of both spaces unlocked; a field secret in the old space becomes
68	/// secret in the new one.
69	Bring,
70	/// Leaves them with the old entity, which keeps them, as no purge of what a move leaves
71	/// behind takes a secret value that did not move.
72	Leave,
73}
74
75/// What a move would take, for an app to show before it moves.
76#[derive(Clone, Debug, PartialEq, Eq)]
77pub struct MovePreview {
78	/// The entities that move: the one given first, then the folders, lists, memberships and
79	/// members that it holds, through every level, each once.
80	pub entities: Vec<EntityId>,
81	/// The folders and lists of the old space that stay, and hold some of them: they find
82	/// what moved through the marks that lead to it. Ordered by ID.
83	pub staying: Vec<EntityId>,
84	/// The members of the old space who are no members of the new one, by name, sorted:
85	/// those who no longer see what moves once what stays behind is purged.
86	pub losing: Vec<String>,
87	/// The members of the new space who are no members of the old one, by name, sorted:
88	/// those who see what moves for the first time, its history too where the move brings it.
89	pub gaining: Vec<String>,
90	/// Whether the mover may purge all that stays behind: in the personal space, or as an
91	/// admin of the old space; an editor purges only the changes they signed there, and those
92	/// who lose what moves lose it only once an admin purges the rest.
93	pub purges_all: bool,
94	/// Whether the move needs the secrets unlocked, as far as this replica can tell: what
95	/// moves holds secret values, values of fields secret in the old space, which move only
96	/// with the secrets of both spaces unlocked, or stay behind; or values of fields secret in
97	/// the new space, which are sealed there. While the old space's secrets are locked, an
98	/// entity whose types list a secret field may hold secret values.
99	pub secrets: bool,
100}
101
102/// A statement that a move carries, with what the old space recorded of it.
103struct Carried {
104	statement: Statement,
105	/// Whether it is a secret value in the old space: sealed there, or of a field secret
106	/// there now.
107	secret: bool,
108	/// When the old space recorded it, if the move brings history.
109	recorded: Option<Timestamp>,
110	/// Who recorded it there, as far as the old space says.
111	author: Option<VerifyingKey>,
112	/// When the old space recorded that it was replaced: it is carried replaced.
113	replaced: Option<Timestamp>,
114}
115
116/// What a move takes: each entity with the statements it carries, the one given first; the
117/// content of the files that they hold now or held before, each with the fields that hold
118/// it, and whether one holds it now; their types; and the fields of their secret values.
119struct Taken {
120	entities: Vec<(EntityId, Vec<Carried>)>,
121	/// What the move writes anew in the other space and leaves where it is too, unmarked:
122	/// thumbnails that files staying behind still show.
123	copies: Vec<(EntityId, Vec<Carried>)>,
124	contents: BTreeMap<Hash, (BTreeSet<FieldName>, bool)>,
125	kinds: BTreeSet<TypeName>,
126	secret: BTreeSet<FieldName>,
127}
128
129impl Taken {
130	/// Takes a copy of an entity with the statements it carries, and the content they hold,
131	/// leaving the entity where it is.
132	fn copy(&mut self, entity: EntityId, carried: Vec<Carried>) {
133		self.add(entity, carried);
134		if let Some(copied) = self.entities.pop() {
135			self.copies.push(copied);
136		}
137	}
138
139	/// Takes an entity with the statements it carries, and the content they hold. What a
140	/// thumbnail was made of, it names without holding it, so it is no content to take.
141	fn add(&mut self, entity: EntityId, carried: Vec<Carried>) {
142		for statement in &carried {
143			if statement.secret {
144				self.secret.insert(statement.statement.field.clone());
145			}
146			if let Value::Blob(content) = statement.statement.value
147				&& !nibkeep_std::names_content_only(&statement.statement.field)
148			{
149				let (holding, now) = self.contents.entry(content).or_default();
150				holding.insert(statement.statement.field.clone());
151				*now |= statement.replaced.is_none();
152			}
153		}
154		self.entities.push((entity, carried));
155	}
156}
157
158impl Library {
159	/// Moves an entity of `from` to the space `to`, with the folders, lists, memberships and
160	/// members that it holds, through every level, each once, as [`Library::move_preview`]
161	/// lists them: marks each in `from` as moved into a new one, and writes the new ones in
162	/// `to`, with their values, references among them leading to the new ones; with
163	/// [`MoveHistory::Bring`], their past values too, replaced, each value with the mover's
164	/// note of where it came from, when that space recorded it and by whom, and when it was
165	/// replaced there; with [`MoveSecrets::Bring`], their secret values, sealed with the
166	/// secrets key of `to`, which this replica sets up there first if it may, and the fields
167	/// secret in `from` made secret for good in `to` where its types leave them plain; the
168	/// definitions of their types that `to` lacks; and their files' content, whose keys are
169	/// wrapped for `to`. A folder that stays no longer holds what moved, which it finds
170	/// through its mark. Returns the entity the given one is now. The old entities keep their
171	/// history in `from`, and links to them lead to the new ones for those who hold `to`. The
172	/// marks come first: a mark whose entity never came is passed over, so a move cut short
173	/// leaves the entities where they were.
174	///
175	/// # Errors
176	///
177	/// Returns an error if the spaces are one, this library lacks either, this replica is an
178	/// AI agent's or revoked there, the entity is not in `from`, was moved already, or what
179	/// would move holds one of the library's own records, a definition or a tree, or is in a
180	/// tree; with [`MoveSecrets::Bring`], [`NodeError::MoveNeedsSecrets`] if any of it may
181	/// hold secret values while the secrets of `from` are locked, or those of `to`, the
182	/// personal space, are; [`NodeError::NotSecretThere`] if a field of its secret values is
183	/// secret in `from` and would be plain in `to`, whose admins alone make it secret; the
184	/// errors of setting up the secrets of `to`, if this replica holds none there, such as
185	/// [`NodeError::AdminsOnly`] or [`NodeError::SpaceSecretsElsewhere`];
186	/// [`NodeError::NotHere`] if a file's content is not on this device; or an error if a
187	/// change cannot be saved. Nothing moves then.
188	#[expect(
189		clippy::too_many_arguments,
190		reason = "one move, with the choices the person makes"
191	)]
192	pub fn move_entity(
193		&mut self,
194		from: SpaceId,
195		entity: EntityId,
196		to: SpaceId,
197		history: MoveHistory,
198		behind: Behind,
199		secrets: MoveSecrets,
200		wall_millis: u64,
201		rng: &mut impl CryptoRng,
202	) -> Result<EntityId, NodeError> {
203		self.check_move(from, to)?;
204		self.check_not_group(to)?;
205		// What other programs wrote, so that nothing moved since, or edited, is missed.
206		self.catch_up()?;
207		let taken = self.to_move((from, to), entity, (history, secrets))?;
208		// What would fail later, before anything is written; and where its secret values go.
209		self.check_contents_here((from, to), &taken)?;
210		self.prepare_secrets((from, to), &taken, wall_millis, rng)?;
211		// The types they have, as this space defines them, with what the other lacks of them,
212		// as careful as the other's types are, so that a field secret there stays so.
213		let source_types = self.types(from)?;
214		for kind in &taken.kinds {
215			if let Some(definition) = source_types.get(kind) {
216				let careful = self.space(to)?.types.careful(definition);
217				self.define_type(to, &careful, wall_millis, rng)?;
218			}
219		}
220		// What is secret here stays secret there.
221		self.keep_secret(to, &taken.secret, wall_millis, rng)?;
222		// Their files' content, whose sealed copies the two spaces share, each of the kind,
223		// secret or ordinary, of the fields that hold it there; and what this replica holds of
224		// the content they had before, which their history names.
225		let secret_there = self.space(to)?.stored.secret_fields().clone();
226		for (content, (holding, now)) in &taken.contents {
227			if !now && !self.space(from)?.stored.holds_blob(content) {
228				continue;
229			}
230			let kinds: BTreeSet<bool> = holding
231				.iter()
232				.map(|field| secret_there.contains(field))
233				.collect();
234			for secret in kinds {
235				self.copy_blob(from, content, (to, secret), wall_millis, rng)?;
236			}
237		}
238		let new: BTreeMap<EntityId, EntityId> = taken
239			.entities
240			.iter()
241			.chain(&taken.copies)
242			.map(|(old, _)| (*old, EntityId::random(rng)))
243			.collect();
244		let mut marks = Vec::new();
245		for (old, _) in &taken.entities {
246			marks.push(Operation::assert(Statement::new(
247				StatementId::random(rng),
248				*old,
249				fields::MOVED_INTO,
250				Value::Reference(new[old]),
251			)));
252			// What stays is purged later, once another device holds the new entity; a move
253			// that keeps it takes back what a move cut short asked.
254			if behind == Behind::Purge {
255				marks.push(Operation::assert(Statement::new(
256					StatementId::random(rng),
257					*old,
258					fields::PURGE_ASKED,
259					Value::Boolean(true),
260				)));
261			} else {
262				let asked: Vec<StatementId> = self
263					.space(from)?
264					.stored
265					.log()
266					.state()
267					.current(*old, &fields::PURGE_ASKED)?
268					.iter()
269					.map(|statement| statement.id)
270					.collect();
271				if !asked.is_empty() {
272					marks.push(Operation::retract(*old, asked));
273				}
274			}
275		}
276		self.commit(from, marks, wall_millis, rng)?;
277		let mut operations = Vec::new();
278		for (old, carried) in taken.entities.iter().chain(&taken.copies) {
279			operations.extend(carried_operations(
280				carried,
281				(new[old], &new),
282				(from, history),
283				rng,
284			));
285		}
286		self.commit(to, operations, wall_millis, rng)?;
287		let given = taken.entities.first().map_or(entity, |(old, _)| *old);
288		Ok(new[&given])
289	}
290
291	/// What moving an entity of `from` to `to` would take: the entity, and the folders,
292	/// lists, memberships and members that it holds, through every level, each once, but
293	/// those deleted or moved already; and the folders and lists of `from` that stay and hold
294	/// some of them, which no longer hold them in `to` ([technical design: spaces and moves]). An app shows
295	/// this before a move takes more than the entity, or takes it out of a folder or a list.
296	///
297	/// [technical design: spaces and moves]: ../../../../docs/Technical-design.md#131-spaces-and-moves
298	///
299	/// # Errors
300	///
301	/// As [`Library::move_entity`], for what a move refuses.
302	pub fn move_preview(
303		&self,
304		from: SpaceId,
305		entity: EntityId,
306		to: SpaceId,
307	) -> Result<MovePreview, NodeError> {
308		self.check_move(from, to)?;
309		self.space(from)?.stored.reading(|_| {
310			let entities = self.held_with(from, entity)?;
311			for &each in &entities {
312				self.check_movable(from, each)?;
313			}
314			let staying = self.staying_holders(from, &entities)?;
315			let (losing, purges_all) = self.losing_and_purging((from, to))?;
316			let (gaining, _) = self.losing_and_purging((to, from))?;
317			// Secret values here, or values that would be sealed there.
318			let state = self.space(from)?.stored.log().state();
319			let mut kinds = BTreeSet::new();
320			for &each in &entities {
321				kinds.extend(state.types(each)?);
322			}
323			let secret_there = self.secret_once_moved((from, to), &kinds)?;
324			let mut secrets = false;
325			for &each in &entities {
326				secrets |= self.may_hold_secrets(from, each)?;
327				for member in state.merged(each)? {
328					secrets |= state
329						.storage()
330						.of_entity(member)?
331						.iter()
332						.any(|(field, _)| secret_there.contains(field));
333				}
334			}
335			Ok(MovePreview {
336				entities,
337				staying,
338				losing,
339				gaining,
340				purges_all,
341				secrets,
342			})
343		})
344	}
345
346	/// Refuses a move from `from` to `to` that no entity may make: within one space, to a
347	/// space this library lacks, by an AI agent's replica, or by one revoked in either.
348	fn check_move(&self, from: SpaceId, to: SpaceId) -> Result<(), NodeError> {
349		if from == to {
350			return Err(NodeError::SameSpace);
351		}
352		self.space(from)?;
353		self.space(to)?;
354		self.check_not_ai_agent("move entities")?;
355		self.check_not_revoked(from)?;
356		self.check_not_revoked(to)
357	}
358
359	/// The entity that an entity of a space was moved into, and its space, following moves
360	/// onward, if this replica holds the space of where it is now: of several, as two moves
361	/// at the same time make, the one with the smallest ID. A mark whose entity this replica
362	/// holds nowhere is passed over.
363	///
364	/// # Errors
365	///
366	/// Returns an error if the library has no such space, or a space cannot be read.
367	pub fn moved_into(
368		&self,
369		space: SpaceId,
370		entity: EntityId,
371	) -> Result<Option<(SpaceId, EntityId)>, NodeError> {
372		let mut at = (space, entity);
373		let mut found = None;
374		for _ in 0..MOST_MOVES {
375			let Some(next) = self.moved_once(at.0, at.1)? else {
376				break;
377			};
378			if next == (space, entity) || found == Some(next) {
379				break;
380			}
381			found = Some(next);
382			at = next;
383		}
384		Ok(found)
385	}
386
387	/// The entities of the replica's other spaces that moved into an entity of `space`, or
388	/// into one merged into it there, each with its space, following moves back, as far as
389	/// [`Library::moved_into`] leads them to it.
390	///
391	/// # Errors
392	///
393	/// Returns an error if the library has no such space, or a space cannot be read.
394	pub fn moved_from(
395		&self,
396		space: SpaceId,
397		entity: EntityId,
398	) -> Result<Vec<(SpaceId, EntityId)>, NodeError> {
399		let state = self.space(space)?.stored.log().state();
400		let canonical = state.canonical(entity)?;
401		let mut found: Vec<(SpaceId, EntityId)> = Vec::new();
402		let mut reached: Vec<(SpaceId, EntityId)> = state
403			.merged(canonical)?
404			.into_iter()
405			.map(|member| (space, member))
406			.collect();
407		for _ in 0..MOST_MOVES {
408			let mut next = Vec::new();
409			for &(into, moved) in &reached {
410				for held in self.spaces() {
411					if held == into {
412						continue;
413					}
414					let marked = self
415						.space(held)?
416						.stored
417						.find(&fields::MOVED_INTO, &Value::Reference(moved))?;
418					for old in marked {
419						if held != space && !found.contains(&(held, old)) {
420							found.push((held, old));
421							next.push((held, old));
422						}
423					}
424				}
425			}
426			if next.is_empty() {
427				break;
428			}
429			reached = next;
430		}
431		let mut leading = Vec::new();
432		for (held, old) in found {
433			if let Some((there, now)) = self.moved_into(held, old)?
434				&& there == space
435				&& state.canonical(now)? == canonical
436			{
437				leading.push((held, old));
438			}
439		}
440		Ok(leading)
441	}
442
443	/// The entities that link to an entity of a space on `day`, as [`Library::links_to`]
444	/// gives them, together with those of the replica's other spaces that link to the
445	/// entities that moved into it, as a replica that holds both spaces shows them
446	/// ([technical design: spaces and moves]): but those whose new entities link to it here, as what moved
447	/// along does. Each field's count counts them all, and its entities are the first
448	/// `limit` by name.
449	///
450	/// [technical design: spaces and moves]: ../../../../docs/Technical-design.md#131-spaces-and-moves
451	///
452	/// # Errors
453	///
454	/// Returns an error if the library has no such space, or a space cannot be read.
455	pub fn links_to_anywhere(
456		&self,
457		space: SpaceId,
458		entity: EntityId,
459		day: nibkeep_time::Day,
460		limit: usize,
461	) -> Result<Vec<Links>, NodeError> {
462		let moved_from = self.moved_from(space, entity)?;
463		if moved_from.is_empty() {
464			return self.links_to(space, entity, day, limit);
465		}
466		let mut links = self.links_to(space, entity, day, usize::MAX)?;
467		let here: BTreeSet<EntityId> = links
468			.iter()
469			.flat_map(|links| links.entities.iter().map(|linking| linking.id))
470			.collect();
471		for (held, old) in moved_from {
472			for mut other in self.links_to(held, old, day, usize::MAX)? {
473				let mut kept = Vec::new();
474				for linking in other.entities {
475					let linked_here = self
476						.moved_into(held, linking.id)?
477						.is_some_and(|(there, now)| there == space && here.contains(&now));
478					if !linked_here {
479						kept.push(linking);
480					}
481				}
482				if kept.is_empty() {
483					continue;
484				}
485				other.count = kept.len();
486				other.entities = kept;
487				match links.iter_mut().find(|links| links.field == other.field) {
488					Some(same) => {
489						same.count += other.count;
490						same.entities.extend(other.entities);
491					}
492					None => links.push(other),
493				}
494			}
495		}
496		for group in &mut links {
497			group.entities.sort_by_key(|linking| {
498				(
499					linking.name.is_none(),
500					linking.name.as_deref().map(str::to_lowercase),
501					linking.id,
502				)
503			});
504			group.entities.truncate(limit);
505		}
506		Ok(links)
507	}
508
509	/// Where one move of an entity led, as [`Library::moved_into`] says, without following
510	/// further moves.
511	fn moved_once(
512		&self,
513		space: SpaceId,
514		entity: EntityId,
515	) -> Result<Option<(SpaceId, EntityId)>, NodeError> {
516		let state = self.space(space)?.stored.log().state();
517		let mut targets: Vec<EntityId> = state
518			.current(entity, &fields::MOVED_INTO)?
519			.iter()
520			.filter_map(|statement| statement.value.as_reference())
521			.collect();
522		targets.sort();
523		for target in targets {
524			for held in self.spaces() {
525				if held == space {
526					continue;
527				}
528				let there = self.space(held)?.stored.log().state();
529				if !there.fields(target)?.is_empty() {
530					return Ok(Some((held, target)));
531				}
532			}
533		}
534		Ok(None)
535	}
536
537	/// An entity's name, in the space it was moved into, if it was, or else in whichever
538	/// space holds it.
539	///
540	/// # Errors
541	///
542	/// Returns an error if a space cannot be read.
543	pub fn name_anywhere(&self, entity: EntityId) -> Result<Option<String>, NodeError> {
544		let Some(space) = self.space_of(entity)? else {
545			return Ok(None);
546		};
547		match self.moved_into(space, entity)? {
548			Some((there, moved)) => self.name(there, moved),
549			None => self.name(space, entity),
550		}
551	}
552
553	/// What a move takes of an entity of `from` to `to`, as [`Library::move_entity`] says,
554	/// and what it refuses.
555	fn to_move(
556		&self,
557		(from, to): (SpaceId, SpaceId),
558		entity: EntityId,
559		(history, secrets): (MoveHistory, MoveSecrets),
560	) -> Result<Taken, NodeError> {
561		self.space(from)?.stored.reading(|_| {
562			let held = self.held_with(from, entity)?;
563			let moving: BTreeSet<EntityId> = held.iter().copied().collect();
564			let mut taken = Taken {
565				entities: Vec::new(),
566				copies: Vec::new(),
567				contents: BTreeMap::new(),
568				kinds: BTreeSet::new(),
569				secret: BTreeSet::new(),
570			};
571			for each in held {
572				taken.kinds.extend(self.check_movable(from, each)?);
573				// Which values are secret is known only with the secrets unlocked.
574				if secrets == MoveSecrets::Bring
575					&& !self.secrets_unlocked(from)
576					&& self.may_hold_secrets(from, each)?
577				{
578					return Err(NodeError::MoveNeedsSecrets);
579				}
580				let carried = self.carried_of((from, to), each, (history, secrets), &moving)?;
581				taken.add(each, carried);
582			}
583			// The thumbnails of the content that moves go with it, as each belongs to a
584			// content (technical design: thumbnails); one that a file staying behind still
585			// shows is written there anew, and stays.
586			for (thumbnail, copied) in self.thumbnails_moving((from, &moving), &taken)? {
587				taken.kinds.extend(self.check_movable(from, thumbnail)?);
588				let carried =
589					self.carried_of((from, to), thumbnail, (history, secrets), &moving)?;
590				if copied {
591					taken.copy(thumbnail, carried);
592				} else {
593					taken.add(thumbnail, carried);
594				}
595			}
596			// Where a file's plain copies are, its origins and checkouts, go with it where
597			// their device is one of the user's own that holds the other space, so that the
598			// other space knows of them; the others are purged with what stays behind. Only
599			// those of a content that moves anyway, so that none brings a version that the
600			// move leaves behind.
601			for record in self.plain_copies_moving((from, to), &moving, &taken)? {
602				taken.kinds.extend(self.check_movable(from, record)?);
603				let carried = self.carried_of((from, to), record, (history, secrets), &moving)?;
604				taken.add(record, carried);
605			}
606			Ok(taken)
607		})
608	}
609
610	/// The origins and checkouts of the files of `from` that a move to `to` takes, those
611	/// merged into them included, that stand there, whose device is one of the user's own
612	/// that holds `to`, by the choices of a replica on it that is not revoked, and whose
613	/// content, if they recorded one, the move `taken` takes anyway, ordered by ID: where
614	/// those files' plain copies are, which the other space then knows of, and which their
615	/// device keeps checking there. Those of other devices, as other members', which this
616	/// replica cannot tell, or the user's that do not hold `to`, stay, and are purged with what
617	/// the move leaves behind; so are those of a version that the move leaves.
618	fn plain_copies_moving(
619		&self,
620		(from, to): (SpaceId, SpaceId),
621		moving: &BTreeSet<EntityId>,
622		taken: &Taken,
623	) -> Result<Vec<EntityId>, NodeError> {
624		let personal = self.space(self.info.personal)?.stored.log().state();
625		let devices = self.holding_devices(to)?;
626		let open = self.space(from)?;
627		let state = open.stored.log().state();
628		let mut files = BTreeSet::new();
629		for &each in moving {
630			files.extend(state.merged(each)?);
631		}
632		let mut moving_along = Vec::new();
633		for (record, moved, deleted) in self.plain_copies_of(from, &files)? {
634			if moved || deleted {
635				continue;
636			}
637			let device = state
638				.current(record, &FOUND_ON)?
639				.into_iter()
640				.chain(state.current(record, &CHECKED_OUT_ON)?)
641				.find_map(|statement| statement.value.as_reference());
642			let Some(device) = device else {
643				continue;
644			};
645			let content = state
646				.current(record, &CONTENT)?
647				.into_iter()
648				.find_map(|statement| match statement.value {
649					Value::Blob(content) => Some(content),
650					_ => None,
651				});
652			if devices.contains(&personal.canonical(device)?)
653				&& content.is_none_or(|content| taken.contents.contains_key(&content))
654			{
655				moving_along.push(record);
656			}
657		}
658		Ok(moving_along)
659	}
660
661	/// The origins and checkouts of a space that name one of `entities`, as given, each once
662	/// as the entity it shows as, with whether it moved and whether it is deleted, ordered by
663	/// ID.
664	pub(crate) fn plain_copies_of(
665		&self,
666		space: SpaceId,
667		entities: &BTreeSet<EntityId>,
668	) -> Result<Vec<(EntityId, bool, bool)>, NodeError> {
669		let open = self.space(space)?;
670		let state = open.stored.log().state();
671		let mut found = BTreeMap::new();
672		for &entity in entities {
673			for field in [&ORIGIN_OF, &CHECKOUT_OF] {
674				for statement in state.referrers_in(entity, field)? {
675					let record = state.canonical(statement.entity)?;
676					if entities.contains(&record) {
677						continue;
678					}
679					let moved = !state.current(record, &fields::MOVED_INTO)?.is_empty();
680					found.insert(record, (moved, state.is_deleted(record)?));
681				}
682			}
683		}
684		Ok(found
685			.into_iter()
686			.map(|(record, (moved, deleted))| (record, moved, deleted))
687			.collect())
688	}
689
690	/// The thumbnails of `from` made of the content that a move takes as a file's ordinary
691	/// content, that are neither deleted nor moved already, nor moving otherwise, ordered by
692	/// ID; each with whether a file that stays in `from` shows it still, so that it is
693	/// written anew in the other space rather than moved. The content of a secret field has
694	/// no thumbnail to take, even where an ordinary file has the same content.
695	fn thumbnails_moving(
696		&self,
697		(from, moving): (SpaceId, &BTreeSet<EntityId>),
698		taken: &Taken,
699	) -> Result<Vec<(EntityId, bool)>, NodeError> {
700		let open = self.space(from)?;
701		let state = open.stored.log().state();
702		let gone =
703			|entity: EntityId| -> Result<bool, NodeError> {
704				Ok(state.is_deleted(entity)?
705					|| !state.current(entity, &fields::MOVED_INTO)?.is_empty())
706			};
707		let mut thumbnails = BTreeMap::new();
708		for (content, (holding, _)) in &taken.contents {
709			if !holding.contains(&CONTENT) || open.stored.secret_fields().contains(&CONTENT) {
710				continue;
711			}
712			let mut staying = false;
713			for file in open.stored.find(&CONTENT, &Value::Blob(*content))? {
714				let file = state.canonical(file)?;
715				staying |=
716					!moving.contains(&file) && state.types(file)?.contains(&FILE) && !gone(file)?;
717			}
718			for thumbnail in open.stored.find(&THUMBNAIL_OF, &Value::Blob(*content))? {
719				let thumbnail = state.canonical(thumbnail)?;
720				if !moving.contains(&thumbnail)
721					&& state.types(thumbnail)?.contains(&THUMBNAIL)
722					&& !gone(thumbnail)?
723				{
724					*thumbnails.entry(thumbnail).or_insert(false) |= staying;
725				}
726			}
727		}
728		Ok(thumbnails.into_iter().collect())
729	}
730
731	/// Whether an entity of a space holds secret values, as far as this replica can tell: a
732	/// value it opened, or a value written before its field was secret; or, while the space's
733	/// secrets are locked, which hides which entity a sealed value is of, a field secret
734	/// there that its types list.
735	///
736	/// # Errors
737	///
738	/// Returns an error if the library has no such space, or it cannot be read.
739	pub fn may_hold_secrets(&self, space: SpaceId, entity: EntityId) -> Result<bool, NodeError> {
740		let open = self.space(space)?;
741		let state = open.stored.log().state();
742		let storage = state.storage();
743		let secret = open.stored.secret_fields();
744		for member in state.merged(entity)? {
745			for (field, ids) in storage.of_entity(member)? {
746				if secret.contains(&field) {
747					return Ok(true);
748				}
749				for id in ids {
750					if storage.is_secret(id)? {
751						return Ok(true);
752					}
753				}
754			}
755		}
756		if self.secrets_unlocked(space) {
757			return Ok(false);
758		}
759		let kinds: Vec<TypeName> = state.types(entity)?.into_iter().collect();
760		Ok(!self.secret_fields_of(space, &kinds)?.is_empty())
761	}
762
763	/// The fields secret in `to` once a move from `from` defined there the types given, as
764	/// `from` defines them: a field that one of them makes secret is secret, whatever the
765	/// other types say.
766	fn secret_once_moved(
767		&self,
768		(from, to): (SpaceId, SpaceId),
769		kinds: &BTreeSet<TypeName>,
770	) -> Result<BTreeSet<FieldName>, NodeError> {
771		let mut secret_there = self.space(to)?.stored.secret_fields().clone();
772		let source_types = &self.space(from)?.types;
773		for kind in kinds {
774			if let Some(definition) = source_types.get(kind) {
775				secret_there.extend(
776					definition
777						.fields()
778						.filter(|(_, field)| field.is_secret())
779						.map(|(name, _)| name.clone()),
780				);
781			}
782		}
783		Ok(secret_there)
784	}
785
786	/// Refuses, before anything is written, a move of content that is not on this device,
787	/// as neither space holds a copy, nor was it found here.
788	fn check_contents_here(
789		&self,
790		(from, to): (SpaceId, SpaceId),
791		taken: &Taken,
792	) -> Result<(), NodeError> {
793		let (source, target) = (&self.space(from)?.stored, &self.space(to)?.stored);
794		for (content, (_, now)) in &taken.contents {
795			if *now
796				&& !source.holds_blob(content)
797				&& !target.holds_blob(content)
798				&& self.originals_here(from, content)?.is_empty()
799			{
800				return Err(NodeError::NotHere(content.to_string()));
801			}
802		}
803		Ok(())
804	}
805
806	/// Refuses, before anything is written, a move of secret values that would not stay
807	/// secret in `to`, where a field secret in `from` would be plain and this replica's
808	/// member may not make it secret; and makes sure that this replica seals in `to` what will
809	/// be secret there: its secrets unlocked, or set up there now, if no other replica holds
810	/// them and its member may.
811	fn prepare_secrets(
812		&mut self,
813		(from, to): (SpaceId, SpaceId),
814		taken: &Taken,
815		wall_millis: u64,
816		rng: &mut impl CryptoRng,
817	) -> Result<(), NodeError> {
818		let secret_there = self.secret_once_moved((from, to), &taken.kinds)?;
819		if let Some(field) = taken.secret.difference(&secret_there).next()
820			&& !self.may_mark_secret(to)?
821		{
822			return Err(NodeError::NotSecretThere(field.clone()));
823		}
824		let sealed_there = taken.entities.iter().any(|(_, carried)| {
825			carried.iter().any(|statement| {
826				let field = &statement.statement.field;
827				secret_there.contains(field) || taken.secret.contains(field)
828			})
829		});
830		if !sealed_there || self.secrets_unlocked(to) {
831			return Ok(());
832		}
833		if to == self.info.personal {
834			return Err(NodeError::MoveNeedsSecrets);
835		}
836		self.set_up_space_secrets(to, wall_millis, rng)
837	}
838
839	/// Whether this replica's member may make a field of a space secret for good: in the
840	/// personal space, or a space without members, or as an admin.
841	fn may_mark_secret(&self, space: SpaceId) -> Result<bool, NodeError> {
842		Ok(space == self.info.personal
843			|| !self.has_members(space)?
844			|| self.check_admin(space, "make a field secret").is_ok())
845	}
846
847	/// Makes the fields of secret values that a move brings secret for good in `to`, where
848	/// they are not secret already, in a change that governs the space.
849	fn keep_secret(
850		&mut self,
851		to: SpaceId,
852		secret: &BTreeSet<FieldName>,
853		wall_millis: u64,
854		rng: &mut impl CryptoRng,
855	) -> Result<(), NodeError> {
856		let open = self.space(to)?;
857		let missing: Vec<FieldName> = secret
858			.difference(open.stored.secret_fields())
859			.cloned()
860			.collect();
861		let Some(first) = missing.first().cloned() else {
862			return Ok(());
863		};
864		if !self.may_mark_secret(to)? {
865			return Err(NodeError::NotSecretThere(first));
866		}
867		let own = self.own_record(to)?;
868		let operations = open.secret_marks(&self.code_types, (own, missing), rng)?;
869		if operations.is_empty() {
870			return Err(NodeError::NotSecretThere(first));
871		}
872		self.commit(to, operations, wall_millis, rng)?;
873		// The fields that the change made secret are secret from now on.
874		self.read_again(to)?;
875		if self.space(to)?.stored.secret_fields().contains(&first) {
876			Ok(())
877		} else {
878			Err(NodeError::NotSecretThere(first))
879		}
880	}
881
882	/// The entity, as merges make it canonical, and the folders, lists, memberships and
883	/// members that it holds, and the files attached to it and to nothing else that stays,
884	/// through every level, each once, but those deleted or moved already, the entity first.
885	/// What names an entity merged into a folder or a list is in it too. A tree, or what is in one, moves only whole, which waits until trees are
886	/// shared, so it is refused; and a membership moves only with its list.
887	fn held_with(&self, from: SpaceId, entity: EntityId) -> Result<Vec<EntityId>, NodeError> {
888		let open = self.space(from)?;
889		let state = open.stored.log().state();
890		let given = state.canonical(entity)?;
891		if state.fields(given)?.is_empty() || state.is_deleted(given)? {
892			return Err(NodeError::NoEntity(given.to_string()));
893		}
894		if state.types(given)?.contains(&MEMBERSHIP) {
895			return Err(NodeError::OwnRecord(given.to_string()));
896		}
897		if self.moved_into(from, given)?.is_some() {
898			return Err(NodeError::MovedAlready);
899		}
900		let naming = |field: &FieldName, each: EntityId| -> Result<Vec<EntityId>, NodeError> {
901			let mut found = Vec::new();
902			for member in state.merged(each)? {
903				found.extend(open.stored.find(field, &Value::Reference(member))?);
904			}
905			Ok(found)
906		};
907		let mut held = Vec::new();
908		let mut seen = BTreeSet::new();
909		let mut waiting = VecDeque::from([given]);
910		while let Some(next) = waiting.pop_front() {
911			let each = state.canonical(next)?;
912			if !seen.insert(each) {
913				continue;
914			}
915			if each != given
916				&& (state.fields(each)?.is_empty()
917					|| state.is_deleted(each)?
918					|| self.moved_into(from, each)?.is_some())
919			{
920				continue;
921			}
922			if state.fields(each)?.contains(&IN_TREE) || !naming(&IN_TREE, each)?.is_empty() {
923				return Err(NodeError::TreeStays(each.to_string()));
924			}
925			held.push(each);
926			waiting.extend(naming(&IN_FOLDER, each)?);
927			// A file attached to it, as an app shows it in it, unless attached to something
928			// else that stays too: one deleted, or moved already, stays nowhere.
929			for file in naming(&ATTACHED_TO, each)? {
930				let file = state.canonical(file)?;
931				let mut alone = true;
932				for statement in state.current(file, &ATTACHED_TO)? {
933					let Some(other) = statement.value.as_reference() else {
934						continue;
935					};
936					let other = state.canonical(other)?;
937					if other != each
938						&& !held.contains(&other)
939						&& !waiting.contains(&other)
940						&& !state.fields(other)?.is_empty()
941						&& !state.is_deleted(other)?
942						&& self.moved_into(from, other)?.is_none()
943					{
944						alone = false;
945						break;
946					}
947				}
948				if alone {
949					waiting.push_back(file);
950				}
951			}
952			for membership in naming(&fields::LIST, each)? {
953				let membership = state.canonical(membership)?;
954				if !state.types(membership)?.contains(&MEMBERSHIP)
955					|| state.is_deleted(membership)?
956				{
957					continue;
958				}
959				waiting.push_back(membership);
960				waiting.extend(
961					state
962						.current(membership, &fields::ITEM)?
963						.iter()
964						.filter_map(|statement| statement.value.as_reference()),
965				);
966			}
967		}
968		Ok(held)
969	}
970
971	/// The types of an entity of `from` that a move may take, or why it may not: one of the
972	/// library's own records.
973	fn check_movable(
974		&self,
975		from: SpaceId,
976		entity: EntityId,
977	) -> Result<BTreeSet<TypeName>, NodeError> {
978		let open = self.space(from)?;
979		let state = open.stored.log().state();
980		let kinds = state.types(entity)?;
981		if OWN_RECORDS.iter().any(|own| kinds.contains(own))
982			|| kinds
983				.iter()
984				.any(|kind| kind.as_str().starts_with("org.nibkeep.") && *kind != MEMBERSHIP)
985		{
986			return Err(NodeError::OwnRecord(entity.to_string()));
987		}
988		Ok(kinds)
989	}
990
991	/// The statements that a move from `from` to `to` carries of an entity: with
992	/// [`MoveHistory::Bring`], every statement that the entity and those merged into it have
993	/// held, current or replaced, with when the space recorded each, by whom, and when it was
994	/// replaced; otherwise, its current ones. Either way, not whether it is deleted, merged or
995	/// moved; of a field whose last writer wins, only the value it shows; none that puts it
996	/// in a folder that stays, as that finds it through its mark; and, with
997	/// [`MoveSecrets::Leave`], no secret value, sealed or of a field secret in `from`. Secret
998	/// values are carried as far as this replica opened them. References are to the entities
999	/// as merges make them canonical, so that those to what moves along lead to it, and those
1000	/// to an entity that moved to `to` already, to that one there.
1001	fn carried_of(
1002		&self,
1003		(from, to): (SpaceId, SpaceId),
1004		entity: EntityId,
1005		(history, secrets): (MoveHistory, MoveSecrets),
1006		moving: &BTreeSet<EntityId>,
1007	) -> Result<Vec<Carried>, NodeError> {
1008		let open = self.space(from)?;
1009		let log = open.stored.log();
1010		let state = log.state();
1011		let storage = state.storage();
1012		let last_writer_wins = open.types.last_writer_wins_fields();
1013		let secret_here = open.stored.secret_fields();
1014		let mut carried = Vec::new();
1015		for member in state.merged(entity)? {
1016			for (field, ids) in storage.of_entity(member)? {
1017				if [
1018					fields::DELETED,
1019					fields::MERGED_INTO,
1020					fields::MOVED_INTO,
1021					fields::PURGE_ASKED,
1022				]
1023				.contains(&field)
1024				{
1025					continue;
1026				}
1027				let shown = if last_writer_wins.contains(&field) {
1028					state
1029						.last_written(entity, &field)?
1030						.map(|statement| statement.id)
1031				} else {
1032					None
1033				};
1034				for id in ids {
1035					if last_writer_wins.contains(&field) && shown != Some(id) {
1036						continue;
1037					}
1038					let Some(recorded) = storage.get(id)? else {
1039						continue;
1040					};
1041					let replaced = storage.superseded_at(id)?;
1042					if history == MoveHistory::Leave && replaced.is_some() {
1043						continue;
1044					}
1045					let secret = secret_here.contains(&field) || storage.is_secret(id)?;
1046					if secret && secrets == MoveSecrets::Leave {
1047						continue;
1048					}
1049					let mut statement = recorded.statement.into_owned();
1050					let mut there = false;
1051					if let Value::Reference(target) = statement.value {
1052						let target = state.canonical(target)?;
1053						statement.value = Value::Reference(target);
1054						if !moving.contains(&target)
1055							&& let Some((space, now)) = self.moved_into(from, target)?
1056							&& space == to
1057						{
1058							statement.value = Value::Reference(now);
1059							there = true;
1060						}
1061					}
1062					if replaced.is_none()
1063						&& statement.field == IN_FOLDER
1064						&& !there
1065						&& statement
1066							.value
1067							.as_reference()
1068							.is_some_and(|folder| !moving.contains(&folder))
1069					{
1070						continue;
1071					}
1072					let (recorded, author) = match history {
1073						MoveHistory::Bring => (Some(recorded.at), log.author_of(id)?),
1074						MoveHistory::Leave => (None, None),
1075					};
1076					carried.push(Carried {
1077						statement,
1078						secret,
1079						recorded,
1080						author,
1081						replaced,
1082					});
1083				}
1084			}
1085		}
1086		Ok(carried)
1087	}
1088
1089	/// The folders and lists of `from` that stay and hold some of these entities, which move.
1090	fn staying_holders(
1091		&self,
1092		from: SpaceId,
1093		entities: &[EntityId],
1094	) -> Result<Vec<EntityId>, NodeError> {
1095		let open = self.space(from)?;
1096		let state = open.stored.log().state();
1097		let moving: BTreeSet<EntityId> = entities.iter().copied().collect();
1098		let mut staying = BTreeSet::new();
1099		for &entity in entities {
1100			for statement in &state.current(entity, &IN_FOLDER)? {
1101				if let Some(folder) = statement.value.as_reference() {
1102					staying.insert(state.canonical(folder)?);
1103				}
1104			}
1105			for membership in open.stored.find(&fields::ITEM, &Value::Reference(entity))? {
1106				let membership = state.canonical(membership)?;
1107				if !state.types(membership)?.contains(&MEMBERSHIP)
1108					|| state.is_deleted(membership)?
1109				{
1110					continue;
1111				}
1112				for statement in &state.current(membership, &fields::LIST)? {
1113					if let Some(list) = statement.value.as_reference() {
1114						staying.insert(state.canonical(list)?);
1115					}
1116				}
1117			}
1118		}
1119		// A holder that moved already is no longer here.
1120		let mut here = Vec::new();
1121		for holder in staying {
1122			if !moving.contains(&holder) && self.moved_into(from, holder)?.is_none() {
1123				here.push(holder);
1124			}
1125		}
1126		Ok(here)
1127	}
1128
1129	/// Gives a blob of one space to another, with a key of the kind given, secret or
1130	/// ordinary, unless that one holds it so already: the copy that the first holds with a key
1131	/// of that kind, whose key is wrapped for the second once the copy was read whole, as a
1132	/// replica keeps one sealed copy of each content, reusing keys only within their kind
1133	/// ([technical design: spaces and moves]); or else, as where the second purged that copy, or the first
1134	/// holds none of that kind, sealed anew for the second from a copy that the first holds,
1135	/// or from where it was found on this device, unless a third space holds a copy of that
1136	/// kind that the second takes up.
1137	///
1138	/// [technical design: spaces and moves]: ../../../../docs/Technical-design.md#131-spaces-and-moves
1139	fn copy_blob(
1140		&mut self,
1141		from: SpaceId,
1142		content: &Hash,
1143		(to, secret): (SpaceId, bool),
1144		wall_millis: u64,
1145		rng: &mut impl CryptoRng,
1146	) -> Result<(), NodeError> {
1147		if !self
1148			.space(to)?
1149			.stored
1150			.held_copies(content, secret)
1151			.is_empty()
1152		{
1153			return Ok(());
1154		}
1155		let held = self.space(from)?.stored.holds_blob(content);
1156		let originals = if held {
1157			Vec::new()
1158		} else {
1159			self.originals_here(from, content)?
1160		};
1161		let mut target = self.spaces.remove(&to).ok_or(NodeError::NoSpace(to))?;
1162		let copied = (|| {
1163			let source = self.space(from)?;
1164			for (sealed, key) in source.stored.held_copies(content, secret) {
1165				let shared = target.stored.share_blob(
1166					&target.keys,
1167					content,
1168					(sealed, &key),
1169					secret,
1170					wall_millis,
1171					rng,
1172				)?;
1173				if shared {
1174					return Ok(());
1175				}
1176			}
1177			// A copy of a third space, as those of the first were tried already.
1178			let others = &self.spaces;
1179			let elsewhere = |content: &Hash| {
1180				held_copies_in(
1181					others
1182						.iter()
1183						.filter(|(id, _)| **id != from)
1184						.map(|(_, open)| open),
1185					content,
1186					secret,
1187				)
1188			};
1189			let sealed = if held {
1190				let reader = source.stored.open_blob(content)?;
1191				target.stored.import_blob_sharing(
1192					&target.keys,
1193					(reader, secret),
1194					&elsewhere,
1195					wall_millis,
1196					rng,
1197				)?
1198			} else {
1199				let mut sealed = None;
1200				for original in &originals {
1201					if let Ok(file) = File::open(original) {
1202						sealed = Some(target.stored.import_blob_sharing(
1203							&target.keys,
1204							(file, secret),
1205							&elsewhere,
1206							wall_millis,
1207							rng,
1208						)?);
1209						break;
1210					}
1211				}
1212				sealed.ok_or_else(|| NodeError::NotHere(content.to_string()))?
1213			};
1214			if sealed == *content {
1215				Ok(())
1216			} else {
1217				Err(NodeError::NotHere(content.to_string()))
1218			}
1219		})();
1220		self.spaces.insert(to, target);
1221		copied
1222	}
1223}
1224
1225/// The operations that write the statements that a move carries of an entity on its new
1226/// entity `new`: under new IDs, drawn in the order of the old ones, so that values whose
1227/// order their IDs make keep it; each form of a value naming its first form by the first
1228/// form's new ID; references to what moves along leading to its new entity, as `moved` maps
1229/// them; and, with [`MoveHistory::Bring`], the mover's note of the space it came from, when
1230/// that space recorded it and by whom, and when it was replaced there, unless a note of an
1231/// earlier move tells it already, which stays whole; and the replaced ones replaced again.
1232fn carried_operations(
1233	carried: &[Carried],
1234	(new, moved): (EntityId, &BTreeMap<EntityId, EntityId>),
1235	(from, history): (SpaceId, MoveHistory),
1236	rng: &mut impl CryptoRng,
1237) -> Vec<Operation> {
1238	let mut carried: Vec<&Carried> = carried.iter().collect();
1239	carried.sort_by_key(|each| each.statement.id);
1240	let mut ids: Vec<StatementId> = carried.iter().map(|_| StatementId::random(rng)).collect();
1241	ids.sort();
1242	let renamed: BTreeMap<StatementId, StatementId> = carried
1243		.iter()
1244		.zip(&ids)
1245		.map(|(each, id)| (each.statement.id, *id))
1246		.collect();
1247	let mut operations = Vec::new();
1248	let mut replaced = Vec::new();
1249	for (each, id) in carried.into_iter().zip(ids) {
1250		let mut qualifiers = each.statement.qualifiers.clone();
1251		if let Some(first) = qualifiers.alternative()
1252			&& let Some(new) = renamed.get(&first)
1253		{
1254			let alternative: FieldName = fields::ALTERNATIVE;
1255			qualifiers.insert(alternative, Value::Text(new.to_string()));
1256		}
1257		if history == MoveHistory::Bring {
1258			let millis =
1259				|at: Timestamp| Value::Integer(i64::try_from(at.millis()).unwrap_or(i64::MAX));
1260			// A note of an earlier move stays whole: it tells of the space that the value came
1261			// from first, not of this one.
1262			if qualifiers.get(&fields::CARRIED_FROM).is_none() {
1263				qualifiers.insert(fields::CARRIED_FROM, Value::Text(from.to_string()));
1264				if let Some(author) = &each.author {
1265					qualifiers.insert(fields::CARRIED_BY, Value::Text(author.to_text()));
1266				}
1267				if let Some(at) = each.recorded {
1268					qualifiers.insert(fields::CARRIED_AT, millis(at));
1269				}
1270				if let Some(at) = each.replaced {
1271					qualifiers.insert(fields::CARRIED_REPLACED, millis(at));
1272				}
1273			}
1274		}
1275		let value = match &each.statement.value {
1276			Value::Reference(target) => {
1277				Value::Reference(moved.get(target).copied().unwrap_or(*target))
1278			}
1279			value => value.clone(),
1280		};
1281		operations.push(Operation::assert(Statement {
1282			id,
1283			entity: new,
1284			field: each.statement.field.clone(),
1285			value,
1286			qualifiers,
1287		}));
1288		if each.replaced.is_some() {
1289			replaced.push(id);
1290		}
1291	}
1292	if !replaced.is_empty() {
1293		operations.push(Operation::retract(new, replaced));
1294	}
1295	operations
1296}