Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
fix(cli): preserve server config sections and restrict ov.conf permissions in setup wizard (#3427)
Zayn Jarvis4ffd255d1a76
diff --git a/openviking_cli/setup_wizard.py b/openviking_cli/setup_wizard.pyindex 3c579e9f2..507d71c21 100644--- a/openviking_cli/setup_wizard.py+++ b/openviking_cli/setup_wizard.py@@ -15,6 +15,7 @@ import selectimport shutilimport subprocessimport sys+import tempfilefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any@@ -399,7 +400,6 @@ def _prompt_confirm(prompt: str, default: bool = True) -> bool:return raw in ("y", "yes")-def _rule(title: str) -> None:"""Print a section rule (rich when available, plain bold header otherwise)."""if _console is not None:@@ -879,8 +879,6 @@ def _ollama_vlm_config(vlm: VLMPreset) -> dict[str, Any]:}--def _build_query_planner_config(preset: QueryPlannerPreset) -> dict[str, Any]:"""Build the ``query_planner`` config block for an Ollama-served model.@@ -932,21 +930,49 @@ def _next_backup_path(config_path: Path) -> Path:i += 1+def _write_secure_backup(config_path: Path, backup: Path) -> None:+ fd, raw_temp_path = tempfile.mkstemp(prefix=f".{backup.name}.", dir=backup.parent)+ temp_path = Path(raw_temp_path)+ try:+ with os.fdopen(fd, "wb") as target, config_path.open("rb") as source:+ shutil.copyfileobj(source, target)+ target.flush()+ os.fsync(target.fileno())+ os.chmod(temp_path, 0o600)+ os.replace(temp_path, backup)+ temp_path = None+ finally:+ if temp_path is not None:+ temp_path.unlink(missing_ok=True)++def _write_config(config_dict: dict[str, Any], config_path: Path) -> bool:"""Write config dict as JSON. Backs up existing file as .bak (rotates on conflict)."""+ temp_path: Path | None = Nonetry:config_path.parent.mkdir(parents=True, exist_ok=True)+ fd, raw_temp_path = tempfile.mkstemp(prefix=f".{config_path.name}.", dir=config_path.parent)+ temp_path = Path(raw_temp_path)+ with os.fdopen(fd, "w", encoding="utf-8") as handle:+ handle.write(json.dumps(config_dict, indent=2, ensure_ascii=False) + "\n")+ handle.flush()+ os.fsync(handle.fileno())+ os.chmod(temp_path, 0o600)if config_path.exists():backup = _next_backup_path(config_path)- config_path.rename(backup)+ os.chmod(config_path, 0o600)+ _write_secure_backup(config_path, backup)print(f" {_dim('Existing config backed up to ' + str(backup))}")- config_path.write_text(- json.dumps(config_dict, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"- )+ os.replace(temp_path, config_path)+ temp_path = None+ os.chmod(config_path, 0o600)return Trueexcept OSError as exc:print(f" {_red(f'Failed to write config: {exc}')}")return False+ finally:+ if temp_path is not None:+ temp_path.unlink(missing_ok=True)# ---------------------------------------------------------------------------@@ -1528,7 +1554,6 @@ def _wizard_two_step() -> tuple[dict[str, Any] | None | object, bool | None]:return config, ollama_running-def _wizard_server(current: dict[str, Any] | None = None) -> dict[str, Any] | None:"""Prompt for server binding, port, and auth (root API key when remote).@@ -1802,7 +1827,11 @@ def _update_existing_config(config_path: Path, section: str) -> int:_summarize_server(current_server),_summarize_server(server_dict),)- data["server"] = server_dict+ updated_server = {**current_server, **server_dict}+ if server_dict.get("host") == "127.0.0.1":+ updated_server.pop("auth_mode", None)+ updated_server.pop("root_api_key", None)+ data["server"] = updated_serverprint(f"\n {_bold('Change:')} {old_summary}")print(f" {_cyan('→')} {new_summary}")diff --git a/tests/cli/test_setup_wizard.py b/tests/cli/test_setup_wizard.pyindex 8b199ec1c..9082c7efe 100644--- a/tests/cli/test_setup_wizard.py+++ b/tests/cli/test_setup_wizard.py@@ -330,6 +330,7 @@ class TestConfigWriting:assert _write_config(config, config_path) is Trueassert config_path.exists()+ assert config_path.stat().st_mode & 0o777 == 0o600loaded = json.loads(config_path.read_text(encoding="utf-8"))assert loaded["embedding"]["dense"]["provider"] == "ollama"@@ -343,6 +344,7 @@ class TestConfigWriting:backup = tmp_path / "ov.conf.bak"assert backup.exists()+ assert backup.stat().st_mode & 0o777 == 0o600assert json.loads(backup.read_text())["old"] is Truedef test_creates_parent_dirs(self, tmp_path):@@ -352,6 +354,31 @@ class TestConfigWriting:assert _write_config(config, config_path) is Trueassert config_path.exists()+ def test_replace_failure_preserves_existing_config(self, tmp_path):+ config_path = tmp_path / "ov.conf"+ config_path.write_text('{"old": true}', encoding="utf-8")++ with patch("openviking_cli.setup_wizard.os.replace", side_effect=OSError("replace")):+ assert _write_config({"new": True}, config_path) is False++ assert json.loads(config_path.read_text()) == {"old": True}+ assert not list(tmp_path.glob(".ov.conf.*"))++ def test_backup_copy_failure_leaves_no_public_backup(self, tmp_path):+ config_path = tmp_path / "ov.conf"+ config_path.write_text('{"secret": true}', encoding="utf-8")++ def fail_after_partial_copy(source, target):+ target.write(source.read(1))+ raise OSError("copy")++ with patch("openviking_cli.setup_wizard.shutil.copyfileobj", fail_after_partial_copy):+ assert _write_config({"new": True}, config_path) is False++ assert json.loads(config_path.read_text()) == {"secret": True}+ assert not (tmp_path / "ov.conf.bak").exists()+ assert not list(tmp_path.glob(".ov.conf*.*"))+def test_run_init_redacts_summary_output(self, tmp_path):config_path = tmp_path / "ov.conf"config = {@@ -947,7 +974,11 @@ class TestPartialUpdate:def test_update_server_only(self, tmp_path):config_path = tmp_path / "ov.conf"- config_path.write_text(json.dumps(_existing_config()), encoding="utf-8")+ original = _existing_config()+ original["server"].update(+ {"auth_mode": "trusted", "workers": 4, "temp_upload": {"default_mode": "shared"}}+ )+ config_path.write_text(json.dumps(original), encoding="utf-8")with (patch(@@ -961,9 +992,38 @@ class TestPartialUpdate:assert _update_existing_config(config_path, "server") == 0data = json.loads(config_path.read_text(encoding="utf-8"))- assert data["server"] == {"host": "0.0.0.0", "root_api_key": "rk"}+ assert data["server"] == {+ "host": "0.0.0.0",+ "root_api_key": "rk",+ "auth_mode": "trusted",+ "workers": 4,+ "temp_upload": {"default_mode": "shared"},+ }assert data["vlm"] == _existing_config()["vlm"]+ def test_update_server_local_removes_root_key_only(self, tmp_path):+ config_path = tmp_path / "ov.conf"+ original = _existing_config()+ original["server"].update({"auth_mode": "api_key", "root_api_key": "rk", "workers": 4})+ config_path.write_text(json.dumps(original), encoding="utf-8")++ with (+ patch(+ "openviking_cli.setup_wizard._wizard_server",+ return_value={"host": "127.0.0.1", "port": 1933},+ ),+ patch("openviking_cli.setup_wizard._prompt_confirm", return_value=True),+ patch("openviking_cli.setup_wizard._post_save_actions", return_value=None),+ patch("builtins.print"),+ ):+ assert _update_existing_config(config_path, "server") == 0++ assert json.loads(config_path.read_text())["server"] == {+ "host": "127.0.0.1",+ "port": 1933,+ "workers": 4,+ }+def test_embedding_dimension_change_requires_confirmation(self, tmp_path):config_path = tmp_path / "ov.conf"original = _existing_config()