Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(cli): honor effective config in status and configuration management (#5551)

Zayn Jarvis914ee57d8eb9
diff --git a/crates/ov_cli/src/config.rs b/crates/ov_cli/src/config.rs
index b48fb03dd..f4e4de479 100644
--- a/crates/ov_cli/src/config.rs
+++ b/crates/ov_cli/src/config.rs
@@ -266,26 +266,11 @@ impl Config {
}
pub fn load_required() -> Result<Self> {
- // Resolution order: env var > default path
- if let Ok(env_path) = std::env::var(OPENVIKING_CLI_CONFIG_ENV) {
- return Self::load_required_from_path(&PathBuf::from(env_path));
- }
-
- let config_path = default_config_path()?;
- Self::load_required_from_path(&config_path)
+ Self::load_required_from_path(&effective_config_path()?)
}
pub fn load_default() -> Result<Self> {
- // Resolution order: env var > default path
- if let Ok(env_path) = std::env::var(OPENVIKING_CLI_CONFIG_ENV) {
- let p = PathBuf::from(env_path);
- if p.exists() {
- return Self::from_file(&p.to_string_lossy());
- }
- }
-
- let config_path = default_config_path()?;
- Self::load_default_from_path(&config_path)
+ Self::load_default_from_path(&effective_config_path()?)
}
pub fn load_required_from_path(path: &Path) -> Result<Self> {
@@ -314,7 +299,7 @@ impl Config {
}
pub fn save_default(&self) -> Result<()> {
- let config_path = default_config_path()?;
+ let config_path = effective_config_path()?;
if let Some(parent) = config_path.parent() {
std::fs::create_dir_all(parent)
.map_err(|e| Error::Config(format!("Failed to create config directory: {}", e)))?;
@@ -412,6 +397,18 @@ impl Config {
}
}
+/// Resolve the file used by both requests and configuration management.
+/// An explicit path stays selected even when it does not exist yet.
+pub fn effective_config_path() -> Result<PathBuf> {
+ match std::env::var_os(OPENVIKING_CLI_CONFIG_ENV) {
+ Some(path) if !path.is_empty() => Ok(PathBuf::from(path)),
+ Some(_) => Err(Error::Config(format!(
+ "{OPENVIKING_CLI_CONFIG_ENV} must not be empty"
+ ))),
+ None => default_config_path(),
+ }
+}
+
pub fn default_config_path() -> Result<PathBuf> {
let home = dirs::home_dir()
.ok_or_else(|| Error::Config("Could not determine home directory".to_string()))?;
@@ -419,9 +416,15 @@ pub fn default_config_path() -> Result<PathBuf> {
}
pub fn display_config_home() -> String {
- let path = default_config_path()
- .ok()
- .and_then(|path| path.parent().map(|parent| parent.to_path_buf()));
+ let path = effective_config_path().ok().and_then(|path| {
+ path.parent().map(|parent| {
+ if parent.as_os_str().is_empty() {
+ PathBuf::from(".")
+ } else {
+ parent.to_path_buf()
+ }
+ })
+ });
let Some(path) = path else {
return "~/.openviking".to_string();
};
diff --git a/crates/ov_cli/src/config_agent.rs b/crates/ov_cli/src/config_agent.rs
index edefe9f30..1030cdb81 100644
--- a/crates/ov_cli/src/config_agent.rs
+++ b/crates/ov_cli/src/config_agent.rs
@@ -209,6 +209,12 @@ fn delete_saved_config(store: &ConfigStore, args: ConfigDeleteArgs) -> AgentResu
}));
}
+ if store.selected_config_name() == Some(args.name.as_str()) {
+ return Err(AgentError::refused(
+ "Cannot delete the file selected by OPENVIKING_CLI_CONFIG_FILE. Change the environment variable first.",
+ ));
+ }
+
match store.load_saved_config(&args.name) {
Ok(_) => {
if store
@@ -675,6 +681,11 @@ fn save_edited_config(
) -> AgentResult<AddEditResult> {
let old_config = store.load_saved_config(old_name).map_err(config_error)?;
let renamed = old_name != new_name;
+ if renamed && store.selected_config_name() == Some(old_name) {
+ return Err(AgentError::refused(
+ "Cannot rename the file selected by OPENVIKING_CLI_CONFIG_FILE. Change the environment variable first.",
+ ));
+ }
let new_path = store.saved_config_path(new_name).map_err(config_error)?;
if renamed && new_path.exists() {
let existing_new = store.load_saved_config(new_name).map_err(config_error)?;
diff --git a/crates/ov_cli/src/config_wizard/store.rs b/crates/ov_cli/src/config_wizard/store.rs
index 905d53158..be030ef40 100644
--- a/crates/ov_cli/src/config_wizard/store.rs
+++ b/crates/ov_cli/src/config_wizard/store.rs
@@ -9,7 +9,7 @@ use url::Url;
use crate::{
base_client::BaseClient,
- config::{Config, DEFAULT_CUSTOM_PORT, KNOWN_CONFIG_KEYS, default_config_path},
+ config::{Config, DEFAULT_CUSTOM_PORT, KNOWN_CONFIG_KEYS, effective_config_path},
error::{Error, Result},
};
@@ -96,10 +96,14 @@ pub struct ConfigStore {
impl ConfigStore {
pub fn new() -> Result<Self> {
- let active_path = default_config_path()?;
+ Self::for_active_path(effective_config_path()?)
+ }
+
+ fn for_active_path(active_path: PathBuf) -> Result<Self> {
let config_dir = active_path
.parent()
- .ok_or_else(|| Error::Config("Could not determine config directory".to_string()))?
+ .filter(|parent| !parent.as_os_str().is_empty())
+ .unwrap_or_else(|| Path::new("."))
.to_path_buf();
Ok(Self {
config_dir,
@@ -213,6 +217,12 @@ impl ConfigStore {
configs.sort_by(|left, right| left.name.cmp(&right.name));
invalid_configs.sort_by(|left, right| left.name.cmp(&right.name));
+ // A directly selected named file wins over an alphabetically earlier copy.
+ if let Some(selected) = self.selected_config_name() {
+ for entry in &mut configs {
+ entry.is_active = entry.name == selected;
+ }
+ }
normalize_active_config(&mut configs);
Ok(ConfigListReport {
configs,
@@ -263,6 +273,11 @@ impl ConfigStore {
) -> Result<()> {
let old_path = self.saved_config_path(old_name)?;
let new_path = self.saved_config_path(new_name)?;
+ if old_name != new_name && self.selected_config_name() == Some(old_name) {
+ return Err(Error::Config(
+ "Cannot rename the file selected by OPENVIKING_CLI_CONFIG_FILE. Change the environment variable first.".to_string(),
+ ));
+ }
let was_active = self.is_config_name_active(old_name)?;
if old_name != new_name && new_path.exists() {
@@ -297,7 +312,19 @@ impl ConfigStore {
.map_err(|e| Error::Config(format!("Failed to delete config '{name}': {e}")))
}
+ pub(crate) fn selected_config_name(&self) -> Option<&str> {
+ let name = self
+ .active_path
+ .file_name()?
+ .to_str()?
+ .strip_prefix("ovcli.conf.")?;
+ (name != "bak" && validate_config_name(name).is_ok()).then_some(name)
+ }
+
pub fn is_config_name_active(&self, name: &str) -> Result<bool> {
+ if let Some(selected) = self.selected_config_name() {
+ return Ok(name == selected);
+ }
let Some(active_config) = self.load_active()? else {
return Ok(false);
};
@@ -837,6 +864,64 @@ mod tests {
std::env::temp_dir().join(format!("openviking-config-{name}-{suffix}"))
}
+ #[test]
+ fn selected_named_file_wins_over_equivalent_profiles_and_is_protected() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("ovcli.conf.z");
+ let store = ConfigStore::for_active_path(path.clone()).unwrap();
+ let config = sample_config("http://selected", None);
+ store.save_named_config("a", &config).unwrap();
+ store.save_named_config("z", &config).unwrap();
+ fs::write(dir.path().join("ovcli.conf"), r#"{"url":"http://default"}"#).unwrap();
+ let entries = store.list_configs().unwrap();
+ assert_eq!(
+ entries.iter().find(|entry| entry.is_active).unwrap().name,
+ "z"
+ );
+ assert_eq!(store.load_active().unwrap().unwrap().url, "http://selected");
+ assert!(store.delete_config("z").is_err());
+ assert!(store.save_edited_config("z", "renamed", &config).is_err());
+ assert!(path.exists());
+ store.delete_config("a").unwrap();
+ store
+ .save_active_config(&sample_config("http://edited", None))
+ .unwrap();
+ assert_eq!(
+ Config::from_file(path.to_str().unwrap()).unwrap().url,
+ "http://edited"
+ );
+ assert_eq!(
+ Config::from_file(dir.path().join("ovcli.conf").to_str().unwrap())
+ .unwrap()
+ .url,
+ "http://default"
+ );
+ }
+
+ #[test]
+ fn switching_updates_the_override_without_touching_default_config() {
+ let dir = tempfile::tempdir().unwrap();
+ let default = dir.path().join("ovcli.conf");
+ fs::write(&default, r#"{"url":"http://default"}"#).unwrap();
+ let store = ConfigStore::for_active_path(dir.path().join("custom.json")).unwrap();
+ store
+ .save_named_config("next", &sample_config("http://next", None))
+ .unwrap();
+ store.activate_config("next").unwrap();
+ assert_eq!(store.load_active().unwrap().unwrap().url, "http://next");
+ assert_eq!(
+ Config::from_file(default.to_str().unwrap()).unwrap().url,
+ "http://default"
+ );
+ }
+
+ #[test]
+ fn relative_override_uses_current_directory_for_profiles() {
+ let store = ConfigStore::for_active_path(PathBuf::from("custom.json")).unwrap();
+ assert_eq!(store.config_dir(), Path::new("."));
+ assert_eq!(store.active_path(), Path::new("custom.json"));
+ }
+
fn sample_config(url: &str, api_key: Option<&str>) -> Config {
let mut config = Config::default();
config.url = url.to_string();
diff --git a/crates/ov_cli/tests/config_override.rs b/crates/ov_cli/tests/config_override.rs
new file mode 100644
index 000000000..125b5483d
--- /dev/null
+++ b/crates/ov_cli/tests/config_override.rs
@@ -0,0 +1,102 @@
+//! Run each override in its own process: never mutate the test runner's environment.
+use serde_json::{Value, json};
+use std::{
+ fs,
+ process::{Command, Output, Stdio},
+};
+
+fn run(dir: &std::path::Path, selected: &str, args: &[&str]) -> Output {
+ Command::new(env!("CARGO_BIN_EXE_ov"))
+ .current_dir(dir)
+ .env("OPENVIKING_CLI_CONFIG_FILE", selected)
+ .env("OPENVIKING_LANG", "en")
+ .env("NO_COLOR", "1")
+ .stdin(Stdio::null())
+ .args(args)
+ .output()
+ .unwrap()
+}
+
+fn seed(dir: &std::path::Path, name: &str, url: &str) {
+ fs::write(
+ dir.join(name),
+ json!({"url": url, "output": "table"}).to_string(),
+ )
+ .unwrap();
+}
+
+#[test]
+fn status_and_config_list_identify_the_selected_file() {
+ let dir = tempfile::tempdir().unwrap();
+ seed(dir.path(), "ovcli.conf", "http://default.invalid");
+ seed(dir.path(), "ovcli.conf.aaa", "http://127.0.0.1:9");
+ seed(dir.path(), "ovcli.conf.selected", "http://127.0.0.1:9");
+ let selected = dir.path().join("ovcli.conf.selected");
+ let result = run(dir.path(), selected.to_str().unwrap(), &["status"]);
+ let text = String::from_utf8_lossy(&result.stdout);
+ assert!(result.status.success(), "{result:?}");
+ assert!(text.contains("selected"), "{text}");
+ assert!(text.contains("127.0.0.1:9"), "{text}");
+ assert!(text.contains(dir.path().to_str().unwrap()), "{text}");
+ assert!(!text.contains("default.invalid"), "{text}");
+ let result = run(
+ dir.path(),
+ "ovcli.conf.selected",
+ &["config", "list", "-o", "json"],
+ );
+ assert!(result.status.success(), "{result:?}");
+ let data: Value = serde_json::from_slice(&result.stdout).unwrap();
+ let entries = data["result"].as_array().unwrap();
+ assert_eq!(entries.iter().filter(|e| e["active"] == true).count(), 1);
+ assert!(
+ entries
+ .iter()
+ .any(|e| e["name"] == "selected" && e["active"] == true)
+ );
+}
+
+#[test]
+fn missing_override_never_loads_another_profile() {
+ let dir = tempfile::tempdir().unwrap();
+ seed(dir.path(), "ovcli.conf", "http://default.invalid");
+ let result = run(dir.path(), "missing.json", &["config", "show"]);
+ assert!(!result.status.success());
+ assert!(!String::from_utf8_lossy(&result.stdout).contains("default.invalid"));
+ let result = run(dir.path(), "missing.json", &["status"]);
+ assert!(!result.status.success());
+}
+
+#[test]
+fn empty_override_is_rejected() {
+ let dir = tempfile::tempdir().unwrap();
+ let result = run(dir.path(), "", &["config", "list"]);
+ assert!(!result.status.success());
+ assert!(String::from_utf8_lossy(&result.stderr).contains("must not be empty"));
+}
+
+#[test]
+fn connected_status_uses_the_same_profile_as_the_request() {
+ use std::io::{Read, Write};
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ let server = std::thread::spawn(move || {
+ let (mut stream, _) = listener.accept().unwrap();
+ stream
+ .set_read_timeout(Some(std::time::Duration::from_secs(5)))
+ .unwrap();
+ let mut request = [0; 4096];
+ let len = stream.read(&mut request).unwrap();
+ assert!(String::from_utf8_lossy(&request[..len]).contains("GET /api/v1/observer/system"));
+ let body = r#"{"status":"ok","result":{}}"#;
+ write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", body.len(), body).unwrap();
+ });
+ let dir = tempfile::tempdir().unwrap();
+ seed(dir.path(), "ovcli.conf", "http://default.invalid");
+ seed(dir.path(), "ovcli.conf.selected", &url);
+ let result = run(dir.path(), "ovcli.conf.selected", &["status"]);
+ server.join().unwrap();
+ assert!(result.status.success(), "{result:?}");
+ let text = String::from_utf8_lossy(&result.stdout);
+ assert!(text.contains("selected") && text.contains(&url), "{text}");
+ assert!(!text.contains("Unreachable"), "{text}");
+}
diff --git a/docs/en/configuration/02-client.md b/docs/en/configuration/02-client.md
index e123f9332..bee2d0866 100644
--- a/docs/en/configuration/02-client.md
+++ b/docs/en/configuration/02-client.md
@@ -327,7 +327,7 @@ Normal `ov` commands, plus `ov config show` and `ov config validate`, resolve th
~/.openviking/ovcli.conf
```
-The interactive manager and `ov config list`, `switch`, `add`, `edit`, and `delete` always manage the default store. Named configurations in that store live next to the default active file:
+The interactive manager and `ov config list`, `switch`, `add`, `edit`, and `delete` use the same effective path. Named configurations live next to that active file. Without an override, their paths are:
```text
~/.openviking/ovcli.conf.<name>
@@ -353,6 +353,6 @@ ov config validate
ov config show
```
-`ov config switch <name>` copies the named configuration to the default active file. If `OPENVIKING_CLI_CONFIG_FILE` remains set, normal `ov` commands continue to use the environment-selected file; unset it to use the switched default. New `ov` commands reread the effective file, while already-running Agent clients must restart before reading changes.
+`ov config switch <name>` copies the named configuration to the effective active file, including the path selected by `OPENVIKING_CLI_CONFIG_FILE`. This overwrites the selected file; unset the variable first if you intend to switch the default `~/.openviking/ovcli.conf` instead. A directly selected `ovcli.conf.<name>` is shown as active even when another profile has identical contents, and cannot be deleted or renamed while selected. New `ov` commands reread the effective file, while already-running Agent clients must restart before reading changes.
See [OpenViking CLI Setup](../getting-started/05-cli-setup.md) for interactive and agent-assisted configuration workflows.
diff --git a/docs/zh/configuration/02-client.md b/docs/zh/configuration/02-client.md
index f59f0b6e3..fe5214b5b 100644
--- a/docs/zh/configuration/02-client.md
+++ b/docs/zh/configuration/02-client.md
@@ -324,7 +324,7 @@ Agent 插件读取 `OPENVIKING_AUTO_RECALL`、`OPENVIKING_RECALL_LIMIT`、`OPENV
~/.openviking/ovcli.conf
```
-交互式管理器以及 `ov config list`、`switch`、`add`、`edit`、`delete` 始终管理默认配置仓库。该仓库中的命名配置与默认 Active 文件位于同一目录:
+交互式管理器以及 `ov config list`、`switch`、`add`、`edit`、`delete` 使用相同的实际配置路径。命名配置与 Active 文件位于同一目录;未设置覆盖路径时为:
```text
~/.openviking/ovcli.conf.<name>
@@ -350,6 +350,6 @@ ov config validate
ov config show
```
-`ov config switch <name>` 会把命名配置复制为默认 Active 文件。如果仍设置了 `OPENVIKING_CLI_CONFIG_FILE`,普通 `ov` 命令会继续读取环境变量指定的文件;需要取消该变量后才会使用刚切换的默认配置。新的 `ov` 命令会重新读取实际配置文件;已经运行的 Agent 客户端需要重启后才会读取变更。
+`ov config switch <name>` 会把命名配置复制到实际 Active 文件,包括 `OPENVIKING_CLI_CONFIG_FILE` 指定的路径。这会覆盖所选文件;如果要切换默认的 `~/.openviking/ovcli.conf`,请先取消该环境变量。直接选中的 `ovcli.conf.<name>` 会显示为当前配置,即使另一个配置的内容完全相同;选中期间不能删除或重命名该文件。新的 `ov` 命令会重新读取实际配置文件;已经运行的 Agent 客户端需要重启后才会读取变更。
交互式配置和 Agent 辅助配置步骤见[OpenViking CLI 配置指南](../getting-started/05-cli-setup.md)。