Skip to main content

cli/
lib.rs

1//! `mushroomdb` CLI library: hand-rolled arg parsing and the demo dataset builder.
2//!
3//! The binary in `main.rs` stays thin — it dispatches on [`parse_args`] and
4//! prints what the lib functions return.
5
6pub mod doctor;
7pub mod export;
8pub(crate) mod hook;
9pub mod ingest_git;
10pub mod install;
11pub mod recall;
12pub mod structure;
13
14#[cfg(test)]
15use core_api::restore::holds_a_store;
16/// Re-exported where it has always been named: `cli::RestoreOutcome`.
17pub use core_api::restore::RestoreOutcome;
18use core_api::schema::Schema;
19use core_api::{
20    default_max_edges, is_write_query, valid_namespace, AlgoDir, BackupReport, DegreeConfig,
21    Explanation, GraphDb, IngestOptions, LouvainConfig, PageRankConfig, Predicate, RealFs,
22    ResultSet, RuleDef, RuleSuggestion, SharedDb, SnapshotOptions, Stats, Value, WccConfig,
23    WriteGuard, NS_MAX_LEN,
24};
25use export::ExportFormat;
26use std::collections::BTreeMap;
27use std::fmt::Write as _;
28use std::net::SocketAddr;
29use std::path::{Path, PathBuf};
30use std::time::Duration;
31
32/// What every snapshot mushroomdb takes *on its own* does with the WAL.
33///
34/// An ingest that ends past the WAL threshold, a `serve --snapshot-every`
35/// tick, a graceful shutdown, and a plain `mushroomdb snapshot` all archive the
36/// WAL to `wal.<N>.archive` rather than dropping it. `node_history`,
37/// `edge_history`, `was_linked` and `open_at` all read WAL frames and all
38/// consult archives, so the store opens fast and still remembers how it got
39/// here. A truncating snapshot ends that reach — it deletes the genesis marker
40/// as well as the tail — so it is never something mushroomdb decides for the
41/// user: only `mushroomdb snapshot --truncate` does it.
42pub const AUTOMATIC_SNAPSHOT: SnapshotOptions = SnapshotOptions {
43    keep_wal: false,
44    archive_wal: true,
45};
46
47/// How many WAL archives a snapshot mushroomdb takes *on its own* keeps.
48/// `None` = all of them. Retention is configured, never defaulted: deleting
49/// history nobody asked to delete is not a default worth having.
50///
51/// Archiving moves the WAL aside rather than deleting it, so without a bound
52/// every automatic snapshot leaves one more file behind and nothing ever
53/// reclaims them. On a dogfooded repository that is a new archive per
54/// [`SNAPSHOT_WAL_BYTES`] of churn, for as long as the store exists — and that
55/// growth is the argument for the default, not against it: the reach archives
56/// exist to preserve — `node_history`, `edge_history`, `was_linked` — is
57/// exactly what pruning costs, so an automatic snapshot never volunteers to
58/// pay it. `mushroomdb stats` and `mushroomdb doctor` both print where history
59/// currently starts, and `mushroomdb snapshot <db> --retention N` is how a
60/// caller bounds the directory once they have decided the trade is worth it.
61///
62/// One consequence is worth stating plainly for whoever does set a bound,
63/// because it is not proportional. The first prune breaks the genesis chain,
64/// and `open_at` refuses any commit it cannot reconstruct from a complete
65/// prefix — so from that point it answers for commits past the last snapshot
66/// and no further, even though the retained archives still answer
67/// `node_history` and `was_linked` over their own window. Time travel to a
68/// point-in-time state is therefore bounded by the last snapshot once a store
69/// has churned this far; the history reads are bounded by the retention.
70///
71/// Only the automatic path takes this default. `mushroomdb snapshot` is a
72/// thing the user asked for, and `--retention N` is theirs to set: an
73/// explicit snapshot with no `--retention` still keeps every archive.
74///
75/// [`SNAPSHOT_WAL_BYTES`]: crate::ingest_git::SNAPSHOT_WAL_BYTES
76pub const AUTO_SNAPSHOT_RETENTION: Option<u32> = None;
77
78/// Take [`AUTOMATIC_SNAPSHOT`] under a held write lock, keeping
79/// [`AUTO_SNAPSHOT_RETENTION`] archives.
80///
81/// The single place the automatic disposition and the automatic bound are
82/// applied together, so no caller can pick up one without the other.
83///
84/// # Errors
85///
86/// Whatever writing the snapshot returned.
87pub fn snapshot_automatically(db: &mut WriteGuard<'_>) -> Result<(), core_api::GraphError> {
88    db.set_wal_archive_retention(AUTO_SNAPSHOT_RETENTION);
89    db.snapshot_with(AUTOMATIC_SNAPSHOT)
90}
91
92/// How long a server-initiated snapshot waits for the store's cross-process
93/// write lock before giving up.
94///
95/// Short on purpose. A snapshot is an optimisation — it shortens the next
96/// open's replay — so skipping one costs nothing but a longer replay, whereas
97/// blocking the shutdown path or piling up timer ticks behind a busy peer
98/// costs the operator.
99pub const SNAPSHOT_LOCK_WAIT: Duration = Duration::from_millis(500);
100
101/// Take the snapshot `serve` takes — on a `--snapshot-every` tick, and once
102/// more on a graceful shutdown.
103///
104/// Lives here rather than in `main.rs` so the behaviour a running server has is
105/// the behaviour a test can call. `Busy` is the caller's to interpret: a tick
106/// skips it, since the next one is only a period away.
107///
108/// # Errors
109///
110/// Whatever taking the write lock or writing the snapshot returned.
111pub fn snapshot_shared(db: &SharedDb) -> Result<(), core_api::GraphError> {
112    snapshot_automatically(&mut db.write_with_wait(SNAPSHOT_LOCK_WAIT)?)
113}
114
115/// Deterministic demo: 10 Orgs, 20 Projects, 30 People.
116pub const N_ORGS: usize = 10;
117pub const N_PROJECTS: usize = 20;
118pub const N_PEOPLE: usize = 30;
119
120/// Sample query printed by `mushroomdb demo` and executed against the fresh store.
121///
122/// Scoped to one person so `ORDER BY score DESC` is visibly ranked (a global
123/// `LIMIT 5` would be five 1.0 home-project hits).
124pub const SAMPLE_QUERY: &str = "\
125MATCH (p:Person {id: 'person-01'})-[r:FIT]->(proj:Project)
126RETURN p, proj, r.score AS score
127ORDER BY score DESC, proj";
128
129const SAMPLE_EXPLAIN_A: &str = "person-01";
130const SAMPLE_EXPLAIN_B: &str = "proj-01";
131
132/// Build version, printed by `mushroomdb --version`.
133pub const VERSION: &str = env!("CARGO_PKG_VERSION");
134
135/// The one line `--version` and the `version` subcommand print.
136#[must_use]
137pub fn version_string() -> String {
138    format!("mushroomdb {VERSION}")
139}
140
141/// Where `--auto` looks for a database, in order.
142///
143/// 1. `$CLAUDE_PROJECT_DIR/mushroom-memory` — the assistant tells a hook which
144///    project it is working in, and that is the most specific answer there is.
145/// 2. `<working-tree root>/mushroom-memory`, but only when the working
146///    directory is inside a git checkout. Without that guard a command run
147///    from a home directory would quietly create a store there.
148/// 3. `<home>/.mushroomdb/memory`, the user-scope default `install` writes.
149///
150/// The two project-scoped answers match [`install::default_db`],
151/// so a hook with `--auto` finds the store `install --project` created.
152#[must_use]
153pub fn resolve_auto_db(
154    env_project_dir: Option<&std::ffi::OsStr>,
155    cwd: &Path,
156    home: &Path,
157) -> PathBuf {
158    if let Some(dir) = env_project_dir.filter(|d| !d.is_empty()) {
159        return Path::new(dir).join("mushroom-memory");
160    }
161    if let Some(root) = worktree_root(cwd) {
162        return root.join("mushroom-memory");
163    }
164    home.join(".mushroomdb").join("memory")
165}
166
167/// The root of the working tree `dir` sits in: the nearest ancestor holding a
168/// `.git` entry, or `None` outside a checkout.
169///
170/// The answer is a *working tree* root, never the `.git` directory several
171/// worktrees share. A linked worktree keeps a `.git` **file** at its root
172/// (`gitdir: …/worktrees/<name>`) rather than a directory, and both spellings
173/// count here, so `git worktree add` produces a checkout that resolves to its
174/// own store. Two worktrees are two different sets of files, and a graph built
175/// from one answers questions about the other wrongly.
176///
177/// Walking up matters as much as the file/directory distinction: a hook fires
178/// with whatever working directory the tool call had, which is often a
179/// subdirectory, and only the root has the `.git` entry.
180#[must_use]
181pub fn worktree_root(dir: &Path) -> Option<&Path> {
182    dir.ancestors().find(|d| d.join(".git").exists())
183}
184
185/// How `serve` should mount a UI. Precedence: `--ui dir` > embedded > `--no-ui`.
186#[derive(Debug, Clone, PartialEq, Eq)]
187pub enum ServeUi {
188    Filesystem(PathBuf),
189    Embedded,
190    None,
191}
192
193/// Algorithm subcommand for `mushroomdb algo`.
194#[derive(Debug, Clone, PartialEq, Eq)]
195pub enum AlgoSubcmd {
196    Pagerank,
197    Wcc,
198    Degree,
199    Communities,
200}
201
202/// Parsed `mushroomdb` invocation.
203///
204/// No `Eq` derive: `Algo { min_weight: Option<f64>, .. }` carries a float.
205#[derive(Debug, Clone, PartialEq)]
206pub enum Command {
207    /// A hook body 0.6 installed and 0.7 retired: `touch`, `intercept`,
208    /// `impact-hook` and `enrich` in the assistant's settings, `sync` in the
209    /// git hooks. A machine that upgraded without re-running `install` still
210    /// calls them, so each is accepted with any arguments, opens nothing, and
211    /// prints one stderr line saying how to remove it. Never in [`usage`].
212    RetiredHook {
213        sub: &'static str,
214    },
215    Serve {
216        db_dir: PathBuf,
217        addr: SocketAddr,
218        ui: ServeUi,
219        /// If the db dir is missing or empty, run [`run_demo`] before serving.
220        /// Docker's default CMD uses this so a fresh volume is ready on first boot.
221        demo_if_empty: bool,
222        /// Bearer token for non-loopback binds. Loopback may omit it.
223        token: Option<String>,
224        /// Role-bound tokens from `--role-token TOKEN:ROLE` flags.
225        /// Merged with `MUSHROOMDB_ROLE_TOKENS` env var in main before serving.
226        role_tokens: Vec<(String, String)>,
227        /// Periodic snapshot cadence. `None` = off (default).
228        snapshot_every: Option<Duration>,
229        /// Seed an empty `db_dir` from the newest backup under this directory
230        /// before opening it. See [`restore_if_empty`]. `None` = off (default).
231        restore_from: Option<PathBuf>,
232        /// Path to PEM certificate for native TLS (`--tls-cert`). Requires `--tls-key`.
233        tls_cert: Option<PathBuf>,
234        /// Path to PEM private key for native TLS (`--tls-key`). Requires `--tls-cert`.
235        tls_key: Option<PathBuf>,
236    },
237    Mcp {
238        /// `None` with `auto` set: resolved by [`resolve_auto_db`] at run time.
239        db_dir: Option<PathBuf>,
240        auto: bool,
241        /// `--all-tools`: advertise every served tool in `tools/list`
242        /// rather than the association tools every store lists by default. The rest are
243        /// callable either way; the flag decides what is listed, and what every
244        /// session pays for before its first turn.
245        all_tools: bool,
246    },
247    Stats {
248        db_dir: PathBuf,
249    },
250    Demo {
251        db_dir: PathBuf,
252    },
253    /// Read-only view of the database at a past commit.
254    AsOf {
255        db_dir: PathBuf,
256        /// 0-based WAL commit index to replay up to (inclusive).
257        ///
258        /// Exactly one of `commit` and `at` is set — the parser refuses both and
259        /// refuses neither, because a precedence rule between them is how a
260        /// caller ends up believing it asked for a date while the engine
261        /// answered a commit.
262        commit: Option<u64>,
263        /// RFC 3339 date to replay up to, resolved against the store's recorded
264        /// commit times once it is open.
265        at: Option<String>,
266        /// Optional Cypher read query to execute against the as-of view.
267        query: Option<String>,
268        /// Read only this namespace, as it was at that commit.
269        namespace: Option<String>,
270    },
271    /// Profile the database and suggest linking rules with estimated edge counts.
272    Suggest {
273        db_dir: PathBuf,
274    },
275    /// Run a graph algorithm (pagerank / wcc / degree / communities).
276    Algo {
277        db_dir: PathBuf,
278        subcmd: AlgoSubcmd,
279        /// Print only the top N results (0 = all).
280        top: usize,
281        /// Edge direction for degree/pagerank (`out` / `in` / `both`).
282        /// Ignored by `wcc` and `communities`, which are always undirected.
283        dir: AlgoDir,
284        /// `communities` only: restrict to the union of these edge types
285        /// (`--edge-type T`, repeatable). Empty means all edge types.
286        edge_types: Vec<String>,
287        /// `communities` only: edge property to read as the edge weight.
288        weight_prop: Option<String>,
289        /// `communities` only: drop edges below this resolved weight.
290        min_weight: Option<f64>,
291    },
292    /// Run a Cypher query (read or write).
293    Query {
294        db_dir: PathBuf,
295        /// Positional after dir (remaining args joined), or `--query`.
296        cypher: String,
297        /// Answer as one of the store's roles: only the nodes it may see.
298        role: Option<String>,
299        /// Answer from one namespace only. Intersects `role` — never widens it.
300        namespace: Option<String>,
301    },
302    /// Write `snapshot.bin`. The WAL is archived unless told otherwise.
303    Snapshot {
304        db_dir: PathBuf,
305        wal: WalDisposition,
306        /// Keep the newest N archives; prune oldest at snapshot time.
307        /// None = unlimited. Applies only when the WAL is archived.
308        retention: Option<u32>,
309    },
310    /// Drive any outstanding vector-index build to completion.
311    BuildIndex {
312        db_dir: PathBuf,
313        /// Build only this rule; `None` builds every pending one.
314        rule: Option<String>,
315    },
316    /// Apply a JSON schema file idempotently (`schema apply <db-dir> <schema.json>`),
317    /// the built-in memory schema (`schema apply <db-dir> --memory-defaults`), or
318    /// the identity preset (`schema apply <db-dir> --memory-identity`).
319    SchemaApply {
320        db_dir: PathBuf,
321        /// `None` when a built-in was named instead.
322        schema_file: Option<PathBuf>,
323        memory_defaults: bool,
324        memory_identity: bool,
325    },
326    /// Migrate an old-format snapshot to the current version and keep `.bak`.
327    Migrate {
328        db_dir: PathBuf,
329    },
330    /// Validate CRC32 integrity of every section in the V8 snapshot.
331    Verify {
332        db_dir: PathBuf,
333    },
334    /// Create a consistent, verified copy of the database directory.
335    Backup {
336        db_dir: PathBuf,
337        dest: PathBuf,
338    },
339    /// Export all nodes, edges, and rules to a destination directory.
340    Export {
341        db_dir: PathBuf,
342        dest: PathBuf,
343        format: ExportFormat,
344    },
345    /// Build (or incrementally sync) a graph of a git repository.
346    IngestGit {
347        db_dir: PathBuf,
348        opts: ingest_git::IngestGitOpts,
349    },
350    /// Wire the /mushroom skill and MCP server into Claude Code / Cursor.
351    Install(install::InstallOpts),
352    /// Undo what `install` wrote (manifest-driven).
353    Uninstall(install::InstallOpts),
354    /// Turn an install off without removing it: strips the hooks, the MCP
355    /// entry and the git hook blocks; the skill, the store and the
356    /// `.gitignore` line stay.
357    Disable(install::ToggleOpts),
358    /// Turn a disabled install back on, re-deriving the dynamic parts (the
359    /// resolved command, the hooks) rather than replaying stale ones.
360    Enable(install::ToggleOpts),
361    /// Verify an install end to end: config, store, hooks, and a real MCP handshake.
362    Doctor(doctor::DoctorOpts),
363    /// Body of the Claude Code UserPromptSubmit hook: reads a prompt payload on
364    /// stdin, prints related graph facts on stdout.
365    Recall {
366        db_dir: Option<PathBuf>,
367        auto: bool,
368    },
369    /// Body of the Claude Code SessionStart hook: prints the repository in one
370    /// byte-stable block, which the host caches for the whole session.
371    Brief {
372        db_dir: Option<PathBuf>,
373        auto: bool,
374    },
375    /// What links two nodes, with the evidence behind each link.
376    Why {
377        db_dir: PathBuf,
378        a: String,
379        b: String,
380    },
381    Version,
382    Help,
383}
384
385/// Outcome of [`run_demo`]. Counts are deterministic.
386#[derive(Debug)]
387pub struct DemoOutcome {
388    pub auto_fk_rules: Vec<String>,
389    pub sample_query: String,
390    pub sample_result: ResultSet,
391    pub explanations: Vec<Explanation>,
392    pub stats: Stats,
393    /// First suggestion from the rule suggester (teaser only — not auto-applied).
394    pub suggestion: Option<RuleSuggestion>,
395}
396
397/// CLI-facing error. [`Display`] is the message printed to stderr.
398#[derive(Debug)]
399pub struct CliError(pub String);
400
401impl std::fmt::Display for CliError {
402    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
403        f.write_str(&self.0)
404    }
405}
406
407impl std::error::Error for CliError {}
408
409impl From<core_api::GraphError> for CliError {
410    fn from(e: core_api::GraphError) -> Self {
411        CliError(e.to_string())
412    }
413}
414
415impl From<std::io::Error> for CliError {
416    fn from(e: std::io::Error) -> Self {
417        CliError(e.to_string())
418    }
419}
420
421/// Usage text for no-args / `--help` / `-h`.
422pub fn usage() -> &'static str {
423    "\
424mushroomdb — embedded graph database
425
426Usage:
427  mushroomdb install [--platform claude-code|cursor|codex|all] [--project|--user] [--db <path>]
428                     [--command <path>] [--no-prewarm] [--delivery cli|mcp|both]
429                     [--always-load|--no-always-load]
430                     --delivery cli writes the skill and the hooks and registers no MCP
431                     server: the skill teaches `mushroomdb <command>` instead (claude-code
432                     only; cursor and codex are always registered as MCP servers)
433                     --always-load marks the registered MCP server alwaysLoad, so the host
434                     keeps its tools in context instead of deferring them; already the
435                     default when --db names a store and a server is registered
436                     (--delivery mcp|both) — --no-always-load opts out
437  mushroomdb uninstall [--platform claude-code|cursor|codex|all] [--project|--user] [--db <path>]
438  mushroomdb disable [--platform claude-code|cursor|codex|all] [--project|--user]
439                     turn an install off without removing it: hooks and MCP entry are
440                     removed; the skill, the store and .gitignore stay
441  mushroomdb enable [--platform claude-code|cursor|codex|all] [--project|--user]
442                     turn a disabled install back on
443  mushroomdb doctor [--project|--user] [--platform claude-code|cursor|codex|all]
444                     verify an install: config entry, store, hooks, and a real stdio
445                     handshake with the configured MCP command; exits 1 on any `fail`
446  mushroomdb serve <db-dir> [--addr 127.0.0.1:8080] [--token <secret>] [--role-token TOKEN:ROLE] [--ui <dist-dir>] [--no-ui] [--demo-if-empty] [--snapshot-every <secs>] [--restore-from <dir>] [--tls-cert <pem> --tls-key <pem>]
447                     --restore-from seeds an empty <db-dir> from the newest backup under <dir>
448                     (or from <dir> itself if it is one); a no-op when <db-dir> already holds a store
449                     --tls-cert and --tls-key go together and need a build with the `tls` feature
450  mushroomdb mcp <db-dir>|--auto [--all-tools]
451                     --all-tools lists every served tool; the default lists the association tools on every store,
452                     a store `ingest-git` built included (the rest stay callable, just unlisted)
453  mushroomdb stats <db-dir>
454  mushroomdb demo <db-dir>
455  mushroomdb recall <db-dir>|--auto   hook body: reads a prompt payload on stdin, prints related graph facts
456  mushroomdb brief <db-dir>|--auto    hook body: the store's schema in one block — labels,
457                                      edge types, history depth, roles and one worked call per
458                                      question kind; byte-stable, so a session host caches it once
459  mushroomdb why <db-dir> <a> <b>
460                                   every rule edge between two keys with the evidence that
461                                   derived it, or a note that there is none
462  mushroomdb suggest <db-dir>
463  mushroomdb asof <db-dir> --commit N|--at <date> [--query \"MATCH ...\"] [--namespace <ns>]
464                     --at takes an RFC 3339 date (2026-06-19, or 2026-06-19T12:00:00Z)
465                     and resolves to the last commit at or before it; exactly one of
466                     --commit and --at
467  mushroomdb query <db-dir> [--query \"MATCH ...\"] [--role <name>] [--namespace <ns>] <cypher…>
468                     --role answers as one of the store's roles and --namespace from one
469                     namespace; together they intersect, so neither ever widens the other
470                     and either one makes the query a read
471  mushroomdb snapshot <db-dir> [--keep-wal|--truncate] [--retention N]
472                     folds the WAL into snapshot.bin and archives it as wal.<N>.archive,
473                     so node_history, edge_history, was_linked and asof keep reaching it;
474                     --truncate discards it instead, --keep-wal leaves wal.bin whole
475  mushroomdb build-index <db-dir> [--rule <name>]
476                     drives a rule's vector index to completion a slice at a time, for an
477                     operator who wants the build finished before traffic arrives; a rule
478                     created over a large corpus derives no edges until its index is whole
479  mushroomdb migrate <db-dir>
480  mushroomdb verify <db-dir>       validate CRC32 integrity of every snapshot section
481  mushroomdb backup <db-dir> <dest>   process-local consistent copy of the database to <dest>
482                                      WARNING: unsafe against a concurrently running serve process;
483                                      use POST /backup on the HTTP server for live-serve backups
484  mushroomdb export <db-dir> <dest> --format jsonl|parquet|graphml   export all data
485                                      graphml writes one file: <dest>/graph.graphml if <dest> is an
486                                      existing directory, otherwise <dest> is the file path itself
487                                      (nodes + edges only; rules have no GraphML analogue)
488  mushroomdb ingest-git <db-dir> <repo-dir> [--exclude <pattern>]... [--max-commits-per-file N]
489                        [--recurse-submodules] [--prs] [--no-structure] [--no-docs] [--ensure-gitignore]
490                                   graph a git repo (authors, commits, files, symbols, imports, calls, mentions); re-run to sync
491                                   --recurse-submodules also walks each initialised submodule
492                                   --prs links merged pull requests via gh (skipped when gh is unavailable)
493                                   --no-structure skips the working-tree pass (no hashes, symbols, imports or calls)
494                                   --no-docs skips Markdown bodies, headings and mentions
495                                   --ensure-gitignore adds the database directory to the repo's .gitignore
496                                   with no --exclude the defaults apply: target/ node_modules/ dist/ .git/ *.lock *.min.js
497  mushroomdb schema apply <db-dir> <schema.json>
498  mushroomdb schema apply <db-dir> --memory-defaults
499                                   applies the built-in memory schema to an existing store;
500                                   full-text on a populated store rebuilds the index at every open from here on
501  mushroomdb schema apply <db-dir> --memory-identity
502                                   adds the identity preset: sixteen SAME_AS rules over each entity's aliases;
503                                   says what it will backfill, then backfills
504  mushroomdb algo pagerank <db-dir> [--top N] [--dir out|in|both]
505  mushroomdb algo wcc <db-dir> [--top N]
506  mushroomdb algo degree <db-dir> [--top N] [--dir out|in|both]
507  mushroomdb algo communities <db-dir> [--edge-type T]... [--weight-prop P] [--min-weight X] [--top N]
508  mushroomdb --version
509  mushroomdb --help
510
511Default serve address is 127.0.0.1:8080. Non-loopback --addr requires --token or MUSHROOMDB_TOKEN.
512install defaults: --platform auto-detect; scope auto (project inside a git checkout, else user);
513the MCP entry runs `npx -y mushroomdb@<version>` unless a `mushroomdb` on PATH is this binary, or
514--command names one (a relative --command or --db is anchored to the current directory).
515--no-prewarm means no network and no resolution: neither the one-off package fetch nor locating the
516package's binary, so every hook keeps the slower `npx` form.
517install and uninstall take out the code-graph hooks and git hook blocks a 0.6 install wrote.
518uninstall resolves the same scope and falls back to the other one when the inferred scope has no
519manifest; undoing a Codex install needs --platform codex.
520A project install inside a git checkout writes --auto rather than a store path, so each `git
521worktree` gets its own store; outside a checkout, and with --db, the store is pinned to an absolute
522path instead.
523--auto resolves the database as $CLAUDE_PROJECT_DIR/mushroom-memory, else mushroom-memory at the
524root of the working tree the current directory is in, else ~/.mushroomdb/memory.
525"
526}
527
528fn parse_install_cmd(args: &[&str]) -> Result<install::InstallOpts, String> {
529    let mut platform: Option<install::Platform> = None;
530    let mut scope: Option<install::Scope> = None;
531    let mut db: Option<PathBuf> = None;
532    let mut command: Option<PathBuf> = None;
533    let mut prewarm = true;
534    let mut delivery = install::Delivery::default();
535    // Tri-state on purpose: `None` is "the user said nothing", which is the
536    // only case the default below is allowed to decide.
537    let mut always_load: Option<bool> = None;
538    let mut i = 0;
539    while i < args.len() {
540        let a = args[i];
541        if a == "--delivery" {
542            let val = args
543                .get(i + 1)
544                .copied()
545                .ok_or_else(|| "missing value for --delivery".to_string())?;
546            delivery = install::Delivery::parse(val)?;
547            i += 2;
548        } else if let Some(val) = a.strip_prefix("--delivery=") {
549            delivery = install::Delivery::parse(val)?;
550            i += 1;
551        } else if a == "--platform" {
552            let val = args
553                .get(i + 1)
554                .copied()
555                .ok_or_else(|| "missing value for --platform".to_string())?;
556            platform = Some(install::Platform::parse(val)?);
557            i += 2;
558        } else if let Some(val) = a.strip_prefix("--platform=") {
559            platform = Some(install::Platform::parse(val)?);
560            i += 1;
561        } else if a == "--project" || a == "--user" {
562            let want = if a == "--project" {
563                install::Scope::Project
564            } else {
565                install::Scope::User
566            };
567            // Two scopes name two different installs; picking one silently
568            // would put files somewhere the user did not ask for.
569            if scope.is_some_and(|s| s != want) {
570                return Err("--project and --user are mutually exclusive".to_string());
571            }
572            scope = Some(want);
573            i += 1;
574        } else if a == "--no-git-hooks" {
575            // Accepted and ignored: 0.7 writes no git hooks, so "none" is
576            // already what every install gets. Refusing it would break every
577            // script that passed it to a 0.6 install for the same result.
578            i += 1;
579        } else if a == "--intercept-grep" || a == "--impact-before-edit" || a == "--enrich-grep" {
580            return Err(format!(
581                "{a} was removed in 0.7 along with the code graph it fed. \
582                 Nothing replaces it. Pin `mushroomdb@0.6.x` to keep it."
583            ));
584        } else if a == "--always-load" {
585            always_load = Some(true);
586            i += 1;
587        } else if a == "--no-always-load" {
588            always_load = Some(false);
589            i += 1;
590        } else if a == "--no-prewarm" {
591            prewarm = false;
592            i += 1;
593        } else if a == "--command" {
594            let val = args
595                .get(i + 1)
596                .copied()
597                .ok_or_else(|| "missing value for --command".to_string())?;
598            command = Some(PathBuf::from(val));
599            i += 2;
600        } else if let Some(val) = a.strip_prefix("--command=") {
601            command = Some(PathBuf::from(val));
602            i += 1;
603        } else if a == "--db" {
604            let val = args
605                .get(i + 1)
606                .copied()
607                .ok_or_else(|| "missing value for --db".to_string())?;
608            db = Some(PathBuf::from(val));
609            i += 2;
610        } else if let Some(val) = a.strip_prefix("--db=") {
611            db = Some(PathBuf::from(val));
612            i += 1;
613        } else if a.starts_with('-') {
614            return Err(format!("unexpected flag: {a}"));
615        } else {
616            return Err(format!("unexpected argument: {a}"));
617        }
618    }
619    // An install that named its store with `--db` and registers a server is
620    // an entity-store install: the session is being pointed at a graph it
621    // could not otherwise find, and the first association run showed what a
622    // deferred tool list costs it — turns spent searching for the tools
623    // before the first question. So `alwaysLoad` is the default there, and
624    // `--no-always-load` is the way out.
625    //
626    // An install with no `--db` takes whatever store the working directory
627    // resolves to, which is usually the code graph: three tools, a skill that
628    // teaches them, and no discovery problem worth pinning context for. That
629    // one stays opt-in through `--always-load`.
630    let always_load =
631        always_load.unwrap_or(db.is_some() && !matches!(delivery, install::Delivery::Cli));
632    Ok(install::InstallOpts {
633        platform,
634        scope,
635        db,
636        command,
637        prewarm,
638        delivery,
639        always_load,
640    })
641}
642
643fn parse_doctor_cmd(args: &[&str]) -> Result<doctor::DoctorOpts, String> {
644    let mut platform: Option<install::Platform> = None;
645    let mut scope: Option<install::Scope> = None;
646    let mut i = 0;
647    while i < args.len() {
648        let a = args[i];
649        if a == "--platform" {
650            let val = args
651                .get(i + 1)
652                .copied()
653                .ok_or_else(|| "missing value for --platform".to_string())?;
654            platform = Some(install::Platform::parse(val)?);
655            i += 2;
656        } else if let Some(val) = a.strip_prefix("--platform=") {
657            platform = Some(install::Platform::parse(val)?);
658            i += 1;
659        } else if a == "--project" || a == "--user" {
660            let want = if a == "--project" {
661                install::Scope::Project
662            } else {
663                install::Scope::User
664            };
665            if scope.is_some_and(|s| s != want) {
666                return Err("--project and --user are mutually exclusive".to_string());
667            }
668            scope = Some(want);
669            i += 1;
670        } else if a.starts_with('-') {
671            return Err(format!("unexpected flag: {a}"));
672        } else {
673            return Err(format!("unexpected argument: {a}"));
674        }
675    }
676    Ok(doctor::DoctorOpts { platform, scope })
677}
678
679/// Shared by `mushroomdb enable` and `mushroomdb disable`: the same
680/// `--platform` / `--project` / `--user` flags `doctor` takes, and nothing
681/// else — neither command chooses a store or a binary, so there is no `--db`
682/// or `--command` to parse.
683fn parse_toggle_cmd(args: &[&str]) -> Result<install::ToggleOpts, String> {
684    let mut platform: Option<install::Platform> = None;
685    let mut scope: Option<install::Scope> = None;
686    let mut i = 0;
687    while i < args.len() {
688        let a = args[i];
689        if a == "--platform" {
690            let val = args
691                .get(i + 1)
692                .copied()
693                .ok_or_else(|| "missing value for --platform".to_string())?;
694            platform = Some(install::Platform::parse(val)?);
695            i += 2;
696        } else if let Some(val) = a.strip_prefix("--platform=") {
697            platform = Some(install::Platform::parse(val)?);
698            i += 1;
699        } else if a == "--project" || a == "--user" {
700            let want = if a == "--project" {
701                install::Scope::Project
702            } else {
703                install::Scope::User
704            };
705            if scope.is_some_and(|s| s != want) {
706                return Err("--project and --user are mutually exclusive".to_string());
707            }
708            scope = Some(want);
709            i += 1;
710        } else if a.starts_with('-') {
711            return Err(format!("unexpected flag: {a}"));
712        } else {
713            return Err(format!("unexpected argument: {a}"));
714        }
715    }
716    Ok(install::ToggleOpts { platform, scope })
717}
718
719fn parse_ingest_git(args: &[&str]) -> Result<Command, String> {
720    let mut positional = Vec::new();
721    let mut exclude = Vec::new();
722    let mut max_commits_per_file = ingest_git::DEFAULT_MAX_COMMITS_PER_FILE;
723    let mut recurse_submodules = false;
724    let mut prs = false;
725    let mut structure = true;
726    let mut docs = true;
727    let mut ensure_gitignore = false;
728    let mut i = 0;
729    while i < args.len() {
730        let a = args[i];
731        if a == "--recurse-submodules" {
732            recurse_submodules = true;
733            i += 1;
734        } else if a == "--prs" {
735            prs = true;
736            i += 1;
737        } else if a == "--no-structure" {
738            structure = false;
739            i += 1;
740        } else if a == "--no-docs" {
741            docs = false;
742            i += 1;
743        } else if a == "--ensure-gitignore" {
744            ensure_gitignore = true;
745            i += 1;
746        } else if a == "--exclude" {
747            exclude.push(
748                args.get(i + 1)
749                    .copied()
750                    .ok_or_else(|| "missing value for --exclude".to_string())?
751                    .to_string(),
752            );
753            i += 2;
754        } else if let Some(val) = a.strip_prefix("--exclude=") {
755            exclude.push(val.to_string());
756            i += 1;
757        } else if a == "--max-commits-per-file" {
758            let val = args
759                .get(i + 1)
760                .copied()
761                .ok_or_else(|| "missing value for --max-commits-per-file".to_string())?;
762            max_commits_per_file = val
763                .parse()
764                .map_err(|e| format!("bad --max-commits-per-file: {e}"))?;
765            i += 2;
766        } else if let Some(val) = a.strip_prefix("--max-commits-per-file=") {
767            max_commits_per_file = val
768                .parse()
769                .map_err(|e| format!("bad --max-commits-per-file: {e}"))?;
770            i += 1;
771        } else if a.starts_with('-') {
772            return Err(format!("unexpected flag: {a}"));
773        } else {
774            positional.push(a);
775            i += 1;
776        }
777    }
778    let [db_dir, repo] = positional.as_slice() else {
779        return Err("ingest-git requires <db-dir> <repo-dir>".into());
780    };
781    // Structure ingest reads the working tree, where a repository carries
782    // build output and vendored dependencies that its history does not. A user
783    // who states any pattern of their own is taken to mean exactly that set.
784    if exclude.is_empty() {
785        exclude = ingest_git::DEFAULT_EXCLUDES
786            .iter()
787            .map(|p| (*p).to_string())
788            .collect();
789    }
790    Ok(Command::IngestGit {
791        db_dir: PathBuf::from(db_dir),
792        opts: ingest_git::IngestGitOpts {
793            repo: PathBuf::from(repo),
794            exclude,
795            max_commits_per_file,
796            recurse_submodules,
797            prs,
798            structure,
799            docs,
800            ensure_gitignore,
801        },
802    })
803}
804
805/// Parse argv after the binary name. Hand-rolled — no clap.
806pub fn parse_args<S: AsRef<str>>(args: &[S]) -> Result<Command, String> {
807    let args: Vec<&str> = args.iter().map(AsRef::as_ref).collect();
808    if args.is_empty() {
809        return Ok(Command::Help);
810    }
811    match args[0] {
812        "--help" | "-h" | "help" => Ok(Command::Help),
813        "--version" | "-V" | "version" => Ok(Command::Version),
814        "serve" => parse_serve(&args[1..]),
815        "mcp" => parse_mcp(&args[1..]),
816        "stats" => parse_one_dir("stats", &args[1..]).map(|db_dir| Command::Stats { db_dir }),
817        "demo" => parse_one_dir("demo", &args[1..]).map(|db_dir| Command::Demo { db_dir }),
818        "suggest" => parse_one_dir("suggest", &args[1..]).map(|db_dir| Command::Suggest { db_dir }),
819        "asof" => parse_asof(&args[1..]),
820        "algo" => parse_algo(&args[1..]),
821        "query" => parse_query(&args[1..]),
822        "snapshot" => parse_snapshot(&args[1..]),
823        "build-index" => parse_build_index(&args[1..]),
824        "schema" => parse_schema(&args[1..]),
825        "migrate" => parse_one_dir("migrate", &args[1..]).map(|db_dir| Command::Migrate { db_dir }),
826        "verify" => parse_one_dir("verify", &args[1..]).map(|db_dir| Command::Verify { db_dir }),
827        "backup" => parse_backup(&args[1..]),
828        "export" => parse_export(&args[1..]),
829        "recall" => parse_dir_or_auto("recall", &args[1..])
830            .map(|(db_dir, auto)| Command::Recall { db_dir, auto }),
831        "brief" => parse_dir_or_auto("brief", &args[1..])
832            .map(|(db_dir, auto)| Command::Brief { db_dir, auto }),
833        "why" => parse_positional("why", &args[1..], 2, 2).map(|(db_dir, rest)| Command::Why {
834            db_dir,
835            a: rest[0].clone(),
836            b: rest[1].clone(),
837        }),
838        "ingest-git" => parse_ingest_git(&args[1..]),
839        "install" => parse_install_cmd(&args[1..]).map(Command::Install),
840        "uninstall" => parse_install_cmd(&args[1..]).map(Command::Uninstall),
841        "disable" => parse_toggle_cmd(&args[1..]).map(Command::Disable),
842        "enable" => parse_toggle_cmd(&args[1..]).map(Command::Enable),
843        "doctor" => parse_doctor_cmd(&args[1..]).map(Command::Doctor),
844        // Arguments are not parsed: whatever a 0.6 install wrote after the
845        // subcommand, the answer is the same.
846        "touch" => Ok(Command::RetiredHook { sub: "touch" }),
847        "intercept" => Ok(Command::RetiredHook { sub: "intercept" }),
848        "impact-hook" => Ok(Command::RetiredHook { sub: "impact-hook" }),
849        "enrich" => Ok(Command::RetiredHook { sub: "enrich" }),
850        "sync" => Ok(Command::RetiredHook { sub: "sync" }),
851        other => Err(format!("unknown command: {other}")),
852    }
853}
854
855fn default_addr() -> SocketAddr {
856    SocketAddr::from(([127, 0, 0, 1], 8080))
857}
858
859fn parse_serve(args: &[&str]) -> Result<Command, String> {
860    let mut db_dir = None;
861    let mut addr = default_addr();
862    let mut ui = ServeUi::Embedded;
863    let mut saw_ui = false;
864    let mut saw_no_ui = false;
865    let mut demo_if_empty = false;
866    let mut token = None;
867    let mut role_tokens: Vec<(String, String)> = Vec::new();
868    let mut snapshot_every = None;
869    let mut restore_from: Option<PathBuf> = None;
870    let mut tls_cert: Option<PathBuf> = None;
871    let mut tls_key: Option<PathBuf> = None;
872    let mut i = 0;
873    while i < args.len() {
874        let a = args[i];
875        if a == "--addr" {
876            let val = args
877                .get(i + 1)
878                .copied()
879                .ok_or_else(|| "missing value for --addr".to_string())?;
880            addr = val.parse().map_err(|_| format!("invalid address: {val}"))?;
881            i += 2;
882        } else if let Some(val) = a.strip_prefix("--addr=") {
883            addr = val.parse().map_err(|_| format!("invalid address: {val}"))?;
884            i += 1;
885        } else if a == "--ui" {
886            let val = args
887                .get(i + 1)
888                .copied()
889                .ok_or_else(|| "missing value for --ui".to_string())?;
890            ui = ServeUi::Filesystem(PathBuf::from(val));
891            saw_ui = true;
892            i += 2;
893        } else if let Some(val) = a.strip_prefix("--ui=") {
894            ui = ServeUi::Filesystem(PathBuf::from(val));
895            saw_ui = true;
896            i += 1;
897        } else if a == "--no-ui" {
898            ui = ServeUi::None;
899            saw_no_ui = true;
900            i += 1;
901        } else if a == "--demo-if-empty" {
902            demo_if_empty = true;
903            i += 1;
904        } else if a == "--token" {
905            let val = args
906                .get(i + 1)
907                .copied()
908                .ok_or_else(|| "missing value for --token".to_string())?;
909            token = Some(val.to_string());
910            i += 2;
911        } else if let Some(val) = a.strip_prefix("--token=") {
912            token = Some(val.to_string());
913            i += 1;
914        } else if a == "--role-token" {
915            let val = args
916                .get(i + 1)
917                .copied()
918                .ok_or_else(|| "missing value for --role-token".to_string())?;
919            let (tok, role) = parse_role_token(val)?;
920            role_tokens.push((tok, role));
921            i += 2;
922        } else if let Some(val) = a.strip_prefix("--role-token=") {
923            let (tok, role) = parse_role_token(val)?;
924            role_tokens.push((tok, role));
925            i += 1;
926        } else if a == "--snapshot-every" {
927            let val = args
928                .get(i + 1)
929                .copied()
930                .ok_or_else(|| "missing value for --snapshot-every".to_string())?;
931            snapshot_every = Some(parse_snapshot_every(val)?);
932            i += 2;
933        } else if let Some(val) = a.strip_prefix("--snapshot-every=") {
934            snapshot_every = Some(parse_snapshot_every(val)?);
935            i += 1;
936        } else if a == "--restore-from" {
937            let val = args
938                .get(i + 1)
939                .copied()
940                .ok_or_else(|| "missing value for --restore-from".to_string())?;
941            restore_from = Some(PathBuf::from(val));
942            i += 2;
943        } else if let Some(val) = a.strip_prefix("--restore-from=") {
944            restore_from = Some(PathBuf::from(val));
945            i += 1;
946        } else if a == "--tls-cert" {
947            let val = args
948                .get(i + 1)
949                .copied()
950                .ok_or_else(|| "missing value for --tls-cert".to_string())?;
951            tls_cert = Some(PathBuf::from(val));
952            i += 2;
953        } else if let Some(val) = a.strip_prefix("--tls-cert=") {
954            tls_cert = Some(PathBuf::from(val));
955            i += 1;
956        } else if a == "--tls-key" {
957            let val = args
958                .get(i + 1)
959                .copied()
960                .ok_or_else(|| "missing value for --tls-key".to_string())?;
961            tls_key = Some(PathBuf::from(val));
962            i += 2;
963        } else if let Some(val) = a.strip_prefix("--tls-key=") {
964            tls_key = Some(PathBuf::from(val));
965            i += 1;
966        } else if a.starts_with('-') {
967            return Err(format!("unexpected flag: {a}"));
968        } else if db_dir.is_none() {
969            db_dir = Some(PathBuf::from(a));
970            i += 1;
971        } else {
972            return Err(format!("unexpected extra argument: {a}"));
973        }
974    }
975    if saw_ui && saw_no_ui {
976        return Err("cannot combine --ui and --no-ui".to_string());
977    }
978    match (&tls_cert, &tls_key) {
979        (Some(_), None) => return Err("--tls-cert requires --tls-key".to_string()),
980        (None, Some(_)) => return Err("--tls-key requires --tls-cert".to_string()),
981        _ => {}
982    }
983    let db_dir = db_dir.ok_or_else(|| "serve requires <db-dir>".to_string())?;
984    Ok(Command::Serve {
985        db_dir,
986        addr,
987        ui,
988        demo_if_empty,
989        token,
990        role_tokens,
991        snapshot_every,
992        restore_from,
993        tls_cert,
994        tls_key,
995    })
996}
997
998fn parse_role_token(val: &str) -> Result<(String, String), String> {
999    let (tok, role) = val
1000        .split_once(':')
1001        .ok_or_else(|| format!("--role-token requires TOKEN:ROLE format, got: {val}"))?;
1002    if tok.is_empty() {
1003        return Err("--role-token: TOKEN must not be empty".to_string());
1004    }
1005    if role.is_empty() {
1006        return Err("--role-token: ROLE must not be empty".to_string());
1007    }
1008    Ok((tok.to_string(), role.to_string()))
1009}
1010
1011fn parse_snapshot_every(val: &str) -> Result<Duration, String> {
1012    let secs: u64 = val
1013        .parse()
1014        .map_err(|_| format!("invalid --snapshot-every: {val}"))?;
1015    if secs == 0 {
1016        return Err("--snapshot-every must be a positive number of seconds".into());
1017    }
1018    Ok(Duration::from_secs(secs))
1019}
1020
1021/// `--ui <dir>` must be a directory that contains `index.html`.
1022pub fn validate_ui_dir(dir: &Path) -> Result<PathBuf, String> {
1023    if !dir.is_dir() {
1024        return Err(format!("--ui directory does not exist: {}", dir.display()));
1025    }
1026    let index = dir.join("index.html");
1027    if !index.is_file() {
1028        return Err(format!(
1029            "--ui directory is missing index.html: {}",
1030            dir.display()
1031        ));
1032    }
1033    Ok(dir.to_path_buf())
1034}
1035
1036fn parse_asof(args: &[&str]) -> Result<Command, String> {
1037    let mut db_dir = None;
1038    let mut commit: Option<u64> = None;
1039    let mut at: Option<String> = None;
1040    let mut query: Option<String> = None;
1041    let mut namespace: Option<String> = None;
1042    let mut i = 0;
1043    while i < args.len() {
1044        let a = args[i];
1045        if a == "--at" {
1046            let val = args
1047                .get(i + 1)
1048                .copied()
1049                .ok_or_else(|| "missing value for --at".to_string())?;
1050            at = Some(val.to_string());
1051            i += 2;
1052        } else if let Some(val) = a.strip_prefix("--at=") {
1053            at = Some(val.to_string());
1054            i += 1;
1055        } else if a == "--commit" {
1056            let val = args
1057                .get(i + 1)
1058                .copied()
1059                .ok_or_else(|| "missing value for --commit".to_string())?;
1060            commit = Some(
1061                val.parse()
1062                    .map_err(|_| format!("invalid commit index: {val}"))?,
1063            );
1064            i += 2;
1065        } else if let Some(val) = a.strip_prefix("--commit=") {
1066            commit = Some(
1067                val.parse()
1068                    .map_err(|_| format!("invalid commit index: {val}"))?,
1069            );
1070            i += 1;
1071        } else if a == "--query" {
1072            let val = args
1073                .get(i + 1)
1074                .copied()
1075                .ok_or_else(|| "missing value for --query".to_string())?;
1076            query = Some(val.to_string());
1077            i += 2;
1078        } else if let Some(val) = a.strip_prefix("--query=") {
1079            query = Some(val.to_string());
1080            i += 1;
1081        } else if a == "--namespace" {
1082            let val = args
1083                .get(i + 1)
1084                .copied()
1085                .ok_or_else(|| "missing value for --namespace".to_string())?;
1086            namespace = Some(val.to_string());
1087            i += 2;
1088        } else if let Some(val) = a.strip_prefix("--namespace=") {
1089            namespace = Some(val.to_string());
1090            i += 1;
1091        } else if a.starts_with('-') {
1092            return Err(format!("unexpected flag: {a}"));
1093        } else if db_dir.is_none() {
1094            db_dir = Some(PathBuf::from(a));
1095            i += 1;
1096        } else {
1097            return Err(format!("unexpected extra argument: {a}"));
1098        }
1099    }
1100    let db_dir = db_dir.ok_or_else(|| "asof requires <db-dir>".to_string())?;
1101    match (commit.is_some(), at.is_some()) {
1102        (false, false) => {
1103            return Err("asof requires --commit N or --at <date>".to_string());
1104        }
1105        (true, true) => {
1106            return Err(
1107                "asof takes --commit or --at, not both: a precedence rule between a \
1108                 commit index and a date is how a caller ends up believing it asked \
1109                 for one and got the other"
1110                    .to_string(),
1111            );
1112        }
1113        _ => {}
1114    }
1115    Ok(Command::AsOf {
1116        db_dir,
1117        commit,
1118        at,
1119        query,
1120        namespace,
1121    })
1122}
1123
1124/// Execute an as-of query at the given commit and print results.
1125///
1126/// `namespace` restricts the read to one namespace as it was at that commit —
1127/// a namespace cannot change, so that is simply the nodes which existed then and
1128/// are in it. A name no node uses answers with nothing, never with everything.
1129pub fn run_asof(
1130    db_dir: &Path,
1131    commit: Option<u64>,
1132    at: Option<&str>,
1133    query: Option<&str>,
1134    namespace: Option<&str>,
1135) -> Result<String, CliError> {
1136    let namespace = check_namespace(namespace)?;
1137    // A date has to be resolved against the store's recorded commit times, and
1138    // `open_at` needs the commit before it opens — so a dated call costs one
1139    // ordinary open first. The parser guarantees exactly one of the two is set.
1140    let commit = match (commit, at) {
1141        (Some(c), _) => c,
1142        (None, Some(date)) => GraphDb::open(db_dir)?.resolve_date(date)?,
1143        (None, None) => {
1144            return Err(CliError(
1145                "asof requires --commit N or --at <date>".to_string(),
1146            ))
1147        }
1148    };
1149    // Counts come off the opened handle: it knows the archives the live WAL no
1150    // longer holds, and where history now starts.
1151    let db = GraphDb::open_at(db_dir, commit)?;
1152    let total = db.wal_total_commits()?;
1153    let floor = db.wal_horizon_floor();
1154    let mut out = String::new();
1155    if floor == 0 {
1156        let _ = writeln!(out, "as-of commit {} of {}", commit, total);
1157    } else {
1158        let _ = writeln!(
1159            out,
1160            "as-of commit {} of {} (history reaches back to commit {})",
1161            commit, total, floor
1162        );
1163    }
1164    if let Some(cypher) = query {
1165        let params = BTreeMap::new();
1166        let rs = match namespace {
1167            Some(ns) => db.query_masked(cypher, &params, &db.mask_for_namespace(ns))?,
1168            None => db.query(cypher, &params)?,
1169        };
1170        out.push_str(&format_result_set(&rs));
1171    }
1172    Ok(out)
1173}
1174
1175/// A `--namespace` value, refused here rather than resolved to an empty mask: a
1176/// typo that silently answers "nothing" reads like an empty store.
1177fn check_namespace(namespace: Option<&str>) -> Result<Option<&str>, CliError> {
1178    match namespace {
1179        Some(ns) if !valid_namespace(ns) => Err(CliError(format!(
1180            "namespace {ns:?} is not a valid namespace name — 1 to {NS_MAX_LEN} characters of \
1181             [A-Za-z0-9_.-]"
1182        ))),
1183        other => Ok(other),
1184    }
1185}
1186
1187fn parse_query(args: &[&str]) -> Result<Command, String> {
1188    let mut db_dir = None;
1189    let mut query_flag: Option<String> = None;
1190    let mut role: Option<String> = None;
1191    let mut namespace: Option<String> = None;
1192    let mut cypher_parts: Vec<&str> = Vec::new();
1193    let mut i = 0;
1194    while i < args.len() {
1195        let a = args[i];
1196        if a == "--query" {
1197            let val = args
1198                .get(i + 1)
1199                .copied()
1200                .ok_or_else(|| "missing value for --query".to_string())?;
1201            query_flag = Some(val.to_string());
1202            i += 2;
1203        } else if let Some(val) = a.strip_prefix("--query=") {
1204            query_flag = Some(val.to_string());
1205            i += 1;
1206        } else if a == "--role" {
1207            let val = args
1208                .get(i + 1)
1209                .copied()
1210                .ok_or_else(|| "missing value for --role".to_string())?;
1211            role = Some(val.to_string());
1212            i += 2;
1213        } else if let Some(val) = a.strip_prefix("--role=") {
1214            role = Some(val.to_string());
1215            i += 1;
1216        } else if a == "--namespace" {
1217            let val = args
1218                .get(i + 1)
1219                .copied()
1220                .ok_or_else(|| "missing value for --namespace".to_string())?;
1221            namespace = Some(val.to_string());
1222            i += 2;
1223        } else if let Some(val) = a.strip_prefix("--namespace=") {
1224            namespace = Some(val.to_string());
1225            i += 1;
1226        } else if a.starts_with('-') {
1227            return Err(format!("unexpected flag: {a}"));
1228        } else if db_dir.is_none() {
1229            db_dir = Some(PathBuf::from(a));
1230            i += 1;
1231        } else {
1232            cypher_parts.push(a);
1233            i += 1;
1234        }
1235    }
1236    let db_dir = db_dir.ok_or_else(|| "query requires <db-dir>".to_string())?;
1237    let cypher = if let Some(q) = query_flag {
1238        if !cypher_parts.is_empty() {
1239            return Err(
1240                "query: pass Cypher as remaining arguments or --query, not both".to_string(),
1241            );
1242        }
1243        q
1244    } else {
1245        if cypher_parts.is_empty() {
1246            return Err("query requires a Cypher string".to_string());
1247        }
1248        cypher_parts.join(" ")
1249    };
1250    Ok(Command::Query {
1251        db_dir,
1252        cypher,
1253        role,
1254        namespace,
1255    })
1256}
1257
1258/// Run a Cypher read or write and print columns/rows like [`run_asof`].
1259///
1260/// `role` answers as one of the store's roles and `namespace` from one
1261/// namespace; together they **intersect**, so a role bound to one namespace
1262/// never sees another and naming a namespace outside its binding answers with
1263/// nothing. Either one makes the query a read: a restricted write is refused.
1264pub fn run_query(
1265    db_dir: &Path,
1266    cypher: &str,
1267    role: Option<&str>,
1268    namespace: Option<&str>,
1269) -> Result<String, CliError> {
1270    let namespace = check_namespace(namespace)?;
1271    let params = BTreeMap::new();
1272    if role.is_some() || namespace.is_some() {
1273        let db = GraphDb::open(db_dir)?;
1274        // The same never-widen composition every other surface uses: one mask
1275        // per leg, intersected.
1276        let mask = match (role, namespace) {
1277            (Some(role), Some(ns)) => db
1278                .mask_for_role(role)?
1279                .intersect(&db.mask_for_namespace(ns)),
1280            (Some(role), None) => db.mask_for_role(role)?,
1281            (None, Some(ns)) => db.mask_for_namespace(ns),
1282            (None, None) => unreachable!("one of the two is Some in this branch"),
1283        };
1284        return Ok(format_result_set(&db.query_masked(cypher, &params, &mask)?));
1285    }
1286    let is_write = is_write_query(cypher).map_err(CliError)?;
1287    let rs = if is_write {
1288        let mut db = GraphDb::open(db_dir)?;
1289        db.query_write(cypher, &params)?
1290    } else {
1291        let db = GraphDb::open(db_dir)?;
1292        db.query(cypher, &params)?
1293    };
1294    Ok(format_result_set(&rs))
1295}
1296
1297fn parse_snapshot(args: &[&str]) -> Result<Command, String> {
1298    let mut db_dir = None;
1299    // Archiving is the default: a snapshot the user did not ask to be
1300    // destructive should not cost them their history.
1301    let mut wal = WalDisposition::Archive;
1302    let mut retention: Option<u32> = None;
1303    let mut i = 0;
1304    while i < args.len() {
1305        let a = args[i];
1306        if a == "--keep-wal" {
1307            wal = WalDisposition::Keep;
1308            i += 1;
1309        } else if a == "--truncate" {
1310            wal = WalDisposition::Truncate;
1311            i += 1;
1312        } else if a == "--archive-wal" {
1313            // Kept for the callers that spelled the default out.
1314            wal = WalDisposition::Archive;
1315            i += 1;
1316        } else if a.starts_with("--retention=") {
1317            let v = a.trim_start_matches("--retention=");
1318            retention = Some(
1319                v.parse::<u32>()
1320                    .map_err(|_| format!("--retention= expects a u32, got: {v}"))?,
1321            );
1322            i += 1;
1323        } else if a == "--retention" {
1324            i += 1;
1325            let v = args
1326                .get(i)
1327                .ok_or_else(|| "--retention requires a value".to_string())?;
1328            retention = Some(
1329                v.parse::<u32>()
1330                    .map_err(|e| format!("--retention value error: {e}"))?,
1331            );
1332            i += 1;
1333        } else if a.starts_with('-') {
1334            return Err(format!("unexpected flag: {a}"));
1335        } else if db_dir.is_none() {
1336            db_dir = Some(PathBuf::from(a));
1337            i += 1;
1338        } else {
1339            return Err(format!("unexpected extra argument: {a}"));
1340        }
1341    }
1342    let db_dir = db_dir.ok_or_else(|| "snapshot requires <db-dir>".to_string())?;
1343    Ok(Command::Snapshot {
1344        db_dir,
1345        wal,
1346        retention,
1347    })
1348}
1349
1350/// Migrate the snapshot at `db_dir` to the current format version.
1351///
1352/// - If the snapshot is already at the current version, prints
1353///   `already current (V<N>)`.
1354/// - If the snapshot is an older version, writes `snapshot.bin.bak` (atomic +
1355///   fsynced) then performs a truncating snapshot at the current version, and
1356///   prints `migrated V<from> -> V<current>`.
1357/// - WAL-only stores (no snapshot) are treated as needing a fresh snapshot.
1358pub fn run_migrate(db_dir: &Path) -> Result<String, CliError> {
1359    let current = core_api::SNAPSHOT_VERSION;
1360    let from_ver = core_api::snapshot_version_at(db_dir)?;
1361
1362    // `>=`, not `==`: a store that has opted in to multiplicity writes V10, a
1363    // version above the default this binary writes. It is already current —
1364    // rewriting it would produce another V10 snapshot and report "V10 -> V9".
1365    if let Some(ver) = from_ver {
1366        if ver >= current {
1367            return Ok(format!("already current (V{ver})\n"));
1368        }
1369    }
1370
1371    // Copy the original snapshot to .bak at OS level — no in-memory buffer
1372    // required for a 2+ GiB file.  The original snapshot.bin is authoritative
1373    // until snapshot_with's write_atomic (tmp+rename) succeeds, so a torn .bak
1374    // on crash is acceptable.
1375    if from_ver.is_some() {
1376        std::fs::copy(db_dir.join("snapshot.bin"), db_dir.join("snapshot.bin.bak"))?;
1377    }
1378
1379    // Open with auto_migrate=false to avoid double-migration, then write
1380    // the truncating snapshot (CLI migrate always truncates the WAL).
1381    let mut db = GraphDb::open_with_options(
1382        db_dir,
1383        core_api::OpenOptions {
1384            auto_migrate: false,
1385            ..Default::default()
1386        },
1387    )?;
1388    db.snapshot()?;
1389
1390    let msg = match from_ver {
1391        Some(ver) => format!("migrated V{ver} -> V{current}\n"),
1392        None => format!("migrated WAL-only -> V{current}\n"),
1393    };
1394    Ok(msg)
1395}
1396
1397/// Validate the CRC32 integrity of every section in a V8 snapshot.
1398///
1399/// Exits with a non-zero code if any section is corrupt.  This is the
1400/// explicit integrity audit path; mushroomdb does NOT CRC-check large
1401/// sections on the hot query path (see format-stability.md).
1402pub fn run_verify(db_dir: &Path) -> Result<String, CliError> {
1403    // A store that has only ever been written via the WAL has no snapshot yet;
1404    // give an actionable message instead of a raw "No such file" io error.
1405    if !db_dir.join("snapshot.bin").exists() {
1406        return Err(CliError(format!(
1407            "verify: no snapshot found in {} — take one first with `mushroomdb snapshot {}`",
1408            db_dir.display(),
1409            db_dir.display()
1410        )));
1411    }
1412    let results = core_api::verify_snapshot(db_dir)
1413        .map_err(|e| CliError(format!("verify: cannot open snapshot: {e}")))?;
1414    let mut any_fail = false;
1415    let mut out = String::new();
1416    for (id, section_name, byte_len, result) in &results {
1417        match result {
1418            Ok(()) => {
1419                let _ = writeln!(
1420                    out,
1421                    "  section {:2} ({:<12}) {:>10} bytes  OK",
1422                    id, section_name, byte_len
1423                );
1424            }
1425            Err(msg) => {
1426                let _ = writeln!(
1427                    out,
1428                    "  section {:2} ({:<12}) {:>10} bytes  CORRUPT: {msg}",
1429                    id, section_name, byte_len
1430                );
1431                any_fail = true;
1432            }
1433        }
1434    }
1435    if any_fail {
1436        Err(CliError(format!("integrity check FAILED:\n{out}")))
1437    } else {
1438        Ok(format!(
1439            "integrity check OK ({} sections):\n{out}",
1440            results.len()
1441        ))
1442    }
1443}
1444
1445/// What a snapshot does with the WAL it folds in.
1446#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1447pub enum WalDisposition {
1448    /// Move it to `wal.<N>.archive`, where the history reads still find it.
1449    /// The default, and what every automatic snapshot does: a store should not
1450    /// forget how it got here in exchange for opening faster.
1451    #[default]
1452    Archive,
1453    /// Leave `wal.bin` whole. Every pre-snapshot commit stays in the live WAL,
1454    /// and every open replays all of it.
1455    Keep,
1456    /// Drop it. The smallest directory and the fastest open, at the price of
1457    /// every commit before this point: `node_history`, `edge_history`,
1458    /// `was_linked` and `open_at` stop reaching them, and any archives an
1459    /// earlier snapshot left become unreachable too.
1460    Truncate,
1461}
1462
1463impl WalDisposition {
1464    fn options(self) -> SnapshotOptions {
1465        match self {
1466            WalDisposition::Archive => AUTOMATIC_SNAPSHOT,
1467            WalDisposition::Keep => SnapshotOptions {
1468                keep_wal: true,
1469                archive_wal: false,
1470            },
1471            WalDisposition::Truncate => SnapshotOptions {
1472                keep_wal: false,
1473                archive_wal: false,
1474            },
1475        }
1476    }
1477}
1478
1479/// Open `dir` and write `snapshot.bin`, archiving the WAL by default.
1480pub fn run_snapshot(
1481    db_dir: &Path,
1482    wal: WalDisposition,
1483    retention: Option<u32>,
1484) -> Result<String, CliError> {
1485    let mut db = GraphDb::open(db_dir)?;
1486    if wal == WalDisposition::Archive {
1487        db.set_wal_archive_retention(retention);
1488    }
1489    db.snapshot_with(wal.options())?;
1490    Ok(format!(
1491        "snapshot written: {}\n",
1492        db_dir.join("snapshot.bin").display()
1493    ))
1494}
1495
1496fn parse_build_index(args: &[&str]) -> Result<Command, String> {
1497    let mut db_dir: Option<PathBuf> = None;
1498    let mut rule: Option<String> = None;
1499    let mut i = 0;
1500    while i < args.len() {
1501        let a = args[i];
1502        if let Some(v) = a.strip_prefix("--rule=") {
1503            if v.is_empty() {
1504                return Err("--rule requires a value".to_string());
1505            }
1506            rule = Some(v.to_string());
1507            i += 1;
1508        } else if a == "--rule" {
1509            i += 1;
1510            let v = args
1511                .get(i)
1512                .ok_or_else(|| "--rule requires a value".to_string())?;
1513            rule = Some((*v).to_string());
1514            i += 1;
1515        } else if a.starts_with('-') {
1516            return Err(format!("unexpected flag: {a}"));
1517        } else if db_dir.is_none() {
1518            db_dir = Some(PathBuf::from(a));
1519            i += 1;
1520        } else {
1521            return Err(format!("unexpected extra argument: {a}"));
1522        }
1523    }
1524    let db_dir = db_dir.ok_or_else(|| "build-index requires <db-dir>".to_string())?;
1525    Ok(Command::BuildIndex { db_dir, rule })
1526}
1527
1528/// Pump every outstanding vector-index build to completion, one slice per
1529/// call, printing a line per slice.
1530///
1531/// `rule` narrows the report to one rule; the pump itself always advances every
1532/// pending build, because they share one write lock and splitting them would
1533/// only mean holding it more often.
1534pub fn run_build_index(db_dir: &Path, rule: Option<&str>) -> Result<String, CliError> {
1535    let mut db = GraphDb::open(db_dir)?;
1536    build_index_on(&mut db, rule)
1537}
1538
1539/// [`run_build_index`] against an already-open handle.
1540///
1541/// Terminates: every pump advances each pending build's cursor by at least one
1542/// node (the slice size is never zero), so the outstanding list empties.
1543///
1544/// Exposed for tests that need a build this handle itself deferred. Whether a
1545/// build is outstanding is decided when the rule is created, so a test using a
1546/// reduced slice size has to keep the handle that created the rule; reopening
1547/// replays `CreateRule` at the production slice size. A build a *snapshot* cut
1548/// short needs no such care — the reopen recognises it, which is what
1549/// [`run_build_index`] relies on.
1550pub fn build_index_on(db: &mut GraphDb<RealFs>, rule: Option<&str>) -> Result<String, CliError> {
1551    let mut out = String::new();
1552    let interesting = |name: &str| rule.is_none_or(|r| r == name);
1553    // Read before pumping, so that "no such rule" and "that rule is already
1554    // built" can be told apart in the empty case below.
1555    let known_rules: Vec<String> = db.stats().rules.iter().map(|r| r.name.clone()).collect();
1556
1557    // Pump before looking. Open registers a build a snapshot cut short, but a
1558    // resumed build can still be registered and finished inside a single call,
1559    // so the outstanding list alone cannot show that anything happened.
1560    loop {
1561        let (finished, outstanding) = db.pump_index_build_reporting()?;
1562        for b in &outstanding {
1563            if interesting(&b.rule) {
1564                out.push_str(&format!("building {}: {}/{}\n", b.rule, b.indexed, b.total));
1565            }
1566        }
1567        // Reported from the pump rather than inferred from a shrinking
1568        // outstanding list: a resumed build is registered and finished inside a
1569        // single call, so it never appears in that list at all.
1570        for b in &finished {
1571            if interesting(&b.rule) {
1572                out.push_str(&format!("built {}: {} vectors\n", b.rule, b.total));
1573            }
1574        }
1575        if outstanding.is_empty() {
1576            break;
1577        }
1578    }
1579    if out.is_empty() {
1580        match rule {
1581            // Distinguish the two ways this can be empty, because they need
1582            // different things from the operator: a finished build is fine, a
1583            // name that is not a rule is a typo.
1584            Some(r) if !known_rules.iter().any(|k| k == r) => out.push_str(&format!(
1585                "no rule named {r:?} in this store; nothing to build\n"
1586            )),
1587            Some(r) => out.push_str(&format!("nothing to build for rule {r:?}\n")),
1588            None => out.push_str("nothing to build\n"),
1589        }
1590    }
1591    Ok(out)
1592}
1593
1594fn parse_schema(args: &[&str]) -> Result<Command, String> {
1595    if args.is_empty() {
1596        return Err("schema requires a subcommand: apply".to_string());
1597    }
1598    match args[0] {
1599        "apply" => parse_schema_apply(&args[1..]),
1600        other => Err(format!(
1601            "unknown schema subcommand: {other}; expected apply"
1602        )),
1603    }
1604}
1605
1606fn parse_schema_apply(args: &[&str]) -> Result<Command, String> {
1607    let mut db_dir = None;
1608    let mut schema_file = None;
1609    let mut memory_defaults = false;
1610    let mut memory_identity = false;
1611    for a in args {
1612        if *a == "--memory-defaults" {
1613            memory_defaults = true;
1614        } else if *a == "--memory-identity" {
1615            memory_identity = true;
1616        } else if a.starts_with('-') {
1617            return Err(format!("unexpected flag: {a}"));
1618        } else if db_dir.is_none() {
1619            db_dir = Some(PathBuf::from(*a));
1620        } else if schema_file.is_none() {
1621            schema_file = Some(PathBuf::from(*a));
1622        } else {
1623            return Err(format!("unexpected extra argument: {a}"));
1624        }
1625    }
1626    let db_dir = db_dir.ok_or_else(|| "schema apply requires <db-dir>".to_string())?;
1627    if memory_identity {
1628        if memory_defaults || schema_file.is_some() {
1629            return Err(
1630                "schema apply --memory-identity takes no schema file and no other preset"
1631                    .to_string(),
1632            );
1633        }
1634        return Ok(Command::SchemaApply {
1635            db_dir,
1636            schema_file: None,
1637            memory_defaults: false,
1638            memory_identity: true,
1639        });
1640    }
1641    if memory_defaults {
1642        if schema_file.is_some() {
1643            return Err("schema apply --memory-defaults takes no schema file argument".to_string());
1644        }
1645        return Ok(Command::SchemaApply {
1646            db_dir,
1647            schema_file: None,
1648            memory_defaults: true,
1649            memory_identity: false,
1650        });
1651    }
1652    let schema_file =
1653        schema_file.ok_or_else(|| "schema apply requires <schema.json>".to_string())?;
1654    Ok(Command::SchemaApply {
1655        db_dir,
1656        schema_file: Some(schema_file),
1657        memory_defaults: false,
1658        memory_identity: false,
1659    })
1660}
1661
1662/// Read `schema_file`, open `db_dir`, apply the schema, and return the diff
1663/// as one line per entry: `"created rule:x"`, `"updated view:y"`, etc.
1664pub fn run_schema_apply(db_dir: &Path, schema_file: &Path) -> Result<String, CliError> {
1665    let json = std::fs::read_to_string(schema_file)
1666        .map_err(|e| CliError(format!("cannot read {}: {e}", schema_file.display())))?;
1667    let schema: Schema = serde_json::from_str(&json).map_err(|e| {
1668        CliError(format!(
1669            "invalid schema JSON in {}: {e}",
1670            schema_file.display()
1671        ))
1672    })?;
1673    let mut db = GraphDb::open(db_dir)?;
1674    let diff = db.apply_schema(&schema)?;
1675    let mut out = String::new();
1676    for entry in &diff.created {
1677        let _ = writeln!(out, "created {entry}");
1678    }
1679    for entry in &diff.updated {
1680        let _ = writeln!(out, "updated {entry}");
1681    }
1682    for entry in &diff.unchanged {
1683        let _ = writeln!(out, "unchanged {entry}");
1684    }
1685    if diff.created.is_empty() && diff.updated.is_empty() && diff.unchanged.is_empty() {
1686        let _ = writeln!(out, "schema applied: nothing to do (empty schema)");
1687    }
1688    Ok(out)
1689}
1690
1691/// `mushroomdb schema apply <db> --memory-defaults`
1692///
1693/// Applies `core_api::memory_schema::memory_defaults()`. Kept separate from
1694/// `run_schema_apply` because it takes no schema file, and separate from
1695/// `open` because declaring full-text on a populated store rebuilds the index
1696/// at open — the caller is told what it will cost before it happens.
1697pub fn run_schema_apply_memory_defaults(db_dir: &Path) -> Result<String, CliError> {
1698    let mut db = GraphDb::open(db_dir)?;
1699    let before = db.stats();
1700    let diff = db.apply_schema(&core_api::memory_schema::memory_defaults())?;
1701    let mut out = String::new();
1702    if diff.created.is_empty() && diff.updated.is_empty() {
1703        let _ = writeln!(out, "schema apply: already current, nothing to do");
1704        return Ok(out);
1705    }
1706    let _ = writeln!(
1707        out,
1708        "schema apply: {} created, {} updated, {} unchanged",
1709        diff.created.len(),
1710        diff.updated.len(),
1711        diff.unchanged.len()
1712    );
1713    for name in diff.created.iter().chain(diff.updated.iter()) {
1714        let _ = writeln!(out, "  {name}");
1715    }
1716    let _ = writeln!(
1717        out,
1718        "note: {} live nodes are now full-text indexed; the index rebuilds at \
1719         every open from here on.",
1720        before.nodes_live
1721    );
1722    Ok(out)
1723}
1724
1725/// `mushroomdb schema apply <db> --memory-identity`
1726///
1727/// Applies `core_api::memory_schema::memory_identity()` — opt-in, because a
1728/// store never gains a rule silently. What it will do is measured and stated
1729/// first, in the same output, before anything is written: how many entity
1730/// nodes the rules will compare, and how many need an `aliases` list written
1731/// before they can. Then the lists are written in one commit and the rules
1732/// created, each with its own backfill.
1733///
1734/// `aliases` is what a node's key and name imply. A node that already carries
1735/// items those do not imply — a user's own `aliases` property from before
1736/// 0.7 — keeps them: the same commit moves them to `alias_keys`, the list the
1737/// five claim rules read, and the output says how many nodes that touched.
1738/// Nothing is dropped. On a store that already carries the preset's
1739/// earlier eleven rules, this adds the five claim rules and leaves the rest
1740/// unchanged.
1741pub fn run_schema_apply_memory_identity(db_dir: &Path) -> Result<String, CliError> {
1742    use core_api::memory::identity::{
1743        aliases_to_backfill, entity_node_count, write_aliases, ALIASES_FIELD, ALIAS_KEYS_FIELD,
1744        SAME_AS_EDGE,
1745    };
1746    let mut db = GraphDb::open(db_dir)?;
1747    let preset = core_api::memory_schema::memory_identity();
1748    let entity_nodes = entity_node_count(&db);
1749    let backfill = aliases_to_backfill(&db)?;
1750    let mut out = String::new();
1751    let _ = writeln!(
1752        out,
1753        "identity preset: {} SAME_AS rules over each entity's aliases, global — they link \
1754         across namespaces",
1755        preset.rules.len()
1756    );
1757    let writes = |field: &str| backfill.iter().filter(|node| node.sets(field)).count();
1758    let _ = writeln!(
1759        out,
1760        "before applying: {entity_nodes} entity node(s); {} need an aliases list written \
1761         first, from the key and the name; each rule then compares aliases across its labels \
1762         once, and every later write to an entity is re-checked",
1763        writes(ALIASES_FIELD)
1764    );
1765    let moved = writes(ALIAS_KEYS_FIELD);
1766    if moved == 0 {
1767        let _ = writeln!(
1768            out,
1769            "alias_keys: nothing to move — it holds only declared aliases; an entity that \
1770             declares one equal to a provisional stub's key links that stub"
1771        );
1772    } else {
1773        let _ = writeln!(
1774            out,
1775            "alias_keys: {moved} node(s) carry aliases their key and name do not imply; those \
1776             are kept, moved to alias_keys as declared aliases — one equal to a provisional \
1777             stub's key links that stub"
1778        );
1779    }
1780    // Two commits: the aliases, then the rules. A failure between them leaves
1781    // the lists written and no rule; a re-run recovers, since the backfill is
1782    // idempotent and finds nothing left to write.
1783    write_aliases(&mut db, &backfill)?;
1784    let diff = db.apply_schema(&preset)?;
1785    let _ = writeln!(
1786        out,
1787        "schema apply: {} created, {} updated, {} unchanged",
1788        diff.created.len(),
1789        diff.updated.len(),
1790        diff.unchanged.len()
1791    );
1792    // Edges are directed and a same-label rule derives both directions, so
1793    // the pair count is the number of identities claimed.
1794    let edges = db.weighted_edges(SAME_AS_EDGE, None);
1795    let pairs: std::collections::BTreeSet<(&str, &str)> = edges
1796        .iter()
1797        .map(|(a, b, _)| {
1798            if a <= b {
1799                (a.as_str(), b.as_str())
1800            } else {
1801                (b.as_str(), a.as_str())
1802            }
1803        })
1804        .collect();
1805    let _ = writeln!(
1806        out,
1807        "SAME_AS edges now: {} ({} pair(s))",
1808        edges.len(),
1809        pairs.len()
1810    );
1811    Ok(out)
1812}
1813
1814fn parse_backup(args: &[&str]) -> Result<Command, String> {
1815    let mut db_dir = None;
1816    let mut dest = None;
1817    for a in args {
1818        if a.starts_with('-') {
1819            return Err(format!("unexpected flag: {a}"));
1820        }
1821        if db_dir.is_none() {
1822            db_dir = Some(PathBuf::from(*a));
1823        } else if dest.is_none() {
1824            dest = Some(PathBuf::from(*a));
1825        } else {
1826            return Err(format!("unexpected extra argument: {a}"));
1827        }
1828    }
1829    let db_dir = db_dir.ok_or_else(|| "backup requires <db-dir>".to_string())?;
1830    let dest = dest.ok_or_else(|| "backup requires <dest>".to_string())?;
1831    Ok(Command::Backup { db_dir, dest })
1832}
1833
1834fn parse_export(args: &[&str]) -> Result<Command, String> {
1835    let mut db_dir = None;
1836    let mut dest = None;
1837    let mut format = ExportFormat::Jsonl;
1838    let mut i = 0;
1839    while i < args.len() {
1840        let a = args[i];
1841        if a == "--format" {
1842            let val = args
1843                .get(i + 1)
1844                .copied()
1845                .ok_or_else(|| "missing value for --format".to_string())?;
1846            format = ExportFormat::parse(val).ok_or_else(|| {
1847                format!("unknown format '{val}'; expected jsonl, parquet, or graphml")
1848            })?;
1849            i += 2;
1850        } else if let Some(val) = a.strip_prefix("--format=") {
1851            format = ExportFormat::parse(val).ok_or_else(|| {
1852                format!("unknown format '{val}'; expected jsonl, parquet, or graphml")
1853            })?;
1854            i += 1;
1855        } else if a.starts_with('-') {
1856            return Err(format!("unexpected flag: {a}"));
1857        } else if db_dir.is_none() {
1858            db_dir = Some(PathBuf::from(a));
1859            i += 1;
1860        } else if dest.is_none() {
1861            dest = Some(PathBuf::from(a));
1862            i += 1;
1863        } else {
1864            return Err(format!("unexpected extra argument: {a}"));
1865        }
1866    }
1867    let db_dir = db_dir.ok_or_else(|| "export requires <db-dir>".to_string())?;
1868    let dest = dest.ok_or_else(|| "export requires <dest>".to_string())?;
1869    Ok(Command::Export {
1870        db_dir,
1871        dest,
1872        format,
1873    })
1874}
1875
1876/// Create a consistent, verified backup of `db_dir` to `dest`.
1877pub fn run_backup(db_dir: &Path, dest: &Path) -> Result<BackupReport, CliError> {
1878    let db = GraphDb::open(db_dir)?;
1879    Ok(db.backup_to(dest)?)
1880}
1881
1882/// [`core_api::restore::restore_if_empty`], in the CLI's error type.
1883///
1884/// The implementation moved down into `core-api` in v0.6.10 so the Python
1885/// binding could reach it without taking a dependency on this crate; the
1886/// semantics, the messages and [`RestoreOutcome`] are unchanged. The engine
1887/// carries the message inside [`core_api::GraphError::Io`], whose own `Display`
1888/// adds a prefix — unwrapped here, so `serve` prints what it always printed.
1889pub fn restore_if_empty(db_dir: &Path, from: &Path) -> Result<RestoreOutcome, CliError> {
1890    core_api::restore::restore_if_empty(db_dir, from).map_err(|e| match e {
1891        core_api::GraphError::Io(io) => CliError(io.to_string()),
1892        other => CliError(other.to_string()),
1893    })
1894}
1895
1896/// Format a [`BackupReport`] for display.
1897pub fn format_backup(dest: &Path, report: &BackupReport) -> String {
1898    let mut out = String::new();
1899    writeln!(out, "backup to: {}", dest.display()).unwrap();
1900    writeln!(out, "  files: {}", report.files.join(", ")).unwrap();
1901    writeln!(out, "  bytes: {}", report.bytes).unwrap();
1902    writeln!(out, "  verified: {}", report.verified).unwrap();
1903    out
1904}
1905
1906/// Export all data from `db_dir` to `dest` in `format`.
1907pub fn run_export(db_dir: &Path, dest: &Path, format: &ExportFormat) -> Result<String, CliError> {
1908    let db = GraphDb::open(db_dir)?;
1909    let nodes = db.all_nodes_for_export();
1910    let edges = db.all_edges_for_export();
1911    let mut rules = db.rules();
1912    rules.sort_by(|a, b| a.name.cmp(&b.name));
1913    let node_count = nodes.len();
1914    let edge_count = edges.len();
1915    let rule_count = rules.len();
1916    match format {
1917        ExportFormat::Jsonl => {
1918            export::write_jsonl(&nodes, &edges, &rules, dest)?;
1919            Ok(format!(
1920                "exported to {} (format={}): {} nodes, {} edges, {} rules\n",
1921                dest.display(),
1922                format.name(),
1923                node_count,
1924                edge_count,
1925                rule_count
1926            ))
1927        }
1928        ExportFormat::Parquet => {
1929            export::write_parquet(&nodes, &edges, &rules, dest)?;
1930            Ok(format!(
1931                "exported to {} (format={}): {} nodes, {} edges, {} rules\n",
1932                dest.display(),
1933                format.name(),
1934                node_count,
1935                edge_count,
1936                rule_count
1937            ))
1938        }
1939        // GraphML has no rule analogue: only nodes and edges are written.
1940        ExportFormat::Graphml => {
1941            let file_path = export::write_graphml(&nodes, &edges, dest)?;
1942            Ok(format!(
1943                "exported to {} (format={}): {} nodes, {} edges\n",
1944                file_path.display(),
1945                format.name(),
1946                node_count,
1947                edge_count,
1948            ))
1949        }
1950    }
1951}
1952
1953fn format_result_set(rs: &ResultSet) -> String {
1954    let mut out = String::new();
1955    let _ = writeln!(out, "columns: {}", rs.columns().join(", "));
1956    for i in 0..rs.len() {
1957        let cells: Vec<String> = rs
1958            .columns()
1959            .iter()
1960            .map(|c| format!("{c}={}", fmt_cell(rs.get(i, c))))
1961            .collect();
1962        let _ = writeln!(out, "  {}", cells.join("  "));
1963    }
1964    out
1965}
1966
1967fn parse_algo(args: &[&str]) -> Result<Command, String> {
1968    if args.is_empty() {
1969        return Err(
1970            "algo requires a subcommand: pagerank | wcc | degree | communities".to_string(),
1971        );
1972    }
1973    let subcmd = match args[0] {
1974        "pagerank" => AlgoSubcmd::Pagerank,
1975        "wcc" => AlgoSubcmd::Wcc,
1976        "degree" => AlgoSubcmd::Degree,
1977        "communities" => AlgoSubcmd::Communities,
1978        other => {
1979            return Err(format!(
1980                "unknown algo subcommand: {other}; expected pagerank | wcc | degree | communities"
1981            ))
1982        }
1983    };
1984    let rest = &args[1..];
1985    let mut db_dir = None;
1986    let mut top: usize = 20;
1987    let mut dir = AlgoDir::Both;
1988    let mut edge_types: Vec<String> = Vec::new();
1989    let mut weight_prop: Option<String> = None;
1990    let mut min_weight: Option<f64> = None;
1991    let mut i = 0;
1992    while i < rest.len() {
1993        let a = rest[i];
1994        if a == "--top" {
1995            let val = rest
1996                .get(i + 1)
1997                .copied()
1998                .ok_or_else(|| "missing value for --top".to_string())?;
1999            top = val
2000                .parse()
2001                .map_err(|_| format!("--top must be a non-negative integer, got {val}"))?;
2002            i += 2;
2003        } else if let Some(val) = a.strip_prefix("--top=") {
2004            top = val
2005                .parse()
2006                .map_err(|_| format!("--top must be a non-negative integer, got {val}"))?;
2007            i += 1;
2008        } else if a == "--dir" {
2009            let val = rest
2010                .get(i + 1)
2011                .copied()
2012                .ok_or_else(|| "missing value for --dir".to_string())?;
2013            dir = parse_algo_dir(val)?;
2014            i += 2;
2015        } else if let Some(val) = a.strip_prefix("--dir=") {
2016            dir = parse_algo_dir(val)?;
2017            i += 1;
2018        } else if a == "--edge-type" {
2019            let val = rest
2020                .get(i + 1)
2021                .copied()
2022                .ok_or_else(|| "missing value for --edge-type".to_string())?;
2023            edge_types.push(val.to_string());
2024            i += 2;
2025        } else if let Some(val) = a.strip_prefix("--edge-type=") {
2026            edge_types.push(val.to_string());
2027            i += 1;
2028        } else if a == "--weight-prop" {
2029            let val = rest
2030                .get(i + 1)
2031                .copied()
2032                .ok_or_else(|| "missing value for --weight-prop".to_string())?;
2033            weight_prop = Some(val.to_string());
2034            i += 2;
2035        } else if let Some(val) = a.strip_prefix("--weight-prop=") {
2036            weight_prop = Some(val.to_string());
2037            i += 1;
2038        } else if a == "--min-weight" {
2039            let val = rest
2040                .get(i + 1)
2041                .copied()
2042                .ok_or_else(|| "missing value for --min-weight".to_string())?;
2043            min_weight = Some(
2044                val.parse()
2045                    .map_err(|_| format!("--min-weight must be a number, got {val}"))?,
2046            );
2047            i += 2;
2048        } else if let Some(val) = a.strip_prefix("--min-weight=") {
2049            min_weight = Some(
2050                val.parse()
2051                    .map_err(|_| format!("--min-weight must be a number, got {val}"))?,
2052            );
2053            i += 1;
2054        } else if a.starts_with('-') {
2055            return Err(format!("unexpected flag: {a}"));
2056        } else if db_dir.is_none() {
2057            db_dir = Some(PathBuf::from(a));
2058            i += 1;
2059        } else {
2060            return Err(format!("unexpected extra argument: {a}"));
2061        }
2062    }
2063    let db_dir = db_dir.ok_or_else(|| format!("algo {} requires <db-dir>", args[0]))?;
2064    Ok(Command::Algo {
2065        db_dir,
2066        subcmd,
2067        top,
2068        dir,
2069        edge_types,
2070        weight_prop,
2071        min_weight,
2072    })
2073}
2074
2075/// Parse the `--dir` value for `algo` into an [`AlgoDir`].
2076fn parse_algo_dir(val: &str) -> Result<AlgoDir, String> {
2077    match val.to_ascii_lowercase().as_str() {
2078        "out" => Ok(AlgoDir::Out),
2079        "in" => Ok(AlgoDir::In),
2080        "both" => Ok(AlgoDir::Both),
2081        other => Err(format!("--dir must be one of out | in | both, got {other}")),
2082    }
2083}
2084
2085/// Body of `mushroomdb brief <db-dir>|--auto`, the `SessionStart` hook.
2086///
2087/// Byte-stable for a given store: the host caches this output for the whole
2088/// session, so two prompts of the same session must not disagree about what
2089/// the repository is. Opened read-only like every other question.
2090pub fn run_brief(db_dir: &Path) -> Result<String, CliError> {
2091    let db = open_for_reading(db_dir)?;
2092    let reach = reach_line(db_dir);
2093    let b = core_api::memory::brief::brief(&db, &core_api::memory::brief::BriefOptions::default());
2094    let mut text = core_api::memory::brief::render(&b, &reach);
2095    // An empty store's line names how to fill it, and `render` cannot know
2096    // which doors this install opened. A cli-only install gets the shell form.
2097    if text == core_api::memory::brief::EMPTY_BRIEF
2098        && matches!(install::delivery_for_store(db_dir), install::Delivery::Cli)
2099    {
2100        text = empty_brief_cli(db_dir);
2101    }
2102    // Said here because a brief is computed once per session and cached,
2103    // where the prompt hook fires every turn. A 0.6.x store upgraded to 0.7
2104    // has no text index until someone asks for one, and a user who never
2105    // calls the `recall` *tool* would otherwise never learn why the hook went
2106    // quiet.
2107    //
2108    // Placed above the reach line rather than after it: a brief ends with how
2109    // to reach the graph, and the tests holding that line read it as the last.
2110    // An empty store's brief has no reach line, so there it simply ends.
2111    //
2112    // The path is quoted and sanitized as the reach line's is: quoted so a
2113    // space or a quote in it stays one argument, sanitized because this line
2114    // is inserted after `render` sanitized everything else.
2115    if db.fulltext_pairs().is_empty() {
2116        let notice = format!(
2117            "no text index: recall cannot match anything here. \
2118             Run: mushroomdb schema apply {} --memory-defaults\n",
2119            core_api::digest::sanitize(&install::sh_quote(&db_dir.to_string_lossy()))
2120        );
2121        let at = text
2122            .rfind("\nreach the graph: ")
2123            .map_or(text.len(), |i| i + 1);
2124        text.insert_str(at, &notice);
2125    }
2126    Ok(text)
2127}
2128
2129/// How a Cypher statement is typed at a shell, in the words every place that
2130/// prints a shell `query` uses: this brief's reach line, the CLI-only
2131/// empty-store line, and the skill's CLI table.
2132///
2133/// The statement is one double-quoted argument because the engine's Cypher
2134/// takes single-quoted strings only. A shell expands `$` and a backtick inside
2135/// double quotes, so a fact holding either would run a command on its way in;
2136/// the rule is in words rather than the characters themselves so it reads the
2137/// same in a Markdown table as in a plain line.
2138const SHELL_QUOTING_RULE: &str = "single-quote Cypher strings; inside the double quotes \
2139                                  backslash every dollar sign, double quote and backtick";
2140
2141/// The brief's last line: how to reach the graph from this session.
2142///
2143/// Two doors, because a session may have either one open — the MCP tool, and
2144/// the same question typed at a shell. The command names the binary the way
2145/// `install` would resolve it right now, which is the same resolution the
2146/// hooks themselves were written with, and it names the store, because both
2147/// tools take one.
2148///
2149/// **Every MCP name here has to be one `tools/list` actually lists.** A
2150/// session can only call what its client was shown, so naming a tool it
2151/// cannot see would be worse than naming none — which is also why a `cli`
2152/// install, registering no server at all, gets the shell form alone. Every
2153/// store is served [`server::ASSOCIATION_TOOLS`], one written by `ingest-git`
2154/// included, so every store is reached through `explain_association` and
2155/// `query`, which is where its entities are.
2156/// `the_reach_line_names_only_tools_its_surface_lists` holds this line and
2157/// that list in step.
2158///
2159/// The shell half names `query` alone. `mushroomdb why <db> <a> <b>` is
2160/// `explain_association`'s shell door, but it answers one pair, and `query`
2161/// answers that question and every other the brief's recipes ask, a Cypher
2162/// read away.
2163fn reach_line(db_dir: &Path) -> String {
2164    let bin = install::detect_mcp_command(None).shell();
2165    let db = install::sh_quote(&db_dir.to_string_lossy());
2166    let tools = format!(
2167        "explain_association <a> <b>{sep}query '<cypher>' (MCP tools; add role: <name> \
2168         or namespace: <ns> to narrow what it sees){sep}or:",
2169        sep = core_api::digest::SEP
2170    );
2171    let shell = format!("{bin} query {db} \"<cypher>\" ({SHELL_QUOTING_RULE})");
2172    match install::delivery_for_store(db_dir) {
2173        install::Delivery::Cli => shell,
2174        _ => format!("{tools} {shell}"),
2175    }
2176}
2177
2178/// An empty store's brief for an install that registered no MCP server.
2179///
2180/// [`core_api::memory::brief::EMPTY_BRIEF`] offers `remember`,
2181/// `upsert_entity` and `ingest_json`, which are MCP tools; a `--delivery cli`
2182/// session has a shell and nothing else. This is the same offer in the one
2183/// form that session can act on — a `query` with a `CREATE`, the write the
2184/// skill's CLI table names, with the `id:` property a `CREATE` needs.
2185///
2186/// The statement is in double quotes for the shell because the engine's
2187/// Cypher takes single-quoted strings only: the line has to run as a shell
2188/// would run it, and
2189/// `an_empty_store_brief_on_a_cli_delivery_install_names_no_mcp_tool` runs
2190/// it, on a store path with a space and a quote in it. The fact a session
2191/// fills in is arbitrary text inside those double quotes, so the line ends
2192/// with [`SHELL_QUOTING_RULE`].
2193///
2194/// The id and the text are placeholders, as the skill's `note:…` is. A
2195/// literal id would be the same key on every paste, and the key is the node.
2196fn empty_brief_cli(db_dir: &Path) -> String {
2197    // Sanitized as the reach line is: `render` returned a constant for this
2198    // store, so nothing downstream sanitizes what is built here.
2199    let bin = core_api::digest::sanitize(&install::detect_mcp_command(None).shell());
2200    let db = core_api::digest::sanitize(&install::sh_quote(&db_dir.to_string_lossy()));
2201    format!(
2202        "mushroomdb brief — empty store; offer to fill it: {bin} query {db} \
2203         \"CREATE (n:Note {{id: 'note:<fresh-id>', text: '<the fact>'}})\" writes a fact; \
2204         fill in both, with an id no note has yet; {SHELL_QUOTING_RULE}\n"
2205    )
2206}
2207
2208/// Open a store the way every question about it is asked: read-only, with both
2209/// write paths off, so asking never migrates a snapshot, rewrites a torn WAL
2210/// tail, or makes a writer wait on the cross-process lock.
2211///
2212/// A directory that is not there is an error rather than an empty store:
2213/// `RealFs::new` runs `create_dir_all`, so without this guard a `brief` hook
2214/// left behind by an uninstall — or any read of a mistyped path — would create
2215/// the very store it then reports as empty. The same guard `run_recall` opens
2216/// behind.
2217fn open_for_reading(db_dir: &Path) -> Result<structure::Db, CliError> {
2218    if !db_dir.exists() {
2219        return Err(CliError(format!("no store at {}", db_dir.display())));
2220    }
2221    Ok(GraphDb::open_with_options(
2222        db_dir,
2223        core_api::OpenOptions {
2224            auto_migrate: false,
2225            repair_wal: false,
2226            read_only: true,
2227        },
2228    )?)
2229}
2230
2231/// Body of `mushroomdb why <db> <a> <b>`: every rule edge between two keys
2232/// with the evidence that derived it, or an honest note that there is none.
2233/// A key the store does not hold is an error (`node key not found: <key>`),
2234/// not an empty answer.
2235///
2236/// The reply is what the `explain_association` tool sends, framing line
2237/// included: the rule names and matched values are graph content.
2238pub fn run_why(db_dir: &Path, a: &str, b: &str) -> Result<String, CliError> {
2239    let db = open_for_reading(db_dir)?;
2240    let explained = core_api::explain_digest::explain_with_evidence(&db, a, b)?;
2241    Ok(format!(
2242        "{}{}",
2243        core_api::digest::UNTRUSTED_FRAMING,
2244        core_api::explain_digest::render_explain(a, b, &explained)
2245    ))
2246}
2247
2248/// Run a graph algorithm and return a formatted string.
2249///
2250/// `dir` selects the edge direction for `degree` and `pagerank`; `wcc` and
2251/// `communities` are always undirected and ignore it. `edge_types` /
2252/// `weight_prop` / `min_weight` are used by `communities` only.
2253#[allow(clippy::too_many_arguments)]
2254pub fn run_algo(
2255    db_dir: &Path,
2256    subcmd: &AlgoSubcmd,
2257    top: usize,
2258    dir: AlgoDir,
2259    edge_types: Vec<String>,
2260    weight_prop: Option<String>,
2261    min_weight: Option<f64>,
2262) -> Result<String, CliError> {
2263    let db = GraphDb::open(db_dir)?;
2264    match subcmd {
2265        AlgoSubcmd::Pagerank => {
2266            let config = PageRankConfig {
2267                direction: dir,
2268                ..PageRankConfig::default()
2269            };
2270            let report = db.pagerank(&config);
2271            Ok(format_pagerank(&report, top))
2272        }
2273        AlgoSubcmd::Wcc => {
2274            let config = WccConfig::default();
2275            let report = db.connected_components(&config);
2276            Ok(format_wcc(&report, top))
2277        }
2278        AlgoSubcmd::Degree => {
2279            let config = DegreeConfig {
2280                direction: dir,
2281                ..DegreeConfig::default()
2282            };
2283            let report = db.degree_centrality(&config);
2284            Ok(format_degree(&report, top))
2285        }
2286        AlgoSubcmd::Communities => {
2287            let config = LouvainConfig {
2288                edge_types,
2289                weight_prop,
2290                min_weight,
2291                ..LouvainConfig::default()
2292            };
2293            let report = db.communities(&config);
2294            Ok(format_communities(&report, top))
2295        }
2296    }
2297}
2298
2299fn format_pagerank(report: &core_api::PageRankReport, top: usize) -> String {
2300    let mut buf = String::new();
2301    let _ = writeln!(buf, "== pagerank (converged={}) ==", report.converged);
2302    let rows = if top == 0 {
2303        report.scores.as_slice()
2304    } else {
2305        &report.scores[..top.min(report.scores.len())]
2306    };
2307    for (i, (key, score)) in rows.iter().enumerate() {
2308        let _ = writeln!(buf, "  {:>4}  {:<40}  {:.6}", i + 1, key, score);
2309    }
2310    buf
2311}
2312
2313fn format_wcc(report: &core_api::WccReport, top: usize) -> String {
2314    let mut buf = String::new();
2315    let _ = writeln!(buf, "== wcc (truncated={}) ==", report.truncated);
2316    let rows = if top == 0 {
2317        report.components.as_slice()
2318    } else {
2319        &report.components[..top.min(report.components.len())]
2320    };
2321    for (key, comp_id) in rows {
2322        let _ = writeln!(buf, "  {:<40}  component={}", key, comp_id);
2323    }
2324    buf
2325}
2326
2327fn format_degree(report: &core_api::DegreeReport, top: usize) -> String {
2328    let mut buf = String::new();
2329    let _ = writeln!(
2330        buf,
2331        "== degree centrality (truncated={}) ==",
2332        report.truncated
2333    );
2334    let rows = if top == 0 {
2335        report.scores.as_slice()
2336    } else {
2337        &report.scores[..top.min(report.scores.len())]
2338    };
2339    for (i, (key, deg)) in rows.iter().enumerate() {
2340        let _ = writeln!(buf, "  {:>4}  {:<40}  degree={}", i + 1, key, deg);
2341    }
2342    buf
2343}
2344
2345/// One line per community: id, size, cohesion, first 3 members.
2346/// Prints `(truncated)` in the header when the time budget fired.
2347fn format_communities(report: &core_api::CommunityReport, top: usize) -> String {
2348    let mut buf = String::new();
2349    let trunc = if report.truncated { " (truncated)" } else { "" };
2350    let _ = writeln!(
2351        buf,
2352        "== communities (modularity={:.2}){trunc} ==",
2353        report.modularity
2354    );
2355    let rows = if top == 0 {
2356        report.communities.as_slice()
2357    } else {
2358        &report.communities[..top.min(report.communities.len())]
2359    };
2360    for c in rows {
2361        let preview: Vec<&str> = c.members.iter().take(3).map(String::as_str).collect();
2362        let _ = writeln!(
2363            buf,
2364            "  {:>4}  size={:<6} cohesion={:<6.2} members=[{}]",
2365            c.id,
2366            c.members.len(),
2367            c.cohesion,
2368            preview.join(", ")
2369        );
2370    }
2371    buf
2372}
2373
2374/// `<db-dir>` or `--auto`, for the commands a hook line invokes.
2375///
2376/// Exactly one of the two: `--auto` says "work it out from the environment",
2377/// which a stated path contradicts rather than refines.
2378fn parse_dir_or_auto(cmd: &str, args: &[&str]) -> Result<(Option<PathBuf>, bool), String> {
2379    let mut db_dir = None;
2380    let mut auto = false;
2381    for a in args {
2382        if *a == "--auto" {
2383            auto = true;
2384        } else if a.starts_with('-') {
2385            return Err(format!("unexpected flag: {a}"));
2386        } else if db_dir.is_some() {
2387            return Err(format!("unexpected extra argument: {a}"));
2388        } else {
2389            db_dir = Some(PathBuf::from(*a));
2390        }
2391    }
2392    match (&db_dir, auto) {
2393        (Some(_), true) => Err(format!("{cmd}: --auto takes no <db-dir>")),
2394        (None, false) => Err(format!("{cmd} requires <db-dir> or --auto")),
2395        _ => Ok((db_dir, auto)),
2396    }
2397}
2398
2399/// `mcp [<db-dir>|--auto] [--all-tools]`. Every other flag is
2400/// [`parse_dir_or_auto`]'s to reject, so `--all-tools` is stripped here and
2401/// the rest of the line parses exactly as `recall`'s does.
2402fn parse_mcp(args: &[&str]) -> Result<Command, String> {
2403    let all_tools = args.contains(&"--all-tools");
2404    let rest: Vec<&str> = args
2405        .iter()
2406        .copied()
2407        .filter(|a| *a != "--all-tools")
2408        .collect();
2409    parse_dir_or_auto("mcp", &rest).map(|(db_dir, auto)| Command::Mcp {
2410        db_dir,
2411        auto,
2412        all_tools,
2413    })
2414}
2415
2416/// `<db-dir>` followed by between `min` and `max` further arguments, none of
2417/// which may look like a flag.
2418///
2419/// The graph tools take keys — paths and symbol names — and a key beginning
2420/// with `-` is far more likely to be a typo'd flag than a file called `-x`, so
2421/// it is refused rather than looked up and reported missing.
2422fn parse_positional(
2423    cmd: &str,
2424    args: &[&str],
2425    min: usize,
2426    max: usize,
2427) -> Result<(PathBuf, Vec<String>), String> {
2428    let mut rest: Vec<String> = Vec::new();
2429    let mut db_dir: Option<PathBuf> = None;
2430    for a in args {
2431        if a.starts_with('-') {
2432            return Err(format!("unexpected flag: {a}"));
2433        }
2434        match db_dir {
2435            None => db_dir = Some(PathBuf::from(*a)),
2436            Some(_) => rest.push((*a).to_string()),
2437        }
2438    }
2439    let db_dir = db_dir.ok_or_else(|| format!("{cmd} requires <db-dir>"))?;
2440    if rest.len() < min {
2441        return Err(format!(
2442            "{cmd} requires <db-dir> and {min} more argument{}",
2443            if min == 1 { "" } else { "s" }
2444        ));
2445    }
2446    if rest.len() > max {
2447        return Err(format!("unexpected extra argument: {}", rest[max]));
2448    }
2449    Ok((db_dir, rest))
2450}
2451
2452fn parse_one_dir(cmd: &str, args: &[&str]) -> Result<PathBuf, String> {
2453    let mut db_dir = None;
2454    for a in args {
2455        if a.starts_with('-') {
2456            return Err(format!("unexpected flag: {a}"));
2457        }
2458        if db_dir.is_some() {
2459            return Err(format!("unexpected extra argument: {a}"));
2460        }
2461        db_dir = Some(PathBuf::from(*a));
2462    }
2463    db_dir.ok_or_else(|| format!("{cmd} requires <db-dir>"))
2464}
2465
2466/// Pretty-print [`Stats`] for `mushroomdb stats` and the demo smoke test.
2467pub fn format_stats(stats: &Stats) -> String {
2468    let mut out = String::new();
2469    let _ = writeln!(
2470        out,
2471        "nodes: {} live, {} tombstoned",
2472        stats.nodes_live, stats.nodes_tombstoned
2473    );
2474    let _ = writeln!(out, "edges: {}", stats.edges);
2475    if stats.history_floor == 0 {
2476        let _ = writeln!(out, "history: complete (nothing pruned)");
2477    } else {
2478        let _ = writeln!(
2479            out,
2480            "history: reaches back to commit {}",
2481            stats.history_floor
2482        );
2483    }
2484    // A store that names no namespace is one implicit `default` namespace, and
2485    // saying so would be noise on every single-tenant store — so the line
2486    // appears only once there is more than one, which keeps existing output
2487    // byte-identical.
2488    if stats.namespaces.len() > 1 {
2489        let names: Vec<String> = stats
2490            .namespaces
2491            .iter()
2492            .map(|n| format!("{} ({})", n.name, n.nodes_live))
2493            .collect();
2494        let _ = writeln!(out, "namespaces: {}", names.join(", "));
2495    }
2496    let _ = writeln!(out, "rules: {}", stats.rules.len());
2497    for r in &stats.rules {
2498        let _ = writeln!(
2499            out,
2500            "  {:<28} edges={}  tripped={}",
2501            r.name, r.edges, r.tripped
2502        );
2503    }
2504    out
2505}
2506
2507/// Open `dir` and return live stats.
2508pub fn read_stats(dir: &Path) -> Result<Stats, CliError> {
2509    let db = SharedDb::open(dir)?;
2510    let stats = db.read().stats();
2511    Ok(stats)
2512}
2513
2514/// Build the deterministic demo dataset in an empty `dir`.
2515///
2516/// Refuses if `dir` already exists and is not empty. Ingests 10 Orgs, 20
2517/// Projects, 30 People via [`SharedDb`] / `ingest_json` (auto-FK on `*_id`)
2518/// then declares `skill_fit` plus the three Predicates II rules.
2519pub fn run_demo(dir: &Path) -> Result<DemoOutcome, CliError> {
2520    refuse_non_empty(dir)?;
2521
2522    let db = SharedDb::open(dir)?;
2523    let opts = IngestOptions::default();
2524    let mut auto_fk_rules = Vec::new();
2525
2526    {
2527        let mut w = db.write();
2528        // A demo store is the first store most readers open. Declare the
2529        // memory schema before the first write so `recall` can answer on it.
2530        w.apply_schema(&core_api::memory_schema::memory_defaults())?;
2531        for (label, json) in [
2532            ("Org", org_json()),
2533            ("Project", project_json()),
2534            ("Person", person_json()),
2535        ] {
2536            let report = w.ingest_json(label, &json, &opts)?;
2537            if !report.row_errors.is_empty() {
2538                return Err(CliError(format!(
2539                    "demo ingest of {label} had row errors: {:?}",
2540                    report.row_errors
2541                )));
2542            }
2543            auto_fk_rules.extend(report.rules_created);
2544        }
2545        let skill_fit = Predicate::Overlap {
2546            field: "skills".into(),
2547            min: 0.5,
2548        };
2549        let skill_fit_k = Some(default_max_edges(&skill_fit));
2550        w.create_rule(RuleDef {
2551            name: "skill_fit".into(),
2552            src_label: "Person".into(),
2553            dst_label: "Project".into(),
2554            predicate: skill_fit,
2555            edge_type: "FIT".into(),
2556            weight_prop: Some("score".into()),
2557            max_edges: skill_fit_k,
2558            approximate: false,
2559            via_label: None,
2560            via_edge: None,
2561            via_dir: None,
2562            namespace: None,
2563        })?;
2564        let founded_within = Predicate::NumericWithin {
2565            field: "founded_year".into(),
2566            tolerance: 2.0,
2567        };
2568        let founded_within_k = Some(default_max_edges(&founded_within));
2569        w.create_rule(RuleDef {
2570            name: "founded_within".into(),
2571            src_label: "Org".into(),
2572            dst_label: "Org".into(),
2573            predicate: founded_within,
2574            edge_type: "FOUNDED_WITHIN".into(),
2575            weight_prop: Some("score".into()),
2576            max_edges: founded_within_k,
2577            approximate: false,
2578            via_label: None,
2579            via_edge: None,
2580            via_dir: None,
2581            namespace: None,
2582        })?;
2583        let nearby_office = Predicate::GeoRadius {
2584            field: "office".into(),
2585            km: 50.0,
2586        };
2587        let nearby_office_k = Some(default_max_edges(&nearby_office));
2588        w.create_rule(RuleDef {
2589            name: "nearby_office".into(),
2590            src_label: "Org".into(),
2591            dst_label: "Org".into(),
2592            predicate: nearby_office,
2593            edge_type: "NEARBY_OFFICE".into(),
2594            weight_prop: Some("score".into()),
2595            max_edges: nearby_office_k,
2596            approximate: false,
2597            via_label: None,
2598            via_edge: None,
2599            via_dir: None,
2600            namespace: None,
2601        })?;
2602        let similar_interests = Predicate::VectorSimilar {
2603            field: "embedding".into(),
2604            min: 0.8,
2605        };
2606        let similar_interests_k = Some(default_max_edges(&similar_interests));
2607        w.create_rule(RuleDef {
2608            name: "similar_interests".into(),
2609            src_label: "Person".into(),
2610            dst_label: "Person".into(),
2611            predicate: similar_interests,
2612            edge_type: "SIMILAR".into(),
2613            weight_prop: Some("score".into()),
2614            max_edges: similar_interests_k,
2615            approximate: false,
2616            via_label: None,
2617            via_edge: None,
2618            via_dir: None,
2619            namespace: None,
2620        })?;
2621    }
2622
2623    let r = db.read();
2624    let sample_result = r.query(SAMPLE_QUERY, &BTreeMap::new())?;
2625    let explanations = r.explain(SAMPLE_EXPLAIN_A, SAMPLE_EXPLAIN_B)?;
2626    let stats = r.stats();
2627    // Rule suggestion teaser: first suggestion sorted by est_edges desc.
2628    let suggestion = r.suggest_rules().into_iter().next();
2629
2630    Ok(DemoOutcome {
2631        auto_fk_rules,
2632        sample_query: SAMPLE_QUERY.to_string(),
2633        sample_result,
2634        explanations,
2635        stats,
2636        suggestion,
2637    })
2638}
2639
2640fn dir_is_empty_or_absent(dir: &Path) -> Result<bool, CliError> {
2641    if dir.is_file() {
2642        return Err(CliError(format!(
2643            "demo refuses a non-empty directory: {} is a file",
2644            dir.display()
2645        )));
2646    }
2647    if !dir.exists() {
2648        return Ok(true);
2649    }
2650    Ok(std::fs::read_dir(dir)?.next().is_none())
2651}
2652
2653fn refuse_non_empty(dir: &Path) -> Result<(), CliError> {
2654    if dir_is_empty_or_absent(dir)? {
2655        Ok(())
2656    } else {
2657        Err(CliError(format!(
2658            "demo refuses a non-empty directory: {} \
2659             (directory must be empty — including hidden files)",
2660            dir.display()
2661        )))
2662    }
2663}
2664
2665/// Run [`run_demo`] when `dir` is missing or empty; otherwise leave it alone.
2666pub fn maybe_run_demo_if_empty(dir: &Path) -> Result<Option<DemoOutcome>, CliError> {
2667    if dir_is_empty_or_absent(dir)? {
2668        Ok(Some(run_demo(dir)?))
2669    } else {
2670        Ok(None)
2671    }
2672}
2673
2674fn json_array(rows: impl IntoIterator<Item = String>) -> String {
2675    let mut out = String::from("[");
2676    let mut first = true;
2677    for row in rows {
2678        if !first {
2679            out.push(',');
2680        }
2681        first = false;
2682        out.push_str(&row);
2683    }
2684    out.push(']');
2685    out
2686}
2687
2688/// Wrap a 1-based project index into `1..=N_PROJECTS`.
2689fn wrap_proj(i: usize) -> usize {
2690    (i - 1) % N_PROJECTS + 1
2691}
2692
2693/// Sliding window of `len` skill tokens starting at project `start`.
2694fn skill_window_json(start: usize, len: usize) -> String {
2695    let parts: Vec<String> = (0..len)
2696        .map(|k| format!(r#""s{:02}""#, wrap_proj(start + k)))
2697        .collect();
2698    format!("[{}]", parts.join(","))
2699}
2700
2701/// Real city [lat, lon] for org `i` (1-based). Four clusters sit inside 50 km:
2702/// NYC / Jersey City / Newark, SF / Oakland / Berkeley, London / Greenwich,
2703/// Paris / Versailles.
2704fn org_office(i: usize) -> (f64, f64) {
2705    match i {
2706        1 => (40.7128, -74.0060),  // New York
2707        2 => (48.8566, 2.3522),    // Paris
2708        3 => (51.5074, -0.1278),   // London
2709        4 => (37.7749, -122.4194), // San Francisco
2710        5 => (37.8044, -122.2711), // Oakland
2711        6 => (37.8715, -122.2730), // Berkeley
2712        7 => (40.7178, -74.0431),  // Jersey City
2713        8 => (51.4769, 0.0005),    // Greenwich
2714        9 => (48.8014, 2.1301),    // Versailles
2715        10 => (40.7357, -74.1724), // Newark
2716        _ => unreachable!("demo orgs are 1..=10"),
2717    }
2718}
2719
2720/// Dim-8 embedding for person `i`. Groups of three share a unit axis (cos = 1);
2721/// two extra groups are (0.8, 0.6, …) and (0.6, 0.8, …) so cos = 0.8 / 0.96
2722/// against the first two axes is hand-checkable.
2723fn person_embedding_json(i: usize) -> String {
2724    let mut v = [0.0_f64; 8];
2725    match i {
2726        9 | 19 | 29 => {
2727            v[0] = 0.8;
2728            v[1] = 0.6;
2729        }
2730        10 | 20 | 30 => {
2731            v[0] = 0.6;
2732            v[1] = 0.8;
2733        }
2734        _ => {
2735            let axis = (i - 1) % 10;
2736            debug_assert!(axis < 8);
2737            v[axis] = 1.0;
2738        }
2739    }
2740    let parts: Vec<String> = v.iter().map(|x| format!("{x}")).collect();
2741    format!("[{}]", parts.join(","))
2742}
2743
2744fn org_json() -> String {
2745    json_array((1..=N_ORGS).map(|i| {
2746        let year = 2010 + (i as i64 - 1);
2747        let (lat, lon) = org_office(i);
2748        format!(
2749            r#"{{"id":"org-{i:02}","name":"Org {i}","founded_year":{year},"office":[{lat},{lon}],"skills":{}}}"#,
2750            skill_window_json(i, 3)
2751        )
2752    }))
2753}
2754
2755fn project_json() -> String {
2756    json_array((1..=N_PROJECTS).map(|i| {
2757        let org = (i - 1) % N_ORGS + 1;
2758        format!(
2759            r#"{{"id":"proj-{i:02}","name":"Project {i}","org_id":"org-{org:02}","skills":{}}}"#,
2760            skill_window_json(i, 3)
2761        )
2762    }))
2763}
2764
2765fn person_json() -> String {
2766    json_array((1..=N_PEOPLE).map(|i| {
2767        let org = (i - 1) % N_ORGS + 1;
2768        let proj = (i - 1) % N_PROJECTS + 1;
2769        format!(
2770            r#"{{"id":"person-{i:02}","name":"Person {i}","org_id":"org-{org:02}","project_id":"proj-{proj:02}","embedding":{},"skills":{}}}"#,
2771            person_embedding_json(i),
2772            skill_window_json(proj, 3)
2773        )
2774    }))
2775}
2776
2777/// Render a [`DemoOutcome`] the way `mushroomdb demo` prints it.
2778pub fn format_demo(dir: &Path, out: &DemoOutcome) -> String {
2779    let mut buf = String::new();
2780    let _ = writeln!(buf, "== demo ==");
2781    let _ = writeln!(
2782        buf,
2783        "ingested {N_ORGS} Orgs, {N_PROJECTS} Projects, {N_PEOPLE} People"
2784    );
2785    let _ = writeln!(
2786        buf,
2787        "overlap rule: skill_fit (Person.skills ∩ Project.skills, min 0.5)"
2788    );
2789    let _ = writeln!(
2790        buf,
2791        "numeric rule: founded_within (Org.founded_year, tolerance 2)"
2792    );
2793    let _ = writeln!(buf, "geo rule: nearby_office (Org.office [lat,lon], 50 km)");
2794    let _ = writeln!(
2795        buf,
2796        "vector rule: similar_interests (Person.embedding dim 8, min 0.8)"
2797    );
2798    let _ = writeln!(buf);
2799    let _ = writeln!(buf, "== auto-FK rules ==");
2800    let mut names = out.auto_fk_rules.clone();
2801    names.sort();
2802    for name in names {
2803        let _ = writeln!(buf, "  {name}");
2804    }
2805    let _ = writeln!(buf);
2806    let _ = writeln!(buf, "== query ==");
2807    let _ = writeln!(buf, "{}", out.sample_query);
2808    let _ = writeln!(buf);
2809    let _ = writeln!(buf, "columns: {}", out.sample_result.columns().join(", "));
2810    for i in 0..out.sample_result.len() {
2811        let cells: Vec<String> = out
2812            .sample_result
2813            .columns()
2814            .iter()
2815            .map(|c| format!("{c}={}", fmt_cell(out.sample_result.get(i, c))))
2816            .collect();
2817        let _ = writeln!(buf, "  {}", cells.join("  "));
2818    }
2819    let _ = writeln!(buf);
2820    let _ = writeln!(
2821        buf,
2822        "== explain ({SAMPLE_EXPLAIN_A}, {SAMPLE_EXPLAIN_B}) =="
2823    );
2824    for e in &out.explanations {
2825        let weight = e
2826            .weight
2827            .map(|w| fmt_value(&Value::Float(w)))
2828            .unwrap_or_else(|| "none".into());
2829        let _ = writeln!(
2830            buf,
2831            "  rule={}  type={}  {}→{}  weight={}",
2832            e.rule, e.edge_type, e.src_key, e.dst_key, weight
2833        );
2834    }
2835    let _ = writeln!(buf);
2836    let _ = writeln!(buf, "== serve ==");
2837    let _ = writeln!(buf, "  mushroomdb serve {}", dir.display());
2838
2839    // Teaser: one suggestion from the rule suggester (not auto-applied).
2840    if let Some(s) = &out.suggestion {
2841        let _ = writeln!(buf);
2842        let _ = writeln!(buf, "== suggested rule (teaser) ==");
2843        let _ = writeln!(buf, "  {}", s.def.name);
2844        let _ = writeln!(
2845            buf,
2846            "  {} → {} via {:?}",
2847            s.def.src_label, s.def.dst_label, s.def.predicate
2848        );
2849        let _ = writeln!(buf, "  est_edges: ~{}", s.est_edges);
2850        let _ = writeln!(buf, "  {}", s.rationale);
2851        let _ = writeln!(
2852            buf,
2853            "  (run `mushroomdb suggest {}` for full analysis)",
2854            dir.display()
2855        );
2856    }
2857
2858    buf
2859}
2860
2861/// Profile the database at `dir` and return all rule suggestions.
2862pub fn run_suggest(dir: &Path) -> Result<Vec<RuleSuggestion>, CliError> {
2863    let db = GraphDb::open(dir)?;
2864    Ok(db.suggest_rules())
2865}
2866
2867/// Pretty-print a list of [`RuleSuggestion`]s for `mushroomdb suggest`.
2868pub fn format_suggest(suggestions: &[RuleSuggestion]) -> String {
2869    let mut buf = String::new();
2870    if suggestions.is_empty() {
2871        let _ = writeln!(
2872            buf,
2873            "no rule suggestions (database may be empty or rules already cover all patterns)"
2874        );
2875        return buf;
2876    }
2877    let _ = writeln!(buf, "== rule suggestions ({}) ==", suggestions.len());
2878    for (i, s) in suggestions.iter().enumerate() {
2879        let _ = writeln!(buf);
2880        let _ = writeln!(buf, "[{}] {}", i + 1, s.def.name);
2881        let _ = writeln!(
2882            buf,
2883            "    {} → {}  via {:?}",
2884            s.def.src_label, s.def.dst_label, s.def.predicate
2885        );
2886        let _ = writeln!(buf, "    est_edges : ~{}", s.est_edges);
2887        let _ = writeln!(buf, "    rationale : {}", s.rationale);
2888        if !s.examples.is_empty() {
2889            let _ = writeln!(buf, "    examples  :");
2890            for (src, dst, score) in &s.examples {
2891                let _ = writeln!(buf, "      {src} → {dst}  score={score:.4}");
2892            }
2893        }
2894        let _ = writeln!(buf, "    predicate : {:?}", s.def.predicate);
2895        let _ = writeln!(
2896            buf,
2897            "    to apply  : POST /rules  or  db.create_rule(suggestion.def)"
2898        );
2899    }
2900    buf
2901}
2902
2903fn fmt_value(v: &Value) -> String {
2904    match v {
2905        Value::Int(i) => i.to_string(),
2906        Value::Float(f) => {
2907            let s = format!("{f}");
2908            if s.contains('.') || s.contains('e') || s.contains('E') {
2909                s
2910            } else {
2911                format!("{s}.0")
2912            }
2913        }
2914        Value::Str(s) => s.clone(),
2915        Value::Bool(b) => b.to_string(),
2916        Value::List(xs) => {
2917            let inner: Vec<String> = xs.iter().map(fmt_value).collect();
2918            format!("[{}]", inner.join(", "))
2919        }
2920        Value::Map(m) => {
2921            let inner: Vec<String> = m
2922                .iter()
2923                .map(|(k, v)| format!("{k}: {}", fmt_value(v)))
2924                .collect();
2925            format!("{{{}}}", inner.join(", "))
2926        }
2927    }
2928}
2929
2930fn fmt_cell(cell: Option<&Value>) -> String {
2931    match cell {
2932        None => "null".into(),
2933        Some(v) => fmt_value(v),
2934    }
2935}
2936
2937#[cfg(test)]
2938mod tests {
2939    use super::*;
2940    use std::collections::BTreeSet;
2941    use std::net::SocketAddr;
2942    use std::path::PathBuf;
2943
2944    fn tmp(name: &str) -> PathBuf {
2945        let nanos = std::time::SystemTime::now()
2946            .duration_since(std::time::UNIX_EPOCH)
2947            .expect("clock")
2948            .as_nanos();
2949        let d = std::env::temp_dir().join(format!(
2950            "graphdb-cli-{}-{}-{}",
2951            name,
2952            std::process::id(),
2953            nanos
2954        ));
2955        let _ = std::fs::remove_dir_all(&d);
2956        d
2957    }
2958
2959    fn directed_pairs(db: &SharedDb, etype: &str) -> BTreeSet<(String, String)> {
2960        let g = db.read();
2961        let mut out = BTreeSet::new();
2962        for i in 1..=N_ORGS {
2963            let src = format!("org-{i:02}");
2964            if let Ok(nbrs) = g.neighbors(&src, etype, core_api::Direction::Out) {
2965                for dst in nbrs {
2966                    out.insert((src.clone(), dst));
2967                }
2968            }
2969        }
2970        for i in 1..=N_PEOPLE {
2971            let src = format!("person-{i:02}");
2972            if let Ok(nbrs) = g.neighbors(&src, etype, core_api::Direction::Out) {
2973                for dst in nbrs {
2974                    out.insert((src.clone(), dst));
2975                }
2976            }
2977        }
2978        out
2979    }
2980
2981    fn assert_weight(db: &SharedDb, a: &str, b: &str, rule: &str, want: f64) {
2982        let hits: Vec<_> = db
2983            .read()
2984            .explain(a, b)
2985            .expect("explain")
2986            .into_iter()
2987            .filter(|e| e.rule == rule && e.src_key == a && e.dst_key == b)
2988            .collect();
2989        assert_eq!(hits.len(), 1, "explain {a}/{b} rule={rule}: {hits:?}");
2990        let got = hits[0].weight.expect("weighted");
2991        assert!(
2992            (got - want).abs() < 1e-12,
2993            "{rule} {a}→{b}: got {got} want {want}"
2994        );
2995    }
2996
2997    fn haversine_km(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {
2998        const R: f64 = 6371.0088;
2999        let phi1 = lat1.to_radians();
3000        let phi2 = lat2.to_radians();
3001        let dphi = (lat2 - lat1).to_radians();
3002        let dlam = (lon2 - lon1).to_radians();
3003        let a = ((dphi / 2.0).sin().powi(2) + phi1.cos() * phi2.cos() * (dlam / 2.0).sin().powi(2))
3004            .clamp(0.0, 1.0);
3005        let c = 2.0 * a.sqrt().atan2((1.0 - a).sqrt());
3006        R * c
3007    }
3008
3009    fn default_bind() -> SocketAddr {
3010        SocketAddr::from(([127, 0, 0, 1], 8080))
3011    }
3012
3013    #[test]
3014    fn parse_args_table() {
3015        struct Case {
3016            args: &'static [&'static str],
3017            check: fn(Result<Command, String>),
3018        }
3019
3020        let cases = [
3021            Case {
3022                args: &[],
3023                check: |r| match r {
3024                    Ok(Command::Help) => {}
3025                    other => panic!("no-args → Help, got {other:?}"),
3026                },
3027            },
3028            Case {
3029                args: &["--help"],
3030                check: |r| match r {
3031                    Ok(Command::Help) => {}
3032                    other => panic!("--help → Help, got {other:?}"),
3033                },
3034            },
3035            Case {
3036                args: &["-h"],
3037                check: |r| match r {
3038                    Ok(Command::Help) => {}
3039                    other => panic!("-h → Help, got {other:?}"),
3040                },
3041            },
3042            Case {
3043                args: &["serve", "/tmp/demo-db"],
3044                check: |r| match r {
3045                    Ok(Command::Serve {
3046                        db_dir,
3047                        addr,
3048                        ui,
3049                        demo_if_empty,
3050                        token,
3051                        role_tokens,
3052                        snapshot_every,
3053                        restore_from,
3054                        tls_cert,
3055                        tls_key,
3056                    }) => {
3057                        assert_eq!(db_dir, PathBuf::from("/tmp/demo-db"));
3058                        assert_eq!(addr, default_bind());
3059                        assert_eq!(ui, super::ServeUi::Embedded);
3060                        assert!(!demo_if_empty);
3061                        assert_eq!(token, None);
3062                        assert!(role_tokens.is_empty());
3063                        assert_eq!(snapshot_every, None);
3064                        assert_eq!(restore_from, None);
3065                        assert_eq!(tls_cert, None);
3066                        assert_eq!(tls_key, None);
3067                    }
3068                    other => panic!("serve <dir> → Serve default addr, got {other:?}"),
3069                },
3070            },
3071            Case {
3072                args: &["serve", "/tmp/demo-db", "--addr", "127.0.0.1:8080"],
3073                check: |r| match r {
3074                    Ok(Command::Serve {
3075                        db_dir,
3076                        addr,
3077                        ui,
3078                        demo_if_empty,
3079                        token,
3080                        role_tokens,
3081                        snapshot_every,
3082                        restore_from,
3083                        tls_cert,
3084                        tls_key,
3085                    }) => {
3086                        assert_eq!(db_dir, PathBuf::from("/tmp/demo-db"));
3087                        assert_eq!(
3088                            addr,
3089                            "127.0.0.1:8080".parse::<std::net::SocketAddr>().unwrap()
3090                        );
3091                        assert_eq!(ui, super::ServeUi::Embedded);
3092                        assert!(!demo_if_empty);
3093                        assert_eq!(token, None);
3094                        assert!(role_tokens.is_empty());
3095                        assert_eq!(snapshot_every, None);
3096                        assert_eq!(restore_from, None);
3097                        assert_eq!(tls_cert, None);
3098                        assert_eq!(tls_key, None);
3099                    }
3100                    other => panic!("serve --addr after dir, got {other:?}"),
3101                },
3102            },
3103            Case {
3104                args: &["serve", "/tmp/demo-db", "--addr=127.0.0.1:9090"],
3105                check: |r| match r {
3106                    Ok(Command::Serve {
3107                        db_dir,
3108                        addr,
3109                        ui,
3110                        demo_if_empty,
3111                        token,
3112                        role_tokens,
3113                        snapshot_every,
3114                        restore_from,
3115                        tls_cert,
3116                        tls_key,
3117                    }) => {
3118                        assert_eq!(db_dir, PathBuf::from("/tmp/demo-db"));
3119                        assert_eq!(
3120                            addr,
3121                            "127.0.0.1:9090".parse::<std::net::SocketAddr>().unwrap()
3122                        );
3123                        assert_eq!(ui, super::ServeUi::Embedded);
3124                        assert!(!demo_if_empty);
3125                        assert_eq!(token, None);
3126                        let _ = role_tokens; // empty, not asserted
3127                        assert_eq!(snapshot_every, None);
3128                        assert_eq!(restore_from, None);
3129                        assert_eq!(tls_cert, None);
3130                        assert_eq!(tls_key, None);
3131                    }
3132                    other => panic!("serve --addr=VALUE, got {other:?}"),
3133                },
3134            },
3135            Case {
3136                args: &["mcp", "/tmp/demo-db"],
3137                check: |r| match r {
3138                    Ok(Command::Mcp {
3139                        db_dir,
3140                        auto,
3141                        all_tools,
3142                    }) => {
3143                        assert_eq!(db_dir, Some(PathBuf::from("/tmp/demo-db")));
3144                        assert!(!auto);
3145                        assert!(!all_tools, "the short list is the default");
3146                    }
3147                    other => panic!("mcp <dir>, got {other:?}"),
3148                },
3149            },
3150            Case {
3151                args: &["stats", "/tmp/demo-db"],
3152                check: |r| match r {
3153                    Ok(Command::Stats { db_dir }) => {
3154                        assert_eq!(db_dir, PathBuf::from("/tmp/demo-db"));
3155                    }
3156                    other => panic!("stats <dir>, got {other:?}"),
3157                },
3158            },
3159            Case {
3160                args: &["demo", "/tmp/demo-db"],
3161                check: |r| match r {
3162                    Ok(Command::Demo { db_dir }) => {
3163                        assert_eq!(db_dir, PathBuf::from("/tmp/demo-db"));
3164                    }
3165                    other => panic!("demo <dir>, got {other:?}"),
3166                },
3167            },
3168            Case {
3169                args: &["serve"],
3170                check: |r| {
3171                    let e = r.expect_err("serve without dir");
3172                    assert!(
3173                        e.to_lowercase().contains("db-dir") || e.to_lowercase().contains("dir"),
3174                        "missing-dir error should mention dir, got {e}"
3175                    );
3176                },
3177            },
3178            Case {
3179                args: &["mcp"],
3180                check: |r| {
3181                    let e = r.expect_err("mcp without dir");
3182                    assert!(
3183                        e.to_lowercase().contains("db-dir") || e.to_lowercase().contains("dir"),
3184                        "missing-dir error should mention dir, got {e}"
3185                    );
3186                },
3187            },
3188            Case {
3189                args: &["stats"],
3190                check: |r| {
3191                    let e = r.expect_err("stats without dir");
3192                    assert!(
3193                        e.to_lowercase().contains("db-dir") || e.to_lowercase().contains("dir"),
3194                        "missing-dir error should mention dir, got {e}"
3195                    );
3196                },
3197            },
3198            Case {
3199                args: &["demo"],
3200                check: |r| {
3201                    let e = r.expect_err("demo without dir");
3202                    assert!(
3203                        e.to_lowercase().contains("db-dir") || e.to_lowercase().contains("dir"),
3204                        "missing-dir error should mention dir, got {e}"
3205                    );
3206                },
3207            },
3208            Case {
3209                args: &["serve", "/tmp/demo-db", "--addr"],
3210                check: |r| {
3211                    let e = r.expect_err("--addr missing value");
3212                    assert!(
3213                        e.to_lowercase().contains("addr"),
3214                        "--addr missing value should mention addr, got {e}"
3215                    );
3216                },
3217            },
3218            Case {
3219                args: &["serve", "/tmp/demo-db", "--addr", "not-an-addr"],
3220                check: |r| {
3221                    let e = r.expect_err("invalid addr");
3222                    assert!(
3223                        e.to_lowercase().contains("addr") || e.to_lowercase().contains("address"),
3224                        "invalid addr should mention address, got {e}"
3225                    );
3226                },
3227            },
3228            Case {
3229                args: &["frobnicate", "/tmp/demo-db"],
3230                check: |r| {
3231                    let e = r.expect_err("unknown command");
3232                    assert!(
3233                        e.to_lowercase().contains("unknown")
3234                            || e.to_lowercase().contains("frobnicate"),
3235                        "unknown command should name it, got {e}"
3236                    );
3237                },
3238            },
3239            Case {
3240                args: &["serve", "/tmp/demo-db", "--ui", "/tmp/ui-dist"],
3241                check: |r| match r {
3242                    Ok(Command::Serve { ui, .. }) => {
3243                        assert_eq!(
3244                            ui,
3245                            super::ServeUi::Filesystem(PathBuf::from("/tmp/ui-dist"))
3246                        );
3247                    }
3248                    other => panic!("serve --ui <dir>, got {other:?}"),
3249                },
3250            },
3251            Case {
3252                args: &["serve", "/tmp/demo-db", "--ui=/tmp/ui-eq"],
3253                check: |r| match r {
3254                    Ok(Command::Serve { ui, .. }) => {
3255                        assert_eq!(ui, super::ServeUi::Filesystem(PathBuf::from("/tmp/ui-eq")));
3256                    }
3257                    other => panic!("serve --ui=VALUE, got {other:?}"),
3258                },
3259            },
3260            Case {
3261                args: &["serve", "/tmp/demo-db", "--ui"],
3262                check: |r| {
3263                    let e = r.expect_err("--ui missing value");
3264                    assert!(
3265                        e.to_lowercase().contains("ui"),
3266                        "--ui missing value should mention ui, got {e}"
3267                    );
3268                },
3269            },
3270            Case {
3271                args: &["serve", "/tmp/demo-db", "--no-ui"],
3272                check: |r| match r {
3273                    Ok(Command::Serve { ui, .. }) => {
3274                        assert_eq!(ui, super::ServeUi::None);
3275                    }
3276                    other => panic!("serve --no-ui, got {other:?}"),
3277                },
3278            },
3279            Case {
3280                args: &["serve", "/tmp/demo-db", "--ui", "/tmp/x", "--no-ui"],
3281                check: |r| {
3282                    let e = r.expect_err("combine --ui and --no-ui");
3283                    assert!(
3284                        e.contains("--ui") && e.contains("--no-ui"),
3285                        "conflict should name both flags, got {e}"
3286                    );
3287                },
3288            },
3289            Case {
3290                args: &["serve", "/tmp/demo-db", "extra"],
3291                check: |r| {
3292                    let e = r.expect_err("extra positional");
3293                    assert!(
3294                        e.to_lowercase().contains("unexpected")
3295                            || e.to_lowercase().contains("extra"),
3296                        "extra arg should be rejected, got {e}"
3297                    );
3298                },
3299            },
3300            Case {
3301                args: &[
3302                    "serve",
3303                    "/data",
3304                    "--addr",
3305                    "0.0.0.0:8080",
3306                    "--demo-if-empty",
3307                ],
3308                check: |r| match r {
3309                    Ok(Command::Serve {
3310                        db_dir,
3311                        addr,
3312                        demo_if_empty,
3313                        ui,
3314                        token,
3315                        snapshot_every,
3316                        ..
3317                    }) => {
3318                        assert_eq!(db_dir, PathBuf::from("/data"));
3319                        assert_eq!(
3320                            addr,
3321                            "0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap()
3322                        );
3323                        assert!(demo_if_empty);
3324                        assert_eq!(ui, super::ServeUi::Embedded);
3325                        assert_eq!(token, None);
3326                        assert_eq!(snapshot_every, None);
3327                    }
3328                    other => panic!("serve --demo-if-empty docker default, got {other:?}"),
3329                },
3330            },
3331            Case {
3332                args: &["install", "--project", "--delivery", "cli"],
3333                check: |r| match r {
3334                    Ok(Command::Install(opts)) => {
3335                        assert_eq!(opts.scope, Some(install::Scope::Project));
3336                        assert_eq!(opts.delivery, install::Delivery::Cli);
3337                    }
3338                    other => panic!("install --delivery cli, got {other:?}"),
3339                },
3340            },
3341            Case {
3342                args: &["install", "--delivery=mcp"],
3343                check: |r| match r {
3344                    Ok(Command::Install(opts)) => {
3345                        assert_eq!(opts.delivery, install::Delivery::Mcp)
3346                    }
3347                    other => panic!("install --delivery=mcp, got {other:?}"),
3348                },
3349            },
3350            Case {
3351                // No flag is the default, and it is the one that opens both
3352                // doors: an upgrade must not quietly drop a user's server.
3353                args: &["install"],
3354                check: |r| match r {
3355                    Ok(Command::Install(opts)) => {
3356                        assert_eq!(opts.delivery, install::Delivery::Both)
3357                    }
3358                    other => panic!("install, got {other:?}"),
3359                },
3360            },
3361            Case {
3362                args: &["install", "--delivery", "sideways"],
3363                check: |r| match r {
3364                    Err(e) => assert!(e.contains("--delivery must be cli | mcp | both"), "{e}"),
3365                    other => panic!("a bad --delivery must be refused, got {other:?}"),
3366                },
3367            },
3368            Case {
3369                args: &["install", "--always-load"],
3370                check: |r| match r {
3371                    Ok(Command::Install(opts)) => assert!(opts.always_load),
3372                    other => panic!("install --always-load, got {other:?}"),
3373                },
3374            },
3375            Case {
3376                // 0.7 writes no git hooks, so `--no-git-hooks` asks for what
3377                // every install already gets: accepted, not refused.
3378                args: &["install", "--no-git-hooks"],
3379                check: |r| match r {
3380                    Ok(Command::Install(_)) => {}
3381                    other => panic!("install --no-git-hooks, got {other:?}"),
3382                },
3383            },
3384            Case {
3385                // An install that names its store and registers a server is
3386                // an entity-store install: `alwaysLoad` without asking, so a
3387                // session meets the tools rather than searching for them.
3388                args: &["install", "--delivery", "mcp", "--db", "./mem"],
3389                check: |r| match r {
3390                    Ok(Command::Install(opts)) => assert!(opts.always_load),
3391                    other => panic!("install --delivery mcp --db, got {other:?}"),
3392                },
3393            },
3394            Case {
3395                // `both` registers a server too, so it defaults the same way.
3396                args: &["install", "--delivery", "both", "--db=./mem"],
3397                check: |r| match r {
3398                    Ok(Command::Install(opts)) => assert!(opts.always_load),
3399                    other => panic!("install --delivery both --db, got {other:?}"),
3400                },
3401            },
3402            Case {
3403                // …and `--no-always-load` is the way out of it.
3404                args: &[
3405                    "install",
3406                    "--delivery",
3407                    "mcp",
3408                    "--db",
3409                    "./mem",
3410                    "--no-always-load",
3411                ],
3412                check: |r| match r {
3413                    Ok(Command::Install(opts)) => assert!(!opts.always_load),
3414                    other => panic!("install --no-always-load, got {other:?}"),
3415                },
3416            },
3417            Case {
3418                // A `--delivery cli` install registers no server, so there is
3419                // no entry for the key to go on: naming a store cannot turn
3420                // it on.
3421                args: &["install", "--delivery", "cli", "--db", "./mem"],
3422                check: |r| match r {
3423                    Ok(Command::Install(opts)) => assert!(!opts.always_load),
3424                    other => panic!("install --delivery cli --db, got {other:?}"),
3425                },
3426            },
3427            Case {
3428                // An install with no `--db` resolves whatever store the
3429                // directory has — usually the code graph — and stays opt-in.
3430                // `--always-load` still forces it.
3431                args: &["install", "--always-load"],
3432                check: |r| match r {
3433                    Ok(Command::Install(opts)) => assert!(opts.always_load),
3434                    other => panic!("install --always-load, got {other:?}"),
3435                },
3436            },
3437            Case {
3438                // The one experiment left is off unless it is asked for.
3439                args: &["install"],
3440                check: |r| match r {
3441                    Ok(Command::Install(opts)) => assert!(!opts.always_load),
3442                    other => panic!("install, got {other:?}"),
3443                },
3444            },
3445        ];
3446
3447        for case in &cases {
3448            (case.check)(parse_args(case.args));
3449        }
3450    }
3451
3452    /// The five code-graph subcommands a person typed, left in 0.7. Each is an
3453    /// unknown command now — not a stub that prints a deprecation — and the
3454    /// help text names none of them. The other five were hook bodies; see
3455    /// [`the_retired_hook_bodies_parse_as_inert`].
3456    #[test]
3457    fn the_retired_code_graph_subcommands_are_unknown() {
3458        for sub in ["map", "explore", "context", "impact", "owners"] {
3459            match parse_args(&[sub, "/tmp/db"]) {
3460                Err(e) => assert_eq!(e, format!("unknown command: {sub}")),
3461                other => panic!("{sub} still parses: {other:?}"),
3462            }
3463            assert!(
3464                !usage().contains(&format!("mushroomdb {sub} ")),
3465                "the help still names {sub}"
3466            );
3467        }
3468    }
3469
3470    /// The five hook bodies 0.6 installed parse, with any arguments, to the
3471    /// inert [`Command::RetiredHook`], so an upgraded machine that has not
3472    /// re-run `install` is not shown a hook error on every tool call. The help
3473    /// still names none of them.
3474    #[test]
3475    fn the_retired_hook_bodies_parse_as_inert() {
3476        for sub in ["touch", "intercept", "impact-hook", "enrich", "sync"] {
3477            for args in [
3478                vec![sub],
3479                vec![sub, "--auto"],
3480                vec![sub, "/tmp/db", "--whatever", "x"],
3481            ] {
3482                assert_eq!(
3483                    parse_args(&args),
3484                    Ok(Command::RetiredHook { sub }),
3485                    "{args:?}"
3486                );
3487            }
3488            assert!(
3489                !usage().contains(&format!("mushroomdb {sub}")),
3490                "the help still names {sub}"
3491            );
3492        }
3493    }
3494
3495    #[test]
3496    fn serve_default_addr_is_loopback_8080() {
3497        match parse_args(&["serve", "/tmp/db"]).unwrap() {
3498            Command::Serve { addr, .. } => {
3499                assert_eq!(
3500                    addr,
3501                    "127.0.0.1:8080".parse::<std::net::SocketAddr>().unwrap()
3502                );
3503            }
3504            other => panic!("{other:?}"),
3505        }
3506    }
3507
3508    #[test]
3509    fn serve_snapshot_every_parses_seconds() {
3510        match parse_args(&["serve", "/tmp/db", "--snapshot-every", "30"]).unwrap() {
3511            Command::Serve { snapshot_every, .. } => {
3512                assert_eq!(snapshot_every, Some(Duration::from_secs(30)));
3513            }
3514            other => panic!("{other:?}"),
3515        }
3516        match parse_args(&["serve", "/tmp/db", "--snapshot-every=5"]).unwrap() {
3517            Command::Serve { snapshot_every, .. } => {
3518                assert_eq!(snapshot_every, Some(Duration::from_secs(5)));
3519            }
3520            other => panic!("{other:?}"),
3521        }
3522        match parse_args(&["serve", "/tmp/db"]).unwrap() {
3523            Command::Serve { snapshot_every, .. } => {
3524                assert_eq!(snapshot_every, None);
3525            }
3526            other => panic!("{other:?}"),
3527        }
3528        let err = parse_args(&["serve", "/tmp/db", "--snapshot-every"]).unwrap_err();
3529        assert!(
3530            err.contains("snapshot-every"),
3531            "missing value should name the flag, got {err}"
3532        );
3533        let err = parse_args(&["serve", "/tmp/db", "--snapshot-every", "0"]).unwrap_err();
3534        assert!(
3535            err.contains("snapshot-every"),
3536            "zero should be rejected, got {err}"
3537        );
3538        let err = parse_args(&["serve", "/tmp/db", "--snapshot-every", "nope"]).unwrap_err();
3539        assert!(
3540            err.contains("snapshot-every"),
3541            "invalid value should name the flag, got {err}"
3542        );
3543    }
3544
3545    #[test]
3546    fn serve_token_flag_and_non_loopback_without_token_is_parsed() {
3547        // parse succeeds; main() enforces the bind rule. Token is stored.
3548        match parse_args(&[
3549            "serve",
3550            "/tmp/db",
3551            "--addr",
3552            "0.0.0.0:8080",
3553            "--token",
3554            "s3cret",
3555        ])
3556        .unwrap()
3557        {
3558            Command::Serve { token, addr, .. } => {
3559                assert_eq!(token.as_deref(), Some("s3cret"));
3560                assert_eq!(addr.ip().to_string(), "0.0.0.0");
3561            }
3562            other => panic!("{other:?}"),
3563        }
3564    }
3565
3566    #[test]
3567    fn parse_build_index_both_forms_and_a_missing_value() {
3568        match parse_args(&["build-index", "/tmp/db"]).unwrap() {
3569            Command::BuildIndex { db_dir, rule } => {
3570                assert_eq!(db_dir, PathBuf::from("/tmp/db"));
3571                assert_eq!(rule, None);
3572            }
3573            other => panic!("{other:?}"),
3574        }
3575        for args in [
3576            vec!["build-index", "/tmp/db", "--rule", "sim"],
3577            vec!["build-index", "/tmp/db", "--rule=sim"],
3578        ] {
3579            match parse_args(&args).unwrap() {
3580                Command::BuildIndex { db_dir, rule } => {
3581                    assert_eq!(db_dir, PathBuf::from("/tmp/db"));
3582                    assert_eq!(rule.as_deref(), Some("sim"), "{args:?}");
3583                }
3584                other => panic!("{other:?}"),
3585            }
3586        }
3587        assert_eq!(
3588            parse_args(&["build-index", "/tmp/db", "--rule"]).unwrap_err(),
3589            "--rule requires a value"
3590        );
3591        assert_eq!(
3592            parse_args(&["build-index", "/tmp/db", "--rule="]).unwrap_err(),
3593            "--rule requires a value"
3594        );
3595        assert_eq!(
3596            parse_args(&["build-index"]).unwrap_err(),
3597            "build-index requires <db-dir>"
3598        );
3599        assert!(usage().contains("mushroomdb build-index <db-dir> [--rule <name>]"));
3600    }
3601
3602    #[test]
3603    fn parse_snapshot_and_query() {
3604        // Archiving is what a snapshot does unless the user says otherwise.
3605        for (args, want) in [
3606            (vec!["snapshot", "/tmp/db"], WalDisposition::Archive),
3607            (
3608                vec!["snapshot", "/tmp/db", "--archive-wal"],
3609                WalDisposition::Archive,
3610            ),
3611            (
3612                vec!["snapshot", "/tmp/db", "--keep-wal"],
3613                WalDisposition::Keep,
3614            ),
3615            (
3616                vec!["snapshot", "/tmp/db", "--truncate"],
3617                WalDisposition::Truncate,
3618            ),
3619        ] {
3620            match parse_args(&args).unwrap() {
3621                Command::Snapshot { wal, .. } => assert_eq!(wal, want, "{args:?}"),
3622                other => panic!("{other:?}"),
3623            }
3624        }
3625        match parse_args(&["query", "/tmp/db", "MATCH (n) RETURN n LIMIT 1"]).unwrap() {
3626            Command::Query { cypher, .. } => assert!(cypher.contains("MATCH")),
3627            other => panic!("{other:?}"),
3628        }
3629        match parse_args(&["query", "/tmp/db", "MATCH", "(n)", "RETURN", "n"]).unwrap() {
3630            Command::Query { cypher, .. } => assert_eq!(cypher, "MATCH (n) RETURN n"),
3631            other => panic!("{other:?}"),
3632        }
3633        match parse_args(&["query", "/tmp/db", "--query", "MATCH (n) RETURN n"]).unwrap() {
3634            Command::Query { cypher, .. } => assert_eq!(cypher, "MATCH (n) RETURN n"),
3635            other => panic!("{other:?}"),
3636        }
3637        let text = usage();
3638        assert!(
3639            text.contains("query"),
3640            "usage should mention query, got:\n{text}"
3641        );
3642        assert!(
3643            text.contains("snapshot"),
3644            "usage should mention snapshot, got:\n{text}"
3645        );
3646    }
3647
3648    /// Binding: the help describes the tree 0.7 ships. One tool surface, the
3649    /// association tools listed on every store, and one brief — the memory
3650    /// schema's. The code-graph listing and the repository brief are gone.
3651    #[test]
3652    fn usage_describes_one_surface_and_the_memory_brief() {
3653        let text = usage();
3654        assert!(
3655            text.contains(
3656                "--all-tools lists every served tool; the default lists the association tools on every store,\n\
3657                 \x20                    a store `ingest-git` built included"
3658            ),
3659            "mcp help line, got:\n{text}"
3660        );
3661        assert!(
3662            text.contains(
3663                "mushroomdb brief <db-dir>|--auto    hook body: the store's schema in one block — labels,\n\
3664                 \x20                                     edge types, history depth, roles and one worked call per\n\
3665                 \x20                                     question kind; byte-stable, so a session host caches it once"
3666            ),
3667            "brief help line, got:\n{text}"
3668        );
3669        for stale in [
3670            "28 tools",
3671            "explore, query, stats",
3672            "most called symbols",
3673            "synced sha",
3674        ] {
3675            assert!(!text.contains(stale), "usage still says {stale:?}");
3676        }
3677    }
3678
3679    #[test]
3680    fn usage_lists_every_subcommand() {
3681        let text = usage();
3682        for word in [
3683            "serve",
3684            "mcp",
3685            "stats",
3686            "demo",
3687            "query",
3688            "snapshot",
3689            "--keep-wal",
3690            "mushroomdb",
3691            "--ui",
3692            "--no-ui",
3693            "--demo-if-empty",
3694            "--token",
3695            "--role-token TOKEN:ROLE",
3696            "--tls-cert <pem> --tls-key <pem>",
3697            "a build with the `tls` feature",
3698            "--snapshot-every",
3699        ] {
3700            assert!(
3701                text.contains(word),
3702                "usage should mention {word}, got:\n{text}"
3703            );
3704        }
3705    }
3706
3707    #[test]
3708    fn validate_ui_dir_requires_index_html() {
3709        let missing = tmp("ui-missing");
3710        let err = super::validate_ui_dir(&missing).expect_err("missing dir");
3711        assert!(
3712            err.contains("does not exist"),
3713            "missing dir error, got {err}"
3714        );
3715
3716        let empty = tmp("ui-empty");
3717        std::fs::create_dir_all(&empty).unwrap();
3718        let err = super::validate_ui_dir(&empty).expect_err("no index");
3719        assert!(
3720            err.contains("index.html"),
3721            "missing index.html error, got {err}"
3722        );
3723
3724        let ok = tmp("ui-ok");
3725        std::fs::create_dir_all(&ok).unwrap();
3726        std::fs::write(ok.join("index.html"), "<!doctype html>").unwrap();
3727        let got = super::validate_ui_dir(&ok).expect("valid ui dir");
3728        assert_eq!(got, ok);
3729    }
3730
3731    #[test]
3732    fn maybe_run_demo_if_empty_seeds_then_skips() {
3733        let dir = tmp("boot-empty");
3734        let first = super::maybe_run_demo_if_empty(&dir)
3735            .expect("empty dir demos")
3736            .expect("Some(DemoOutcome)");
3737        assert_eq!(first.stats.nodes_live, 60);
3738        let db = SharedDb::open(&dir).expect("reopen");
3739        assert!(db.read().has_node("person-01"));
3740        let second = super::maybe_run_demo_if_empty(&dir).expect("non-empty is ok");
3741        assert!(
3742            second.is_none(),
3743            "second boot must not re-demo a populated volume"
3744        );
3745
3746        let occupied = tmp("boot-occupied");
3747        std::fs::create_dir_all(&occupied).unwrap();
3748        std::fs::write(occupied.join("keep-me"), b"x").unwrap();
3749        let skipped = super::maybe_run_demo_if_empty(&occupied).expect("occupied skip");
3750        assert!(skipped.is_none());
3751        assert_eq!(
3752            std::fs::read(occupied.join("keep-me")).unwrap(),
3753            b"x",
3754            "existing volume contents must be untouched"
3755        );
3756    }
3757
3758    #[test]
3759    fn demo_builder_is_deterministic_and_refuses_second_run() {
3760        let dir = tmp("demo");
3761        let out = run_demo(&dir).expect("first demo run");
3762
3763        assert_eq!(
3764            out.stats.nodes_live, 60,
3765            "10 orgs + 20 projects + 30 people"
3766        );
3767        assert_eq!(out.stats.nodes_tombstoned, 0);
3768        // Auto-FK: 20 project→org + 30 person→org + 30 person→project = 80.
3769        // FIT: each of 30 people matches home (Jaccard 1.0) and two adjacent
3770        // projects (3-skill window shifted ±1 → Jaccard 2/4 = 0.5) = 30*3 = 90.
3771        // founded_within: |year_i − year_j| ≤ 2 on 2010+(i-1) → 17 pairs × 2 = 34.
3772        // nearby_office: 4 city clusters (NYC/SF/London/Paris) → 8 pairs × 2 = 16.
3773        // similar_interests: dim-8 groups → 57 pairs × 2 = 114.
3774        // Total: 80 + 90 + 34 + 16 + 114 = 334.
3775        assert_eq!(out.stats.edges, 334);
3776        assert_eq!(
3777            out.stats.rules.len(),
3778            7,
3779            "3 auto-FK + overlap + numeric + geo + vector"
3780        );
3781        let fit = out
3782            .stats
3783            .rules
3784            .iter()
3785            .find(|r| r.name == "skill_fit")
3786            .expect("skill_fit");
3787        assert_eq!(fit.edges, 90, "30 people × 3 FIT edges");
3788        let founded = out
3789            .stats
3790            .rules
3791            .iter()
3792            .find(|r| r.name == "founded_within")
3793            .expect("founded_within");
3794        assert_eq!(founded.edges, 34);
3795        let nearby = out
3796            .stats
3797            .rules
3798            .iter()
3799            .find(|r| r.name == "nearby_office")
3800            .expect("nearby_office");
3801        assert_eq!(nearby.edges, 16);
3802        let similar = out
3803            .stats
3804            .rules
3805            .iter()
3806            .find(|r| r.name == "similar_interests")
3807            .expect("similar_interests");
3808        assert_eq!(similar.edges, 114);
3809
3810        let mut names: Vec<&str> = out.stats.rules.iter().map(|r| r.name.as_str()).collect();
3811        names.sort_unstable();
3812        assert_eq!(
3813            names,
3814            vec![
3815                "auto_fk_person_org_id",
3816                "auto_fk_person_project_id",
3817                "auto_fk_project_org_id",
3818                "founded_within",
3819                "nearby_office",
3820                "similar_interests",
3821                "skill_fit",
3822            ]
3823        );
3824
3825        // `recall` needs a name index; the memory schema applied at store
3826        // creation adds it, plus every other memory-entity label — no nodes,
3827        // edges or rules.
3828        let db = SharedDb::open(&dir).expect("reopen demo");
3829        assert_eq!(
3830            db.read().fulltext_pairs(),
3831            vec![
3832                ("Concept".to_string(), "name".to_string()),
3833                ("Concept".to_string(), "summary".to_string()),
3834                ("Entity".to_string(), "name".to_string()),
3835                ("Event".to_string(), "name".to_string()),
3836                ("Note".to_string(), "text".to_string()),
3837                ("Org".to_string(), "name".to_string()),
3838                ("Person".to_string(), "name".to_string()),
3839                ("Project".to_string(), "name".to_string()),
3840            ]
3841        );
3842
3843        let mut auto = out.auto_fk_rules.clone();
3844        auto.sort();
3845        assert_eq!(
3846            auto,
3847            vec![
3848                "auto_fk_person_org_id".to_string(),
3849                "auto_fk_person_project_id".to_string(),
3850                "auto_fk_project_org_id".to_string(),
3851            ]
3852        );
3853
3854        assert!(
3855            !out.sample_result.is_empty(),
3856            "sample Cypher query must return rows"
3857        );
3858        assert!(
3859            out.sample_query.contains("ORDER BY score DESC"),
3860            "sample query must rank by score, got {}",
3861            out.sample_query
3862        );
3863        let scores: Vec<f64> = (0..out.sample_result.len())
3864            .map(|i| match out.sample_result.get(i, "score") {
3865                Some(Value::Float(f)) => *f,
3866                other => panic!("score col should be Float, got {other:?}"),
3867            })
3868            .collect();
3869        let distinct: std::collections::BTreeSet<u64> =
3870            scores.iter().map(|s| s.to_bits()).collect();
3871        assert!(
3872            distinct.len() >= 2,
3873            "sample results must be visibly ranked, got {scores:?}"
3874        );
3875        for w in scores.windows(2) {
3876            assert!(
3877                w[0] >= w[1],
3878                "scores must be non-increasing, got {scores:?}"
3879            );
3880        }
3881        assert!(
3882            !out.explanations.is_empty(),
3883            "explain(person-01, proj-01) must find the derived edges"
3884        );
3885
3886        let db = SharedDb::open(&dir).expect("reopen demo");
3887        assert_eq!(
3888            directed_pairs(&db, "FOUNDED_WITHIN"),
3889            [
3890                ("org-01", "org-02"),
3891                ("org-01", "org-03"),
3892                ("org-02", "org-01"),
3893                ("org-02", "org-03"),
3894                ("org-02", "org-04"),
3895                ("org-03", "org-01"),
3896                ("org-03", "org-02"),
3897                ("org-03", "org-04"),
3898                ("org-03", "org-05"),
3899                ("org-04", "org-02"),
3900                ("org-04", "org-03"),
3901                ("org-04", "org-05"),
3902                ("org-04", "org-06"),
3903                ("org-05", "org-03"),
3904                ("org-05", "org-04"),
3905                ("org-05", "org-06"),
3906                ("org-05", "org-07"),
3907                ("org-06", "org-04"),
3908                ("org-06", "org-05"),
3909                ("org-06", "org-07"),
3910                ("org-06", "org-08"),
3911                ("org-07", "org-05"),
3912                ("org-07", "org-06"),
3913                ("org-07", "org-08"),
3914                ("org-07", "org-09"),
3915                ("org-08", "org-06"),
3916                ("org-08", "org-07"),
3917                ("org-08", "org-09"),
3918                ("org-08", "org-10"),
3919                ("org-09", "org-07"),
3920                ("org-09", "org-08"),
3921                ("org-09", "org-10"),
3922                ("org-10", "org-08"),
3923                ("org-10", "org-09"),
3924            ]
3925            .into_iter()
3926            .map(|(a, b)| (a.to_string(), b.to_string()))
3927            .collect::<BTreeSet<_>>()
3928        );
3929        assert_eq!(
3930            directed_pairs(&db, "NEARBY_OFFICE"),
3931            [
3932                ("org-01", "org-07"),
3933                ("org-01", "org-10"),
3934                ("org-02", "org-09"),
3935                ("org-03", "org-08"),
3936                ("org-04", "org-05"),
3937                ("org-04", "org-06"),
3938                ("org-05", "org-04"),
3939                ("org-05", "org-06"),
3940                ("org-06", "org-04"),
3941                ("org-06", "org-05"),
3942                ("org-07", "org-01"),
3943                ("org-07", "org-10"),
3944                ("org-08", "org-03"),
3945                ("org-09", "org-02"),
3946                ("org-10", "org-01"),
3947                ("org-10", "org-07"),
3948            ]
3949            .into_iter()
3950            .map(|(a, b)| (a.to_string(), b.to_string()))
3951            .collect::<BTreeSet<_>>()
3952        );
3953        assert_weight(&db, "org-01", "org-02", "founded_within", 0.5);
3954        let nyc_jc = 1.0 - haversine_km(40.7128, -74.0060, 40.7178, -74.0431) / 50.0;
3955        assert_weight(&db, "org-01", "org-07", "nearby_office", nyc_jc);
3956        assert_weight(&db, "person-01", "person-11", "similar_interests", 1.0);
3957        assert_weight(&db, "person-01", "person-09", "similar_interests", 0.8);
3958
3959        let err = run_demo(&dir).expect_err("second run into the same dir");
3960        let msg = err.to_string().to_lowercase();
3961        assert!(
3962            msg.contains("not empty") || msg.contains("non-empty") || msg.contains("non empty"),
3963            "refuse message must mention non-empty dir, got {err}"
3964        );
3965        assert!(
3966            msg.contains("hidden"),
3967            "refuse message must mention hidden files, got {err}"
3968        );
3969
3970        let _ = std::fs::remove_dir_all(&dir);
3971    }
3972
3973    #[test]
3974    fn run_snapshot_writes_snapshot_bin() {
3975        let dir = tmp("snapshot-cli");
3976        {
3977            let mut db = GraphDb::open(&dir).expect("open");
3978            db.insert_node("Person", "alice", vec![]).expect("insert");
3979        }
3980        assert!(
3981            !dir.join("snapshot.bin").exists(),
3982            "GraphDb Drop must not snapshot"
3983        );
3984        let out = run_snapshot(&dir, WalDisposition::Archive, None).expect("snapshot");
3985        assert!(
3986            dir.join("snapshot.bin").is_file(),
3987            "run_snapshot must write snapshot.bin"
3988        );
3989        assert!(
3990            out.contains("snapshot.bin"),
3991            "snapshot output should mention snapshot.bin, got {out}"
3992        );
3993        let db = GraphDb::open(&dir).expect("reopen");
3994        assert!(db.has_node("alice"), "reopen after snapshot must recover");
3995        let _ = std::fs::remove_dir_all(&dir);
3996    }
3997
3998    /// Every snapshot mushroomdb takes on its own — the ingest's, a
3999    /// `serve --snapshot-every` tick, the graceful-shutdown one — archives the
4000    /// WAL, so a store never loses its past to a write nobody asked for. Only
4001    /// an explicit `--truncate` ends that reach.
4002    #[test]
4003    fn an_automatic_snapshot_keeps_history_reachable_and_truncate_ends_it() {
4004        let dir = tmp("snapshot-archive");
4005        {
4006            let mut db = GraphDb::open(&dir).expect("open");
4007            db.insert_node("Person", "alice", vec![]).expect("insert");
4008        }
4009        let before = core_api::wal_commit_count_at(&dir).expect("count");
4010        assert!(before > 0, "the insert is a commit");
4011
4012        // Exactly the call `serve` makes on a tick and on shutdown.
4013        {
4014            let shared = SharedDb::open(&dir).expect("open");
4015            snapshot_shared(&shared).expect("snapshot");
4016        }
4017
4018        let archives = || {
4019            std::fs::read_dir(&dir)
4020                .expect("read dir")
4021                .filter_map(Result::ok)
4022                .filter(|e| e.file_name().to_string_lossy().ends_with(".archive"))
4023                .count()
4024        };
4025        assert_eq!(archives(), 1, "the WAL was archived, not dropped");
4026        assert!(
4027            dir.join("wal.genesis").is_file(),
4028            "the genesis marker is what lets asof reach an archived commit"
4029        );
4030        {
4031            let db = GraphDb::open(&dir).expect("reopen");
4032            assert!(db.has_node("alice"));
4033            assert!(
4034                !db.node_history("alice").expect("history").items.is_empty(),
4035                "the insert is still explainable"
4036            );
4037        }
4038        assert!(
4039            GraphDb::open_at(&dir, before - 1).is_ok(),
4040            "asof still reaches a commit the snapshot folded in"
4041        );
4042
4043        // A truncating snapshot is the destructive one, and only the user asks
4044        // for it.
4045        run_snapshot(&dir, WalDisposition::Truncate, None).expect("truncate");
4046        assert!(
4047            !dir.join("wal.genesis").exists(),
4048            "truncating ends asof's reach into the archives"
4049        );
4050        let db = GraphDb::open(&dir).expect("reopen");
4051        assert!(
4052            db.has_node("alice"),
4053            "the data survives; only the past goes"
4054        );
4055        let _ = std::fs::remove_dir_all(&dir);
4056    }
4057
4058    /// Automatic snapshots keep every archive: history is the thing archives
4059    /// exist for, and nothing deletes it unless a caller asks with
4060    /// `--retention`.
4061    #[test]
4062    fn automatic_snapshots_keep_every_archive() {
4063        let dir = tmp("snapshot-retention");
4064        let archives = |d: &Path| {
4065            std::fs::read_dir(d)
4066                .expect("read dir")
4067                .filter_map(Result::ok)
4068                .filter(|e| e.file_name().to_string_lossy().ends_with(".archive"))
4069                .count()
4070        };
4071
4072        // Ten rounds of "commit something, then take the snapshot the ingest,
4073        // the sync hook and the server tick all take".
4074        let rounds = 10;
4075        for i in 0..rounds {
4076            {
4077                let mut db = GraphDb::open(&dir).expect("open");
4078                db.insert_node("Person", &format!("p{i}"), vec![])
4079                    .expect("insert");
4080            }
4081            let shared = SharedDb::open(&dir).expect("open shared");
4082            snapshot_shared(&shared).expect("snapshot");
4083        }
4084
4085        assert_eq!(
4086            archives(&dir),
4087            rounds,
4088            "an automatic snapshot must not delete an archive"
4089        );
4090
4091        let db = GraphDb::open(&dir).expect("reopen");
4092        assert_eq!(
4093            db.wal_horizon_floor(),
4094            0,
4095            "nothing was pruned, so the floor stays at 0"
4096        );
4097        for i in 0..rounds {
4098            assert!(db.has_node(&format!("p{i}")), "p{i} survived");
4099        }
4100        assert!(
4101            !db.node_history("p0").expect("history").items.is_empty(),
4102            "the oldest history is still there: that is the point of the default"
4103        );
4104        assert_eq!(db.node_history("p0").expect("history").horizon, 0);
4105        drop(db);
4106
4107        // The explicit command is the user's, and keeps everything unless the
4108        // user says otherwise.
4109        let manual = tmp("snapshot-retention-manual");
4110        for i in 0..3 {
4111            {
4112                let mut db = GraphDb::open(&manual).expect("open");
4113                db.insert_node("Person", &format!("p{i}"), vec![])
4114                    .expect("insert");
4115            }
4116            run_snapshot(&manual, WalDisposition::Archive, None).expect("snapshot");
4117        }
4118        assert_eq!(
4119            archives(&manual),
4120            3,
4121            "`mushroomdb snapshot` with no --retention keeps every archive"
4122        );
4123
4124        let _ = std::fs::remove_dir_all(&dir);
4125        let _ = std::fs::remove_dir_all(&manual);
4126    }
4127
4128    /// `--retention N` still bounds the archives when a caller asks for it —
4129    /// the automatic default changed, not the escape hatch.
4130    #[test]
4131    fn retention_is_still_available_when_configured() {
4132        let dir = tmp("retention-configured");
4133        for i in 0..5 {
4134            {
4135                let mut db = GraphDb::open(&dir).unwrap();
4136                db.insert_node("Person", &format!("p{i}"), vec![]).unwrap();
4137            }
4138            run_snapshot(&dir, WalDisposition::Archive, Some(2)).unwrap();
4139        }
4140        let archives = std::fs::read_dir(&dir)
4141            .expect("read dir")
4142            .filter_map(Result::ok)
4143            .filter(|e| e.file_name().to_string_lossy().ends_with(".archive"))
4144            .count();
4145        assert_eq!(archives, 2, "--retention 2 still prunes to two");
4146        assert!(GraphDb::open(&dir).unwrap().wal_horizon_floor() > 0);
4147        let _ = std::fs::remove_dir_all(&dir);
4148    }
4149
4150    #[test]
4151    fn run_query_formats_like_asof() {
4152        let dir = tmp("query-cli");
4153        {
4154            let mut db = GraphDb::open(&dir).expect("open");
4155            db.insert_node(
4156                "Person",
4157                "alice",
4158                vec![("id".into(), Value::Str("alice".into()))],
4159            )
4160            .expect("insert");
4161        }
4162        let out = run_query(&dir, "MATCH (n:Person) RETURN n.id AS id", None, None).expect("query");
4163        assert!(out.contains("columns:"), "got {out}");
4164        assert!(out.contains("id=alice"), "got {out}");
4165        let _ = run_query(&dir, "CREATE (n:Person {id: 'bob'})", None, None).expect("write");
4166        let db = GraphDb::open(&dir).expect("reopen");
4167        assert!(db.has_node("bob"), "query_write must persist CREATE");
4168        let _ = std::fs::remove_dir_all(&dir);
4169    }
4170
4171    /// The as-of header says how far back history reaches, and counts every
4172    /// commit the store still holds — including the archived ones the live
4173    /// WAL no longer carries.
4174    #[test]
4175    fn asof_header_names_the_horizon() {
4176        let dir = tmp("asof-horizon");
4177        // Ten rounds of "write, then snapshot with an explicit retention": the
4178        // bound prunes the oldest archives and the floor advances past 0. The
4179        // automatic path no longer prunes on its own, so the horizon here is
4180        // built with `--retention` rather than the automatic default.
4181        for i in 0..10 {
4182            {
4183                let mut db = GraphDb::open(&dir).expect("open");
4184                db.insert_node("Person", &format!("p{i}"), vec![])
4185                    .expect("insert");
4186            }
4187            run_snapshot(&dir, WalDisposition::Archive, Some(2)).expect("snapshot");
4188        }
4189        // One more write after the last snapshot: that commit lives in the live
4190        // WAL, which is what `asof` can still reconstruct on a pruned store.
4191        {
4192            let mut db = GraphDb::open(&dir).expect("open");
4193            db.insert_node("Person", "after", vec![]).expect("insert");
4194        }
4195        let (floor, total) = {
4196            let db = GraphDb::open(&dir).expect("reopen");
4197            (
4198                db.wal_horizon_floor(),
4199                db.wal_total_commits().expect("total"),
4200            )
4201        };
4202        assert!(floor > 0, "the retention must have pruned something");
4203
4204        let out = run_asof(&dir, Some(total - 1), None, None, None).expect("asof");
4205        assert_eq!(
4206            out.trim(),
4207            format!(
4208                "as-of commit {} of {total} (history reaches back to commit {floor})",
4209                total - 1
4210            ),
4211            "the header must name the horizon it can reach"
4212        );
4213        let _ = std::fs::remove_dir_all(&dir);
4214
4215        // A store that has pruned nothing reads exactly as it always did.
4216        let clean = tmp("asof-clean");
4217        {
4218            let mut db = GraphDb::open(&clean).expect("open");
4219            db.insert_node("Person", "a", vec![]).expect("insert");
4220        }
4221        assert_eq!(
4222            run_asof(&clean, Some(0), None, None, None)
4223                .expect("asof")
4224                .trim(),
4225            "as-of commit 0 of 1"
4226        );
4227        let _ = std::fs::remove_dir_all(&clean);
4228    }
4229
4230    /// `stats` says whether history is complete, and where it starts when it
4231    /// is not.
4232    #[test]
4233    fn format_stats_says_how_far_back_history_reaches() {
4234        let dir = tmp("stats-horizon");
4235        {
4236            let mut db = GraphDb::open(&dir).expect("open");
4237            db.insert_node("Person", "a", vec![]).expect("insert");
4238        }
4239        let text = format_stats(&read_stats(&dir).expect("stats"));
4240        assert!(
4241            text.contains("history: complete (nothing pruned)"),
4242            "an unpruned store says so, got:\n{text}"
4243        );
4244        let _ = std::fs::remove_dir_all(&dir);
4245
4246        let pruned = tmp("stats-horizon-pruned");
4247        for i in 0..10 {
4248            {
4249                let mut db = GraphDb::open(&pruned).expect("open");
4250                db.insert_node("Person", &format!("p{i}"), vec![])
4251                    .expect("insert");
4252            }
4253            run_snapshot(&pruned, WalDisposition::Archive, Some(2)).expect("snapshot");
4254        }
4255        let stats = read_stats(&pruned).expect("stats");
4256        assert!(stats.history_floor > 0, "the retention must have pruned");
4257        assert!(
4258            format_stats(&stats).contains(&format!(
4259                "history: reaches back to commit {}",
4260                stats.history_floor
4261            )),
4262            "a pruned store names its floor"
4263        );
4264        let _ = std::fs::remove_dir_all(&pruned);
4265    }
4266
4267    #[test]
4268    fn format_stats_contains_counts() {
4269        let dir = tmp("stats-smoke");
4270        let out = run_demo(&dir).expect("demo for stats smoke");
4271        let text = format_stats(&out.stats);
4272        assert!(
4273            text.contains("60"),
4274            "stats output should include live node count, got:\n{text}"
4275        );
4276        assert!(
4277            text.contains("334"),
4278            "stats output should include edge count, got:\n{text}"
4279        );
4280        assert!(
4281            text.to_lowercase().contains("node"),
4282            "stats output should mention nodes, got:\n{text}"
4283        );
4284        assert!(
4285            text.to_lowercase().contains("edge"),
4286            "stats output should mention edges, got:\n{text}"
4287        );
4288        let _ = std::fs::remove_dir_all(&dir);
4289    }
4290
4291    // ── backup CLI tests ──────────────────────────────────────────────────────
4292
4293    #[test]
4294    fn parse_backup_round_trip() {
4295        let r = parse_args(&["backup", "/db/dir", "/backup/dest"]);
4296        match r {
4297            Ok(Command::Backup { db_dir, dest }) => {
4298                assert_eq!(db_dir, PathBuf::from("/db/dir"));
4299                assert_eq!(dest, PathBuf::from("/backup/dest"));
4300            }
4301            other => panic!("backup parse, got {other:?}"),
4302        }
4303    }
4304
4305    #[test]
4306    fn parse_backup_missing_dest_errors() {
4307        let r = parse_args(&["backup", "/db/dir"]);
4308        assert!(r.is_err(), "backup without <dest> should error");
4309        let e = r.unwrap_err();
4310        assert!(
4311            e.to_lowercase().contains("dest"),
4312            "error should mention dest, got: {e}"
4313        );
4314    }
4315
4316    #[test]
4317    fn parse_export_defaults_to_jsonl() {
4318        let r = parse_args(&["export", "/db/dir", "/export/dest"]);
4319        match r {
4320            Ok(Command::Export { format, .. }) => {
4321                assert_eq!(format, ExportFormat::Jsonl);
4322            }
4323            other => panic!("export parse, got {other:?}"),
4324        }
4325    }
4326
4327    #[test]
4328    fn parse_export_parquet_flag() {
4329        let r = parse_args(&["export", "/db/dir", "/export/dest", "--format", "parquet"]);
4330        match r {
4331            Ok(Command::Export { format, .. }) => {
4332                assert_eq!(format, ExportFormat::Parquet);
4333            }
4334            other => panic!("export --format parquet parse, got {other:?}"),
4335        }
4336    }
4337
4338    #[test]
4339    fn parse_export_parquet_flag_eq() {
4340        let r = parse_args(&["export", "/db/dir", "/dest", "--format=parquet"]);
4341        match r {
4342            Ok(Command::Export { format, .. }) => {
4343                assert_eq!(format, ExportFormat::Parquet);
4344            }
4345            other => panic!("export --format=parquet parse, got {other:?}"),
4346        }
4347    }
4348
4349    #[test]
4350    fn run_backup_cli_produces_verified_report() {
4351        let src = tmp("cli-backup-src");
4352        let dst = tmp("cli-backup-dst");
4353        let _ = run_demo(&src).expect("demo");
4354        let report = run_backup(&src, &dst).expect("run_backup");
4355        assert!(report.verified, "backup must be verified");
4356        assert!(!report.files.is_empty());
4357        assert!(report.bytes > 0);
4358        let _ = std::fs::remove_dir_all(&src);
4359        let _ = std::fs::remove_dir_all(&dst);
4360    }
4361
4362    /// Build a one-node store at `dir` and snapshot it, so `backup_to` has a
4363    /// `snapshot.bin` to copy.
4364    fn seed_store(dir: &Path, key: &str) {
4365        let mut db = GraphDb::open(dir).expect("open seed store");
4366        db.insert_node("N", key, vec![]).expect("insert seed node");
4367        db.snapshot().expect("snapshot seed store");
4368    }
4369
4370    #[test]
4371    fn restore_from_seeds_an_empty_dir() {
4372        let src = tmp("restore-src");
4373        seed_store(&src, "a");
4374        let vault = tmp("restore-vault");
4375        run_backup(&src, &vault.join("2026-09-10T00-00Z")).expect("backup");
4376
4377        let fresh = tmp("restore-fresh");
4378        match restore_if_empty(&fresh, &vault).expect("restore_if_empty") {
4379            RestoreOutcome::Restored { files, bytes, .. } => {
4380                assert!(
4381                    files.contains(&"snapshot.bin".to_string()),
4382                    "expected snapshot.bin among {files:?}"
4383                );
4384                assert!(bytes > 0, "expected a non-zero byte count");
4385            }
4386            other => panic!("expected Restored, got {other:?}"),
4387        }
4388        assert!(GraphDb::open(&fresh).expect("open restored").has_node("a"));
4389
4390        let _ = std::fs::remove_dir_all(&src);
4391        let _ = std::fs::remove_dir_all(&vault);
4392        let _ = std::fs::remove_dir_all(&fresh);
4393    }
4394
4395    #[test]
4396    fn restore_from_a_backup_dir_itself() {
4397        let src = tmp("restore-direct-src");
4398        seed_store(&src, "a");
4399        let backup = tmp("restore-direct-backup");
4400        run_backup(&src, &backup).expect("backup");
4401
4402        let fresh = tmp("restore-direct-fresh");
4403        match restore_if_empty(&fresh, &backup).expect("restore_if_empty") {
4404            RestoreOutcome::Restored { from, .. } => assert_eq!(from, backup),
4405            other => panic!("expected Restored, got {other:?}"),
4406        }
4407        assert!(GraphDb::open(&fresh).expect("open restored").has_node("a"));
4408
4409        let _ = std::fs::remove_dir_all(&src);
4410        let _ = std::fs::remove_dir_all(&backup);
4411        let _ = std::fs::remove_dir_all(&fresh);
4412    }
4413
4414    /// A store that has never snapshotted backs up as `wal.bin` and nothing
4415    /// else — `mushroomdb demo` then `mushroomdb backup` is exactly that — and
4416    /// it carries every commit. Ranking on `snapshot.bin` alone would skip it
4417    /// and start the server empty, which is the failure the flag exists to
4418    /// prevent.
4419    #[test]
4420    fn restore_from_a_wal_only_backup() {
4421        let src = tmp("restore-walonly-src");
4422        {
4423            let mut db = GraphDb::open(&src).expect("open src");
4424            db.insert_node("N", "a", vec![]).expect("insert");
4425        }
4426        assert!(
4427            !src.join("snapshot.bin").exists(),
4428            "test setup: src must not have snapshotted"
4429        );
4430        let vault = tmp("restore-walonly-vault");
4431        run_backup(&src, &vault.join("2026-09-10T00-00Z")).expect("backup");
4432
4433        let fresh = tmp("restore-walonly-fresh");
4434        match restore_if_empty(&fresh, &vault).expect("restore_if_empty") {
4435            RestoreOutcome::Restored { files, .. } => assert!(
4436                files.contains(&"wal.bin".to_string()),
4437                "expected wal.bin among {files:?}"
4438            ),
4439            other => panic!("expected Restored, got {other:?}"),
4440        }
4441        assert!(GraphDb::open(&fresh).expect("open restored").has_node("a"));
4442
4443        let _ = std::fs::remove_dir_all(&src);
4444        let _ = std::fs::remove_dir_all(&vault);
4445        let _ = std::fs::remove_dir_all(&fresh);
4446    }
4447
4448    #[test]
4449    fn restore_from_picks_latest_then_newest() {
4450        let older_src = tmp("restore-rank-old-src");
4451        seed_store(&older_src, "old");
4452        let newer_src = tmp("restore-rank-new-src");
4453        seed_store(&newer_src, "new");
4454        let latest_src = tmp("restore-rank-latest-src");
4455        seed_store(&latest_src, "named-latest");
4456
4457        // Newest by mtime, with no `latest/` present.
4458        let vault = tmp("restore-rank-vault");
4459        run_backup(&older_src, &vault.join("2026-09-01")).expect("backup old");
4460        std::thread::sleep(std::time::Duration::from_millis(1100));
4461        run_backup(&newer_src, &vault.join("2026-09-02")).expect("backup new");
4462
4463        let fresh = tmp("restore-rank-fresh");
4464        match restore_if_empty(&fresh, &vault).expect("restore by mtime") {
4465            RestoreOutcome::Restored { from, .. } => assert_eq!(from, vault.join("2026-09-02")),
4466            other => panic!("expected Restored, got {other:?}"),
4467        }
4468        assert!(GraphDb::open(&fresh)
4469            .expect("open restored")
4470            .has_node("new"));
4471
4472        // `latest/` wins outright, even though it is older than 2026-09-02.
4473        run_backup(&latest_src, &vault.join("latest")).expect("backup latest");
4474        let older_than_latest = std::fs::metadata(vault.join("2026-09-02").join("snapshot.bin"))
4475            .expect("stat newest")
4476            .modified()
4477            .expect("mtime");
4478        let latest_mtime = std::fs::metadata(vault.join("latest").join("snapshot.bin"))
4479            .expect("stat latest")
4480            .modified()
4481            .expect("mtime");
4482        assert!(
4483            latest_mtime >= older_than_latest,
4484            "test setup: latest/ should not be older here"
4485        );
4486
4487        let fresh2 = tmp("restore-rank-fresh2");
4488        match restore_if_empty(&fresh2, &vault).expect("restore by name") {
4489            RestoreOutcome::Restored { from, .. } => assert_eq!(from, vault.join("latest")),
4490            other => panic!("expected Restored, got {other:?}"),
4491        }
4492        assert!(GraphDb::open(&fresh2)
4493            .expect("open restored")
4494            .has_node("named-latest"));
4495
4496        for d in [&older_src, &newer_src, &latest_src, &vault, &fresh, &fresh2] {
4497            let _ = std::fs::remove_dir_all(d);
4498        }
4499    }
4500
4501    #[test]
4502    fn restore_from_is_a_no_op_when_a_store_exists() {
4503        let src = tmp("restore-noop-src");
4504        seed_store(&src, "a");
4505        let vault = tmp("restore-noop-vault");
4506        run_backup(&src, &vault.join("2026-09-10T00-00Z")).expect("backup");
4507
4508        let existing = tmp("restore-noop-existing");
4509        seed_store(&existing, "b");
4510
4511        assert_eq!(
4512            restore_if_empty(&existing, &vault).expect("restore_if_empty"),
4513            RestoreOutcome::AlreadyPresent
4514        );
4515        let db = GraphDb::open(&existing).expect("open existing");
4516        assert!(db.has_node("b"), "the existing store must survive");
4517        assert!(!db.has_node("a"), "the backup must not have been copied in");
4518
4519        let _ = std::fs::remove_dir_all(&src);
4520        let _ = std::fs::remove_dir_all(&vault);
4521        let _ = std::fs::remove_dir_all(&existing);
4522    }
4523
4524    #[test]
4525    fn restore_from_an_empty_vault_is_not_an_error() {
4526        let vault = tmp("restore-empty-vault");
4527        std::fs::create_dir_all(&vault).expect("mkdir vault");
4528        let fresh = tmp("restore-empty-fresh");
4529        assert_eq!(
4530            restore_if_empty(&fresh, &vault).expect("restore_if_empty"),
4531            RestoreOutcome::Empty
4532        );
4533        // A missing `from` is the same warning: a first boot with no volume yet.
4534        assert_eq!(
4535            restore_if_empty(&fresh, &vault.join("nope")).expect("restore_if_empty"),
4536            RestoreOutcome::Empty
4537        );
4538
4539        let _ = std::fs::remove_dir_all(&vault);
4540        let _ = std::fs::remove_dir_all(&fresh);
4541    }
4542
4543    #[test]
4544    fn restore_from_a_corrupt_backup_fails_loudly() {
4545        let src = tmp("restore-corrupt-src");
4546        seed_store(&src, "a");
4547        let vault = tmp("restore-corrupt-vault");
4548        let backup = vault.join("2026-09-10T00-00Z");
4549        run_backup(&src, &backup).expect("backup");
4550
4551        // Truncate the copied snapshot: the CRC check on open must reject it.
4552        let snap = backup.join("snapshot.bin");
4553        let bytes = std::fs::read(&snap).expect("read snapshot");
4554        std::fs::write(&snap, &bytes[..bytes.len() / 2]).expect("truncate snapshot");
4555
4556        let fresh = tmp("restore-corrupt-fresh");
4557        let err = restore_if_empty(&fresh, &vault).expect_err("expected a hard failure");
4558        let msg = err.to_string();
4559        assert!(
4560            msg.contains(&fresh.display().to_string()),
4561            "error must name the restored dir, got: {msg}"
4562        );
4563        assert!(
4564            msg.contains(&backup.display().to_string()),
4565            "error must name the backup, got: {msg}"
4566        );
4567
4568        let _ = std::fs::remove_dir_all(&src);
4569        let _ = std::fs::remove_dir_all(&vault);
4570        let _ = std::fs::remove_dir_all(&fresh);
4571    }
4572
4573    /// A failed restore is all-or-nothing: nothing of the bad copy reaches
4574    /// `db_dir`, so the next boot restores rather than reporting
4575    /// `AlreadyPresent` over a half-written store.
4576    #[test]
4577    fn a_failed_restore_leaves_the_db_dir_untouched() {
4578        let src = tmp("restore-atomic-src");
4579        seed_store(&src, "a");
4580
4581        let bad_vault = tmp("restore-atomic-bad-vault");
4582        let bad = bad_vault.join("2026-09-10T00-00Z");
4583        run_backup(&src, &bad).expect("backup the bad one");
4584        let snap = bad.join("snapshot.bin");
4585        let bytes = std::fs::read(&snap).expect("read snapshot");
4586        std::fs::write(&snap, &bytes[..bytes.len() / 2]).expect("truncate snapshot");
4587
4588        let good_vault = tmp("restore-atomic-good-vault");
4589        run_backup(&src, &good_vault.join("2026-09-11T00-00Z")).expect("backup the good one");
4590
4591        let fresh = tmp("restore-atomic-fresh");
4592        let err = restore_if_empty(&fresh, &bad_vault).expect_err("expected a hard failure");
4593        let msg = err.to_string();
4594        assert!(
4595            msg.contains(&fresh.display().to_string()) && msg.contains(&bad.display().to_string()),
4596            "error must name both paths, got: {msg}"
4597        );
4598
4599        // Nothing was left behind — not the copied files, not the staging dir.
4600        let leftovers: Vec<String> = std::fs::read_dir(&fresh)
4601            .expect("read fresh")
4602            .flatten()
4603            .filter_map(|e| e.file_name().into_string().ok())
4604            .collect();
4605        assert!(
4606            leftovers.is_empty(),
4607            "a failed restore must leave nothing behind, found: {leftovers:?}"
4608        );
4609        assert!(!holds_a_store(&fresh), "the dir must not hold a store");
4610
4611        // So the retry against a good backup restores, rather than deciding a
4612        // store is already there.
4613        match restore_if_empty(&fresh, &good_vault).expect("retry must restore") {
4614            RestoreOutcome::Restored { from, .. } => {
4615                assert_eq!(from, good_vault.join("2026-09-11T00-00Z"))
4616            }
4617            other => panic!("expected Restored on retry, got {other:?}"),
4618        }
4619        assert!(GraphDb::open(&fresh).expect("open restored").has_node("a"));
4620
4621        for d in [&src, &bad_vault, &good_vault, &fresh] {
4622            let _ = std::fs::remove_dir_all(d);
4623        }
4624    }
4625
4626    /// The staging directory never outlives a successful restore either — a
4627    /// served store directory holds the store and nothing else.
4628    #[test]
4629    fn a_successful_restore_leaves_no_staging_dir() {
4630        let src = tmp("restore-staging-src");
4631        seed_store(&src, "a");
4632        let vault = tmp("restore-staging-vault");
4633        run_backup(&src, &vault.join("2026-09-11T00-00Z")).expect("backup");
4634
4635        let fresh = tmp("restore-staging-fresh");
4636        restore_if_empty(&fresh, &vault).expect("restore");
4637
4638        let stray: Vec<String> = std::fs::read_dir(&fresh)
4639            .expect("read fresh")
4640            .flatten()
4641            .filter_map(|e| e.file_name().into_string().ok())
4642            .filter(|n| n.starts_with(".restore-"))
4643            .collect();
4644        assert!(
4645            stray.is_empty(),
4646            "staging dir must be gone, found: {stray:?}"
4647        );
4648
4649        for d in [&src, &vault, &fresh] {
4650            let _ = std::fs::remove_dir_all(d);
4651        }
4652    }
4653
4654    #[test]
4655    fn serve_parses_restore_from() {
4656        match parse_args(&["serve", "/tmp/db", "--restore-from", "/vol/backups"]) {
4657            Ok(Command::Serve { restore_from, .. }) => {
4658                assert_eq!(restore_from, Some(PathBuf::from("/vol/backups")))
4659            }
4660            other => panic!("--restore-from parse, got {other:?}"),
4661        }
4662        match parse_args(&["serve", "/tmp/db", "--restore-from=/vol/backups"]) {
4663            Ok(Command::Serve { restore_from, .. }) => {
4664                assert_eq!(restore_from, Some(PathBuf::from("/vol/backups")))
4665            }
4666            other => panic!("--restore-from= parse, got {other:?}"),
4667        }
4668        match parse_args(&["serve", "/tmp/db"]) {
4669            Ok(Command::Serve { restore_from, .. }) => assert_eq!(restore_from, None),
4670            other => panic!("default restore_from, got {other:?}"),
4671        }
4672        let err = parse_args(&["serve", "/tmp/db", "--restore-from"])
4673            .expect_err("missing value must be an error");
4674        assert!(
4675            err.contains("--restore-from"),
4676            "error must name the flag, got: {err}"
4677        );
4678    }
4679
4680    #[test]
4681    fn run_export_jsonl_two_runs_byte_identical() {
4682        let src = tmp("cli-export-src");
4683        let dst1 = tmp("cli-export-dst1");
4684        let dst2 = tmp("cli-export-dst2");
4685        let _ = run_demo(&src).expect("demo");
4686
4687        run_export(&src, &dst1, &ExportFormat::Jsonl).expect("first export");
4688        run_export(&src, &dst2, &ExportFormat::Jsonl).expect("second export");
4689
4690        for filename in &["nodes.jsonl", "edges.jsonl", "rules.jsonl"] {
4691            let f1 = std::fs::read(dst1.join(filename)).expect("read first");
4692            let f2 = std::fs::read(dst2.join(filename)).expect("read second");
4693            assert_eq!(
4694                f1, f2,
4695                "{filename} must be byte-identical across two export runs"
4696            );
4697        }
4698        let _ = std::fs::remove_dir_all(&src);
4699        let _ = std::fs::remove_dir_all(&dst1);
4700        let _ = std::fs::remove_dir_all(&dst2);
4701    }
4702
4703    #[test]
4704    fn run_export_jsonl_nodes_are_sorted() {
4705        let src = tmp("cli-export-sorted");
4706        let dst = tmp("cli-export-sorted-dst");
4707        let _ = run_demo(&src).expect("demo");
4708        run_export(&src, &dst, &ExportFormat::Jsonl).expect("export");
4709
4710        let content = std::fs::read_to_string(dst.join("nodes.jsonl")).expect("read nodes");
4711        let keys: Vec<String> = content
4712            .lines()
4713            .filter(|l| !l.is_empty())
4714            .map(|l| {
4715                let v: serde_json::Value = serde_json::from_str(l).expect("parse line");
4716                v["key"].as_str().unwrap_or("").to_string()
4717            })
4718            .collect();
4719        let mut sorted = keys.clone();
4720        sorted.sort();
4721        assert_eq!(keys, sorted, "nodes.jsonl must be sorted by key");
4722        let _ = std::fs::remove_dir_all(&src);
4723        let _ = std::fs::remove_dir_all(&dst);
4724    }
4725
4726    #[test]
4727    fn run_export_jsonl_derived_edges_have_rule() {
4728        let src = tmp("cli-export-derived");
4729        let dst = tmp("cli-export-derived-dst");
4730        let _ = run_demo(&src).expect("demo");
4731        run_export(&src, &dst, &ExportFormat::Jsonl).expect("export");
4732
4733        let content = std::fs::read_to_string(dst.join("edges.jsonl")).expect("read edges");
4734        let derived_lines: Vec<serde_json::Value> = content
4735            .lines()
4736            .filter(|l| !l.is_empty())
4737            .map(|l| serde_json::from_str(l).expect("parse line"))
4738            .filter(|v: &serde_json::Value| v["derived"].as_bool().unwrap_or(false))
4739            .collect();
4740        assert!(
4741            !derived_lines.is_empty(),
4742            "demo store should have derived edges"
4743        );
4744        for edge in &derived_lines {
4745            assert!(
4746                !edge["rule"].is_null(),
4747                "derived edge must have non-null rule: {edge}"
4748            );
4749        }
4750        let _ = std::fs::remove_dir_all(&src);
4751        let _ = std::fs::remove_dir_all(&dst);
4752    }
4753
4754    #[test]
4755    fn run_export_parquet_produces_files() {
4756        let src = tmp("cli-export-parq-src");
4757        let dst = tmp("cli-export-parq-dst");
4758        let _ = run_demo(&src).expect("demo");
4759        run_export(&src, &dst, &ExportFormat::Parquet).expect("parquet export");
4760
4761        assert!(
4762            dst.join("nodes.parquet").exists(),
4763            "nodes.parquet must exist"
4764        );
4765        assert!(
4766            dst.join("edges.parquet").exists(),
4767            "edges.parquet must exist"
4768        );
4769        assert!(
4770            dst.join("rules.parquet").exists(),
4771            "rules.parquet must exist"
4772        );
4773        // All files must be non-empty.
4774        for f in &["nodes.parquet", "edges.parquet", "rules.parquet"] {
4775            let meta = std::fs::metadata(dst.join(f)).expect("metadata");
4776            assert!(meta.len() > 0, "{f} must be non-empty");
4777        }
4778        let _ = std::fs::remove_dir_all(&src);
4779        let _ = std::fs::remove_dir_all(&dst);
4780    }
4781
4782    #[test]
4783    fn parse_export_graphml_flag() {
4784        let r = parse_args(&["export", "/db/dir", "/dest", "--format", "graphml"]);
4785        match r {
4786            Ok(Command::Export { format, .. }) => {
4787                assert_eq!(format, ExportFormat::Graphml);
4788            }
4789            other => panic!("export --format graphml parse, got {other:?}"),
4790        }
4791    }
4792
4793    #[test]
4794    fn run_export_graphml_structure() {
4795        let src = tmp("cli-export-gml-src");
4796        let dst_dir = tmp("cli-export-gml-dst");
4797        let dst = dst_dir.join("graph.graphml");
4798        let _ = run_demo(&src).expect("demo");
4799        run_export(&src, &dst, &ExportFormat::Graphml).expect("graphml export");
4800
4801        let content = std::fs::read_to_string(&dst).expect("read graphml");
4802
4803        assert!(
4804            content.starts_with("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"),
4805            "must start with an XML declaration"
4806        );
4807        assert!(
4808            content.contains("<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\">"),
4809            "must use the standard GraphML namespace"
4810        );
4811        assert!(
4812            content.contains(
4813                "<key id=\"n_label\" for=\"node\" attr.name=\"label\" attr.type=\"string\"/>"
4814            ),
4815            "must declare the node label key"
4816        );
4817        assert!(
4818            content.contains(
4819                "<key id=\"e_type\" for=\"edge\" attr.name=\"type\" attr.type=\"string\"/>"
4820            ),
4821            "must declare the edge type key"
4822        );
4823        assert!(
4824            content.contains(
4825                "<key id=\"e_derived\" for=\"edge\" attr.name=\"derived\" attr.type=\"boolean\"/>"
4826            ),
4827            "must declare the edge derived key"
4828        );
4829        assert!(
4830            content.contains(
4831                "<key id=\"e_rule\" for=\"edge\" attr.name=\"rule\" attr.type=\"string\"/>"
4832            ),
4833            "must declare the edge rule key"
4834        );
4835        assert!(
4836            content.contains(
4837                "<key id=\"e_weight\" for=\"edge\" attr.name=\"weight\" attr.type=\"double\"/>"
4838            ),
4839            "must declare the edge weight key"
4840        );
4841        // The demo store's Org nodes carry `founded_year` as a JSON integer
4842        // (`Value::Int`, a 64-bit i64). GraphML's informal convention treats
4843        // `attr.type="int"` as 32-bit, so this must declare `"long"`.
4844        assert!(
4845            content.contains(
4846                "<key id=\"n_founded_year\" for=\"node\" attr.name=\"founded_year\" attr.type=\"long\"/>"
4847            ),
4848            "an int-valued prop must declare attr.type=\"long\", not \"int\", got: {content}"
4849        );
4850        assert!(
4851            content.contains("<graph id=\"G\" edgedefault=\"directed\">"),
4852            "must declare a single directed graph element"
4853        );
4854        assert!(content.contains("<node id="), "must contain node elements");
4855        assert!(
4856            content.contains("<edge id=\"e0\" source=\""),
4857            "must contain a sequentially-numbered edge starting at e0"
4858        );
4859        assert!(
4860            content.trim_end().ends_with("</graphml>"),
4861            "must close the root element"
4862        );
4863
4864        // The demo store's `skill_fit` rule declares weight_prop "score"; its
4865        // derived FIT edges must carry both a rule and a weight in GraphML.
4866        assert!(
4867            content.contains("<data key=\"e_rule\">skill_fit</data>")
4868                || content.contains("<data key=\"e_rule\">founded_within</data>"),
4869            "at least one derived edge must carry its rule name"
4870        );
4871        assert!(
4872            content.contains(&format!(
4873                "<data key=\"{}\">",
4874                "e_weight" /* declared above */
4875            )),
4876            "at least one derived edge must carry a weight value"
4877        );
4878
4879        let _ = std::fs::remove_dir_all(&src);
4880        let _ = std::fs::remove_dir_all(&dst_dir);
4881    }
4882
4883    #[test]
4884    fn run_export_graphml_dest_dir_writes_graph_dot_graphml() {
4885        let src = tmp("cli-export-gml-dir-src");
4886        let dst_dir = tmp("cli-export-gml-dir-dst");
4887        std::fs::create_dir_all(&dst_dir).expect("mkdir dest");
4888        let _ = run_demo(&src).expect("demo");
4889
4890        let msg = run_export(&src, &dst_dir, &ExportFormat::Graphml).expect("graphml export");
4891
4892        assert!(
4893            dst_dir.join("graph.graphml").exists(),
4894            "an existing directory dest must produce dest/graph.graphml"
4895        );
4896        assert!(
4897            msg.contains("graph.graphml"),
4898            "report must name the file actually written, got: {msg}"
4899        );
4900
4901        let _ = std::fs::remove_dir_all(&src);
4902        let _ = std::fs::remove_dir_all(&dst_dir);
4903    }
4904
4905    /// python3-gated: parses the exported file with the stdlib XML parser to
4906    /// confirm it is well-formed. Skipped (not failed) when python3 is absent.
4907    #[test]
4908    fn run_export_graphml_is_well_formed_xml() {
4909        let has_python3 = std::process::Command::new("python3")
4910            .arg("--version")
4911            .output()
4912            .map(|o| o.status.success())
4913            .unwrap_or(false);
4914        if !has_python3 {
4915            eprintln!("skipping run_export_graphml_is_well_formed_xml: python3 not found");
4916            return;
4917        }
4918
4919        let src = tmp("cli-export-gml-wf-src");
4920        let dst_dir = tmp("cli-export-gml-wf-dst");
4921        let dst = dst_dir.join("graph.graphml");
4922        let _ = run_demo(&src).expect("demo");
4923        run_export(&src, &dst, &ExportFormat::Graphml).expect("graphml export");
4924
4925        let status = std::process::Command::new("python3")
4926            .arg("-c")
4927            .arg("import sys, xml.etree.ElementTree as E; E.parse(sys.argv[1])")
4928            .arg(&dst)
4929            .status()
4930            .expect("run python3");
4931        assert!(
4932            status.success(),
4933            "python3's XML parser must accept the exported GraphML file"
4934        );
4935
4936        let _ = std::fs::remove_dir_all(&src);
4937        let _ = std::fs::remove_dir_all(&dst_dir);
4938    }
4939
4940    #[test]
4941    fn run_export_graphml_two_runs_byte_identical() {
4942        let src = tmp("cli-export-gml-bi-src");
4943        let dst_dir1 = tmp("cli-export-gml-bi-dst1");
4944        let dst_dir2 = tmp("cli-export-gml-bi-dst2");
4945        let dst1 = dst_dir1.join("graph.graphml");
4946        let dst2 = dst_dir2.join("graph.graphml");
4947        let _ = run_demo(&src).expect("demo");
4948
4949        run_export(&src, &dst1, &ExportFormat::Graphml).expect("first export");
4950        run_export(&src, &dst2, &ExportFormat::Graphml).expect("second export");
4951
4952        let f1 = std::fs::read(&dst1).expect("read first");
4953        let f2 = std::fs::read(&dst2).expect("read second");
4954        assert_eq!(
4955            f1, f2,
4956            "graph.graphml must be byte-identical across two export runs"
4957        );
4958
4959        let _ = std::fs::remove_dir_all(&src);
4960        let _ = std::fs::remove_dir_all(&dst_dir1);
4961        let _ = std::fs::remove_dir_all(&dst_dir2);
4962    }
4963
4964    #[test]
4965    fn run_export_graphml_escapes_and_lists() {
4966        use core_api::{GraphDb, Value};
4967        let src = tmp("cli-export-gml-esc-src");
4968        let dst_dir = tmp("cli-export-gml-esc-dst");
4969        let dst = dst_dir.join("graph.graphml");
4970
4971        {
4972            let mut db = GraphDb::open(&src).unwrap();
4973            db.insert_node(
4974                "Widget",
4975                "w1",
4976                vec![
4977                    (
4978                        "title".into(),
4979                        Value::Str("Tom & Jerry <says> \"hi\" 'bye'".into()),
4980                    ),
4981                    (
4982                        "tags".into(),
4983                        Value::List(vec![Value::Str("a".into()), Value::Str("b".into())]),
4984                    ),
4985                ],
4986            )
4987            .unwrap();
4988        }
4989
4990        run_export(&src, &dst, &ExportFormat::Graphml).expect("graphml export");
4991        let content = std::fs::read_to_string(&dst).expect("read graphml");
4992
4993        assert!(
4994            content.contains("Tom &amp; Jerry &lt;says&gt; &quot;hi&quot; &apos;bye&apos;"),
4995            "special XML characters in string props must be escaped, got: {content}"
4996        );
4997        assert!(
4998            !content.contains("Tom & Jerry <says>"),
4999            "unescaped special characters must not appear verbatim"
5000        );
5001        assert!(
5002            content.contains(
5003                "<key id=\"n_tags\" for=\"node\" attr.name=\"tags\" attr.type=\"string\"/>"
5004            ),
5005            "list-valued props must declare attr.type=\"string\""
5006        );
5007        assert!(
5008            content.contains("<data key=\"n_tags\">[&quot;a&quot;,&quot;b&quot;]</data>"),
5009            "list-valued props must render as XML-escaped JSON text, got: {content}"
5010        );
5011
5012        let _ = std::fs::remove_dir_all(&src);
5013        let _ = std::fs::remove_dir_all(&dst_dir);
5014    }
5015
5016    /// I2: when nodes disagree on the `Value` variant for a prop name (one
5017    /// int, one string), the key must declare `attr.type="string"` — a value
5018    /// of either type fits text — rather than picking one node's type and
5019    /// risking a value that doesn't fit it.
5020    #[test]
5021    fn run_export_graphml_mixed_type_prop_declares_string() {
5022        use core_api::{GraphDb, Value};
5023        let src = tmp("cli-export-gml-mixed-src");
5024        let dst_dir = tmp("cli-export-gml-mixed-dst");
5025        let dst = dst_dir.join("graph.graphml");
5026
5027        {
5028            let mut db = GraphDb::open(&src).unwrap();
5029            db.insert_node("Metric", "m1", vec![("score".into(), Value::Int(5))])
5030                .unwrap();
5031            db.insert_node(
5032                "Metric",
5033                "m2",
5034                vec![("score".into(), Value::Str("high".into()))],
5035            )
5036            .unwrap();
5037        }
5038
5039        run_export(&src, &dst, &ExportFormat::Graphml).expect("graphml export");
5040        let content = std::fs::read_to_string(&dst).expect("read graphml");
5041
5042        assert!(
5043            content.contains(
5044                "<key id=\"n_score\" for=\"node\" attr.name=\"score\" attr.type=\"string\"/>"
5045            ),
5046            "a prop name with conflicting value types across nodes must declare \
5047             attr.type=\"string\", got: {content}"
5048        );
5049        assert!(
5050            !content.contains("attr.name=\"score\" attr.type=\"long\""),
5051            "must not declare a narrower type once a conflict is seen, got: {content}"
5052        );
5053        // Each node's own value still renders in its own literal text form,
5054        // regardless of the declared (fallback) attr.type.
5055        assert!(
5056            content.contains("<data key=\"n_score\">5</data>"),
5057            "the int-valued node must still render its literal int text, got: {content}"
5058        );
5059        assert!(
5060            content.contains("<data key=\"n_score\">high</data>"),
5061            "the string-valued node must still render its literal string text, got: {content}"
5062        );
5063
5064        let _ = std::fs::remove_dir_all(&src);
5065        let _ = std::fs::remove_dir_all(&dst_dir);
5066    }
5067
5068    #[test]
5069    fn parse_algo_degree_defaults_dir_both() {
5070        let cmd = parse_args(&["algo", "degree", "/db"]).unwrap();
5071        match cmd {
5072            Command::Algo { dir, .. } => assert_eq!(dir, AlgoDir::Both),
5073            other => panic!("expected Algo, got {other:?}"),
5074        }
5075    }
5076
5077    #[test]
5078    fn parse_algo_degree_with_dir_flag() {
5079        for (arg, want) in [
5080            ("out", AlgoDir::Out),
5081            ("in", AlgoDir::In),
5082            ("both", AlgoDir::Both),
5083        ] {
5084            let cmd = parse_args(&["algo", "degree", "/db", "--dir", arg]).unwrap();
5085            match cmd {
5086                Command::Algo { dir, .. } => assert_eq!(dir, want, "--dir {arg}"),
5087                other => panic!("expected Algo, got {other:?}"),
5088            }
5089        }
5090        // `--dir=out` form too.
5091        let cmd = parse_args(&["algo", "degree", "/db", "--dir=in"]).unwrap();
5092        match cmd {
5093            Command::Algo { dir, .. } => assert_eq!(dir, AlgoDir::In),
5094            other => panic!("expected Algo, got {other:?}"),
5095        }
5096    }
5097
5098    #[test]
5099    fn parse_algo_rejects_unknown_dir() {
5100        assert!(parse_args(&["algo", "degree", "/db", "--dir", "sideways"]).is_err());
5101    }
5102
5103    #[test]
5104    fn parse_algo_communities_parses_edge_type_weight_prop_min_weight() {
5105        let cmd = parse_args(&[
5106            "algo",
5107            "communities",
5108            "/db",
5109            "--edge-type",
5110            "IMPORTS",
5111            "--edge-type=CO_CHANGED",
5112            "--weight-prop",
5113            "score",
5114            "--min-weight",
5115            "0.3",
5116            "--top",
5117            "5",
5118        ])
5119        .unwrap();
5120        match cmd {
5121            Command::Algo {
5122                subcmd,
5123                top,
5124                edge_types,
5125                weight_prop,
5126                min_weight,
5127                ..
5128            } => {
5129                assert_eq!(subcmd, AlgoSubcmd::Communities);
5130                assert_eq!(top, 5);
5131                assert_eq!(
5132                    edge_types,
5133                    vec!["IMPORTS".to_string(), "CO_CHANGED".to_string()]
5134                );
5135                assert_eq!(weight_prop, Some("score".to_string()));
5136                assert_eq!(min_weight, Some(0.3));
5137            }
5138            other => panic!("expected Algo, got {other:?}"),
5139        }
5140    }
5141
5142    #[test]
5143    fn parse_algo_communities_defaults_have_no_edge_type_or_weight_filter() {
5144        let cmd = parse_args(&["algo", "communities", "/db"]).unwrap();
5145        match cmd {
5146            Command::Algo {
5147                subcmd,
5148                edge_types,
5149                weight_prop,
5150                min_weight,
5151                ..
5152            } => {
5153                assert_eq!(subcmd, AlgoSubcmd::Communities);
5154                assert!(edge_types.is_empty());
5155                assert_eq!(weight_prop, None);
5156                assert_eq!(min_weight, None);
5157            }
5158            other => panic!("expected Algo, got {other:?}"),
5159        }
5160    }
5161
5162    /// I1: exporting a store containing NaN/Inf floats must succeed, not panic.
5163    /// The NaN field must be serialised as JSON null (lossy but safe).
5164    #[test]
5165    fn run_export_jsonl_nan_float_becomes_null() {
5166        use core_api::{GraphDb, Value};
5167        let src = tmp("cli-export-nan-src");
5168        let dst = tmp("cli-export-nan-dst");
5169
5170        // Insert a node with NaN, +Inf, and -Inf properties via the public API.
5171        {
5172            let mut db = GraphDb::open(&src).unwrap();
5173            db.insert_node(
5174                "Sensor",
5175                "s1",
5176                vec![
5177                    ("nan_val".into(), Value::Float(f64::NAN)),
5178                    ("pos_inf".into(), Value::Float(f64::INFINITY)),
5179                    ("neg_inf".into(), Value::Float(f64::NEG_INFINITY)),
5180                    ("normal".into(), Value::Float(1.5)),
5181                ],
5182            )
5183            .unwrap();
5184        }
5185
5186        // Export must succeed.
5187        run_export(&src, &dst, &ExportFormat::Jsonl).expect("export with NaN must succeed");
5188
5189        // nodes.jsonl must exist and the NaN fields must be null.
5190        let content =
5191            std::fs::read_to_string(dst.join("nodes.jsonl")).expect("nodes.jsonl missing");
5192        let row: serde_json::Value =
5193            serde_json::from_str(content.lines().next().unwrap()).expect("valid json line");
5194        assert_eq!(
5195            row["nan_val"],
5196            serde_json::Value::Null,
5197            "NaN must export as null"
5198        );
5199        assert_eq!(
5200            row["pos_inf"],
5201            serde_json::Value::Null,
5202            "+Inf must export as null"
5203        );
5204        assert_eq!(
5205            row["neg_inf"],
5206            serde_json::Value::Null,
5207            "-Inf must export as null"
5208        );
5209        // Normal float must survive.
5210        assert_eq!(
5211            row["normal"],
5212            serde_json::json!(1.5),
5213            "normal float roundtrips"
5214        );
5215
5216        let _ = std::fs::remove_dir_all(&src);
5217        let _ = std::fs::remove_dir_all(&dst);
5218    }
5219
5220    #[test]
5221    fn serve_tls_flags_parse_both_forms() {
5222        // --tls-cert VALUE --tls-key VALUE (space form)
5223        match parse_args(&[
5224            "serve",
5225            "/tmp/db",
5226            "--tls-cert",
5227            "/a/cert.pem",
5228            "--tls-key",
5229            "/a/key.pem",
5230        ])
5231        .unwrap()
5232        {
5233            Command::Serve {
5234                tls_cert, tls_key, ..
5235            } => {
5236                assert_eq!(tls_cert, Some(PathBuf::from("/a/cert.pem")));
5237                assert_eq!(tls_key, Some(PathBuf::from("/a/key.pem")));
5238            }
5239            other => panic!("{other:?}"),
5240        }
5241        // --tls-cert=VALUE --tls-key=VALUE (equals form)
5242        match parse_args(&[
5243            "serve",
5244            "/tmp/db",
5245            "--tls-cert=/b/cert.pem",
5246            "--tls-key=/b/key.pem",
5247        ])
5248        .unwrap()
5249        {
5250            Command::Serve {
5251                tls_cert, tls_key, ..
5252            } => {
5253                assert_eq!(tls_cert, Some(PathBuf::from("/b/cert.pem")));
5254                assert_eq!(tls_key, Some(PathBuf::from("/b/key.pem")));
5255            }
5256            other => panic!("{other:?}"),
5257        }
5258        // Neither → both None.
5259        match parse_args(&["serve", "/tmp/db"]).unwrap() {
5260            Command::Serve {
5261                tls_cert, tls_key, ..
5262            } => {
5263                assert_eq!(tls_cert, None);
5264                assert_eq!(tls_key, None);
5265            }
5266            other => panic!("{other:?}"),
5267        }
5268    }
5269
5270    #[test]
5271    fn serve_tls_flags_require_both() {
5272        // --tls-cert alone → error
5273        let err = parse_args(&["serve", "/tmp/db", "--tls-cert", "/a/cert.pem"]).unwrap_err();
5274        assert!(
5275            err.contains("tls-key"),
5276            "--tls-cert alone must mention --tls-key in error, got {err}"
5277        );
5278        // --tls-key alone → error
5279        let err = parse_args(&["serve", "/tmp/db", "--tls-key", "/a/key.pem"]).unwrap_err();
5280        assert!(
5281            err.contains("tls-cert"),
5282            "--tls-key alone must mention --tls-cert in error, got {err}"
5283        );
5284    }
5285
5286    #[test]
5287    fn version_flag_parses() {
5288        assert_eq!(parse_args(&["--version"]).unwrap(), Command::Version);
5289        assert_eq!(parse_args(&["-V"]).unwrap(), Command::Version);
5290        assert_eq!(parse_args(&["version"]).unwrap(), Command::Version);
5291    }
5292
5293    #[test]
5294    fn recall_parses_one_dir_and_is_listed_in_usage() {
5295        assert_eq!(
5296            parse_args(&["recall", "/tmp/db"]).unwrap(),
5297            Command::Recall {
5298                db_dir: Some(PathBuf::from("/tmp/db")),
5299                auto: false,
5300            }
5301        );
5302        assert!(
5303            parse_args(&["recall"]).is_err(),
5304            "one of <db-dir> or --auto is required"
5305        );
5306        assert!(usage().contains("mushroomdb recall <db-dir>"));
5307    }
5308
5309    #[test]
5310    fn why_takes_a_dir_and_two_keys() {
5311        assert_eq!(
5312            parse_args(&["why", "/tmp/db", "a.rs", "b.rs"]).unwrap(),
5313            Command::Why {
5314                db_dir: PathBuf::from("/tmp/db"),
5315                a: "a.rs".to_string(),
5316                b: "b.rs".to_string(),
5317            }
5318        );
5319
5320        // Too few arguments, too many, and a key that looks like a flag.
5321        for args in [
5322            vec!["why", "/tmp/db", "a"],
5323            vec!["why", "/tmp/db", "a", "b", "c"],
5324            vec!["why", "/tmp/db", "-a", "b"],
5325        ] {
5326            assert!(parse_args(&args).is_err(), "{args:?} must not parse");
5327        }
5328        assert!(usage().contains("mushroomdb why <db-dir> <a> <b>"));
5329    }
5330
5331    /// Every hook-driven command takes either a path or `--auto`, never both
5332    /// and never neither.
5333    #[test]
5334    fn hook_commands_take_a_dir_or_auto() {
5335        assert_eq!(
5336            parse_args(&["mcp", "--auto"]).unwrap(),
5337            Command::Mcp {
5338                db_dir: None,
5339                auto: true,
5340                all_tools: false
5341            }
5342        );
5343        assert_eq!(
5344            parse_args(&["recall", "--auto"]).unwrap(),
5345            Command::Recall {
5346                db_dir: None,
5347                auto: true
5348            }
5349        );
5350        assert_eq!(
5351            parse_args(&["brief", "--auto"]).unwrap(),
5352            Command::Brief {
5353                db_dir: None,
5354                auto: true
5355            }
5356        );
5357        assert_eq!(
5358            parse_args(&["brief", "/tmp/db"]).unwrap(),
5359            Command::Brief {
5360                db_dir: Some(PathBuf::from("/tmp/db")),
5361                auto: false
5362            }
5363        );
5364        for cmd in ["mcp", "recall", "brief"] {
5365            assert!(parse_args(&[cmd]).is_err(), "{cmd} with no target");
5366            assert!(
5367                parse_args(&[cmd, "/tmp/db", "--auto"]).is_err(),
5368                "{cmd} with both"
5369            );
5370        }
5371        assert!(usage().contains("--auto"));
5372    }
5373
5374    /// Binding: `--all-tools` is `mcp`'s alone, sits either side of the store
5375    /// path, and every other flag is still rejected.
5376    #[test]
5377    fn mcp_takes_all_tools() {
5378        for args in [
5379            &["mcp", "/tmp/db", "--all-tools"][..],
5380            &["mcp", "--all-tools", "/tmp/db"][..],
5381        ] {
5382            assert_eq!(
5383                parse_args(args).unwrap(),
5384                Command::Mcp {
5385                    db_dir: Some(PathBuf::from("/tmp/db")),
5386                    auto: false,
5387                    all_tools: true
5388                },
5389                "{args:?}"
5390            );
5391        }
5392        assert_eq!(
5393            parse_args(&["mcp", "--auto", "--all-tools"]).unwrap(),
5394            Command::Mcp {
5395                db_dir: None,
5396                auto: true,
5397                all_tools: true
5398            }
5399        );
5400        assert!(parse_args(&["mcp", "--all-tools"]).is_err(), "no target");
5401        assert!(parse_args(&["mcp", "/tmp/db", "--nope"]).is_err());
5402        assert!(parse_args(&["recall", "/tmp/db", "--all-tools"]).is_err());
5403        assert!(usage().contains("--all-tools"));
5404    }
5405
5406    #[test]
5407    fn ingest_git_parses_excludes() {
5408        let cmd = parse_args(&[
5409            "ingest-git",
5410            "/tmp/db",
5411            "/tmp/repo",
5412            "--exclude",
5413            "target/",
5414            "--exclude=*.lock",
5415            "--max-commits-per-file",
5416            "50",
5417            "--recurse-submodules",
5418            "--prs",
5419            "--ensure-gitignore",
5420        ])
5421        .unwrap();
5422        assert_eq!(
5423            cmd,
5424            Command::IngestGit {
5425                db_dir: PathBuf::from("/tmp/db"),
5426                opts: ingest_git::IngestGitOpts {
5427                    repo: PathBuf::from("/tmp/repo"),
5428                    exclude: vec!["target/".into(), "*.lock".into()],
5429                    max_commits_per_file: 50,
5430                    recurse_submodules: true,
5431                    prs: true,
5432                    structure: true,
5433                    docs: true,
5434                    ensure_gitignore: true,
5435                },
5436            }
5437        );
5438        // Defaults and arity.
5439        let Command::IngestGit { opts, .. } =
5440            parse_args(&["ingest-git", "/tmp/db", "/tmp/repo"]).unwrap()
5441        else {
5442            panic!("expected IngestGit");
5443        };
5444        assert_eq!(
5445            opts.exclude,
5446            ingest_git::DEFAULT_EXCLUDES
5447                .iter()
5448                .map(|p| (*p).to_string())
5449                .collect::<Vec<_>>(),
5450            "with no --exclude the defaults apply"
5451        );
5452        assert_eq!(
5453            opts.max_commits_per_file,
5454            ingest_git::DEFAULT_MAX_COMMITS_PER_FILE
5455        );
5456        assert!(!opts.recurse_submodules && !opts.prs && !opts.ensure_gitignore);
5457        assert!(
5458            opts.structure && opts.docs,
5459            "structure and docs default on and are recorded on the marker"
5460        );
5461        let Command::IngestGit { opts, .. } = parse_args(&[
5462            "ingest-git",
5463            "/tmp/db",
5464            "/tmp/repo",
5465            "--no-structure",
5466            "--no-docs",
5467        ])
5468        .unwrap() else {
5469            panic!("expected IngestGit");
5470        };
5471        assert!(!opts.structure && !opts.docs);
5472        assert!(parse_args(&["ingest-git", "/tmp/db"]).is_err());
5473        assert!(parse_args(&["ingest-git", "/tmp/db", "/tmp/repo", "--nope"]).is_err());
5474        assert!(parse_args(&["ingest-git", "/tmp/db", "/tmp/repo", "--exclude"]).is_err());
5475        assert!(usage().contains("mushroomdb ingest-git <db-dir> <repo-dir>"));
5476    }
5477
5478    #[test]
5479    fn version_constant_matches_cargo() {
5480        assert_eq!(VERSION, env!("CARGO_PKG_VERSION"));
5481        assert!(usage().contains("--version"));
5482    }
5483    // ── Namespaces on the CLI ────────────────────────────────────────────────
5484
5485    /// A store with two namespaces and one role bound to the first.
5486    fn ns_store(name: &str) -> PathBuf {
5487        let dir = tmp(name);
5488        let mut db = GraphDb::open(&dir).expect("open");
5489        for (key, ns) in [
5490            ("d1", None),
5491            ("a1", Some("tenant-a")),
5492            ("a2", Some("tenant-a")),
5493            ("b1", Some("tenant-b")),
5494        ] {
5495            let mut props = vec![("id".into(), Value::Str(key.into()))];
5496            if let Some(ns) = ns {
5497                props.push(("ns".into(), Value::Str(ns.into())));
5498            }
5499            db.insert_node("Doc", key, props).expect("insert");
5500        }
5501        db.apply_schema(&Schema {
5502            roles: vec![core_api::RoleDef {
5503                name: "a-reader".into(),
5504                keys: vec![],
5505                labels: vec!["Doc".into()],
5506                visible_where: None,
5507                namespaces: Some(vec!["tenant-a".into()]),
5508                write: None,
5509            }],
5510            ..Default::default()
5511        })
5512        .expect("schema");
5513        dir
5514    }
5515
5516    /// `stats` names every namespace and its live count once a store has more
5517    /// than the default one.
5518    #[test]
5519    fn format_stats_lists_namespaces() {
5520        let dir = ns_store("stats-namespaces");
5521        let text = format_stats(&read_stats(&dir).expect("stats"));
5522        assert!(
5523            text.contains("namespaces: default (1), tenant-a (2), tenant-b (1)"),
5524            "got:\n{text}"
5525        );
5526        let _ = std::fs::remove_dir_all(&dir);
5527    }
5528
5529    /// A single-tenant store's `stats` output is byte-identical to what it was
5530    /// before namespaces existed: no line at all.
5531    #[test]
5532    fn format_stats_omits_the_namespaces_line_on_one_namespace() {
5533        let dir = tmp("stats-one-namespace");
5534        {
5535            let mut db = GraphDb::open(&dir).expect("open");
5536            db.insert_node("Person", "a", vec![]).expect("insert");
5537        }
5538        let text = format_stats(&read_stats(&dir).expect("stats"));
5539        assert!(
5540            !text.contains("namespaces"),
5541            "a store with only `default` says nothing about namespaces, got:\n{text}"
5542        );
5543        let _ = std::fs::remove_dir_all(&dir);
5544    }
5545
5546    /// `query --namespace` and `query --role` parse, and they compose.
5547    #[test]
5548    fn parse_query_takes_a_role_and_a_namespace() {
5549        let Ok(Command::Query {
5550            role, namespace, ..
5551        }) = parse_args(&[
5552            "query",
5553            "/tmp/db",
5554            "--role",
5555            "a-reader",
5556            "--namespace",
5557            "tenant-a",
5558            "MATCH (n) RETURN n",
5559        ])
5560        else {
5561            panic!("expected Query");
5562        };
5563        assert_eq!(role.as_deref(), Some("a-reader"));
5564        assert_eq!(namespace.as_deref(), Some("tenant-a"));
5565
5566        let Ok(Command::Query {
5567            role, namespace, ..
5568        }) = parse_args(&[
5569            "query",
5570            "/tmp/db",
5571            "--namespace=tenant-b",
5572            "MATCH (n) RETURN n",
5573        ])
5574        else {
5575            panic!("expected Query");
5576        };
5577        assert_eq!(role, None);
5578        assert_eq!(namespace.as_deref(), Some("tenant-b"));
5579
5580        assert!(parse_args(&["query", "/tmp/db", "--namespace"]).is_err());
5581        assert!(parse_args(&["query", "/tmp/db", "--role"]).is_err());
5582        assert!(usage().contains("--namespace <ns>"));
5583    }
5584
5585    /// `query --role` answers as that role, `--namespace` narrows, and the two
5586    /// together intersect — a role bound to one namespace never sees another.
5587    #[test]
5588    fn run_query_with_a_role_and_a_namespace_never_widens() {
5589        let dir = ns_store("query-namespace");
5590        let q = "MATCH (n) RETURN n.id AS id ORDER BY n.id";
5591
5592        let all = run_query(&dir, q, None, None).expect("query");
5593        assert!(all.contains("id=a1") && all.contains("id=b1") && all.contains("id=d1"));
5594
5595        let ns = run_query(&dir, q, None, Some("tenant-a")).expect("query");
5596        assert!(ns.contains("id=a1") && ns.contains("id=a2"), "got {ns}");
5597        assert!(!ns.contains("id=b1") && !ns.contains("id=d1"), "got {ns}");
5598
5599        let role = run_query(&dir, q, Some("a-reader"), None).expect("query");
5600        assert!(
5601            role.contains("id=a1") && !role.contains("id=b1"),
5602            "got {role}"
5603        );
5604
5605        let both = run_query(&dir, q, Some("a-reader"), Some("tenant-b")).expect("query");
5606        assert!(
5607            !both.contains("id=a1") && !both.contains("id=b1"),
5608            "role ∩ namespace, never role ∪ namespace: {both}"
5609        );
5610
5611        // Either argument makes the query a read: a restricted write is refused
5612        // and nothing lands.
5613        for (role, namespace) in [
5614            (None, Some("tenant-a")),
5615            (Some("a-reader"), None),
5616            (Some("a-reader"), Some("tenant-a")),
5617        ] {
5618            let write = run_query(&dir, "CREATE (n:Doc {id: 'z1'})", role, namespace);
5619            assert!(
5620                write
5621                    .as_ref()
5622                    .err()
5623                    .is_some_and(|e| e.0.contains("read-only")),
5624                "a restricted write must be refused, got {write:?}"
5625            );
5626            assert!(
5627                !GraphDb::open(&dir).expect("reopen").has_node("z1"),
5628                "the write must not have landed"
5629            );
5630        }
5631
5632        let unknown = run_query(&dir, q, Some("nobody"), None);
5633        assert!(unknown.is_err(), "an unknown role is an error");
5634        let invalid = run_query(&dir, q, None, Some("no spaces"));
5635        assert!(
5636            invalid
5637                .as_ref()
5638                .err()
5639                .is_some_and(|e| e.0.contains("valid namespace name")),
5640            "{invalid:?}"
5641        );
5642        let _ = std::fs::remove_dir_all(&dir);
5643    }
5644
5645    /// `asof --namespace` reads one namespace as it was at a commit.
5646    #[test]
5647    fn run_asof_in_a_namespace() {
5648        let dir = ns_store("asof-namespace");
5649        let at = {
5650            let db = GraphDb::open(&dir).expect("open");
5651            db.wal_total_commits().expect("commits") - 1
5652        };
5653        {
5654            let mut db = GraphDb::open(&dir).expect("open");
5655            db.insert_node(
5656                "Doc",
5657                "a3",
5658                vec![
5659                    ("id".into(), Value::Str("a3".into())),
5660                    ("ns".into(), Value::Str("tenant-a".into())),
5661                ],
5662            )
5663            .expect("insert");
5664        }
5665        let q = "MATCH (n) RETURN n.id AS id ORDER BY n.id";
5666        let then = run_asof(&dir, Some(at), None, Some(q), Some("tenant-a")).expect("asof");
5667        assert!(
5668            then.contains("id=a1") && then.contains("id=a2"),
5669            "got {then}"
5670        );
5671        assert!(
5672            !then.contains("id=a3") && !then.contains("id=b1"),
5673            "a3 did not exist then and b1 is another namespace: {then}"
5674        );
5675        let now = run_asof(&dir, Some(at + 1), None, Some(q), Some("tenant-a")).expect("asof");
5676        assert!(now.contains("id=a3"), "got {now}");
5677        let _ = std::fs::remove_dir_all(&dir);
5678    }
5679
5680    /// `schema apply` takes a v4 roles file — a role bound to namespaces — and
5681    /// the sidecar it writes says version 4.
5682    #[test]
5683    fn schema_apply_accepts_v4_roles_with_namespaces() {
5684        let dir = tmp("schema-v4");
5685        {
5686            let mut db = GraphDb::open(&dir).expect("open");
5687            db.insert_node(
5688                "Doc",
5689                "a1",
5690                vec![("ns".into(), Value::Str("tenant-a".into()))],
5691            )
5692            .expect("insert");
5693        }
5694        let file = dir.join("schema.json");
5695        std::fs::write(
5696            &file,
5697            r#"{"roles": [{"name": "a-reader", "labels": ["Doc"], "keys": [],
5698                 "namespaces": ["tenant-a"]}]}"#,
5699        )
5700        .expect("write schema");
5701        let out = run_schema_apply(&dir, &file).expect("apply");
5702        assert!(out.contains("a-reader"), "got {out}");
5703        let sidecar = std::fs::read_to_string(dir.join("roles.json")).expect("roles.json");
5704        assert!(
5705            sidecar.contains("\"version\": 4") || sidecar.contains("\"version\":4"),
5706            "a role with namespaces writes version 4: {sidecar}"
5707        );
5708        assert!(sidecar.contains("tenant-a"), "{sidecar}");
5709        let _ = std::fs::remove_dir_all(&dir);
5710    }
5711}