Skip to main content

nibkeep_cli/
lib.rs

1//! `nib`, the generic command-line tool for NibKeep.
2//!
3//! The commands run on an [`Environment`], which gives them randomness, the time, prompts
4//! for passphrases and the platform's keystore, so that tests can run every command in the
5//! test process. The reasons for the tool's shape are in `docs/Technical-design.md`,
6//! section 16.
7
8mod clients;
9mod environment;
10mod mcp;
11mod output;
12mod trees;
13mod types;
14
15pub use trees::TreeCommand;
16
17use std::cell::RefCell;
18use std::collections::BTreeMap;
19use std::io::{self, Write};
20use std::path::{Path, PathBuf};
21use std::sync::Arc;
22use std::sync::atomic::AtomicBool;
23use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
24
25use clap::{Args, Parser, Subcommand, ValueEnum};
26use getrandom::SysRng;
27use getrandom::rand_core::UnwrapErr;
28use nibkeep_base::{EntityId, SpaceId};
29use nibkeep_crypto::RecoveryCode;
30use nibkeep_model::{FieldName, Languages, ParseLanguagesError, Tag, TypeName};
31use nibkeep_node::{
32	Backup, BackupEdit, DeviceRole, Kept, MoveHistory, MoveSecrets, Needs, NewBackup, NewRule,
33	Place, PolicyEdit, at_login,
34};
35use nibkeep_node::{Checkout, Dating, Edit, EntityView, LanguagesFor, NewLibrary};
36use nibkeep_node::{
37	Holding, KeysError, Library, MemberRole, NewProtection, NodeError, PairingCode, Protection,
38	Replica, Role, SecretsState, Unlocker,
39};
40use nibkeep_std::{FILE, PHOTO, VIDEO};
41use nibkeep_time::{Day, Edtf};
42
43pub use environment::{
44	Account, Environment, Firewall, System, clear_git_variables, platform_keystore,
45};
46pub use mcp::McpServer;
47use nibkeep_node::pointer::{
48	self, Found, LIBRARY_DATA, PointerError, holds_library,
49	resolved_as_far_as_it_exists as resolved,
50};
51
52/// The service name under which the platform's keystore holds the keys of libraries.
53use nibkeep_node::KEYSTORE_SERVICE;
54
55/// The name of the replica that `nib` keeps, after the app.
56const APP: &str = "nib";
57
58/// What is wrong with a `.nib` file, as nib says it.
59impl From<PointerError> for CliError {
60	fn from(error: PointerError) -> Self {
61		match error {
62			PointerError::Bad { file, why } => Self::BadPointer { file, why },
63			PointerError::Stray { file, library } => Self::StrayPointer { file, library },
64			PointerError::InTheWay(file) => Self::PointerInTheWay(file),
65			PointerError::NotWritten { file, error } => Self::PointerNotWritten { file, error },
66			PointerError::NotTakenAway { file, error } => Self::PointerNotTakenAway { file, error },
67			PointerError::Library(error) => error.into(),
68		}
69	}
70}
71
72/// nib: structured data and files, on your own devices.
73#[derive(Debug, Parser)]
74// The name, not the program's file, in usage lines: `nib.exe` on Windows.
75#[command(name = "nib", bin_name = "nib", version = env!("NIB_VERSION"), about)]
76pub struct Cli {
77	/// The library to work in: a folder that holds one in its folder `.nib`. Without it,
78	/// the library whose folder the current folder is, or is in; or that the `.nib` file of
79	/// the tree whose folder it is, or is in, names; or else, outside every library's folder,
80	/// the one that the environment variable `NIBKEEP_LIBRARY` names.
81	#[arg(long, global = true, value_name = "FOLDER")]
82	pub library: Option<PathBuf>,
83	/// The space to add to, and to look for entities in: by its name or the start of its ID,
84	/// as nib space list shows them. Without it, new entities go to your personal space,
85	/// and an entity is found in whichever space holds it.
86	#[arg(long, global = true, value_name = "SPACE")]
87	pub space: Option<String>,
88	/// Prints JSON instead of text, for scripts.
89	#[arg(long, global = true)]
90	pub json: bool,
91	/// Prints to standard error how long the command's parts took: unlocking the keys,
92	/// opening the spaces, the work and printing. For measuring nib, so not listed.
93	#[arg(long, global = true, hide = true)]
94	pub timings: bool,
95	/// Reads the library's passphrase from the first line of this file instead of asking for
96	/// it, for scripts. Nobody else may be able to read the file. The passphrase of the
97	/// library's secrets is asked for all the same.
98	#[arg(
99		long,
100		global = true,
101		value_name = "FILE",
102		env = "NIBKEEP_PASSPHRASE_FILE"
103	)]
104	pub passphrase_file: Option<PathBuf>,
105	/// What to do.
106	#[command(subcommand)]
107	pub command: Command,
108}
109
110impl Cli {
111	/// How the endpoint of nib starts: on the home network, taking connections at the port
112	/// that the command asks for, or only making them, from any free port.
113	fn network(&self, accept: bool) -> nibkeep_node::NetworkOptions {
114		let port = match &self.command {
115			Command::Sync { port, .. } if accept => *port,
116			Command::Device {
117				command: DeviceCommand::Pair { port, .. },
118			}
119			| Command::Space {
120				command: SpaceCommand::Invite { port, .. },
121			} if accept => port.port,
122			_ => 0,
123		};
124		nibkeep_node::NetworkOptions {
125			discovery: true,
126			port: (port != 0).then_some(port),
127			accept,
128		}
129	}
130}
131
132/// The UDP port that a command takes connections on.
133#[derive(Debug, Args)]
134pub struct Port {
135	/// The UDP port to take connections on, for a firewall to let through: the first free of
136	/// the ten from it, then any; any with 0.
137	#[arg(
138		long,
139		value_name = "PORT",
140		env = "NIBKEEP_PORT",
141		default_value_t = nibkeep_node::DEFAULT_PORT
142	)]
143	pub port: u16,
144}
145
146/// The commands that `nib --help` lists, by what they work on, in place of clap's one list.
147const OVERVIEW: &[(&str, &[&str])] = &[
148	(
149		"Library",
150		&[
151			"init",
152			"status",
153			"verify",
154			"languages",
155			"protect",
156			"export",
157			"import",
158		],
159	),
160	(
161		"Entities",
162		&[
163			"new", "show", "edit", "list", "find", "history", "merge", "move", "purge", "type",
164		],
165	),
166	(
167		"Trees",
168		&[
169			"commit", "mv", "rm", "log", "diff", "blame", "restore", "revert", "update", "pull",
170			"clone",
171		],
172	),
173	("Files and secrets", &["file", "policy", "secret"]),
174	("Devices and sharing", &["sync", "device", "space", "mcp"]),
175	("Safekeeping", &["backup", "recovery", "purges"]),
176];
177
178/// `nib`'s commands as clap knows them, with `nib --help` listing them by what they work on,
179/// and the other names that some answer to.
180#[must_use]
181pub fn command() -> clap::Command {
182	use clap::CommandFactory;
183	use std::fmt::Write as _;
184	let command = Cli::command();
185	let styles = command.get_styles();
186	let (header, literal) = (styles.get_header(), styles.get_literal());
187	let width = OVERVIEW
188		.iter()
189		.flat_map(|(_, names)| names.iter())
190		.map(|name| name.len())
191		.max()
192		.unwrap_or(0);
193	let mut overview = String::new();
194	let mut aliases = Vec::new();
195	for (heading, names) in OVERVIEW {
196		let _ = writeln!(overview, "{header}{heading}:{header:#}");
197		for name in *names {
198			let about = command
199				.find_subcommand(name)
200				.and_then(clap::Command::get_about)
201				.map_or_else(String::new, ToString::to_string);
202			let _ = writeln!(overview, "  {literal}{name:width$}{literal:#}  {about}");
203			if let Some(sub) = command.find_subcommand(name) {
204				aliases.extend(
205					sub.get_visible_aliases()
206						.map(|alias| format!("{alias} for {name}")),
207				);
208			}
209		}
210		overview.push('\n');
211	}
212	if !aliases.is_empty() {
213		// Wrapped to the width of a terminal, as the lines above fit it, never within the
214		// words for one command.
215		let last = aliases.len() - 1;
216		let words =
217			"Other names, as other version control systems have them:"
218				.split(' ')
219				.map(str::to_owned)
220				.chain(aliases.iter().enumerate().map(|(index, alias)| {
221					format!("{alias}{}", if index == last { "." } else { "," })
222				}));
223		let mut line = String::new();
224		for word in words {
225			if !line.is_empty() && line.len() + 1 + word.len() > 80 {
226				overview.push_str(&line);
227				overview.push('\n');
228				line.clear();
229			}
230			if !line.is_empty() {
231				line.push(' ');
232			}
233			line.push_str(&word);
234		}
235		overview.push_str(&line);
236		overview.push('\n');
237	}
238	overview.push_str("nib help COMMAND, or nib COMMAND --help, tells more of each.\n\n");
239	// The overview holds no braces, which the template would take for its own tags.
240	let template = format!(
241		"{{before-help}}{{about-with-newline}}\n{{usage-heading}} {{usage}}\n\n{overview}{header}Options:{header:#}\n{{options}}{{after-help}}"
242	);
243	command.help_template(template)
244}
245
246/// The environment's wall clock as it moves on: its time now, moved on as the system's wall
247/// clock moves, so that a command that waits makes and checks changes at the time they
248/// happen, and one that runs for days, through the computer's sleeps, records the times of
249/// syncs as the other programs on the replica read theirs.
250fn clock<E: Environment>(environment: &E) -> impl Fn() -> u64 + use<E> {
251	let system = || {
252		SystemTime::now()
253			.duration_since(UNIX_EPOCH)
254			.map_or(0, |since| {
255				i128::try_from(since.as_millis()).unwrap_or(i128::MAX)
256			})
257	};
258	let offset = i128::from(environment.now()) - system();
259	move || u64::try_from(system() + offset).unwrap_or(0)
260}
261
262/// What `nib` can do.
263#[derive(Debug, Subcommand)]
264pub enum Command {
265	/// Makes a library, once on each computer, or a folder in one a tree.
266	///
267	/// Where no library is found, in the folders it is in, or named by --library or
268	/// `NIBKEEP_LIBRARY`, makes the current folder, or the one --library names, a library: you
269	/// as its user, named after your account on this computer, as `whoami` prints it, or as
270	/// --name says, linked to a person with your full name, if the system knows it, this
271	/// device, and a personal space. The library keeps them in the folder `.nib`; the rest of
272	/// the folder is yours, for your files. With --join, makes it a copy of a library you have
273	/// on another device instead: there, nib device pair shows the code to give. A library is
274	/// brought back with nib recovery restore.
275	///
276	/// In a library's folder, or with the library that --library or `NIBKEEP_LIBRARY` names,
277	/// makes the current folder, or the one given, a tree, as `git init` does: NibKeep keeps
278	/// every version of its files, by their paths, and nib commit records them. The folder
279	/// given may be anywhere: its own library, if it is in one, or else the current folder's,
280	/// keeps it. A tree's folder outside the library's gets a file `.nib` that names the
281	/// library, by which nib finds it there; for a tree that lost the file, init writes it
282	/// again. Its files
283	/// become the tree's copies, committed as its first revision: a purge of a file's content
284	/// deletes its copy where it was not edited, so it asks first. What `.nibignore` files
285	/// name is left out, in Git's syntax for `.gitignore`, and always `.nib`, every `.git`,
286	/// and the inside of folders that hold Git repositories. A tree is never inside another,
287	/// nor started in a folder that holds a Git repository. Files such as `.env` and private
288	/// keys, and what `.nibsecret` files name, go in as secret files, sealed for the secrets,
289	/// whose passphrase it asks for, or sets up.
290	#[command(group(
291		clap::ArgGroup::new("making")
292			.args(["name", "join", "device", "passphrase", "languages", "allow_fat"])
293			.multiple(true)
294	))]
295	Init {
296		/// The folder to make a tree; without it, the current one.
297		#[arg(conflicts_with = "making")]
298		folder: Option<PathBuf>,
299		/// The message of the tree's first revision.
300		#[arg(short, long, conflicts_with = "making")]
301		message: Option<String>,
302		/// Makes the folder a tree without asking.
303		#[arg(long, conflicts_with = "making")]
304		yes: bool,
305		/// Your own name, such as `Ada Lovelace`, not the library's, which is its folder's: you
306		/// become the library's user, linked to a person of that name. Without it, your
307		/// account's name, as `whoami` prints it, and your full name for the person, if the
308		/// system knows it. Giving it makes a library.
309		#[arg(long)]
310		name: Option<String>,
311		/// This device's name, instead of the computer's. Giving it makes a library.
312		#[arg(long)]
313		device: Option<String>,
314		/// Protects the library's keys with a passphrase instead of the platform's keystore.
315		/// Giving it makes a library.
316		#[arg(long)]
317		passphrase: bool,
318		/// The languages you read, ranked, such as `en, *-Latn, ru`: English first, then
319		/// anything in the Latin script, then Russian. Without it, the system's. Giving it
320		/// makes a library.
321		#[arg(
322			long,
323			value_name = "RANGES",
324			value_parser = parse_languages,
325			conflicts_with = "join"
326		)]
327		languages: Option<Languages>,
328		/// Joins the library of another device of yours, which shows this code: nib device
329		/// pair shows it there. Both devices must be on the same network.
330		#[arg(long, value_name = "CODE", value_parser = parse_code, conflicts_with = "name")]
331		join: Option<PairingCode>,
332		/// With --join, asks the device that shows the code for the library's secrets too,
333		/// with a passphrase of their own here, asked for twice before the code is used. It
334		/// gives them if its secrets are unlocked, as nib device pair --give-secrets does;
335		/// otherwise nib secret give does there later.
336		#[arg(long, requires = "join", conflicts_with = "name")]
337		secrets: bool,
338		/// Keeps the library on this drive although its file system keeps no journal, as
339		/// FAT32 and exFAT, which most USB sticks have. There, a drive removed without
340		/// ejecting it, or that loses its power, while the library is open, must be checked
341		/// for errors before the library is used again: nib says so then. Giving it makes a
342		/// library.
343		#[arg(long)]
344		allow_fat: bool,
345	},
346	/// Shows or sets the languages that values are shown in.
347	///
348	/// The languages are ranked, such as `en, *-Latn, ru`. This app's list comes before this
349	/// device's, and this device's before yours.
350	Languages {
351		/// The languages, ranked. Without them, shows the lists.
352		#[arg(value_name = "RANGES")]
353		ranges: Option<String>,
354		/// Sets this device's list, for every app on it, instead of yours.
355		#[arg(long, conflicts_with = "app")]
356		device: bool,
357		/// Sets this app's list instead of yours.
358		#[arg(long)]
359		app: bool,
360		/// Clears the list, so that the next one counts.
361		#[arg(long, conflicts_with = "ranges")]
362		clear: bool,
363	},
364	/// Shows what changed in the tree here, or what the library holds.
365	///
366	/// In a tree's folder, shows what changed in the tree's copy here since it was written or
367	/// committed: new, edited, moved and deleted files, and executable bits, and the Git
368	/// repositories found, with the work they hold that their remotes lack; and what changed
369	/// in the tree elsewhere. Only the files whose size or modification time changed are read.
370	/// Elsewhere, or with --library-wide, shows what the library holds.
371	#[command(visible_alias = "st")]
372	Status {
373		/// Shows what the library holds, in a tree's folder too.
374		#[arg(long)]
375		library_wide: bool,
376		/// Lists the tree's secret files instead, which only devices that hold the secrets
377		/// read or write, and its ordinary files that look secret, as files committed before
378		/// a rule named them, or taken in as ordinary.
379		#[arg(long, conflicts_with = "library_wide")]
380		secrets: bool,
381	},
382	/// Checks every change, log file and readable file of the library.
383	///
384	/// Every blob this device can read is read in full. Fails if anything is wrong.
385	Verify {
386		/// Checks an export instead: every file against its sums, and what it holds against
387		/// what the library held at its moment.
388		#[arg(long, value_name = "FOLDER")]
389		export: Option<PathBuf>,
390		/// Says that the library's drive was checked for errors, as by Windows' Scan and fix
391		/// or by fsck, after it was removed without ejecting it, or lost its power, while the
392		/// library was open; then verifies the whole library.
393		#[arg(long, conflicts_with = "export")]
394		drive_checked: bool,
395	},
396	/// Adds an entity of a type, with its values.
397	///
398	/// Its values are given as `field=value`, such as `nib new book name="Leviathan Wakes"
399	/// published=2011`.
400	New {
401		/// Its type, or several separated by commas, such as `edition,audiobook`. A name
402		/// without a dot is your own type of that name, or else the only known type whose
403		/// name ends in it.
404		#[arg(value_name = "TYPES")]
405		kind: String,
406		/// Its values, as `field=value`. Give a field with many values several times.
407		values: Vec<String>,
408		/// The language of its text, names and files, such as `en` or `uk-Latn`, except for
409		/// fields of codes, such as ISBNs, which are in no language.
410		#[arg(long, value_name = "TAG", value_parser = parse_tag)]
411		language: Option<Tag>,
412	},
413	/// Shows an entity, found by its ID, a prefix of its ID, or its name.
414	Show {
415		/// The entity.
416		entity: String,
417		/// Shows the entity as it was on this day, such as `2000-01-01`, instead of today.
418		#[arg(long, value_name = "DAY", value_parser = parse_day)]
419		on: Option<Day>,
420		/// Shows the entity as the library had recorded it by then, without the changes
421		/// made since: a day, such as `2026-10-10`, which means its end, or a moment, such
422		/// as `2026-10-10T20:00`, in local time unless it gives its offset from UTC. Without
423		/// --on, as it was on that day.
424		#[arg(long, value_name = "WHEN", value_parser = parse_moment)]
425		as_of: Option<Moment>,
426	},
427	/// Moves an entity to another space, such as one you share.
428	///
429	/// A new entity there gets its values, with their history as you carry it, its types and
430	/// its files, and links to it lead there. A folder or a list moves with all it holds,
431	/// through every level, which nib lists first. The old space keeps the history it had, for
432	/// those who can read it.
433	Move {
434		/// The entity, by its ID, the start of its ID, or its name.
435		entity: String,
436		/// The space to move it to, by its name or the start of its ID.
437		#[arg(long, value_name = "SPACE")]
438		to: String,
439		/// Brings its current values alone, and leaves its history in the old space.
440		#[arg(long)]
441		without_history: bool,
442		/// Keeps what it leaves in the old space. Otherwise that is purged once another
443		/// device, yours or another member's, holds what moved: what your role there lets you
444		/// purge, and the rest once an admin of that space purges it.
445		#[arg(long)]
446		keep_behind: bool,
447		/// Leaves its secret values, such as passwords, with it in the old space, where no
448		/// purge of what stays behind takes them. Otherwise they move too, which needs the
449		/// secrets of both spaces, unlocked as it moves.
450		#[arg(long)]
451		leave_secrets: bool,
452		/// Moves a folder or a list with all it holds, or an entity out of the folders and
453		/// lists that stay, which nib otherwise only lists.
454		#[arg(long)]
455		yes: bool,
456	},
457	/// Merges an entity into another that it turns out to be the same as.
458	///
459	/// The other shows what both say from then on, and references to either lead to it. With
460	/// --undo, sets apart again an entity merged into ENTITY: the only one, or the one given.
461	Merge {
462		/// The entity.
463		entity: String,
464		/// The entity to merge it into, or with --undo, the entity merged into it to set
465		/// apart, by its ID, a prefix of its ID, or its own name.
466		#[arg(required_unless_present = "undo")]
467		other: Option<String>,
468		/// Undoes a merge.
469		#[arg(long)]
470		undo: bool,
471	},
472	/// Exports the library into a folder, as JSON, files and their sums.
473	///
474	/// The folder, empty or new, gets the library's entities as JSON, the files they refer to
475	/// as they were added, and the SHA-256 sums of them all, which read without NibKeep. The
476	/// folder is not encrypted, and secret values are left out.
477	Export {
478		/// The folder.
479		folder: PathBuf,
480		/// Only the values entities have now, without their history, who recorded them or
481		/// when, without deleted entities and the records of users and devices: for giving
482		/// a collection to someone.
483		#[arg(long)]
484		current: bool,
485	},
486	/// Imports an export of a library, or Google Takeout's photos.
487	///
488	/// A folder that nib export made brings what it holds and the library lacks, with the
489	/// same IDs, so that importing it again adds nothing. Its records of users, devices,
490	/// replicas and spaces are left out, and an export whose sums do not match is refused.
491	///
492	/// Anything else is taken for Google Takeout's archive of Google Photos: its parts, zip
493	/// or tgz files, all at once, or the folder one was unpacked into, read where they are.
494	/// Each photo and video comes with what its JSON file says, when and where it was taken
495	/// and its description, in place of what it says of itself, as that is where corrections
496	/// made in Google Photos are; its name as uploaded; and in a folder for each album it is
497	/// in, inside a folder named after the source. A photo the library holds already, as from
498	/// a phone, is stored once, found in one more place. Other products of the archive, as
499	/// Drive, are left out. Imported again, what an import added is not read again, so one
500	/// cut short goes on where it stopped.
501	Import {
502		/// The folder of the export; or the parts of Takeout's archive, or the folder it was
503		/// unpacked into.
504		#[arg(required = true, value_name = "PATH")]
505		paths: Vec<PathBuf>,
506		/// The source of Takeout's photos, by a name of yours: `Google Photos` unless given,
507		/// such as `Google Photos (Mom)`.
508		#[arg(long, value_name = "SOURCE")]
509		from: Option<String>,
510	},
511	/// Shows every value an entity has had, or one field's.
512	///
513	/// Each value comes with when it was recorded, by whom, and when it was replaced.
514	History {
515		/// The entity.
516		entity: String,
517		/// The field.
518		field: Option<String>,
519	},
520	/// Changes an entity's values or types.
521	///
522	/// `field=value` sets a field, correcting the value it shows;
523	/// `field+=value` adds a value, which with `--date` records a change, such as a new
524	/// employer, that ends the value before it in a field with one value; `field-=value`
525	/// removes a value; and `field=` clears the field. `type+=TYPE` gives the entity
526	/// another type, and `type-=TYPE` takes one away; its values stay. Where a type of the
527	/// entity has a field named `type`, `org.nibkeep.type+=` and `-=` change the types.
528	Edit(EditArgs),
529	/// Purges values for good, everywhere, with their history.
530	///
531	/// `field=value` purges that value of an entity, current or past, and `field=` every
532	/// value the field has held. What else the changes that held them held stays, and what
533	/// they replaced stays replaced. Without --yes, it says what it would purge, and purges
534	/// nothing. With --behind and no entity, lists what moves left behind and asked you to
535	/// purge, as an admin of its space.
536	Purge {
537		/// The entity.
538		#[arg(required_unless_present = "behind")]
539		entity: Option<String>,
540		/// What to purge, as `field=value` or `field=`.
541		#[arg(required_unless_present = "behind")]
542		value: Option<String>,
543		/// Purges what a move left behind of the entity, as its mover asked: as an admin of
544		/// its space, all but the marks that lead to where it is now; as an editor, the
545		/// changes you signed.
546		#[arg(long, conflicts_with = "value")]
547		behind: bool,
548		/// Purges for good, which cannot be undone.
549		#[arg(long)]
550		yes: bool,
551	},
552	/// Finds the entities whose values hold every word.
553	///
554	/// The last word also matches the start of a longer one. Then, through links, what they
555	/// lead to: the books of an author they
556	/// are, a pen name they use, and the books credited to it. Lists the first 50 of each
557	/// space and says how many more there are.
558	Find {
559		/// The words.
560		#[arg(required = true)]
561		words: Vec<String>,
562		/// Lists every entity found, not only the first 50.
563		#[arg(long)]
564		all: bool,
565	},
566	/// Lists the entities, or those of a type.
567	///
568	/// They are listed by name or in the order of a field, such as `nib list book --where
569	/// in-series="The Expanse" --sort number-in-series`. A field is
570	/// one of the type's, or else of the other types that its entities have, as an audiobook
571	/// can be an edition too; which one a short name finds can change with the entities, so
572	/// scripts give full names, such as `std.published`.
573	List {
574		/// The type.
575		#[arg(value_name = "TYPE")]
576		kind: Option<String>,
577		/// Lists only the entities whose field shows this value today. A reference is given
578		/// by the ID, the start of the ID or the name of what it refers to. Give it several
579		/// times for entities that meet every condition.
580		#[arg(long = "where", value_name = "FIELD=VALUE")]
581		conditions: Vec<String>,
582		/// Orders the entities by the first value the field shows: numbers by size, dates
583		/// by when they start, text and names alphabetically, references by the names of
584		/// what they refer to. Entities without a value come last.
585		#[arg(long, value_name = "FIELD")]
586		sort: Option<String>,
587		/// Lists the entities as they were on this day, such as `2000-01-01`, instead of
588		/// today: by the names they had then, and the values their fields showed then.
589		#[arg(long, value_name = "DAY", value_parser = parse_day)]
590		on: Option<Day>,
591	},
592	/// Works with types: the fields that entities of a type may have.
593	Type {
594		/// What to do with types.
595		#[command(subcommand)]
596		command: TypeCommand,
597	},
598	/// Works with files, each stored once with every place it was found.
599	///
600	/// A file's content is stored once, however often it is added.
601	File {
602		/// What to do with files.
603		#[command(subcommand)]
604		command: FileCommand,
605	},
606	/// The commands of trees, named as other version control systems name theirs.
607	#[command(flatten)]
608	Trees(TreeCommand),
609	/// Protects the library's keys, or its secrets, anew.
610	///
611	/// The keys go to the platform's keystore, or with --passphrase, under a new passphrase;
612	/// with --secrets, the library's secrets do instead, after their passphrase. The library's
613	/// passphrase and its secrets' are never the same.
614	Protect {
615		/// A new passphrase, asked for twice, instead of the platform's keystore.
616		#[arg(long)]
617		passphrase: bool,
618		/// Protects the library's secrets, not its keys.
619		#[arg(long)]
620		secrets: bool,
621	},
622	/// Works with secret values, such as passwords, and secret files.
623	///
624	/// No other command shows or takes secret values. Each asks for the passphrase of the
625	/// library's secrets, which is not the library's, and forgets the secrets when it ends;
626	/// nib secret generate needs no library.
627	Secret {
628		/// What to do with secret values.
629		#[command(subcommand)]
630		command: SecretCommand,
631	},
632	/// Works with storage policies: how many copies files need, and where.
633	///
634	/// A policy says how many copies the files of the personal space need, and whether this
635	/// device keeps them in NibKeep's store or where they are. Rules choose a file's policy in
636	/// order, unless the file has a policy of its own. The first command gives the space the
637	/// default policies, Critical, Standard and Replaceable.
638	Policy {
639		/// What to do with policies.
640		#[command(subcommand)]
641		command: PolicyCommand,
642	},
643	/// Works with spaces, the parts of the library shared as a whole.
644	///
645	/// Each space holds its own entities, and is shared, or not, as a whole. Your personal
646	/// space is never shared.
647	Space {
648		/// What to do with spaces.
649		#[command(subcommand)]
650		command: SpaceCommand,
651	},
652	/// Works with your devices, which sync over the home network.
653	///
654	/// Each device holds copies of the library, which sync with each other.
655	Device {
656		/// What to do with devices.
657		#[command(subcommand)]
658		command: DeviceCommand,
659	},
660	/// Works with your backups on drives and network shares.
661	///
662	/// A backup is a folder on a USB drive, a drive kept away from home, or a network share,
663	/// which your computers keep up to date whenever they find it, such as when the drive is
664	/// plugged in. It holds the library's data encrypted, and no keys: whoever finds it reads
665	/// nothing, and you restore from it on a device of yours.
666	Backup {
667		/// What to do with backups.
668		#[command(subcommand)]
669		command: BackupCommand,
670	},
671	/// Works with recovery codes, and brings a library back.
672	///
673	/// A recovery code is on paper, and brings the library back when every device is lost,
674	/// from a backup, or when this computer's library no longer unlocks. It holds keys and no
675	/// data. Whoever has the code and a backup reads everything, so keep it as safely as a
676	/// passport.
677	Recovery {
678		/// What to do with recovery codes.
679		#[command(subcommand)]
680		command: RecoveryCommand,
681	},
682	/// Lists the purges that wait here, and stops one or ends its wait.
683	///
684	/// A purge waits on this device, and on your backups plugged in here, before what it
685	/// destroyed goes for good. An archive node keeps it apart, unreadable to everyone, for
686	/// a while after it learns of a purge, 30 days unless marked otherwise (nib device mark
687	/// --waits), so that no mistake or infected device wipes data everywhere at once.
688	/// Meanwhile, a purge can be stopped here, which brings back everywhere what it
689	/// destroyed, or its wait ended sooner.
690	Purges {
691		/// What to do with a purge that waits.
692		#[command(subcommand)]
693		command: Option<PurgesCommand>,
694	},
695	/// Syncs the library with your other devices on the home network.
696	///
697	/// Each gets what the other has, files too. Where a program syncs this device for all, as
698	/// nib sync --serve or an app that has the library open does, it asks that one to sync
699	/// now, and says what happened. As nib push, it sends your commits, as Git's push does.
700	#[command(visible_alias = "push")]
701	Sync {
702		/// Syncs this device for every program here, until stopped: answers your other
703		/// devices, and syncs with them as changes come and they appear on the network.
704		/// Where another program does that already, it waits, and takes over when that one
705		/// ends.
706		#[arg(long, conflicts_with = "wait")]
707		serve: bool,
708		/// How long to look for your other devices on the network, in seconds; where a
709		/// program syncs this device, how much longer than two minutes to wait for it.
710		#[arg(long, value_name = "SECONDS", default_value_t = 10)]
711		wait: u64,
712		/// Syncs this library whenever you are logged in to this computer, with no app open,
713		/// or stops: nibkeep-sync, installed beside nib, does it for every library turned on.
714		/// It needs the library's keys in the keystore, as nobody is there to type a
715		/// passphrase.
716		#[arg(long, value_name = "SWITCH", conflicts_with_all = ["serve", "wait"])]
717		at_login: Option<Switch>,
718		/// With --serve, the UDP port to take connections on, for a firewall to let through:
719		/// the first free of the ten from it, then any; any with 0. Without --serve, nib sync
720		/// only makes connections.
721		#[arg(
722			long,
723			value_name = "PORT",
724			env = "NIBKEEP_PORT",
725			default_value_t = nibkeep_node::DEFAULT_PORT
726		)]
727		port: u16,
728	},
729	/// Syncs with your other devices, then updates the copy of the tree.
730	///
731	/// It syncs as nib sync does, then brings the copy of the tree here to the tree as they
732	/// left it, as nib update does: what Git's pull does. The copy is brought up to date even
733	/// if the sync fails, which it says after.
734	Pull {
735		/// How long to look for your other devices on the network, in seconds.
736		#[arg(long, value_name = "SECONDS", default_value_t = 10)]
737		wait: u64,
738		/// Writes what parts have arrived of a commit whose other parts have not.
739		#[arg(long)]
740		partial: bool,
741		/// Clones the Git repositories added elsewhere without asking.
742		#[arg(long, conflicts_with = "no_clone")]
743		clone: bool,
744		/// Clones no Git repository, and lists those it would.
745		#[arg(long)]
746		no_clone: bool,
747	},
748	/// Serves nib to AI clients, and lets them work on your library.
749	///
750	/// An AI client runs nib mcp serve, on your library where nib mcp enable allowed AI
751	/// agents, or on an AI agent's copy of the library, which nib device pair --ai-agent adds.
752	#[command(subcommand_required = true, arg_required_else_help = true)]
753	Mcp {
754		/// What to do.
755		#[command(subcommand)]
756		action: McpAction,
757	},
758	/// The commands of other version control systems that nib does not have.
759	#[command(flatten)]
760	Absent(Absent),
761}
762
763/// What `nib mcp` does.
764#[derive(Debug, Subcommand)]
765pub enum McpAction {
766	/// Serves an AI client nib's operations as tools, over standard input.
767	///
768	/// It serves them by the Model Context Protocol, over standard input and output, until
769	/// the input ends: on your library, where nib mcp enable allowed AI agents, as the client,
770	/// with a key of its own named after it; or on an AI agent's copy of the library, which
771	/// nib device pair --ai-agent adds for an AI agent kept apart. It asks for nothing on a
772	/// terminal, so a library protected by a passphrase needs --passphrase-file. On an AI
773	/// agent's copy, it syncs with your device that waits with nib sync --serve: when it
774	/// starts, before a request if it last synced a minute before, and a few seconds after the
775	/// AI agent's changes; on your library, the program that syncs this device sends them on.
776	Serve {
777		/// The AI client's name, which history names its changes by, instead of the name the
778		/// client gives itself.
779		#[arg(long, value_name = "NAME")]
780		agent: Option<String>,
781		/// How long to look for your other devices on the network when it syncs, in seconds.
782		#[arg(long, value_name = "SECONDS", default_value_t = 2)]
783		wait: u64,
784	},
785	/// Allows AI agents on your library here, and tells the AI clients.
786	///
787	/// The AI clients on this computer are told of its server through their own commands,
788	/// Claude Code's and Codex's: each client then works on the library with a key of its own,
789	/// named after it, in your personal space and never with your secrets. A client's session
790	/// that runs already sees the server once it starts anew.
791	Enable {
792		/// Tells this client alone, such as `claude` or `codex`.
793		#[arg(long, value_name = "CLIENT", conflicts_with = "print")]
794		client: Option<String>,
795		/// Tells no client: prints the server's command line, and its entry for the
796		/// `mcpServers` of JSON that most clients take, to paste into any.
797		#[arg(long)]
798		print: bool,
799	},
800	/// Withdraws AI agents from your library here.
801	///
802	/// It revokes the key of every AI client that worked on it, and takes its server out of the
803	/// clients that nib mcp enable told.
804	Disable {
805		/// Takes the server out of this client alone, such as `claude` or `codex`.
806		#[arg(long, value_name = "CLIENT")]
807		client: Option<String>,
808	},
809}
810
811/// The commands of other version control systems that nib does not have, each of which
812/// says what to do instead, with whatever it is given.
813#[derive(Debug, Subcommand)]
814pub enum Absent {
815	/// Git's add.
816	#[command(hide = true)]
817	Add(Rest),
818	/// Git's checkout.
819	#[command(hide = true)]
820	Checkout(Rest),
821	/// Git's branch.
822	#[command(hide = true)]
823	Branch(Rest),
824	/// Git's tag.
825	#[command(hide = true)]
826	Tag(Rest),
827	/// Git's stash.
828	#[command(hide = true)]
829	Stash(Rest),
830	/// Git's reset.
831	#[command(hide = true)]
832	Reset(Rest),
833	/// Git's rebase.
834	#[command(hide = true)]
835	Rebase(Rest),
836	/// Git's fetch.
837	#[command(hide = true)]
838	Fetch(Rest),
839}
840
841impl Absent {
842	/// The command's name, and what to do instead.
843	const fn instead(&self) -> (&'static str, &'static str) {
844		const NO_BRANCHES: &str = "a tree has no branches or tags: what devices change apart competes, and nib update merges it";
845		match self {
846			Self::Add(_) => (
847				"add",
848				"nib commit takes in new files, and leaves out what .nibignore names",
849			),
850			Self::Checkout(_) => (
851				"checkout",
852				"nib clone writes a tree into a folder, and nib restore writes a file as it was",
853			),
854			Self::Branch(_) => ("branch", NO_BRANCHES),
855			Self::Tag(_) => ("tag", NO_BRANCHES),
856			Self::Rebase(_) => ("rebase", NO_BRANCHES),
857			Self::Stash(_) => (
858				"stash",
859				"a tree has no stash: nib restore writes a file as it was, and keeps your edits beside it",
860			),
861			Self::Reset(_) => (
862				"reset",
863				"nib restore writes a file as it was, and nib revert undoes a revision",
864			),
865			Self::Fetch(_) => (
866				"fetch",
867				"nib sync brings what your other devices recorded without writing it, and nib pull writes it too",
868			),
869		}
870	}
871}
872
873/// Whatever a command that nib does not have is given.
874#[derive(Debug, Args)]
875pub struct Rest {
876	/// What it is given.
877	#[arg(trailing_var_arg = true, allow_hyphen_values = true, hide = true)]
878	rest: Vec<String>,
879}
880
881/// On or off.
882#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
883pub enum Switch {
884	/// On.
885	On,
886	/// Off.
887	Off,
888}
889
890/// Whether a device takes the spaces made later, or asks first.
891#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
892pub enum NewSpacesArg {
893	/// Takes them, as a computer does.
894	Take,
895	/// Asks first, as a phone does.
896	Ask,
897}
898
899/// What `nib space` can do.
900#[derive(Debug, Subcommand)]
901pub enum SpaceCommand {
902	/// Makes a space besides your personal one, or a group.
903	///
904	/// A space, such as `Family`, reaches those of your other devices that take new
905	/// spaces, as computers do, when they sync; a phone asks first, with nib space take,
906	/// unless you give it the space with --on. With --group, makes a group, such as
907	/// `Household`: a space with members and no entities of its own, which you add to spaces
908	/// with nib space add-group, so that whoever you invite to the group joins each of them.
909	New {
910		/// Its name.
911		name: String,
912		/// Makes a group.
913		#[arg(long)]
914		group: bool,
915		/// Gives it to that device of yours too, by its name or ID, such as a phone, which
916		/// still takes it only once you say so there with nib space take; give it once for
917		/// each.
918		#[arg(long = "on", value_name = "DEVICE")]
919		on: Vec<String>,
920	},
921	/// Adds a group to a space, or to another group.
922	///
923	/// You add it as an admin of the space who is a member of the group: its members join
924	/// with the lower of the group's role there and their own role in the group, and, added
925	/// to a group, join every space that group is in. The group joins once an admin of the
926	/// group agrees, at once if you are one.
927	AddGroup {
928		/// The space or the group, by its name or the start of its ID.
929		space: String,
930		/// The group, by its name or the start of its ID.
931		group: String,
932		/// The group's role there: editor or viewer, never admin.
933		#[arg(long, value_enum, default_value_t = RoleArg::Editor)]
934		role: RoleArg,
935	},
936	/// Takes a group out of a space, as an admin of the space.
937	///
938	/// Its members leave the space, unless they are members there some other way.
939	RemoveGroup {
940		/// The space, by its name or the start of its ID.
941		space: String,
942		/// The group, by its name or the start of its ID.
943		group: String,
944	},
945	/// Agrees, as an admin of a group, that it join a space.
946	///
947	/// The space is one that a request in the group names, as nib space show lists them.
948	Agree {
949		/// The group, by its name or the start of its ID.
950		group: String,
951		/// The space, by its name in the request or the start of its ID.
952		space: String,
953	},
954	/// Withdraws, as an admin of a group, its agreement to join a space.
955	///
956	/// It is withdrawn for good: its members leave the space, unless they are members there
957	/// some other way.
958	Withdraw {
959		/// The group, by its name or the start of its ID.
960		group: String,
961		/// The space, by its name in the request or the start of its ID.
962		space: String,
963	},
964	/// Lists your spaces, and which of your devices hold each.
965	///
966	/// With how many entities each holds here. Your personal space comes first, then those
967	/// on this device, then those on your other devices alone: one given to this device
968	/// waits for nib space take, and one that another device of yours asks for, for nib
969	/// space allow here.
970	List,
971	/// Takes a space onto this device.
972	///
973	/// One given to this device, at once: it fills as it syncs. Any other, such as one made
974	/// on another device of yours, or one this device dropped, it asks for: approve it with
975	/// nib space allow on a device that holds it.
976	Take {
977		/// The space, by its name or the start of its ID, as nib space list shows it. Not
978		/// named `space`, which the global --space would take, for a space this device holds.
979		#[arg(value_name = "SPACE")]
980		wanted: String,
981	},
982	/// Drops a space from this device, which your other devices keep.
983	///
984	/// Refused while, without this device, the space would be below its storage policies
985	/// or on no other device of yours, and while a tree's folder or an edited checkout of it
986	/// is here: it says what is missing. Otherwise it waits until your changes there, and
987	/// the copies of its files, are on other disks as its policies ask, which the holder of
988	/// the sync role, such as nib sync --serve, proves, removing this device's copies a
989	/// little at a time; and until another device holds its secrets, where this one does.
990	/// Then this device says that it no longer holds the space, and deletes it, its
991	/// unedited checkouts too, once another device of yours that holds it has learned so,
992	/// after their next syncs. Run it again to see what it waits for; nib space take keeps
993	/// the space until then. A space that you left goes at once.
994	Drop {
995		/// The space, by its name or the start of its ID. Not named `space`, which the global
996		/// --space would take.
997		#[arg(value_name = "SPACE")]
998		wanted: String,
999	},
1000	/// Gives a space to another device of yours that asked for it.
1001	///
1002	/// The device takes it as it syncs; one that dropped the space gets it back.
1003	Allow {
1004		/// The space, by its name or the start of its ID.
1005		space: String,
1006		/// The device, by its name or ID, as nib space list shows it.
1007		device: String,
1008	},
1009	/// Shows a space's members, groups, claims and changes set aside.
1010	///
1011	/// For a shared space: its members, with their roles and devices; the groups in it, with
1012	/// their roles, whether they agreed to join, and their members; the claims to its admin
1013	/// role, with when each takes effect; and the changes set aside there, which wait for an
1014	/// admin's review: what members changed before they learned that they had left, been
1015	/// removed or lost a role, and what their roles never allowed, with the entities each
1016	/// changes. For a group, also the requests in it that it join spaces, with each space's
1017	/// name where it is sealed to you, as to the group's admins.
1018	Show {
1019		/// The space or the group, by its name or the start of its ID.
1020		space: String,
1021	},
1022	/// Renames a space; your personal space keeps its name.
1023	Rename {
1024		/// The space, by its name or the start of its ID.
1025		space: String,
1026		/// Its new name.
1027		name: String,
1028	},
1029	/// Invites someone to a space, as an admin of it.
1030	///
1031	/// It shows a code to give to nib space join on their device, which then gets the space
1032	/// and syncs it with yours. The code works once, for ten minutes, and both devices must
1033	/// be on the same network. It shows who asks to join before they are added, and asks
1034	/// you to confirm, but with --yes.
1035	Invite {
1036		/// The space, by its name or the start of its ID.
1037		space: String,
1038		/// The role they get.
1039		#[arg(long, value_enum, default_value_t = RoleArg::Editor)]
1040		role: RoleArg,
1041		/// The person in the space whom they are, such as `Olga` in a family tree, by name or
1042		/// ID: they are linked to that person once they agree, as they join.
1043		#[arg(long = "as", value_name = "PERSON")]
1044		person: Option<String>,
1045		/// Adds whoever joins with the code, without asking.
1046		#[arg(long)]
1047		yes: bool,
1048		/// The port to take the connection on.
1049		#[command(flatten)]
1050		port: Port,
1051	},
1052	/// Joins a space that someone invited you to, with their code.
1053	///
1054	/// Their device shows the code: this device gets the space, and those of your other
1055	/// devices that take new spaces get it when they sync. If the invitation names the
1056	/// person in the space whom you are, it asks whether you are.
1057	Join {
1058		/// The code, as nib space invite shows it.
1059		code: PairingCode,
1060		/// Agrees, without asking, to be the person whom the invitation names you.
1061		#[arg(long)]
1062		yes: bool,
1063		/// Gives the space to that device of yours too, by its name or ID, as nib space new
1064		/// --on does; give it once for each.
1065		#[arg(long = "on", value_name = "DEVICE")]
1066		on: Vec<String>,
1067	},
1068	/// Says whether a space allows AI agents, or sets it as an admin.
1069	///
1070	/// An AI agent's copy of the library is listed there, by nib device pair --ai-agent
1071	/// --in, only while it does. Without on or off, says whether it does.
1072	AiAgents {
1073		/// The space, by its name or the start of its ID.
1074		space: String,
1075		/// Whether it allows them.
1076		#[arg(value_enum)]
1077		switch: Option<Switch>,
1078	},
1079	/// Links a member of a space to the person in it whom they are.
1080	///
1081	/// Without a person, it unlinks them: yourself, or, as an admin, another member. The
1082	/// link holds once an admin and the member agree, and history names the member by that
1083	/// person in the space.
1084	Link {
1085		/// The space, by its name or the start of its ID.
1086		space: String,
1087		/// The member, by their name or the start of their record's ID.
1088		member: String,
1089		/// The person, by name or ID.
1090		person: Option<String>,
1091	},
1092	/// Leaves a space, keeping what your devices have there, read only.
1093	///
1094	/// Your devices get nothing added after; the members who stay give the space a new key.
1095	/// You come back only if an admin invites you again, or lets you back in if you are in
1096	/// it through a group, whose member you stay. The only admin makes another an admin
1097	/// first; the last member's leaving closes the space. Without --yes, it says what
1098	/// leaving would do.
1099	Leave {
1100		/// The space, by its name or the start of its ID.
1101		space: String,
1102		/// Leaves.
1103		#[arg(long)]
1104		yes: bool,
1105	},
1106	/// Removes a member of a space, as an admin of it.
1107	///
1108	/// Every device of theirs there keeps what it has, read only, and gets nothing added
1109	/// after, and the space gets a new key. What they change before they learn of it waits
1110	/// for an admin's review. A member through a group is kept out of the space, and stays
1111	/// in the group, until you let them back in. Without --yes, it says what removing would
1112	/// do.
1113	Remove {
1114		/// The space, by its name or the start of its ID.
1115		space: String,
1116		/// The member, by their name or the start of their record's ID, or that of their
1117		/// record in a group.
1118		member: String,
1119		/// Removes them.
1120		#[arg(long)]
1121		yes: bool,
1122	},
1123	/// Lets a member through a group back in, as an admin of the space.
1124	///
1125	/// The space kept them out, as nib space remove does, while they stayed in the group.
1126	LetIn {
1127		/// The space, by its name or the start of its ID.
1128		space: String,
1129		/// The member, by their name or the start of their record's ID in the group.
1130		member: String,
1131	},
1132	/// Makes a member through a group a direct member of a space.
1133	///
1134	/// An admin of the space does it, such as to make them an admin, with no code: once
1135	/// they confirm with nib space confirm, their devices list themselves on the new
1136	/// record, with its role.
1137	MakeDirect {
1138		/// The space, by its name or the start of its ID.
1139		space: String,
1140		/// The member, by their name or the start of their record's ID in the group.
1141		member: String,
1142		/// Their role as a direct member.
1143		#[arg(long, value_enum, default_value_t = RoleArg::Editor)]
1144		role: RoleArg,
1145	},
1146	/// Confirms the record that an admin of a space made for you.
1147	///
1148	/// As a member through a group, you become a direct member there, with its role, and
1149	/// your other devices follow.
1150	Confirm {
1151		/// The space, by its name or the start of its ID.
1152		space: String,
1153	},
1154	/// Claims the admin role of a space when its admins are gone.
1155	///
1156	/// You claim it as a direct member who is an editor there: every member sees the claim,
1157	/// which takes effect 30 days after another member's device first sees it, unless an
1158	/// admin rejects it, and for 30 days after that you can only undo. Without --yes, it
1159	/// says what claiming would do.
1160	Claim {
1161		/// The space, by its name or the start of its ID.
1162		space: String,
1163		/// Claims the role.
1164		#[arg(long)]
1165		yes: bool,
1166	},
1167	/// Rejects a member's claim to the admin role, as an admin.
1168	///
1169	/// The claim,
1170	/// and what they did as an admin, count for nothing once another member's device sees
1171	/// the rejection, if that is within 30 days after the claim took effect.
1172	Reject {
1173		/// The space, by its name or the start of its ID.
1174		space: String,
1175		/// The member, by their name or the start of their record's ID.
1176		member: String,
1177	},
1178	/// Accepts a member's changes that were set aside in a space.
1179	///
1180	/// As an admin of the space, you accept them: they count after all, with their own
1181	/// times. Only those that the member's role allowed when they made them are accepted;
1182	/// changes that say who may write to the space never are. Without --yes, it says how
1183	/// many it would accept.
1184	Accept {
1185		/// The space, by its name or the start of its ID.
1186		space: String,
1187		/// The member, by their name or the start of their record's ID.
1188		member: String,
1189		/// Accepts them.
1190		#[arg(long)]
1191		yes: bool,
1192	},
1193	/// Gives a member of a space a role, as an admin of it.
1194	Role {
1195		/// The space, by its name or the start of its ID.
1196		space: String,
1197		/// The member, by their name or the start of their record's ID.
1198		member: String,
1199		/// The role they get.
1200		#[arg(value_enum)]
1201		role: RoleArg,
1202	},
1203}
1204
1205/// A role in a shared space.
1206#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
1207pub enum RoleArg {
1208	/// Sees everything, and changes only their own records.
1209	Viewer,
1210	/// Also changes everything but other members' records.
1211	Editor,
1212	/// May do anything, as invite others and give roles.
1213	Admin,
1214}
1215
1216impl RoleArg {
1217	/// The role it names.
1218	const fn role(self) -> MemberRole {
1219		match self {
1220			Self::Viewer => MemberRole::Viewer,
1221			Self::Editor => MemberRole::Editor,
1222			Self::Admin => MemberRole::Admin,
1223		}
1224	}
1225}
1226
1227/// What `nib purges` can do.
1228#[derive(Debug, Subcommand)]
1229pub enum PurgesCommand {
1230	/// Stops a purge that waits here, bringing back what it destroyed.
1231	///
1232	/// The purge waits on this device, or on a backup plugged in here. What it destroyed
1233	/// comes back everywhere, as it was, with its own authors and times, through a change
1234	/// that every device takes. An admin may stop any purge, and an editor one of what
1235	/// their own devices wrote. Without --yes, it says what it would bring back.
1236	Stop {
1237		/// The purge, by the start of its ID, as nib purges shows it.
1238		purge: String,
1239		/// Only where it waits on this backup, by its name or ID, or `here` on this device;
1240		/// without it, everywhere it waits here.
1241		#[arg(long, value_name = "BACKUP")]
1242		on: Option<String>,
1243		/// Stops it.
1244		#[arg(long)]
1245		yes: bool,
1246	},
1247	/// Ends the wait of a purge here, destroying now what it kept.
1248	///
1249	/// The purge waits on this device, or on a backup plugged in here, which keeps what the
1250	/// purge destroyed everywhere else; ending the wait destroys it now, as for a photo that
1251	/// someone asked to have removed. Without --yes, it says what would go.
1252	End {
1253		/// The purge, by the start of its ID, as nib purges shows it.
1254		purge: String,
1255		/// Only where it waits on this backup, by its name or ID, or `here` on this device;
1256		/// without it, everywhere it waits here.
1257		#[arg(long, value_name = "BACKUP")]
1258		on: Option<String>,
1259		/// Destroys it for good, which cannot be undone.
1260		#[arg(long)]
1261		yes: bool,
1262	},
1263}
1264
1265/// What `nib recovery` can do.
1266#[derive(Debug, Subcommand)]
1267pub enum RecoveryCommand {
1268	/// Makes a recovery code and shows it, for you to write down.
1269	///
1270	/// Write it down or print it. It counts only once you have typed it back, here or with
1271	/// nib recovery confirm, so that a code written down wrongly is never relied on. It
1272	/// replaces the codes made before it, which are revoked once every backup carries it.
1273	New {
1274		/// Gives the code the secrets too, so that it brings the passwords back: asks for the
1275		/// secrets' passphrase first.
1276		#[arg(long)]
1277		secrets: bool,
1278		/// Revokes the codes made before it at once, rather than once every backup carries
1279		/// it: a backup not updated since then brings nothing back.
1280		#[arg(long)]
1281		revoke_older: bool,
1282	},
1283	/// Takes a code typed from your paper, and has the library name it.
1284	///
1285	/// The library names it, if nothing names it yet.
1286	Confirm {
1287		/// Gives the code the secrets too, also one that the library names already: asks
1288		/// for the secrets' passphrase first.
1289		#[arg(long)]
1290		secrets: bool,
1291		/// Revokes the codes made before the newest at once, rather than once every backup
1292		/// carries it: a backup not updated since then brings nothing back.
1293		#[arg(long)]
1294		revoke_older: bool,
1295	},
1296	/// Lists your recovery codes, with when and where each was made.
1297	///
1298	/// They go by the names printed beside them, with when and on which device each was made.
1299	List,
1300	/// Says whether a code that you type stands and opens the keys.
1301	Check {
1302		/// Checks that it opens the secrets too: asks for the secrets' passphrase first.
1303		#[arg(long)]
1304		secrets: bool,
1305	},
1306	/// Revokes a recovery code, for good.
1307	///
1308	/// It opens nothing added later, and brings no device back. Shows what it would revoke,
1309	/// and revokes with --yes.
1310	Revoke {
1311		/// The code, by the name printed beside it, or by its ID.
1312		code: String,
1313		/// Revokes it.
1314		#[arg(long)]
1315		yes: bool,
1316	},
1317	/// Brings your library back on this computer with your recovery code.
1318	///
1319	/// nib asks for the code, after you lost your devices, or the means to unlock them. The
1320	/// library comes from the backup or the library in the folder given, or without one,
1321	/// from the library here, in the current folder or the one --library names, which no
1322	/// longer unlocks, as after a forgotten passphrase. This computer becomes a new device of
1323	/// yours, and your other devices are revoked, but those you keep: unless --keep names
1324	/// them, nib asks about each where it can ask, at a terminal and without --json, and
1325	/// otherwise revokes every one. A library here that no longer unlocks is replaced, and
1326	/// its old folder set aside for you to delete; a library elsewhere is left as it was. A
1327	/// backup must have been updated since the code was made. If the code holds your secrets,
1328	/// nib asks twice for a passphrase for them here, not the library's.
1329	Restore {
1330		/// The backup, or the folder of a library, to bring the library back from.
1331		#[arg(value_name = "SOURCE")]
1332		source: Option<PathBuf>,
1333		/// Keeps a device of yours that you still have, rather than revoke it as lost, by its
1334		/// name or ID, or an AI agent by its name, as nib device list showed them; give it
1335		/// once for each. Then nib asks about no other device. The library that no longer
1336		/// unlocks, which the recovery reads, is revoked in any case.
1337		#[arg(long, value_name = "DEVICE")]
1338		keep: Vec<String>,
1339		/// How the new device is made.
1340		#[command(flatten)]
1341		new: NewDevice,
1342	},
1343	/// Makes this computer a device of its own from a copy of the library.
1344	///
1345	/// The copy is in the current folder, or the one --library names, which a backup, a
1346	/// program that syncs folders or a person brought from another computer or drive, with
1347	/// the copy's own keys: only where no other device of yours can add this one, as after
1348	/// the library of your only device was restored from its backup. The copy's device is
1349	/// revoked, and the copy stays as it was. Asks for the copy's passphrase, unless this
1350	/// computer's keystore holds its key, and for its secrets' passphrase, if it has secrets.
1351	FromCopy {
1352		/// How the new device is made.
1353		#[command(flatten)]
1354		new: NewDevice,
1355	},
1356}
1357
1358/// How `nib recovery` makes this computer a new device.
1359#[derive(Debug, Args)]
1360pub struct NewDevice {
1361	/// This device's name, instead of the computer's.
1362	#[arg(long)]
1363	pub device: Option<String>,
1364	/// Protects the library's keys with a passphrase instead of the platform's keystore.
1365	#[arg(long)]
1366	pub passphrase: bool,
1367	/// Keeps the library on this drive although its file system keeps no journal, as FAT32
1368	/// and exFAT, which most USB sticks have. There, a drive removed without ejecting it, or
1369	/// that loses its power, while the library is open, must be checked for errors before the
1370	/// library is used again: nib says so then.
1371	#[arg(long)]
1372	pub allow_fat: bool,
1373}
1374
1375/// What `nib backup` can do.
1376#[derive(Debug, Subcommand)]
1377pub enum BackupCommand {
1378	/// Makes a backup in a folder, such as on a USB drive.
1379	///
1380	/// The folder, new or empty, is updated now. While nib sync --serve, syncing from login or
1381	/// an app runs, your computers then update it whenever they find it.
1382	New {
1383		/// The folder.
1384		folder: PathBuf,
1385		/// Its name, such as `Blue stick`; the folder's name by default.
1386		#[arg(long)]
1387		name: Option<String>,
1388		/// A space that it holds, by its name or the start of its ID; give it once for each.
1389		/// Every space of the library by default.
1390		#[arg(long = "of", value_name = "SPACE")]
1391		spaces: Vec<String>,
1392		/// A storage policy whose files it keeps, such as `Critical`, by its name in each of
1393		/// its spaces; give it once for each. Every policy's files by default. The library's
1394		/// records, thumbnails and secret files are always kept.
1395		#[arg(long = "policy", value_name = "POLICY")]
1396		policies: Vec<String>,
1397		/// Marks it as kept away from home, so that its copies count as copies away from
1398		/// home.
1399		#[arg(long)]
1400		away: bool,
1401		/// How many days it waits, from 1 to 365, before what a purge destroys leaves it,
1402		/// counted from the update that first brings the purge, during which nib purges on a
1403		/// computer it is plugged into can stop the purge; `none` for not at all, `default`
1404		/// for 30.
1405		#[arg(long, value_name = "DAYS", value_parser = parse_waits)]
1406		waits: Option<Waits>,
1407	},
1408	/// Lists your backups, with what they hold and still have to check.
1409	///
1410	/// Each comes with where this computer finds it, how many updates it has had and files it
1411	/// holds, how much of it is still to check, and how many copies were found damaged lately.
1412	List,
1413	/// Updates a backup now, or each that this computer finds.
1414	///
1415	/// An update takes in what this device lacks, writes what the backup lacks, and checks its
1416	/// files.
1417	Update {
1418		/// The backup, by its name or ID.
1419		backup: Option<String>,
1420		/// Where it is, if this computer does not find it on its own.
1421		#[arg(long, value_name = "FOLDER")]
1422		at: Option<PathBuf>,
1423	},
1424	/// Changes a backup: its name, spaces, policies, and where it is kept.
1425	///
1426	/// It is kept at home or away. Taking a space or a policy off stops writing it; what the
1427	/// backup holds of it stays.
1428	Edit {
1429		/// The backup, by its name or ID.
1430		backup: String,
1431		/// Its new name.
1432		#[arg(long)]
1433		name: Option<String>,
1434		/// The spaces that it holds from now on; give it once for each.
1435		#[arg(long = "of", value_name = "SPACE")]
1436		spaces: Vec<String>,
1437		/// The policies whose files it keeps from now on; give it once for each.
1438		#[arg(
1439			long = "policy",
1440			value_name = "POLICY",
1441			conflicts_with = "every_policy"
1442		)]
1443		policies: Vec<String>,
1444		/// Keeps every policy's files from now on.
1445		#[arg(long)]
1446		every_policy: bool,
1447		/// Marks it as kept away from home.
1448		#[arg(long, conflicts_with = "home")]
1449		away: bool,
1450		/// Marks it as kept at home.
1451		#[arg(long)]
1452		home: bool,
1453		/// How many days it waits before purging, from 1 to 365; `none`, or `default` for
1454		/// 30. A shorter wait, or none, holds only once the wait before it has passed.
1455		#[arg(long, value_name = "DAYS", value_parser = parse_waits)]
1456		waits: Option<Waits>,
1457	},
1458	/// Forgets a backup, whose folder stays for you to delete.
1459	///
1460	/// Your computers stop updating it.
1461	Remove {
1462		/// The backup, by its name or ID.
1463		backup: String,
1464	},
1465}
1466
1467/// What `nib device` can do.
1468#[derive(Debug, Subcommand)]
1469pub enum DeviceCommand {
1470	/// Adds another device of yours, or an AI agent's copy of the library.
1471	///
1472	/// It shows a code to give to nib init --join on the device, which then gets a copy of
1473	/// the library. The code works for ten minutes, three wrong tries end it, and both
1474	/// devices must be on the same network. A computer gets every space of this device's,
1475	/// and takes the spaces made later; a phone, with --phone, gets your personal space
1476	/// alone, and asks before it takes a space made later. The new device gets no secrets,
1477	/// but with --give-secrets.
1478	Pair {
1479		/// Adds a copy of the library for an AI agent instead, named after it, such as
1480		/// `Claude`, which nib mcp serves it: it gets no secrets, and may not purge, add or
1481		/// revoke devices, or change the library's own records, such as types and storage
1482		/// policies. Run nib init --join where nib mcp will run.
1483		#[arg(long, value_name = "NAME")]
1484		ai_agent: Option<String>,
1485		/// Adds a phone: it gets your personal space alone, or the spaces given with --in,
1486		/// and asks before it takes a space made later, with nib space take there.
1487		#[arg(long, conflicts_with = "ai_agent")]
1488		phone: bool,
1489		/// A space besides your personal one that the new device gets, by its name or the
1490		/// start of its ID, instead of the default, every space for a computer and none for a
1491		/// phone; give it once for each. For an AI agent, a space that it may read and write
1492		/// too: a shared space must allow AI agents, which its admins say with nib space
1493		/// ai-agents; an admin's device allows them here at once. Pair the AI agent anew to
1494		/// change its spaces.
1495		#[arg(long = "in", value_name = "SPACE")]
1496		spaces: Vec<String>,
1497		/// Gives the new device the library's secrets too, if it asks for them, as nib init
1498		/// --join --secrets does: asks for the passphrase of the secrets here before it shows
1499		/// the code.
1500		#[arg(long, conflicts_with = "ai_agent")]
1501		give_secrets: bool,
1502		/// The port to take the connection on.
1503		#[command(flatten)]
1504		port: Port,
1505	},
1506	/// Lists your devices: the copies of the library on them.
1507	///
1508	/// Each copy is kept by an app; those revoked are listed too, with how many of their
1509	/// changes wait for review.
1510	List,
1511	/// Revokes a device of yours, such as a lost phone.
1512	///
1513	/// It revokes every copy of the library on the device, or one copy by its ID: no device
1514	/// syncs with it any more, what it changed that this device does not have is set aside
1515	/// for review, and the library gets a new key that it does not get. Revoking is final.
1516	/// Without --yes, it says what it would revoke, and revokes nothing.
1517	Revoke {
1518		/// The device, by its name or ID, one copy of the library by its ID, or an AI
1519		/// agent by its name, as nib device list shows them.
1520		device: String,
1521		/// Revokes for good, which cannot be undone.
1522		#[arg(long)]
1523		yes: bool,
1524		/// Revokes too the recovery codes made on it, which it names: whoever has the device
1525		/// may have read them as they were made. Without it, they stay.
1526		#[arg(long)]
1527		codes: bool,
1528	},
1529	/// Marks a device as an archive node or everyday, at home or away.
1530	///
1531	/// An archive node, such as a NAS or a desktop, keeps
1532	/// the files that policies assign it, or as an everyday device, as every device is until
1533	/// marked; and as kept away from home, such as a relative's NAS, or at home. Copies on an
1534	/// archive node, and away from home, count where a policy asks for them. Your devices
1535	/// tell the others at their next syncs. Without a mark, it says how the device is marked.
1536	Mark {
1537		/// The device, by its name or ID, or one copy of the library on it by its ID.
1538		device: String,
1539		/// Marks it as an archive node.
1540		#[arg(long, conflicts_with = "everyday")]
1541		archive: bool,
1542		/// Marks it as an everyday device.
1543		#[arg(long)]
1544		everyday: bool,
1545		/// Marks it as kept away from home.
1546		#[arg(long, conflicts_with = "home")]
1547		away: bool,
1548		/// Marks it as kept at home.
1549		#[arg(long)]
1550		home: bool,
1551		/// How many bytes of files it keeps as an everyday device, such as 20GB: the files
1552		/// pinned to it, then the newest and those opened lately, while some device is an
1553		/// archive node; `default` for a tenth of its disk, or nothing on a phone.
1554		#[arg(long, value_name = "SIZE", value_parser = parse_keeps)]
1555		keeps: Option<Keeps>,
1556		/// How many days it waits as an archive node, from 1 to 365, before it destroys what a
1557		/// purge destroys, during which nib purges there can stop the purge; `none` for not at
1558		/// all, `default` for 30. A shorter wait, or none, holds only once the wait before it
1559		/// has passed, so that no infected device can shorten it and purge at once.
1560		#[arg(long, value_name = "DAYS", value_parser = parse_waits)]
1561		waits: Option<Waits>,
1562		/// Whether nib's copy of the library on this device takes the spaces made later on
1563		/// your other devices, as a computer does, or asks first, as a phone does, with nib
1564		/// space take: said only on the device itself, so that no other device can say it for
1565		/// it, and by each app's copy for itself.
1566		#[arg(long, value_enum, value_name = "take|ask")]
1567		new_spaces: Option<NewSpacesArg>,
1568	},
1569	/// Lists the changes of revoked devices that were set aside.
1570	///
1571	/// They were set aside as no device that revoked them had them; so are those of devices
1572	/// nobody added.
1573	Review,
1574	/// Accepts every change of a device that was set aside.
1575	///
1576	/// They count after all, with their own times. Changes that say who may write to the
1577	/// library, such as one that revokes another device, are never accepted. Without --yes,
1578	/// it says how many it would accept.
1579	Accept {
1580		/// The device, by its name or ID, one copy of the library by its ID, or an AI
1581		/// agent by its name.
1582		device: String,
1583		/// Accepts them.
1584		#[arg(long)]
1585		yes: bool,
1586	},
1587}
1588
1589/// What `nib edit` takes.
1590#[derive(Debug, Args)]
1591pub struct EditArgs {
1592	/// The entity, found by its ID, a prefix of its ID, or its name.
1593	entity: String,
1594	/// The changes.
1595	#[arg(required_unless_present_any = ["delete", "restore"])]
1596	changes: Vec<String>,
1597	/// When the values written were true: a date for something that happened, such as
1598	/// `2019-03`, or an interval for a state, such as `1990/2015`.
1599	#[arg(long, value_name = "DATE", value_parser = parse_edtf)]
1600	date: Option<Edtf>,
1601	/// Edits the entity as it was on this day, such as `2000-01-01`, instead of today:
1602	/// setting a field corrects the value it showed then.
1603	#[arg(long, value_name = "DAY", value_parser = parse_day)]
1604	on: Option<Day>,
1605	/// Deletes the entity: hides it and keeps it, until it is restored.
1606	#[arg(long, conflicts_with = "restore")]
1607	delete: bool,
1608	/// Restores a deleted entity.
1609	#[arg(long)]
1610	restore: bool,
1611	/// The language of the text, names and files written, such as `en` or `uk-Latn`,
1612	/// except for fields of codes, such as ISBNs, which are in no language.
1613	#[arg(long, value_name = "TAG", value_parser = parse_tag)]
1614	language: Option<Tag>,
1615	/// Works on forms, in other languages or scripts, rather than whole values:
1616	/// `field+=value` adds another form of the only value the field shows, and
1617	/// `field-=value` removes one form, where it would remove the value with every form.
1618	#[arg(long, conflicts_with = "form_of")]
1619	form: bool,
1620	/// As `--form`, with forms added to this value of the field, given in any of its forms.
1621	#[arg(long, value_name = "VALUE")]
1622	form_of: Option<String>,
1623}
1624
1625/// What `field+=value` and `field-=value` work on.
1626#[derive(Clone, Copy, Debug)]
1627enum Forms<'a> {
1628	/// Whole values.
1629	No,
1630	/// Forms; those added, of the only value the field shows.
1631	OfTheOnly,
1632	/// Forms; those added, of this value, given in any of its forms.
1633	Of(&'a str),
1634}
1635
1636/// What `nib type` can do. Names without a dot are your own, in the namespace `local`.
1637#[derive(Debug, Subcommand)]
1638pub enum TypeCommand {
1639	/// Defines a type, or adds fields to it.
1640	///
1641	/// Names that start with std. are the standard vocabulary's: a standard type takes fields
1642	/// of your own, and a type lists a standard field as the vocabulary defines it, but no
1643	/// new standard name is made.
1644	Add {
1645		/// The type's name, such as `book` or `org.example.book`.
1646		name: String,
1647		/// Its fields, as `name:kind`, with `:many`, `:lww`, `:secret` or `:role` after the
1648		/// kind; for quantities `:unit=` and a unit in UCUM, such as `:unit=kg`; for
1649		/// references `:stands-for`, `:search-through` and `:reverse=` and a field's name; and
1650		/// for text `:code`, for values in no language, such as ISBNs, which a language
1651		/// given with nib new or nib edit is not put on. The kinds are text, integer,
1652		/// boolean, date, reference, blob, decimal, quantity and name.
1653		fields: Vec<String>,
1654	},
1655	/// Shows a type's fields.
1656	Show {
1657		/// The type's name.
1658		name: String,
1659	},
1660	/// Lists the types.
1661	List,
1662}
1663
1664/// What `nib file` can do, in the personal space.
1665#[derive(Debug, Subcommand)]
1666pub enum FileCommand {
1667	/// Adds files, and the files in folders.
1668	///
1669	/// They are added in the order of their names: each with its name, its content's type
1670	/// and size, and where it was found, and a photo or a video with when, where and by
1671	/// which camera it was taken. Content that the library holds already is that file,
1672	/// found in one more place; a file found before at the same place, with the same size
1673	/// and modification time, is not read again. In folders, links, hidden files and
1674	/// folders, checkouts, and the library's own folder are left out. A file that cannot be
1675	/// read is reported, and the others are added all the same; an error of the library
1676	/// ends the command. Each photo, video or other picture gets a thumbnail, if nib reads
1677	/// its format: JPEG, PNG, GIF, WebP, BMP and TIFF.
1678	///
1679	/// With --secret, each file becomes a secret file, such as the scan of a passport: sealed
1680	/// for the secrets, so that only the devices that hold them read it, with its name, type
1681	/// and size readable by all, and nothing recorded of where it was found. The original
1682	/// stays where it is, unprotected. The library's first secret sets up its secrets, with
1683	/// a passphrase of their own.
1684	Add {
1685		/// The files and folders; with --secret, files only.
1686		#[arg(required = true)]
1687		paths: Vec<PathBuf>,
1688		/// Adds secret files.
1689		#[arg(long)]
1690		secret: bool,
1691		/// The entity, such as a login, to attach the secret files to; given again, several.
1692		#[arg(long, value_name = "ENTITY", requires = "secret")]
1693		to: Vec<String>,
1694		/// Where the files came from, such as an old phone, a disc or a drive, by a name of
1695		/// yours, such as `Mom's old phone`: made the first time, and recorded with where each
1696		/// file was found, with its path there from the folder given on.
1697		#[arg(long, value_name = "SOURCE", conflicts_with = "secret")]
1698		from: Option<String>,
1699	},
1700	/// Writes a plain copy of a file to open or edit in other apps.
1701	///
1702	/// The copy is of the file's current version, recorded as a checkout on this device:
1703	/// into a folder, under the file's name, or as a new file; without either, into the
1704	/// current folder. It replaces nothing, and a copy there already, unchanged, stays as
1705	/// it is. Checking in records its edits; a purge of the file's content deletes it,
1706	/// unless it was edited.
1707	Checkout {
1708		/// The file, by its ID, a prefix of its ID, or its name.
1709		file: String,
1710		/// The folder, or the path of the copy.
1711		path: Option<PathBuf>,
1712	},
1713	/// Says which disks hold a copy of a file, and how.
1714	///
1715	/// A copy is sealed in a store, with when it was last checked, or as a plain copy,
1716	/// where it was found or checked out. Copies count disks, as a copy is lost with its
1717	/// disk. What other devices hold is as their accounts last said, which each gives at
1718	/// its syncs.
1719	Where {
1720		/// The file, by its ID, a prefix of its ID, or its name.
1721		file: String,
1722	},
1723	/// Writes the thumbnail of a file, a JPEG, for scripts and tests.
1724	///
1725	/// Not listed beside nib file thumbnails, which most want.
1726	///
1727	/// The thumbnail is of the file's current version, the one every device shows, written
1728	/// into a file. A photo gets its thumbnail from the device
1729	/// that adds it, if that device reads its format; nib reads JPEG, PNG, GIF, WebP, BMP
1730	/// and TIFF.
1731	#[command(hide = true)]
1732	Thumbnail {
1733		/// The file, by its ID, a prefix of its ID, or its name.
1734		file: String,
1735		/// Where to write the JPEG, which must not exist yet.
1736		path: PathBuf,
1737	},
1738	/// Makes the thumbnails that files lack, from the copies here.
1739	///
1740	/// It makes those of the formats nib reads, whichever device added the files: for files
1741	/// added before thumbnails were made. The newest go first, by when a photo was taken,
1742	/// else when it was added.
1743	Thumbnails,
1744	/// Pins a file to a device of yours, which keeps it whatever its size.
1745	///
1746	/// The device is this one unless --device names another; it keeps the file from its next
1747	/// sync. Pins are yours alone, kept in your
1748	/// personal space.
1749	Pin {
1750		/// The file, by its ID, a prefix of its ID, or its name.
1751		file: String,
1752		/// The device, by its name or ID, or one copy of the library on it by its ID.
1753		#[arg(long)]
1754		device: Option<String>,
1755	},
1756	/// Unpins a file from a device of yours.
1757	///
1758	/// The device is this one unless --device names another; it then keeps the file only
1759	/// while it is among the newest files that fit its size.
1760	Unpin {
1761		/// The file, by its ID, a prefix of its ID, or its name.
1762		file: String,
1763		/// The device, by its name or ID, or one copy of the library on it by its ID.
1764		#[arg(long)]
1765		device: Option<String>,
1766	},
1767	/// Ends a checkout: its copy's edits become a new version.
1768	///
1769	/// The edits of the copy on this device become a new version of the file,
1770	/// sealed into the store, and the copy is deleted. A copy that is gone ends its
1771	/// checkout. Edits of a version that is no longer the file's own are refused, unless
1772	/// --force records them on top. A new version of a photo gets its own thumbnail.
1773	Checkin {
1774		/// The copy, by its path, or the file, if it is checked out in one place.
1775		copy: String,
1776		/// Keeps the copy, as a checkout of the new version.
1777		#[arg(long)]
1778		keep: bool,
1779		/// Records the edits of an older version on top of the file's newer one, which
1780		/// history keeps.
1781		#[arg(long)]
1782		force: bool,
1783	},
1784}
1785
1786/// What `nib secret` can do, in the personal space. The entity is found by its ID, a prefix
1787/// of its ID, or its name.
1788#[derive(Debug, Subcommand)]
1789pub enum SecretCommand {
1790	/// Sets a secret field of an entity, asking for the value.
1791	///
1792	/// It replaces the values the field has: asks for the value twice, without showing it,
1793	/// or with --generate, makes a new password. The library's first secret sets up its
1794	/// secrets, with a passphrase of their own. The secret of one-time codes,
1795	/// std.one-time-code, is taken as a site shows it: as base32 text, or as the otpauth://
1796	/// link of its QR code.
1797	Set {
1798		/// The entity.
1799		entity: String,
1800		/// The secret field.
1801		field: String,
1802		/// Sets a new random password, as the options below say, without showing it.
1803		#[arg(long)]
1804		generate: bool,
1805		/// What a generated password is made of.
1806		#[command(flatten)]
1807		recipe: RecipeArgs,
1808	},
1809	/// Copies a secret value to the clipboard, and clears it after a while.
1810	///
1811	/// The value of a secret field of an entity is marked so that clipboard histories leave it
1812	/// out, and clears it after a while, unless something
1813	/// else was copied since. nib waits until then; Ctrl+C clears it at once. Of values that
1814	/// compete, it copies the first.
1815	Copy {
1816		/// The entity.
1817		entity: String,
1818		/// The secret field.
1819		field: String,
1820		/// How many seconds the clipboard holds the secret.
1821		#[arg(long, value_name = "SECONDS", default_value_t = nibkeep_passwords::CLEAR_AFTER.as_secs())]
1822		clear_after: u64,
1823	},
1824	/// Prints a new random password, which nothing keeps.
1825	///
1826	/// For nib secret set, there is --generate.
1827	Generate {
1828		/// What the password is made of.
1829		#[command(flatten)]
1830		recipe: RecipeArgs,
1831	},
1832	/// Shows the one-time code of an entity now.
1833	///
1834	/// It says how many seconds the code lasts, made from the secret in a field:
1835	/// std.one-time-code, unless another is given.
1836	Code {
1837		/// The entity.
1838		entity: String,
1839		/// The secret field that holds the secret of one-time codes.
1840		field: Option<String>,
1841	},
1842	/// Shows the values of a secret field of an entity.
1843	Show {
1844		/// The entity.
1845		entity: String,
1846		/// The secret field.
1847		field: String,
1848	},
1849	/// Shows every value a secret field of an entity has had.
1850	///
1851	/// It shows them as `nib history` does.
1852	History {
1853		/// The entity.
1854		entity: String,
1855		/// The secret field.
1856		field: String,
1857	},
1858	/// Clears a secret field of an entity, keeping its history.
1859	///
1860	/// It shows no value from now on, and its history keeps those it had.
1861	Clear {
1862		/// The entity.
1863		entity: String,
1864		/// The secret field.
1865		field: String,
1866	},
1867	/// Purges one value of a secret field for good, everywhere.
1868	///
1869	/// The value of the entity's field, current or past, is asked for without showing it.
1870	/// Without --yes, it says what it would purge, and purges nothing.
1871	Purge {
1872		/// The entity.
1873		entity: String,
1874		/// The secret field.
1875		field: String,
1876		/// Purges for good, which cannot be undone.
1877		#[arg(long)]
1878		yes: bool,
1879	},
1880	/// Asks another of your devices for the library's secrets.
1881	///
1882	/// The device that holds them is named by its name, or one copy of the library on it,
1883	/// by its ID, as nib device list shows them: sets up the secrets here, with a
1884	/// passphrase of their own, asked for twice, and never the library's. That device gives
1885	/// them, with nib secret give; they arrive with the next sync, and this device takes
1886	/// them when its secrets are next unlocked. It takes them from that device alone. A
1887	/// device that asked already asks another this way, without a passphrase. nib protect
1888	/// --secrets moves them to the keystore. With --space naming a shared space, asks
1889	/// another member's device there for that space's secrets, by its name, or its ID as
1890	/// nib space show --json shows it; this device's secrets must be set up, and your other
1891	/// devices take the space's from it by themselves.
1892	Ask {
1893		/// The device that holds the secrets, or the ID of a copy of the library on it.
1894		from: String,
1895	},
1896	/// Gives the library's secrets to a device of yours that asked.
1897	///
1898	/// The device is named by its name, or one copy of the library on it, by its ID, as nib
1899	/// device list shows them. Asks for the passphrase of the secrets here; they reach it
1900	/// with the next sync. An AI agent never gets them. With --space naming a shared space,
1901	/// gives that space's secrets to another member's device there that asked this one, by
1902	/// its name or ID; your own devices get them by themselves.
1903	Give {
1904		/// The device, or the ID of a copy of the library on it.
1905		device: String,
1906	},
1907	/// Takes the secrets from a copy of the library beside this one.
1908	///
1909	/// The copy is beside this device's, which a backup, a program that syncs folders or a
1910	/// person brought from another device: only the keys that the copy's device was given.
1911	/// Asks for the passphrase of the copy's secrets, unless this computer's keystore holds
1912	/// their key, and for a passphrase of the secrets here, twice. Take them before
1913	/// revoking the copy's device, if it alone held them.
1914	FromCopy,
1915	/// Saves a plain copy of a secret file, which nothing records.
1916	///
1917	/// NibKeep neither protects it, nor keeps track of it, nor deletes it if the file is
1918	/// purged. Into a folder, under the file's name, or as a new file; without either, into
1919	/// the current folder. It replaces nothing.
1920	Save {
1921		/// The secret file.
1922		file: String,
1923		/// The folder, or the path of the copy.
1924		path: Option<PathBuf>,
1925	},
1926}
1927
1928/// What a generated password is made of: twenty characters of every kind, unless these
1929/// say otherwise.
1930#[derive(Debug, Clone, PartialEq, Eq, Args)]
1931#[expect(
1932	clippy::struct_excessive_bools,
1933	reason = "one flag for each kind of character, as nibkeep_passwords::Recipe has"
1934)]
1935pub struct RecipeArgs {
1936	/// How many characters the password has, from 4 to 1024; 20 unless given.
1937	#[arg(long)]
1938	pub length: Option<usize>,
1939	/// Leaves out lowercase letters.
1940	#[arg(long)]
1941	pub no_lowercase: bool,
1942	/// Leaves out uppercase letters.
1943	#[arg(long)]
1944	pub no_uppercase: bool,
1945	/// Leaves out digits.
1946	#[arg(long)]
1947	pub no_digits: bool,
1948	/// Leaves out symbols.
1949	#[arg(long)]
1950	pub no_symbols: bool,
1951	/// Leaves out characters that look like others, such as 0 and O, or 1 and l.
1952	#[arg(long)]
1953	pub unambiguous: bool,
1954}
1955
1956impl RecipeArgs {
1957	/// The recipe that these options ask for.
1958	fn recipe(&self) -> nibkeep_passwords::Recipe {
1959		let default = nibkeep_passwords::Recipe::default();
1960		nibkeep_passwords::Recipe {
1961			length: self.length.unwrap_or(default.length),
1962			lowercase: !self.no_lowercase,
1963			uppercase: !self.no_uppercase,
1964			digits: !self.no_digits,
1965			symbols: !self.no_symbols,
1966			unambiguous: self.unambiguous,
1967		}
1968	}
1969
1970	/// Whether any of these options was given.
1971	fn given(&self) -> bool {
1972		self.length.is_some()
1973			|| self.no_lowercase
1974			|| self.no_uppercase
1975			|| self.no_digits
1976			|| self.no_symbols
1977			|| self.unambiguous
1978	}
1979}
1980
1981/// What `nib policy` can do, in the personal space. A policy is found by its name, its ID or
1982/// a prefix of its ID; a rule by its number in `nib policy list`, its ID or a prefix of it.
1983#[derive(Debug, Subcommand)]
1984pub enum PolicyCommand {
1985	/// Lists the policies, and the rules in the order in which they choose.
1986	List,
1987	/// Shows a policy, and the rules that choose it.
1988	Show {
1989		/// The policy.
1990		policy: String,
1991	},
1992	/// Makes a policy.
1993	New {
1994		/// Its name.
1995		name: String,
1996		/// How many copies its files need.
1997		#[arg(long, default_value_t = 1)]
1998		copies: u32,
1999		/// How many of the copies are outside the home.
2000		#[arg(long, default_value_t = 0)]
2001		away: u32,
2002		/// How many of the copies are on archive nodes.
2003		#[arg(long, default_value_t = 0)]
2004		archived: u32,
2005		/// Keeps its files where they are, rather than in NibKeep's store.
2006		#[arg(long)]
2007		in_place: bool,
2008	},
2009	/// Changes a policy.
2010	Edit {
2011		/// The policy.
2012		policy: String,
2013		/// Its new name.
2014		#[arg(long)]
2015		name: Option<String>,
2016		/// How many copies its files need.
2017		#[arg(long)]
2018		copies: Option<u32>,
2019		/// How many of the copies are outside the home.
2020		#[arg(long)]
2021		away: Option<u32>,
2022		/// How many of the copies are on archive nodes.
2023		#[arg(long)]
2024		archived: Option<u32>,
2025		/// Keeps its files where they are.
2026		#[arg(long, conflicts_with = "store")]
2027		in_place: bool,
2028		/// Keeps its files in NibKeep's store.
2029		#[arg(long)]
2030		store: bool,
2031	},
2032	/// Removes a policy; its rules choose nothing.
2033	///
2034	/// The rules that choose it choose nothing, and the files that have it as their own get
2035	/// theirs from the rules.
2036	Remove {
2037		/// The policy.
2038		policy: String,
2039	},
2040	/// Works with the rules that choose a file's policy.
2041	Rule {
2042		/// What to do with rules.
2043		#[command(subcommand)]
2044		command: RuleCommand,
2045	},
2046	/// Gives a file a policy of its own, which wins over the rules.
2047	///
2048	/// With --clear, lets the rules choose again.
2049	Set {
2050		/// The file, or any entity.
2051		entity: String,
2052		/// The policy.
2053		#[arg(required_unless_present = "clear")]
2054		policy: Option<String>,
2055		/// Clears the file's own policy.
2056		#[arg(long, conflicts_with = "policy")]
2057		clear: bool,
2058	},
2059	/// Tells which policy a file has, and what chose it.
2060	Why {
2061		/// The file.
2062		entity: String,
2063	},
2064	/// Tells, for each policy, how many files it has, and which lack copies.
2065	///
2066	/// With one device, everything on it counts as one copy.
2067	Check,
2068}
2069
2070/// What `nib policy rule` can do.
2071#[derive(Debug, Subcommand)]
2072pub enum RuleCommand {
2073	/// Makes a rule: the files that meet every condition get the policy.
2074	///
2075	/// Without a place, it goes before the rule for any other file.
2076	New {
2077		/// The policy it chooses.
2078		policy: String,
2079		/// The file has this type, such as `std.photo`.
2080		#[arg(long = "type", value_name = "TYPE")]
2081		of_type: Option<String>,
2082		/// The file has a value of this field, such as `std.camera-make`.
2083		#[arg(long, value_name = "FIELD")]
2084		has: Option<String>,
2085		/// Every place the file was found is in this folder of this device, or below it.
2086		#[arg(long, value_name = "FOLDER")]
2087		folder: Option<PathBuf>,
2088		/// The file's media type is this one or starts with it, such as `video/`.
2089		#[arg(long, value_name = "TYPE")]
2090		media_type: Option<String>,
2091		/// The file is larger than this, such as `500MB` or `2GiB`.
2092		#[arg(long, value_name = "SIZE", value_parser = parse_size)]
2093		larger_than: Option<u64>,
2094		/// Adding a larger file that the rule chooses for asks whether it can be got again.
2095		#[arg(long, value_name = "SIZE", value_parser = parse_size)]
2096		asks_above: Option<u64>,
2097		/// Where the rule goes.
2098		#[command(flatten)]
2099		place: PlaceArgs,
2100	},
2101	/// Removes a rule.
2102	Remove {
2103		/// The rule.
2104		rule: String,
2105	},
2106	/// Moves a rule.
2107	Move {
2108		/// The rule.
2109		rule: String,
2110		/// Where it goes.
2111		#[command(flatten)]
2112		place: PlaceArgs,
2113	},
2114}
2115
2116/// Where a rule goes among the others.
2117#[derive(Debug, Args)]
2118pub struct PlaceArgs {
2119	/// First, where it wins over every other rule.
2120	#[arg(long, conflicts_with_all = ["last", "before", "after"])]
2121	first: bool,
2122	/// Last.
2123	#[arg(long, conflicts_with_all = ["before", "after"])]
2124	last: bool,
2125	/// Just before this rule.
2126	#[arg(long, value_name = "RULE", conflicts_with = "after")]
2127	before: Option<String>,
2128	/// Just after this rule.
2129	#[arg(long, value_name = "RULE")]
2130	after: Option<String>,
2131}
2132
2133/// How many of the entities that link to an entity through one field `nib show` lists.
2134const LINKS_SHOWN: usize = 10;
2135
2136/// Why a command failed.
2137#[derive(Debug, thiserror::Error)]
2138#[non_exhaustive]
2139pub enum CliError {
2140	/// An archive to import could not be read, or held nothing to import.
2141	#[error("{0}")]
2142	Import(String),
2143	/// A file has no thumbnail, as its device could not read its format, or it is no
2144	/// picture.
2145	#[error(
2146		"{0} has no thumbnail: the device that added it could not read its format, or it is no picture"
2147	)]
2148	NoThumbnail(String),
2149	/// Something is where a file would be written, which replaces nothing.
2150	#[error("{} exists already", .0.display())]
2151	Exists(PathBuf),
2152	/// No library was given, and the current folder is in none.
2153	#[error(
2154		"this folder is not in a library; if it is a tree's folder that lost its .nib file, run nib init FOLDER in your library's folder; otherwise make a library with nib init, or give one with --library or NIBKEEP_LIBRARY"
2155	)]
2156	NotInLibrary,
2157	/// The folder given as the library holds none.
2158	#[error("there is no library in {}", .0.display())]
2159	NoLibraryIn(PathBuf),
2160	/// The system lets nib not read a folder where a library would be, as macOS does with a
2161	/// removable drive until the person allows the terminal to reach it.
2162	#[error(
2163		"nib may not read {folder}: {error}; on a Mac, allow your terminal to reach removable volumes, in System Settings, Privacy & Security, Files and Folders",
2164		folder = .0.display(),
2165		error = .1
2166	)]
2167	NoAccess(PathBuf, #[source] io::Error),
2168	/// `NIBKEEP_LIBRARY` names a folder that holds no library.
2169	#[error("there is no library in {}, which NIBKEEP_LIBRARY names", .0.display())]
2170	NoDefaultLibrary(PathBuf),
2171	/// `NIBKEEP_LIBRARY` names a folder relative to the current one.
2172	#[error("NIBKEEP_LIBRARY names {}, which is not a full path", .0.display())]
2173	RelativeDefault(PathBuf),
2174	/// A library's `.nib` holds what is left of starting it, in this replica's folder.
2175	#[error(
2176		"a library was started in {}, but not finished; remove that folder to start again",
2177		.0.display()
2178	)]
2179	Unfinished(PathBuf),
2180	/// A library's `.nib` holds only copies of replicas made elsewhere, which are never used
2181	/// as the devices they were (technical design: copies of a replica).
2182	#[error(
2183		"the library in {} is a copy, made on another computer or drive, or in another folder, and is never used here as the device it was; to make this computer a device of its own, add it from another of your devices with nib device pair there and nib init --join here, which takes in what the copy holds, or, where no other device of yours can, use nib recovery from-copy",
2184		.0.display()
2185	)]
2186	IsCopy(PathBuf),
2187	/// `nib secret from-copy` found no secrets keys in the copies, or the person left the
2188	/// passphrase of the copy's secrets empty.
2189	#[error("no secrets were taken from a copy")]
2190	NoSecretsInCopies,
2191	/// `nib recovery from-copy` finds no copy in the library's `.nib`.
2192	#[error("there is no copy of a library in {}", .0.display())]
2193	NoCopy(PathBuf),
2194	/// `nib recovery from-copy` finds several copies, of which it would not know which to use.
2195	#[error("{} holds copies of several libraries' devices; keep the one to use", .0.display())]
2196	SeveralCopies(PathBuf),
2197	/// A library's `.nib` holds only copies of replicas made elsewhere, so a new library is
2198	/// not started there.
2199	#[error(
2200		"{} holds a copy of a library made on another computer or drive, or in another folder; join that library with nib init --join, or start one elsewhere",
2201		.0.display()
2202	)]
2203	CopiedHere(PathBuf),
2204	/// A library would be on a drive without a journal, which the person did not allow
2205	/// (technical design: drives without a journal).
2206	#[error(
2207		"{} is on a drive whose file system keeps no journal, as FAT32 and exFAT, which most USB sticks have: a library there can be damaged after the drive is removed without ejecting it, or loses its power; keep the library on another drive, or run again with --allow-fat to keep it there, and check the drive for errors after any such removal",
2208		.0.display()
2209	)]
2210	NoJournal(PathBuf),
2211	/// The drive of a library without a journal was removed, or lost its power, while the
2212	/// library was open.
2213	#[error(
2214		"the library in {} was not closed: its drive was removed without ejecting it, or lost its power, while the library was open, or a program that had it open was stopped, so its files may be damaged; check the drive for errors first, with Scan and fix on Windows, First Aid on a Mac or fsck on Linux, then run nib verify --drive-checked",
2215		.0.display()
2216	)]
2217	UncleanRemoval(PathBuf),
2218	/// A library would be started in what another library keeps.
2219	#[error("{} is in a library's own folder .nib; start the library elsewhere", .0.display())]
2220	InLibraryData(PathBuf),
2221	/// The current folder cannot be found.
2222	#[error("the current folder cannot be found: {0}")]
2223	NoCurrentFolder(#[source] io::Error),
2224	/// Ranked languages that cannot be read.
2225	#[error(transparent)]
2226	Languages(#[from] ParseLanguagesError),
2227	/// `--form` without forms to add or remove.
2228	#[error("--form adds and removes forms with field+=value and field-=value; there are none")]
2229	NoForms,
2230	/// Entities to merge that are one already.
2231	#[error("{entity} and {into} are one entity already")]
2232	OneAlready {
2233		/// The entity, as it was given.
2234		entity: String,
2235		/// The entity to merge it into, as it was given.
2236		into: String,
2237	},
2238	/// A merge to undo, of an entity that nothing was merged into.
2239	#[error("no entity was merged into {0}")]
2240	NothingMerged(String),
2241	/// A merge to undo, of one of several entities merged into another, not said which.
2242	#[error("say which entity to set apart from {entity}: {candidates}")]
2243	WhichMerged {
2244		/// The entity, as it was given.
2245		entity: String,
2246		/// The entities merged into it.
2247		candidates: String,
2248	},
2249	/// A merge to undo, of an entity that was not merged into the one given.
2250	#[error("no entity merged into {entity} is {other}")]
2251	NotMergedInto {
2252		/// The entity, as it was given.
2253		entity: String,
2254		/// The entity to set apart, as it was given.
2255		other: String,
2256	},
2257	/// A field that an entity never had, in `nib history`.
2258	#[error("the entity never had a field {0}")]
2259	NoHistory(String),
2260	/// A moment that cannot be used.
2261	#[error("the moment cannot be used: {0}")]
2262	Moment(String),
2263	/// An entity shown as recorded by a moment, when the library had no record of it yet.
2264	#[error("the library had no record of {entity} by {when}")]
2265	NotYet {
2266		/// The entity, as it was given.
2267		entity: String,
2268		/// The moment, for people.
2269		when: String,
2270	},
2271	/// The passphrase and its confirmation differ.
2272	#[error("the passphrases differ")]
2273	PassphrasesDiffer,
2274	/// The edits of a checkout's copy, made to a version that is no longer the file's own.
2275	#[error(
2276		"{} was checked out from a version that is no longer the file's own; --force records its edits on top, and history keeps both",
2277		.0.display()
2278	)]
2279	Stale(PathBuf),
2280	/// Files that could not be added, while the others were.
2281	#[error("{}", files_failed(*.0))]
2282	FilesFailed(usize),
2283	/// A file to check out that this device lacks, which none of the devices that hold it
2284	/// gave, as none was found on the network.
2285	#[error(
2286		"{name} is not on this device, and no device that holds it was found on the network: {}",
2287		holders.join(", ")
2288	)]
2289	NotFetched {
2290		/// The file.
2291		name: String,
2292		/// The devices that hold it, as their accounts say.
2293		holders: Vec<String>,
2294	},
2295	/// A file to check out that this device lacks, which the devices that hold it, as their
2296	/// accounts say, did not give, though a sync reached them.
2297	#[error(
2298		"{name} is not on this device, and did not come from {}, which hold it as their accounts say; they may have lost it, which nib verify there tells",
2299		holders.join(", ")
2300	)]
2301	NotGiven {
2302		/// The file.
2303		name: String,
2304		/// The devices that a sync reached.
2305		holders: Vec<String>,
2306	},
2307	/// Devices that could not be synced with, while the others were.
2308	#[error("{}", syncs_failed(*.0))]
2309	SyncsFailed(usize),
2310	/// The program that syncs this device did not answer `nib sync` in time.
2311	#[error("{0} did not sync in time; it may be busy with a long sync")]
2312	NotAnswered(String),
2313	/// `nib mcp` on a library that neither allows AI agents nor is an AI agent's.
2314	#[error(
2315		"AI agents are not allowed on this library here; allow them with nib mcp enable in its folder"
2316	)]
2317	NotAnAiAgent,
2318	/// `--client` names no AI client that `nib mcp enable` knows.
2319	#[error(
2320		"nib knows no AI client {0}; it knows Claude Code (claude) and Codex (codex), and --print gives the line for any other"
2321	)]
2322	UnknownAiClient(String),
2323	/// `nib mcp` on a library whose keys need a passphrase, without a file that holds it.
2324	#[error(
2325		"nib mcp serve asks for nothing on a terminal; give the library's passphrase with --passphrase-file"
2326	)]
2327	NoTerminal,
2328	/// A secret value and its confirmation differ.
2329	#[error("the values differ")]
2330	ValuesDiffer,
2331	/// A secret value to set is empty.
2332	#[error("the value is empty")]
2333	EmptyValue,
2334	/// A secret field, in a command that takes no secret values.
2335	#[error(
2336		"{0} is secret: nib secret set asks for its value without showing it, and nib secret clear clears it"
2337	)]
2338	SecretField(nibkeep_model::FieldName),
2339	/// A value of a secret field given on the command line, which shells keep.
2340	#[error(
2341		"{0} is secret, and its values are not given on the command line: nib secret purge asks for one without showing it, and {0}= purges every value it has had"
2342	)]
2343	SecretGiven(nibkeep_model::FieldName),
2344	/// The history of a secret field, which `nib history` leaves out.
2345	#[error("{0} is secret: nib secret history shows the values it has had")]
2346	SecretHistory(nibkeep_model::FieldName),
2347	/// A folder given to `nib file add --secret`, which takes files one by one.
2348	#[error("{} is a folder; nib file add --secret adds files one by one", .0.display())]
2349	SecretFolder(PathBuf),
2350	/// A secret file to check out, of which NibKeep records no copies.
2351	#[error(
2352		"{0} is a secret file, of which NibKeep records no copies; nib secret save writes one that nothing keeps track of"
2353	)]
2354	SecretFileCheckout(String),
2355	/// A field that is not secret, in `nib secret`.
2356	#[error("{0} is not secret; nib show and nib edit read and set it")]
2357	NotSecret(nibkeep_model::FieldName),
2358	/// A password that cannot be generated as asked.
2359	#[error(transparent)]
2360	Generator(#[from] nibkeep_passwords::GeneratorError),
2361	/// A secret of one-time codes that makes none.
2362	#[error(transparent)]
2363	OneTime(#[from] nibkeep_passwords::OneTimeError),
2364	/// The clipboard failed.
2365	#[error(transparent)]
2366	Clipboard(#[from] nibkeep_passwords::ClipboardError),
2367	/// Options for a generated password, without --generate.
2368	#[error("--length and the --no- options say what --generate makes; give --generate too")]
2369	RecipeWithoutGenerate,
2370	/// A generated secret of one-time codes, which only the site can give.
2371	#[error(
2372		"{0} holds the secret of one-time codes, which the site gives; --generate makes passwords"
2373	)]
2374	GeneratedOneTimeCode(nibkeep_model::FieldName),
2375	/// A rule that no number or ID names.
2376	#[error("there is no rule {0}; nib policy list numbers the rules")]
2377	NoRule(String),
2378	/// A rule to move, without saying where.
2379	#[error("say where the rule goes: --first, --last, --before RULE or --after RULE")]
2380	WhereTo,
2381	/// Secrets to unlock, in a library that has none.
2382	#[error("the library holds no secrets yet; nib secret set stores the first")]
2383	NoSecrets,
2384	/// A secret field without values, in `nib secret show`.
2385	#[error("{entity} has no value of {field}")]
2386	NoSecretValue {
2387		/// The entity, as it was given.
2388		entity: String,
2389		/// The field.
2390		field: nibkeep_model::FieldName,
2391	},
2392	/// The passphrase is empty.
2393	#[error("the passphrase is empty")]
2394	EmptyPassphrase,
2395	/// The file that gives the passphrase cannot be read.
2396	#[error("the passphrase file {} cannot be read: {error}", path.display())]
2397	PassphraseFile {
2398		/// The file.
2399		path: PathBuf,
2400		/// Why not.
2401		error: io::Error,
2402	},
2403	/// The file that gives the passphrase can be read by others.
2404	#[error("others can read the passphrase file {}; make it yours alone, such as with chmod 600", .0.display())]
2405	PassphraseFileOpen(PathBuf),
2406	/// Syncing from login, for a library whose keys a passphrase protects.
2407	#[error(
2408		"syncing from login needs the library's keys in the keystore, as nobody is there to type a passphrase at login; nib protect puts them there"
2409	)]
2410	AtLoginPassphrase,
2411	/// No home folder to keep the list of libraries synced from login in.
2412	#[error("there is no home folder here to keep the list of libraries synced from login in")]
2413	NoStateFolder,
2414	/// No `nibkeep-sync` beside `nib`.
2415	#[error(
2416		"nibkeep-sync, which syncs from login, is not installed beside nib; cargo install --path apps/nib installs both"
2417	)]
2418	NoSyncProgram,
2419	/// The library's keys are in the platform's keystore, which is not there.
2420	#[error("the library's keys are in the platform's keystore, which is not available")]
2421	NoKeystore,
2422	/// The platform's keystore failed while a library was started.
2423	#[error("the platform's keystore failed ({0}); start the library with --passphrase instead")]
2424	Keystore(NodeError),
2425	/// No keystore to protect a library's keys or its secrets with.
2426	#[error(
2427		"there is no platform keystore here; nib protect --passphrase protects with a passphrase"
2428	)]
2429	NoKeystoreToProtect,
2430	/// The platform's keystore failed while protecting a library's keys or its secrets.
2431	#[error(
2432		"the platform's keystore failed ({0}); nib protect --passphrase protects with a passphrase"
2433	)]
2434	KeystoreToProtect(NodeError),
2435	/// A name is not valid.
2436	#[error("{0} is not a valid name")]
2437	Name(String),
2438	/// A name that a person gives is a standard one, which only the standard vocabulary
2439	/// gives, so that a later version's standard field never meets another kind of it.
2440	#[error(
2441		"{name} is a standard name, which only the standard vocabulary gives; choose another \
2442		 {what} name, such as one starting with local."
2443	)]
2444	StandardName {
2445		/// The name given.
2446		name: String,
2447		/// What it names: a type or a field.
2448		what: &'static str,
2449	},
2450	/// A field is not given as `name:kind`.
2451	#[error(
2452		"a field is name:kind, with flags such as :many, :lww, :secret or :role after it, not {0}"
2453	)]
2454	Field(String),
2455	/// There is no such kind of value.
2456	#[error("there is no kind of value called {kind}; the kinds are {kinds}")]
2457	Kind {
2458		/// The kind given.
2459		kind: String,
2460		/// The kinds there are.
2461		kinds: String,
2462	},
2463	/// There is no such flag for a field.
2464	#[error(
2465		"there is no flag {0} for a field; the flags are many, lww, secret, role, stands-for, search-through, code, unit= and reverse="
2466	)]
2467	Flag(String),
2468	/// A field's flags contradict each other, or repeat.
2469	#[error("{0}")]
2470	Flags(String),
2471	/// There is no such type.
2472	#[error("there is no type {0}; define it with nib type add")]
2473	NoType(TypeName),
2474	/// Several types end in the name.
2475	#[error("{name} could be any of the types {candidates}")]
2476	AmbiguousType {
2477		/// The name as given.
2478		name: String,
2479		/// The types it could be.
2480		candidates: String,
2481	},
2482	/// The types have no such field.
2483	#[error(
2484		"{types} has no field {field}; give its full name, such as local.{field}, for a field that no type defines"
2485	)]
2486	NoField {
2487		/// The field as given.
2488		field: String,
2489		/// The types.
2490		types: String,
2491	},
2492	/// Several fields of the types end in the name.
2493	#[error("{field} could be any of the fields {candidates}")]
2494	AmbiguousField {
2495		/// The field as given.
2496		field: String,
2497		/// The fields it could be.
2498		candidates: String,
2499	},
2500	/// Types set, or cleared, rather than given or taken away one by one.
2501	#[error("an entity's types are given with type+=TYPE and taken away with type-=TYPE")]
2502	TypeSet,
2503	/// A value is not given as `field=value`.
2504	#[error("a value is field=value, not {0}")]
2505	Assignment(String),
2506	/// Checking the library found something wrong.
2507	#[error("{}", unsound(*.0))]
2508	Unsound(usize),
2509	/// An export that differs from the library, with how many problems were found.
2510	#[error("{}", unsound_export(*.0))]
2511	UnsoundExport(usize),
2512	/// A purge was not confirmed.
2513	#[error("nothing was purged; add --yes to purge for good")]
2514	Unconfirmed,
2515	/// A move of a folder or a list, with all it holds, was not confirmed.
2516	#[error("nothing was moved; add --yes to move them all")]
2517	UnconfirmedMove,
2518	/// Starting a tree was not confirmed.
2519	#[error("no tree was started; add --yes to start it")]
2520	UnconfirmedStart,
2521	/// Pinning a folder that holds no Git repository with a commit.
2522	#[error("{} holds no Git repository with a commit to pin", .0.display())]
2523	NoGitCommit(PathBuf),
2524	/// A tree's command run outside every tree's folder on this device.
2525	#[error("{} is in no tree's folder on this device; nib init makes it one", .0.display())]
2526	NotInTree(PathBuf),
2527	/// A command that reads a tree's history run outside every tree's folder on this device,
2528	/// with no tree named.
2529	#[error(
2530		"{} is in no tree's folder on this device: name a tree with --tree, or see an entity's values with nib history",
2531		.0.display()
2532	)]
2533	NoTreeHere(PathBuf),
2534	/// `nib init` given a folder, a message or --yes, to make a tree, where neither that folder
2535	/// nor the current one is in a library.
2536	#[error(
2537		"neither {} nor the current folder is in a library: run nib init FOLDER in your library's folder, nib init alone to make a library here, or nib init --join CODE to join yours from another device",
2538		.0.display()
2539	)]
2540	NoLibraryForTree(PathBuf),
2541	/// A `.nib` file in a folder that names no library nib may open.
2542	#[error("{} should name the library of the tree in its folder, but {why}", .file.display())]
2543	BadPointer {
2544		/// The file.
2545		file: PathBuf,
2546		/// What is wrong with it.
2547		why: String,
2548	},
2549	/// A `.nib` file that names a library which keeps no tree in that folder on this device, as
2550	/// a copy of a tree's folder would.
2551	#[error(
2552		"{} names the library in {}, which keeps no tree in that folder on this device: nib init there makes the folder a tree, and deleting the file leaves the folder out of the library",
2553		.file.display(),
2554		.library.display()
2555	)]
2556	StrayPointer {
2557		/// The file.
2558		file: PathBuf,
2559		/// The library's folder.
2560		library: PathBuf,
2561	},
2562	/// A command about the library's place, run where only a tree's `.nib` file names the
2563	/// library.
2564	#[error(
2565		"{} names the library for the commands of the tree in its folder; run this in the library's folder, or name the library with --library",
2566		.0.display()
2567	)]
2568	ThroughPointer(PathBuf),
2569	/// Something other than a file where the `.nib` file of a tree outside the library's
2570	/// folder goes.
2571	#[error(
2572		"{} is no file: nib keeps a file there that names the library of a tree outside the library's folder",
2573		.0.display()
2574	)]
2575	PointerInTheWay(PathBuf),
2576	/// The `.nib` file of a tree outside the library's folder could not be written.
2577	#[error(
2578		"{} could not be written: {error}; the tree is there, and nib init {} in the library's folder writes the file again",
2579		.file.display(),
2580		pointer::folder_of(.file)
2581	)]
2582	PointerNotWritten {
2583		/// The file.
2584		file: PathBuf,
2585		/// Why not.
2586		error: io::Error,
2587	},
2588	/// The `.nib` file of a tree inside the library's folder, which would take over the
2589	/// commands there, could not be deleted.
2590	#[error(
2591		"{} could not be deleted: {error}; the tree is there, and once the file is gone, commands in {} find the library",
2592		.file.display(),
2593		pointer::folder_of(.file)
2594	)]
2595	PointerNotTakenAway {
2596		/// The file.
2597		file: PathBuf,
2598		/// Why not.
2599		error: io::Error,
2600	},
2601	/// `nib init` without --name, where the system names no account to name the user after.
2602	#[error("the system names no account for you: give your name with nib init --name YOUR-NAME")]
2603	NoAccountName,
2604	/// A command of other version control systems that nib does not have.
2605	#[error("there is no {verb} command: {instead}")]
2606	NoSuchCommand {
2607		/// The command.
2608		verb: &'static str,
2609		/// What to do instead.
2610		instead: &'static str,
2611	},
2612	/// `nib revert` given a path, as Mercurial's revert takes, rather than a revision.
2613	#[error(
2614		"{0} is no revision: nib revert undoes a revision, and nib restore {0} writes a file as it was"
2615	)]
2616	RevertTakesRevision(String),
2617	/// A revocation was not confirmed.
2618	#[error("nothing was revoked; add --yes to revoke for good")]
2619	UnconfirmedRevoke,
2620	/// Whether another device takes new spaces, which only that device says.
2621	#[error("only {0} says whether it takes new spaces: run nib device mark --new-spaces there")]
2622	NewSpacesElsewhere(String),
2623	/// What was typed was no recovery code, each time it was asked for.
2624	#[error("that was no recovery code; nothing was changed")]
2625	NotARecoveryCode,
2626	/// A recovery in place of a library here that still unlocks with the keystore, which it
2627	/// would only revoke.
2628	#[error(
2629		"the library here still unlocks with this computer's keystore: there is nothing to recover, and a recovery would only revoke it"
2630	)]
2631	StillUnlocks,
2632	/// The recovery code typed is none that the library names.
2633	#[error("the library names no such recovery code")]
2634	UnknownRecoveryCode,
2635	/// Accepting changes that were set aside was not confirmed.
2636	#[error("nothing was accepted; add --yes to accept them")]
2637	UnconfirmedAccept,
2638	/// Leaving a space was not confirmed.
2639	#[error("you did not leave; add --yes to leave")]
2640	UnconfirmedLeave,
2641	/// Removing a member was not confirmed.
2642	#[error("nobody was removed; add --yes to remove them")]
2643	UnconfirmedRemove,
2644	/// Claiming the admin role was not confirmed.
2645	#[error("nothing was claimed; add --yes to claim the admin role")]
2646	UnconfirmedClaim,
2647	/// An invitation without --yes, where there is no terminal to ask whether to add whoever
2648	/// asks.
2649	#[error(
2650		"nobody can be asked whether to add whoever joins, as there is no terminal; run it on a terminal, or add --yes to add whoever joins with the code"
2651	)]
2652	UnconfirmedInvite,
2653	/// A field is set and cleared in one edit.
2654	#[error("{0} is both set and cleared")]
2655	SetAndCleared(nibkeep_model::FieldName),
2656	/// A value cannot be read as its field's kind says.
2657	#[error("{field} takes {expected}")]
2658	Value {
2659		/// The field.
2660		field: nibkeep_model::FieldName,
2661		/// What it takes.
2662		expected: &'static str,
2663	},
2664	/// A name or a prefix of an ID that several entities have.
2665	#[error(
2666		"{reference} could be any of {count} entities; give the ID, or its start:\n{candidates}"
2667	)]
2668	Ambiguous {
2669		/// The name or prefix, as it was given.
2670		reference: String,
2671		/// How many entities have it.
2672		count: usize,
2673		/// Some of them, one per line, by short ID, name and types.
2674		candidates: String,
2675	},
2676	/// The engine failed.
2677	#[error(transparent)]
2678	Node(#[from] NodeError),
2679	/// Reading or writing failed.
2680	#[error(transparent)]
2681	Io(#[from] std::io::Error),
2682}
2683
2684/// How long the parts of a command took. A part that the command had no need of is `None`:
2685/// `nib init` opens no library, and makes and protects its keys as part of its work.
2686#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2687pub struct Timings {
2688	/// Waiting for someone to type a passphrase, which no other part includes.
2689	pub waiting: Option<Duration>,
2690	/// Unlocking the library's keys: reading them, reaching the platform's keystore, and
2691	/// deriving a key from a passphrase, which is slow on purpose.
2692	pub unlock: Option<Duration>,
2693	/// Opening the spaces: reading their logs, and building their indexes.
2694	pub open: Option<Duration>,
2695	/// The command's own work.
2696	pub work: Duration,
2697	/// Writing out what the command has to say.
2698	pub print: Duration,
2699}
2700
2701impl Timings {
2702	/// The parts that the command had, by name, in the order they came.
2703	fn parts(&self) -> Vec<(&'static str, Duration)> {
2704		let mut parts = Vec::new();
2705		for (name, part) in [
2706			("waiting", self.waiting),
2707			("unlock", self.unlock),
2708			("open", self.open),
2709		] {
2710			if let Some(duration) = part {
2711				parts.push((name, duration));
2712			}
2713		}
2714		parts.push(("work", self.work));
2715		parts.push(("print", self.print));
2716		parts
2717	}
2718
2719	/// The timings for people, such as `unlock 0.412 s, open 1.603 s, work 0.010 s, print
2720	/// 0.001 s`, or as one line of JSON with seconds, such as `{"unlock_seconds":0.412,
2721	/// …}`. Parts that the command had no need of are left out.
2722	#[must_use]
2723	pub fn describe(&self, json: bool) -> String {
2724		let parts = self.parts();
2725		if json {
2726			let object: serde_json::Map<String, serde_json::Value> = parts
2727				.iter()
2728				.map(|(part, duration)| (format!("{part}_seconds"), duration.as_secs_f64().into()))
2729				.collect();
2730			return serde_json::Value::Object(object).to_string();
2731		}
2732		parts
2733			.iter()
2734			.map(|(part, duration)| format!("{part} {:.3} s", duration.as_secs_f64()))
2735			.collect::<Vec<_>>()
2736			.join(", ")
2737	}
2738
2739	/// The sum of the parts before the work.
2740	fn before_work(&self) -> Duration {
2741		[self.waiting, self.unlock, self.open]
2742			.into_iter()
2743			.flatten()
2744			.sum()
2745	}
2746}
2747
2748/// Adds to a part of the timings.
2749fn add(part: &mut Option<Duration>, duration: Duration) {
2750	*part = Some(part.unwrap_or_default() + duration);
2751}
2752
2753/// Runs a command, and writes what it has to say to `output`.
2754///
2755/// # Errors
2756///
2757/// Returns an error if the command fails.
2758pub fn run<E: Environment>(
2759	cli: &Cli,
2760	environment: &mut E,
2761	output: &mut dyn Write,
2762) -> Result<(), CliError> {
2763	// The parts are timed only when asked for, so that every write is not.
2764	run_command(cli, environment, output, &mut Timings::default())
2765}
2766
2767/// Runs a command as [`run`] does, and tells how long its parts took.
2768///
2769/// # Errors
2770///
2771/// Returns an error if the command fails.
2772pub fn run_timed<E: Environment>(
2773	cli: &Cli,
2774	environment: &mut E,
2775	output: &mut dyn Write,
2776) -> Result<Timings, CliError> {
2777	let started = Instant::now();
2778	let mut timings = Timings::default();
2779	let mut timed = Timed {
2780		inner: output,
2781		spent: Duration::ZERO,
2782	};
2783	run_command(cli, environment, &mut timed, &mut timings)?;
2784	// What is still buffered is written now, so that printing counts all of it.
2785	timed.flush()?;
2786	timings.print = timed.spent;
2787	timings.work = started
2788		.elapsed()
2789		.saturating_sub(timings.before_work() + timings.print);
2790	Ok(timings)
2791}
2792
2793/// A line for the terminal, with the characters that it would hide or act on, but line
2794/// breaks, written as escapes: a carriage return as `\r`, an escape as `\u{1b}`, and the
2795/// invisible ones that hide or reorder text, as a zero-width space or a right-to-left
2796/// override. So an argument that a script read on Windows, ending in a carriage return,
2797/// shows it, and a name or path that another device wrote cannot change what the terminal
2798/// shows in an error, a note or a question. What commands print on standard output is left
2799/// as it is, for other programs to read.
2800#[must_use]
2801pub fn printable(line: &str) -> std::borrow::Cow<'_, str> {
2802	fn hidden(c: char) -> bool {
2803		(c.is_control() && c != '\n')
2804			|| matches!(c, '\u{200b}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}' | '\u{feff}')
2805	}
2806	if !line.chars().any(hidden) {
2807		return line.into();
2808	}
2809	line.chars()
2810		.map(|c| {
2811			if hidden(c) {
2812				c.escape_debug().to_string()
2813			} else {
2814				c.to_string()
2815			}
2816		})
2817		.collect::<String>()
2818		.into()
2819}
2820
2821/// A writer that writes until nothing reads what it writes, as when `head` has read
2822/// enough, and then takes what is written without writing it: a command finishes its work
2823/// whether or not its output is read, and says nothing of output that nobody reads.
2824pub struct UntilUnread<W> {
2825	inner: W,
2826	unread: bool,
2827}
2828
2829impl<W> UntilUnread<W> {
2830	/// Writes to `inner` until nothing reads it.
2831	pub const fn new(inner: W) -> Self {
2832		Self {
2833			inner,
2834			unread: false,
2835		}
2836	}
2837
2838	/// The result of writing, or of flushing, with a broken pipe taken as nothing reading.
2839	fn read_or_not<T>(&mut self, done: io::Result<T>, nothing: T) -> io::Result<T> {
2840		match done {
2841			Err(error) if error.kind() == io::ErrorKind::BrokenPipe => {
2842				self.unread = true;
2843				Ok(nothing)
2844			}
2845			done => done,
2846		}
2847	}
2848}
2849
2850impl<W: Write> Write for UntilUnread<W> {
2851	fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
2852		if self.unread {
2853			return Ok(bytes.len());
2854		}
2855		let written = self.inner.write(bytes);
2856		self.read_or_not(written, bytes.len())
2857	}
2858
2859	fn flush(&mut self) -> io::Result<()> {
2860		if self.unread {
2861			return Ok(());
2862		}
2863		let flushed = self.inner.flush();
2864		self.read_or_not(flushed, ())
2865	}
2866}
2867
2868/// A writer that counts the time spent writing.
2869struct Timed<'a> {
2870	inner: &'a mut dyn Write,
2871	spent: Duration,
2872}
2873
2874impl Write for Timed<'_> {
2875	fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
2876		let started = Instant::now();
2877		let written = self.inner.write(bytes);
2878		self.spent += started.elapsed();
2879		written
2880	}
2881
2882	fn flush(&mut self) -> io::Result<()> {
2883		let started = Instant::now();
2884		let flushed = self.inner.flush();
2885		self.spent += started.elapsed();
2886		flushed
2887	}
2888}
2889
2890fn run_command<E: Environment>(
2891	cli: &Cli,
2892	environment: &mut E,
2893	output: &mut dyn Write,
2894	timings: &mut Timings,
2895) -> Result<(), CliError> {
2896	// As the replicas it opens record it, beside the apps.
2897	nibkeep_node::name_program(APP);
2898	if let Command::Absent(absent) = &cli.command {
2899		let (verb, instead) = absent.instead();
2900		return Err(CliError::NoSuchCommand { verb, instead });
2901	}
2902	if let Command::Secret {
2903		command: SecretCommand::Generate { recipe },
2904	} = &cli.command
2905	{
2906		return generate_command(recipe, cli.json, environment, output);
2907	}
2908	let (found, making) = command_folder(cli, environment)?;
2909	place_not_through_pointer(cli, &found)?;
2910	let folder = found.folder.clone();
2911	let directory = folder.join(LIBRARY_DATA);
2912	if let Command::Mcp {
2913		action: McpAction::Serve { .. },
2914	} = &cli.command
2915	{
2916		return mcp::serve(cli, environment, output);
2917	}
2918	if making {
2919		let library = new_library(&directory, cli, environment, timings, output)?;
2920		let zone = environment.time_zone();
2921		let checks = output::Checks {
2922			status: None,
2923			name_of: &|_, _| None,
2924			zone: &zone,
2925		};
2926		let status = (
2927			&library.status()?,
2928			&[][..],
2929			&std::collections::BTreeMap::new(),
2930		);
2931		return output::status(status, checks, &folder, cli.json, output);
2932	}
2933	if let Command::Verify {
2934		drive_checked: true,
2935		..
2936	} = &cli.command
2937	{
2938		Library::drive_checked(&directory)?;
2939	}
2940	if let Command::Sync {
2941		at_login: Some(switch),
2942		..
2943	} = &cli.command
2944	{
2945		return at_login_command(*switch, &directory, cli, environment, timings, output);
2946	}
2947	let opened = open(
2948		&directory,
2949		cli.passphrase_file.as_deref(),
2950		environment,
2951		timings,
2952	);
2953	let mut library = opened.map_err(|error| opened_error(error, &directory))?;
2954	check_found(&library, &found, cli, environment)?;
2955	if library.told_of_syncing()? {
2956		environment.note(SYNCED_BY_PROGRAM);
2957	}
2958	if let Some(space) = &cli.space {
2959		let space = library.find_space(space)?;
2960		library.choose_space(Some(space))?;
2961	}
2962	if let Command::Sync { serve: true, .. } = &cli.command {
2963		return serve_command(library, cli, environment, output);
2964	}
2965	if let Command::Secret {
2966		command: SecretCommand::Copy {
2967			entity,
2968			field,
2969			clear_after,
2970		},
2971	} = &cli.command
2972	{
2973		// The clipboard first, before the passphrase is asked for; and the library is closed
2974		// while the copy waits, for other programs to use.
2975		let board = environment.clipboard()?;
2976		let read = read_secret(&mut library, entity, field, environment, timings)
2977			.map_err(|error| candidates_named(&library, error, environment))?;
2978		drop(library);
2979		return copy_and_clear(board, &read, *clear_after, cli.json, environment, output);
2980	}
2981	let ran = match &cli.command {
2982		Command::Backup { .. } | Command::Recovery { .. } => {
2983			safekeeping_command(&mut library, cli, environment, timings, output)
2984		}
2985		Command::Purges { command } => purges_waiting_command(
2986			&mut library,
2987			command.as_ref(),
2988			cli.json,
2989			environment,
2990			output,
2991		),
2992		_ => library_command(&mut library, cli, &folder, environment, timings, output),
2993	};
2994	// An entity named ambiguously is told apart by what the library knows of each.
2995	ran.map_err(|error| candidates_named(&library, error, environment))
2996}
2997
2998/// Refuses what concerns the library's place where only a tree's `.nib` file names the
2999/// library: it runs before the library opens, so before the file could be checked, and
3000/// belongs to no tree.
3001fn place_not_through_pointer(cli: &Cli, found: &Found) -> Result<(), CliError> {
3002	let place = matches!(
3003		&cli.command,
3004		Command::Verify {
3005			drive_checked: true,
3006			..
3007		} | Command::Sync {
3008			at_login: Some(_),
3009			..
3010		}
3011	);
3012	match &found.named_in {
3013		Some(file) if place => Err(CliError::ThroughPointer(file.clone())),
3014		_ => Ok(()),
3015	}
3016}
3017
3018/// Refuses a library that a tree's `.nib` file named, unless it keeps that tree
3019/// ([`pointer::check`]). `nib init` takes the file in the folder it makes a tree, which it
3020/// then writes anew, as in a copy of a tree's folder.
3021fn check_found<E: Environment>(
3022	library: &Library,
3023	found: &Found,
3024	cli: &Cli,
3025	environment: &E,
3026) -> Result<(), CliError> {
3027	let starting = match &cli.command {
3028		Command::Init { folder, .. } => Some(match folder {
3029			Some(folder) => absolute(folder, environment)?,
3030			None => current_dir(environment)?,
3031		}),
3032		_ => None,
3033	};
3034	Ok(pointer::check(library, found, starting.as_deref())?)
3035}
3036
3037/// The folder of the library that a command works in, and whether the command makes it: for
3038/// `nib init` that makes a library, where it goes; for one that makes a tree, the library it
3039/// goes into, as for the other commands. `nib init` alone, where it finds no library, makes
3040/// one, as `git init` makes a repository.
3041fn command_folder<E: Environment>(cli: &Cli, environment: &E) -> Result<(Found, bool), CliError> {
3042	if cli.command.makes_library() {
3043		return Ok((
3044			Found::library(new_library_folder(cli.library.as_deref(), environment)?),
3045			true,
3046		));
3047	}
3048	if let Command::Init {
3049		folder,
3050		message,
3051		yes,
3052		..
3053	} = &cli.command
3054	{
3055		// The library that holds the folder to make a tree, as Git finds a repository, or else
3056		// that of the current folder, as git worktree add takes it.
3057		let from = match folder {
3058			Some(folder) => absolute(folder, environment)?,
3059			None => current_dir(environment)?,
3060		};
3061		let here = environment.current_dir().ok();
3062		let places: Vec<&Path> = std::iter::once(from.as_path())
3063			.chain(here.as_deref())
3064			.collect();
3065		let given = cli.library.as_deref();
3066		let alone = folder.is_none() && message.is_none() && !yes;
3067		let found = match library_folder_from(given, &places, environment) {
3068			// A file there that names no library, as after the library's folder moved, is
3069			// written again, in the current folder's library.
3070			Err(CliError::BadPointer { file, .. }) if file == from.join(LIBRARY_DATA) => {
3071				library_folder_from(given, &places[1..], environment)
3072			}
3073			found => found,
3074		};
3075		return match found {
3076			Ok(found) => Ok((found, false)),
3077			Err(CliError::NotInLibrary | CliError::NoLibraryIn(_)) if alone => Ok((
3078				Found::library(new_library_folder(given, environment)?),
3079				true,
3080			)),
3081			Err(CliError::NotInLibrary) => Err(CliError::NoLibraryForTree(from)),
3082			Err(error) => Err(error),
3083		};
3084	}
3085	if let (
3086		Command::Sync {
3087			at_login: Some(Switch::Off),
3088			..
3089		},
3090		Some(given),
3091	) = (&cli.command, cli.library.as_deref())
3092	{
3093		// A library deleted or moved since stays listed, until turned off by its old folder.
3094		return Ok((
3095			Found::library(resolved(absolute(given, environment)?)),
3096			false,
3097		));
3098	}
3099	Ok((library_folder(cli.library.as_deref(), environment)?, false))
3100}
3101
3102impl Command {
3103	/// Whether it is a command of trees, `nib init` among them where it makes no library, or
3104	/// `nib status`, which shows a tree's status in its folder.
3105	const fn is_of_trees(&self) -> bool {
3106		matches!(
3107			self,
3108			Self::Init { .. } | Self::Status { .. } | Self::Trees(_) | Self::Pull { .. }
3109		)
3110	}
3111
3112	/// Whether it makes a library on this computer: `nib init` told to make one or join one,
3113	/// rather than a tree in a library, by any of the arguments that only a new library takes,
3114	/// or `nib recovery` that brings one back. Without them, `nib init` makes a library only
3115	/// where none is found.
3116	const fn makes_library(&self) -> bool {
3117		matches!(
3118			self,
3119			Self::Init {
3120				name,
3121				join,
3122				device,
3123				passphrase,
3124				languages,
3125				allow_fat,
3126				..
3127			} if name.is_some()
3128				|| join.is_some()
3129				|| device.is_some()
3130				|| *passphrase
3131				|| languages.is_some()
3132				|| *allow_fat
3133		) || matches!(
3134			self,
3135			Self::Recovery {
3136				command: RecoveryCommand::Restore { .. } | RecoveryCommand::FromCopy { .. }
3137			}
3138		)
3139	}
3140}
3141
3142/// The library that a command other than `nib init` works in, as Git finds a repository:
3143/// the one given; or else the nearest of the current folder and those it is in, below the
3144/// environment's ceiling, whose `.nib` holds a library, or is a file in a tree's folder that
3145/// names one; or else the one that the environment names.
3146fn library_folder<E: Environment>(
3147	given: Option<&Path>,
3148	environment: &E,
3149) -> Result<Found, CliError> {
3150	if given.is_some() {
3151		return library_folder_from(given, &[], environment);
3152	}
3153	library_folder_from(given, &[&current_dir(environment)?], environment)
3154}
3155
3156/// The library that [`library_folder`] finds, looked for from each of `places` in turn
3157/// rather than from the current folder.
3158fn library_folder_from<E: Environment>(
3159	given: Option<&Path>,
3160	places: &[&Path],
3161	environment: &E,
3162) -> Result<Found, CliError> {
3163	if let Some(given) = given {
3164		let folder = resolved(absolute(given, environment)?);
3165		if !holds_library(&folder) {
3166			return Err(match unreadable(&folder) {
3167				Some(error) => CliError::NoAccess(folder, error),
3168				None => CliError::NoLibraryIn(folder),
3169			});
3170		}
3171		return Ok(Found::library(folder));
3172	}
3173	let ceiling = environment.ceiling();
3174	for here in places {
3175		if let Some(found) = pointer::nearest(here, ceiling.as_deref())? {
3176			return Ok(found);
3177		}
3178		if let Some(error) = unreadable(here) {
3179			return Err(CliError::NoAccess(here.to_path_buf(), error));
3180		}
3181	}
3182	let named = environment
3183		.default_library()
3184		.ok_or(CliError::NotInLibrary)?;
3185	// Relative to every folder in turn, it would name another library in each.
3186	if !named.is_absolute() {
3187		return Err(CliError::RelativeDefault(named));
3188	}
3189	let named = resolved(named);
3190	if !holds_library(&named) {
3191		return Err(CliError::NoDefaultLibrary(named));
3192	}
3193	Ok(Found::library(named))
3194}
3195
3196/// The folder that `nib init` makes a library: the one given, or else the current folder,
3197/// as the file system will resolve it, and never in a library's own `.nib`. Nothing is
3198/// made yet.
3199fn new_library_folder<E: Environment>(
3200	given: Option<&Path>,
3201	environment: &E,
3202) -> Result<PathBuf, CliError> {
3203	let folder = match given {
3204		Some(given) => absolute(given, environment)?,
3205		None => current_dir(environment)?,
3206	};
3207	let folder = resolved(folder);
3208	if folder
3209		.components()
3210		.any(|part| part.as_os_str() == LIBRARY_DATA)
3211	{
3212		return Err(CliError::InLibraryData(folder));
3213	}
3214	Ok(folder)
3215}
3216
3217/// What `nib` says once, when a program that syncs folders syncs the library's folder.
3218const SYNCED_BY_PROGRAM: &str = "a program that syncs folders syncs this library's folder. NibKeep syncs it with your other devices on its own, and keeps each device's copy apart, so nothing is lost. But that program puts every device's keys on every computer it syncs and with its provider, where keys protected by a passphrase can be guessed at, and a deletion or an older version on one computer reaches the others. Keep the library out of it if you can.";
3219
3220/// The error for a library whose start was cut short: it names the replica's own folder,
3221/// which removing leaves the copies of other replicas beside it as they are.
3222fn unfinished(directory: &Path) -> CliError {
3223	CliError::Unfinished(
3224		Library::replica_folder(directory).unwrap_or_else(|_| directory.to_owned()),
3225	)
3226}
3227
3228/// Why the system lets nib not read a folder, if it does not, so that a library there is not
3229/// taken for missing.
3230fn unreadable(folder: &Path) -> Option<io::Error> {
3231	match std::fs::read_dir(folder) {
3232		Err(error) if error.kind() == io::ErrorKind::PermissionDenied => Some(error),
3233		_ => None,
3234	}
3235}
3236
3237fn current_dir<E: Environment>(environment: &E) -> Result<PathBuf, CliError> {
3238	environment.current_dir().map_err(CliError::NoCurrentFolder)
3239}
3240
3241/// A folder given on the command line, relative to the current folder unless it is a full
3242/// path.
3243fn absolute<E: Environment>(folder: &Path, environment: &E) -> Result<PathBuf, CliError> {
3244	if folder.is_absolute() {
3245		Ok(folder.to_owned())
3246	} else {
3247		Ok(current_dir(environment)?.join(folder))
3248	}
3249}
3250
3251/// Runs a command on an open library, in its folder: any but `nib init`.
3252fn library_command<E: Environment>(
3253	library: &mut Library,
3254	cli: &Cli,
3255	folder: &Path,
3256	environment: &mut E,
3257	timings: &mut Timings,
3258	output: &mut dyn Write,
3259) -> Result<(), CliError> {
3260	let json = cli.json;
3261	match &cli.command {
3262		Command::Languages { .. } => {
3263			languages_command(library, &cli.command, json, environment, output)
3264		}
3265		Command::Show { .. }
3266		| Command::History { .. }
3267		| Command::Export { .. }
3268		| Command::Find { .. }
3269		| Command::List { .. } => reading_command(library, cli, folder, environment, output),
3270		Command::Verify { export, .. } => {
3271			verify_command(library, export.as_deref(), json, environment, output)
3272		}
3273		Command::New {
3274			kind,
3275			values,
3276			language,
3277		} => {
3278			let new = (kind.as_str(), values.as_slice(), language.as_ref());
3279			new_command(library, new, json, environment, output)
3280		}
3281		Command::Merge {
3282			entity,
3283			other,
3284			undo,
3285		} => {
3286			let merge = (entity.as_str(), other.as_deref(), *undo);
3287			merge_command(library, merge, json, environment, output)
3288		}
3289		Command::Edit(arguments) => edit_command(library, arguments, json, environment, output),
3290		Command::Move {
3291			entity,
3292			to,
3293			without_history,
3294			keep_behind,
3295			leave_secrets,
3296			yes,
3297		} => {
3298			let args = (
3299				(entity.as_str(), to.as_str(), *without_history, *yes),
3300				(*keep_behind, *leave_secrets),
3301			);
3302			move_command(library, args, json, environment, timings, output)
3303		}
3304		Command::Purge { .. } => purge_or_list(library, cli, environment, timings, output),
3305		Command::File { command } => {
3306			let file = (command, folder);
3307			file_command(library, file, cli, environment, timings, output)
3308		}
3309		Command::Policy { command } => policy_command(library, command, json, environment, output),
3310
3311		Command::Secret { command } => {
3312			secret_command(library, command, json, environment, timings, output)
3313		}
3314		Command::Protect {
3315			passphrase,
3316			secrets,
3317		} => {
3318			let protect = (*passphrase, *secrets);
3319			protect_command(library, protect, json, environment, timings, output)?;
3320			// Nobody is there to type a passphrase at login.
3321			if *passphrase && !*secrets {
3322				turn_off_at_login(&folder.join(LIBRARY_DATA), environment);
3323			}
3324			Ok(())
3325		}
3326		Command::Import { paths, from } => {
3327			let import = (paths.as_slice(), from.as_deref());
3328			import_command(library, import, json, environment, output)
3329		}
3330		Command::Type { command } => type_command(library, command, json, environment, output),
3331		Command::Space { command } => space_command(library, command, cli, environment, output),
3332		Command::Device { command } => {
3333			let directory = folder.join(LIBRARY_DATA);
3334			device_command(
3335				library,
3336				(command, &directory),
3337				cli,
3338				environment,
3339				timings,
3340				output,
3341			)
3342		}
3343		Command::Sync {
3344			serve: false, wait, ..
3345		} => {
3346			let wait = Duration::from_secs(*wait);
3347			sync_command(library, cli, wait, environment, output)
3348		}
3349		Command::Sync { serve: true, .. } => unreachable!("nib sync --serve closes the library"),
3350		Command::Mcp {
3351			action: McpAction::Serve { .. },
3352		} => unreachable!("nib mcp serve opens the library itself"),
3353		Command::Mcp { action } => mcp::manage(library, action, folder, cli, environment, output),
3354		command if command.is_of_trees() => {
3355			tree_command(library, cli, folder, environment, timings, output)
3356		}
3357		// What makes a library, and safekeeping, purges and commands nib does not have, which
3358		// run_command runs.
3359		_ => unreachable!("run_command runs it"),
3360	}
3361}
3362
3363/// Runs the commands of trees, and `nib status`, which shows a tree's status in its folder.
3364fn tree_command<E: Environment>(
3365	library: &mut Library,
3366	cli: &Cli,
3367	folder: &Path,
3368	environment: &mut E,
3369	timings: &mut Timings,
3370	output: &mut dyn Write,
3371) -> Result<(), CliError> {
3372	let json = cli.json;
3373	match &cli.command {
3374		Command::Init {
3375			folder: target,
3376			message,
3377			yes,
3378			..
3379		} => {
3380			let start = (target.as_deref(), message.as_deref(), *yes);
3381			trees::init_command(
3382				library,
3383				(folder, start),
3384				json,
3385				(environment, timings),
3386				output,
3387			)
3388		}
3389		Command::Status { secrets: true, .. } => {
3390			trees::secrets_command(library, json, environment, output)
3391		}
3392		Command::Status { library_wide, .. } => {
3393			if !*library_wide && trees::in_tree_here(library, environment)? {
3394				return trees::status_command(library, json, environment, output);
3395			}
3396			reading_command(library, cli, folder, environment, output)
3397		}
3398		Command::Trees(command) => trees::tree_command(
3399			library,
3400			(folder, command),
3401			json,
3402			(environment, timings),
3403			output,
3404		),
3405		Command::Pull {
3406			wait,
3407			partial,
3408			clone,
3409			no_clone,
3410		} => {
3411			let wait = Duration::from_secs(*wait);
3412			let update = (*partial, *clone, *no_clone);
3413			pull_command(library, cli, (wait, update), environment, timings, output)
3414		}
3415		_ => unreachable!("only the commands of trees come here"),
3416	}
3417}
3418
3419/// How long a pairing code works.
3420const PAIRING_MINUTES: u64 = 10;
3421
3422/// How long a new device looks for the one that shows its code.
3423const FIND_SPONSOR: Duration = Duration::from_mins(1);
3424
3425/// Runs `nib device pair`: shows a code, and waits for a new device, or an AI agent's
3426/// replica, to pair with it and to sync for the first time.
3427fn pair_command<E: Environment>(
3428	library: &mut Library,
3429	((ai_agent, spaces, give_secrets), device): (
3430		(Option<&str>, &[nibkeep_base::SpaceId], bool),
3431		&nibkeep_node::NewDevice,
3432	),
3433	cli: &Cli,
3434	environment: &mut E,
3435	timings: &mut Timings,
3436	output: &mut dyn Write,
3437) -> Result<(), CliError> {
3438	let json = cli.json;
3439	// Before showing a code that could not be used.
3440	library.check_not_ai_agent("add devices")?;
3441	if ai_agent.is_none() {
3442		library.check_new_device(device)?;
3443	}
3444	// Unlocked first, the secrets are given to a new device that asks for them.
3445	if give_secrets {
3446		unlock_secrets(library, false, environment, timings)?;
3447	}
3448	// The program that syncs this device stops its endpoint while this one pairs; nib stops
3449	// waiting for it only as it ends.
3450	let _borrowed =
3451		nibkeep_node::borrow_network(library, &AtomicBool::new(false), UnwrapErr(SysRng))?;
3452	let code = PairingCode::generate(environment.rng());
3453	let network = library.network(cli.network(true))?;
3454	output::port_taken(&network, json, output)?;
3455	output::pairing_code(&code, PAIRING_MINUTES, json, output)?;
3456	let now = clock(environment);
3457	// Each try that fails before the code matched shows as the code waits on; one that cannot
3458	// be shown stops nothing.
3459	let printing = RefCell::new(output);
3460	let wrong_try = |error: &NodeError, left: usize| {
3461		let _ = output::wrong_try(error, left, json, &mut **printing.borrow_mut());
3462	};
3463	let showing = nibkeep_node::Showing {
3464		timeout: Duration::from_mins(PAIRING_MINUTES),
3465		wrong_try: &wrong_try,
3466	};
3467	let paired = match ai_agent {
3468		Some(name) => nibkeep_node::pair_ai_agent_in(
3469			library,
3470			&network,
3471			&code,
3472			(name, spaces),
3473			showing,
3474			&now,
3475			environment.rng(),
3476		),
3477		None => nibkeep_node::pair_device(
3478			library,
3479			&network,
3480			&code,
3481			(device, give_secrets),
3482			showing,
3483			&now,
3484			environment.rng(),
3485		),
3486	};
3487	library.lock_secrets();
3488	output::paired(&paired?, json, printing.into_inner())
3489}
3490
3491/// Runs `nib device`.
3492fn device_command<E: Environment>(
3493	library: &mut Library,
3494	(command, directory): (&DeviceCommand, &Path),
3495	cli: &Cli,
3496	environment: &mut E,
3497	timings: &mut Timings,
3498	output: &mut dyn Write,
3499) -> Result<(), CliError> {
3500	match command {
3501		DeviceCommand::List => {
3502			// What the program that syncs this device recorded, as far as it can be read.
3503			let records = library.sync_records(UnwrapErr(SysRng)).ok();
3504			let recorded = records.as_ref().and_then(|records| records.replicas().ok());
3505			let holder = records.and_then(|records| records.holder().ok().flatten());
3506			let zone = environment.time_zone();
3507			let synced = (holder.as_ref(), recorded.as_ref());
3508			let replicas = library.replicas()?;
3509			let this = replicas
3510				.iter()
3511				.find(|replica| replica.this)
3512				.map(|replica| replica.id);
3513			let at_login = at_login_state((directory, this), environment);
3514			let shown = (synced, at_login.as_ref());
3515			output::replicas(&replicas, shown, &zone, cli.json, output)
3516		}
3517		DeviceCommand::Pair {
3518			ai_agent,
3519			phone,
3520			spaces,
3521			give_secrets,
3522			..
3523		} => {
3524			let mut chosen = Vec::new();
3525			for space in spaces {
3526				chosen.push(library.find_space(space)?);
3527			}
3528			let device = nibkeep_node::NewDevice {
3529				phone: *phone,
3530				spaces: (!spaces.is_empty()).then(|| chosen.clone()),
3531			};
3532			let pairing = (ai_agent.as_deref(), &chosen[..], *give_secrets);
3533			pair_command(
3534				library,
3535				(pairing, &device),
3536				cli,
3537				environment,
3538				timings,
3539				output,
3540			)
3541		}
3542		DeviceCommand::Revoke { device, yes, codes } => revoke_command(
3543			library,
3544			(device, *yes, *codes),
3545			cli.json,
3546			environment,
3547			output,
3548		),
3549		DeviceCommand::Mark { .. } => mark_command(library, command, cli.json, environment, output),
3550		DeviceCommand::Review => output::set_aside(
3551			&library.set_aside()?,
3552			&library.replicas()?,
3553			cli.json,
3554			output,
3555		),
3556		DeviceCommand::Accept { device, yes } => {
3557			accept_command(library, (device, *yes), cli.json, environment, output)
3558		}
3559	}
3560}
3561
3562/// Runs `nib device mark`: marks a device as the person says, or says how it is marked.
3563fn mark_command<E: Environment>(
3564	library: &mut Library,
3565	command: &DeviceCommand,
3566	json: bool,
3567	environment: &mut E,
3568	output: &mut dyn Write,
3569) -> Result<(), CliError> {
3570	let DeviceCommand::Mark {
3571		device,
3572		archive,
3573		everyday,
3574		away,
3575		home,
3576		keeps,
3577		waits,
3578		new_spaces,
3579	} = command
3580	else {
3581		unreachable!("only nib device mark comes here");
3582	};
3583	let (chosen, name) = one_device(library, device)?;
3584	// Whether it takes new spaces is said on the device itself, by its own key.
3585	let this = library.user_and_device()?.1.id == chosen;
3586	if let Some(new_spaces) = new_spaces {
3587		if !this {
3588			return Err(CliError::NewSpacesElsewhere(
3589				name.clone().unwrap_or_else(|| device.clone()),
3590			));
3591		}
3592		let now = environment.now();
3593		library.set_takes_new_spaces(*new_spaces == NewSpacesArg::Take, now, environment.rng())?;
3594	}
3595	let takes = if this {
3596		Some(library.takes_new_spaces()?)
3597	} else {
3598		None
3599	};
3600	let mut marks = library.device_marks(chosen)?;
3601	if let Some(Waits(waits)) = waits {
3602		marks.waits = *waits;
3603	}
3604	if *archive {
3605		marks.role = DeviceRole::Archive;
3606	}
3607	if *everyday {
3608		marks.role = DeviceRole::Everyday;
3609	}
3610	if *away {
3611		marks.away = true;
3612	}
3613	if *home {
3614		marks.away = false;
3615	}
3616	if let Some(Keeps(keeps)) = keeps {
3617		marks.keeps = *keeps;
3618	}
3619	// Without a mark given, it only says how the device is marked.
3620	if *archive || *everyday || *away || *home || keeps.is_some() || waits.is_some() {
3621		library.set_device_marks(chosen, marks, environment.now(), environment.rng())?;
3622	}
3623	output::device_marked(
3624		(name.as_deref(), chosen),
3625		(marks, takes, new_spaces.is_some()),
3626		json,
3627		output,
3628	)
3629}
3630
3631/// Runs `nib device revoke`: with `yes`, revokes a device's replicas, and with `codes` the
3632/// recovery codes that they made; without it, says what it would revoke.
3633fn revoke_command<E: Environment>(
3634	library: &mut Library,
3635	(device, yes, codes): (&str, bool, bool),
3636	json: bool,
3637	environment: &mut E,
3638	output: &mut dyn Write,
3639) -> Result<(), CliError> {
3640	let mut replicas = library.to_revoke(device)?;
3641	let ids: Vec<_> = replicas.iter().map(|replica| replica.id).collect();
3642	// The spaces that this device does not hold, where the devices that do revoke them: only
3643	// named, so that a failure to read them never stops a revocation.
3644	let out_of_reach = library.out_of_reach(&ids).unwrap_or_default();
3645	// The recovery codes made on it, which it names, and revokes as asked.
3646	let mut made = library.recovery_codes_made_by(&ids)?;
3647	let mut elsewhere = Vec::new();
3648	if yes && !replicas.is_empty() {
3649		let spaces = library.revoke(&ids, environment.now(), environment.rng())?;
3650		elsewhere = spaces
3651			.iter()
3652			.copied()
3653			.zip(space_names(library, &spaces))
3654			.collect();
3655		elsewhere.sort_by(|a, b| a.1.cmp(&b.1));
3656		if codes {
3657			for code in &made {
3658				let now = environment.now();
3659				library.revoke_recovery_code(&code.record.to_string(), now, environment.rng())?;
3660			}
3661			let records: Vec<_> = made.iter().map(|code| code.record).collect();
3662			made = library
3663				.recovery_codes()?
3664				.into_iter()
3665				.filter(|code| records.contains(&code.record))
3666				.collect();
3667		}
3668		// As the library lists them now, revoked.
3669		replicas = library
3670			.replicas()?
3671			.into_iter()
3672			.filter(|replica| ids.contains(&replica.id))
3673			.collect();
3674	}
3675	output::revoked(
3676		&replicas,
3677		(&made, codes),
3678		(yes, &elsewhere),
3679		&out_of_reach,
3680		json,
3681		output,
3682	)?;
3683	if yes || replicas.is_empty() {
3684		Ok(())
3685	} else {
3686		Err(CliError::UnconfirmedRevoke)
3687	}
3688}
3689
3690/// Runs `nib device accept`: accepts the changes of a device's replicas that were set
3691/// aside, or with `confirmed` false, says how many it would.
3692fn accept_command<E: Environment>(
3693	library: &mut Library,
3694	(device, confirmed): (&str, bool),
3695	json: bool,
3696	environment: &mut E,
3697	output: &mut dyn Write,
3698) -> Result<(), CliError> {
3699	let named: Vec<_> = library
3700		.replicas_named(device)?
3701		.into_iter()
3702		.map(|replica| replica.id)
3703		.collect();
3704	let changes: Vec<_> = library
3705		.set_aside()?
3706		.into_iter()
3707		// Only what accepting makes count: never what says who may write to the library.
3708		.filter(|aside| {
3709			aside.acceptable
3710				&& aside
3711					.replica
3712					.is_some_and(|replica| named.contains(&replica))
3713		})
3714		.map(|aside| aside.change)
3715		.collect();
3716	let accepted = if confirmed {
3717		library.accept_set_aside(&changes, environment.now(), environment.rng())?
3718	} else {
3719		changes.len()
3720	};
3721	output::accepted(accepted, confirmed, json, output)?;
3722	if confirmed || accepted == 0 {
3723		Ok(())
3724	} else {
3725		Err(CliError::UnconfirmedAccept)
3726	}
3727}
3728
3729/// Runs `nib sync`: syncs once with each of the user's other devices found on the network.
3730fn sync_command<E: Environment>(
3731	library: &mut Library,
3732	cli: &Cli,
3733	wait: Duration,
3734	environment: &mut E,
3735	output: &mut dyn Write,
3736) -> Result<(), CliError> {
3737	let json = cli.json;
3738	// A device that sees itself revoked still syncs: a revocation it learns of may set that
3739	// one aside.
3740	// Without another device, there is nothing to look for on the network.
3741	if library.peers()?.is_empty() {
3742		return Err(NodeError::NoOtherReplicas.into());
3743	}
3744	// A program that syncs this device for all is asked to sync now; one that holds the role
3745	// for a moment, as another nib sync, is waited for.
3746	let waited = Instant::now();
3747	let _role = loop {
3748		if let Some(role) = library.take_role()? {
3749			break role;
3750		}
3751		if library.sync_records(UnwrapErr(SysRng))?.holder()?.is_some() {
3752			if let Some(asked) = ask_to_sync(library, wait, cli, environment, output)? {
3753				return asked;
3754			}
3755			continue;
3756		}
3757		if waited.elapsed() > wait + ASK_WAIT {
3758			return Err(CliError::NotAnswered("another program".to_owned()));
3759		}
3760		std::thread::sleep(Duration::from_millis(100));
3761	};
3762	// It only connects, so that a device that connects to it learns at once to wait for
3763	// another that answers, with nib sync --serve.
3764	let network = library.network(cli.network(false))?;
3765	output::progress("Looking for your other devices…", json, output)?;
3766	let now = clock(environment);
3767	let synced = nibkeep_node::sync_with_others(library, &network, wait, &now, environment.rng())?;
3768	output::synced_with(&synced, json, output)?;
3769	if library.is_revoked()? {
3770		return Err(NodeError::Revoked.into());
3771	}
3772	match synced.iter().filter(|with| with.synced.is_err()).count() {
3773		0 => Ok(()),
3774		failed => Err(CliError::SyncsFailed(failed)),
3775	}
3776}
3777
3778/// Runs `nib pull`: syncs, then brings the copy of the tree here up to date, whatever the
3779/// sync did, and then says how the sync failed, if it did. With --json, one object holds
3780/// what each printed: `sync`, `null` where it failed before it synced, and `update`.
3781fn pull_command<E: Environment>(
3782	library: &mut Library,
3783	cli: &Cli,
3784	(wait, update): (Duration, (bool, bool, bool)),
3785	environment: &mut E,
3786	timings: &mut Timings,
3787	output: &mut dyn Write,
3788) -> Result<(), CliError> {
3789	let json = cli.json;
3790	let mut synced = Vec::new();
3791	let sync = if json {
3792		sync_command(library, cli, wait, environment, &mut synced)
3793	} else {
3794		sync_command(library, cli, wait, environment, output)
3795	};
3796	let mut updated = Vec::new();
3797	if let Err(error) =
3798		trees::update_here(library, update, json, (environment, timings), &mut updated)
3799	{
3800		if let Err(failed) = &sync {
3801			environment.note(&format!("the sync failed too: {failed}"));
3802		}
3803		return Err(error);
3804	}
3805	if json {
3806		let read = |printed: &[u8]| -> Result<serde_json::Value, CliError> {
3807			if printed.iter().all(u8::is_ascii_whitespace) {
3808				return Ok(serde_json::Value::Null);
3809			}
3810			serde_json::from_slice(printed).map_err(|error| CliError::Io(io::Error::other(error)))
3811		};
3812		let pulled = serde_json::json!({ "sync": read(&synced)?, "update": read(&updated)? });
3813		output::print_json(&pulled, output)?;
3814	} else {
3815		output.write_all(&updated)?;
3816	}
3817	sync
3818}
3819
3820/// How long `nib sync` waits for the program that syncs this device to answer, beyond the
3821/// time it is told to look for the other devices: a sync takes a while.
3822const ASK_WAIT: Duration = Duration::from_mins(2);
3823
3824/// Asks the program that holds this device's sync role to sync with all the other devices
3825/// it finds, waits until it did, and says what happened, as it recorded it: the result of
3826/// `nib sync`. `None` if the holder let go of the role first, for `nib sync` to sync itself.
3827fn ask_to_sync<E: Environment>(
3828	library: &mut Library,
3829	wait: Duration,
3830	cli: &Cli,
3831	environment: &mut E,
3832	output: &mut dyn Write,
3833) -> Result<Option<Result<(), CliError>>, CliError> {
3834	let json = cli.json;
3835	let records = library.sync_records(UnwrapErr(SysRng))?;
3836	let Some(holder) = records.holder()? else {
3837		return Ok(None);
3838	};
3839	output::progress(&format!("Asking {} to sync…", holder.program), json, output)?;
3840	let asked = environment.now();
3841	let ask = records.ask(None, asked)?;
3842	let waited = Instant::now();
3843	while records.answered(ask)?.is_none() {
3844		// The holder ended, even by a crash, which let go of the role.
3845		if library.take_role()?.is_some() {
3846			return Ok(None);
3847		}
3848		if waited.elapsed() > wait + ASK_WAIT {
3849			return Err(CliError::NotAnswered(holder.program));
3850		}
3851		std::thread::sleep(Duration::from_millis(100));
3852	}
3853	// What the holder's sync brought, as a revocation of this device.
3854	library.catch_up()?;
3855	let failed = output::asked(
3856		&library.peers()?,
3857		&records.synced_since(asked)?,
3858		json,
3859		output,
3860	)?;
3861	if library.is_revoked()? {
3862		return Err(NodeError::Revoked.into());
3863	}
3864	Ok(Some(match failed {
3865		0 => Ok(()),
3866		failed => Err(CliError::SyncsFailed(failed)),
3867	}))
3868}
3869
3870/// How a command makes a library on this computer.
3871enum Making<'a> {
3872	/// A new library, `nib init`, with the user's name, if given, and languages.
3873	New(Option<&'a str>, Option<&'a Languages>),
3874	/// A copy of a library on another device, `nib init --join`, and whether to ask for its
3875	/// secrets.
3876	Join(&'a PairingCode, bool),
3877	/// The library brought back with a recovery code, `nib recovery restore`, from a source,
3878	/// keeping these devices.
3879	Recover(Option<&'a Path>, &'a [String]),
3880	/// A device of its own from a copy, `nib recovery from-copy`.
3881	FromCopy,
3882}
3883
3884/// Runs `nib init` that makes a library or joins one, or `nib recovery` that brings one back,
3885/// once it is clear that a new replica can go where the library is.
3886fn new_library<E: Environment>(
3887	directory: &Path,
3888	cli: &Cli,
3889	environment: &mut E,
3890	timings: &mut Timings,
3891	output: &mut dyn Write,
3892) -> Result<Library, CliError> {
3893	let (making, device, passphrase, allow_fat) = match &cli.command {
3894		Command::Init {
3895			name,
3896			device,
3897			passphrase,
3898			languages,
3899			join,
3900			secrets,
3901			allow_fat,
3902			..
3903		} => {
3904			let making = match (join, name) {
3905				(Some(code), _) => Making::Join(code, *secrets),
3906				(None, name) => Making::New(name.as_deref(), languages.as_ref()),
3907			};
3908			(making, device.as_deref(), *passphrase, *allow_fat)
3909		}
3910		Command::Recovery {
3911			command: RecoveryCommand::Restore { source, keep, new },
3912		} => (
3913			Making::Recover(source.as_deref(), keep),
3914			new.device.as_deref(),
3915			new.passphrase,
3916			new.allow_fat,
3917		),
3918		Command::Recovery {
3919			command: RecoveryCommand::FromCopy { new },
3920		} => (
3921			Making::FromCopy,
3922			new.device.as_deref(),
3923			new.passphrase,
3924			new.allow_fat,
3925		),
3926		_ => unreachable!("only nib init and nib recovery make a library"),
3927	};
3928	if allow_fat {
3929		Library::allow_fat(directory)?;
3930	}
3931	// Where a new replica would go, before any passphrase is asked for.
3932	if matches!(
3933		Library::replica_folder(directory),
3934		Err(NodeError::NoLibrary | NodeError::Copied)
3935	) {
3936		Library::check_place(directory).map_err(|error| no_journal(error.into(), directory))?;
3937	}
3938	let protection = (passphrase, cli.passphrase_file.as_deref());
3939	match making {
3940		Making::Join(code, secrets) => join_command(
3941			directory,
3942			(code, device, secrets),
3943			protection,
3944			cli,
3945			environment,
3946			timings,
3947			output,
3948		),
3949		Making::New(name, languages) => init_command(
3950			directory,
3951			(name, device, languages),
3952			protection,
3953			environment,
3954			timings,
3955		),
3956		Making::Recover(source, keep) => recover_command(
3957			directory,
3958			(source, device, keep),
3959			protection,
3960			cli,
3961			environment,
3962			timings,
3963			output,
3964		),
3965		Making::FromCopy => from_copy_command(
3966			directory,
3967			device,
3968			protection,
3969			cli,
3970			environment,
3971			timings,
3972			output,
3973		),
3974	}
3975	.map_err(|error| no_journal(error, directory))
3976}
3977
3978/// Runs `nib sync --at-login on` or `off`: turns syncing this library from login on or off
3979/// ([technical design](../../docs/Technical-design.md#106-syncing-from-login)). On, it adds
3980/// the library to the list, names the copy of `nibkeep-sync` beside `nib` if it is newer
3981/// than the one listed, and starts the copy that should run. Off, it takes the library off
3982/// the list by its folder, which may hold no library any more, or by its replica, as after
3983/// its folder was moved.
3984fn at_login_command<E: Environment>(
3985	switch: Switch,
3986	directory: &Path,
3987	cli: &Cli,
3988	environment: &mut E,
3989	timings: &mut Timings,
3990	output: &mut dyn Write,
3991) -> Result<(), CliError> {
3992	let state = environment.state_folder().ok_or(CliError::NoStateFolder)?;
3993	let directory = std::path::absolute(directory)?;
3994	let keystore = matches!(
3995		Library::protection(&directory),
3996		Ok(Protection::Keystore { .. })
3997	);
3998	if switch == Switch::Off {
3999		let replica = if keystore {
4000			open(&directory, None, environment, timings)
4001				.ok()
4002				.and_then(|library| own_replica(&library).ok())
4003		} else {
4004			None
4005		};
4006		let entry = environment.login_entry();
4007		let turned_off = at_login::turn_off(&state, (&directory, replica), entry.as_ref())?;
4008		return output::at_login_off(&turned_off, cli.json, output);
4009	}
4010	// Before anything is asked for: nobody is there to type a passphrase at login.
4011	if !keystore {
4012		Library::protection(&directory).map_err(|error| opening(error, &directory))?;
4013		return Err(CliError::AtLoginPassphrase);
4014	}
4015	let program = environment.sync_program().ok_or(CliError::NoSyncProgram)?;
4016	let library = open(&directory, None, environment, timings)
4017		.map_err(|error| opened_error(error, &directory))?;
4018	let served = at_login::Served {
4019		replica: own_replica(&library)?,
4020		directory,
4021	};
4022	drop(library);
4023	let entry = environment.login_entry();
4024	let version_of = |listed: &Path| environment.sync_version(listed);
4025	let turned_on = at_login::turn_on(&state, served, (&program, &version_of), entry.as_ref())
4026		.map_err(|error| match error {
4027			NodeError::NotInKeystore => CliError::AtLoginPassphrase,
4028			other => CliError::Node(other),
4029		})?;
4030	// The firewall first, so that Windows does not ask about the copy that starts, whose
4031	// refusal would block it.
4032	let firewall = environment.open_firewall();
4033	if let Some(start) = &turned_on.start {
4034		environment.start_sync(start)?;
4035	}
4036	output::at_login_on(&turned_on.entry, firewall, cli.json, output)
4037}
4038
4039/// The ID of the library's own replica.
4040fn own_replica(library: &Library) -> Result<EntityId, CliError> {
4041	library
4042		.replicas()?
4043		.into_iter()
4044		.find(|replica| replica.this)
4045		.map(|replica| replica.id)
4046		.ok_or_else(|| {
4047			CliError::Node(NodeError::Damaged(
4048				"the library lists no replica of its own".to_owned(),
4049			))
4050		})
4051}
4052
4053/// The error of a library that could not be opened, as the person is told it: where its
4054/// start was cut short, it holds only copies, or its drive must be checked, with what to do.
4055fn opening(error: NodeError, directory: &Path) -> CliError {
4056	match error {
4057		NodeError::Unfinished => unfinished(directory),
4058		NodeError::Copied => CliError::IsCopy(directory.to_owned()),
4059		NodeError::UncleanRemoval => CliError::UncleanRemoval(directory.to_owned()),
4060		other => CliError::Node(other),
4061	}
4062}
4063
4064/// [`opening`], for an error that opening a library returned.
4065fn opened_error(error: CliError, directory: &Path) -> CliError {
4066	match error {
4067		CliError::Node(error) => opening(error, directory),
4068		other => other,
4069	}
4070}
4071
4072/// Turns syncing from login off for the library in `directory`, if it was on, and says so:
4073/// as best it can, since the library's new protection is in place already.
4074fn turn_off_at_login<E: Environment>(directory: &Path, environment: &mut E) {
4075	let Some(state) = environment.state_folder() else {
4076		return;
4077	};
4078	let entry = environment.login_entry();
4079	let turned_off = std::path::absolute(directory)
4080		.map_err(CliError::from)
4081		.and_then(|directory| {
4082			Ok(at_login::turn_off(
4083				&state,
4084				(&directory, None),
4085				entry.as_ref(),
4086			)?)
4087		});
4088	match turned_off {
4089		Ok(turned_off) => {
4090			if turned_off.removed {
4091				environment.note(AT_LOGIN_TURNED_OFF);
4092			}
4093			if let Some(error) = &turned_off.entry_failed {
4094				environment.note(&entry_not_removed(error));
4095			}
4096		}
4097		Err(error) => environment.note(&format!(
4098			"nib: could not turn syncing from login off for this library ({error}); nibkeep-sync turns it off as it finds the passphrase"
4099		)),
4100	}
4101}
4102
4103/// What `nib` says when the login entry could not be removed with the last library.
4104fn entry_not_removed(error: &str) -> String {
4105	format!(
4106		"nib: the login entry could not be removed ({error}); nib sync --at-login off tries again"
4107	)
4108}
4109
4110/// What `nib` says when protecting a library with a passphrase turned syncing from login off.
4111const AT_LOGIN_TURNED_OFF: &str = "nib: syncing from login is off for this library now, as it needs the library's keys in the keystore";
4112
4113/// Whether the library in `directory`, or with `replica` here, is synced from login, and
4114/// what `nibkeep-sync` does for it: `None` if it is not, or that cannot be read.
4115fn at_login_state<E: Environment>(
4116	(directory, replica): (&Path, Option<EntityId>),
4117	environment: &E,
4118) -> Option<at_login::AtLoginStatus> {
4119	let state = environment.state_folder()?;
4120	let directory = std::path::absolute(directory).ok()?;
4121	let entry = environment.login_entry();
4122	let status = at_login::status(&state, (&directory, replica), entry.as_ref());
4123	status.on.then_some(status)
4124}
4125
4126/// Runs `nib sync --serve`: holds this device's sync role, or waits for the program that
4127/// holds it to end and takes over, and syncs for every program here until stopped
4128/// (technical design: the sync role).
4129fn serve_command<E: Environment>(
4130	library: Library,
4131	cli: &Cli,
4132	environment: &mut E,
4133	output: &mut dyn Write,
4134) -> Result<(), CliError> {
4135	let json = cli.json;
4136	let closed = library.close();
4137	let stop = Arc::new(AtomicBool::new(false));
4138	environment.stop_on_interrupt(Arc::clone(&stop));
4139	let role = if let Some(role) = Role::take(&closed)? {
4140		role
4141	} else {
4142		let program = closed
4143			.open()?
4144			.sync_records(UnwrapErr(SysRng))?
4145			.holder()?
4146			.map_or_else(|| "Another program".to_owned(), |holder| holder.program);
4147		output::progress(
4148			&format!(
4149				"{program} syncs this device; this one takes over when it ends. Stop with Ctrl-C."
4150			),
4151			json,
4152			output,
4153		)?;
4154		// Stopped before it took over: nothing to let go of.
4155		let Some(role) = Role::wait(&closed, &stop)? else {
4156			return Ok(());
4157		};
4158		role
4159	};
4160	output::progress(
4161		"Syncing this device with your other devices; stop with Ctrl-C.",
4162		json,
4163		output,
4164	)?;
4165	let now = clock(environment);
4166	let holding = Holding {
4167		program: "nib sync --serve",
4168		network: cli.network(true),
4169		known: Vec::new(),
4170		quiet: Holding::QUIET,
4171		appear_wait: Holding::APPEAR_WAIT,
4172		check: nibkeep_node::Pace::DEFAULT,
4173		stop: &stop,
4174		now: &now,
4175	};
4176	// Output that fails, as into a pipe closed, stops it too.
4177	let mut printed = Ok(());
4178	nibkeep_node::hold(
4179		&closed,
4180		role,
4181		&holding,
4182		&|| UnwrapErr(SysRng),
4183		&mut |held| {
4184			if printed.is_ok() {
4185				printed = output::held(&held, json, output);
4186				if printed.is_err() {
4187					stop.store(true, std::sync::atomic::Ordering::SeqCst);
4188				}
4189			}
4190		},
4191	)?;
4192	printed
4193}
4194
4195/// Runs `nib init --join`: pairs with the device that shows the code, which makes the
4196/// library here, and syncs with it.
4197fn join_command<E: Environment>(
4198	directory: &Path,
4199	(code, device, secrets): (&PairingCode, Option<&str>, bool),
4200	(passphrase, file): (bool, Option<&Path>),
4201	cli: &Cli,
4202	environment: &mut E,
4203	timings: &mut Timings,
4204	output: &mut dyn Write,
4205) -> Result<Library, CliError> {
4206	// Copies of replicas made elsewhere stay, and this one goes beside them, and takes in
4207	// what they hold once it has joined.
4208	if Library::exists(directory) {
4209		match Library::protection(directory) {
4210			Err(NodeError::Copied) => {}
4211			Err(NodeError::Unfinished) => return Err(unfinished(directory)),
4212			_ => return Err(NodeError::Exists.into()),
4213		}
4214	}
4215	let device = device_name(device, environment);
4216	let passphrase = new_passphrase((passphrase, file), environment, timings)?;
4217	let protection = match &passphrase {
4218		Some(passphrase) => NewProtection::Passphrase(passphrase, environment.passphrase_params()),
4219		None => NewProtection::Keystore {
4220			service: KEYSTORE_SERVICE,
4221		},
4222	};
4223	// Before the code is used.
4224	let secrets_passphrase = if secrets {
4225		let typed = ask_twice(
4226			environment,
4227			timings,
4228			(
4229				"A passphrase for the secrets on this device, not the library's: ",
4230				"The passphrase again: ",
4231			),
4232			(|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
4233		)?;
4234		Some(typed)
4235	} else {
4236		None
4237	};
4238	let json = cli.json;
4239	let secrets_params = environment.passphrase_params();
4240	let mut joining = nibkeep_node::Joining::new(&device, APP, environment.rng())?;
4241	// With copies here, the secrets come from them, once this device has taken in what
4242	// they hold, rather than from the device that shows the code.
4243	let beside_copies = !Library::copies_in(directory).is_empty();
4244	if let Some(typed) = secrets_passphrase.as_ref().filter(|_| !beside_copies) {
4245		let protection = NewProtection::Passphrase(typed, secrets_params);
4246		joining = joining.asking_for_secrets(protection, environment.rng());
4247	}
4248	let network = joining.network(cli.network(false))?;
4249	output::progress("Looking for the device that shows the code…", json, output)?;
4250	let now = clock(environment);
4251	let joined = nibkeep_node::join(
4252		directory,
4253		joining,
4254		&network,
4255		code,
4256		&protection,
4257		FIND_SPONSOR,
4258		&now,
4259		environment.rng(),
4260	)
4261	.map_err(|error| match error {
4262		error @ NodeError::Keys(KeysError::Keystore(_)) => CliError::Keystore(error),
4263		other => CliError::Node(other),
4264	})?;
4265	// What became of the secrets it asked for: taken with the first sync, asked for, or none.
4266	let mut library = joined.library;
4267	library.lock_secrets();
4268	let secrets = if secrets {
4269		Some((library.secrets_state()?, library.is_ai_agent()?))
4270	} else {
4271		None
4272	};
4273	let copies = take_in_copies(&mut library, environment)?;
4274	// The device joined: if the copy's secrets cannot be taken now, nib secret from-copy
4275	// takes them later.
4276	if let (Some(typed), Some(copies)) = (&secrets_passphrase, &copies) {
4277		let protection = NewProtection::Passphrase(typed, secrets_params);
4278		if let Err(error) = secrets_from_copies(
4279			&mut library,
4280			&copies.folders,
4281			&protection,
4282			environment,
4283			timings,
4284		) {
4285			environment.note(&format!(
4286				"the copy's secrets were not taken: {error}; nib secret from-copy takes them"
4287			));
4288		}
4289	}
4290	let secrets = match secrets {
4291		Some(_) => Some((library.secrets_state()?, library.is_ai_agent()?)),
4292		None => None,
4293	};
4294	output::joined(
4295		(&joined.synced, joined.refused),
4296		secrets,
4297		copies.as_ref(),
4298		json,
4299		output,
4300	)?;
4301	Ok(library)
4302}
4303
4304/// Takes the secrets from the first of `copies` that holds them, which the person unlocks:
4305/// with the keystore that holds their key, or the passphrase of the copy's secrets, which
4306/// the person may leave empty to take none. Returns how many keys it took.
4307fn secrets_from_copies<E: Environment>(
4308	library: &mut Library,
4309	copies: &[PathBuf],
4310	protection: &NewProtection<'_>,
4311	environment: &mut E,
4312	timings: &mut Timings,
4313) -> Result<usize, CliError> {
4314	for folder in copies {
4315		let copy = nibkeep_node::ReplicaCopy {
4316			folder: folder.clone(),
4317			replica: None,
4318		};
4319		let Ok((_, Some(kept))) = copy.protections() else {
4320			continue;
4321		};
4322		let typed;
4323		let unlocker = match kept {
4324			Protection::Keystore { .. } => Unlocker::Keystore,
4325			Protection::Passphrase { .. } => {
4326				typed = ask_once(
4327					environment,
4328					timings,
4329					"The passphrase of the copy's secrets, or nothing to leave them: ",
4330				)?;
4331				if typed.is_empty() {
4332					return Ok(0);
4333				}
4334				Unlocker::Passphrase(&typed)
4335			}
4336		};
4337		let now = environment.now();
4338		return Ok(library.take_secrets_from_copy(
4339			folder,
4340			&unlocker,
4341			protection,
4342			now,
4343			environment.rng(),
4344		)?);
4345	}
4346	Ok(0)
4347}
4348
4349/// Runs `nib secret from-copy`: takes the secrets from a copy beside this device's replica.
4350fn from_copy_secrets_command<E: Environment>(
4351	library: &mut Library,
4352	json: bool,
4353	environment: &mut E,
4354	timings: &mut Timings,
4355	output: &mut dyn Write,
4356) -> Result<(), CliError> {
4357	let copies: Vec<PathBuf> = library
4358		.copies()
4359		.into_iter()
4360		.map(|copy| copy.folder)
4361		.collect();
4362	let typed = ask_twice(
4363		environment,
4364		timings,
4365		(
4366			"A passphrase for the secrets on this device, not the library's: ",
4367			"The passphrase again: ",
4368		),
4369		(|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
4370	)?;
4371	let protection = NewProtection::Passphrase(&typed, environment.passphrase_params());
4372	let taken = secrets_from_copies(library, &copies, &protection, environment, timings);
4373	library.lock_secrets();
4374	match taken? {
4375		0 => Err(CliError::NoSecretsInCopies),
4376		taken => output::progress(
4377			&format!("Took {taken} secrets keys from the copy: this device holds the secrets."),
4378			json,
4379			output,
4380		),
4381	}
4382}
4383
4384/// Runs `nib recovery from-copy`: makes this computer a device of its own from the copy in the
4385/// library's folder, with the copy's own keys, where no other device can add it.
4386fn from_copy_command<E: Environment>(
4387	directory: &Path,
4388	device: Option<&str>,
4389	(passphrase, file): (bool, Option<&Path>),
4390	cli: &Cli,
4391	environment: &mut E,
4392	timings: &mut Timings,
4393	output: &mut dyn Write,
4394) -> Result<Library, CliError> {
4395	if Library::replica_folder(directory).is_ok() {
4396		return Err(NodeError::Exists.into());
4397	}
4398	let copies = Library::copies_in(directory);
4399	let copy = match copies.as_slice() {
4400		[copy] => copy,
4401		[] => return Err(CliError::NoCopy(directory.to_owned())),
4402		_ => return Err(CliError::SeveralCopies(directory.to_owned())),
4403	};
4404	let (kept, secrets_kept) = copy.protections()?;
4405	let typed;
4406	let unlocker = match kept {
4407		Protection::Keystore { .. } => Unlocker::Keystore,
4408		Protection::Passphrase { .. } => {
4409			typed = ask_once(
4410				environment,
4411				timings,
4412				"The passphrase of the copy, the library's: ",
4413			)?;
4414			Unlocker::Passphrase(&typed)
4415		}
4416	};
4417	let device = device_name(device, environment);
4418	let new_passphrase = new_passphrase((passphrase, file), environment, timings)?;
4419	let protection = match &new_passphrase {
4420		Some(passphrase) => NewProtection::Passphrase(passphrase, environment.passphrase_params()),
4421		None => NewProtection::Keystore {
4422			service: KEYSTORE_SERVICE,
4423		},
4424	};
4425	// The copy's secrets, which only it may hold, are taken before its device is revoked.
4426	let mut copy_secrets = None;
4427	let secrets_typed;
4428	if let Some(kept) = secrets_kept {
4429		let typed = match kept {
4430			Protection::Keystore { .. } => None,
4431			Protection::Passphrase { .. } => Some(ask_once(
4432				environment,
4433				timings,
4434				"The passphrase of the copy's secrets, or nothing to leave them: ",
4435			)?),
4436		};
4437		if typed.as_ref().is_none_or(|typed| !typed.is_empty()) {
4438			let new = ask_twice(
4439				environment,
4440				timings,
4441				(
4442					"A passphrase for the secrets on this device, not the library's: ",
4443					"The passphrase again: ",
4444				),
4445				(|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
4446			)?;
4447			secrets_typed = (typed, new);
4448			copy_secrets = Some(&secrets_typed);
4449		}
4450	}
4451	let secrets_params = environment.passphrase_params();
4452	let secrets_unlocker = copy_secrets.map(|(typed, _)| match typed {
4453		Some(typed) => Unlocker::Passphrase(typed),
4454		None => Unlocker::Keystore,
4455	});
4456	let secrets_protection =
4457		copy_secrets.map(|(_, new)| NewProtection::Passphrase(new, secrets_params));
4458	let joining = nibkeep_node::Joining::new(&device, APP, environment.rng())?;
4459	let now = clock(environment);
4460	let library = Library::add_from_copy(
4461		directory,
4462		(&copy.folder, &unlocker),
4463		joining,
4464		&protection,
4465		secrets_unlocker.as_ref().zip(secrets_protection.as_ref()),
4466		&now,
4467		environment.rng(),
4468	)?;
4469	output::progress(
4470		"Made this device a device of its own from the copy, whose device is revoked. Devices of yours that turn up later are added anew.",
4471		cli.json,
4472		output,
4473	)?;
4474	Ok(library)
4475}
4476
4477/// Runs `nib recovery restore`: brings the library back on this computer, as a new device of
4478/// the person's, from the backup or the library in `source`, or else the library here, and
4479/// the recovery code that the person types, checked against the source before anything else
4480/// is asked; the other devices are revoked, but those that `keep` names, or else those that
4481/// the person says they still have.
4482fn recover_command<E: Environment>(
4483	directory: &Path,
4484	(source, device, keep): (Option<&Path>, Option<&str>, &[String]),
4485	(passphrase, file): (bool, Option<&Path>),
4486	cli: &Cli,
4487	environment: &mut E,
4488	timings: &mut Timings,
4489	output: &mut dyn Write,
4490) -> Result<Library, CliError> {
4491	// Without a source, the library here, which no longer unlocks.
4492	let source = match source {
4493		Some(source) => absolute(source, environment)?,
4494		None => directory.to_owned(),
4495	};
4496	// Before anything is asked: a library here stays, but for what a recovery cut short left,
4497	// or the library that the recovery replaces.
4498	let replaces = Library::exists(directory) && Library::recovery_replaces(directory, &source);
4499	if Library::exists(directory) && !replaces {
4500		match Library::protection(directory) {
4501			Err(NodeError::Copied | NodeError::RecoveryCutShort) => {}
4502			Err(NodeError::Unfinished) => return Err(unfinished(directory)),
4503			_ => return Err(NodeError::Exists.into()),
4504		}
4505	}
4506	// One that still unlocks with the keystore has nothing to recover, which a passphrase
4507	// does not tell.
4508	if replaces
4509		&& matches!(
4510			Library::protection(directory),
4511			Ok(Protection::Keystore { .. })
4512		)
4513		&& environment.keystore()
4514		&& Library::open(directory, &Unlocker::Keystore).is_ok()
4515	{
4516		return Err(CliError::StillUnlocks);
4517	}
4518	let code = typed_recovery_code("Your recovery code: ", environment, cli.json, output)?;
4519	Library::check_recovery_source(&source, &code)?;
4520	let device = device_name(device, environment);
4521	let new_passphrase = new_passphrase((passphrase, file), environment, timings)?;
4522	let protection = match &new_passphrase {
4523		Some(passphrase) => NewProtection::Passphrase(passphrase, environment.passphrase_params()),
4524		None => NewProtection::Keystore {
4525			service: KEYSTORE_SERVICE,
4526		},
4527	};
4528	let joining = nibkeep_node::Joining::new(&device, APP, environment.rng())?;
4529	let now = clock(environment);
4530	let mut recovering = Library::start_recovery(
4531		directory,
4532		(&source, &code),
4533		joining,
4534		&protection,
4535		&now,
4536		environment.rng(),
4537	)?;
4538	// The devices to keep, first, as a name that --keep does not find ends the recovery;
4539	// then the secrets' passphrase, asked only of a code that holds them. A recovery left
4540	// unfinished removes the new device.
4541	let kept = devices_kept(&recovering, keep, cli.json, environment)?;
4542	recovering.keep(&kept)?;
4543	let secrets_passphrase = if recovering.holds_secrets() {
4544		Some(recovered_secrets_passphrase(
4545			environment,
4546			timings,
4547			new_passphrase.as_deref().map(String::as_str),
4548		)?)
4549	} else {
4550		None
4551	};
4552	let secrets_params = environment.passphrase_params();
4553	let secrets = secrets_passphrase
4554		.as_ref()
4555		.map(|typed| NewProtection::Passphrase(typed, secrets_params));
4556	let (mut library, recovered) = recovering.finish(secrets.as_ref(), &now, environment.rng())?;
4557	library.lock_secrets();
4558	let spaces = sorted_space_names(&library, &recovered.spaces);
4559	let elsewhere = sorted_space_names(&library, &recovered.revoked_elsewhere);
4560	// The room that the old library's folder takes, which the person deletes.
4561	let old_size = match &recovered.from {
4562		nibkeep_node::RecoveredFrom::Library {
4563			set_aside, folder, ..
4564		} => folder_size(set_aside.as_ref().unwrap_or(folder)),
4565		nibkeep_node::RecoveredFrom::Backup { .. } => 0,
4566	};
4567	output::recovered(
4568		&recovered,
4569		(&spaces, &elsewhere, old_size),
4570		cli.json,
4571		output,
4572	)?;
4573	Ok(library)
4574}
4575
4576/// The replicas of the person's other devices that a recovery keeps: those of the devices
4577/// that `named` names, with --keep; without it, those of the devices that the person says
4578/// they still have, asked about each, where nib can ask, which it does not with --json, as
4579/// `json` says; otherwise none, as every other device is lost.
4580fn devices_kept<E: Environment>(
4581	recovering: &nibkeep_node::Recovering<'_>,
4582	named: &[String],
4583	json: bool,
4584	environment: &mut E,
4585) -> Result<Vec<EntityId>, CliError> {
4586	if !named.is_empty() {
4587		let mut kept = Vec::new();
4588		for target in named {
4589			kept.extend(
4590				recovering
4591					.others_named(target)?
4592					.into_iter()
4593					.map(|replica| replica.id),
4594			);
4595		}
4596		return Ok(kept);
4597	}
4598	// With --json, nib runs for a program, which is not asked.
4599	if json || !environment.can_ask() {
4600		return Ok(Vec::new());
4601	}
4602	// One question for each device, with its replicas, and for each AI agent's replica, by
4603	// name, and by ID too where two would read alike.
4604	let mut devices: BTreeMap<EntityId, Vec<Replica>> = BTreeMap::new();
4605	for replica in recovering.others()? {
4606		let device = match replica.device {
4607			Some(device) if !replica.ai_agent => device,
4608			_ => replica.id,
4609		};
4610		devices.entry(device).or_default().push(replica);
4611	}
4612	let mut asked: Vec<(String, EntityId, Vec<Replica>)> = devices
4613		.into_iter()
4614		.map(|(device, replicas)| (output::kept_device_text(&replicas), device, replicas))
4615		.collect();
4616	asked.sort_by(|a, b| (&a.0, a.1).cmp(&(&b.0, b.1)));
4617	let alike: Vec<bool> = asked
4618		.iter()
4619		.map(|(text, ..)| asked.iter().filter(|(other, ..)| other == text).count() > 1)
4620		.collect();
4621	let mut kept = Vec::new();
4622	for ((text, device, replicas), alike) in asked.into_iter().zip(alike) {
4623		let text = if alike {
4624			format!("{text} {}", output::short(device))
4625		} else {
4626			text
4627		};
4628		let answer = environment.ask(&output::keep_question(&text))?;
4629		if answer.is_some_and(|answer| matches!(answer.trim().to_lowercase().as_str(), "y" | "yes"))
4630		{
4631			kept.extend(replicas.iter().map(|replica| replica.id));
4632		}
4633	}
4634	Ok(kept)
4635}
4636
4637/// Asks twice for a passphrase for the secrets that a recovery code brings back, and up to
4638/// three times, as a mistake here would end the recovery and throw away what it took in so
4639/// far: one that is empty, typed differently the second time, or that is `library`, the
4640/// library's passphrase, is asked for again.
4641fn recovered_secrets_passphrase<E: Environment>(
4642	environment: &mut E,
4643	timings: &mut Timings,
4644	library: Option<&str>,
4645) -> Result<zeroize::Zeroizing<String>, CliError> {
4646	let mut tries = 0;
4647	loop {
4648		tries += 1;
4649		let typed = ask_twice(
4650			environment,
4651			timings,
4652			(
4653				"Your recovery code holds your secrets. A passphrase for them on this device, not the library's: ",
4654				"The passphrase again: ",
4655			),
4656			(|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
4657		);
4658		let error = match typed {
4659			Ok(typed) if library.is_some_and(|library| *typed == *library) => {
4660				CliError::Node(NodeError::LibraryPassphrase)
4661			}
4662			Ok(typed) => return Ok(typed),
4663			Err(error @ (CliError::EmptyPassphrase | CliError::PassphrasesDiffer)) => error,
4664			Err(error) => return Err(error),
4665		};
4666		if tries == 3 {
4667			return Err(error);
4668		}
4669		environment.note(&format!("{error}; type it again"));
4670	}
4671}
4672
4673/// Takes in what the copies beside a new replica hold, if there are any: what a backup, a
4674/// program that syncs folders, or a person brought from the devices they are copies of.
4675fn take_in_copies<E: Environment>(
4676	library: &mut Library,
4677	environment: &mut E,
4678) -> Result<Option<output::Copies>, CliError> {
4679	let copies = library.copies();
4680	if copies.is_empty() {
4681		return Ok(None);
4682	}
4683	let now = clock(environment);
4684	let taken = library.take_in_copies(&now)?;
4685	let replicas = library.replicas()?;
4686	let mut devices: Vec<String> = copies
4687		.iter()
4688		.filter_map(|copy| {
4689			let (replica, _) = copy.replica?;
4690			let known = replicas.iter().find(|known| known.id == replica)?;
4691			known.device_name.clone().or_else(|| known.name.clone())
4692		})
4693		.collect();
4694	devices.sort();
4695	devices.dedup();
4696	let size = copies.iter().map(|copy| folder_size(&copy.folder)).sum();
4697	// Secrets that only a copy holds would go with its device, if it were revoked first.
4698	let secrets_left = library.secrets_state()? != nibkeep_node::SecretsState::Here
4699		&& copies.iter().any(|copy| {
4700			copy.protections()
4701				.is_ok_and(|(_, secrets)| secrets.is_some())
4702		});
4703	Ok(Some(output::Copies {
4704		taken,
4705		secrets_left,
4706		devices,
4707		folders: copies.into_iter().map(|copy| copy.folder).collect(),
4708		size,
4709	}))
4710}
4711
4712/// How many bytes the files in a folder take, those in its folders too.
4713fn folder_size(folder: &Path) -> u64 {
4714	std::fs::read_dir(folder)
4715		.into_iter()
4716		.flatten()
4717		.flatten()
4718		.map(|entry| match entry.file_type() {
4719			Ok(kind) if kind.is_dir() => folder_size(&entry.path()),
4720			_ => entry.metadata().map_or(0, |metadata| metadata.len()),
4721		})
4722		.sum()
4723}
4724
4725/// The names of a new library's user and of the person the user is: the name given, for
4726/// both; or else the account's name, as `whoami` prints it, for the user, and the person's
4727/// full name, if the system knows one that differs, for the person.
4728fn user_names<E: Environment>(
4729	given: Option<&str>,
4730	environment: &E,
4731) -> Result<(String, Option<String>), CliError> {
4732	if let Some(given) = given {
4733		return Ok((given.to_owned(), None));
4734	}
4735	let account = environment.account();
4736	let user = account
4737		.name
4738		.map(|name| name.trim().to_owned())
4739		.filter(|name| !name.is_empty())
4740		.ok_or(CliError::NoAccountName)?;
4741	let person = account
4742		.full_name
4743		.map(|name| name.trim().to_owned())
4744		.filter(|name| !name.is_empty() && *name != user);
4745	Ok((user, person))
4746}
4747
4748/// This device's name: the one given, or else the computer's.
4749fn device_name<E: Environment>(given: Option<&str>, environment: &E) -> String {
4750	// A computer without a name still gets a device with one.
4751	given.map_or_else(
4752		|| {
4753			Some(environment.computer_name())
4754				.filter(|name| !name.is_empty())
4755				.unwrap_or_else(|| "device".to_owned())
4756		},
4757		str::to_owned,
4758	)
4759}
4760
4761/// Reads a pairing code from the command line.
4762fn parse_code(text: &str) -> Result<PairingCode, String> {
4763	text.parse()
4764		.map_err(|error: nibkeep_node::NotACode| error.to_string())
4765}
4766
4767/// What `nib sync` says when syncs failed.
4768fn syncs_failed(failed: usize) -> String {
4769	if failed == 1 {
4770		"a device could not be synced with".to_owned()
4771	} else {
4772		format!("{failed} devices could not be synced with")
4773	}
4774}
4775
4776/// How many of the entities that a name could be an error lists.
4777const CANDIDATES_LISTED: usize = 10;
4778
4779/// The error, with the entities it could be named, by short ID, name and types, if it is
4780/// about a name that several entities have.
4781fn candidates_named<E: Environment>(
4782	library: &Library,
4783	error: CliError,
4784	environment: &E,
4785) -> CliError {
4786	let CliError::Node(NodeError::Ambiguous {
4787		reference,
4788		candidates,
4789	}) = error
4790	else {
4791		return error;
4792	};
4793	let personal = library.personal_space();
4794	let day = dating(environment, environment.now(), None).day;
4795	let mut listed = Vec::new();
4796	// The members of each merged entity, read once.
4797	let mut members: std::collections::BTreeMap<EntityId, Vec<nibkeep_node::Listed>> =
4798		std::collections::BTreeMap::new();
4799	for &id in candidates.iter().take(CANDIDATES_LISTED) {
4800		// Each in its own space.
4801		let space = library.space_of(id).ok().flatten().unwrap_or(personal);
4802		let (name, types) = match library.entity(space, id, day) {
4803			Ok(Some(view)) if view.id == id => (view.name, view.types),
4804			// An entity merged into another goes by its own name and types.
4805			Ok(Some(view)) => {
4806				let of_view = members
4807					.entry(view.id)
4808					.or_insert_with(|| library.merged(space, view.id).unwrap_or_default());
4809				let name = of_view
4810					.iter()
4811					.find(|member| member.id == id)
4812					.and_then(|member| member.name.clone());
4813				let types = library.own_types(space, id).unwrap_or_default();
4814				(name.or(view.name), types)
4815			}
4816			_ => (None, Vec::new()),
4817		};
4818		listed.push(nibkeep_node::Listed {
4819			id,
4820			name,
4821			types,
4822			via: None,
4823		});
4824	}
4825	CliError::Ambiguous {
4826		reference,
4827		count: candidates.len(),
4828		candidates: output::candidates(&listed, candidates.len()),
4829	}
4830}
4831
4832/// What `nib file add` says when files could not be added.
4833fn files_failed(failed: usize) -> String {
4834	if failed == 1 {
4835		"a file could not be added".to_owned()
4836	} else {
4837		format!("{failed} files could not be added")
4838	}
4839}
4840
4841/// What `nib verify --export` says when it finds problems.
4842fn unsound_export(problems: usize) -> String {
4843	if problems == 1 {
4844		"the export has a problem".to_owned()
4845	} else {
4846		format!("the export has {problems} problems")
4847	}
4848}
4849
4850/// What `nib verify` says when it finds problems.
4851fn unsound(problems: usize) -> String {
4852	if problems == 1 {
4853		"the library has a problem".to_owned()
4854	} else {
4855		format!("the library has {problems} problems")
4856	}
4857}
4858
4859/// The edits that changes on the command line ask for: values that one command sets for a
4860/// field are set together, before the values it adds and removes.
4861/// Values added and removed are forms if `forms` says so.
4862fn edits(
4863	changes: &[String],
4864	forms: Forms<'_>,
4865	view: &EntityView,
4866	library: &Library,
4867	space: nibkeep_base::SpaceId,
4868) -> Result<Vec<Edit>, CliError> {
4869	let types = library.types(space)?;
4870	let mut sets: Vec<(nibkeep_model::FieldName, Vec<nibkeep_model::Value>)> = Vec::new();
4871	let mut cleared = std::collections::BTreeSet::new();
4872	let mut others = Vec::new();
4873	// Types first, so that the fields of a type given in the same edit can be set.
4874	let mut kinds = view.types.clone();
4875	let (mut given, mut taken) = (Vec::new(), Vec::new());
4876	let mut rest = Vec::new();
4877	for change in changes {
4878		let (left, text) = change
4879			.split_once('=')
4880			.ok_or_else(|| CliError::Assignment(change.clone()))?;
4881		let (field, how) = match (left.strip_suffix('+'), left.strip_suffix('-')) {
4882			(Some(field), _) => (field, '+'),
4883			(_, Some(field)) => (field, '-'),
4884			_ => (left, '='),
4885		};
4886		// `type` is a field of the entity's types where one of them has a field of that name;
4887		// `org.nibkeep.type` is always the types.
4888		let of_types = field == nibkeep_model::fields::TYPE.as_str()
4889			|| (field == "type"
4890				&& matches!(
4891					types::field_named(field, &types, &kinds),
4892					Err(CliError::NoField { .. })
4893				));
4894		if !of_types {
4895			rest.push((change, field, how, text));
4896			continue;
4897		}
4898		match how {
4899			'+' => {
4900				let name = types::type_named(text, &types)?;
4901				kinds.push(name.clone());
4902				given.push(Edit::AddType(name));
4903			}
4904			'-' => taken.push(Edit::RemoveType(types::type_of(text, &view.types, &types)?)),
4905			_ => return Err(CliError::TypeSet),
4906		}
4907	}
4908	for (change, field, how, text) in rest {
4909		let field = types::field_named(field, &types, &kinds)?;
4910		if is_secret(library, space, &field) {
4911			return Err(CliError::SecretField(field));
4912		}
4913		if text.is_empty() {
4914			if how != '=' {
4915				return Err(CliError::Assignment(change.clone()));
4916			}
4917			if sets
4918				.iter()
4919				.any(|(set, values)| *set == field && !values.is_empty())
4920			{
4921				return Err(CliError::SetAndCleared(field));
4922			}
4923			if cleared.insert(field.clone()) {
4924				sets.push((field, Vec::new()));
4925			}
4926			continue;
4927		}
4928		let value = types::value(text, &field, &types, library, space)?;
4929		match how {
4930			'+' if !matches!(forms, Forms::No) => {
4931				let of = match forms {
4932					Forms::Of(of) => Some(types::value(of, &field, &types, library, space)?),
4933					_ => None,
4934				};
4935				others.push(Edit::AddForm { field, of, value });
4936			}
4937			'-' if !matches!(forms, Forms::No) => others.push(Edit::RemoveForm(field, value)),
4938			'+' => others.push(Edit::Add(field, value)),
4939			'-' => others.push(Edit::Remove(field, value)),
4940			_ => {
4941				if cleared.contains(&field) {
4942					return Err(CliError::SetAndCleared(field));
4943				}
4944				match sets.iter_mut().find(|(set, _)| *set == field) {
4945					Some((_, values)) => values.push(value),
4946					None => sets.push((field, vec![value])),
4947				}
4948			}
4949		}
4950	}
4951	if !matches!(forms, Forms::No)
4952		&& !others
4953			.iter()
4954			.any(|edit| matches!(edit, Edit::AddForm { .. } | Edit::RemoveForm(..)))
4955	{
4956		return Err(CliError::NoForms);
4957	}
4958	// Types are given before any is taken away, so that an entity can trade its only type.
4959	Ok(given
4960		.into_iter()
4961		.chain(taken)
4962		.chain(
4963			sets.into_iter()
4964				.map(|(field, values)| Edit::Set(field, values)),
4965		)
4966		.chain(others)
4967		.collect())
4968}
4969
4970/// The ranked languages that the system's languages make: each language, with its script
4971/// if the system names one, once, in the system's order. Regions are left out, so that a
4972/// system set to `en_US` shows English from anywhere; `C` and `POSIX` name no language.
4973/// The modifiers `@latin` and `@cyrillic` name scripts.
4974fn system_languages(locales: &[String]) -> Languages {
4975	let mut ranges: Vec<String> = Vec::new();
4976	for written in locales {
4977		// `sr_RS.UTF-8@latin` names the language, the region, the encoding and a modifier.
4978		let script = match written.rsplit_once('@').map(|(_, modifier)| modifier) {
4979			Some("latin") => Some("Latn"),
4980			Some("cyrillic") => Some("Cyrl"),
4981			_ => None,
4982		};
4983		let locale = written.split(['.', '@']).next().unwrap_or_default();
4984		if locale.is_empty() || locale == "C" || locale == "POSIX" {
4985			continue;
4986		}
4987		let mut subtags = locale.split(['_', '-']);
4988		let mut range = subtags.next().unwrap_or_default().to_owned();
4989		let named = subtags
4990			.next()
4991			.filter(|subtag| subtag.len() == 4 && subtag.chars().all(|c| c.is_ascii_alphabetic()));
4992		if let Some(script) = named.or(script) {
4993			range = format!("{range}-{script}");
4994		}
4995		// One that is not a range is left out, so that the others still count.
4996		if let Ok(parsed) = range.parse::<Languages>() {
4997			let range = parsed.to_string();
4998			if !range.is_empty() && !ranges.contains(&range) {
4999				ranges.push(range);
5000			}
5001		}
5002	}
5003	ranges.join(", ").parse().unwrap_or_default()
5004}
5005
5006/// Reads ranked languages from the command line.
5007fn parse_languages(text: &str) -> Result<Languages, String> {
5008	text.parse()
5009		.map_err(|error: ParseLanguagesError| error.to_string())
5010}
5011
5012/// Reads a language tag from the command line.
5013fn parse_tag(text: &str) -> Result<Tag, String> {
5014	Tag::parse(text).ok_or_else(|| {
5015		"a language tag is written as in BCP 47, such as en, uk or uk-Latn".to_owned()
5016	})
5017}
5018
5019/// The day a command shows, and the time it writes: today at `now`, at the device's offset
5020/// from UTC, unless the person chose another day.
5021fn dating<E: Environment>(environment: &E, now: u64, on: Option<Day>) -> Dating {
5022	match on {
5023		Some(day) => Dating::on(day),
5024		None => Dating::today(now, environment.offset_minutes())
5025			.or_else(|| Dating::today(now, 0))
5026			.expect("the time has a day in UTC"),
5027	}
5028}
5029
5030/// Reads a day, such as `2000-01-01`, from the command line.
5031fn parse_day(text: &str) -> Result<Day, String> {
5032	text.parse()
5033		.map_err(|_| "a day is written as YYYY-MM-DD, such as 2000-01-01".to_owned())
5034}
5035
5036/// A moment from the command line: a day, which means its end, or a date and time, in local
5037/// time unless it gives its offset from UTC.
5038#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5039pub enum Moment {
5040	/// The end of a day, in local time.
5041	Day(jiff::civil::Date),
5042	/// A date and time, in local time.
5043	Local(jiff::civil::DateTime),
5044	/// A date and time with its offset from UTC.
5045	Exact(jiff::Timestamp),
5046}
5047
5048impl Moment {
5049	/// The moment, in milliseconds since 1970, and its day, in a time zone; no milliseconds
5050	/// for a moment before 1970, before the library recorded anything. The end of a day is
5051	/// its last millisecond.
5052	///
5053	/// # Errors
5054	///
5055	/// Returns an error if the moment cannot be placed in the time zone.
5056	fn resolve(self, zone: &jiff::tz::TimeZone) -> Result<(Option<u64>, Day), CliError> {
5057		let unplaced = || CliError::Moment("it cannot be placed in local time".to_owned());
5058		let timestamp = match self {
5059			Self::Day(date) => date
5060				.tomorrow()
5061				.ok()
5062				.and_then(|next| next.to_zoned(zone.clone()).ok())
5063				.and_then(|next| {
5064					next.timestamp()
5065						.checked_sub(jiff::SignedDuration::from_millis(1))
5066						.ok()
5067				})
5068				.ok_or_else(unplaced)?,
5069			Self::Local(time) => time
5070				.to_zoned(zone.clone())
5071				.map_err(|_| unplaced())?
5072				.timestamp(),
5073			Self::Exact(timestamp) => timestamp,
5074		};
5075		let millis = u64::try_from(timestamp.as_millisecond()).ok();
5076		let date = match self {
5077			Self::Day(date) => date,
5078			_ => timestamp.to_zoned(zone.clone()).date(),
5079		};
5080		let day = Day::from_ymd(
5081			i64::from(date.year()),
5082			date.month().unsigned_abs(),
5083			date.day().unsigned_abs(),
5084		)
5085		.expect("every date of a calendar is a day");
5086		Ok((millis, day))
5087	}
5088}
5089
5090/// Reads a moment from the command line.
5091fn parse_moment(text: &str) -> Result<Moment, String> {
5092	let wrong = || {
5093		"a day such as 2026-10-10, or a moment such as 2026-10-10T20:00, with its offset such as +02:00 if not in local time"
5094			.to_owned()
5095	};
5096	// A day is written as YYYY-MM-DD and nothing more; anything longer has a time.
5097	if text.len() == "YYYY-MM-DD".len() {
5098		return text
5099			.parse::<jiff::civil::Date>()
5100			.map(Moment::Day)
5101			.map_err(|_| wrong());
5102	}
5103	if let Ok(timestamp) = text.parse::<jiff::Timestamp>() {
5104		return Ok(Moment::Exact(timestamp));
5105	}
5106	text.parse::<jiff::civil::DateTime>()
5107		.map(Moment::Local)
5108		.map_err(|_| wrong())
5109}
5110
5111/// Reads a date, a date and time, or an interval in EDTF from the command line.
5112fn parse_edtf(text: &str) -> Result<Edtf, String> {
5113	text.parse()
5114		.map_err(|error: nibkeep_time::ParseEdtfError| error.to_string())
5115}
5116
5117/// Prints an entity as it is on a day, as recorded now or by a moment, with the names of
5118/// the entities it refers to.
5119fn show(
5120	library: &Library,
5121	space: nibkeep_base::SpaceId,
5122	entity: nibkeep_base::EntityId,
5123	when: When,
5124	json: bool,
5125	output: &mut dyn Write,
5126) -> Result<(), CliError> {
5127	show_added(library, space, entity, &[], when, json, output)
5128}
5129
5130/// The day to show an entity on, and the moment, in milliseconds since 1970, by which its
5131/// record is shown, if not now.
5132#[derive(Clone, Copy, Debug)]
5133struct When {
5134	day: Day,
5135	as_of: Option<u64>,
5136	/// The day given with `--on`, if one was: what `nib list --on` lists on.
5137	given: Option<Day>,
5138}
5139
5140impl When {
5141	/// A day, as recorded now.
5142	const fn on(day: Day) -> Self {
5143		Self {
5144			day,
5145			as_of: None,
5146			given: None,
5147		}
5148	}
5149
5150	/// A day given with `--on`, or today, as recorded now.
5151	fn given(day: Day, given: Option<Day>) -> Self {
5152		Self {
5153			given,
5154			..Self::on(day)
5155		}
5156	}
5157}
5158
5159/// Prints an entity as [`show`] does, with the entities recorded before it with the same
5160/// participants, if it was just added.
5161fn show_added(
5162	library: &Library,
5163	space: nibkeep_base::SpaceId,
5164	entity: nibkeep_base::EntityId,
5165	recorded_before: &[nibkeep_base::EntityId],
5166	when: When,
5167	json: bool,
5168	output: &mut dyn Write,
5169) -> Result<(), CliError> {
5170	let When { day, as_of, given } = when;
5171	let view: Option<EntityView> = match as_of {
5172		Some(millis) => library.entity_as_of(space, entity, day, millis)?,
5173		None => library.entity(space, entity, day)?,
5174	};
5175	let view = view.ok_or_else(|| NodeError::NoEntity(entity.to_string()))?;
5176	let links = match as_of {
5177		Some(millis) => library.links_to_as_of(space, view.id, day, millis, LINKS_SHOWN)?,
5178		None => library.links_to_anywhere(space, view.id, day, LINKS_SHOWN)?,
5179	};
5180	// The entities it refers to go by the names they had then.
5181	let merged = match as_of {
5182		Some(millis) => library.merged_as_of(space, view.id, millis)?,
5183		None => library.merged(space, view.id)?,
5184	};
5185	// A link may lead to an entity of another space, or one moved there.
5186	let name_of = |entity| match as_of {
5187		Some(millis) => library.name_as_of(space, entity, millis).ok().flatten(),
5188		None => library
5189			.name_anywhere(entity)
5190			.ok()
5191			.flatten()
5192			.or_else(|| library.name(space, entity).ok().flatten()),
5193	};
5194	// Secret values are sealed, so which entity they are of is not known until they are
5195	// unlocked: the secret fields that its types list are named instead.
5196	let mut secret = library.secret_fields_of(space, &view.types)?;
5197	secret.retain(|field| !view.fields.iter().any(|shown| shown.field == *field));
5198	// What `nib list` takes to list the links left out; none lists them as recorded by a
5199	// moment.
5200	let more = match as_of {
5201		Some(_) => None,
5202		None => Some(given.map_or_default(|day| format!(" --on {day}"))),
5203	};
5204	// A file shows its thumbnail, as recorded now.
5205	let thumbnail = if as_of.is_none() && view.types.contains(&FILE) {
5206		library.thumbnail(space, view.id)?
5207	} else {
5208		None
5209	};
5210	let shown = output::Shown {
5211		view: &view,
5212		merged: &merged,
5213		secret: &secret,
5214		links: &links,
5215		more: more.as_deref(),
5216		recorded_before,
5217		thumbnail: thumbnail.as_ref(),
5218	};
5219	output::entity(&shown, &name_of, json, output)
5220}
5221
5222/// Runs `nib init`: starts a library for the user, named as given or else after the account,
5223/// on this device, with the languages given or else the system's.
5224fn init_command<E: Environment>(
5225	directory: &Path,
5226	(name, device, languages): (Option<&str>, Option<&str>, Option<&Languages>),
5227	passphrase: (bool, Option<&Path>),
5228	environment: &mut E,
5229	timings: &mut Timings,
5230) -> Result<Library, CliError> {
5231	let (user, person) = user_names(name, environment)?;
5232	let device = device_name(device, environment);
5233	let languages = languages
5234		.cloned()
5235		.unwrap_or_else(|| system_languages(&environment.languages()));
5236	let new = NewLibrary::new(&user, &device, APP)
5237		.with_person(person.as_deref())
5238		.with_languages(languages);
5239	init(directory, &new, passphrase, environment, timings)
5240}
5241
5242/// Runs `nib show`, in the personal space: an entity on a day, today unless another is
5243/// given, as recorded now or by a moment; a tree's revision with what it changed, as
5244/// `git show` shows a commit.
5245fn show_command<E: Environment>(
5246	library: &Library,
5247	(reference, on, as_of): (&str, Option<Day>, Option<Moment>),
5248	json: bool,
5249	environment: &E,
5250	output: &mut dyn Write,
5251) -> Result<(), CliError> {
5252	let (space, entity) = library.locate_or_deleted(reference)?;
5253	let Some(diff) = library.revision_diff(space, entity, false)? else {
5254		return show_entity(
5255			library,
5256			(space, entity),
5257			(reference, on, as_of),
5258			json,
5259			environment,
5260			output,
5261		);
5262	};
5263	let mut shown = Vec::new();
5264	let what = (reference, on, as_of);
5265	show_entity(
5266		library,
5267		(space, entity),
5268		what,
5269		json,
5270		environment,
5271		&mut shown,
5272	)?;
5273	if json {
5274		let mut value: serde_json::Value = serde_json::from_slice(&shown)
5275			.map_err(|error| CliError::Io(io::Error::other(error)))?;
5276		value["diff"] = trees::diff_json(&diff);
5277		return output::print_json(&value, output);
5278	}
5279	output.write_all(&shown)?;
5280	writeln!(output)?;
5281	trees::diff_text(&diff, output)
5282}
5283
5284/// Prints an entity for `nib show`, on a day, as recorded now or by a moment.
5285fn show_entity<E: Environment>(
5286	library: &Library,
5287	(space, entity): (SpaceId, EntityId),
5288	(reference, on, as_of): (&str, Option<Day>, Option<Moment>),
5289	json: bool,
5290	environment: &E,
5291	output: &mut dyn Write,
5292) -> Result<(), CliError> {
5293	let Some(as_of) = as_of else {
5294		let day = dating(environment, environment.now(), on).day;
5295		return show(library, space, entity, When::given(day, on), json, output);
5296	};
5297	let zone = environment.time_zone();
5298	let (millis, as_of_day) = as_of.resolve(&zone)?;
5299	let when = When {
5300		day: on.unwrap_or(as_of_day),
5301		as_of: millis,
5302		given: Some(on.unwrap_or(as_of_day)),
5303	};
5304	let recorded = match millis {
5305		Some(millis) => library
5306			.entity_as_of(space, entity, when.day, millis)?
5307			.is_some(),
5308		None => false,
5309	};
5310	if !recorded {
5311		return Err(CliError::NotYet {
5312			entity: reference.to_owned(),
5313			when: millis.map_or_else(
5314				|| "1970".to_owned(),
5315				|millis| output::moment_text(millis, &zone),
5316			),
5317		});
5318	}
5319	show(library, space, entity, when, json, output)
5320}
5321
5322/// Runs a command that only reads the library: `status`, `show`, `history`, `export`,
5323/// `find` and `list`.
5324fn reading_command<E: Environment>(
5325	library: &Library,
5326	cli: &Cli,
5327	library_folder: &Path,
5328	environment: &E,
5329	output: &mut dyn Write,
5330) -> Result<(), CliError> {
5331	let json = cli.json;
5332	match &cli.command {
5333		Command::Status { .. } => {
5334			let mut checkouts = Vec::new();
5335			for space in library.spaces() {
5336				checkouts.extend(library.checkouts(space)?);
5337			}
5338			let checks = library
5339				.sync_records(UnwrapErr(SysRng))
5340				.ok()
5341				.and_then(|records| library.check_status(&records, environment.now()).ok());
5342			let name_of = |space, file: Option<EntityId>| match file {
5343				Some(file) => library.name(space, file).ok().flatten(),
5344				None => library.space_name(space).ok().flatten(),
5345			};
5346			let zone = environment.time_zone();
5347			let checks = output::Checks {
5348				status: checks.as_ref(),
5349				name_of: &name_of,
5350				zone: &zone,
5351			};
5352			let mut thumbnails = std::collections::BTreeMap::new();
5353			for space in library.spaces() {
5354				thumbnails.insert(space, library.thumbnail_counts(space)?);
5355			}
5356			output::status(
5357				(&library.status()?, &checkouts, &thumbnails),
5358				checks,
5359				library_folder,
5360				json,
5361				output,
5362			)
5363		}
5364		Command::Show { entity, on, as_of } => {
5365			show_command(library, (entity, *on, *as_of), json, environment, output)
5366		}
5367		Command::History { entity, field } => history_command(
5368			library,
5369			(entity, field.as_deref()),
5370			json,
5371			environment,
5372			output,
5373		),
5374		Command::Export { folder, current } => {
5375			export_command(library, folder, *current, json, output)
5376		}
5377		Command::Find { words, all } => {
5378			let words = words.join(" ");
5379			let first = if *all { usize::MAX } else { FIND_FIRST };
5380			let mut groups = Vec::new();
5381			for space in spaces_to_read(library) {
5382				// Not those moved into another space that this library holds, which show
5383				// there.
5384				let found = library.search_first(space, &words, first, |entity, _| {
5385					Ok(library.moved_into(space, entity)?.is_none())
5386				})?;
5387				groups.push((library.space_name(space)?, found));
5388			}
5389			let missed = not_looked_in(library)?;
5390			output::found_in_spaces((&groups, &missed), json, output)
5391		}
5392		Command::List {
5393			kind,
5394			conditions,
5395			sort,
5396			on,
5397		} => {
5398			let list = (kind.as_deref(), conditions.as_slice(), sort.as_deref());
5399			list_command(library, list, *on, json, environment, output)
5400		}
5401		_ => unreachable!("only commands that read come here"),
5402	}
5403}
5404
5405/// Runs `nib export`: the personal space, in full or as it is now, into a folder.
5406fn export_command(
5407	library: &Library,
5408	folder: &Path,
5409	current: bool,
5410	json: bool,
5411	output: &mut dyn Write,
5412) -> Result<(), CliError> {
5413	let kind = if current {
5414		nibkeep_node::ExportKind::Current
5415	} else {
5416		nibkeep_node::ExportKind::Full
5417	};
5418	let exported = library.export(library.default_space(), folder, kind)?;
5419	output::exported(&exported, folder, kind, json, output)
5420}
5421
5422/// Runs `nib verify --export`: checks an export against the library, and fails if it finds
5423/// problems.
5424fn verify_export_command(
5425	library: &Library,
5426	folder: &Path,
5427	json: bool,
5428	output: &mut dyn Write,
5429) -> Result<(), CliError> {
5430	let check = library.verify_export(folder)?;
5431	output::export_check(&check, folder, json, output)?;
5432	match check.problems.len() {
5433		0 => Ok(()),
5434		problems => Err(CliError::UnsoundExport(problems)),
5435	}
5436}
5437
5438/// Runs `nib verify`: checks the library, or with a folder, an export against it, and fails
5439/// if it finds problems.
5440fn verify_command<E: Environment>(
5441	library: &mut Library,
5442	export: Option<&Path>,
5443	json: bool,
5444	environment: &E,
5445	output: &mut dyn Write,
5446) -> Result<(), CliError> {
5447	if let Some(folder) = export {
5448		return verify_export_command(library, folder, json, output);
5449	}
5450	let report = library.verify(environment.now())?;
5451	// A damaged copy, moved aside, comes again with the next sync: the holder of the sync
5452	// role, if a program holds it, syncs now.
5453	let set_aside = report.spaces.iter().any(|space| {
5454		space
5455			.problems
5456			.iter()
5457			.any(|problem| matches!(problem, nibkeep_node::Problem::DamagedBlob(_)))
5458	});
5459	if set_aside && let Ok(records) = library.sync_records(UnwrapErr(SysRng)) {
5460		let _ = records.ask(None, environment.now());
5461	}
5462	output::report(&report, json, output)?;
5463	let problems = report.problems();
5464	if problems > 0 {
5465		return Err(CliError::Unsound(problems));
5466	}
5467	Ok(())
5468}
5469
5470/// Runs `nib list`, in the personal space: the entities, or those of a type.
5471fn list_command<E: Environment>(
5472	library: &Library,
5473	list: (Option<&str>, &[String], Option<&str>),
5474	on: Option<Day>,
5475	json: bool,
5476	environment: &E,
5477	output: &mut dyn Write,
5478) -> Result<(), CliError> {
5479	// The space chosen, or every space: one where the type or a field is unknown is passed
5480	// over, unless every space is.
5481	let mut groups = Vec::new();
5482	let mut failed = None;
5483	for space in spaces_to_read(library) {
5484		match listed_in(library, space, list, on, environment) {
5485			Ok(listed) => groups.push((space, listed)),
5486			// A type or a field that this space does not know.
5487			Err(
5488				error @ (CliError::NoType(_)
5489				| CliError::AmbiguousType { .. }
5490				| CliError::NoField { .. }
5491				| CliError::AmbiguousField { .. }),
5492			) => {
5493				failed = failed.or(Some(error));
5494			}
5495			Err(error) => return Err(error),
5496		}
5497	}
5498	if groups.is_empty()
5499		&& let Some(error) = failed
5500	{
5501		return Err(error);
5502	}
5503	let missed = not_looked_in(library)?;
5504	output::entities_in_spaces((&named_groups(library, groups)?, &missed), json, output)
5505}
5506
5507/// The names of the person's spaces that a command reading every space did not look in, as
5508/// this device does not hold them: none when a space is chosen.
5509fn not_looked_in(library: &Library) -> Result<Vec<String>, CliError> {
5510	if library.chosen_space().is_some() {
5511		return Ok(Vec::new());
5512	}
5513	let looked_in = library.spaces();
5514	Ok(library
5515		.known_spaces()?
5516		.into_iter()
5517		.filter(|known| !looked_in.contains(&known.space))
5518		.map(|known| known.name.unwrap_or_else(|| known.space.to_string()))
5519		.collect())
5520}
5521
5522/// The spaces a command that reads looks in: the one chosen, or else every space.
5523fn spaces_to_read(library: &Library) -> Vec<nibkeep_base::SpaceId> {
5524	match library.chosen_space() {
5525		Some(space) => vec![space],
5526		None => library.spaces(),
5527	}
5528}
5529
5530/// How many entities `nib find` lists of each space, unless asked for all: enough to find
5531/// what one looks for, while a common word, which finds thousands, takes a moment to list,
5532/// and fills a screen or an AI agent's context.
5533const FIND_FIRST: usize = 50;
5534
5535/// What was found in a space, under the space's name.
5536type NamedGroup = (Option<String>, Vec<nibkeep_node::Listed>);
5537
5538/// What was found in each space, with the space's name, but entities moved into another
5539/// space that this library holds, which show there.
5540fn named_groups(
5541	library: &Library,
5542	groups: Vec<(nibkeep_base::SpaceId, Vec<nibkeep_node::Listed>)>,
5543) -> Result<Vec<NamedGroup>, CliError> {
5544	groups
5545		.into_iter()
5546		.map(|(space, listed)| {
5547			let mut kept = Vec::new();
5548			for entity in listed {
5549				if library.moved_into(space, entity.id)?.is_none() {
5550					kept.push(entity);
5551				}
5552			}
5553			Ok((library.space_name(space)?, kept))
5554		})
5555		.collect()
5556}
5557
5558/// The entities of one space that `nib list` lists.
5559fn listed_in<E: Environment>(
5560	library: &Library,
5561	space: nibkeep_base::SpaceId,
5562	(kind, conditions, sort): (Option<&str>, &[String], Option<&str>),
5563	on: Option<Day>,
5564	environment: &E,
5565) -> Result<Vec<nibkeep_node::Listed>, CliError> {
5566	let types = library.types(space)?;
5567	let kind = match kind {
5568		Some(kind) => Some(types::type_named(kind, &types)?),
5569		None => None,
5570	};
5571	// Fields are those of the type, or else of the other types its entities have, as an
5572	// audiobook is an edition too, read only when needed; without a type, any type's.
5573	let mut held: Option<Vec<TypeName>> = None;
5574	let mut field_named = |text: &str| -> Result<FieldName, CliError> {
5575		let Some(kind) = &kind else {
5576			let every: Vec<TypeName> = types
5577				.iter()
5578				.map(|definition| definition.name().clone())
5579				.collect();
5580			return types::field_named(text, &types, &every);
5581		};
5582		types::field_of_listed(text, &types, kind, || {
5583			if held.is_none() {
5584				held = Some(library.types_with(space, kind)?.into_iter().collect());
5585			}
5586			Ok(held.as_deref().unwrap_or_default())
5587		})
5588	};
5589	let mut conditions_given = Vec::new();
5590	for condition in conditions {
5591		let (field, text) = condition
5592			.split_once('=')
5593			.filter(|(_, text)| !text.is_empty())
5594			.ok_or_else(|| CliError::Assignment(condition.clone()))?;
5595		let field = field_named(field)?;
5596		if is_secret(library, space, &field) {
5597			return Err(CliError::SecretField(field));
5598		}
5599		let value = types::value(text, &field, &types, library, space)?;
5600		conditions_given.push((field, value));
5601	}
5602	let order_by = match sort {
5603		Some(field) => {
5604			let field = field_named(field)?;
5605			if is_secret(library, space, &field) {
5606				return Err(CliError::SecretField(field));
5607			}
5608			Some(field)
5609		}
5610		None => None,
5611	};
5612	let listing = nibkeep_node::Listing {
5613		of_type: kind,
5614		conditions: conditions_given,
5615		order_by,
5616		on,
5617	};
5618	let today = dating(environment, environment.now(), None).day;
5619	Ok(library.list(space, &listing, today)?)
5620}
5621
5622/// Runs `nib merge`, in the personal space: merges an entity into another, or undoes the
5623/// merge of one merged into it, and shows the entity that stands apart or for both.
5624fn merge_command<E: Environment>(
5625	library: &mut Library,
5626	(reference, other, undo): (&str, Option<&str>, bool),
5627	json: bool,
5628	environment: &mut E,
5629	output: &mut dyn Write,
5630) -> Result<(), CliError> {
5631	let (space, found) = library.locate(reference)?;
5632	// The command works in the space that holds the entity.
5633	library.choose_space(Some(space))?;
5634	let now = environment.now();
5635	let shown = if undo {
5636		let member = match other {
5637			Some(other) => match library.find_merged(space, found, other) {
5638				Err(NodeError::NotMerged(_)) if library.merged(space, found)?.is_empty() => {
5639					return Err(CliError::NothingMerged(reference.to_owned()));
5640				}
5641				Err(NodeError::NotMerged(_)) => {
5642					return Err(CliError::NotMergedInto {
5643						entity: reference.to_owned(),
5644						other: other.to_owned(),
5645					});
5646				}
5647				found => found?,
5648			},
5649			None => match library.merged(space, found)?.as_slice() {
5650				[] => return Err(CliError::NothingMerged(reference.to_owned())),
5651				[only] => only.id,
5652				merged => {
5653					return Err(CliError::WhichMerged {
5654						entity: reference.to_owned(),
5655						candidates: output::listed_names(merged),
5656					});
5657				}
5658			},
5659		};
5660		library.undo_merge(space, member, now, environment.rng())?;
5661		member
5662	} else {
5663		// An entity merged into another is named by its own names: merged again, it moves.
5664		let from = match library.find_merged(space, found, reference) {
5665			Ok(member) => member,
5666			Err(NodeError::NotMerged(_)) => found,
5667			Err(error) => return Err(error.into()),
5668		};
5669		let other = other.unwrap_or_default();
5670		let into = library.find_entity(space, other)?;
5671		library
5672			.merge_entities(space, from, into, now, environment.rng())
5673			.map_err(|error| match error {
5674				NodeError::SameEntity(_) => CliError::OneAlready {
5675					entity: reference.to_owned(),
5676					into: other.to_owned(),
5677				},
5678				error => error.into(),
5679			})?;
5680		into
5681	};
5682	let day = dating(environment, now, None).day;
5683	show(library, space, shown, When::on(day), json, output)
5684}
5685
5686/// Runs `nib history`, in the personal space: every value an entity has had, or one
5687/// field's.
5688fn history_command<E: Environment>(
5689	library: &Library,
5690	(reference, field): (&str, Option<&str>),
5691	json: bool,
5692	environment: &E,
5693	output: &mut dyn Write,
5694) -> Result<(), CliError> {
5695	let (space, entity) = library.locate_or_deleted(reference)?;
5696	let mut history = library
5697		.history(space, entity, None)?
5698		.ok_or_else(|| NodeError::NoEntity(entity.to_string()))?;
5699	// A field is any the entity has had, of a type it has now or not.
5700	if let Some(field) = field {
5701		let had: Vec<_> = history
5702			.fields
5703			.iter()
5704			.map(|past| past.field.clone())
5705			.collect();
5706		let wanted = types::field_among(field, &had).map_err(|error| {
5707			// Secret values are left out until they are unlocked.
5708			let day = dating(environment, environment.now(), None).day;
5709			let view = library.entity(space, entity, day).ok().flatten();
5710			let types = library.types(space).ok();
5711			let secret = types
5712				.zip(view)
5713				.and_then(|(types, view)| types::field_named(field, &types, &view.types).ok())
5714				.filter(|field| is_secret(library, space, field));
5715			secret.map_or(error, CliError::SecretHistory)
5716		})?;
5717		history.fields.retain(|past| past.field == wanted);
5718	}
5719	let name_of = |entity| library.name(space, entity).ok().flatten();
5720	output::history(&history, &name_of, &environment.time_zone(), json, output)
5721}
5722
5723/// Runs `nib new`, in the personal space: adds an entity of a type, with values as
5724/// `field=value`, in a language if given.
5725fn new_command<E: Environment>(
5726	library: &mut Library,
5727	(kind, values, language): (&str, &[String], Option<&Tag>),
5728	json: bool,
5729	environment: &mut E,
5730	output: &mut dyn Write,
5731) -> Result<(), CliError> {
5732	let space = library.default_space();
5733	let types = library.types(space)?;
5734	let mut kinds: Vec<TypeName> = Vec::new();
5735	for name in kind.split(',') {
5736		let name = types::type_named(name.trim(), &types)?;
5737		// NibKeep's own commands make the records of users, devices, replicas and spaces.
5738		if nibkeep_node::OWN_RECORDS.contains(&name) {
5739			return Err(NodeError::OwnType(name).into());
5740		}
5741		if !kinds.contains(&name) {
5742			kinds.push(name);
5743		}
5744	}
5745	let mut parsed = Vec::new();
5746	for assignment in values {
5747		let (field, text) = assignment
5748			.split_once('=')
5749			.ok_or_else(|| CliError::Assignment(assignment.clone()))?;
5750		let field = types::field_named(field, &types, &kinds)?;
5751		if is_secret(library, space, &field) {
5752			return Err(CliError::SecretField(field));
5753		}
5754		let value = types::value(text, &field, &types, library, space)?;
5755		parsed.push((field, value));
5756	}
5757	// A relationship is an entity, so recording one twice makes two: say so.
5758	let recorded_before = library.same_relationship(space, &kinds, &parsed)?;
5759	let now = environment.now();
5760	let rng = environment.rng();
5761	let entity = match language {
5762		Some(language) => {
5763			library.create_entity_with_language(space, &kinds, parsed, language, now, rng)?
5764		}
5765		None => library.create_entity(space, &kinds, parsed, now, rng)?,
5766	};
5767	let day = dating(environment, now, None).day;
5768	show_added(
5769		library,
5770		space,
5771		entity,
5772		&recorded_before,
5773		When::on(day),
5774		json,
5775		output,
5776	)
5777}
5778
5779/// Runs `nib languages`: shows the lists of languages, after setting or clearing one.
5780fn languages_command<E: Environment>(
5781	library: &mut Library,
5782	command: &Command,
5783	json: bool,
5784	environment: &mut E,
5785	output: &mut dyn Write,
5786) -> Result<(), CliError> {
5787	let Command::Languages {
5788		ranges,
5789		device,
5790		app,
5791		clear,
5792	} = command
5793	else {
5794		unreachable!("only for nib languages");
5795	};
5796	let whose = match (device, app) {
5797		(true, _) => LanguagesFor::Device,
5798		(_, true) => LanguagesFor::Replica,
5799		_ => LanguagesFor::User,
5800	};
5801	let set = match ranges {
5802		Some(ranges) => Some(Some(ranges.parse::<Languages>()?)),
5803		None if *clear => Some(None),
5804		None => None,
5805	};
5806	if let Some(languages) = set {
5807		let now = environment.now();
5808		library.set_languages(whose, languages.as_ref(), now, environment.rng())?;
5809	}
5810	output::languages(&library.language_settings()?, json, output)
5811}
5812
5813/// Runs `nib edit`, in the personal space.
5814fn edit_command<E: Environment>(
5815	library: &mut Library,
5816	arguments: &EditArgs,
5817	json: bool,
5818	environment: &mut E,
5819	output: &mut dyn Write,
5820) -> Result<(), CliError> {
5821	let EditArgs {
5822		entity,
5823		changes,
5824		date,
5825		on,
5826		delete,
5827		restore,
5828		language,
5829		form,
5830		form_of,
5831	} = arguments;
5832	let (space, id) = library.locate_or_deleted(entity)?;
5833	// The command works in the space that holds the entity.
5834	library.choose_space(Some(space))?;
5835	// One reading of the clock, for the values' dates and the change alike.
5836	let now = environment.now();
5837	let mut dating = dating(environment, now, *on);
5838	if let Some(date) = date {
5839		dating = dating.with_valid_time(date.clone());
5840	}
5841	if let Some(language) = language {
5842		dating = dating.with_language(language.clone());
5843	}
5844	let view = library
5845		.entity(space, id, dating.day)?
5846		.ok_or_else(|| NodeError::NoEntity(entity.clone()))?;
5847	let forms = match (form_of, form) {
5848		(Some(of), _) => Forms::Of(of),
5849		(None, true) => Forms::OfTheOnly,
5850		(None, false) => Forms::No,
5851	};
5852	let mut edits = edits(changes, forms, &view, library, space)?;
5853	if *delete {
5854		edits.push(Edit::Delete);
5855	}
5856	if *restore {
5857		edits.push(Edit::Restore);
5858	}
5859	library.edit_entity(space, id, edits, &dating, now, environment.rng())?;
5860	show(
5861		library,
5862		space,
5863		id,
5864		When::given(dating.day, *on),
5865		json,
5866		output,
5867	)
5868}
5869
5870/// Runs `nib purge`, in the personal space. The values of a secret field are purged all
5871/// at once, after the secrets are unlocked, since none is given on the command line; `nib
5872/// secret purge` purges one.
5873fn purge_command<E: Environment>(
5874	library: &mut Library,
5875	(entity, assignment, confirmed): (&str, &str, bool),
5876	json: bool,
5877	environment: &mut E,
5878	timings: &mut Timings,
5879	output: &mut dyn Write,
5880) -> Result<(), CliError> {
5881	let (space, id) = library.locate_or_deleted(entity)?;
5882	// The command works in the space that holds the entity.
5883	library.choose_space(Some(space))?;
5884	let view = library
5885		.entity(space, id, dating(environment, environment.now(), None).day)?
5886		.ok_or_else(|| NodeError::NoEntity(entity.to_owned()))?;
5887	let (field, text) = assignment
5888		.split_once('=')
5889		.ok_or_else(|| CliError::Assignment(assignment.to_owned()))?;
5890	let types = library.types(space)?;
5891	let field = types::field_named(field, &types, &view.types)?;
5892	let secret = is_secret(library, space, &field);
5893	if secret && !text.is_empty() {
5894		return Err(CliError::SecretGiven(field));
5895	}
5896	let value = if text.is_empty() {
5897		None
5898	} else {
5899		Some(types::value(text, &field, &types, library, space)?)
5900	};
5901	// Values written before the field was secret are plain, and show without secrets.
5902	if secret && library.secrets_protection()?.is_some() {
5903		unlock_secrets(library, false, environment, timings)?;
5904	}
5905	let purged = purge_values(
5906		library,
5907		(id, &field, value.as_ref()),
5908		confirmed,
5909		environment,
5910	);
5911	library.lock_secrets();
5912	let purged = purged?;
5913	let name_of = |entity| library.name(space, entity).ok().flatten();
5914	let elsewhere = space_names(library, &purged.elsewhere);
5915	output::purge(
5916		&purged,
5917		(&field, &name_of),
5918		&elsewhere,
5919		confirmed,
5920		json,
5921		output,
5922	)?;
5923	if confirmed {
5924		Ok(())
5925	} else {
5926		Err(CliError::Unconfirmed)
5927	}
5928}
5929
5930/// Runs `nib purges`: lists the purges that wait on this device, stops one, or ends its wait,
5931/// once confirmed; unconfirmed, it says what it would do.
5932fn purges_waiting_command<E: Environment>(
5933	library: &mut Library,
5934	command: Option<&PurgesCommand>,
5935	json: bool,
5936	environment: &mut E,
5937	output: &mut dyn Write,
5938) -> Result<(), CliError> {
5939	let zone = environment.time_zone();
5940	// The backups plugged in here, where purges may wait too.
5941	let records = library.sync_records(UnwrapErr(SysRng))?;
5942	let remembered: BTreeMap<EntityId, PathBuf> = records
5943		.backup_folders()?
5944		.into_iter()
5945		.map(|(backup, found)| (backup, found.folder))
5946		.collect();
5947	let found = library.find_backups(&remembered)?;
5948	let Some(command) = command else {
5949		let mut waiting = library.waiting_purges()?;
5950		waiting.extend(library.waiting_purges_on(&found)?);
5951		let mut spaces = Vec::new();
5952		for purge in &waiting {
5953			spaces.push(space_display_name(library, purge.space)?);
5954		}
5955		let days = library.own_wait_days()?;
5956		return output::waiting_purges((&waiting, &spaces), days, &zone, json, output);
5957	};
5958	let (name, on, yes, stopping) = match command {
5959		PurgesCommand::Stop { purge, on, yes } => (purge, on, *yes, true),
5960		PurgesCommand::End { purge, on, yes } => (purge, on, *yes, false),
5961	};
5962	let waiting = library.find_waiting_purges(name, (&found, on.as_deref()))?;
5963	let space = space_display_name(library, waiting[0].space)?;
5964	if yes {
5965		let now = environment.now();
5966		let updated = if stopping {
5967			library.stop_purge(&waiting, now, environment.rng())?
5968		} else {
5969			library.end_wait(&waiting, now)?.1
5970		};
5971		// The backups updated here, as the holder records its own updates.
5972		let kept = library.changes_kept()?;
5973		for backup in updated {
5974			if let Some(on) = waiting
5975				.iter()
5976				.filter_map(|place| place.on.as_ref())
5977				.find(|on| on.backup == backup.id)
5978			{
5979				records.record_backup(on.backup, &on.folder, Some((now, kept)))?;
5980			}
5981		}
5982	}
5983	output::purge_waited((&waiting, &space), (stopping, yes), &zone, json, output)?;
5984	if yes {
5985		Ok(())
5986	} else {
5987		Err(CliError::Unconfirmed)
5988	}
5989}
5990
5991/// Runs `nib move`: moves an entity to another space, with its history unless
5992/// `without_history`, and its secret values unless `leave_secrets`, unlocking the secrets
5993/// when it may hold some; a folder or a list, with what it holds, or an entity that leaves a
5994/// folder or a list that stays, only once `confirmed`, and otherwise says what it would take.
5995fn move_command<E: Environment>(
5996	library: &mut Library,
5997	((entity, to, without_history, confirmed), (keep_behind, leave_secrets)): (
5998		(&str, &str, bool, bool),
5999		(bool, bool),
6000	),
6001	json: bool,
6002	environment: &mut E,
6003	timings: &mut Timings,
6004	output: &mut dyn Write,
6005) -> Result<(), CliError> {
6006	let (from, found) = library.locate(entity)?;
6007	let to = library.find_space(to)?;
6008	let preview = library.move_preview(from, found, to)?;
6009	let name = |space: nibkeep_base::SpaceId| -> Result<String, CliError> {
6010		Ok(library
6011			.space_name(space)?
6012			.unwrap_or_else(|| space.to_string()))
6013	};
6014	let (from_name, to_name) = (name(from)?, name(to)?);
6015	// What moves along, or out of a folder or a list that stays, is listed first, and who
6016	// stops seeing it, or sees it for the first time.
6017	let others = !preview.losing.is_empty() || !preview.gaining.is_empty();
6018	if (preview.entities.len() > 1 || !preview.staying.is_empty() || others) && !confirmed {
6019		let name_of = |entity| library.name(from, entity).ok().flatten();
6020		output::move_preview(&preview, (&from_name, &to_name), &name_of, json, output)?;
6021		return Err(CliError::UnconfirmedMove);
6022	}
6023	let history = if without_history {
6024		MoveHistory::Leave
6025	} else {
6026		MoveHistory::Bring
6027	};
6028	let behind = if keep_behind {
6029		nibkeep_node::Behind::Keep
6030	} else {
6031		nibkeep_node::Behind::Purge
6032	};
6033	let secrets = if leave_secrets {
6034		MoveSecrets::Leave
6035	} else {
6036		MoveSecrets::Bring
6037	};
6038	// Secret values move with the secrets unlocked; held elsewhere, the move says so.
6039	if preview.secrets && !leave_secrets && library.secrets_protection()?.is_some() {
6040		unlock_secrets(library, false, environment, timings)?;
6041	}
6042	let now = environment.now();
6043	let moved = library.move_entity(
6044		from,
6045		found,
6046		to,
6047		history,
6048		behind,
6049		secrets,
6050		now,
6051		environment.rng(),
6052	);
6053	library.lock_secrets();
6054	let moved = moved?;
6055	output::moved(moved, preview.entities.len(), &to_name, json, output)?;
6056	output::seen_first(
6057		&preview.gaining,
6058		history == MoveHistory::Bring,
6059		json,
6060		output,
6061	)?;
6062	if behind == nibkeep_node::Behind::Purge {
6063		output::purged_later(&preview, &from_name, json, output)?;
6064	}
6065	Ok(())
6066}
6067
6068/// Runs `nib purge`: of a value, or with no value, as with --behind, of what a move left
6069/// behind.
6070fn purge_either<E: Environment>(
6071	library: &mut Library,
6072	(entity, value, confirmed): (&str, Option<&str>, bool),
6073	json: bool,
6074	environment: &mut E,
6075	timings: &mut Timings,
6076	output: &mut dyn Write,
6077) -> Result<(), CliError> {
6078	match value {
6079		Some(value) => purge_command(
6080			library,
6081			(entity, value, confirmed),
6082			json,
6083			environment,
6084			timings,
6085			output,
6086		),
6087		None => purge_behind_command(
6088			library,
6089			(entity, confirmed),
6090			json,
6091			environment,
6092			timings,
6093			output,
6094		),
6095	}
6096}
6097
6098/// Runs `nib purge --behind`: purges what a move left behind of an entity, as its mover
6099/// asked, once `confirmed`, and otherwise says what it would do. Where secret values may
6100/// have moved, and the secrets are on this device, it unlocks them first, as only then does
6101/// it see which secret values moved.
6102fn purge_behind_command<E: Environment>(
6103	library: &mut Library,
6104	(entity, confirmed): (&str, bool),
6105	json: bool,
6106	environment: &mut E,
6107	timings: &mut Timings,
6108	output: &mut dyn Write,
6109) -> Result<(), CliError> {
6110	// The entity that a move left in its space, which keeps it there with its marks, and
6111	// whose move asked for a purge.
6112	let mut asked = None;
6113	for space in library.spaces() {
6114		if let Ok(found) = library.find_entity_or_deleted(space, entity)
6115			&& library.behind(space, found)?.is_some()
6116		{
6117			asked = Some((space, found));
6118			break;
6119		}
6120	}
6121	let Some((space, found)) = asked else {
6122		return Err(NodeError::NoPurgeAsked(entity.to_owned()).into());
6123	};
6124	// What moved shows whether secret values may have, after the rest was purged too.
6125	let mut secret = library.may_hold_secrets(space, found)?;
6126	if let Some((there, now)) = library.moved_into(space, found)? {
6127		secret |= library.may_hold_secrets(there, now)?;
6128	}
6129	if secret && library.secrets_protection()?.is_some() {
6130		unlock_secrets(library, false, environment, timings)?;
6131	}
6132	let purged = purge_behind_found(
6133		library,
6134		(space, found, confirmed),
6135		json,
6136		environment,
6137		output,
6138	);
6139	library.lock_secrets();
6140	purged
6141}
6142
6143/// Runs `nib purge --behind` on the entity found, once the secrets are unlocked where they
6144/// may be needed.
6145fn purge_behind_found<E: Environment>(
6146	library: &mut Library,
6147	(space, found, confirmed): (nibkeep_base::SpaceId, nibkeep_base::EntityId, bool),
6148	json: bool,
6149	environment: &mut E,
6150	output: &mut dyn Write,
6151) -> Result<(), CliError> {
6152	let remaining = library.behind(space, found)?.unwrap_or_default();
6153	if !confirmed && remaining > 0 {
6154		output::purge_behind(remaining, false, json, output)?;
6155		return Err(CliError::Unconfirmed);
6156	}
6157	let now = environment.now();
6158	let purged = library.purge_behind(space, found, now, environment.rng())?;
6159	output::purge_behind(purged, true, json, output)
6160}
6161
6162/// The names of spaces, or their IDs where they have none.
6163fn space_names(library: &Library, spaces: &[nibkeep_base::SpaceId]) -> Vec<String> {
6164	spaces
6165		.iter()
6166		.map(|&space| {
6167			library
6168				.space_name(space)
6169				.ok()
6170				.flatten()
6171				.unwrap_or_else(|| space.to_string())
6172		})
6173		.collect()
6174}
6175
6176/// The names of spaces, as [`space_names`] gives them, sorted.
6177fn sorted_space_names(library: &Library, spaces: &[nibkeep_base::SpaceId]) -> Vec<String> {
6178	let mut names = space_names(library, spaces);
6179	names.sort();
6180	names
6181}
6182
6183/// Purges values of an entity of the personal space, or with `confirmed` false, says what
6184/// purging them would take away.
6185fn purge_values<E: Environment>(
6186	library: &mut Library,
6187	(entity, field, value): (
6188		nibkeep_base::EntityId,
6189		&FieldName,
6190		Option<&nibkeep_model::Value>,
6191	),
6192	confirmed: bool,
6193	environment: &mut E,
6194) -> Result<nibkeep_node::Purge, NodeError> {
6195	let space = library.default_space();
6196	if confirmed {
6197		let now = environment.now();
6198		library.purge(space, entity, field, value, now, environment.rng())
6199	} else {
6200		library.purgeable(space, entity, field, value)
6201	}
6202}
6203
6204/// Runs `nib import` of a Takeout archive of Google Photos: imports it into the personal
6205/// space, from the source `from`, or Google Photos, making thumbnails as it goes, and says
6206/// what it did.
6207fn takeout_command<E: Environment>(
6208	library: &mut Library,
6209	(parts, from): (&[PathBuf], Option<&str>),
6210	json: bool,
6211	environment: &mut E,
6212	output: &mut dyn Write,
6213) -> Result<(), CliError> {
6214	let space = library.default_space();
6215	let takeout = nibkeep_import::Takeout::open(parts).map_err(import_error)?;
6216	let started = environment.now();
6217	let began = std::time::Instant::now();
6218	let now = move || started + u64::try_from(began.elapsed().as_millis()).unwrap_or(0);
6219	library.install_policies(
6220		space,
6221		environment.downloads().as_deref(),
6222		now(),
6223		environment.rng(),
6224	)?;
6225	let mut found = output::FilesAdded::default();
6226	let mut pictures = Vec::new();
6227	let mut thumbnails_rng = UnwrapErr(SysRng);
6228	let source = from.unwrap_or(nibkeep_import::GOOGLE_PHOTOS);
6229	let report = takeout
6230		.import(
6231			library,
6232			(space, source),
6233			&now,
6234			environment.rng(),
6235			&mut |library, imported| {
6236				if let Some(added) = &imported.added
6237					&& !added.known
6238				{
6239					pictures.push(added.content);
6240				}
6241				if pictures.len() >= THUMBNAIL_ROUND {
6242					thumbnails_of(
6243						library,
6244						(space, &mut pictures),
6245						&mut found,
6246						(now(), &mut thumbnails_rng),
6247					);
6248				}
6249				Ok(())
6250			},
6251		)
6252		.map_err(import_error)?;
6253	thumbnails_of(
6254		library,
6255		(space, &mut pictures),
6256		&mut found,
6257		(now(), &mut thumbnails_rng),
6258	);
6259	output::takeout_imported((&report, source), &found, json, output)?;
6260	match report.failed.len() {
6261		0 => Ok(()),
6262		failed => Err(CliError::FilesFailed(failed)),
6263	}
6264}
6265
6266/// An importer's error, as `nib` reports it: the library's own as it is.
6267fn import_error(error: nibkeep_import::ImportError) -> CliError {
6268	match error {
6269		nibkeep_import::ImportError::Node(error) => error.into(),
6270		other => CliError::Import(other.to_string()),
6271	}
6272}
6273
6274/// The path of a file within the source it is added from: from the name of the folder or
6275/// file given that holds it on, its names joined by `/`.
6276fn path_in_source(given: &[PathBuf], file: &Path) -> Option<String> {
6277	let root = given.iter().find(|given| file.starts_with(given))?;
6278	let base = root.parent().unwrap_or(Path::new(""));
6279	let within = file.strip_prefix(base).ok()?;
6280	let names: Vec<String> = within
6281		.components()
6282		.filter_map(|part| match part {
6283			std::path::Component::Normal(name) => Some(name.to_string_lossy().into_owned()),
6284			_ => None,
6285		})
6286		.collect();
6287	(!names.is_empty()).then(|| names.join("/"))
6288}
6289
6290/// Runs `nib file add`, in the personal space: adds each file found, saying what came of
6291/// it as it goes, and then what came of all of them. A file that cannot be read fails
6292/// alone; an error of the library ends the command, after what came of the files before.
6293fn file_add_command<E: Environment>(
6294	library: &mut Library,
6295	(paths, own, from): (&[PathBuf], &Path, Option<&str>),
6296	json: bool,
6297	environment: &mut E,
6298	output: &mut dyn Write,
6299) -> Result<(), CliError> {
6300	let space = library.default_space();
6301	let source = match from {
6302		Some(name) => {
6303			let now = environment.now();
6304			Some(library.source_named(space, name, now, environment.rng())?)
6305		}
6306		None => None,
6307	};
6308	let mut found = output::FilesAdded::default();
6309	let mut files = Vec::new();
6310	// The library's folder as the file system resolves it, if it can.
6311	let own = std::fs::canonicalize(own).unwrap_or_else(|_| own.to_owned());
6312	for path in paths {
6313		gather(path, (true, &own), &mut files, &mut found);
6314	}
6315	if !json {
6316		for (path, reason) in &found.failed {
6317			output::file_failed(path, reason, output)?;
6318		}
6319	}
6320	let downloads = environment.downloads();
6321	let now = environment.now();
6322	library.install_policies(space, downloads.as_deref(), now, environment.rng())?;
6323	// The contents added since the last round of thumbnails.
6324	let mut pictures = Vec::new();
6325	for path in files {
6326		if pictures.len() >= THUMBNAIL_ROUND {
6327			thumbnail_round(library, (space, &mut pictures), &mut found, environment);
6328		}
6329		// With --json, nib runs for a program, which is not asked.
6330		if !json && let Ok(Some(question)) = library.question_for(space, &path) {
6331			let asked = environment.ask(&output::question(&path, &question))?;
6332			let answer = asked.and_then(|answer| match answer.to_lowercase().as_str() {
6333				"y" | "yes" => Some(true),
6334				"n" | "no" => Some(false),
6335				_ => None,
6336			});
6337			if let Some(again) = answer {
6338				let now = environment.now();
6339				library.answer(space, &question, again, now, environment.rng())?;
6340			}
6341		}
6342		let now = environment.now();
6343		let from = nibkeep_node::FileFrom {
6344			source,
6345			source_path: source.and_then(|_| path_in_source(paths, &path)),
6346			..nibkeep_node::FileFrom::default()
6347		};
6348		match library.add_file_from(space, &path, &from, now, environment.rng()) {
6349			Ok(added) => {
6350				if !json {
6351					let name_of = |entity| library.name(space, entity).ok().flatten();
6352					output::file_added(&path, &added, &name_of, output)?;
6353				}
6354				// Content new to the library; what it knew has its thumbnail, or no thumbnailer
6355				// read it, and nib file thumbnails makes those that files added before lack.
6356				if !added.known {
6357					pictures.push(added.content);
6358				}
6359				found.added.push((path, added));
6360			}
6361			Err(NodeError::Unreadable { reason, .. }) => {
6362				if !json {
6363					output::file_failed(&path, &reason, output)?;
6364				}
6365				found.failed.push((path, reason));
6366			}
6367			// In a folder, a checkout or a tree's file is left out, as hidden files are.
6368			Err(NodeError::CheckedOut(_) | NodeError::InTree(_)) if !paths.contains(&path) => {
6369				found.left_out += 1;
6370			}
6371			Err(error @ (NodeError::CheckedOut(_) | NodeError::InTree(_))) => {
6372				let reason = if matches!(error, NodeError::InTree(_)) {
6373					"in a tree; nib commit records it"
6374				} else {
6375					"a checkout; nib file checkin records its edits"
6376				};
6377				if !json {
6378					output::file_failed(&path, reason, output)?;
6379				}
6380				found.failed.push((path, reason.to_owned()));
6381			}
6382			Err(error) => {
6383				thumbnail_round(library, (space, &mut pictures), &mut found, environment);
6384				output::files_added(&found, json, output)?;
6385				return Err(error.into());
6386			}
6387		}
6388	}
6389	thumbnail_round(library, (space, &mut pictures), &mut found, environment);
6390	output::files_added(&found, json, output)?;
6391	match found.failed.len() {
6392		0 => Ok(()),
6393		failed => Err(CliError::FilesFailed(failed)),
6394	}
6395}
6396
6397/// Makes the thumbnails of a round of contents that `nib file add` added, and empties the
6398/// round. An add never fails because of its thumbnails: an error of the library while they
6399/// are recorded is kept to be said, and no more rounds are made.
6400fn thumbnail_round<E: Environment>(
6401	library: &mut Library,
6402	(space, pictures): (SpaceId, &mut Vec<nibkeep_base::Hash>),
6403	found: &mut output::FilesAdded,
6404	environment: &mut E,
6405) {
6406	let now = environment.now();
6407	thumbnails_of(library, (space, pictures), found, (now, environment.rng()));
6408}
6409
6410/// Makes the thumbnails of `pictures`, unless making them failed before, and empties it.
6411fn thumbnails_of(
6412	library: &mut Library,
6413	(space, pictures): (SpaceId, &mut Vec<nibkeep_base::Hash>),
6414	found: &mut output::FilesAdded,
6415	(now, rng): (u64, &mut impl getrandom::rand_core::CryptoRng),
6416) {
6417	if found.thumbnails_failed.is_none() && !pictures.is_empty() {
6418		match library.make_thumbnails(space, pictures, now, rng) {
6419			Ok(made) => found.thumbnails += made,
6420			Err(error) => found.thumbnails_failed = Some(error.to_string()),
6421		}
6422	}
6423	pictures.clear();
6424}
6425
6426/// Runs `nib file`, in the personal space of the library in `folder`.
6427fn file_command<E: Environment>(
6428	library: &mut Library,
6429	(command, folder): (&FileCommand, &Path),
6430	cli: &Cli,
6431	environment: &mut E,
6432	timings: &mut Timings,
6433	output: &mut dyn Write,
6434) -> Result<(), CliError> {
6435	let json = cli.json;
6436	match command {
6437		FileCommand::Add {
6438			paths,
6439			secret: true,
6440			to,
6441			..
6442		} => {
6443			let added =
6444				secret_file_add_command(library, (paths, to), json, environment, timings, output);
6445			library.lock_secrets();
6446			added
6447		}
6448		FileCommand::Add { paths, from, .. } => {
6449			let own = folder.join(LIBRARY_DATA);
6450			let added = (paths.as_slice(), &*own, from.as_deref());
6451			file_add_command(library, added, json, environment, output)
6452		}
6453		FileCommand::Checkout { file, path } => {
6454			let checkout = (file.as_str(), path.as_deref());
6455			file_checkout_command(library, checkout, cli, environment, output)
6456		}
6457		FileCommand::Pin { file, device } | FileCommand::Unpin { file, device } => {
6458			let pinned = matches!(command, FileCommand::Pin { .. });
6459			let (space, file) = library.locate(file)?;
6460			let (device, device_name) = if let Some(device) = device {
6461				one_device(library, device)?
6462			} else {
6463				let this = library.replicas()?.into_iter().find(|replica| replica.this);
6464				(
6465					this.as_ref()
6466						.and_then(|replica| replica.device)
6467						.ok_or_else(|| NodeError::WhichDevice("this device".to_owned()))?,
6468					this.and_then(|replica| replica.device_name),
6469				)
6470			};
6471			let now = environment.now();
6472			library.pin_file((space, file), device, pinned, now, environment.rng())?;
6473			let name = library.name(space, file)?;
6474			output::pinned(
6475				(file, name.as_deref()),
6476				(device, device_name.as_deref()),
6477				pinned,
6478				json,
6479				output,
6480			)
6481		}
6482		FileCommand::Checkin { copy, keep, force } => {
6483			let checkin = (copy.as_str(), *keep, *force);
6484			file_checkin_command(library, checkin, json, environment, output)
6485		}
6486		FileCommand::Where { file } => {
6487			let (space, file) = library.locate(file)?;
6488			let copies = library.copies_of(space, file, environment.now())?;
6489			let name = library.name(space, file)?;
6490			let zone = environment.time_zone();
6491			output::file_copies((&copies, name.as_deref()), &zone, json, output)
6492		}
6493		FileCommand::Thumbnail { file, path } => {
6494			let (space, file) = library.locate(file)?;
6495			let path = absolute(path, environment)?;
6496			let thumbnail = library
6497				.thumbnail(space, file)?
6498				.ok_or_else(|| CliError::NoThumbnail(file.to_string()))?;
6499			match library.save_thumbnail(space, &thumbnail, &path) {
6500				Err(NodeError::PlaceTaken(path)) => return Err(CliError::Exists(path)),
6501				saved => saved?,
6502			}
6503			output::thumbnail_written(&thumbnail, &path, json, output)
6504		}
6505		FileCommand::Thumbnails => {
6506			let space = library.default_space();
6507			let now = environment.now();
6508			// A long run says how far it got after each round.
6509			let mut progress = |made: nibkeep_node::ThumbnailsMade, of: usize| {
6510				let done = made.made + made.unreadable + made.not_here;
6511				if of > THUMBNAIL_ROUND && done < of {
6512					let _ = output::progress(&format!("{done} of {of} pictures…"), json, output);
6513				}
6514			};
6515			let made = library.make_missing_thumbnails(
6516				space,
6517				THUMBNAIL_ROUND,
6518				now,
6519				environment.rng(),
6520				&mut progress,
6521			)?;
6522			let left = library.missing_thumbnails(space)?.len();
6523			output::thumbnails_made(made, left, json, output)
6524		}
6525	}
6526}
6527
6528/// How many pictures go to the thumbnailer at a time as files are added: a round's
6529/// thumbnails are recorded once its pictures are added, so that an import cut short keeps
6530/// the thumbnails of what it added.
6531const THUMBNAIL_ROUND: usize = 64;
6532
6533/// What makes thumbnails in nib: decoders in memory-safe Rust for JPEG, PNG, GIF, WebP, BMP
6534/// and TIFF ([technical design](../../../docs/Technical-design.md#98-thumbnails)).
6535struct RustDecoders;
6536
6537impl nibkeep_node::Thumbnailer for RustDecoders {
6538	fn made_with(&self) -> &str {
6539		nibkeep_thumbnails::MADE_WITH
6540	}
6541
6542	fn reads(&self, media_type: &str) -> bool {
6543		nibkeep_thumbnails::reads(media_type)
6544	}
6545
6546	fn make(&self, picture: &[u8]) -> Option<nibkeep_node::Thumbnail> {
6547		let made = nibkeep_thumbnails::make(picture).ok()?;
6548		Some(nibkeep_node::Thumbnail {
6549			jpeg: made.jpeg,
6550			width: made.width,
6551			height: made.height,
6552			picture_hash: Some(made.picture_hash),
6553		})
6554	}
6555}
6556
6557/// Runs `nib file checkout`, in the personal space: into the folder or at the path given,
6558/// relative to the current folder, or else into the current folder.
6559fn file_checkout_command<E: Environment>(
6560	library: &mut Library,
6561	(file, place): (&str, Option<&Path>),
6562	cli: &Cli,
6563	environment: &mut E,
6564	output: &mut dyn Write,
6565) -> Result<(), CliError> {
6566	let json = cli.json;
6567	let (space, file) = library.locate(file)?;
6568	// The command works in the space that holds the entity.
6569	library.choose_space(Some(space))?;
6570	let place = match place {
6571		Some(place) => absolute(place, environment)?,
6572		None => current_dir(environment)?,
6573	};
6574	let now = environment.now();
6575	let checked_out = match library.checkout(space, file, &place, now, environment.rng()) {
6576		Err(NodeError::SecretFile(name)) => return Err(CliError::SecretFileCheckout(name)),
6577		// Not on this device: fetched from one that holds it, on the home network.
6578		Err(NodeError::NoCopyHere(name)) => {
6579			let (holders, reached) = fetch((space, file), library, cli, environment, output)?;
6580			let now = environment.now();
6581			match library.checkout(space, file, &place, now, environment.rng()) {
6582				Err(NodeError::NoCopyHere(_)) if !reached.is_empty() => {
6583					return Err(CliError::NotGiven {
6584						name,
6585						holders: reached,
6586					});
6587				}
6588				Err(NodeError::NoCopyHere(_)) if !holders.is_empty() => {
6589					return Err(CliError::NotFetched { name, holders });
6590				}
6591				checked_out => checked_out?,
6592			}
6593		}
6594		checked_out => checked_out?,
6595	};
6596	let name = library.name(space, checked_out.file)?;
6597	output::checked_out(&checked_out, name.as_deref(), json, output)
6598}
6599
6600/// How long `nib file checkout` looks on the network for a device that holds a file that
6601/// this device lacks.
6602const FETCH_WAIT: Duration = Duration::from_secs(10);
6603
6604/// Fetches the content of a file that this device lacks, which `nib file checkout` recorded
6605/// as opened, so that this device keeps it: syncs with the devices whose accounts hold it,
6606/// through the program that syncs this device, or itself. Returns the names of those
6607/// devices, none if no device holds it, and of those that a sync reached.
6608fn fetch<E: Environment>(
6609	(space, file): (nibkeep_base::SpaceId, EntityId),
6610	library: &mut Library,
6611	cli: &Cli,
6612	environment: &mut E,
6613	output: &mut dyn Write,
6614) -> Result<(Vec<String>, Vec<String>), CliError> {
6615	let holders = library.holders_of(space, file)?;
6616	let name_of = |replica: &nibkeep_node::Replica| {
6617		let app = replica.name.clone().unwrap_or_else(|| "nib".to_owned());
6618		match &replica.device_name {
6619			Some(device) => format!("{app} on {device}"),
6620			None => app,
6621		}
6622	};
6623	let names: Vec<String> = holders.iter().map(name_of).collect();
6624	if holders.is_empty() {
6625		return Ok((names, Vec::new()));
6626	}
6627	output::progress(
6628		&format!("Fetching it from {}…", names.join(", ")),
6629		cli.json,
6630		output,
6631	)?;
6632	let waited = Instant::now();
6633	let _role = loop {
6634		if let Some(role) = library.take_role()? {
6635			break role;
6636		}
6637		let records = library.sync_records(UnwrapErr(SysRng))?;
6638		if let Some(holder) = records.holder()? {
6639			let asked = environment.now();
6640			let asks = holders
6641				.iter()
6642				.map(|replica| records.ask(Some(replica.id), asked))
6643				.collect::<Result<Vec<_>, _>>()?;
6644			let mut released = false;
6645			while !released
6646				&& asks
6647					.iter()
6648					.any(|ask| matches!(records.answered(*ask), Ok(None)))
6649			{
6650				if library.take_role()?.is_some() {
6651					released = true;
6652				} else if waited.elapsed() > FETCH_WAIT + ASK_WAIT {
6653					return Err(CliError::NotAnswered(holder.program));
6654				} else {
6655					std::thread::sleep(Duration::from_millis(100));
6656				}
6657			}
6658			if !released {
6659				library.catch_up()?;
6660				let synced = records.synced_since(asked)?;
6661				let reached = holders
6662					.iter()
6663					.filter(|replica| synced.contains_key(&replica.id))
6664					.map(name_of)
6665					.collect();
6666				return Ok((names, reached));
6667			}
6668			continue;
6669		}
6670		if waited.elapsed() > FETCH_WAIT + ASK_WAIT {
6671			return Err(CliError::NotAnswered("another program".to_owned()));
6672		}
6673		std::thread::sleep(Duration::from_millis(100));
6674	};
6675	let network = library.network(cli.network(false))?;
6676	let endpoints = holders
6677		.iter()
6678		.filter_map(|replica| replica.endpoint)
6679		.collect();
6680	let found = network.find(&endpoints, FETCH_WAIT);
6681	let now = clock(environment);
6682	// A sync that fails leaves the file not here, which the checkout then says.
6683	let synced =
6684		nibkeep_node::sync_with_found(library, &network, holders, &found, &now, environment.rng());
6685	let reached = synced
6686		.iter()
6687		.filter(|with| with.synced.is_ok())
6688		.map(|with| name_of(&with.replica))
6689		.collect();
6690	Ok((names, reached))
6691}
6692
6693/// The one device of the person's that `device` names, by its name or ID, or by one copy of
6694/// the library on it, with its name.
6695fn one_device(library: &Library, device: &str) -> Result<(EntityId, Option<String>), CliError> {
6696	let replicas = library.replicas_named(device)?;
6697	let devices: std::collections::BTreeSet<EntityId> = replicas
6698		.iter()
6699		.filter_map(|replica| replica.device)
6700		.collect();
6701	let mut found = devices.into_iter();
6702	let (Some(chosen), None) = (found.next(), found.next()) else {
6703		return Err(NodeError::WhichDevice(format!(
6704			"{device} names no one device of yours; nib device list shows them"
6705		))
6706		.into());
6707	};
6708	let name = replicas
6709		.iter()
6710		.find(|replica| replica.device == Some(chosen))
6711		.and_then(|replica| replica.device_name.clone());
6712	Ok((chosen, name))
6713}
6714
6715/// The records of the replicas of the person's other devices that `devices` name, by name
6716/// or ID, as `--on` and nib space allow name them: those not revoked, of no AI agent's.
6717fn devices_named(library: &Library, devices: &[String]) -> Result<Vec<EntityId>, CliError> {
6718	let mut records = Vec::new();
6719	for device in devices {
6720		let named: Vec<EntityId> = library
6721			.replicas_named(device)?
6722			.into_iter()
6723			.filter(|replica| !replica.revoked && !replica.ai_agent && !replica.this)
6724			.map(|replica| replica.id)
6725			.collect();
6726		if named.is_empty() {
6727			return Err(NodeError::WhichDevice(format!(
6728				"{device} names no other device of yours; nib device list shows them"
6729			))
6730			.into());
6731		}
6732		records.extend(named);
6733	}
6734	Ok(records)
6735}
6736
6737/// How many bytes of files an everyday device keeps, as `--keeps` gives it: `None` for the
6738/// default.
6739#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6740pub struct Keeps(Option<u64>);
6741
6742/// How many days an archive node waits before purging, as `--waits` gives it: `None` for the
6743/// default, `Some(0)` for none.
6744#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6745pub struct Waits(Option<u64>);
6746
6747/// A wait of `--waits`: days from 1 to 365, such as `30` or `30d`, `none`, or `default`.
6748fn parse_waits(text: &str) -> Result<Waits, String> {
6749	let text = text.trim().to_ascii_lowercase();
6750	match text.as_str() {
6751		"default" => return Ok(Waits(None)),
6752		"none" | "0" => return Ok(Waits(Some(0))),
6753		_ => {}
6754	}
6755	let digits = text
6756		.strip_suffix("days")
6757		.or_else(|| text.strip_suffix("day"))
6758		.or_else(|| text.strip_suffix('d'))
6759		.unwrap_or(&text)
6760		.trim();
6761	match digits.parse::<u64>() {
6762		Ok(days @ 1..=nibkeep_node::MOST_WAIT_DAYS) => Ok(Waits(Some(days))),
6763		_ => Err("days from 1 to 365, such as 30, or none, or default".to_owned()),
6764	}
6765}
6766
6767/// A size of `--keeps`: a size, such as `20GB`, or `default`.
6768fn parse_keeps(text: &str) -> Result<Keeps, String> {
6769	if text.trim().eq_ignore_ascii_case("default") {
6770		return Ok(Keeps(None));
6771	}
6772	parse_size(text).map(|size| Keeps(Some(size)))
6773}
6774
6775/// Runs `nib file add --secret`, in the personal space: unlocks the secrets, or sets them up
6776/// for the library's first secret, and adds each file as a secret file, attached to the
6777/// entities `to`. The secrets are locked again by the caller.
6778fn secret_file_add_command<E: Environment>(
6779	library: &mut Library,
6780	(paths, to): (&[PathBuf], &[String]),
6781	json: bool,
6782	environment: &mut E,
6783	timings: &mut Timings,
6784	output: &mut dyn Write,
6785) -> Result<(), CliError> {
6786	let space = library.default_space();
6787	let mut attached_to = Vec::with_capacity(to.len());
6788	for entity in to {
6789		attached_to.push(library.find_entity(space, entity)?);
6790	}
6791	// Each a file, before the passphrase is asked for.
6792	let mut files = Vec::with_capacity(paths.len());
6793	for path in paths {
6794		let path = absolute(path, environment)?;
6795		if path.is_dir() {
6796			return Err(CliError::SecretFolder(path));
6797		}
6798		files.push(path);
6799	}
6800	unlock_secrets(library, true, environment, timings)?;
6801	let mut added = Vec::with_capacity(files.len());
6802	let mut failed = Vec::new();
6803	for path in files {
6804		// A file that cannot be read is reported, and the others are added all the same.
6805		let file = match std::fs::File::open(&path) {
6806			Ok(file) => file,
6807			Err(error) => {
6808				if !json {
6809					output::file_failed(&path, &error.to_string(), output)?;
6810				}
6811				failed.push((path, error.to_string()));
6812				continue;
6813			}
6814		};
6815		let name = path
6816			.file_name()
6817			.map_or_default(|name| name.to_string_lossy().into_owned());
6818		let now = environment.now();
6819		let secret_file =
6820			match library.add_secret_file(space, &name, file, &attached_to, now, environment.rng())
6821			{
6822				Ok(secret_file) => secret_file,
6823				Err(NodeError::Unreadable { reason, .. }) => {
6824					if !json {
6825						output::file_failed(&path, &reason, output)?;
6826					}
6827					failed.push((path, reason));
6828					continue;
6829				}
6830				Err(error) => return Err(error.into()),
6831			};
6832		if !json {
6833			let name_of = |entity| library.name(space, entity).ok().flatten();
6834			output::secret_file_added(&path, &secret_file, (&attached_to, &name_of), output)?;
6835		}
6836		added.push((path, name, secret_file));
6837	}
6838	output::secret_files_added((&added, &failed), &attached_to, json, output)?;
6839	match failed.len() {
6840		0 => Ok(()),
6841		failed => Err(CliError::FilesFailed(failed)),
6842	}
6843}
6844
6845/// Runs `nib file checkin`, in the personal space: records the edits of the copy, and,
6846/// unless `keep`, ends the checkout.
6847fn file_checkin_command<E: Environment>(
6848	library: &mut Library,
6849	(copy, keep, force): (&str, bool, bool),
6850	json: bool,
6851	environment: &mut E,
6852	output: &mut dyn Write,
6853) -> Result<(), CliError> {
6854	// The checkout's space: the one chosen, or else whichever has it.
6855	if library.chosen_space().is_none() {
6856		for space in library.spaces() {
6857			library.choose_space(Some(space))?;
6858			if find_checkout(library, copy, environment).is_ok() {
6859				break;
6860			}
6861			library.choose_space(None)?;
6862		}
6863	}
6864	let space = library.default_space();
6865	let checkout = find_checkout(library, copy, environment)?;
6866	let now = environment.now();
6867	let recorded = match library.record_edits(space, checkout.id, force, now, environment.rng()) {
6868		Err(NodeError::Stale(path)) => return Err(CliError::Stale(path)),
6869		recorded => recorded?,
6870	};
6871	let ended = if keep {
6872		None
6873	} else {
6874		let now = environment.now();
6875		Some(library.end_checkout(space, checkout.id, now, environment.rng())?)
6876	};
6877	// A new version of a picture gets its own thumbnail; a check-in never fails because of
6878	// it, and says why it has none.
6879	let mut thumbnail_failed = None;
6880	if let Some(version) = recorded.version {
6881		let now = environment.now();
6882		if let Err(error) = library.make_thumbnails(space, &[version], now, environment.rng()) {
6883			thumbnail_failed = Some(error.to_string());
6884		}
6885	}
6886	let name = library.name(space, checkout.file)?;
6887	let checked_in = output::CheckedIn {
6888		checkout: &checkout,
6889		recorded,
6890		ended: ended.as_ref(),
6891		name: name.as_deref(),
6892		thumbnail_failed: thumbnail_failed.as_deref(),
6893	};
6894	output::checked_in(&checked_in, json, output)
6895}
6896
6897/// The checkout on this device of the personal space that `copy` names: the path of its
6898/// copy, relative to the current folder, or else the file, if it is checked out in one
6899/// place.
6900fn find_checkout<E: Environment>(
6901	library: &Library,
6902	copy: &str,
6903	environment: &E,
6904) -> Result<Checkout, CliError> {
6905	let space = library.default_space();
6906	let path = absolute(Path::new(copy), environment)?;
6907	if let Some(checkout) = library.checkout_at(space, &path)? {
6908		return Ok(checkout);
6909	}
6910	let file = match library.find_entity(space, copy) {
6911		Ok(file) => file,
6912		Err(NodeError::NoEntity(_)) => return Err(NodeError::NotCheckedOut(copy.to_owned()).into()),
6913		Err(error) => return Err(error.into()),
6914	};
6915	let mut checkouts = library.checkouts_of(space, file)?;
6916	match checkouts.len() {
6917		0 => Err(NodeError::NotCheckedOut(copy.to_owned()).into()),
6918		1 => Ok(checkouts.remove(0)),
6919		_ => Err(NodeError::WhichCheckout {
6920			file: copy.to_owned(),
6921			paths: checkouts
6922				.into_iter()
6923				.map(|checkout| checkout.path)
6924				.collect(),
6925		}
6926		.into()),
6927	}
6928}
6929
6930/// Runs `nib backup edit`: changes a backup, and says how it is now.
6931fn backup_edit<E: Environment>(
6932	library: &mut Library,
6933	command: &BackupCommand,
6934	environment: &mut E,
6935	json: bool,
6936	output: &mut dyn Write,
6937) -> Result<(), CliError> {
6938	let BackupCommand::Edit {
6939		backup,
6940		name,
6941		spaces,
6942		policies,
6943		every_policy,
6944		away,
6945		home,
6946		waits,
6947	} = command
6948	else {
6949		unreachable!("backup_command passes only an edit");
6950	};
6951
6952	let known = library.find_backup(backup)?;
6953	let spaces = (!spaces.is_empty())
6954		.then(|| {
6955			spaces
6956				.iter()
6957				.map(|space| library.find_space(space))
6958				.collect::<Result<Vec<_>, _>>()
6959		})
6960		.transpose()?;
6961	let of = spaces.clone().unwrap_or_else(|| known.spaces.clone());
6962	let policies = if *every_policy {
6963		Some(Vec::new())
6964	} else if policies.is_empty() {
6965		None
6966	} else {
6967		Some(backup_policies(library, &of, policies, environment)?)
6968	};
6969	let edit = BackupEdit {
6970		name: name.clone(),
6971		spaces,
6972		policies,
6973		away: (*away || *home).then_some(*away),
6974		waits: waits.map(|Waits(days)| days),
6975	};
6976	let now = environment.now();
6977	library.edit_backup(known.id, &edit, now, environment.rng())?;
6978	let edited = library.find_backup(&known.id.to_string())?;
6979	output::backup_edited(&edited, json, output)
6980}
6981
6982/// Runs `nib backup` and `nib recovery`, which keep a library safe from the loss of its
6983/// devices.
6984fn safekeeping_command<E: Environment>(
6985	library: &mut Library,
6986	cli: &Cli,
6987	environment: &mut E,
6988	timings: &mut Timings,
6989	output: &mut dyn Write,
6990) -> Result<(), CliError> {
6991	match &cli.command {
6992		Command::Backup { command } => backup_command(library, command, cli, environment, output),
6993		Command::Recovery { command } => {
6994			recovery_command(library, command, cli.json, environment, timings, output)
6995		}
6996		_ => unreachable!("only nib backup and nib recovery come here"),
6997	}
6998}
6999
7000/// How many times a person may type a recovery code before a command gives up.
7001const CODE_TRIES: usize = 3;
7002
7003/// Reads a recovery code that the person types, as a passphrase is read, and says which
7004/// group to look at when it does not check.
7005fn typed_recovery_code<E: Environment>(
7006	prompt: &str,
7007	environment: &mut E,
7008	json: bool,
7009	output: &mut dyn Write,
7010) -> Result<RecoveryCode, CliError> {
7011	for _ in 0..CODE_TRIES {
7012		let typed = environment.passphrase(prompt)?;
7013		match RecoveryCode::from_text(&typed) {
7014			Ok(code) => return Ok(code),
7015			Err(error) if !json => writeln!(output, "{error}.")?,
7016			Err(_) => {}
7017		}
7018	}
7019	Err(CliError::NotARecoveryCode)
7020}
7021
7022/// Runs `nib recovery new`: makes a code and shows it, which counts once typed back.
7023fn recovery_new_command<E: Environment>(
7024	library: &mut Library,
7025	(secrets, revoke_older): (bool, bool),
7026	json: bool,
7027	environment: &mut E,
7028	output: &mut dyn Write,
7029) -> Result<(), CliError> {
7030	let code = RecoveryCode::generate(environment.rng());
7031	output::recovery_shown(&code, json, output)?;
7032	// With --json, a program asked: the person confirms the code another time.
7033	let mut stands = None;
7034	for _ in 0..if json { 0 } else { CODE_TRIES } {
7035		// Nobody to answer, as when the output goes to a file: the code is shown, and
7036		// counts once it is confirmed.
7037		let prompt = "Type the code back, or press Enter to do it later: ";
7038		let Ok(typed) = environment.passphrase(prompt) else {
7039			break;
7040		};
7041		if typed.trim().is_empty() {
7042			break;
7043		}
7044		match RecoveryCode::from_text(&typed) {
7045			Ok(typed) if typed.same_as(&code) => {
7046				let now = environment.now();
7047				stands = Some(library.add_recovery_code(&code, secrets, now, environment.rng())?);
7048				break;
7049			}
7050			Ok(_) => writeln!(output, "That is another code than the one shown.")?,
7051			Err(error) => writeln!(output, "{error}.")?,
7052		}
7053	}
7054	// The codes that it replaces: revoked once every backup carries it, or at once.
7055	let replaced = if stands.is_some() {
7056		let now = environment.now();
7057		library.revoke_replaced_recovery_codes(revoke_older, now, environment.rng())?
7058	} else {
7059		Vec::new()
7060	};
7061	let codes = library.recovery_codes()?;
7062	output::recovery_made(&code, stands.as_ref(), (&replaced, &codes), json, output)
7063}
7064
7065/// Runs `nib recovery`.
7066fn recovery_command<E: Environment>(
7067	library: &mut Library,
7068	command: &RecoveryCommand,
7069	json: bool,
7070	environment: &mut E,
7071	timings: &mut Timings,
7072	output: &mut dyn Write,
7073) -> Result<(), CliError> {
7074	const TYPE_IT: &str = "The recovery code: ";
7075	// The secrets are unlocked first, so that a wrong passphrase stops before a code is shown.
7076	if let RecoveryCommand::New { secrets: true, .. }
7077	| RecoveryCommand::Confirm { secrets: true, .. }
7078	| RecoveryCommand::Check { secrets: true } = command
7079	{
7080		unlock_secrets(library, false, environment, timings)?;
7081	}
7082	match command {
7083		RecoveryCommand::New {
7084			secrets,
7085			revoke_older,
7086		} => {
7087			let new = (*secrets, *revoke_older);
7088			recovery_new_command(library, new, json, environment, output)
7089		}
7090		RecoveryCommand::Confirm {
7091			secrets,
7092			revoke_older,
7093		} => {
7094			let code = typed_recovery_code(TYPE_IT, environment, json, output)?;
7095			let standing = library
7096				.check_recovery_code(&code)?
7097				.code
7098				.filter(|named| !named.revoked);
7099			let already = standing.is_some();
7100			let named = match standing {
7101				Some(named) if !*secrets || named.holds_secrets => named,
7102				_ => {
7103					let now = environment.now();
7104					library.add_recovery_code(&code, *secrets, now, environment.rng())?
7105				}
7106			};
7107			// At once only for the newest code, which replaces the others: an older one typed
7108			// back with --revoke-older stays, as revoking it is not what was asked.
7109			let at_once = *revoke_older && named.replaced_by.is_none();
7110			let now = environment.now();
7111			let replaced =
7112				library.revoke_replaced_recovery_codes(at_once, now, environment.rng())?;
7113			let codes = library.recovery_codes()?;
7114			output::recovery_confirmed(&named, already, (&replaced, &codes), json, output)
7115		}
7116		RecoveryCommand::List => {
7117			let zone = environment.time_zone();
7118			output::recovery_list(&library.recovery_codes()?, &zone, json, output)
7119		}
7120		RecoveryCommand::Check { .. } => {
7121			let code = typed_recovery_code(TYPE_IT, environment, json, output)?;
7122			let check = library.check_recovery_code(&code)?;
7123			output::recovery_checked(&check, json, output)?;
7124			if check.code.is_some() {
7125				Ok(())
7126			} else {
7127				Err(CliError::UnknownRecoveryCode)
7128			}
7129		}
7130		RecoveryCommand::Revoke { code, yes } => {
7131			let mut named = library.find_recovery_code(code)?;
7132			if *yes {
7133				let now = environment.now();
7134				named = library.revoke_recovery_code(code, now, environment.rng())?;
7135			}
7136			let zone = environment.time_zone();
7137			output::recovery_revoked(&named, &zone, json, output)?;
7138			if *yes {
7139				Ok(())
7140			} else {
7141				Err(CliError::UnconfirmedRevoke)
7142			}
7143		}
7144		RecoveryCommand::Restore { .. } | RecoveryCommand::FromCopy { .. } => {
7145			unreachable!("run_command makes the library")
7146		}
7147	}
7148}
7149
7150/// Runs `nib backup`.
7151fn backup_command<E: Environment>(
7152	library: &mut Library,
7153	command: &BackupCommand,
7154	cli: &Cli,
7155	environment: &mut E,
7156	output: &mut dyn Write,
7157) -> Result<(), CliError> {
7158	let json = cli.json;
7159	let records = library.sync_records(UnwrapErr(SysRng))?;
7160	let remembered: BTreeMap<EntityId, PathBuf> = records
7161		.backup_folders()?
7162		.into_iter()
7163		.map(|(backup, found)| (backup, found.folder))
7164		.collect();
7165	match command {
7166		BackupCommand::New {
7167			folder,
7168			name,
7169			spaces,
7170			policies,
7171			away,
7172			waits,
7173		} => {
7174			let spaces = spaces
7175				.iter()
7176				.map(|space| library.find_space(space))
7177				.collect::<Result<Vec<_>, _>>()?;
7178			let policies = backup_policies(library, &spaces, policies, environment)?;
7179			let name = name.clone().unwrap_or_else(|| {
7180				folder.file_name().map_or_else(
7181					|| "Backup".to_owned(),
7182					|name| name.to_string_lossy().into_owned(),
7183				)
7184			});
7185			let new = NewBackup {
7186				name,
7187				spaces,
7188				policies,
7189				away: *away,
7190				waits: waits.and_then(|Waits(days)| days),
7191			};
7192			backup_add(library, (folder, &new), &records, environment, json, output)
7193		}
7194		BackupCommand::List => backup_list(library, &remembered, environment, json, output),
7195		BackupCommand::Update { backup, at } => {
7196			let chosen = backups_to_update(library, backup.as_deref(), at.as_deref(), &remembered)?;
7197			let mut failed = None;
7198			for (backup, folder) in chosen {
7199				let folder = std::path::absolute(&folder).unwrap_or(folder);
7200				let now = || environment.now();
7201				let updated = library.update_backup(&backup, &folder, &now, &|| false);
7202				if let Ok(Some(_)) = &updated {
7203					let kept = library.changes_kept()?;
7204					records.record_backup(backup.id, &folder, Some((now(), kept)))?;
7205				}
7206				let shown = output::backup_updated(&backup, &folder, &updated, json, output);
7207				if let Err(error) = updated {
7208					failed.get_or_insert(error);
7209				}
7210				shown?;
7211			}
7212			failed.map_or(Ok(()), |error| Err(error.into()))
7213		}
7214		BackupCommand::Edit { .. } => backup_edit(library, command, environment, json, output),
7215		BackupCommand::Remove { backup } => {
7216			let known = library.find_backup(backup)?;
7217			let now = environment.now();
7218			library.remove_backup(known.id, now, environment.rng())?;
7219			let folder = remembered.get(&known.id);
7220			output::backup_removed(&known, folder.map(PathBuf::as_path), json, output)
7221		}
7222	}
7223}
7224
7225/// Makes a backup, updates it, and remembers where it is.
7226fn backup_add<E: Environment>(
7227	library: &mut Library,
7228	(folder, new): (&Path, &NewBackup),
7229	records: &nibkeep_node::Records,
7230	environment: &mut E,
7231	json: bool,
7232	output: &mut dyn Write,
7233) -> Result<(), CliError> {
7234	let now = environment.now();
7235	let added = library.add_backup(folder, new, now, environment.rng())?;
7236	let folder = std::path::absolute(folder).unwrap_or_else(|_| folder.to_owned());
7237	let now = || environment.now();
7238	let updated = library
7239		.update_backup(&added.backup, &folder, &now, &|| false)?
7240		.unwrap_or_default();
7241	records.record_backup(
7242		added.backup.id,
7243		&folder,
7244		Some((now(), library.changes_kept()?)),
7245	)?;
7246	output::backup_added(&added, &folder, &updated, json, output)
7247}
7248
7249/// Lists the person's backups, with what the folder of each that this computer finds says.
7250fn backup_list<E: Environment>(
7251	library: &Library,
7252	remembered: &BTreeMap<EntityId, PathBuf>,
7253	environment: &E,
7254	json: bool,
7255	output: &mut dyn Write,
7256) -> Result<(), CliError> {
7257	let found: BTreeMap<EntityId, PathBuf> = library
7258		.find_backups(remembered)?
7259		.into_iter()
7260		.map(|(backup, folder)| (backup.id, folder))
7261		.collect();
7262	let now = environment.now();
7263	let mut listed = Vec::new();
7264	for backup in library.backups()? {
7265		let state = found
7266			.get(&backup.id)
7267			.and_then(|folder| library.backup_state(&backup, folder, now).ok());
7268		let spaces = backup
7269			.spaces
7270			.iter()
7271			.map(|space| {
7272				library
7273					.space_name(*space)
7274					.ok()
7275					.flatten()
7276					.unwrap_or_else(|| space.to_string())
7277			})
7278			.collect();
7279		let policies = backup
7280			.policies
7281			.iter()
7282			.map(|policy| {
7283				backup
7284					.spaces
7285					.iter()
7286					.find_map(|space| library.name(*space, *policy).ok().flatten())
7287					.unwrap_or_else(|| policy.to_string())
7288			})
7289			.collect();
7290		let folder = found.get(&backup.id).cloned();
7291		listed.push(output::ListedBackup {
7292			backup,
7293			folder,
7294			state,
7295			spaces,
7296			policies,
7297		});
7298	}
7299	output::backups(&listed, json, output)
7300}
7301
7302/// The backups that `nib backup update` updates, with their folders: the one named, where
7303/// `at` says or where this computer finds it; the one whose folder `at` is; or each that
7304/// this computer finds.
7305fn backups_to_update(
7306	library: &Library,
7307	backup: Option<&str>,
7308	at: Option<&Path>,
7309	remembered: &BTreeMap<EntityId, PathBuf>,
7310) -> Result<Vec<(Backup, PathBuf)>, NodeError> {
7311	Ok(match (backup, at) {
7312		(Some(reference), Some(folder)) => {
7313			vec![(library.find_backup(reference)?, folder.to_owned())]
7314		}
7315		(None, Some(folder)) => {
7316			let named = library
7317				.backups()?
7318				.into_iter()
7319				.find(|known| nibkeep_node::backup_named_at(folder) == Some(known.id))
7320				.ok_or_else(|| {
7321					NodeError::WhichBackup(format!("{} is no backup of yours", folder.display()))
7322				})?;
7323			vec![(named, folder.to_owned())]
7324		}
7325		(Some(reference), None) => {
7326			let backup = library.find_backup(reference)?;
7327			let found = library
7328				.find_backups(remembered)?
7329				.into_iter()
7330				.find(|(known, _)| known.id == backup.id)
7331				.ok_or_else(|| {
7332					NodeError::WhichBackup(format!(
7333						"this computer does not find the backup {}; plug it in, or say where it is with --at",
7334						backup.name
7335					))
7336				})?;
7337			vec![found]
7338		}
7339		(None, None) => library.find_backups(remembered)?,
7340	})
7341}
7342
7343/// The policies that `names` name in each of `spaces`, whose default policies are installed
7344/// first: each must name one in at least one of them.
7345fn backup_policies<E: Environment>(
7346	library: &mut Library,
7347	spaces: &[SpaceId],
7348	names: &[String],
7349	environment: &mut E,
7350) -> Result<Vec<EntityId>, CliError> {
7351	// No policy named installs none.
7352	if names.is_empty() {
7353		return Ok(Vec::new());
7354	}
7355	let spaces = if spaces.is_empty() {
7356		library.spaces()
7357	} else {
7358		spaces.to_vec()
7359	};
7360	let downloads = environment.downloads();
7361	for space in &spaces {
7362		let now = environment.now();
7363		library.install_policies(*space, downloads.as_deref(), now, environment.rng())?;
7364	}
7365	let mut found = Vec::new();
7366	for name in names {
7367		let policies: Vec<EntityId> = spaces
7368			.iter()
7369			.filter_map(|space| library.find_policy(*space, name).ok())
7370			.collect();
7371		if policies.is_empty() {
7372			return Err(NodeError::NoEntity(format!(
7373				"no policy of the backup's spaces is named {name}"
7374			))
7375			.into());
7376		}
7377		found.extend(policies);
7378	}
7379	found.sort();
7380	found.dedup();
7381	Ok(found)
7382}
7383
7384/// Runs `nib policy`, in the personal space, which gets the default policies first if it
7385/// never had them, and this device a rule for its downloads folder.
7386fn policy_command<E: Environment>(
7387	library: &mut Library,
7388	command: &PolicyCommand,
7389	json: bool,
7390	environment: &mut E,
7391	output: &mut dyn Write,
7392) -> Result<(), CliError> {
7393	let space = library.default_space();
7394	let downloads = environment.downloads();
7395	let now = environment.now();
7396	library.install_policies(space, downloads.as_deref(), now, environment.rng())?;
7397	match command {
7398		PolicyCommand::List => {
7399			let policies = library.policies(space)?;
7400			let rules = library.rules(space)?;
7401			let name_of = |entity| library.name(space, entity).ok().flatten();
7402			output::policies(&policies, &rules, &name_of, json, output)
7403		}
7404		PolicyCommand::Show { policy } => {
7405			let id = library.find_policy(space, policy)?;
7406			let policies = library.policies(space)?;
7407			let rules = library.rules(space)?;
7408			let name_of = |entity| library.name(space, entity).ok().flatten();
7409			output::policy(id, &policies, &rules, &name_of, json, output)
7410		}
7411		PolicyCommand::New {
7412			name,
7413			copies,
7414			away,
7415			archived,
7416			in_place,
7417		} => {
7418			let needs = Needs {
7419				copies: *copies,
7420				away: *away,
7421				archived: *archived,
7422				kept: if *in_place {
7423					Kept::InPlace
7424				} else {
7425					Kept::Store
7426				},
7427			};
7428			let id = library.add_policy(space, name, needs, now, environment.rng())?;
7429			policy_changed("Added", id, library, json, output)
7430		}
7431		PolicyCommand::Edit {
7432			policy,
7433			name,
7434			copies,
7435			away,
7436			archived,
7437			in_place,
7438			store,
7439		} => {
7440			let id = library.find_policy(space, policy)?;
7441			let kept = match (*in_place, *store) {
7442				(true, _) => Some(Kept::InPlace),
7443				(_, true) => Some(Kept::Store),
7444				_ => None,
7445			};
7446			let edit = PolicyEdit {
7447				name: name.clone(),
7448				copies: *copies,
7449				away: *away,
7450				archived: *archived,
7451				kept,
7452			};
7453			library.edit_policy(space, id, &edit, now, environment.rng())?;
7454			policy_changed("Changed", id, library, json, output)
7455		}
7456		PolicyCommand::Remove { policy } => {
7457			let id = library.find_policy(space, policy)?;
7458			let name = library
7459				.policies(space)?
7460				.into_iter()
7461				.find(|known| known.id == id)
7462				.and_then(|known| known.name);
7463			library.remove_policy(space, id, now, environment.rng())?;
7464			output::removed_policy(id, name.as_deref(), json, output)
7465		}
7466		PolicyCommand::Rule { command } => {
7467			rule_command(library, command, json, environment, output)
7468		}
7469		PolicyCommand::Set {
7470			entity,
7471			policy,
7472			clear: _,
7473		} => {
7474			let id = library.find_entity(space, entity)?;
7475			let policy = policy
7476				.as_deref()
7477				.map(|policy| library.find_policy(space, policy))
7478				.transpose()?;
7479			library.set_policy(space, id, policy, now, environment.rng())?;
7480			why(library, id, json, output)
7481		}
7482		PolicyCommand::Why { entity } => {
7483			let id = library.find_entity(space, entity)?;
7484			why(library, id, json, output)
7485		}
7486		PolicyCommand::Check => {
7487			let check = library.check_policies(space, environment.now())?;
7488			let name_of = |entity| library.name(space, entity).ok().flatten();
7489			let zone = environment.time_zone();
7490			output::policy_check(&check, (&name_of, &zone), json, output)
7491		}
7492	}
7493}
7494
7495/// Runs `nib policy rule`, in the personal space.
7496fn rule_command<E: Environment>(
7497	library: &mut Library,
7498	command: &RuleCommand,
7499	json: bool,
7500	environment: &mut E,
7501	output: &mut dyn Write,
7502) -> Result<(), CliError> {
7503	let space = library.default_space();
7504	let now = environment.now();
7505	match command {
7506		RuleCommand::New {
7507			policy,
7508			of_type,
7509			has,
7510			folder,
7511			media_type,
7512			larger_than,
7513			asks_above,
7514			place,
7515		} => {
7516			let types = library.types(space)?;
7517			let rule = NewRule {
7518				of_type: of_type
7519					.as_deref()
7520					.map(|name| types::type_named(name, &types))
7521					.transpose()?,
7522				has: has
7523					.as_deref()
7524					.map(|field| types::field_named(field, &types, &[FILE, PHOTO, VIDEO]))
7525					.transpose()?,
7526				folder: folder.clone(),
7527				media_type: media_type.clone(),
7528				larger_than: *larger_than,
7529				asks_above: *asks_above,
7530				..NewRule::new(library.find_policy(space, policy)?)
7531			};
7532			let place = place_of(library, place)?.unwrap_or(Place::BeforeTheRest);
7533			let id = library.add_rule(space, &rule, place, now, environment.rng())?;
7534			rule_changed("Added", id, library, json, output)
7535		}
7536		RuleCommand::Remove { rule } => {
7537			let id = rule_named(library, rule)?;
7538			library.remove_rule(space, id, now, environment.rng())?;
7539			output::removed_rule(id, json, output)
7540		}
7541		RuleCommand::Move { rule, place } => {
7542			let id = rule_named(library, rule)?;
7543			let place = place_of(library, place)?.ok_or(CliError::WhereTo)?;
7544			library.move_rule(space, id, place, now, environment.rng())?;
7545			rule_changed("Moved", id, library, json, output)
7546		}
7547	}
7548}
7549
7550/// Prints a rule that a command added or moved, as `nib policy list` shows it.
7551fn rule_changed(
7552	what: &str,
7553	id: EntityId,
7554	library: &Library,
7555	json: bool,
7556	output: &mut dyn Write,
7557) -> Result<(), CliError> {
7558	let space = library.default_space();
7559	let rules = library.rules(space)?;
7560	let policies = library.policies(space)?;
7561	let name_of = |entity| library.name(space, entity).ok().flatten();
7562	output::rule_changed(what, id, &rules, &policies, &name_of, json, output)
7563}
7564
7565/// Prints a policy that a command added or changed.
7566fn policy_changed(
7567	what: &str,
7568	id: EntityId,
7569	library: &Library,
7570	json: bool,
7571	output: &mut dyn Write,
7572) -> Result<(), CliError> {
7573	let policies = library.policies(library.default_space())?;
7574	match policies.iter().find(|policy| policy.id == id) {
7575		Some(policy) => output::policy_changed(what, policy, json, output),
7576		None => Ok(()),
7577	}
7578}
7579
7580/// The rule of the personal space that `text` names: its number in `nib policy list`, its
7581/// ID, or a prefix of its ID of at least six characters.
7582fn rule_named(library: &Library, text: &str) -> Result<EntityId, CliError> {
7583	let rules = library.rules(library.default_space())?;
7584	// A number in the list, or else a prefix of an ID, which may be all digits too.
7585	if let Some(rule) = text
7586		.parse::<usize>()
7587		.ok()
7588		.and_then(|number| number.checked_sub(1))
7589		.and_then(|index| rules.get(index))
7590	{
7591		return Ok(rule.id);
7592	}
7593	let lowered = text.to_lowercase();
7594	let found: Vec<EntityId> = rules
7595		.iter()
7596		.map(|rule| rule.id)
7597		.filter(|id| {
7598			let id = id.to_string();
7599			id == lowered || (lowered.len() >= 6 && id.starts_with(&lowered))
7600		})
7601		.collect();
7602	match found.as_slice() {
7603		[one] => Ok(*one),
7604		_ => Err(CliError::NoRule(text.to_owned())),
7605	}
7606}
7607
7608/// Where a rule goes, as the person said, if they did.
7609fn place_of(library: &Library, place: &PlaceArgs) -> Result<Option<Place>, CliError> {
7610	Ok(if place.first {
7611		Some(Place::First)
7612	} else if place.last {
7613		Some(Place::Last)
7614	} else if let Some(rule) = &place.before {
7615		Some(Place::Before(rule_named(library, rule)?))
7616	} else if let Some(rule) = &place.after {
7617		Some(Place::After(rule_named(library, rule)?))
7618	} else {
7619		None
7620	})
7621}
7622
7623/// Prints the policy chosen for an entity of the personal space, and what chose it.
7624fn why(
7625	library: &Library,
7626	entity: EntityId,
7627	json: bool,
7628	output: &mut dyn Write,
7629) -> Result<(), CliError> {
7630	let space = library.default_space();
7631	let choice = library.policy_of(space, entity)?;
7632	let policies = library.policies(space)?;
7633	let rules = library.rules(space)?;
7634	let name_of = |entity| library.name(space, entity).ok().flatten();
7635	output::why(&choice, &policies, &rules, &name_of, json, output)
7636}
7637
7638/// A size, such as `500MB`, `2 GiB` or `1073741824`: a whole number of bytes, or of a
7639/// decimal or binary unit.
7640fn parse_size(text: &str) -> Result<u64, String> {
7641	let text = text.trim();
7642	let digits = text
7643		.find(|c: char| !c.is_ascii_digit())
7644		.unwrap_or(text.len());
7645	let (number, unit) = text.split_at(digits);
7646	let number: u64 = number
7647		.parse()
7648		.map_err(|_| format!("{text} is not a size, such as 500MB or 2GiB"))?;
7649	let unit = unit.trim().to_lowercase();
7650	let size: u64 = match unit.as_str() {
7651		"" | "b" => 1,
7652		"kb" => 1_000,
7653		"mb" => 1_000_000,
7654		"gb" => 1_000_000_000,
7655		"tb" => 1_000_000_000_000,
7656		"kib" => 1 << 10,
7657		"mib" => 1 << 20,
7658		"gib" => 1 << 30,
7659		"tib" => 1 << 40,
7660		_ => {
7661			return Err(format!(
7662				"{unit} is not a unit of size: B, kB, MB, GB, TB, KiB, MiB, GiB or TiB"
7663			));
7664		}
7665	};
7666	number
7667		.checked_mul(size)
7668		.ok_or_else(|| format!("{text} is too large"))
7669}
7670
7671/// Gathers the files to add at `path`: the file, or the files in the folder and the
7672/// folders in it, in the order of their names. A path given is followed if it is a link,
7673/// and fails if it is neither a file nor a folder, or in the library's own folder, `own`;
7674/// in folders, links, hidden files and folders, and `own`, wherever a link puts it, are
7675/// left out, and counted.
7676fn gather(
7677	path: &Path,
7678	(given, own): (bool, &Path),
7679	files: &mut Vec<PathBuf>,
7680	found: &mut output::FilesAdded,
7681) {
7682	let mut fail = |reason: String| found.failed.push((path.to_owned(), reason));
7683	let metadata = if given {
7684		std::fs::metadata(path)
7685	} else {
7686		std::fs::symlink_metadata(path)
7687	};
7688	let metadata = match metadata {
7689		Ok(metadata) => metadata,
7690		Err(error) => return fail(error.to_string()),
7691	};
7692	let is_own = || std::fs::canonicalize(path).is_ok_and(|resolved| resolved.starts_with(own));
7693	if given && (metadata.is_file() || metadata.is_dir()) && is_own() {
7694		return fail("the library's own folder holds it".to_owned());
7695	}
7696	if metadata.is_file() {
7697		files.push(path.to_owned());
7698	} else if metadata.is_dir() {
7699		if !given && is_own() {
7700			found.left_out += 1;
7701			return;
7702		}
7703		let entries = match std::fs::read_dir(path) {
7704			Ok(entries) => entries,
7705			Err(error) => return fail(error.to_string()),
7706		};
7707		let mut inside = Vec::new();
7708		for entry in entries {
7709			match entry {
7710				Ok(entry) => inside.push(entry.path()),
7711				// The rest of the folder may be read all the same.
7712				Err(error) => fail(error.to_string()),
7713			}
7714		}
7715		inside.sort();
7716		for entry in inside {
7717			let hidden = entry
7718				.file_name()
7719				.is_some_and(|name| name.to_string_lossy().starts_with('.'));
7720			if hidden {
7721				found.left_out += 1;
7722			} else {
7723				gather(&entry, (false, own), files, found);
7724			}
7725		}
7726	} else if given {
7727		fail("neither a file nor a folder".to_owned());
7728	} else {
7729		// A link in a folder, or what is neither a file nor a folder.
7730		found.left_out += 1;
7731	}
7732}
7733
7734/// Runs `nib secret`, in the personal space, and forgets the secrets however it ends.
7735fn secret_command<E: Environment>(
7736	library: &mut Library,
7737	command: &SecretCommand,
7738	json: bool,
7739	environment: &mut E,
7740	timings: &mut Timings,
7741	output: &mut dyn Write,
7742) -> Result<(), CliError> {
7743	let (SecretCommand::Set { entity, field, .. }
7744	| SecretCommand::Show { entity, field }
7745	| SecretCommand::History { entity, field }
7746	| SecretCommand::Clear { entity, field }
7747	| SecretCommand::Purge { entity, field, .. }) = command
7748	else {
7749		return entityless_secret_command(library, command, json, environment, timings, output);
7750	};
7751	let (space, id) = library.locate_or_deleted(entity)?;
7752	// The command works in the space that holds the entity.
7753	library.choose_space(Some(space))?;
7754	let day = dating(environment, environment.now(), None).day;
7755	let view = library
7756		.entity(space, id, day)?
7757		.ok_or_else(|| NodeError::NoEntity(entity.clone()))?;
7758	let types = library.types(space)?;
7759	let field = types::field_named(field, &types, &view.types)?;
7760	if !is_secret(library, space, &field) {
7761		return Err(CliError::NotSecret(field));
7762	}
7763	// Before the passphrase is asked for, and the first secrets set up.
7764	let generated = generated_secret(command, &field, environment)?;
7765	let set = matches!(command, SecretCommand::Set { .. });
7766	unlock_secrets(library, set, environment, timings)?;
7767	let no_value = || CliError::NoSecretValue {
7768		entity: entity.clone(),
7769		field: field.clone(),
7770	};
7771	let done = match command {
7772		SecretCommand::Set { .. } => set_secret(
7773			library,
7774			(id, &field, &types),
7775			generated,
7776			environment,
7777			timings,
7778		),
7779		SecretCommand::Clear { .. } => edit_now(
7780			library,
7781			id,
7782			Edit::Set(field.clone(), Vec::new()),
7783			environment,
7784		),
7785		SecretCommand::Purge { yes, .. } => (|| {
7786			let asked = Instant::now();
7787			let text = environment.passphrase(&format!("The value of {field} to purge: "))?;
7788			add(&mut timings.waiting, asked.elapsed());
7789			if text.is_empty() {
7790				return Err(CliError::EmptyValue);
7791			}
7792			let value = types::value(&text, &field, &types, library, space)?;
7793			let purged = purge_values(library, (id, &field, Some(&value)), *yes, environment)?;
7794			let name_of = |entity| library.name(space, entity).ok().flatten();
7795			let elsewhere = space_names(library, &purged.elsewhere);
7796			output::purge(&purged, (&field, &name_of), &elsewhere, *yes, json, output)
7797		})(),
7798		SecretCommand::Show { .. } => (|| {
7799			let view = library
7800				.entity(space, id, day)?
7801				.ok_or_else(|| NodeError::NoEntity(entity.clone()))?;
7802			let values = view.values(&field);
7803			if values.is_empty() {
7804				return Err(no_value());
7805			}
7806			let name_of = |entity| library.name(space, entity).ok().flatten();
7807			output::secret_values(view.id, &field, values, &name_of, json, output)
7808		})(),
7809		SecretCommand::History { .. } => {
7810			let history = (entity.as_str(), Some(field.as_str()));
7811			history_command(library, history, json, environment, output).map_err(
7812				|error| match error {
7813					CliError::SecretHistory(_) => no_value(),
7814					other => other,
7815				},
7816			)
7817		}
7818		SecretCommand::Copy { .. }
7819		| SecretCommand::Generate { .. }
7820		| SecretCommand::Code { .. }
7821		| SecretCommand::Ask { .. }
7822		| SecretCommand::Give { .. }
7823		| SecretCommand::FromCopy
7824		| SecretCommand::Save { .. } => {
7825			unreachable!("answered above")
7826		}
7827	};
7828	library.lock_secrets();
7829	done?;
7830	match command {
7831		SecretCommand::Set { .. } | SecretCommand::Clear { .. } => {
7832			let day = dating(environment, environment.now(), None).day;
7833			show(library, space, id, When::on(day), json, output)
7834		}
7835		SecretCommand::Purge { yes: false, .. } => Err(CliError::Unconfirmed),
7836		_ => Ok(()),
7837	}
7838}
7839
7840/// Runs the `nib secret` commands that name no entity's field: `code`, which finds its field
7841/// itself, `ask` and `give`.
7842fn entityless_secret_command<E: Environment>(
7843	library: &mut Library,
7844	command: &SecretCommand,
7845	json: bool,
7846	environment: &mut E,
7847	timings: &mut Timings,
7848	output: &mut dyn Write,
7849) -> Result<(), CliError> {
7850	match command {
7851		SecretCommand::Code { entity, field } => {
7852			let code = (entity.as_str(), field.as_deref());
7853			code_command(library, code, json, environment, timings, output)
7854		}
7855		SecretCommand::Ask { from } => match shared_space(library) {
7856			Some(space) => {
7857				let asking = (space, from.as_str());
7858				ask_space_command(library, asking, json, environment, timings, output)
7859			}
7860			None => ask_command(library, from, json, environment, timings, output),
7861		},
7862		SecretCommand::Give { device } => match shared_space(library) {
7863			Some(space) => {
7864				let giving = (space, device.as_str());
7865				give_space_command(library, giving, json, environment, timings, output)
7866			}
7867			None => give_command(library, device, json, environment, timings, output),
7868		},
7869		SecretCommand::FromCopy => {
7870			from_copy_secrets_command(library, json, environment, timings, output)
7871		}
7872		SecretCommand::Save { file, path } => {
7873			let save = (file.as_str(), path.as_deref());
7874			let saved = secret_save_command(library, save, json, environment, timings, output);
7875			library.lock_secrets();
7876			saved
7877		}
7878		// One needs no library, and the other closes it before it waits; the rest name a
7879		// field.
7880		_ => unreachable!("run_command runs nib secret generate and copy"),
7881	}
7882}
7883
7884/// Runs `nib secret save`, in the personal space: unlocks the secrets and saves a plain copy
7885/// of a secret file into the folder or at the path given, relative to the current folder, or
7886/// else into the current folder. The secrets are locked again by the caller.
7887fn secret_save_command<E: Environment>(
7888	library: &mut Library,
7889	(file, place): (&str, Option<&Path>),
7890	json: bool,
7891	environment: &mut E,
7892	timings: &mut Timings,
7893	output: &mut dyn Write,
7894) -> Result<(), CliError> {
7895	let (space, file) = library.locate(file)?;
7896	// The command works in the space that holds the entity.
7897	library.choose_space(Some(space))?;
7898	let place = match place {
7899		Some(place) => absolute(place, environment)?,
7900		None => current_dir(environment)?,
7901	};
7902	unlock_secrets(library, false, environment, timings)?;
7903	let saved = library.save_secret_file(space, file, &place)?;
7904	let name = library.name(space, file)?;
7905	output::secret_saved((file, name.as_deref()), &saved, json, output)
7906}
7907
7908/// The space that `--space` chose, if it is shared with another member: in a space of the
7909/// user's own, the library's own secrets are asked for and given.
7910fn shared_space(library: &Library) -> Option<SpaceId> {
7911	library.chosen_space().filter(|&space| {
7912		space != library.personal_space()
7913			&& library
7914				.members(space)
7915				.is_ok_and(|members| members.iter().any(|member| !member.this_user))
7916	})
7917}
7918
7919/// The device of another member of a shared space that `name` names, by its device's name
7920/// or the start of its record's ID, of eight characters or more, among those that `wanted`
7921/// takes, with the member's name.
7922fn member_device(
7923	library: &Library,
7924	space: SpaceId,
7925	name: &str,
7926	wanted: impl Fn(&nibkeep_node::MemberReplica) -> bool,
7927) -> Result<(String, nibkeep_node::MemberReplica), CliError> {
7928	let mut found = Vec::new();
7929	for member in library.members(space)? {
7930		for replica in member.replicas {
7931			let id = replica.record.to_string();
7932			let named = replica.device.as_deref() == Some(name)
7933				|| id == name
7934				|| (name.len() >= 8 && id.starts_with(name));
7935			if named && !replica.this && !replica.revoked && wanted(&replica) {
7936				found.push((member.name.clone().unwrap_or_default(), replica));
7937			}
7938		}
7939	}
7940	match found.len() {
7941		1 => Ok(found.remove(0)),
7942		0 => Err(NodeError::WhichDevice(format!(
7943			"no other member's device in the space that is {name} can do that; nib space \
7944			 members shows them"
7945		))
7946		.into()),
7947		_ => Err(NodeError::WhichDevice(format!(
7948			"{name} names several devices in the space; give the ID of the one you mean, as \
7949			 nib space show --json shows it"
7950		))
7951		.into()),
7952	}
7953}
7954
7955/// Runs `nib secret ask` in a shared space: asks another member's device that holds the
7956/// space's secrets for them, once this device's secrets are unlocked.
7957fn ask_space_command<E: Environment>(
7958	library: &mut Library,
7959	(space, from): (SpaceId, &str),
7960	json: bool,
7961	environment: &mut E,
7962	timings: &mut Timings,
7963	output: &mut dyn Write,
7964) -> Result<(), CliError> {
7965	let (member, device) = member_device(library, space, from, |replica| replica.holds_secrets)?;
7966	if library.secrets_protection()?.is_none() {
7967		return Err(NodeError::SetUpSecretsFirst.into());
7968	}
7969	unlock_secrets(library, false, environment, timings)?;
7970	let now = environment.now();
7971	let asked = library.ask_for_space_secrets(space, device.record, now, environment.rng());
7972	library.lock_secrets();
7973	asked?;
7974	let name = library.space_name(space)?.unwrap_or_default();
7975	output::asked_for_space_secrets(&name, (&member, &device), json, output)
7976}
7977
7978/// Runs `nib secret give` in a shared space: gives the space's secrets to another member's
7979/// device that asked this one, once the secrets here are unlocked.
7980fn give_space_command<E: Environment>(
7981	library: &mut Library,
7982	(space, to): (SpaceId, &str),
7983	json: bool,
7984	environment: &mut E,
7985	timings: &mut Timings,
7986	output: &mut dyn Write,
7987) -> Result<(), CliError> {
7988	let (member, device) = member_device(library, space, to, |replica| replica.asks_for_secrets)?;
7989	unlock_secrets(library, false, environment, timings)?;
7990	let now = environment.now();
7991	let given = library.give_space_secrets(space, device.record, now, environment.rng());
7992	library.lock_secrets();
7993	let keys = given?;
7994	let name = library.space_name(space)?.unwrap_or_default();
7995	output::gave_space_secrets(&name, (&member, &device), keys, json, output)
7996}
7997
7998/// Runs `nib secret ask`: sets up the secrets of this device, which holds none while another
7999/// does, with a passphrase of their own, and asks for them from the device named; or, on a
8000/// device that asked already, asks another
8001/// ([technical design](../../../docs/Technical-design.md#12-secrets)).
8002fn ask_command<E: Environment>(
8003	library: &mut Library,
8004	from: &str,
8005	json: bool,
8006	environment: &mut E,
8007	timings: &mut Timings,
8008	output: &mut dyn Write,
8009) -> Result<(), CliError> {
8010	// The device that holds them: of its replicas, one that does.
8011	let Some(from) = library
8012		.replicas_named(from)?
8013		.into_iter()
8014		.find(|replica| replica.holds_secrets && !replica.this && !replica.revoked)
8015	else {
8016		return Err(NodeError::WhichDevice(
8017			"that device does not hold the secrets, or has not said so yet: unlock its secrets \
8018			 once"
8019				.to_owned(),
8020		)
8021		.into());
8022	};
8023	let now = environment.now();
8024	if library.secrets_state()? == SecretsState::Asked {
8025		library.ask_secrets_from(from.id, now, environment.rng())?;
8026	} else {
8027		// Before the passphrase is asked for.
8028		library.check_may_ask(from.id)?;
8029		let passphrase = ask_twice(
8030			environment,
8031			timings,
8032			(
8033				"A passphrase for the secrets on this device, not the library's: ",
8034				"The passphrase again: ",
8035			),
8036			(|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
8037		)?;
8038		let protection = NewProtection::Passphrase(&passphrase, environment.passphrase_params());
8039		let now = environment.now();
8040		let asked = library.ask_for_secrets(from.id, &protection, now, environment.rng());
8041		library.lock_secrets();
8042		asked?;
8043	}
8044	let own = library.replicas()?.into_iter().find(|replica| replica.this);
8045	output::asked_for_secrets(own.as_ref(), &from, json, output)
8046}
8047
8048/// Runs `nib secret give`: gives the secrets to the replicas of a device, or one replica,
8049/// that asked for them, after the passphrase of the secrets here.
8050fn give_command<E: Environment>(
8051	library: &mut Library,
8052	device: &str,
8053	json: bool,
8054	environment: &mut E,
8055	timings: &mut Timings,
8056	output: &mut dyn Write,
8057) -> Result<(), CliError> {
8058	// Before the passphrase is asked for: which replicas, and that one of them asks this one.
8059	let named: Vec<Replica> = library
8060		.replicas_named(device)?
8061		.into_iter()
8062		.filter(|replica| !replica.this && !replica.revoked)
8063		.collect();
8064	if named.is_empty() {
8065		return Err(NodeError::WhichDevice(
8066			"that names no other device of yours that is not revoked".to_owned(),
8067		)
8068		.into());
8069	}
8070	let own = library.replicas()?.into_iter().find(|replica| replica.this);
8071	let own = own.map(|replica| replica.id);
8072	let asking: Vec<Replica> = named
8073		.iter()
8074		.filter(|replica| replica.asks_for_secrets && replica.secrets_from == own)
8075		.cloned()
8076		.collect();
8077	if asking.is_empty() {
8078		return Err(if named.iter().any(|replica| replica.asks_for_secrets) {
8079			NodeError::WhichDevice("that device asks another of yours for the secrets".to_owned())
8080		} else {
8081			NodeError::NotAsked
8082		}
8083		.into());
8084	}
8085	unlock_secrets(library, false, environment, timings)?;
8086	let mut given = Vec::new();
8087	let mut failed = None;
8088	for replica in asking {
8089		let now = environment.now();
8090		match library.give_secrets(replica.id, now, environment.rng()) {
8091			Ok(keys) => given.push((replica, keys)),
8092			Err(error) => {
8093				failed = Some(error);
8094				break;
8095			}
8096		}
8097	}
8098	library.lock_secrets();
8099	// What was given is said, also when the rest failed.
8100	output::gave_secrets(&given, json, output)?;
8101	match failed {
8102		Some(error) => Err(error.into()),
8103		None => Ok(()),
8104	}
8105}
8106
8107/// The password that `nib secret set --generate` sets, generated before the passphrase is
8108/// asked for, so that a recipe that cannot be met changes nothing; `None` without
8109/// `--generate`, whose options are refused alone.
8110fn generated_secret<E: Environment>(
8111	command: &SecretCommand,
8112	field: &FieldName,
8113	environment: &mut E,
8114) -> Result<Option<zeroize::Zeroizing<String>>, CliError> {
8115	let SecretCommand::Set {
8116		generate, recipe, ..
8117	} = command
8118	else {
8119		return Ok(None);
8120	};
8121	if !generate {
8122		return if recipe.given() {
8123			Err(CliError::RecipeWithoutGenerate)
8124		} else {
8125			Ok(None)
8126		};
8127	}
8128	if *field == nibkeep_std::ONE_TIME_CODE {
8129		return Err(CliError::GeneratedOneTimeCode(field.clone()));
8130	}
8131	Ok(Some(nibkeep_passwords::generate(
8132		&recipe.recipe(),
8133		environment.rng(),
8134	)?))
8135}
8136
8137/// Sets a secret field of an entity of the personal space to the value `generated`, or to
8138/// one asked for twice, while the secrets are unlocked.
8139fn set_secret<E: Environment>(
8140	library: &mut Library,
8141	(id, field, types): (EntityId, &FieldName, &nibkeep_model::Types),
8142	generated: Option<zeroize::Zeroizing<String>>,
8143	environment: &mut E,
8144	timings: &mut Timings,
8145) -> Result<(), CliError> {
8146	let text = if let Some(generated) = generated {
8147		generated
8148	} else {
8149		ask_twice(
8150			environment,
8151			timings,
8152			(&format!("{field}: "), &format!("{field} again: ")),
8153			(|| CliError::EmptyValue, || CliError::ValuesDiffer),
8154		)?
8155	};
8156	// The secret of one-time codes is checked before it is kept, as it is typed.
8157	if *field == nibkeep_std::ONE_TIME_CODE {
8158		nibkeep_passwords::OneTimeCode::check(&text)?;
8159	}
8160	let space = library.default_space();
8161	let value = types::value(&text, field, types, library, space)?;
8162	edit_now(
8163		library,
8164		id,
8165		Edit::Set(field.clone(), vec![value]),
8166		environment,
8167	)
8168}
8169
8170/// Shows the one-time code of an entity now, from the secret in a field: std.one-time-code,
8171/// unless another is given.
8172fn code_command<E: Environment>(
8173	library: &mut Library,
8174	(entity, field): (&str, Option<&str>),
8175	json: bool,
8176	environment: &mut E,
8177	timings: &mut Timings,
8178	output: &mut dyn Write,
8179) -> Result<(), CliError> {
8180	let default = nibkeep_std::ONE_TIME_CODE;
8181	let field = field.unwrap_or(default.as_str());
8182	let read = read_secret(library, entity, field, environment, timings)?;
8183	let generator = nibkeep_passwords::OneTimeCode::parse(&read.values[0])?;
8184	output::one_time_code(&generator, environment.now() / 1000, json, output)
8185}
8186
8187/// The values of a secret field of an entity, read after the secrets' passphrase.
8188struct SecretRead {
8189	/// The entity.
8190	entity: EntityId,
8191	/// Its name, or how it was given.
8192	name: String,
8193	/// The secret field.
8194	field: FieldName,
8195	/// Its values, in the order they are shown: one at least.
8196	values: Vec<zeroize::Zeroizing<String>>,
8197}
8198
8199/// Reads the values of a secret field of an entity of the personal space, asking for the
8200/// secrets' passphrase, and locks the secrets again.
8201fn read_secret<E: Environment>(
8202	library: &mut Library,
8203	entity: &str,
8204	field: &str,
8205	environment: &mut E,
8206	timings: &mut Timings,
8207) -> Result<SecretRead, CliError> {
8208	let (space, id) = library.locate_or_deleted(entity)?;
8209	// The command works in the space that holds the entity.
8210	library.choose_space(Some(space))?;
8211	let day = dating(environment, environment.now(), None).day;
8212	let view = library
8213		.entity(space, id, day)?
8214		.ok_or_else(|| NodeError::NoEntity(entity.to_owned()))?;
8215	let types = library.types(space)?;
8216	let field = types::field_named(field, &types, &view.types)?;
8217	if !is_secret(library, space, &field) {
8218		return Err(CliError::NotSecret(field));
8219	}
8220	unlock_secrets(library, false, environment, timings)?;
8221	let read = library.entity(space, id, day);
8222	library.lock_secrets();
8223	let view = read?.ok_or_else(|| NodeError::NoEntity(entity.to_owned()))?;
8224	let name_of = |entity| library.name(space, entity).ok().flatten();
8225	let values: Vec<zeroize::Zeroizing<String>> = view
8226		.values(&field)
8227		.iter()
8228		.map(|shown| zeroize::Zeroizing::new(output::value_text(&shown.value, &name_of)))
8229		.collect();
8230	if values.is_empty() {
8231		return Err(CliError::NoSecretValue {
8232			entity: entity.to_owned(),
8233			field,
8234		});
8235	}
8236	Ok(SecretRead {
8237		entity: view.id,
8238		name: view.name.unwrap_or_else(|| entity.to_owned()),
8239		field,
8240		values,
8241	})
8242}
8243
8244/// Copies the first value of a secret to `board`, marked as sensitive, waits `clear_after`
8245/// seconds, or until the person interrupts, and then clears the clipboard if it still holds
8246/// the secret. Whatever fails once the secret is copied, the clipboard is cleared.
8247fn copy_and_clear<E: Environment>(
8248	board: Box<dyn nibkeep_passwords::Board>,
8249	read: &SecretRead,
8250	clear_after: u64,
8251	json: bool,
8252	environment: &mut E,
8253	output: &mut dyn Write,
8254) -> Result<(), CliError> {
8255	environment.interruptible();
8256	let mut clipboard = nibkeep_passwords::Clipboard::new(board, environment.rng());
8257	clipboard.copy_secret(&read.values[0])?;
8258	let printed = if json {
8259		Ok(())
8260	} else {
8261		output::copied(
8262			&read.field,
8263			&read.name,
8264			read.values.len(),
8265			clear_after,
8266			output,
8267		)
8268		.and_then(|()| Ok(output.flush()?))
8269	};
8270	let interrupted = printed.is_ok() && environment.wait(Duration::from_secs(clear_after));
8271	// Another program may hold the clipboard for a moment.
8272	let cleared = clipboard.clear_if_ours().or_else(|_| {
8273		std::thread::sleep(Duration::from_millis(200));
8274		clipboard.clear_if_ours()
8275	});
8276	printed?;
8277	output::copy_ended(
8278		(read.entity, &read.field, read.values.len()),
8279		(cleared?, interrupted),
8280		json,
8281		output,
8282	)
8283}
8284
8285/// Prints a new random password, as `recipe` says.
8286fn generate_command<E: Environment>(
8287	recipe: &RecipeArgs,
8288	json: bool,
8289	environment: &mut E,
8290	output: &mut dyn Write,
8291) -> Result<(), CliError> {
8292	let recipe = recipe.recipe();
8293	let password = nibkeep_passwords::generate(&recipe, environment.rng())?;
8294	output::generated(&password, recipe.bits(), json, output)
8295}
8296
8297/// Runs `nib import`: imports an export that nib export made, or else Google Takeout's
8298/// archive of Google Photos.
8299fn import_command<E: Environment>(
8300	library: &mut Library,
8301	(paths, from): (&[PathBuf], Option<&str>),
8302	json: bool,
8303	environment: &mut E,
8304	output: &mut dyn Write,
8305) -> Result<(), CliError> {
8306	// An export says what it is in its manifest and its sums, which Takeout's archives never
8307	// hold: a folder with either is read as an export, whose errors then say what it lacks.
8308	if let [folder] = paths
8309		&& ["manifest.json", "SHA256SUMS"]
8310			.iter()
8311			.any(|name| folder.join(name).is_file())
8312	{
8313		if from.is_some() {
8314			return Err(CliError::Import(
8315				"--from names the source of Google Takeout's photos; an export keeps where its files came from".to_owned(),
8316			));
8317		}
8318		let space = library.default_space();
8319		let imported = library.import(space, folder, environment.now(), environment.rng())?;
8320		return output::imported(&imported, folder, json, output);
8321	}
8322	takeout_command(library, (paths, from), json, environment, output)
8323}
8324
8325/// Protects the library's keys, or with `secrets`, its secrets, with a new passphrase if
8326/// `passphrase` says so, and otherwise with the platform's keystore.
8327fn protect_command<E: Environment>(
8328	library: &mut Library,
8329	(passphrase, secrets): (bool, bool),
8330	json: bool,
8331	environment: &mut E,
8332	timings: &mut Timings,
8333	output: &mut dyn Write,
8334) -> Result<(), CliError> {
8335	// Before any passphrase is asked for.
8336	if !passphrase && !environment.keystore() {
8337		return Err(CliError::NoKeystoreToProtect);
8338	}
8339	if secrets {
8340		unlock_secrets(library, false, environment, timings)?;
8341	}
8342	let protected = (|| {
8343		let typed = if passphrase {
8344			let prompt = if secrets {
8345				"A new passphrase for the secrets, not the library's: "
8346			} else {
8347				"A new passphrase for the library: "
8348			};
8349			Some(ask_twice(
8350				environment,
8351				timings,
8352				(prompt, "The passphrase again: "),
8353				(|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
8354			)?)
8355		} else {
8356			None
8357		};
8358		let params = environment.passphrase_params();
8359		let protection = match &typed {
8360			Some(passphrase) => NewProtection::Passphrase(passphrase, params),
8361			None => NewProtection::Keystore {
8362				service: KEYSTORE_SERVICE,
8363			},
8364		};
8365		let protected = if secrets {
8366			library.protect_secrets(&protection, environment.rng())
8367		} else {
8368			library.protect(&protection, environment.rng())
8369		};
8370		protected.map_err(|error| match error {
8371			error @ NodeError::Keys(KeysError::Keystore(_)) => CliError::KeystoreToProtect(error),
8372			other => CliError::Node(other),
8373		})
8374	})();
8375	library.lock_secrets();
8376	protected?;
8377	output::protected(secrets, passphrase, json, output)
8378}
8379
8380/// Edits an entity of the personal space today, at the time it is edited, which may come
8381/// long after the command began, as it waited for the person to type.
8382fn edit_now<E: Environment>(
8383	library: &mut Library,
8384	entity: nibkeep_base::EntityId,
8385	edit: Edit,
8386	environment: &mut E,
8387) -> Result<(), CliError> {
8388	let space = library.default_space();
8389	let now = environment.now();
8390	let dating = dating(environment, now, None);
8391	library.edit_entity(space, entity, vec![edit], &dating, now, environment.rng())?;
8392	Ok(())
8393}
8394
8395/// Whether a field is secret in a space.
8396fn is_secret(library: &Library, space: nibkeep_base::SpaceId, field: &FieldName) -> bool {
8397	library
8398		.secret_fields(space)
8399		.is_some_and(|secret| secret.contains(field))
8400}
8401
8402/// Unlocks the library's secrets, asking for their passphrase; or, for a library that has
8403/// none yet, if `set_up` says so, sets them up with a passphrase of their own, asked for
8404/// twice. Then takes the secrets keys that another device gave this one, and states what
8405/// the records do not say yet ([technical
8406/// design](../../../docs/Technical-design.md#12-secrets)).
8407pub(crate) fn unlock_secrets<E: Environment>(
8408	library: &mut Library,
8409	set_up: bool,
8410	environment: &mut E,
8411	timings: &mut Timings,
8412) -> Result<(), CliError> {
8413	match library.secrets_protection()? {
8414		None if !set_up => return Err(CliError::NoSecrets),
8415		None => {
8416			let passphrase = ask_twice(
8417				environment,
8418				timings,
8419				(
8420					"The library's first secret. A passphrase for its secrets, not the library's: ",
8421					"The passphrase again: ",
8422				),
8423				(|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
8424			)?;
8425			let protection =
8426				NewProtection::Passphrase(&passphrase, environment.passphrase_params());
8427			let now = environment.now();
8428			return Ok(library.set_up_secrets(&protection, now, environment.rng())?);
8429		}
8430		Some(Protection::Passphrase { .. }) => {
8431			let asked = Instant::now();
8432			let passphrase = environment.passphrase("Passphrase for secrets: ")?;
8433			add(&mut timings.waiting, asked.elapsed());
8434			library.unlock_secrets(&Unlocker::Passphrase(&passphrase))?;
8435		}
8436		Some(Protection::Keystore { .. }) => {
8437			if !environment.keystore() {
8438				return Err(CliError::NoKeystore);
8439			}
8440			library.unlock_secrets(&Unlocker::Keystore)?;
8441		}
8442	}
8443	let now = environment.now();
8444	let settled = library.settle_secrets(now, environment.rng());
8445	// Unlocked, and then failed, or without keys yet: the secrets are forgotten, as when it
8446	// ends.
8447	let personal = library.personal_space();
8448	if settled.is_err() || !library.secrets_unlocked(personal) {
8449		library.lock_secrets();
8450	}
8451	settled?;
8452	if library.secrets_unlocked(personal) {
8453		Ok(())
8454	} else {
8455		Err(NodeError::SecretsAsked.into())
8456	}
8457}
8458
8459/// The errors of something asked for twice: that it is empty, and that the two differ.
8460type Mistyped = (fn() -> CliError, fn() -> CliError);
8461
8462/// Asks for a passphrase once, which may be empty: the person waited meanwhile.
8463fn ask_once<E: Environment>(
8464	environment: &mut E,
8465	timings: &mut Timings,
8466	prompt: &str,
8467) -> Result<zeroize::Zeroizing<String>, CliError> {
8468	let asked = Instant::now();
8469	let typed = environment.passphrase(prompt);
8470	add(&mut timings.waiting, asked.elapsed());
8471	Ok(typed?)
8472}
8473
8474/// Asks for something new twice, without showing it, as a passphrase or a secret value,
8475/// and counts the time spent typing as waiting. Fails as `empty` says if it is empty, and
8476/// as `differ` says if the two differ.
8477fn ask_twice<E: Environment>(
8478	environment: &mut E,
8479	timings: &mut Timings,
8480	(prompt, again): (&str, &str),
8481	(empty, differ): Mistyped,
8482) -> Result<zeroize::Zeroizing<String>, CliError> {
8483	let asked = Instant::now();
8484	let first = environment.passphrase(prompt);
8485	let second = match &first {
8486		Ok(first) if !first.is_empty() => Some(environment.passphrase(again)),
8487		_ => None,
8488	};
8489	add(&mut timings.waiting, asked.elapsed());
8490	let first = first?;
8491	let Some(second) = second else {
8492		return Err(empty());
8493	};
8494	if *first != *second? {
8495		return Err(differ());
8496	}
8497	Ok(first)
8498}
8499
8500/// Runs `nib type`, in the personal space.
8501fn type_command<E: Environment>(
8502	library: &mut Library,
8503	command: &TypeCommand,
8504	json: bool,
8505	environment: &mut E,
8506	output: &mut dyn Write,
8507) -> Result<(), CliError> {
8508	let space = library.default_space();
8509	let (name, types) = match command {
8510		TypeCommand::Add { name, fields } => {
8511			let name: TypeName = types::name(name)?;
8512			let fields = fields
8513				.iter()
8514				.map(|field| types::field(field))
8515				.collect::<Result<Vec<_>, _>>()?;
8516			// Standard names come from the vocabulary alone.
8517			let known = library.types(space)?;
8518			let type_known = types::standard_type_known(&known, &name);
8519			types::check_standard(name.as_str(), "type", type_known)?;
8520			for (field, definition) in &fields {
8521				let field_known = types::standard_field_known(&known, field, definition);
8522				types::check_standard(field.as_str(), "field", field_known)?;
8523				if let Some(reverse) = definition.reverse() {
8524					let reverse_known = types::standard_reverse_known(&known, reverse);
8525					types::check_standard(reverse.as_str(), "field", reverse_known)?;
8526				}
8527			}
8528			let definition = library.types(space)?.extend(name.clone(), fields);
8529			let now = environment.now();
8530			let types = library.define_type(space, &definition, now, environment.rng())?;
8531			(name, types)
8532		}
8533		TypeCommand::Show { name } => (types::name(name)?, library.types(space)?),
8534		TypeCommand::List => {
8535			let types = library.types(space)?;
8536			return output::type_list(&types, library.languages(), json, output);
8537		}
8538	};
8539	let definition = types.get(&name).ok_or(CliError::NoType(name))?;
8540	// Whether a field is secret is the space's to say, whatever the type's definition says.
8541	let secret = library.secret_fields(space).cloned().unwrap_or_default();
8542	output::type_definition(definition, (library.languages(), &secret), json, output)
8543}
8544
8545/// Runs `nib space`: makes, lists or renames spaces, invites to them, joins them, and lists
8546/// their members and gives them roles.
8547fn space_command<E: Environment>(
8548	library: &mut Library,
8549	command: &SpaceCommand,
8550	cli: &Cli,
8551	environment: &mut E,
8552	output: &mut dyn Write,
8553) -> Result<(), CliError> {
8554	let json = cli.json;
8555	match command {
8556		SpaceCommand::New { .. }
8557		| SpaceCommand::Take { .. }
8558		| SpaceCommand::Drop { .. }
8559		| SpaceCommand::Allow { .. } => taking_command(library, command, json, environment, output),
8560		SpaceCommand::AddGroup { .. }
8561		| SpaceCommand::RemoveGroup { .. }
8562		| SpaceCommand::Agree { .. }
8563		| SpaceCommand::Withdraw { .. } => group_command(library, command, json, environment, output),
8564		SpaceCommand::List => {
8565			let status = library.status()?;
8566			let known = library.known_spaces()?;
8567			let requests = library.space_requests()?;
8568			output::spaces(
8569				(&status.spaces, &known, &requests),
8570				library.personal_space(),
8571				json,
8572				output,
8573			)
8574		}
8575		SpaceCommand::Show { space } => {
8576			show_space_command(library, space, json, environment, output)
8577		}
8578		SpaceCommand::Rename { space, name } => {
8579			let space = library.find_space(space)?;
8580			let now = environment.now();
8581			library.rename_space(space, name, now, environment.rng())?;
8582			output::space_renamed(space, name, json, output)
8583		}
8584		SpaceCommand::Invite {
8585			space,
8586			role,
8587			person,
8588			yes,
8589			..
8590		} => {
8591			let space = library.find_space(space)?;
8592			let person = person
8593				.as_deref()
8594				.map(|person| library.find_person(space, person))
8595				.transpose()?;
8596			let invitation = nibkeep_node::Invitation {
8597				space,
8598				role: role.role(),
8599				person,
8600			};
8601			invite_command(library, (&invitation, *yes), cli, environment, output)
8602		}
8603		SpaceCommand::Join { code, yes, on } => {
8604			let also = devices_named(library, on)?;
8605			join_space_command(library, (code, *yes, &also), cli, environment, output)
8606		}
8607		SpaceCommand::AiAgents { space, switch } => {
8608			let space = library.find_space(space)?;
8609			if let Some(switch) = switch {
8610				let now = environment.now();
8611				library.allow_ai_agents(space, *switch == Switch::On, now, environment.rng())?;
8612			}
8613			let allowed = library.ai_agents_allowed(space)?;
8614			output::ai_agents_allowed(allowed, json, output)
8615		}
8616		SpaceCommand::Link {
8617			space,
8618			member,
8619			person,
8620		} => link_command(
8621			library,
8622			(space, member, person.as_deref()),
8623			json,
8624			environment,
8625			output,
8626		),
8627		SpaceCommand::Accept { space, member, yes } => {
8628			accept_in_space_command(library, (space, member, *yes), json, environment, output)
8629		}
8630		SpaceCommand::Leave { space, yes } => {
8631			let space = library.find_space(space)?;
8632			leave_command(library, (space, *yes), json, environment, output)
8633		}
8634		SpaceCommand::Remove { space, member, yes } => {
8635			remove_command(library, (space, member, *yes), json, environment, output)
8636		}
8637		SpaceCommand::LetIn { .. }
8638		| SpaceCommand::MakeDirect { .. }
8639		| SpaceCommand::Confirm { .. } => direct_command(library, command, json, environment, output),
8640		SpaceCommand::Claim { .. } | SpaceCommand::Reject { .. } => {
8641			claim_command(library, command, json, environment, output)
8642		}
8643		SpaceCommand::Role {
8644			space,
8645			member,
8646			role,
8647		} => role_command(library, (space, member, *role), json, environment, output),
8648	}
8649}
8650
8651/// Runs `nib space new`, `nib space take`, `nib space drop` and `nib space allow`: makes a
8652/// space for the devices chosen, takes or asks for a space on this device, drops one from it,
8653/// or gives one to another device that asked for it.
8654fn taking_command<E: Environment>(
8655	library: &mut Library,
8656	command: &SpaceCommand,
8657	json: bool,
8658	environment: &mut E,
8659	output: &mut dyn Write,
8660) -> Result<(), CliError> {
8661	match command {
8662		SpaceCommand::New { name, group, on } => {
8663			let also = devices_named(library, on)?;
8664			let now = environment.now();
8665			let space = if *group {
8666				library.create_group_on(name, &also, now, environment.rng())?
8667			} else {
8668				library.create_space_on(name, &also, now, environment.rng())?
8669			};
8670			output::space_made(space, name, json, output)
8671		}
8672		SpaceCommand::Take { wanted } => {
8673			let space = library.find_known_space(wanted)?;
8674			let now = environment.now();
8675			let taking = library.take_space(space, now, environment.rng())?;
8676			let name = library
8677				.known_spaces()?
8678				.into_iter()
8679				.find(|known| known.space == space)
8680				.and_then(|known| known.name)
8681				.unwrap_or_else(|| space.to_string());
8682			let this = library
8683				.replicas()?
8684				.into_iter()
8685				.find(|replica| replica.this)
8686				.ok_or(NodeError::NotListed)?;
8687			let named = (this.device_name.as_deref(), this.id);
8688			output::space_taken((space, &name), taking, named, json, output)
8689		}
8690		SpaceCommand::Drop { wanted } => {
8691			let space = library.find_space(wanted)?;
8692			let name = library
8693				.space_name(space)?
8694				.unwrap_or_else(|| space.to_string());
8695			let now = environment.now();
8696			let dropping = library.drop_space(space, now, environment.rng())?;
8697			output::space_dropping(&dropping, &name, json, output)
8698		}
8699		SpaceCommand::Allow { space, device } => {
8700			let space = library.find_space(space)?;
8701			let replicas = devices_named(library, std::slice::from_ref(device))?;
8702			let request = library
8703				.space_requests()?
8704				.into_iter()
8705				.find(|request| request.space == space && replicas.contains(&request.replica))
8706				.ok_or(NodeError::NoRequest)?;
8707			let now = environment.now();
8708			library.allow_space(space, request.replica, now, environment.rng())?;
8709			output::space_allowed(&request, json, output)
8710		}
8711		_ => unreachable!("only nib space new, take, drop and allow come here"),
8712	}
8713}
8714
8715/// Runs `nib space role`: gives a member of a space a role.
8716fn role_command<E: Environment>(
8717	library: &mut Library,
8718	(space, member, role): (&str, &str, RoleArg),
8719	json: bool,
8720	environment: &mut E,
8721	output: &mut dyn Write,
8722) -> Result<(), CliError> {
8723	let space = library.find_space(space)?;
8724	let member = library.find_member(space, member)?;
8725	let now = environment.now();
8726	library.give_role(space, member, role.role(), now, environment.rng())?;
8727	let name = library
8728		.members(space)?
8729		.into_iter()
8730		.find(|found| found.record == member)
8731		.and_then(|found| found.name);
8732	output::role_given(name.as_deref(), role.role(), json, output)
8733}
8734
8735/// Runs `nib space accept`: accepts a member's changes that were set aside in a space, those
8736/// that accepting makes count, or with `confirmed` false, says how many it would.
8737fn accept_in_space_command<E: Environment>(
8738	library: &mut Library,
8739	(space, member, confirmed): (&str, &str, bool),
8740	json: bool,
8741	environment: &mut E,
8742	output: &mut dyn Write,
8743) -> Result<(), CliError> {
8744	let space = library.find_space(space)?;
8745	// Every record of the member's user: one who came back has another from before.
8746	let chosen = library.find_member(space, member)?;
8747	let members = library.members(space)?;
8748	let user = members
8749		.iter()
8750		.find(|found| found.record == chosen)
8751		.and_then(|found| found.user);
8752	let records: Vec<_> = members
8753		.iter()
8754		.filter(|found| found.record == chosen || (user.is_some() && found.user == user))
8755		.map(|found| found.record)
8756		.collect();
8757	let changes: Vec<_> = library
8758		.set_aside_in(space)?
8759		.into_iter()
8760		.filter(|aside| {
8761			aside.acceptable && aside.member.is_some_and(|member| records.contains(&member))
8762		})
8763		.map(|aside| aside.change)
8764		.collect();
8765	let accepted = if confirmed {
8766		let now = environment.now();
8767		library.accept_set_aside_in(space, &changes, now, environment.rng())?
8768	} else {
8769		library.check_admin(space, "accept changes that were set aside")?;
8770		changes.len()
8771	};
8772	output::accepted(accepted, confirmed, json, output)?;
8773	if confirmed || accepted == 0 {
8774		Ok(())
8775	} else {
8776		Err(CliError::UnconfirmedAccept)
8777	}
8778}
8779
8780/// Runs `nib space leave`: leaves a space, or with `confirmed` false, says what leaving
8781/// would do.
8782fn leave_command<E: Environment>(
8783	library: &mut Library,
8784	(space, confirmed): (nibkeep_base::SpaceId, bool),
8785	json: bool,
8786	environment: &mut E,
8787	output: &mut dyn Write,
8788) -> Result<(), CliError> {
8789	let name = library
8790		.space_name(space)?
8791		.unwrap_or_else(|| space.to_string());
8792	if !confirmed {
8793		let closes = library.check_leave(space)?;
8794		output::leaving(&name, closes, json, output)?;
8795		return Err(CliError::UnconfirmedLeave);
8796	}
8797	let now = environment.now();
8798	let closed = library.leave(space, now, environment.rng())?;
8799	output::left(&name, closed, json, output)
8800}
8801
8802/// The name to show for a space: its own, or else its ID.
8803fn space_display_name(library: &Library, space: nibkeep_base::SpaceId) -> Result<String, CliError> {
8804	Ok(library
8805		.space_name(space)?
8806		.unwrap_or_else(|| space.to_string()))
8807}
8808
8809/// Keeps a member through a group out of a space, as `nib space remove` does for one, saying
8810/// first what it would do without `--yes`.
8811fn keep_out_command<E: Environment>(
8812	library: &mut Library,
8813	(space, member, confirmed): (nibkeep_base::SpaceId, &str, bool),
8814	json: bool,
8815	environment: &mut E,
8816	output: &mut dyn Write,
8817) -> Result<(), CliError> {
8818	let found = library.find_group_member(space, member)?;
8819	let name = space_display_name(library, space)?;
8820	if !confirmed {
8821		library.check_admin(space, "keep members out")?;
8822		output::removing((&name, Some(member)), json, output)?;
8823		return Err(CliError::UnconfirmedRemove);
8824	}
8825	let now = environment.now();
8826	library.keep_out(space, found, now, environment.rng())?;
8827	output::removed((&name, Some(member)), json, output)
8828}
8829
8830/// Runs `nib space remove`: removes a member of a space, or with `confirmed` false, says what
8831/// removing them would do.
8832fn remove_command<E: Environment>(
8833	library: &mut Library,
8834	(space, member, confirmed): (&str, &str, bool),
8835	json: bool,
8836	environment: &mut E,
8837	output: &mut dyn Write,
8838) -> Result<(), CliError> {
8839	let space = library.find_space(space)?;
8840	let record = match library.find_member(space, member) {
8841		Ok(record) => record,
8842		// A member through a group alone is kept out of the space.
8843		Err(NodeError::NoMember(_)) => {
8844			return keep_out_command(
8845				library,
8846				(space, member, confirmed),
8847				json,
8848				environment,
8849				output,
8850			);
8851		}
8852		Err(error) => return Err(error.into()),
8853	};
8854	// Removing oneself is leaving.
8855	if library.check_remove(space, record)? {
8856		return leave_command(library, (space, confirmed), json, environment, output);
8857	}
8858	let space_name = space_display_name(library, space)?;
8859	let name = library
8860		.members(space)?
8861		.into_iter()
8862		.find(|found| found.record == record)
8863		.and_then(|found| found.name);
8864	if !confirmed {
8865		output::removing((&space_name, name.as_deref()), json, output)?;
8866		return Err(CliError::UnconfirmedRemove);
8867	}
8868	let now = environment.now();
8869	library.remove_member(space, record, now, environment.rng())?;
8870	output::removed((&space_name, name.as_deref()), json, output)
8871}
8872
8873/// Runs `nib space show`: a space's members, with the names of the people they are linked
8874/// to, the groups in it, the claims to its admin role and the changes set aside there; and
8875/// for a group, the requests in it that it join spaces.
8876fn show_space_command<E: Environment>(
8877	library: &Library,
8878	space: &str,
8879	json: bool,
8880	environment: &E,
8881	output: &mut dyn Write,
8882) -> Result<(), CliError> {
8883	let space = library.find_space(space)?;
8884	let members = library.members(space)?;
8885	let mut names = std::collections::BTreeMap::new();
8886	for member in &members {
8887		let link = member.person;
8888		for person in [link.holds, link.by_admin, link.by_member]
8889			.into_iter()
8890			.flatten()
8891		{
8892			if let Some(name) = library.name(space, person)? {
8893				names.insert(person, name);
8894			}
8895		}
8896	}
8897	let requests = if library.is_group(space)? {
8898		Some(library.join_requests(space)?)
8899	} else {
8900		None
8901	};
8902	let shown = output::SpaceShown {
8903		members: &members,
8904		names: &names,
8905		groups: &library.space_groups(space)?,
8906		requests: requests.as_deref(),
8907		claims: &library.claims(space)?,
8908		set_aside: &library.set_aside_in(space)?,
8909	};
8910	output::space_shown(&shown, &environment.time_zone(), json, output)
8911}
8912
8913/// Runs `nib purge`: purges values of an entity, or what a move left behind of it; or,
8914/// without an entity, lists what moves left behind.
8915fn purge_or_list<E: Environment>(
8916	library: &mut Library,
8917	cli: &Cli,
8918	environment: &mut E,
8919	timings: &mut Timings,
8920	output: &mut dyn Write,
8921) -> Result<(), CliError> {
8922	let Command::Purge {
8923		entity, value, yes, ..
8924	} = &cli.command
8925	else {
8926		unreachable!("nib purge is the command");
8927	};
8928	let Some(entity) = entity else {
8929		return behind_command(library, cli, output);
8930	};
8931	let purge = (entity.as_str(), value.as_deref(), *yes);
8932	purge_either(library, purge, cli.json, environment, timings, output)
8933}
8934
8935/// Runs `nib purge --behind` without an entity: lists what moves left behind and asked the
8936/// admins of its space to purge, in the space that --space names, or in every space.
8937fn behind_command(library: &Library, cli: &Cli, output: &mut dyn Write) -> Result<(), CliError> {
8938	let spaces = if cli.space.is_some() {
8939		vec![library.default_space()]
8940	} else {
8941		library.spaces()
8942	};
8943	let mut shown = Vec::new();
8944	for left_in in spaces {
8945		for request in library.purge_requests(left_in)? {
8946			let (now_in, moved) = request.moved_into;
8947			shown.push(output::LeftBehind {
8948				request,
8949				left_in: (left_in, library.space_name(left_in)?),
8950				name: library.name(now_in, moved)?,
8951				now_in: library.space_name(now_in)?,
8952			});
8953		}
8954	}
8955	output::purge_requests(&shown, cli.json, output)
8956}
8957
8958/// Runs the parts of `nib space` that are about claims to the admin role: claims it, lists
8959/// the claims, and rejects one.
8960fn claim_command<E: Environment>(
8961	library: &mut Library,
8962	command: &SpaceCommand,
8963	json: bool,
8964	environment: &mut E,
8965	output: &mut dyn Write,
8966) -> Result<(), CliError> {
8967	match command {
8968		SpaceCommand::Claim { space, yes } => {
8969			let space = library.find_space(space)?;
8970			let name = space_display_name(library, space)?;
8971			if !*yes {
8972				library.check_claim(space)?;
8973				output::claiming(&name, json, output)?;
8974				return Err(CliError::UnconfirmedClaim);
8975			}
8976			let now = environment.now();
8977			library.claim_admin(space, now, environment.rng())?;
8978			output::claimed(&name, json, output)
8979		}
8980		SpaceCommand::Reject { space, member } => {
8981			let space = library.find_space(space)?;
8982			let record = library.find_member(space, member)?;
8983			let now = environment.now();
8984			library.reject_claim(space, record, now, environment.rng())?;
8985			let name = space_display_name(library, space)?;
8986			output::rejected_claim((&name, member), json, output)
8987		}
8988		_ => unreachable!("space_command passes only these"),
8989	}
8990}
8991
8992/// Runs the parts of `nib space` that are about members through groups: makes one a direct
8993/// member, confirms such a record, and lets one back in.
8994fn direct_command<E: Environment>(
8995	library: &mut Library,
8996	command: &SpaceCommand,
8997	json: bool,
8998	environment: &mut E,
8999	output: &mut dyn Write,
9000) -> Result<(), CliError> {
9001	match command {
9002		SpaceCommand::LetIn { space, member } => {
9003			let space = library.find_space(space)?;
9004			let found = library.find_group_member(space, member)?;
9005			let now = environment.now();
9006			library.let_in(space, found, now, environment.rng())?;
9007			let name = space_display_name(library, space)?;
9008			output::let_in((&name, member), json, output)
9009		}
9010		SpaceCommand::MakeDirect {
9011			space,
9012			member,
9013			role,
9014		} => {
9015			let space = library.find_space(space)?;
9016			let found = library.find_group_member(space, member)?;
9017			let now = environment.now();
9018			library.make_direct(space, found, role.role(), now, environment.rng())?;
9019			let name = space_display_name(library, space)?;
9020			output::made_direct((&name, member), role.role(), json, output)
9021		}
9022		SpaceCommand::Confirm { space } => {
9023			let space = library.find_space(space)?;
9024			let now = environment.now();
9025			library.confirm_direct(space, now, environment.rng())?;
9026			let name = space_display_name(library, space)?;
9027			output::confirmed_direct(&name, json, output)
9028		}
9029		_ => unreachable!("space_command passes only these"),
9030	}
9031}
9032
9033/// Runs the parts of `nib space` that are about groups: adds a group to a space, lists a
9034/// space's groups and a group's requests to join spaces, and agrees or withdraws.
9035fn group_command<E: Environment>(
9036	library: &mut Library,
9037	command: &SpaceCommand,
9038	json: bool,
9039	environment: &mut E,
9040	output: &mut dyn Write,
9041) -> Result<(), CliError> {
9042	match command {
9043		SpaceCommand::AddGroup { space, group, role } => {
9044			let (space, group) = (library.find_space(space)?, library.find_space(group)?);
9045			let now = environment.now();
9046			library.add_group(space, group, role.role(), now, environment.rng())?;
9047			let groups = library.space_groups(space)?;
9048			output::space_groups(&groups, json, output)
9049		}
9050		SpaceCommand::RemoveGroup { space, group } => {
9051			let (space, group) = (library.find_space(space)?, library.find_space(group)?);
9052			let now = environment.now();
9053			library.remove_group(space, group, now, environment.rng())?;
9054			output::space_groups(&library.space_groups(space)?, json, output)
9055		}
9056		SpaceCommand::Agree { group, space } | SpaceCommand::Withdraw { group, space } => {
9057			let group = library.find_space(group)?;
9058			let space = requested_space(library, group, space)?;
9059			let now = environment.now();
9060			if matches!(command, SpaceCommand::Withdraw { .. }) {
9061				library.withdraw_group(group, space, now, environment.rng())?;
9062			} else {
9063				library.agree_to_join(group, space, now, environment.rng())?;
9064			}
9065			output::join_requests(&library.join_requests(group)?, json, output)
9066		}
9067		_ => Ok(()),
9068	}
9069}
9070
9071/// The space that a request in a group names, by its name there, whatever the case, or by
9072/// the start of its ID.
9073fn requested_space(
9074	library: &Library,
9075	group: nibkeep_base::SpaceId,
9076	reference: &str,
9077) -> Result<nibkeep_base::SpaceId, CliError> {
9078	let lowered = reference.to_lowercase();
9079	let requests = library.join_requests(group)?;
9080	// By name first, as nib finds a space; by the start of its ID, of at least four
9081	// characters, only where no name matches.
9082	let by_name: Vec<nibkeep_base::SpaceId> = requests
9083		.iter()
9084		.filter(|request| {
9085			request
9086				.name
9087				.as_deref()
9088				.is_some_and(|name| name.to_lowercase() == lowered)
9089		})
9090		.map(|request| request.space)
9091		.collect();
9092	let found: Vec<nibkeep_base::SpaceId> = if by_name.is_empty() && lowered.len() >= 4 {
9093		requests
9094			.iter()
9095			.filter(|request| request.space.to_string().starts_with(&lowered))
9096			.map(|request| request.space)
9097			.collect()
9098	} else {
9099		by_name
9100	};
9101	match found.as_slice() {
9102		[space] => Ok(*space),
9103		[] => Err(nibkeep_node::NodeError::NoGroupRequest.into()),
9104		_ => Err(nibkeep_node::NodeError::SpacesNamed(reference.to_owned()).into()),
9105	}
9106}
9107
9108/// Runs `nib space link`: links a member to a person, or unlinks them.
9109fn link_command<E: Environment>(
9110	library: &mut Library,
9111	(space, member, person): (&str, &str, Option<&str>),
9112	json: bool,
9113	environment: &mut E,
9114	output: &mut dyn Write,
9115) -> Result<(), CliError> {
9116	let space = library.find_space(space)?;
9117	let member = library.find_member(space, member)?;
9118	let person = person
9119		.map(|person| library.find_person(space, person))
9120		.transpose()?;
9121	let now = environment.now();
9122	library.link_member(space, member, person, now, environment.rng())?;
9123	let found = library
9124		.members(space)?
9125		.into_iter()
9126		.find(|found| found.record == member);
9127	let name = found.as_ref().and_then(|found| found.name.clone());
9128	let link = found.map_or_default(|found| found.person);
9129	let person = match person {
9130		Some(person) => Some((person, library.name(space, person)?)),
9131		None => None,
9132	};
9133	output::linked(name.as_deref(), (person, link), json, output)
9134}
9135
9136/// How long an invitation's code works.
9137const INVITATION_MINUTES: u64 = 10;
9138
9139/// Runs `nib space invite`: shows a code, shows who asks to join with it, and adds them once
9140/// the person confirms, or at once with `confirmed`, as a member of `space` with `role`.
9141fn invite_command<E: Environment>(
9142	library: &mut Library,
9143	(invitation, confirmed): (&nibkeep_node::Invitation, bool),
9144	cli: &Cli,
9145	environment: &mut E,
9146	output: &mut dyn Write,
9147) -> Result<(), CliError> {
9148	let json = cli.json;
9149	let (space, role) = (invitation.space, invitation.role);
9150	// Before showing a code that could not be used.
9151	library.check_admin(space, "invite")?;
9152	if !confirmed && !environment.can_ask() {
9153		return Err(CliError::UnconfirmedInvite);
9154	}
9155	let name = library
9156		.space_name(space)?
9157		.unwrap_or_else(|| space.to_string());
9158	let suggest = role != MemberRole::Admin && library.suggests_second_admin(space)?;
9159	// The program that syncs this device stops its endpoint while this one invites; nib
9160	// stops waiting for it only as it ends.
9161	let _borrowed =
9162		nibkeep_node::borrow_network(library, &AtomicBool::new(false), UnwrapErr(SysRng))?;
9163	let code = PairingCode::generate(environment.rng());
9164	let network = library.network(cli.network(true))?;
9165	output::port_taken(&network, json, output)?;
9166	output::invitation_code(
9167		&code,
9168		(&name, role),
9169		(INVITATION_MINUTES, suggest),
9170		json,
9171		output,
9172	)?;
9173	let now = clock(environment);
9174	let mut unasked = false;
9175	let mut confirm = |invitee: &nibkeep_node::Invitee| {
9176		if confirmed {
9177			return true;
9178		}
9179		let question = output::invitee_question(invitee, (&name, role));
9180		if let Ok(Some(answer)) = environment.ask(&question) {
9181			matches!(answer.to_lowercase().as_str(), "y" | "yes")
9182		} else {
9183			unasked = true;
9184			false
9185		}
9186	};
9187	let printing = RefCell::new(output);
9188	let wrong_try = |error: &NodeError, left: usize| {
9189		let _ = output::wrong_try(error, left, json, &mut **printing.borrow_mut());
9190	};
9191	let invited = nibkeep_node::invite(
9192		library,
9193		&network,
9194		invitation,
9195		&code,
9196		&mut confirm,
9197		nibkeep_node::Showing {
9198			timeout: Duration::from_mins(INVITATION_MINUTES),
9199			wrong_try: &wrong_try,
9200		},
9201		&now,
9202		&mut UnwrapErr(SysRng),
9203	);
9204	match invited {
9205		Err(NodeError::Declined) if unasked => Err(CliError::UnconfirmedInvite),
9206		invited => output::invited(&invited?, (&name, role), json, printing.into_inner()),
9207	}
9208}
9209
9210/// Runs `nib space join`: joins the space that the device showing `code` invites to, and, if
9211/// the invitation names the person whom the user is, links them once they agree, or at once
9212/// with `confirmed`.
9213fn join_space_command<E: Environment>(
9214	library: &mut Library,
9215	(code, confirmed, also): (&PairingCode, bool, &[EntityId]),
9216	cli: &Cli,
9217	environment: &mut E,
9218	output: &mut dyn Write,
9219) -> Result<(), CliError> {
9220	let json = cli.json;
9221	library.check_not_ai_agent("join spaces")?;
9222	let _borrowed =
9223		nibkeep_node::borrow_network(library, &AtomicBool::new(false), UnwrapErr(SysRng))?;
9224	let network = library.network(cli.network(false))?;
9225	output::progress("Looking for the device that shows the code…", json, output)?;
9226	let now = clock(environment);
9227	let joined = nibkeep_node::join_space(
9228		library,
9229		&network,
9230		code,
9231		FIND_SPONSOR,
9232		&now,
9233		environment.rng(),
9234	)?;
9235	// The devices of the person's chosen besides those that take new spaces.
9236	if !also.is_empty() {
9237		let now = environment.now();
9238		library.give_space(joined.space, also, now, environment.rng())?;
9239	}
9240	let linked = match &joined.person {
9241		None => None,
9242		Some((person, name)) => {
9243			// The space is joined: what follows only says whether the user is that person.
9244			let yes = confirmed
9245				|| matches!(
9246					environment.ask(&output::person_question(name, &joined.name)),
9247					Ok(Some(answer)) if matches!(answer.to_lowercase().as_str(), "y" | "yes")
9248				);
9249			let now = environment.now();
9250			let linked = yes
9251				&& match library.link_member(
9252					joined.space,
9253					joined.member,
9254					Some(*person),
9255					now,
9256					environment.rng(),
9257				) {
9258					Ok(()) => true,
9259					Err(error) => {
9260						environment.note(&format!("could not link you to {name}: {error}"));
9261						false
9262					}
9263				};
9264			Some(linked)
9265		}
9266	};
9267	output::joined_space(&joined, linked, json, output)
9268}
9269
9270/// Tells the person how to keep a library on a drive without a journal, if that is why it was
9271/// not made.
9272fn no_journal(error: CliError, directory: &Path) -> CliError {
9273	match error {
9274		CliError::Node(NodeError::NoJournal) => CliError::NoJournal(directory.to_owned()),
9275		other => other,
9276	}
9277}
9278
9279/// Starts a library, protected by the platform's keystore unless a passphrase is asked for,
9280/// or given in a file, or there is no keystore.
9281fn init<E: Environment>(
9282	directory: &Path,
9283	new: &NewLibrary<'_>,
9284	(passphrase, file): (bool, Option<&Path>),
9285	environment: &mut E,
9286	timings: &mut Timings,
9287) -> Result<Library, CliError> {
9288	// Before any passphrase is asked for. A new library is not started among copies of
9289	// another's replicas.
9290	if Library::exists(directory) {
9291		return Err(match Library::protection(directory) {
9292			Err(NodeError::Unfinished) => unfinished(directory),
9293			Err(NodeError::Copied) => CliError::CopiedHere(directory.to_owned()),
9294			_ => NodeError::Exists.into(),
9295		});
9296	}
9297	if let Some(first) = new_passphrase((passphrase, file), environment, timings)? {
9298		let protection = NewProtection::Passphrase(&first, environment.passphrase_params());
9299		create(directory, new, &protection, environment)
9300	} else {
9301		let protection = NewProtection::Keystore {
9302			service: KEYSTORE_SERVICE,
9303		};
9304		create(directory, new, &protection, environment).map_err(|error| match error {
9305			CliError::Node(error @ NodeError::Keys(KeysError::Keystore(_))) => {
9306				CliError::Keystore(error)
9307			}
9308			other => other,
9309		})
9310	}
9311}
9312
9313/// The passphrase in the first line of a file, which nobody else may be able to read.
9314/// The passphrase that protects a new library's keys, where the person asked for one with
9315/// `passphrase` or in `file`, or this computer has no keystore: read from the file, or
9316/// asked for twice. `None` for the keystore.
9317fn new_passphrase<E: Environment>(
9318	(passphrase, file): (bool, Option<&Path>),
9319	environment: &mut E,
9320	timings: &mut Timings,
9321) -> Result<Option<zeroize::Zeroizing<String>>, CliError> {
9322	if !(passphrase || file.is_some() || !environment.keystore()) {
9323		return Ok(None);
9324	}
9325	Ok(Some(match file {
9326		Some(file) => passphrase_in(file)?,
9327		None => ask_twice(
9328			environment,
9329			timings,
9330			("A passphrase for the library: ", "The passphrase again: "),
9331			(|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
9332		)?,
9333	}))
9334}
9335
9336fn passphrase_in(path: &Path) -> Result<zeroize::Zeroizing<String>, CliError> {
9337	use std::io::Read;
9338	let unreadable = |error: io::Error| CliError::PassphraseFile {
9339		path: path.to_owned(),
9340		error,
9341	};
9342	let mut file = std::fs::File::open(path).map_err(unreadable)?;
9343	let metadata = file.metadata().map_err(unreadable)?;
9344	#[cfg(unix)]
9345	{
9346		use std::os::unix::fs::PermissionsExt;
9347		if metadata.permissions().mode() & 0o077 != 0 {
9348			return Err(CliError::PassphraseFileOpen(path.to_owned()));
9349		}
9350	}
9351	// Room for all of it at once, so that growing leaves no copies behind.
9352	let room = usize::try_from(metadata.len()).unwrap_or(0);
9353	let mut text = zeroize::Zeroizing::new(String::with_capacity(room + 1));
9354	file.read_to_string(&mut text).map_err(unreadable)?;
9355	let end = text.find(['\n', '\r']).unwrap_or(text.len());
9356	text.truncate(end);
9357	if text.is_empty() {
9358		return Err(CliError::EmptyPassphrase);
9359	}
9360	Ok(text)
9361}
9362
9363fn create<E: Environment>(
9364	directory: &Path,
9365	new: &NewLibrary<'_>,
9366	protection: &NewProtection<'_>,
9367	environment: &mut E,
9368) -> Result<Library, CliError> {
9369	let now = environment.now();
9370	let mut library = Library::create(directory, new, protection, now, environment.rng())?;
9371	library.make_thumbnails_with(Arc::new(RustDecoders));
9372	Ok(library)
9373}
9374
9375/// Opens the library, asking for its passphrase if it has one, unless a file gives it.
9376fn open<E: Environment>(
9377	directory: &Path,
9378	passphrase_file: Option<&Path>,
9379	environment: &mut E,
9380	timings: &mut Timings,
9381) -> Result<Library, CliError> {
9382	let started = Instant::now();
9383	let mut waited = Duration::ZERO;
9384	let (mut library, opening) = match Library::protection(directory)? {
9385		Protection::Passphrase { .. } => {
9386			let passphrase = if let Some(file) = passphrase_file {
9387				passphrase_in(file)?
9388			} else {
9389				let asked = Instant::now();
9390				let passphrase = environment.passphrase("Passphrase: ")?;
9391				waited = asked.elapsed();
9392				add(&mut timings.waiting, waited);
9393				passphrase
9394			};
9395			Library::open_timed(directory, &Unlocker::Passphrase(&passphrase))?
9396		}
9397		Protection::Keystore { .. } => {
9398			if !environment.keystore() {
9399				return Err(CliError::NoKeystore);
9400			}
9401			Library::open_timed(directory, &Unlocker::Keystore)?
9402		}
9403	};
9404	// Unlocking is everything but the waiting and the spaces: reading which protection the
9405	// keys have, reaching the keystore, and unlocking.
9406	add(
9407		&mut timings.unlock,
9408		started.elapsed().saturating_sub(waited + opening.spaces),
9409	);
9410	add(&mut timings.open, opening.spaces);
9411	library.make_thumbnails_with(Arc::new(RustDecoders));
9412	Ok(library)
9413}
9414
9415#[cfg(test)]
9416mod tests {
9417	use std::io::{self, Write};
9418
9419	use super::{CliError, UntilUnread, parse_size};
9420
9421	/// A writer that takes `room` bytes, then fails as `error` says.
9422	struct Closing {
9423		written: Vec<u8>,
9424		room: usize,
9425		error: io::ErrorKind,
9426	}
9427
9428	impl Write for Closing {
9429		fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
9430			if self.written.len() + bytes.len() > self.room {
9431				return Err(self.error.into());
9432			}
9433			self.written.extend_from_slice(bytes);
9434			Ok(bytes.len())
9435		}
9436
9437		fn flush(&mut self) -> io::Result<()> {
9438			Ok(())
9439		}
9440	}
9441
9442	#[test]
9443	fn output_that_nothing_reads_is_taken_and_not_written() {
9444		let closing = Closing {
9445			written: Vec::new(),
9446			room: 6,
9447			error: io::ErrorKind::BrokenPipe,
9448		};
9449		let mut output = UntilUnread::new(closing);
9450		writeln!(output, "first").expect("written");
9451		writeln!(output, "second").expect("taken");
9452		writeln!(output, "third").expect("taken");
9453		output.flush().expect("flushed");
9454		assert_eq!(output.inner.written, b"first\n");
9455		assert!(output.unread);
9456		// Other errors are errors.
9457		let mut full = UntilUnread::new(Closing {
9458			written: Vec::new(),
9459			room: 0,
9460			error: io::ErrorKind::StorageFull,
9461		});
9462		assert_eq!(
9463			writeln!(full, "first").expect_err("full").kind(),
9464			io::ErrorKind::StorageFull
9465		);
9466		assert!(!full.unread);
9467	}
9468
9469	#[test]
9470	fn sizes_are_read_in_bytes_and_units() {
9471		assert_eq!(parse_size("1073741824"), Ok(1 << 30));
9472		assert_eq!(parse_size("1GiB"), Ok(1 << 30));
9473		assert_eq!(parse_size("500 MB"), Ok(500_000_000));
9474		assert_eq!(parse_size("10b"), Ok(10));
9475		assert!(parse_size("1.5GB").is_err());
9476		assert!(parse_size("GB").is_err());
9477		assert!(parse_size("2PB").is_err());
9478		assert!(parse_size("99999999TiB").is_err());
9479		assert_eq!(super::output::size_text(1 << 30), "1 GiB");
9480		assert_eq!(super::output::size_text(500_000_000), "500 MB");
9481		assert_eq!(super::output::size_text(22), "22 bytes");
9482	}
9483
9484	#[test]
9485	fn an_unsound_library_counts_its_problems() {
9486		assert_eq!(
9487			CliError::Unsound(1).to_string(),
9488			"the library has a problem"
9489		);
9490		assert_eq!(
9491			CliError::Unsound(3).to_string(),
9492			"the library has 3 problems"
9493		);
9494	}
9495}