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