diff --git a/Cargo.lock b/Cargo.lock index 29ae3504..603efedc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -188,6 +188,7 @@ dependencies = [ "bytes", "chrono", "clap", + "clap_complete", "console", "data-encoding", "dialoguer", @@ -547,6 +548,18 @@ dependencies = [ "terminal_size", ] +[[package]] +name = "clap_complete" +version = "4.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f84a88507dbd05c695f2cb5e8558e747179134005e9893882dec964190ed89" +dependencies = [ + "clap", + "clap_lex", + "is_executable", + "shlex", +] + [[package]] name = "clap_derive" version = "4.6.1" @@ -1591,6 +1604,15 @@ dependencies = [ "once_cell", ] +[[package]] +name = "is_executable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82cb6a9f675da968c63b6208c641b9dca58fc0133ae53375736b1767b0cab8bd" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "is_terminal_polyfill" version = "1.70.2" diff --git a/Cargo.toml b/Cargo.toml index 3ce1a156..4aaf72e5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -64,6 +64,7 @@ rusqlite = { version = "0.32", features = ["bundled"] } # CLI clap = { version = "4.5", features = ["derive", "env", "wrap_help"] } +clap_complete = { version = "4.5", features = ["unstable-dynamic"] } indicatif = "0.17" dialoguer = "0.11" console = "0.15" diff --git a/atomic-cli/Cargo.toml b/atomic-cli/Cargo.toml index 031297f7..f2be7494 100644 --- a/atomic-cli/Cargo.toml +++ b/atomic-cli/Cargo.toml @@ -34,6 +34,7 @@ atomic-teams = { workspace = true, optional = true } # CLI clap = { workspace = true } +clap_complete = { workspace = true } indicatif = { workspace = true } dialoguer = { workspace = true } console = { workspace = true } diff --git a/atomic-cli/src/commands/change/command.rs b/atomic-cli/src/commands/change/command.rs index 12d04638..ec9f71ed 100644 --- a/atomic-cli/src/commands/change/command.rs +++ b/atomic-cli/src/commands/change/command.rs @@ -1,3 +1,7 @@ +use clap_complete::engine::ArgValueCompleter; + +use crate::commands::complete::{complete_change_hashes, complete_view_names}; + use super::*; // Change Command @@ -35,14 +39,14 @@ pub struct ChangeCmd { /// /// If omitted, shows the most recent change on the current view. /// Sequence numbers can be prefixed with `#` (e.g., `#42`). - #[arg(value_name = "HASH_OR_SEQ")] + #[arg(value_name = "HASH_OR_SEQ", add = ArgValueCompleter::new(complete_change_hashes))] pub identifier: Option, /// View to use for sequence lookup. /// /// When looking up by sequence number, use this view instead /// of the current view. - #[arg(long = "view", value_name = "NAME")] + #[arg(long = "view", value_name = "NAME", add = ArgValueCompleter::new(complete_view_names))] pub view: Option, /// Output format. diff --git a/atomic-cli/src/commands/client.rs b/atomic-cli/src/commands/client.rs index aa5cb9b2..6bcf9b61 100644 --- a/atomic-cli/src/commands/client.rs +++ b/atomic-cli/src/commands/client.rs @@ -219,7 +219,9 @@ pub fn remote_err(e: atomic_remote::RemoteError) -> CliError { /// Resolution order: /// 1. `--org` override (if `Some(non-empty)`) /// 2. `server.default_org` from the resolved server profile -/// 3. Error with a hint to run `atomic org set` +/// 3. The default identity's personal org (the identity name), so commands +/// always target the tenant associated with the active identity even +/// before any `atomic org set` /// /// An explicit empty string (`--org ""`) is an error: the user asked for "no /// org" which never makes sense. @@ -236,19 +238,27 @@ pub fn resolve_org_with_server( return Ok(s.to_string()); } - server - .default_org - .clone() - .ok_or_else(|| CliError::InvalidArgument { - message: "No organization specified.\n \ - Use --org or set a default with: atomic org set " - .to_string(), - }) + if let Some(org) = &server.default_org { + return Ok(org.clone()); + } + + // Fall back to the personal org of the identity this server authenticates + // as. Registration seeds the personal org slug from the identity name, so + // the identity name is the correct default until the user runs + // `atomic org set` to switch to a team org. + let identity = resolve_identity_for_server(server).map_err(|_| CliError::InvalidArgument { + message: "No organization specified.\n \ + Use --org or set a default with: atomic org set " + .to_string(), + })?; + Ok(identity.name) } -/// Resolve the org slug using the legacy (single-server) config path. +/// Resolve the org slug for callers that don't already hold a server config. /// -/// Kept for callers that don't yet pass a server override. +/// Loads global config, resolves the active server profile, and delegates to +/// [`resolve_org_with_server`] so the identity-personal-org fallback applies +/// consistently. pub fn resolve_org(org_override: Option<&str>) -> CliResult { if let Some(s) = org_override { if s.is_empty() { @@ -262,14 +272,11 @@ pub fn resolve_org(org_override: Option<&str>) -> CliResult { let config = GlobalConfig::load() .map_err(|e| CliError::Internal(anyhow::anyhow!("Failed to load global config: {}", e)))?; - config - .server - .default_org - .ok_or_else(|| CliError::InvalidArgument { - message: "No organization specified.\n \ - Use --org or set a default with: atomic org set " - .to_string(), - }) + let (server, _name) = config + .resolve_server(None) + .map_err(|e| CliError::Internal(anyhow::anyhow!("{}", e)))?; + + resolve_org_with_server(None, server) } /// Resolve the workspace slug for a command, with fallback to the @@ -310,22 +317,28 @@ pub fn resolve_workspace_with_server( } /// Resolve the workspace slug for a command, with fallback to the -/// org-scoped default workspace from global config. +/// org-scoped default workspace from the **active** server profile. /// -/// Uses the legacy (single-server) config path. Prefer -/// [`resolve_workspace_with_server`] when you have already resolved the -/// active server. +/// Loads global config, resolves the active server profile (honouring +/// `server_override` → `default_server` → legacy `[server]`), and delegates +/// to [`resolve_workspace_with_server`]. This keeps reads aligned with +/// `atomic workspace set`, which writes into that same active profile — +/// otherwise a default set on a named profile would be invisible here. /// /// Resolution order: /// 1. `--workspace` override (if `Some(non-empty)`) -/// 2. `server.default_workspaces[org_slug]` from global config +/// 2. `server.default_workspaces[org_slug]` from the active server profile /// 3. Error with a hint to run `atomic workspace set` /// /// An explicit empty string (`--workspace ""`) is an error: the user /// explicitly asked for "no workspace", which is meaningless. Distinguishing /// `None` (not provided → fall back to default) from `Some("")` (provided /// empty → error) prevents a class of confusing bugs. -pub fn resolve_workspace(org_slug: &str, workspace_override: Option<&str>) -> CliResult { +pub fn resolve_workspace( + org_slug: &str, + workspace_override: Option<&str>, + server_override: Option<&str>, +) -> CliResult { if let Some(s) = workspace_override { if s.is_empty() { return Err(CliError::InvalidArgument { @@ -338,17 +351,11 @@ pub fn resolve_workspace(org_slug: &str, workspace_override: Option<&str>) -> Cl let config = GlobalConfig::load() .map_err(|e| CliError::Internal(anyhow::anyhow!("Failed to load global config: {}", e)))?; - config - .server - .default_workspaces - .get(org_slug) - .cloned() - .ok_or_else(|| CliError::InvalidArgument { - message: format!( - "No workspace specified for org '{org_slug}'.\n \ - Use --workspace or set a default with: atomic workspace set " - ), - }) + let (server, _name) = config + .resolve_server(server_override) + .map_err(|e| CliError::Internal(anyhow::anyhow!("{}", e)))?; + + resolve_workspace_with_server(org_slug, None, server) } /// Resolve a flexible identity reference to a UUID. @@ -487,13 +494,13 @@ mod tests { #[test] fn resolve_workspace_passes_through_explicit_override() { - let result = resolve_workspace("acme", Some("backend")).unwrap(); + let result = resolve_workspace("acme", Some("backend"), None).unwrap(); assert_eq!(result, "backend"); } #[test] fn resolve_workspace_rejects_explicit_empty_override() { - let err = resolve_workspace("acme", Some("")).unwrap_err(); + let err = resolve_workspace("acme", Some(""), None).unwrap_err(); match err { CliError::InvalidArgument { message } => { assert!(message.contains("cannot be empty")); diff --git a/atomic-cli/src/commands/complete.rs b/atomic-cli/src/commands/complete.rs new file mode 100644 index 00000000..02bda6ce --- /dev/null +++ b/atomic-cli/src/commands/complete.rs @@ -0,0 +1,140 @@ +//! Dynamic shell-completion helpers. +//! +//! These back the `clap_complete` dynamic engine (see `main.rs`'s +//! `CompleteEnv`). Commands attach them to individual arguments with +//! `#[arg(add = ArgValueCompleter::new(...))]` so that, at completion time, +//! the binary offers live values from the repository — view names and change +//! hashes — instead of nothing. +//! +//! The pure `*_candidates` functions take a `&Repository` and are unit-tested +//! directly. The `complete_*` wrappers open the repository from the current +//! working directory and return an empty list (never an error) when there is +//! no repository there, so completion is always safe to invoke. + +use std::ffi::OsStr; + +use clap_complete::engine::CompletionCandidate; + +use atomic_core::types::Base32; +use atomic_repository::Repository; + +use crate::commands::require_repository; + +/// Maximum number of change-hash completion candidates to return. +/// +/// Bounds the per-keystroke cost (we load a header per candidate) on repos +/// with large histories. Users typically type a hash prefix, which filters +/// the set down well before this cap. +const MAX_CHANGE_CANDIDATES: usize = 50; + +/// View-name completion candidates matching `prefix`, sorted. +/// +/// Pure over the repository so it can be unit-tested without the shell +/// completion machinery. +pub(crate) fn view_name_candidates(repo: &Repository, prefix: &str) -> Vec { + let mut names = match repo.list_views() { + Ok(v) => v, + Err(_) => return Vec::new(), + }; + names.retain(|n| n.starts_with(prefix)); + names.sort(); + names +} + +/// Change-hash completion candidates drawn from the change store. +/// +/// Commands that address a change by hash can reference *any* change that +/// exists in the repo, so the candidate source is the change store rather than +/// a single view's log. Returns `(base32_hash, optional_message)` pairs +/// filtered by `prefix` and capped at [`MAX_CHANGE_CANDIDATES`]. Pure over the +/// repository for unit testing. +pub(crate) fn change_hash_candidates( + repo: &Repository, + prefix: &str, +) -> Vec<(String, Option)> { + let mut out = Vec::new(); + for result in repo.iter_changes() { + let Ok(hash) = result else { continue }; + let b32 = hash.to_base32(); + if !prefix.is_empty() && !b32.starts_with(prefix) { + continue; + } + let message = repo + .load_change(&hash) + .ok() + .map(|c| c.hashed.header.message.clone()); + out.push((b32, message)); + if out.len() >= MAX_CHANGE_CANDIDATES { + break; + } + } + out +} + +/// Dynamic completer for view-name arguments. +/// +/// Runs in the user's CWD during completion; if there is no repository there +/// it returns no candidates rather than erroring. +pub(crate) fn complete_view_names(current: &OsStr) -> Vec { + let prefix = current.to_string_lossy(); + let Ok(repo) = require_repository(None) else { + return Vec::new(); + }; + view_name_candidates(&repo, &prefix) + .into_iter() + .map(CompletionCandidate::new) + .collect() +} + +/// Dynamic completer for change-hash arguments, annotating each hash with its +/// commit message as the completion description. +pub(crate) fn complete_change_hashes(current: &OsStr) -> Vec { + let prefix = current.to_string_lossy(); + let Ok(repo) = require_repository(None) else { + return Vec::new(); + }; + change_hash_candidates(&repo, &prefix) + .into_iter() + .map(|(hash, msg)| { + let cand = CompletionCandidate::new(hash); + match msg { + Some(m) => cand.help(Some(m.into())), + None => cand, + } + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn view_name_candidates_filter_and_sort() { + let tmp = tempfile::tempdir().unwrap(); + let repo = Repository::init(tmp.path()).unwrap(); + + // A freshly initialised repo has the default `dev` view. + let all = view_name_candidates(&repo, ""); + assert!( + all.iter().any(|v| v == "dev"), + "expected default view: {all:?}" + ); + + // Prefix filtering. + let d = view_name_candidates(&repo, "d"); + assert!(d.iter().all(|v| v.starts_with('d'))); + assert!(d.iter().any(|v| v == "dev")); + + // Non-matching prefix yields nothing. + assert!(view_name_candidates(&repo, "zzz").is_empty()); + } + + #[test] + fn change_hash_candidates_empty_repo_is_empty() { + let tmp = tempfile::tempdir().unwrap(); + let repo = Repository::init(tmp.path()).unwrap(); + // No changes recorded yet -> no candidates, and no error/panic. + assert!(change_hash_candidates(&repo, "").is_empty()); + } +} diff --git a/atomic-cli/src/commands/completions.rs b/atomic-cli/src/commands/completions.rs new file mode 100644 index 00000000..7a7dbbc7 --- /dev/null +++ b/atomic-cli/src/commands/completions.rs @@ -0,0 +1,49 @@ +//! The `completions` command: emit a static shell completion script. +//! +//! This is the stable, ahead-of-time completion layer. It generates a script +//! (via `clap_complete::aot`) that completes subcommands and flags for the +//! given shell. Install it once, e.g. for zsh: +//! +//! ```text +//! atomic completions zsh > ~/.zfunc/_atomic +//! # ensure ~/.zfunc is on $fpath and `autoload -Uz compinit && compinit` runs +//! ``` +//! +//! For *dynamic* value completion — completing live view names and change +//! hashes after `atomic insert view`/`atomic insert change` — enable the +//! dynamic engine instead by adding this to your shell rc: +//! +//! ```text +//! source <(COMPLETE=zsh atomic) +//! ``` +//! +//! The dynamic path is wired in `main.rs` via `clap_complete::CompleteEnv` and +//! supersedes the static script (it also completes subcommands and flags). + +use clap_complete::aot::Shell; + +use crate::error::CliResult; + +/// Generate a shell completion script. +/// +/// The `` argument accepts any shell clap supports (`bash`, `zsh`, +/// `fish`, `elvish`, `powershell`). zsh is the primary target for now. +#[derive(Debug, clap::Args)] +#[command(name = "completions")] +pub struct Completions { + /// Shell to generate a completion script for. + #[arg(value_name = "SHELL")] + pub shell: Shell, +} + +impl Completions { + /// Write the completion script for `cmd` to stdout. + /// + /// `cmd` is supplied by the caller (the top-level `Cli::command()`), since + /// the completion generator needs the full command tree. + pub fn generate(&self, mut cmd: clap::Command) -> CliResult<()> { + let bin = cmd.get_name().to_string(); + clap_complete::aot::generate(self.shell, &mut cmd, bin, &mut std::io::stdout()); + Ok(()) + } +} diff --git a/atomic-cli/src/commands/diff/command.rs b/atomic-cli/src/commands/diff/command.rs index 531b207d..a5fccec6 100644 --- a/atomic-cli/src/commands/diff/command.rs +++ b/atomic-cli/src/commands/diff/command.rs @@ -1,3 +1,7 @@ +use clap_complete::engine::ArgValueCompleter; + +use crate::commands::complete::{complete_change_hashes, complete_view_names}; + use super::output::*; use super::*; @@ -28,7 +32,7 @@ pub struct Diff { pub files: Vec, /// Compare against a specific change hash or prefix. - #[arg(short = 'c', long = "change")] + #[arg(short = 'c', long = "change", add = ArgValueCompleter::new(complete_change_hashes))] pub change: Option, /// Diff algorithm: myers or patience. @@ -68,7 +72,7 @@ pub struct Diff { pub cached: bool, /// View to compare against. - #[arg(long)] + #[arg(long, add = ArgValueCompleter::new(complete_view_names))] pub view: Option, /// Enable token-level diff highlighting (CRDT-powered). diff --git a/atomic-cli/src/commands/insert.rs b/atomic-cli/src/commands/insert.rs index ce2cf179..25158e10 100644 --- a/atomic-cli/src/commands/insert.rs +++ b/atomic-cli/src/commands/insert.rs @@ -7,12 +7,14 @@ //! - Cherry-picking specific changes use clap::{Args, Subcommand}; +use clap_complete::engine::ArgValueCompleter; use atomic_core::types::{Base32, Hash}; use atomic_repository::{ CrossViewInsertOptions, CrossViewInsertOutcome, InsertOptions, Repository, }; +use crate::commands::complete::{complete_change_hashes, complete_view_names}; use crate::commands::{format_hash, require_repository}; use crate::error::{CliError, CliResult}; use crate::output; @@ -24,21 +26,31 @@ use crate::output; /// This command inserts changes into the repository graph. It supports several /// modes of operation: /// +/// - **Bare `atomic insert`** (no arguments): promote the current view's +/// changes into its parent view. This is the "I'm done with this draft, +/// land it" gesture. /// - Insert a single change by hash -/// - Insert all changes from one view to another -/// - Insert changes up to a specific tag -/// - Cherry-pick specific changes +/// - Insert all changes from one view to another (`from-view`) +/// - Insert changes up to a specific tag (`tag`) +/// - Cherry-pick specific changes (`pick`) #[derive(Debug, Args)] pub struct Insert { #[command(subcommand)] command: Option, /// Hash of the change to insert (when not using subcommands). - #[arg(value_name = "CHANGE")] + /// + /// Omit entirely to promote the current view's changes into its parent + /// view (see the command-level docs). + #[arg(value_name = "CHANGE", add = ArgValueCompleter::new(complete_change_hashes))] change: Option, - /// View to insert the change into (default: current view). - #[arg(long)] + /// Target view. + /// + /// For `atomic insert ` this is the view the change is inserted + /// into (default: current view). For the bare `atomic insert` promotion + /// it overrides the target (default: the current view's parent). + #[arg(long, visible_alias = "to", add = ArgValueCompleter::new(complete_view_names))] view: Option, /// Insert dependencies automatically. @@ -49,6 +61,14 @@ pub struct Insert { #[arg(long)] allow_conflicts: bool, + /// Preview the promotion without inserting anything. + #[arg(short = 'n', long)] + dry_run: bool, + + /// Skip the confirmation prompt when promoting between two shared views. + #[arg(long)] + confirm: bool, + /// Repository path. #[arg(short = 'R', long)] repository: Option, @@ -57,32 +77,36 @@ pub struct Insert { /// Insert subcommands for cross-view operations. #[derive(Debug, Subcommand)] pub enum InsertSubcommand { - /// Insert changes from one view to another. - #[command(name = "from-view")] - FromView(FromViewArgs), + /// Insert all changes from another view. + /// + /// `from-view` is kept as an alias for backward compatibility. + #[command(name = "view", alias = "from-view")] + View(ViewArgs), /// Insert changes up to a specific tag. #[command(name = "tag")] Tag(TagArgs), - /// Cherry-pick specific changes. - #[command(name = "pick")] - Pick(PickArgs), + /// Insert specific change(s) by hash. + /// + /// `pick` is kept as an alias for backward compatibility. + #[command(name = "change", alias = "pick")] + Change(ChangeArgs), /// Show what would be inserted (dry run). #[command(name = "preview")] Preview(PreviewArgs), } -/// Arguments for inserting from one view to another. +/// Arguments for inserting all changes from another view. #[derive(Debug, Args)] -pub struct FromViewArgs { +pub struct ViewArgs { /// Source view to copy changes from. - #[arg(value_name = "SOURCE")] + #[arg(value_name = "SOURCE", add = ArgValueCompleter::new(complete_view_names))] from_view: String, /// Target view to insert changes into (default: current view). - #[arg(long)] + #[arg(long, visible_alias = "to", add = ArgValueCompleter::new(complete_view_names))] to_view: Option, /// Insert dependencies automatically. @@ -94,7 +118,7 @@ pub struct FromViewArgs { allow_conflicts: bool, /// Perform a dry run (don't actually insert). - #[arg(long)] + #[arg(short = 'n', long)] dry_run: bool, } @@ -106,11 +130,11 @@ pub struct TagArgs { tag_name: String, /// Source view containing the tag. - #[arg(long)] + #[arg(long, add = ArgValueCompleter::new(complete_view_names))] from_view: Option, /// Target view to insert changes into (default: current view). - #[arg(long)] + #[arg(long, visible_alias = "to", add = ArgValueCompleter::new(complete_view_names))] to_view: Option, /// Insert dependencies automatically. @@ -122,19 +146,19 @@ pub struct TagArgs { allow_conflicts: bool, /// Perform a dry run (don't actually insert). - #[arg(long)] + #[arg(short = 'n', long)] dry_run: bool, } -/// Arguments for cherry-picking specific changes. +/// Arguments for inserting specific change(s) by hash. #[derive(Debug, Args)] -pub struct PickArgs { - /// Hashes of changes to cherry-pick. - #[arg(value_name = "CHANGES", required = true)] +pub struct ChangeArgs { + /// Hashes of changes to insert. + #[arg(value_name = "CHANGES", required = true, add = ArgValueCompleter::new(complete_change_hashes))] changes: Vec, /// Target view to insert changes into (default: current view). - #[arg(long)] + #[arg(long, visible_alias = "to", add = ArgValueCompleter::new(complete_view_names))] to_view: Option, /// Insert dependencies automatically. @@ -150,11 +174,11 @@ pub struct PickArgs { #[derive(Debug, Args)] pub struct PreviewArgs { /// Source view to preview changes from. - #[arg(value_name = "SOURCE")] + #[arg(value_name = "SOURCE", add = ArgValueCompleter::new(complete_view_names))] from_view: String, /// Target view (default: current view). - #[arg(long)] + #[arg(long, visible_alias = "to", add = ArgValueCompleter::new(complete_view_names))] to_view: Option, /// Optional tag to limit preview up to. @@ -170,18 +194,18 @@ impl crate::commands::Command for Insert { let repo = require_repository(repo_path)?; match &self.command { - Some(InsertSubcommand::FromView(args)) => run_from_view(&repo, args), + Some(InsertSubcommand::View(args)) => run_view_insert(&repo, args), Some(InsertSubcommand::Tag(args)) => run_tag(&repo, args), - Some(InsertSubcommand::Pick(args)) => run_pick(&repo, args), + Some(InsertSubcommand::Change(args)) => run_change_insert(&repo, args), Some(InsertSubcommand::Preview(args)) => run_preview(&repo, args), None => { - // Insert a single change if let Some(ref change_str) = self.change { + // Insert a single change into the current (or --view) view. run_single_insert(&repo, change_str, self) } else { - Err(CliError::InvalidArgument { - message: "Missing CHANGE argument. Provide a change hash or use a subcommand (from-view, tag, pick)".to_string(), - }) + // No change and no subcommand: promote the current view's + // changes into its parent view. + run_promote_to_parent(&repo, self) } } } @@ -236,8 +260,128 @@ fn run_single_insert(repo: &Repository, change_str: &str, args: &Insert) -> CliR Ok(()) } -/// Insert changes from one view to another. -fn run_from_view(repo: &Repository, args: &FromViewArgs) -> CliResult<()> { +/// Promote the current view's changes into its parent view. +/// +/// This is the behavior of a bare `atomic insert` (no change hash and no +/// subcommand). The source is always the current view; the target defaults to +/// the current view's parent but can be overridden with `--to`/`--view`. +/// +/// The working copy is intentionally NOT rematerialized: the target view is +/// not checked out, so the current view's on-disk state is unchanged. +fn run_promote_to_parent(repo: &Repository, args: &Insert) -> CliResult<()> { + let source = repo.current_view().to_string(); + let source_info = repo + .get_view_info(&source) + .map_err(|e| CliError::Internal(anyhow::anyhow!("{}", e)))?; + + // Resolve the target: explicit --to/--view, else the current view's parent. + let target = match args.view.as_deref() { + Some(v) => v.to_string(), + None => source_info + .parent_name + .clone() + .ok_or_else(|| CliError::InvalidArgument { + message: format!( + "'{source}' is a root view — there is no parent to insert into.\n \ + Use 'atomic insert from-view ' or pass --to \ + to choose a target." + ), + })?, + }; + + if target == source { + return Err(CliError::InvalidArgument { + message: format!( + "Source and target are the same view ('{source}'). \ + Pass --to to insert somewhere else." + ), + }); + } + + // Figure out what would move so we can show a count and short-circuit. + let missing = repo + .get_missing_changes_between(&source, Some(&target)) + .map_err(|e| CliError::Conflict { + description: e.to_string(), + })?; + + if missing.is_empty() { + output::print_success(&format!( + "Already even with '{target}' — nothing to insert." + )); + return Ok(()); + } + + output::print_info(&format!( + "Inserting {} change(s): {source} → {target}", + missing.len() + )); + + // Dry run: list the changes and stop before mutating. + if args.dry_run { + println!(); + for (i, hash) in missing.iter().enumerate() { + if let Ok(change) = repo.load_change(hash) { + let message = &change.hashed.header.message; + let short_msg = if message.len() > 50 { + format!("{}...", &message[..47]) + } else { + message.to_string() + }; + println!(" {}. {} {}", i + 1, format_hash(hash, true), short_msg); + } else { + println!(" {}. {}", i + 1, format_hash(hash, true)); + } + } + println!(); + output::print_info("Dry run: no changes inserted. Re-run without --dry-run to insert."); + return Ok(()); + } + + // Guard: promoting between two shared views is a bigger deal than landing + // a draft, so require confirmation unless --confirm was passed. + let target_info = repo + .get_view_info(&target) + .map_err(|e| CliError::Internal(anyhow::anyhow!("{}", e)))?; + let both_shared = source_info.scope.is_shared() && target_info.scope.is_shared(); + if both_shared && !args.confirm { + let prompt = format!( + "Insert {} change(s) from shared view '{source}' into shared view '{target}'?", + missing.len() + ); + let confirmed = dialoguer::Confirm::new() + .with_prompt(&prompt) + .default(false) + .interact() + .map_err(|_| CliError::InvalidArgument { + message: "Refusing to insert between two shared views without \ + confirmation. Re-run with --confirm to proceed \ + non-interactively." + .to_string(), + })?; + if !confirmed { + output::print_info("Aborted."); + return Ok(()); + } + } + + let options = CrossViewInsertOptions::new(&source, &target) + .with_dependencies(args.deps) + .allow_conflicts(args.allow_conflicts); + + let outcome = repo + .insert_from_view(options) + .map_err(|e| CliError::Conflict { + description: e.to_string(), + })?; + + print_cross_view_outcome(&outcome, false); + + Ok(()) +} + +/// Insert all changes from another view (the `insert view` subcommand). +fn run_view_insert(repo: &Repository, args: &ViewArgs) -> CliResult<()> { let to_view = args .to_view .clone() @@ -372,8 +516,8 @@ fn run_tag(repo: &Repository, args: &TagArgs) -> CliResult<()> { Ok(()) } -/// Cherry-pick specific changes. -fn run_pick(repo: &Repository, args: &PickArgs) -> CliResult<()> { +/// Insert specific change(s) by hash (the `insert change` subcommand). +fn run_change_insert(repo: &Repository, args: &ChangeArgs) -> CliResult<()> { let to_view = args .to_view .clone() @@ -473,7 +617,7 @@ fn run_preview(repo: &Repository, args: &PreviewArgs) -> CliResult<()> { } println!(); output::print_info(&format!( - "Run 'atomic insert from-view {}' to insert these changes.", + "Run 'atomic insert view {}' to insert these changes.", args.from_view )); } @@ -584,7 +728,7 @@ mod tests { #[test] fn test_insert_subcommand_variants() { // Just verify the enums compile correctly - let _ = InsertSubcommand::FromView(FromViewArgs { + let _ = InsertSubcommand::View(ViewArgs { from_view: "feature".to_string(), to_view: Some("main".to_string()), deps: true, @@ -601,7 +745,7 @@ mod tests { dry_run: false, }); - let _ = InsertSubcommand::Pick(PickArgs { + let _ = InsertSubcommand::Change(ChangeArgs { changes: vec!["abc123".to_string()], to_view: None, deps: true, @@ -616,8 +760,8 @@ mod tests { } #[test] - fn test_from_view_args_defaults() { - let args = FromViewArgs { + fn test_view_args_defaults() { + let args = ViewArgs { from_view: "feature".to_string(), to_view: None, deps: true, @@ -652,8 +796,8 @@ mod tests { } #[test] - fn test_pick_args_multiple_changes() { - let args = PickArgs { + fn test_change_args_multiple_changes() { + let args = ChangeArgs { changes: vec![ "abc123".to_string(), "def456".to_string(), diff --git a/atomic-cli/src/commands/log/command.rs b/atomic-cli/src/commands/log/command.rs index 7c64a05c..3944d5a9 100644 --- a/atomic-cli/src/commands/log/command.rs +++ b/atomic-cli/src/commands/log/command.rs @@ -1,3 +1,7 @@ +use clap_complete::engine::ArgValueCompleter; + +use crate::commands::complete::complete_view_names; + use super::*; // Log Command @@ -41,7 +45,7 @@ pub struct Log { /// /// By default, shows history for the current view. Use this /// option to view another view's history without switching. - #[arg(long = "view", value_name = "NAME")] + #[arg(long = "view", value_name = "NAME", add = ArgValueCompleter::new(complete_view_names))] pub view: Option, /// Only show tagged changes. diff --git a/atomic-cli/src/commands/mod.rs b/atomic-cli/src/commands/mod.rs index 58026626..3c19559f 100644 --- a/atomic-cli/src/commands/mod.rs +++ b/atomic-cli/src/commands/mod.rs @@ -69,6 +69,8 @@ use crate::error::{CliError, CliResult}; // Phase 2: Core Local Commands pub mod add; pub mod change; +pub mod complete; +pub mod completions; pub mod diff; pub mod doctor; pub mod init; @@ -130,6 +132,7 @@ pub use add::Add; pub use agent::Agent; pub use change::ChangeCmd; pub use clone::Clone; +pub use completions::Completions; pub use diff::Diff; pub use doctor::Doctor; pub use git::Git; diff --git a/atomic-cli/src/commands/org/delete.rs b/atomic-cli/src/commands/org/delete.rs index f9a19863..4ddc3da5 100644 --- a/atomic-cli/src/commands/org/delete.rs +++ b/atomic-cli/src/commands/org/delete.rs @@ -137,26 +137,26 @@ impl OrgDelete { /// Remove references to a deleted org from the local global config. /// -/// Returns the side effects performed so the caller can print appropriate -/// hints. Specifically: -/// - If `server.default_org == Some(slug)`, set it to `None` and hint. -/// - Remove `server.default_workspaces[slug]` if present. +/// Operates on the **active** server profile (the same one reads/writes +/// resolve to), so cleanup stays consistent when a named profile is active. +/// Specifically: +/// - If `default_org == Some(slug)`, set it to `None` and hint. +/// - Remove `default_workspaces[slug]` if present. fn clean_up_local_config(deleted_slug: &str) -> CliResult<()> { let mut config = GlobalConfig::load() .map_err(|e| CliError::Internal(anyhow::anyhow!("Failed to load global config: {e}")))?; + let (server, _name) = config + .resolve_server_mut(None) + .map_err(|e| CliError::Internal(anyhow::anyhow!("{e}")))?; + let mut changed = false; - let was_default_org = config.server.default_org.as_deref() == Some(deleted_slug); + let was_default_org = server.default_org.as_deref() == Some(deleted_slug); if was_default_org { - config.server.default_org = None; + server.default_org = None; changed = true; } - if config - .server - .default_workspaces - .remove(deleted_slug) - .is_some() - { + if server.default_workspaces.remove(deleted_slug).is_some() { changed = true; } diff --git a/atomic-cli/src/commands/org/set.rs b/atomic-cli/src/commands/org/set.rs index 3f558597..8d0fdb5c 100644 --- a/atomic-cli/src/commands/org/set.rs +++ b/atomic-cli/src/commands/org/set.rs @@ -109,13 +109,28 @@ impl OrgSet { CliError::Internal(anyhow::anyhow!("Failed to load global config: {e}")) })?; - let previous = config.server.default_org.clone(); - config.server.default_org = Some(self.slug.clone()); + // Write to the *active* server profile (named profile when one is + // active, else the legacy `[server]` block) so the new default is + // read back by org/workspace/project commands, which resolve the + // same profile. + let (server, profile_name) = config + .resolve_server_mut(None) + .map_err(|e| CliError::Internal(anyhow::anyhow!("{e}")))?; + + let previous = server.default_org.clone(); + server.default_org = Some(self.slug.clone()); + config.save().map_err(|e| { CliError::Internal(anyhow::anyhow!("Failed to save global config: {e}")) })?; - print_success(&format!("Default organization set to: {}", self.slug)); + match &profile_name { + Some(name) => print_success(&format!( + "Default organization for server '{name}' set to: {}", + self.slug + )), + None => print_success(&format!("Default organization set to: {}", self.slug)), + } if let Some(prev) = &previous { if prev != &self.slug { @@ -221,9 +236,12 @@ mod tests { use serial_test::serial; - /// Save the current `HOME` value and point it at a tempdir for the - /// lifetime of the guard. Restores on drop. Wraps the tempdir so the - /// directory lives as long as `HOME` points at it. + /// Redirect `ATOMIC_CONFIG_DIR` to a tempdir for the lifetime of the guard, + /// isolating `GlobalConfig` load/save from the real user config. Restores + /// the original value on drop. Uses `ATOMIC_CONFIG_DIR` rather than `HOME` + /// because `atomic_config` resolves its path via that override — `HOME` + /// alone does not isolate on Windows (where `dirs::home_dir()` reads the + /// profile known-folder, not `HOME`). struct HomeGuard { _tmp: tempfile::TempDir, original: Option, @@ -232,18 +250,12 @@ mod tests { impl HomeGuard { fn new() -> Self { let tmp = tempfile::tempdir().unwrap(); - let original = std::env::var_os("HOME"); - // SAFETY: env mutation is technically UB if accessed - // concurrently from another thread. `#[serial]` serializes - // these tests against each other but does NOT prevent - // unmarked tests elsewhere in the workspace from reading - // HOME concurrently. No other test in this crate currently - // mutates or reads HOME outside its own `#[serial]` block, - // so the race window is empty today. A path-aware - // GlobalConfig API would eliminate this — tracked as a - // follow-up. + let original = std::env::var_os("ATOMIC_CONFIG_DIR"); + // SAFETY: env mutation is technically UB under concurrent access. + // `#[serial]` serializes these tests, and no other test reads + // ATOMIC_CONFIG_DIR outside its own `#[serial]` block. unsafe { - std::env::set_var("HOME", tmp.path()); + std::env::set_var("ATOMIC_CONFIG_DIR", tmp.path()); } Self { _tmp: tmp, @@ -257,8 +269,8 @@ mod tests { // SAFETY: see HomeGuard::new. unsafe { match &self.original { - Some(v) => std::env::set_var("HOME", v), - None => std::env::remove_var("HOME"), + Some(v) => std::env::set_var("ATOMIC_CONFIG_DIR", v), + None => std::env::remove_var("ATOMIC_CONFIG_DIR"), } } } @@ -299,6 +311,48 @@ mod tests { ); } + #[test] + #[serial] + fn writes_to_active_named_profile_not_legacy_block() { + // Regression for the "org set doesn't pass through" bug: when a named + // profile is active (default_server set), `org set` must mutate that + // profile's default_org, not the legacy [server] block — otherwise + // read commands (which resolve the named profile) never see it. + let _guard = HomeGuard::new(); + + let mut cfg = GlobalConfig::load().unwrap(); + cfg.default_server = Some("prod".to_string()); + cfg.servers.insert( + "prod".to_string(), + atomic_config::ServerConfig { + url: Some("https://atomic.storage".to_string()), + default_org: None, + default_workspaces: std::collections::BTreeMap::new(), + identity: Some("continuouslee".to_string()), + single_tenant: false, + }, + ); + cfg.save().unwrap(); + + let cmd = OrgSet { + slug: "atomic".to_string(), + no_verify: false, + }; + let result = cmd.run_with_verifier(|_| Ok(())); + assert!(result.is_ok()); + + let after = GlobalConfig::load().unwrap(); + assert_eq!( + after.servers["prod"].default_org.as_deref(), + Some("atomic"), + "org set must write to the active named profile" + ); + assert!( + after.server.default_org.is_none(), + "org set must not touch the legacy [server] block when a named profile is active" + ); + } + #[test] #[serial] fn config_written_when_verifier_succeeds() { diff --git a/atomic-cli/src/commands/project/create.rs b/atomic-cli/src/commands/project/create.rs index 8eae9ca7..09843eb7 100644 --- a/atomic-cli/src/commands/project/create.rs +++ b/atomic-cli/src/commands/project/create.rs @@ -133,7 +133,8 @@ impl Command for ProjectCreate { rt.block_on(async { let (client, org_slug) = build_client_with_org(self.org.as_deref(), self.server.as_deref()).await?; - let workspace = resolve_workspace(&org_slug, self.workspace.as_deref())?; + let workspace = + resolve_workspace(&org_slug, self.workspace.as_deref(), self.server.as_deref())?; let visibility = self.parse_visibility()?; let req = CreateProjectRequest { diff --git a/atomic-cli/src/commands/project/init.rs b/atomic-cli/src/commands/project/init.rs index 67b4ccd4..4d595dae 100644 --- a/atomic-cli/src/commands/project/init.rs +++ b/atomic-cli/src/commands/project/init.rs @@ -115,7 +115,7 @@ impl ProjectInit { // 2. Build the storage client and resolve the workspace. let (client, org_slug) = build_client_with_org(self.org.as_deref(), None).await?; - let workspace = resolve_workspace(&org_slug, self.workspace.as_deref())?; + let workspace = resolve_workspace(&org_slug, self.workspace.as_deref(), None)?; // 3. Ensure the workspace exists — create it if necessary. // A 409 (Conflict) means it already exists, which is fine. diff --git a/atomic-cli/src/commands/project/list.rs b/atomic-cli/src/commands/project/list.rs index 2944aaad..2bf4a5aa 100644 --- a/atomic-cli/src/commands/project/list.rs +++ b/atomic-cli/src/commands/project/list.rs @@ -76,7 +76,8 @@ impl Command for ProjectList { rt.block_on(async { let (client, org_slug) = build_client_with_org(self.org.as_deref(), self.server.as_deref()).await?; - let workspace = resolve_workspace(&org_slug, self.workspace.as_deref())?; + let workspace = + resolve_workspace(&org_slug, self.workspace.as_deref(), self.server.as_deref())?; let projects = client.list_projects(&workspace).await.map_err(remote_err)?; diff --git a/atomic-cli/src/commands/query/mod.rs b/atomic-cli/src/commands/query/mod.rs index c4455fd1..ea3b1d48 100644 --- a/atomic-cli/src/commands/query/mod.rs +++ b/atomic-cli/src/commands/query/mod.rs @@ -1081,7 +1081,13 @@ impl Command for QueryNodes { // fetch_limit = pool so all pool candidates become results (pool_val, Some(pool_val)) } else { - (self.limit, self.pool) + // Without a kind filter, request a generous candidate pool so the + // diversity-aware selection in `vault_kg_search` engages. Otherwise + // (pool == limit) it falls back to plain top-N by score, and once a + // content index exists, high-scoring `file`/`module` nodes crowd + // out lower-scored vault nodes (intents, todos, sessions, + // memories), so an enriched repo would only ever return files. + (self.limit, Some(self.pool.unwrap_or(5000))) }; let all_nodes = repo @@ -1476,6 +1482,17 @@ pub struct QueryEnrich { /// Without this option, all VCS-derived KG data is rebuilt. #[arg(long = "change", value_name = "FULL_HASH")] pub changes: Vec, + + /// Force a clean rebuild: drop all previously enriched VCS/AST-derived + /// KG nodes (files, modules, views, changes, entities) before + /// re-deriving them. + /// + /// A plain enrich only upserts, so nodes that no longer apply — files + /// that became ignored or were deleted — linger as stale entries. Pass + /// `--rebuild` to reconcile. Vault and session nodes are never affected. + /// Cannot be combined with `--change`. + #[arg(long, conflicts_with = "changes")] + pub rebuild: bool, } fn parse_change_hash(value: &str) -> CliResult { @@ -1558,6 +1575,7 @@ mod enrich_tests { std::env::set_current_dir(temp.path()).unwrap(); QueryEnrich { changes: vec![full_hash], + rebuild: false, } .run() .unwrap(); @@ -1584,13 +1602,23 @@ impl Command for QueryEnrich { .collect::>>()?; for hash in &hashes { - repo.kg_enrich_change(hash).map_err(CliError::Repository)?; + repo.enrich_change(hash).map_err(CliError::Repository)?; } println!("Enriched {} change(s).", hashes.len()); return Ok(()); } + // Clean rebuild: drop stale VCS/AST-derived nodes so files that became + // ignored or were deleted don't linger. Vault/session nodes are kept. + if self.rebuild { + let spinner = create_spinner("Clearing stale KG entries..."); + match repo.kg_clear_derived() { + Ok(n) => finish_success(&spinner, &format!("{} stale node(s) removed", n)), + Err(e) => finish_error(&spinner, &format!("clear failed: {}", e)), + } + } + let mut total = atomic_repository::KgEnrichStats::default(); // Phase 1: Views diff --git a/atomic-cli/src/commands/workspace/delete.rs b/atomic-cli/src/commands/workspace/delete.rs index 41e91c59..ce6cc5a3 100644 --- a/atomic-cli/src/commands/workspace/delete.rs +++ b/atomic-cli/src/commands/workspace/delete.rs @@ -115,14 +115,21 @@ impl Command for WorkspaceDelete { } } -/// Remove a deleted workspace from `[server.default_workspaces]` if it was -/// the configured default for its org. +/// Remove a deleted workspace from the active server profile's +/// `default_workspaces` if it was the configured default for its org. +/// +/// Operates on the **active** server profile (the same one +/// `atomic workspace set` writes to) so cleanup stays consistent when a +/// named profile is active. fn clean_up_local_config(org_slug: &str, deleted_workspace: &str) -> CliResult<()> { let mut config = GlobalConfig::load() .map_err(|e| CliError::Internal(anyhow::anyhow!("Failed to load global config: {e}")))?; - let was_default = config - .server + let (server, _name) = config + .resolve_server_mut(None) + .map_err(|e| CliError::Internal(anyhow::anyhow!("{e}")))?; + + let was_default = server .default_workspaces .get(org_slug) .map(|v| v == deleted_workspace) @@ -132,7 +139,7 @@ fn clean_up_local_config(org_slug: &str, deleted_workspace: &str) -> CliResult<( return Ok(()); } - config.server.default_workspaces.remove(org_slug); + server.default_workspaces.remove(org_slug); config .save() .map_err(|e| CliError::Internal(anyhow::anyhow!("Failed to save global config: {e}")))?; diff --git a/atomic-cli/src/commands/workspace/set.rs b/atomic-cli/src/commands/workspace/set.rs index b0309683..bc36b530 100644 --- a/atomic-cli/src/commands/workspace/set.rs +++ b/atomic-cli/src/commands/workspace/set.rs @@ -46,7 +46,7 @@ use clap::Parser; use atomic_config::GlobalConfig; -use crate::commands::client::{build_client_with_org, remote_err}; +use crate::commands::client::{build_client_with_org, remote_err, resolve_org_with_server}; use crate::commands::Command; use crate::error::{CliError, CliResult}; use crate::output::{print_hint, print_success}; @@ -112,10 +112,9 @@ impl WorkspaceSet { CliError::Internal(anyhow::anyhow!("Failed to load global config: {e}")) })?; - // Determine the target org. Explicit --org wins; otherwise fall - // back to the configured default. We don't go through `resolve_org` - // here because we want a distinct error message tied to *this* - // command's flow. + // Determine the target org. Explicit --org wins; otherwise resolve + // the active server profile's default org (falling back to the + // identity's personal org), so this matches what read commands use. let target_org = match self.org.as_deref() { Some(o) if !o.is_empty() => o.to_string(), Some(_) => { @@ -123,15 +122,12 @@ impl WorkspaceSet { message: "Organization slug cannot be empty.".to_string(), }); } - None => config - .server - .default_org - .clone() - .ok_or_else(|| CliError::InvalidArgument { - message: "No default org set. Use --org or first run: \ - atomic org set " - .to_string(), - })?, + None => { + let (server, _name) = config + .resolve_server(None) + .map_err(|e| CliError::Internal(anyhow::anyhow!("{e}")))?; + resolve_org_with_server(None, server)? + } }; // Validate against the server first so a bad slug fails fast @@ -142,10 +138,16 @@ impl WorkspaceSet { verify(&target_org, &self.slug)?; } - let previous = config - .server + // Write into the *active* server profile so the default is read back + // by commands that resolve the same profile. + let (server, _profile_name) = config + .resolve_server_mut(None) + .map_err(|e| CliError::Internal(anyhow::anyhow!("{e}")))?; + + let previous = server .default_workspaces .insert(target_org.clone(), self.slug.clone()); + let current_org = server.default_org.clone(); config.save().map_err(|e| { CliError::Internal(anyhow::anyhow!("Failed to save global config: {e}")) @@ -164,7 +166,7 @@ impl WorkspaceSet { // If the user set a workspace for a non-current org, remind them // that it won't take effect until they switch orgs. - if let Some(current_org) = config.server.default_org.as_deref() { + if let Some(current_org) = current_org.as_deref() { if current_org != target_org { print_hint(&format!( "Current default org is '{current_org}' — \ @@ -255,12 +257,16 @@ mod tests { // mutated. Protects against accidentally reordering verify / save in // future refactors. // - // Tests touch HOME to redirect `GlobalConfig::{load,save}` at an - // isolated config dir, so `#[serial]` is required. + // Tests redirect `ATOMIC_CONFIG_DIR` to isolate `GlobalConfig::{load,save}` + // at a tempdir, so `#[serial]` is required. // ----------------------------------------------------------------- use serial_test::serial; + /// Redirect `ATOMIC_CONFIG_DIR` to a tempdir for the lifetime of the guard, + /// isolating `GlobalConfig` from the real user config. `ATOMIC_CONFIG_DIR` + /// (not `HOME`) is used because `atomic_config` resolves its path via that + /// override — `HOME` alone does not isolate on Windows. struct HomeGuard { _tmp: tempfile::TempDir, original: Option, @@ -269,18 +275,12 @@ mod tests { impl HomeGuard { fn new() -> Self { let tmp = tempfile::tempdir().unwrap(); - let original = std::env::var_os("HOME"); - // SAFETY: env mutation is technically UB if accessed - // concurrently from another thread. `#[serial]` serializes - // these tests against each other but does NOT prevent - // unmarked tests elsewhere in the workspace from reading - // HOME concurrently. No other test in this crate currently - // mutates or reads HOME outside its own `#[serial]` block, - // so the race window is empty today. A path-aware - // GlobalConfig API would eliminate this — tracked as a - // follow-up. + let original = std::env::var_os("ATOMIC_CONFIG_DIR"); + // SAFETY: env mutation is technically UB under concurrent access. + // `#[serial]` serializes these tests, and no other test reads + // ATOMIC_CONFIG_DIR outside its own `#[serial]` block. unsafe { - std::env::set_var("HOME", tmp.path()); + std::env::set_var("ATOMIC_CONFIG_DIR", tmp.path()); } Self { _tmp: tmp, @@ -294,8 +294,8 @@ mod tests { // SAFETY: see HomeGuard::new. unsafe { match &self.original { - Some(v) => std::env::set_var("HOME", v), - None => std::env::remove_var("HOME"), + Some(v) => std::env::set_var("ATOMIC_CONFIG_DIR", v), + None => std::env::remove_var("ATOMIC_CONFIG_DIR"), } } } diff --git a/atomic-cli/src/main.rs b/atomic-cli/src/main.rs index c4b529c5..1eadc472 100644 --- a/atomic-cli/src/main.rs +++ b/atomic-cli/src/main.rs @@ -61,6 +61,7 @@ use commands::{ ChangeCmd, Clone, Command, + Completions, Diff, Doctor, Git, @@ -847,6 +848,19 @@ enum Commands { /// atomic update --check /// ``` Update(Update), + + /// Generate a shell completion script. + /// + /// Emits a static completion script for the given shell. For live + /// completion of view names and change hashes, enable the dynamic engine + /// instead with `source <(COMPLETE=zsh atomic)`. + /// + /// # Examples + /// + /// ```text + /// atomic completions zsh > ~/.zfunc/_atomic + /// ``` + Completions(Completions), } // Main Entry Point @@ -855,6 +869,14 @@ fn main() { // Initialize logging env_logger::init(); + // Dynamic shell completion. When invoked in completion mode (the `COMPLETE` + // env var is set by the installed shell hook), this emits candidates — + // including live view names and change hashes registered on the insert + // args — and exits before normal argument parsing. In normal invocations + // it is a no-op. The factory mirrors the real command tree so completion + // matches actual subcommands and aliases. + clap_complete::CompleteEnv::with_factory(|| apply_agent_help(Cli::command())).complete(); + // Parse command-line arguments through the agent-native help layout. // // `try_get_matches_from_mut` rather than `get_matches`: clap's own failure @@ -951,6 +973,8 @@ fn main() { Commands::Update(update) => update.run(), + Commands::Completions(completions) => completions.generate(Cli::command()), + Commands::Query(query) => query.run(), Commands::Vault(vault) => vault.run(), diff --git a/atomic-cli/tests/insert_promote_integration_test.rs b/atomic-cli/tests/insert_promote_integration_test.rs new file mode 100644 index 00000000..0f54fb74 --- /dev/null +++ b/atomic-cli/tests/insert_promote_integration_test.rs @@ -0,0 +1,256 @@ +//! Integration tests for the bare `atomic insert` promotion path, driving the +//! real CLI binary end-to-end against a temporary repository. +//! +//! Bare `atomic insert` (no change hash, no subcommand) inserts the current +//! view's changes into its parent view. These tests exercise the happy path, +//! the dry-run preview, the idempotent "already even" no-op, the root-view +//! guard, and the shared -> shared confirmation gate. + +use std::path::Path; +use std::process::{Command, Output}; + +use tempfile::TempDir; + +/// Path to the compiled `atomic` binary (provided by Cargo to integration tests). +const ATOMIC_BIN: &str = env!("CARGO_BIN_EXE_atomic"); + +/// Run `atomic ` inside `dir`. +fn atomic(dir: &Path, args: &[&str]) -> Output { + Command::new(ATOMIC_BIN) + .args(args) + .current_dir(dir) + .output() + .expect("run atomic") +} + +/// Combined stdout + stderr as a lossy string, for substring assertions. +fn combined(out: &Output) -> String { + let mut s = String::from_utf8_lossy(&out.stdout).into_owned(); + s.push_str(&String::from_utf8_lossy(&out.stderr)); + s +} + +/// Initialize a repo (default view `dev`) with a base file recorded on `dev`. +fn repo_with_base() -> TempDir { + let dir = TempDir::new().expect("tempdir"); + let root = dir.path(); + assert!(atomic(root, &["init"]).status.success(), "init"); + std::fs::write(root.join("base.txt"), b"base\n").unwrap(); + assert!( + atomic(root, &["add", "base.txt"]).status.success(), + "add base" + ); + assert!( + atomic(root, &["record", "-m", "base"]).status.success(), + "record base" + ); + dir +} + +/// Create a draft view `feature` (parent = dev), switch to it, and record a +/// change unique to that view. +fn add_draft_change(root: &Path) { + assert!( + atomic(root, &["view", "create", "feature", "--draft", "--switch"]) + .status + .success(), + "create+switch draft" + ); + std::fs::write(root.join("feature.txt"), b"feature work\n").unwrap(); + assert!( + atomic(root, &["add", "feature.txt"]).status.success(), + "add feature file" + ); + assert!( + atomic(root, &["record", "-m", "feature change"]) + .status + .success(), + "record feature change" + ); +} + +#[test] +fn bare_insert_promotes_draft_into_parent() { + let dir = repo_with_base(); + let root = dir.path(); + add_draft_change(root); + + let out = atomic(root, &["insert"]); + let text = combined(&out); + assert!(out.status.success(), "bare insert should succeed:\n{text}"); + // Direction is shown explicitly, source -> parent. + assert!( + text.contains("feature"), + "should name the source view:\n{text}" + ); + assert!(text.contains("dev"), "should name the parent view:\n{text}"); + assert!( + text.contains("Inserted") && text.contains("change"), + "should report the insert:\n{text}" + ); + + // Running it again is a friendly no-op: nothing left to promote. + let again = atomic(root, &["insert"]); + let again_text = combined(&again); + assert!( + again.status.success(), + "second insert should succeed:\n{again_text}" + ); + assert!( + again_text.to_lowercase().contains("already even") + || again_text.to_lowercase().contains("nothing"), + "second insert should be a no-op:\n{again_text}" + ); +} + +#[test] +fn bare_insert_dry_run_does_not_mutate() { + let dir = repo_with_base(); + let root = dir.path(); + add_draft_change(root); + + let out = atomic(root, &["insert", "-n"]); + let text = combined(&out); + assert!(out.status.success(), "dry-run should succeed:\n{text}"); + assert!( + text.to_lowercase().contains("dry run"), + "should announce a dry run:\n{text}" + ); + + // Nothing was inserted, so a real insert still has work to do. + let real = atomic(root, &["insert"]); + let real_text = combined(&real); + assert!( + real.status.success(), + "real insert after dry-run should succeed:\n{real_text}" + ); + assert!( + real_text.contains("Inserted") && real_text.contains("change"), + "dry-run must not have inserted anything:\n{real_text}" + ); +} + +#[test] +fn bare_insert_on_root_view_errors() { + // Fresh repo sits on `dev`, a root view with no parent. + let dir = repo_with_base(); + let root = dir.path(); + + let out = atomic(root, &["insert"]); + let text = combined(&out); + assert!( + !out.status.success(), + "insert on a root view should fail:\n{text}" + ); + assert!( + text.contains("root view"), + "error should explain there is no parent:\n{text}" + ); +} + +#[test] +fn insert_view_subcommand_and_alias_are_equivalent() { + // `insert view ` and its `from-view` alias both insert the source + // view's changes into the current view. Set up a draft with one change, + // then drive the insert from `dev` (the parent/current view). + for subcmd in ["view", "from-view"] { + let dir = repo_with_base(); + let root = dir.path(); + add_draft_change(root); // creates+switches to `feature` with one change + assert!( + atomic(root, &["view", "switch", "dev"]).status.success(), + "switch back to dev" + ); + + let out = atomic(root, &["insert", subcmd, "feature"]); + let text = combined(&out); + assert!( + out.status.success(), + "insert {subcmd} feature should succeed:\n{text}" + ); + assert!( + text.contains("Inserted") && text.contains("change"), + "insert {subcmd} should report the insert:\n{text}" + ); + // The change's file is now materialized on dev. + assert_eq!( + std::fs::read(root.join("feature.txt")).unwrap(), + b"feature work\n", + "insert {subcmd} should materialize the inserted change on dev" + ); + } +} + +#[test] +fn insert_change_alias_pick_still_parses() { + // The `change` subcommand accepts its `pick` alias. A bogus hash should + // fail at hash resolution (not at argument parsing), proving the alias and + // positional wiring are intact. + let dir = repo_with_base(); + let root = dir.path(); + + let out = atomic(root, &["insert", "pick", "deadbeef"]); + let text = combined(&out); + assert!( + !out.status.success(), + "a nonexistent change should fail:\n{text}" + ); + // Should be a change-resolution error, not an "unrecognized subcommand". + assert!( + !text.to_lowercase().contains("unrecognized") + && !text.to_lowercase().contains("unexpected argument"), + "'pick' alias must be accepted as a subcommand:\n{text}" + ); +} + +#[test] +fn bare_insert_shared_to_shared_requires_confirmation() { + let dir = repo_with_base(); + let root = dir.path(); + + // Create a *shared* view parented on dev and switch to it. + assert!( + atomic( + root, + &["view", "create", "staging", "--parent", "dev", "--switch"] + ) + .status + .success(), + "create shared staging" + ); + std::fs::write(root.join("staging.txt"), b"staging work\n").unwrap(); + assert!( + atomic(root, &["add", "staging.txt"]).status.success(), + "add" + ); + assert!( + atomic(root, &["record", "-m", "staging change"]) + .status + .success(), + "record staging change" + ); + + // Non-interactive (piped stdin): without --confirm this must refuse. + let refused = atomic(root, &["insert"]); + let refused_text = combined(&refused); + assert!( + !refused.status.success(), + "shared->shared insert without --confirm should fail:\n{refused_text}" + ); + assert!( + refused_text.to_lowercase().contains("confirm"), + "error should point at --confirm:\n{refused_text}" + ); + + // With --confirm it proceeds in one line. + let ok = atomic(root, &["insert", "--confirm"]); + let ok_text = combined(&ok); + assert!( + ok.status.success(), + "insert --confirm should succeed:\n{ok_text}" + ); + assert!( + ok_text.contains("Inserted") && ok_text.contains("change"), + "should report the insert:\n{ok_text}" + ); +} diff --git a/atomic-config/src/lib.rs b/atomic-config/src/lib.rs index 89fed49c..6a25da38 100644 --- a/atomic-config/src/lib.rs +++ b/atomic-config/src/lib.rs @@ -296,6 +296,47 @@ impl GlobalConfig { // 3. Legacy [server] block Ok((&self.server, None)) } + + /// Resolve the effective server config mutably, honouring the optional + /// name override. + /// + /// Mirrors the resolution order of [`resolve_server`](Self::resolve_server) + /// so that writes (e.g. `atomic org set`, `atomic workspace set`) land on + /// the same profile that reads resolve to: + /// + /// 1. `server_override` (from `--server ` CLI flag) + /// 2. `default_server` (from `~/.atomic/config.toml`) + /// 3. Legacy `server` block + /// + /// Returns the mutable profile plus its name (`Some` for a named profile, + /// `None` for the legacy block). + pub fn resolve_server_mut( + &mut self, + server_override: Option<&str>, + ) -> Result<(&mut ServerConfig, Option), String> { + // Determine which profile name to target, if any. We resolve the name + // first (immutable borrow) so the mutable borrow below is unambiguous. + let name = if let Some(name) = server_override { + Some(name.to_string()) + } else { + self.default_server.clone() + }; + + match name { + Some(name) => { + let profile = self.servers.get_mut(&name).ok_or_else(|| { + format!( + "Server profile '{}' not found. \ + Use 'atomic server list' to see available profiles, \ + or 'atomic server add {0} ' to create it.", + name + ) + })?; + Ok((profile, Some(name))) + } + None => Ok((&mut self.server, None)), + } + } } /// Color output preference @@ -366,8 +407,29 @@ pub struct RemoteConfig { pub default_channel: Option, } -/// Get the global configuration directory +/// Get the global configuration directory. +/// +/// Resolution order: +/// 1. The `ATOMIC_CONFIG_DIR` environment variable, if set — used verbatim as +/// the config directory (the one containing `config.toml`). This lets tests +/// isolate the global config on every platform, and lets users relocate it. +/// 2. `dirs::home_dir()/.atomic` (the default). +/// +/// The variable is read at call time so it can be set and restored per test +/// (`dirs::home_dir()` on Windows resolves the profile known-folder, not +/// `HOME`, so an env override is the only reliable cross-platform isolation). pub fn global_config_dir() -> Option { + global_config_dir_from(std::env::var_os("ATOMIC_CONFIG_DIR")) +} + +/// Resolve the global config directory from an explicit override value. +/// +/// Split out so the override precedence is unit-testable without mutating +/// process environment (which is racy and platform-sensitive). +fn global_config_dir_from(env_override: Option) -> Option { + if let Some(dir) = env_override { + return Some(PathBuf::from(dir)); + } dirs::home_dir().map(|p| p.join(".atomic")) } @@ -663,6 +725,81 @@ mod tests { ); } + #[test] + fn test_resolve_server_mut_targets_named_profile() { + // default_server points at a named profile → mutation must land there, + // not on the legacy [server] block. + let mut config = GlobalConfig { + default_server: Some("prod".to_string()), + ..GlobalConfig::default() + }; + config.servers.insert( + "prod".to_string(), + ServerConfig { + url: Some("https://atomic.storage".to_string()), + default_org: None, + default_workspaces: BTreeMap::new(), + identity: Some("continuouslee".to_string()), + single_tenant: false, + }, + ); + + let (server, name) = config.resolve_server_mut(None).unwrap(); + assert_eq!(name.as_deref(), Some("prod")); + server.default_org = Some("atomic".to_string()); + + assert_eq!( + config.servers["prod"].default_org.as_deref(), + Some("atomic") + ); + assert!(config.server.default_org.is_none()); + } + + #[test] + fn test_resolve_server_mut_falls_back_to_legacy_block() { + // No default_server and no override → legacy [server] block. + let mut config = GlobalConfig::default(); + + let (server, name) = config.resolve_server_mut(None).unwrap(); + assert!(name.is_none()); + server.default_org = Some("alice".to_string()); + + assert_eq!(config.server.default_org.as_deref(), Some("alice")); + } + + #[test] + fn test_resolve_server_mut_override_wins() { + let mut config = GlobalConfig { + default_server: Some("prod".to_string()), + ..GlobalConfig::default() + }; + config + .servers + .insert("prod".to_string(), ServerConfig::default()); + config + .servers + .insert("staging".to_string(), ServerConfig::default()); + + let (server, name) = config.resolve_server_mut(Some("staging")).unwrap(); + assert_eq!(name.as_deref(), Some("staging")); + server.default_org = Some("staging-org".to_string()); + + assert_eq!( + config.servers["staging"].default_org.as_deref(), + Some("staging-org") + ); + assert!(config.servers["prod"].default_org.is_none()); + } + + #[test] + fn test_resolve_server_mut_missing_profile_errors() { + let mut config = GlobalConfig { + default_server: Some("ghost".to_string()), + ..GlobalConfig::default() + }; + assert!(config.resolve_server_mut(None).is_err()); + } + #[test] fn test_default_workspaces_backward_compatibility() { // Old configs without default_workspaces should still parse. @@ -749,4 +886,27 @@ default_org = "alice" Some("https://alice.atomic.storage") ); } + + #[test] + fn global_config_dir_uses_env_override_verbatim() { + // With the override set, the directory is used exactly as given. + let override_dir = std::ffi::OsString::from("/some/test/config/dir"); + assert_eq!( + global_config_dir_from(Some(override_dir)), + Some(PathBuf::from("/some/test/config/dir")) + ); + } + + #[test] + fn global_config_dir_falls_back_to_home_when_unset() { + // Without the override, it falls back to /.atomic (matching the + // pre-existing behavior). We only assert the `.atomic` suffix so the + // test is host-independent. + if let Some(dir) = global_config_dir_from(None) { + assert!( + dir.ends_with(".atomic"), + "expected /.atomic, got {dir:?}" + ); + } + } } diff --git a/atomic-core/src/pristine/traits/triples.rs b/atomic-core/src/pristine/traits/triples.rs index bb1b5b29..41ebc1e9 100644 --- a/atomic-core/src/pristine/traits/triples.rs +++ b/atomic-core/src/pristine/traits/triples.rs @@ -80,6 +80,14 @@ pub trait KgTxnT { /// Count total nodes in the KG. fn count_kg_nodes(&self) -> Result; + /// Return the IDs of all KG nodes whose `source` field matches one of + /// `sources`. + /// + /// Used to select derived nodes (e.g. `"vcs"` and `"ast"` for the + /// VCS/tree-sitter enrichment pipeline) so a rebuild can drop them before + /// re-deriving, without touching vault- or session-sourced nodes. + fn kg_node_ids_by_source(&self, sources: &[&str]) -> Result, PristineError>; + /// Count total edges in the KG. fn count_kg_edges(&self) -> Result; } diff --git a/atomic-core/src/pristine/txn/read.rs b/atomic-core/src/pristine/txn/read.rs index 0c56af06..0a821cc1 100644 --- a/atomic-core/src/pristine/txn/read.rs +++ b/atomic-core/src/pristine/txn/read.rs @@ -1061,6 +1061,24 @@ impl KgTxnT for ReadTxn { Ok(table.len()? as usize) } + fn kg_node_ids_by_source(&self, sources: &[&str]) -> PristineResult> { + let table = match self.txn.open_table(KG_NODES) { + Ok(t) => t, + Err(redb::TableError::TableDoesNotExist(_)) => return Ok(Vec::new()), + Err(e) => return Err(PristineError::from(e)), + }; + let mut ids = Vec::new(); + for entry in table.iter()? { + let (key, value) = entry?; + if let Ok(node) = serde_json::from_slice::(value.value()) { + if sources.contains(&node.source.as_str()) { + ids.push(key.value().to_string()); + } + } + } + Ok(ids) + } + fn count_kg_edges(&self) -> PristineResult { let table = match self.txn.open_table(KG_EDGES) { Ok(t) => t, diff --git a/atomic-core/src/pristine/txn/write/triples.rs b/atomic-core/src/pristine/txn/write/triples.rs index f0a653c2..3ce9cb18 100644 --- a/atomic-core/src/pristine/txn/write/triples.rs +++ b/atomic-core/src/pristine/txn/write/triples.rs @@ -331,6 +331,24 @@ impl<'a> KgTxnT for WriteTxn<'a> { Ok(table.len()? as usize) } + fn kg_node_ids_by_source(&self, sources: &[&str]) -> PristineResult> { + let table = match self.txn.open_table(KG_NODES) { + Ok(t) => t, + Err(redb::TableError::TableDoesNotExist(_)) => return Ok(Vec::new()), + Err(e) => return Err(PristineError::from(e)), + }; + let mut ids = Vec::new(); + for entry in table.iter()? { + let (key, value) = entry?; + if let Ok(node) = serde_json::from_slice::(value.value()) { + if sources.contains(&node.source.as_str()) { + ids.push(key.value().to_string()); + } + } + } + Ok(ids) + } + fn count_kg_edges(&self) -> PristineResult { let table = match self.txn.open_table(KG_EDGES) { Ok(t) => t, diff --git a/atomic-repository/src/content_search.rs b/atomic-repository/src/content_search.rs index 30bf585a..ab523a03 100644 --- a/atomic-repository/src/content_search.rs +++ b/atomic-repository/src/content_search.rs @@ -6,16 +6,43 @@ use std::path::Path; -use syntext::index::Index; +use syntext::index::{ExternalFileRecord, Index}; use syntext::{Config, IndexError, SearchOptions}; /// Build (or rebuild) the content search index for the repository. /// -/// Indexes all files in the working copy, respecting `.gitignore` and -/// `.atomicignore` patterns. The index is stored at `.atomic/content-index/`. +/// Indexes files in the working copy while respecting `.gitignore`, `.ignore`, +/// `.atomicignore` (and the global ignore file), and skipping Atomic-internal +/// directories (`.atomic`, `.git`, `.vault`). The index is stored at +/// `.atomic/content-index/`. +/// +/// Discovery is owned here rather than delegated to syntext's `Index::build`: +/// syntext's walker respects `.gitignore`/`.ignore` but NOT `.atomicignore`, +/// and it descends into hidden dirs like `.atomic`/`.vault`, so it would index +/// build artifacts, dependencies, and Atomic internals. We reuse syntext's +/// walker (for its symlink resolution and size handling), then drop the paths +/// Atomic excludes before handing the corpus to `build_from_file_records`. pub fn build_content_index(repo_root: &Path) -> Result<(), ContentSearchError> { let config = content_config(repo_root); - let _index = Index::build(config)?; + + let (files, _skips) = syntext::index::walk::enumerate_files(&config)?; + let ignore_rules = crate::ignore::IgnoreRules::load_for_enrichment(repo_root); + let records: Vec = files + .into_iter() + .filter(|(_absolute, relative, _size)| { + !crate::ignore::is_enrichment_internal(relative) + && !ignore_rules.is_ignored(relative, false) + }) + .map( + |(absolute_path, relative_path, size_bytes)| ExternalFileRecord { + absolute_path, + relative_path, + size_bytes, + }, + ) + .collect(); + + let _index = Index::build_from_file_records(config, records)?; Ok(()) } @@ -44,6 +71,73 @@ pub fn notify_and_commit(repo_root: &Path, changed_path: &Path) -> Result<(), Co Ok(()) } +/// Incrementally refresh the content index for a set of repo-relative paths +/// that changed (e.g. the files touched by a recorded change) and persist the +/// result to disk. +/// +/// Each path is re-read from disk: added/modified files are re-indexed and +/// deleted files are removed, keeping the index in sync with the working copy +/// without re-walking the whole tree. Ignored and Atomic-internal paths are +/// skipped so build artifacts, dependencies, and internals never enter the +/// index. +/// +/// syntext's per-file edits land in an in-memory overlay that is not visible to +/// a later `Index::open` (e.g. the next `search` in a fresh process). To make +/// the update durable we `compact()` afterward, folding the overlay into fresh +/// on-disk base segments — cheaper than [`build_content_index`] because +/// unchanged files are reused from existing segments rather than re-read. +/// +/// No-op when the content index does not yet exist — building it is the job of +/// [`build_content_index`]; this only maintains an existing index. +pub fn update_content_index_paths( + repo_root: &Path, + paths: I, +) -> Result<(), ContentSearchError> +where + I: IntoIterator, + P: AsRef, +{ + if !has_content_index(repo_root) { + return Ok(()); + } + + let ignore_rules = crate::ignore::IgnoreRules::load_for_enrichment(repo_root); + let config = content_config(repo_root); + let index = Index::open(config)?; + + let mut any = false; + for path in paths { + let rel = path.as_ref(); + if crate::ignore::is_enrichment_internal(rel) || ignore_rules.is_ignored(rel, false) { + continue; + } + // syntext strips `repo_root` to derive the relative path, so hand it an + // absolute path. The file need not exist — a missing file is treated as + // a deletion and removed from the index. + let absolute = repo_root.join(rel); + index.notify_change(&absolute)?; + any = true; + } + + if !any { + return Ok(()); + } + + // Commit the pending overlay and fold it into on-disk base segments so the + // change survives to the next `Index::open`. When the changed set is large + // relative to the index (syntext caps the overlay at 50% of base docs), + // `compact` reports `OverlayFull`; the sanctioned recovery is a full + // (filtered) rebuild. + match index.compact() { + Ok(()) => Ok(()), + Err(IndexError::OverlayFull { .. }) => { + drop(index); + build_content_index(repo_root) + } + Err(e) => Err(e.into()), + } +} + /// Search the content index. /// /// Returns matching lines with file paths, line numbers, and content. @@ -80,6 +174,23 @@ pub fn search_content( }; let raw_matches = index.search(pattern, &search_opts)?; + + // Drop matches in ignored or Atomic-internal paths. syntext's index walk + // respects `.gitignore`/`.ignore` but NOT `.atomicignore`, and it descends + // into hidden dirs like `.atomic`/`.vault`, so build artifacts and + // dependencies excluded only by `.atomicignore` (plus Atomic internals) + // would otherwise surface here and, via the KG search's content-only file + // promotion, as `file:` results. Filter at this shared consumption point + // so both `query search` and `query code` stay clean regardless of what + // the index contains. + let ignore_rules = crate::ignore::IgnoreRules::load_for_enrichment(repo_root); + let raw_matches: Vec = raw_matches + .into_iter() + .filter(|m| { + !crate::ignore::is_enrichment_internal(&m.path) + && !ignore_rules.is_ignored(&m.path, false) + }) + .collect(); let total_matches = raw_matches.len(); // Build per-directory match counts for the facets summary. @@ -351,3 +462,89 @@ impl From for ContentSearchError { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn search_content_excludes_ignored_and_internal_paths() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + + // A distinctive token present in a source file plus in files that + // must be excluded: a `.atomicignore`'d build dir, a `.atomicignore`'d + // dependency dir (with many files), and `.atomic`/`.vault` internals. + std::fs::create_dir_all(root.join("src")).unwrap(); + std::fs::create_dir_all(root.join("node_modules/dep")).unwrap(); + std::fs::create_dir_all(root.join("dist")).unwrap(); + std::fs::create_dir_all(root.join(".vault")).unwrap(); + std::fs::write(root.join("src/index.ts"), b"const marker = wombatxyz;\n").unwrap(); + for i in 0..20 { + std::fs::write( + root.join(format!("node_modules/dep/lib{i}.js")), + b"var wombatxyz = 1;\n", + ) + .unwrap(); + } + std::fs::write(root.join("dist/index.js"), b"var wombatxyz = 1;\n").unwrap(); + std::fs::write(root.join(".vault/note.md"), b"wombatxyz in vault\n").unwrap(); + std::fs::write(root.join(".atomicignore"), b"node_modules/\ndist/\n").unwrap(); + + build_content_index(root).unwrap(); + + // The index itself must exclude the ignored/internal files: with 20 + // node_modules files plus dist/.vault, an unfiltered build would index + // 20+ docs. A filtered build indexes only the handful of real sources. + let stats = content_index_stats(root).expect("index stats"); + assert!( + stats.total_documents < 10, + "index should exclude ignored/internal files, but indexed {} documents", + stats.total_documents + ); + + let result = search_content(root, "wombatxyz", ContentSearchOptions::default()).unwrap(); + let paths: Vec<&str> = result.matches.iter().map(|m| m.path.as_str()).collect(); + + assert!( + paths.contains(&"src/index.ts"), + "source file should match, got: {paths:?}" + ); + assert!( + !paths.iter().any(|p| p.starts_with("node_modules/")), + ".atomicignore'd dependency must be excluded, got: {paths:?}" + ); + assert!( + !paths.iter().any(|p| p.starts_with("dist/")), + ".atomicignore'd build artifact must be excluded, got: {paths:?}" + ); + assert!( + !paths + .iter() + .any(|p| p.starts_with(".vault/") || p.starts_with(".atomic/")), + "Atomic-internal paths must be excluded, got: {paths:?}" + ); + } + + #[test] + fn update_content_index_paths_persists_new_file() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + std::fs::create_dir_all(root.join("src")).unwrap(); + std::fs::write(root.join("src/a.ts"), b"const alpha = 1;\n").unwrap(); + + build_content_index(root).unwrap(); + + // Add a new file on disk and incrementally update the index. + std::fs::write(root.join("src/b.ts"), b"const betamarker = 2;\n").unwrap(); + update_content_index_paths(root, ["src/b.ts"]).unwrap(); + + // A fresh search (new Index::open) must see the persisted addition. + let result = search_content(root, "betamarker", ContentSearchOptions::default()).unwrap(); + let paths: Vec<&str> = result.matches.iter().map(|m| m.path.as_str()).collect(); + assert!( + paths.contains(&"src/b.ts"), + "incrementally indexed file must be searchable after reopen, got: {paths:?}" + ); + } +} diff --git a/atomic-repository/src/ignore.rs b/atomic-repository/src/ignore.rs index d371b8cd..6bf0d751 100644 --- a/atomic-repository/src/ignore.rs +++ b/atomic-repository/src/ignore.rs @@ -116,6 +116,28 @@ impl IgnoreRules { } } + /// Load ignore rules for knowledge-graph enrichment. + /// + /// Like [`load`](Self::load), but the repository-local rules are built + /// from `.atomicignore`, `.gitignore`, and `.ignore` (in that order, so + /// later files take precedence on conflicting patterns). This lets + /// `atomic query enrich` skip build artifacts and dependencies that those + /// files exclude (e.g. `node_modules/`, `dist/`, `target/`) instead of + /// creating knowledge-graph nodes for them. + /// + /// Only the files at the repository root are consulted; nested ignore + /// files in subdirectories are not (matching the existing `.atomicignore` + /// behavior of [`load`](Self::load)). + pub fn load_for_enrichment(repo_root: &Path) -> Self { + let global = load_global_ignore(); + let local = load_local_enrichment_ignore(repo_root); + Self { + global, + local, + repo_root: repo_root.to_path_buf(), + } + } + /// Create an empty IgnoreRules (ignores nothing except built-in patterns). /// /// This is useful for testing or when you want to start fresh. @@ -365,6 +387,70 @@ fn load_local_ignore(repo_root: &Path) -> Option { } } +/// Load repository-local ignore rules for enrichment from `.atomicignore`, +/// `.gitignore`, and `.ignore` at the repository root. +/// +/// All existing files are merged into a single matcher. Later files take +/// precedence on conflicting patterns (`.atomicignore` < `.gitignore` < +/// `.ignore`), following the `ignore` crate's last-match-wins semantics. +/// Returns `None` when none of the files exist or all fail to parse. +fn load_local_enrichment_ignore(repo_root: &Path) -> Option { + let mut builder = GitignoreBuilder::new(repo_root); + let mut added = false; + + for name in [".atomicignore", ".gitignore", ".ignore"] { + let ignore_path = repo_root.join(name); + if !ignore_path.exists() { + continue; + } + if let Some(err) = builder.add(&ignore_path) { + log::warn!( + "Failed to parse {} at {}: {}", + name, + ignore_path.display(), + err + ); + continue; + } + added = true; + } + + if !added { + return None; + } + + match builder.build() { + Ok(gitignore) => Some(gitignore), + Err(err) => { + log::warn!( + "Failed to build enrichment ignore rules for {}: {}", + repo_root.display(), + err + ); + None + } + } +} + +/// True if `path` lives in an Atomic-internal directory that must never be +/// enriched into the knowledge graph or indexed for content search. +/// +/// Covers the always-ignored `.atomic`/`.git` (shared with `status`) plus +/// `.vault`, which is internal for enrichment/search only: its entries are +/// otherwise tracked content, but they surface as their own semantic KG nodes +/// (`intent:`, `memory:`, `goal:`, `session:`…), so a `file:.vault/…` node or +/// content hit would be pure duplication. `.vault` is deliberately *not* added +/// to the shared `ALWAYS_IGNORED` set because `status`/tracking must keep +/// seeing it. +pub(crate) fn is_enrichment_internal(path: &Path) -> bool { + if crate::status::is_always_ignored(path) { + return true; + } + path.components().any(|component| { + matches!(component, std::path::Component::Normal(name) if name.to_str() == Some(".vault")) + }) +} + /// Get the path to the global ignore file. pub fn global_ignore_path() -> Option { atomic_config::global_config_dir().map(|p| p.join("ignore")) @@ -407,6 +493,45 @@ mod tests { assert!(!rules.is_ignored(Path::new("anything.txt"), false)); } + #[test] + fn test_load_for_enrichment_honors_gitignore_and_ignore() { + let temp = TempDir::new().unwrap(); + std::fs::write(temp.path().join(".atomicignore"), "dist/\n").unwrap(); + std::fs::write(temp.path().join(".gitignore"), "node_modules/\n").unwrap(); + std::fs::write(temp.path().join(".ignore"), "scratch/\n").unwrap(); + + let rules = IgnoreRules::load_for_enrichment(temp.path()); + + // Patterns from all three files are honored. + assert!(rules.is_ignored(Path::new("dist/index.js"), false)); + assert!(rules.is_ignored(Path::new("node_modules/typescript/lib.d.ts"), false)); + assert!(rules.is_ignored(Path::new("scratch/tmp.txt"), false)); + + // Non-matching source files are not ignored. + assert!(!rules.is_ignored(Path::new("src/index.ts"), false)); + } + + #[test] + fn test_load_for_enrichment_ignores_nothing_without_files() { + let temp = TempDir::new().unwrap(); + let rules = IgnoreRules::load_for_enrichment(temp.path()); + + assert!(!rules.has_local_rules()); + assert!(!rules.is_ignored(Path::new("node_modules/pkg/index.js"), false)); + } + + #[test] + fn test_load_for_enrichment_load_does_not_read_gitignore() { + // The general-purpose `load` must remain `.atomicignore`-only so that + // enabling gitignore semantics for enrichment does not silently change + // VCS-wide behavior (status, tracking, switch). + let temp = TempDir::new().unwrap(); + std::fs::write(temp.path().join(".gitignore"), "node_modules/\n").unwrap(); + + let rules = IgnoreRules::load(temp.path()); + assert!(!rules.is_ignored(Path::new("node_modules/pkg/index.js"), false)); + } + #[test] fn test_ignore_rules_basic_patterns() { let temp = TempDir::new().unwrap(); diff --git a/atomic-repository/src/lib.rs b/atomic-repository/src/lib.rs index e723357e..f2d02215 100644 --- a/atomic-repository/src/lib.rs +++ b/atomic-repository/src/lib.rs @@ -128,8 +128,8 @@ pub mod query_plan; // Content search re-exports pub use content_search::{ build_content_index, content_index_stats, has_content_index, search_content, - update_content_index, ContentIndexStats, ContentMatch, ContentSearchError, - ContentSearchOptions, ContentSearchResult, + update_content_index, update_content_index_paths, ContentIndexStats, ContentMatch, + ContentSearchError, ContentSearchOptions, ContentSearchResult, }; // Re-export main types at crate root for convenience diff --git a/atomic-repository/src/repository/record.rs b/atomic-repository/src/repository/record.rs index cb9cc613..3729c3b9 100644 --- a/atomic-repository/src/repository/record.rs +++ b/atomic-repository/src/repository/record.rs @@ -836,12 +836,20 @@ impl Repository { } } - // Auto-enrich KG with the new change (best-effort) + // Auto-update the enrich database (KG + content search index) with the + // new change (best-effort). The content index step is a no-op unless an + // index already exists, so this maintains — never builds — it. if options.get_enrich_kg() && outcome.was_saved() { let hash = *outcome.hash(); if let Err(e) = self.kg_enrich_change(&hash) { log::debug!("KG enrich for change: {}", e); } + if let Err(e) = crate::content_search::update_content_index_paths( + self.root(), + outcome.recorded_files(), + ) { + log::debug!("content index update for change: {}", e); + } } if trace_record { diff --git a/atomic-repository/src/repository/vault_kg_enrich.rs b/atomic-repository/src/repository/vault_kg_enrich.rs index 18fe9f74..b88139c9 100644 --- a/atomic-repository/src/repository/vault_kg_enrich.rs +++ b/atomic-repository/src/repository/vault_kg_enrich.rs @@ -13,9 +13,29 @@ use std::collections::{HashMap, HashSet}; use super::*; use atomic_core::pristine::ontology::edge_kind; use atomic_core::pristine::vault::{KgEdge, KgNode}; -use atomic_core::pristine::KgMutTxnT; +use atomic_core::pristine::{KgMutTxnT, KgTxnT}; use atomic_core::types::Base32; +/// KG node `source` values produced by the VCS/tree-sitter enrichment +/// pipeline. Nodes with these sources are fully regenerated by +/// [`Repository::kg_enrich_from_vcs`] and its phases, so a rebuild can safely +/// drop and re-derive them. Vault- and session-sourced nodes use other +/// `source` values and are never touched by enrichment. +const DERIVED_KG_SOURCES: &[&str] = &["vcs", "ast"]; + +/// True if `path` must be excluded from KG enrichment: an Atomic-internal +/// path (see [`crate::ignore::is_enrichment_internal`]) or one matched by the +/// enrichment ignore rules (`.atomicignore`, `.gitignore`, `.ignore`, global). +/// +/// `rules` is a preloaded [`IgnoreRules::load_for_enrichment`] matcher so +/// callers can reuse it across many paths. Paths are treated as files; +/// directory-only ignore patterns (e.g. `node_modules/`) still match via the +/// crate's parent-directory matching. +fn is_path_ignored_for_enrichment(path: &str, rules: &IgnoreRules) -> bool { + let p = std::path::Path::new(path); + crate::ignore::is_enrichment_internal(p) || rules.is_ignored(p, false) +} + impl Repository { /// Enrich the KG from all VCS data (views, changes, files, deps). /// @@ -56,6 +76,62 @@ impl Repository { Ok(stats) } + /// List tracked files eligible for knowledge-graph enrichment. + /// + /// Filters [`list_tracked_files`](Self::list_tracked_files) to exclude: + /// - Atomic/Git internal directories (`.atomic`, `.git`), and + /// - paths matched by `.atomicignore`, `.gitignore`, `.ignore`, or the + /// global ignore file. + /// + /// This keeps build artifacts and dependencies (e.g. `node_modules/`, + /// `dist/`, `target/`) out of the KG so `atomic query enrich` indexes + /// only meaningful source files. + fn list_enrichable_files(&self) -> Result, RepositoryError> { + let files = self.list_tracked_files()?; + let rules = IgnoreRules::load_for_enrichment(&self.root); + + Ok(files + .into_iter() + .filter(|file| { + !crate::ignore::is_enrichment_internal(&file.path) + && !rules.is_ignored(&file.path, file.is_directory) + }) + .collect()) + } + + /// Remove all knowledge-graph nodes (and their edges) derived from VCS + /// data and tree-sitter parsing. + /// + /// Clears `file:`, `module:`, `view:`, `change:`, `identity:`, and + /// `entity:` nodes (those whose `source` is in `DERIVED_KG_SOURCES`) so + /// a subsequent full enrich rebuilds the graph from scratch, dropping + /// entries that no longer apply — e.g. files that became ignored or were + /// deleted. Vault- and session-sourced nodes (intents, memories, goals, + /// sessions, todos) are left untouched. + /// + /// Returns the number of nodes removed. + pub fn kg_clear_derived(&self) -> Result { + let mut txn = self + .pristine + .write_txn() + .map_err(|e| RepositoryError::Database(e.to_string()))?; + txn.init_kg() + .map_err(|e| RepositoryError::Database(e.to_string()))?; + + let ids = txn + .kg_node_ids_by_source(DERIVED_KG_SOURCES) + .map_err(|e| RepositoryError::Database(e.to_string()))?; + + for id in &ids { + txn.del_kg_node(id) + .map_err(|e| RepositoryError::Database(e.to_string()))?; + } + + txn.commit() + .map_err(|e| RepositoryError::Database(e.to_string()))?; + Ok(ids.len()) + } + /// Enrich the KG with view hierarchy data. /// /// For each view in the repository, creates a `view:{name}` node and @@ -123,9 +199,7 @@ impl Repository { /// file → module and module → parent module (only between modules that /// were created, not every intermediate directory). pub fn kg_enrich_modules(&self) -> Result { - let files = self - .list_tracked_files() - .map_err(|e| RepositoryError::Database(e.to_string()))?; + let files = self.list_enrichable_files()?; // Collect directories that directly contain at least one file. let mut dirs_with_files: HashSet = HashSet::new(); @@ -201,9 +275,7 @@ impl Repository { /// /// Creates a `file:{path}` node for each file tracked in the repository. pub fn kg_enrich_files(&self) -> Result { - let files = self - .list_tracked_files() - .map_err(|e| RepositoryError::Database(e.to_string()))?; + let files = self.list_enrichable_files()?; let mut txn = self .pristine @@ -247,6 +319,7 @@ impl Repository { } let view_name = self.current_view().to_string(); + let ignore_rules = IgnoreRules::load_for_enrichment(&self.root); let mut txn = self .pristine @@ -339,6 +412,12 @@ impl Repository { if path.is_empty() { continue; } + // Skip ignored paths so build artifacts and + // dependencies recorded in a change do not reappear + // as `file:` nodes. + if is_path_ignored_for_enrichment(path, &ignore_rules) { + continue; + } let file_label = path.rsplit('/').next().unwrap_or(path); let file_node = KgNode::new(format!("file:{}", path), "file", file_label, "vcs"); @@ -439,12 +518,19 @@ impl Repository { } // File modification edges from FileOps + let ignore_rules = IgnoreRules::load_for_enrichment(&self.root); let mut file_paths = Vec::new(); for file_op in change.file_ops() { let path = file_op.path(); if path.is_empty() { continue; } + // Skip ignored paths so build artifacts and dependencies recorded + // in the change do not reappear as `file:` nodes (or get parsed + // for AST entities below). + if is_path_ignored_for_enrichment(path, &ignore_rules) { + continue; + } file_paths.push(path.to_string()); let file_label = path.rsplit('/').next().unwrap_or(path); let file_node = KgNode::new(format!("file:{}", path), "file", file_label, "vcs"); @@ -536,6 +622,52 @@ impl Repository { Ok(()) } + /// Update the enrich database for a single recorded change. + /// + /// This is the incremental "keep the enrich database current" entry point + /// used after a change is recorded (by `record()` when `enrich_kg` is set, + /// and by `atomic query enrich --change `): + /// + /// 1. Adds the change's KG nodes and edges via + /// [`kg_enrich_change`](Self::kg_enrich_change). + /// 2. Incrementally refreshes the content search index for the files the + /// change touched (added/modified files re-indexed, deleted files + /// removed), skipping ignored and Atomic-internal paths. + /// + /// The content-index step is best-effort and a no-op when no content index + /// exists yet — building it is the job of `atomic query enrich`/`index`; + /// this only maintains an index that already exists. + pub fn enrich_change(&self, hash: &Hash) -> Result<(), RepositoryError> { + self.kg_enrich_change(hash)?; + + // Collect the paths this change touched for an incremental content + // index refresh. Best-effort: a load failure just skips the content + // step (the KG is already updated above). + let paths: Vec = match self.load_change(hash) { + Ok(change) => change + .file_ops() + .iter() + .map(|op| op.path().to_string()) + .filter(|path| !path.is_empty()) + .collect(), + Err(e) => { + log::debug!( + "enrich_change: could not load change for content index: {}", + e + ); + Vec::new() + } + }; + + if !paths.is_empty() { + if let Err(e) = crate::content_search::update_content_index_paths(self.root(), &paths) { + log::debug!("enrich_change: content index update failed: {}", e); + } + } + + Ok(()) + } + /// Enrich the KG with AST entities from tracked files. /// /// Enrich the KG with `INCLUDES` edges derived from import entities. @@ -545,9 +677,7 @@ impl Repository { /// If a match is found, creates an `INCLUDES` edge from the source file /// to the included file. Best-effort — unresolvable imports are skipped. pub fn kg_enrich_includes(&self) -> Result { - let files = self - .list_tracked_files() - .map_err(|e| RepositoryError::Database(e.to_string()))?; + let files = self.list_enrichable_files()?; // Build a lookup set of tracked file paths for resolution. let tracked_paths: HashSet = files @@ -674,9 +804,7 @@ impl Repository { /// Callee resolution is name-based: a call to `foo()` matches any entity named `foo` /// across all tracked files. Calls to external crates / stdlib are silently skipped. pub fn kg_enrich_calls(&self) -> Result { - let files = self - .list_tracked_files() - .map_err(|e| RepositoryError::Database(e.to_string()))?; + let files = self.list_enrichable_files()?; let mut parser_registry = atomic_semantic::ParserRegistry::new(); @@ -810,9 +938,7 @@ impl Repository { /// the corresponding file nodes. Runs during bulk enrichment /// (`atomic vault query enrich`, `atomic git import`). pub fn kg_enrich_entities(&self) -> Result { - let files = self - .list_tracked_files() - .map_err(|e| RepositoryError::Database(e.to_string()))?; + let files = self.list_enrichable_files()?; let mut parser_registry = atomic_semantic::ParserRegistry::new(); let mut count = 0; @@ -1039,4 +1165,189 @@ mod tests { assert_eq!(node.kind, "view"); assert_eq!(node.source, "vcs"); } + + #[test] + fn test_kg_clear_derived_removes_vcs_and_ast_but_keeps_vault() { + use atomic_core::pristine::vault::KgNode; + use atomic_core::pristine::KgMutTxnT; + + let dir = tempfile::tempdir().unwrap(); + let repo = Repository::init(dir.path()).unwrap(); + repo.init_kg().unwrap(); + + { + let mut txn = repo.pristine.write_txn().unwrap(); + txn.init_kg().unwrap(); + txn.upsert_kg_node(&KgNode::new("file:src/a.ts", "file", "a.ts", "vcs")) + .unwrap(); + txn.upsert_kg_node(&KgNode::new( + "entity:src/a.ts:foo:1", + "entity", + "foo", + "ast", + )) + .unwrap(); + txn.upsert_kg_node(&KgNode::new("memory:keep", "memory", "keep", "vault")) + .unwrap(); + txn.commit().unwrap(); + } + + let removed = repo.kg_clear_derived().unwrap(); + assert_eq!(removed, 2, "both the vcs and ast nodes should be removed"); + + assert!(repo.vault_kg_node("file:src/a.ts").unwrap().is_none()); + assert!(repo + .vault_kg_node("entity:src/a.ts:foo:1") + .unwrap() + .is_none()); + assert!( + repo.vault_kg_node("memory:keep").unwrap().is_some(), + "vault-sourced nodes must survive a derived-node clear" + ); + } + + #[test] + fn test_kg_enrich_files_skips_ignored_paths() { + use crate::tracking::TrackingOptions; + + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + + // Source file (should be enriched) plus build artifacts, a dependency + // directory, and a `.vault` entry that must all be excluded. + std::fs::create_dir_all(root.join("src")).unwrap(); + std::fs::create_dir_all(root.join("node_modules/typescript")).unwrap(); + std::fs::create_dir_all(root.join("dist")).unwrap(); + std::fs::create_dir_all(root.join(".vault/intents/x")).unwrap(); + std::fs::write(root.join("src/index.ts"), b"export const x = 1;\n").unwrap(); + std::fs::write( + root.join("node_modules/typescript/lib.d.ts"), + b"declare var y;\n", + ) + .unwrap(); + std::fs::write(root.join("dist/index.js"), b"var x = 1;\n").unwrap(); + std::fs::write(root.join(".vault/intents/x/intent.md"), b"# intent\n").unwrap(); + + // Ignore files: node_modules via .gitignore, dist via .atomicignore. + std::fs::write(root.join(".gitignore"), b"node_modules/\n").unwrap(); + std::fs::write(root.join(".atomicignore"), b"dist/\n").unwrap(); + + let repo = Repository::init(root).unwrap(); + repo.init_kg().unwrap(); + + // Track everything on disk. `add` itself only consults `.atomicignore`, + // so node_modules still lands in the tree — enrichment must be the + // layer that filters it out. + repo.add(".", TrackingOptions::default()).unwrap(); + + repo.kg_enrich_files().unwrap(); + + assert!( + repo.vault_kg_node("file:src/index.ts").unwrap().is_some(), + "source file should be enriched" + ); + assert!( + repo.vault_kg_node("file:node_modules/typescript/lib.d.ts") + .unwrap() + .is_none(), + ".gitignore'd dependency file should not be enriched" + ); + assert!( + repo.vault_kg_node("file:dist/index.js").unwrap().is_none(), + ".atomicignore'd build artifact should not be enriched" + ); + assert!( + repo.vault_kg_node("file:.vault/intents/x/intent.md") + .unwrap() + .is_none(), + ".vault entries must not become file nodes (they have semantic nodes)" + ); + } + + #[test] + fn test_kg_enrich_changes_skips_ignored_paths() { + use crate::record::RecordOptions; + use crate::tracking::TrackingOptions; + use atomic_core::change::ChangeHeader; + + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + + std::fs::create_dir_all(root.join("src")).unwrap(); + std::fs::create_dir_all(root.join("node_modules")).unwrap(); + std::fs::write(root.join("src/index.ts"), b"export const x = 1;\n").unwrap(); + std::fs::write(root.join("node_modules/dep.js"), b"var d = 1;\n").unwrap(); + std::fs::write(root.join(".gitignore"), b"node_modules/\n").unwrap(); + + let repo = Repository::init(root).unwrap(); + repo.init_kg().unwrap(); + repo.add(".", TrackingOptions::default()).unwrap(); + repo.record( + ChangeHeader::builder().message("init").build(), + RecordOptions::new().enrich_kg(false), + ) + .unwrap(); + + // Change enrichment builds `file:` nodes from the change's file_ops. + // Ignored paths recorded in the change must still be filtered out. + repo.kg_enrich_changes().unwrap(); + + assert!( + repo.vault_kg_node("file:src/index.ts").unwrap().is_some(), + "source file modified by the change should be enriched" + ); + assert!( + repo.vault_kg_node("file:node_modules/dep.js") + .unwrap() + .is_none(), + ".gitignore'd file recorded in a change must not reappear as a file node" + ); + } + + #[test] + fn test_record_updates_content_index_incrementally() { + use crate::record::RecordOptions; + use crate::tracking::TrackingOptions; + use atomic_core::change::ChangeHeader; + + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + std::fs::create_dir_all(root.join("src")).unwrap(); + std::fs::write(root.join("src/a.ts"), b"const alpha = 1;\n").unwrap(); + + let repo = Repository::init(root).unwrap(); + repo.init_kg().unwrap(); + repo.add(".", TrackingOptions::default()).unwrap(); + repo.record( + ChangeHeader::builder().message("init").build(), + RecordOptions::new().with_all(true), + ) + .unwrap(); + + // Build the content index over the current working copy (indexes a.ts). + crate::content_search::build_content_index(root).unwrap(); + + // A newly recorded file must become searchable WITHOUT an explicit + // rebuild: record() (enrich_kg defaults on) refreshes the index for the + // change's paths. + std::fs::write(root.join("src/b.ts"), b"const betamarker = 2;\n").unwrap(); + repo.add(".", TrackingOptions::default()).unwrap(); + repo.record( + ChangeHeader::builder().message("add b").build(), + RecordOptions::new().with_all(true), + ) + .unwrap(); + + let result = crate::content_search::search_content( + root, + "betamarker", + crate::content_search::ContentSearchOptions::default(), + ) + .unwrap(); + let paths: Vec<&str> = result.matches.iter().map(|m| m.path.as_str()).collect(); + assert!( + paths.contains(&"src/b.ts"), + "newly recorded file should be searchable without a manual rebuild, got: {paths:?}" + ); + } } diff --git a/atomic-repository/src/repository/vault_triples.rs b/atomic-repository/src/repository/vault_triples.rs index c99a1376..6d35fdd9 100644 --- a/atomic-repository/src/repository/vault_triples.rs +++ b/atomic-repository/src/repository/vault_triples.rs @@ -2446,6 +2446,56 @@ first assert_eq!(memories[0].id, "memory:authentication"); } + #[test] + fn test_kg_search_generous_pool_surfaces_mixed_kinds() { + // Regression test: with a generous candidate pool the diversity-aware + // selection must surface lower-scored vault kinds (e.g. memory) + // alongside high-scored files, instead of returning only files. This + // mirrors the CLI default search path, which passes a large pool so an + // enriched repo does not collapse to file-only results. + let dir = tempdir().unwrap(); + let repo = Repository::init(dir.path()).unwrap(); + repo.init_vault().unwrap(); + + let files: Vec = (0..20) + .map(|index| { + KgNode::new( + format!("file:src/authentication-{index}.rs"), + "file", + format!("authentication-{index}.rs"), + "test", + ) + }) + .collect(); + let mut txn = repo.pristine.write_txn().unwrap(); + txn.init_kg().unwrap(); + for node in &files { + txn.upsert_kg_node(node).unwrap(); + } + txn.commit().unwrap(); + repo.vault_store( + "memory/authentication.md", + VaultEntryType::Memory, + b"Current authentication decision".to_vec(), + r#"{"name":"authentication","status":"active"}"#.to_string(), + ) + .unwrap(); + + // pool > limit engages diversity-aware selection. + let mixed = repo + .vault_kg_search("authentication", 5, Some(5000)) + .unwrap(); + assert!( + mixed.iter().any(|node| node.kind == "memory"), + "a generous pool should surface the memory node alongside files, got: {:?}", + mixed.iter().map(|n| &n.id).collect::>() + ); + assert!( + mixed.iter().any(|node| node.kind == "file"), + "file nodes should still appear in the mixed results" + ); + } + #[test] fn test_kg_search_by_kind_rejects_legacy_stale_postings() { let dir = tempdir().unwrap();