Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(env): accept the DODAIOS_ prefix wherever JARVIS_ is read (#591)
Ruben Lütkeca818ff23eb6
diff --git a/.env.example b/.env.exampleindex 674bbcce86..3b661d7c66 100644--- a/.env.example+++ b/.env.example@@ -12,6 +12,9 @@# 2. environment variable# 3. this .env file (dev fallback only)#+# A JARVIS_* name below may also be written DODAIOS_*; if both are set,+# the DODAIOS_ one wins.+## Every provider is OPTIONAL — set only the keys you actually use.# A single cloud Brain key (e.g. GEMINI_API_KEY) is enough to boot.# ============================================================diff --git a/docs/product/reference/configuration-reference.md b/docs/product/reference/configuration-reference.mdindex 0b278a220c..578d084f23 100644--- a/docs/product/reference/configuration-reference.md+++ b/docs/product/reference/configuration-reference.md@@ -56,6 +56,13 @@ read-only installation. They control loading and are not nested settings.Changing `JARVIS_CONFIG` does not relocate profiles; a missing profile fileproduces no overlay.+Every variable on this page can also be written with the `DODAIOS_` prefix:+`DODAIOS__SECTION__KEY`, `DODAIOS_CONFIG`, `DODAIOS_PROFILE`, and so on (and+`DODAIOSCTL_` for the command-line client's `JARVISCTL_` variables). The+`JARVIS_` spelling keeps working. When both are set to different values, the+`DODAIOS_` one is used and a log line names the variable. Dodaios reads the+value under the `JARVIS_` name, and that is the name a program it starts sees.+| Location | Resolution ||---|---|| Active configuration | Non-blank `JARVIS_CONFIG`; otherwise `<project-folder>/jarvis.toml` |diff --git a/install/README.md b/install/README.mdindex f4136e540d..c2c57a68c8 100644--- a/install/README.md+++ b/install/README.md@@ -194,6 +194,11 @@ on macOS at all:| `JARVIS_PYTHON` | Use one explicit Python interpreter; the pin is authoritative. || `JARVIS_INSTALL_NO_PIP` | Skip the pip steps (re-run only prefetch / launch). |+Each `JARVIS_INSTALL_*` option also answers to `DODAIOS_INSTALL_*`+(`DODAIOS_INSTALL_DIR`, `DODAIOS_INSTALL_REF`, ...). When both spellings are set+to different values, the `DODAIOS_` one is used and the installer names the+option.+## Local development of the installer```bashdiff --git a/install/install.ps1 b/install/install.ps1index a01d310892..b2f46dc331 100644--- a/install/install.ps1+++ b/install/install.ps1@@ -195,6 +195,25 @@ function Write-Err([string]$Text) { Write-Host "$Gut $Red$Crs $Text$Rst" }Write-Banner# ----------------------------------------------------------------- config+# Every JARVIS_INSTALL_* option also answers to DODAIOS_INSTALL_*. When both+# are set to different values the DODAIOS_ one wins, and the clash is named,+# never its values. The rest of this script, and installer.py after it, read+# the JARVIS_ spelling (jarvis/core/env_prefix.py does the same for the app).+function Use-InstallOptionNames {+ foreach ($Option in 'REPO', 'REF', 'DIR', 'PREREQS') {+ $NewName = "DODAIOS_INSTALL_$Option"+ $OldName = "JARVIS_INSTALL_$Option"+ $NewValue = [Environment]::GetEnvironmentVariable($NewName)+ if (-not $NewValue) { continue }+ $OldValue = [Environment]::GetEnvironmentVariable($OldName)+ if ($OldValue -and $OldValue -cne $NewValue) {+ Write-Note "$NewName and $OldName differ; using $NewName."+ }+ [Environment]::SetEnvironmentVariable($OldName, $NewValue)+ }+}+Use-InstallOptionNames+# Standalone bootstrap projections of jarvis/core/branding.py. The branding# contract test rejects drift because this script runs before Python is installed.$OfficialRepoSlug = "$env:JARVIS_OFFICIAL_REPO_SLUG"diff --git a/install/install.sh b/install/install.shindex cbbb67e0b6..56880140bd 100755--- a/install/install.sh+++ b/install/install.sh@@ -17,6 +17,28 @@set -euo pipefail+# --- install-option-names begin+# Every JARVIS_INSTALL_* option also answers to DODAIOS_INSTALL_*. When both+# are set to different values the DODAIOS_ one wins, and the clash is named,+# never its values. The rest of this script, and installer.py after it, read+# the JARVIS_ spelling (jarvis/core/env_prefix.py does the same for the app).+adopt_install_option_names() {+ local option new_name old_name new_value old_value+ for option in REPO REF DIR PREREQS YES; do+ new_name="DODAIOS_INSTALL_$option"+ old_name="JARVIS_INSTALL_$option"+ new_value="${!new_name:-}"+ old_value="${!old_name:-}"+ [ -n "$new_value" ] || continue+ if [ -n "$old_value" ] && [ "$old_value" != "$new_value" ]; then+ printf '%s and %s differ; using %s.\n' "$new_name" "$old_name" "$new_name" >&2+ fi+ export "$old_name=$new_value"+ done+}+adopt_install_option_names+# --- install-option-names end+# Standalone bootstrap projections of jarvis/core/branding.py. The branding# contract test rejects drift because this script runs before Python is installed.OFFICIAL_REPO_SLUG="${JARVIS_OFFICIAL_REPO_SLUG:-Dodaios/Dodaios}"diff --git a/install/uninstall.ps1 b/install/uninstall.ps1index 5a284af66e..7560296eb3 100644--- a/install/uninstall.ps1+++ b/install/uninstall.ps1@@ -65,7 +65,8 @@ $WindowsShortcutFileName = 'Personal Jarvis.lnk'$WindowsUninstallRegistrySubkey = 'Software\Microsoft\Windows\CurrentVersion\Uninstall\PersonalJarvis'$WindowsAppUserModelId = 'PersonalJarvis.PersonalJarvis'-$InstallDir = if ($env:JARVIS_INSTALL_DIR) { $env:JARVIS_INSTALL_DIR } else { Join-Path $env:USERPROFILE $DefaultInstallDirName }+# DODAIOS_INSTALL_DIR and JARVIS_INSTALL_DIR are one option; the new name wins.+$InstallDir = if ($env:DODAIOS_INSTALL_DIR) { $env:DODAIOS_INSTALL_DIR } elseif ($env:JARVIS_INSTALL_DIR) { $env:JARVIS_INSTALL_DIR } else { Join-Path $env:USERPROFILE $DefaultInstallDirName }$VenvPython = Join-Path $InstallDir '.venv\Scripts\python.exe'Write-Step 'Uninstall Personal Jarvis'diff --git a/install/uninstall.sh b/install/uninstall.shindex a76d7c0e6c..4ab74b1076 100644--- a/install/uninstall.sh+++ b/install/uninstall.sh@@ -27,7 +27,8 @@ MACOS_AUTOSTART_LABEL="com.personal-jarvis.autostart"LINUX_DESKTOP_ENTRY_FILE_NAME="personal-jarvis.desktop"KEYRING_SERVICE_NAME="personal-jarvis"-INSTALL_DIR="${JARVIS_INSTALL_DIR:-$HOME/$DEFAULT_INSTALL_DIR_NAME}"+# DODAIOS_INSTALL_DIR and JARVIS_INSTALL_DIR are one option; the new name wins.+INSTALL_DIR="${DODAIOS_INSTALL_DIR:-${JARVIS_INSTALL_DIR:-$HOME/$DEFAULT_INSTALL_DIR_NAME}}"VENV_PYTHON="$INSTALL_DIR/.venv/bin/python"if [ -t 1 ]; thendiff --git a/jarvis.toml.example b/jarvis.toml.exampleindex 75da4f680a..a4b87341c4 100644--- a/jarvis.toml.example+++ b/jarvis.toml.example@@ -11,6 +11,7 @@# Never commit a real jarvis.toml — it is gitignored.## Overrides cascade: jarvis.toml → ENV (JARVIS__SECTION__KEY=...)+# DODAIOS__SECTION__KEY=... is the same override; if both are set, it wins.# Any section you delete falls back to the code defaults.# This template ships cloud-first defaults (no GPU, no local model,# no microphone required) so it runs on a 1 vCPU / 1 GB VPS.diff --git a/jarvis/__init__.py b/jarvis/__init__.pyindex 37eb8c8afe..bbe24b7632 100644--- a/jarvis/__init__.py+++ b/jarvis/__init__.py@@ -2,13 +2,21 @@__version__ = "3.1.1"+# A variable written as ``DODAIOS_<NAME>`` is moved to the ``JARVIS_<NAME>``+# spelling the code reads. Done here, on the first import of the package, so+# every entry point (the app, the CLIs, the MCP servers, each helper process)+# sees it before any reader runs. A dictionary pass; see+# jarvis/core/env_prefix.py for the precedence.+from jarvis.core.env_prefix import adopt_environment as _adopt_environment+# Every httpx client in the process shares one parsed CA bundle instead of# re-parsing it (~200 ms of CPU) per client. Patches httpx lazily, the moment# it is first imported; importing ``jarvis`` itself still loads nothing heavy.from jarvis.core.shared_tls import install_when_imported as _install_shared_tls+_adopt_environment()_install_shared_tls()-del _install_shared_tls+del _adopt_environment, _install_shared_tls# numpy and scipy each start one BLAS thread per CPU core and commit 32 MB for# every one (~1 GB per process on a 16-thread Windows box). Cap that pool thediff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex 1f51a7cb6d..747d5945b7 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -43,6 +43,7 @@ from jarvis.speech.wake_constants import DEFAULT_WAKE_PHRASE, WAKE_ENGINESfrom jarvis.ui.pets.states import DEFAULT_PET_IDfrom .branding import CONFIG_FILE_NAME, KEYRING_SERVICE_NAME+from .env_prefix import accepted_namesfrom .instance import current_instance, resolve_data_dirfrom .protocols import RiskTier@@ -5794,16 +5795,22 @@ def get_secret(key: str, env_fallback: str | None = None) -> str | None:if env_fallback and (val := os.environ.get(env_fallback)):return val- # Development fallback: .env file.+ # Development fallback: .env file. A JARVIS_ name may be written under the+ # DODAIOS_ prefix there too; as in the environment, the new spelling wins.env_file = PROJECT_ROOT / ".env"if env_file.exists() and env_fallback:+ names = accepted_names(env_fallback)+ found: dict[str, str] = {}for line in env_file.read_text(encoding="utf-8").splitlines():line = line.strip()if not line or line.startswith("#") or "=" not in line:continuek, _, v = line.partition("=")- if k.strip() == env_fallback:- return v.strip().strip('"').strip("'")+ if k.strip() in names:+ found.setdefault(k.strip(), v.strip().strip('"').strip("'"))+ for name in names:+ if name in found:+ return found[name]if file_val:return file_valdiff --git a/jarvis/core/env_prefix.py b/jarvis/core/env_prefix.pynew file mode 100644index 0000000000..55f243a6f6--- /dev/null+++ b/jarvis/core/env_prefix.py@@ -0,0 +1,125 @@+"""``DODAIOS_`` is the prefix to write; ``JARVIS_`` is the prefix the code reads.++Every variable the app reads is spelled ``JARVIS_<NAME>`` in the code+(``JARVIS__<SECTION>__<KEY>`` for a config override, ``JARVISCTL_<NAME>`` for+the control CLI). People and scripts may write ``DODAIOS_<NAME>``,+``DODAIOS__<SECTION>__<KEY>`` and ``DODAIOSCTL_<NAME>`` instead. No reader+changes: :func:`adopt_environment` runs once, when the ``jarvis`` package is+first imported, and moves every new-prefix variable to the name the readers+use before any of them runs.++Precedence+----------+* Only the ``DODAIOS_`` name is set: its value becomes the ``JARVIS_`` value.+* Both are set to the same value, or the ``DODAIOS_`` one is blank: the+ ``JARVIS_`` value stands.+* Both are set to different values: **the ``DODAIOS_`` name wins**, and one line+ names the variable (never its value).++Why the new name is moved, not mirrored+---------------------------------------+After the adoption the process environment holds one spelling, the one all+existing code is written against. Keeping (or adding) a ``DODAIOS_`` twin beside+every ``JARVIS_`` variable would break two things that work today:++* **Scrubbing.** Code that starts an external tool removes credentials from the+ child's environment by name (``JARVIS_CONTROL_API_KEY`` before a vendor CLI+ starts). A twin under a second name would carry the same credential past it.+* **Overrides.** The app sets, replaces and deletes ``JARVIS_`` variables for+ its children: its own data directory for a worker, a one-shot marker dropped+ before a restart, a persisted override re-read from the registry. A child+ that still saw the twin's earlier value, and let the new name win, would undo+ each of those.++So a child process and a plugin read the ``JARVIS_`` name; they never see a+``DODAIOS_`` one, whoever set it.++Standard library only and no I/O besides the environment: this runs before+logging exists and on every process start. ``packaging/pyinstaller_rthook_frozen.py``+cannot import the package and carries a copy of :func:`_adopt`;+``tests/unit/core/test_env_prefix.py`` holds the two copies identical.+"""++from __future__ import annotations++import os+from collections.abc import MutableMapping++# (prefix to write, prefix the code reads). No prefix is the start of another:+# ``DODAIOSCTL_X`` does not begin with ``DODAIOS_``.+_PREFIXES = (("DODAIOS_", "JARVIS_"), ("DODAIOSCTL_", "JARVISCTL_"))++#: Config overrides (``<PREFIX>_<SECTION>__<KEY>``) under the two prefixes.+CONFIG_ENV_PREFIX = f"{_PREFIXES[0][0]}_"+LEGACY_CONFIG_ENV_PREFIX = f"{_PREFIXES[0][1]}_"+++def _adopt(environ):+ """Move every new-prefix variable to the name the code reads; return the clashing names."""+ clashes = []+ for name in list(environ):+ for new_prefix, old_prefix in _PREFIXES:+ if not name.startswith(new_prefix) or name == new_prefix:+ continue+ value = environ.pop(name)+ old_name = old_prefix + name[len(new_prefix) :]+ if value:+ if environ.get(old_name) not in (None, "", value):+ clashes.append(name)+ environ[old_name] = value+ elif old_name not in environ:+ environ[old_name] = value+ break+ return clashes+++def old_name_of(new_name: str) -> str | None:+ """The name the code reads for a new-prefix variable, ``None`` for any other name."""+ for new_prefix, old_prefix in _PREFIXES:+ if new_name.startswith(new_prefix) and new_name != new_prefix:+ return old_prefix + new_name[len(new_prefix) :]+ return None+++def accepted_names(name: str) -> tuple[str, ...]:+ """Every spelling of a variable the code reads, the one that wins first.++ For a reader of something that is not the process environment (a ``.env``+ file) and therefore never passed through :func:`adopt_environment`.+ """+ for new_prefix, old_prefix in _PREFIXES:+ if name.startswith(old_prefix) and name != old_prefix:+ return (new_prefix + name[len(old_prefix) :], name)+ return (name,)+++def adopt_environment(environ: MutableMapping[str, str] | None = None) -> tuple[str, ...]:+ """Run the adoption on ``environ`` (the process environment by default).++ Returns the new-prefix names that were set to a different value than the+ variable the code reads, and won. Safe to call again: after one pass there+ is no new-prefix variable left to move.+ """+ clashes = tuple(_adopt(os.environ if environ is None else environ))+ if clashes:+ # Imported only now: a clash is rare, and ``import jarvis`` stays light.+ import logging++ log = logging.getLogger(__name__)+ for new_name in clashes:+ log.warning(+ "%s and %s are set to different values; using %s.",+ new_name,+ old_name_of(new_name),+ new_name,+ )+ return clashes+++__all__ = [+ "CONFIG_ENV_PREFIX",+ "LEGACY_CONFIG_ENV_PREFIX",+ "accepted_names",+ "adopt_environment",+ "old_name_of",+]diff --git a/jarvis/ui/relauncher.py b/jarvis/ui/relauncher.pyindex 52832b6b48..2de57fde45 100644--- a/jarvis/ui/relauncher.py+++ b/jarvis/ui/relauncher.py@@ -38,6 +38,7 @@ from jarvis.core.branding import (WINDOWS_BRANDED_LAUNCH_ENV_VAR,WINDOWS_BRANDED_LAUNCHER_DIR_NAME,)+from jarvis.core.env_prefix import CONFIG_ENV_PREFIX, LEGACY_CONFIG_ENV_PREFIXfrom jarvis.core.update_contract import (DEFAULT_CONTRACT,UpdateContract,@@ -49,6 +50,9 @@ MANAGED_MARKER = MANAGED_INSTALL_MARKERPENDING_UPDATE_FILENAME = ".jarvis-update-pending.json"UPDATE_RESULT_FILENAME = ".jarvis-update-result.json"_REVISION_RE = re.compile(r"^[0-9a-fA-F]{7,64}$")+#: Both spellings of a persisted config override (``<PREFIX>_SECTION__KEY``).+#: This process holds only the second one: the first was moved to it at start.+_CONFIG_ENV_PREFIXES = (CONFIG_ENV_PREFIX, LEGACY_CONFIG_ENV_PREFIX)#: Must match ``jarvis.ui.web.launcher._DEFAULT_ADMIN_PORT`` / the packaged#: ``[ui].admin_api_port`` default. Used only when the checkout's config#: cannot be read, so a restart still has a port to probe.@@ -330,7 +334,7 @@ def _read_windows_user_jarvis_env() -> dict[str, str] | None:except OSError:breakindex += 1- if isinstance(name, str) and name.upper().startswith("JARVIS__"):+ if isinstance(name, str) and name.upper().startswith(_CONFIG_ENV_PREFIXES):persisted[name] = str(value)return persistedexcept OSError:@@ -369,6 +373,9 @@ def fresh_user_env(# refreshed names), then lay down the persisted set verbatim.for stale in [k for k in env if k.upper().startswith("JARVIS__") and k not in persisted]:del env[stale]+ # A persisted DODAIOS__* override travels under its own name: the new+ # process moves it to the JARVIS__ spelling when it starts, where it wins+ # over a persisted JARVIS__ value (jarvis/core/env_prefix.py).env.update(persisted)return envdiff --git a/packaging/pyinstaller_rthook_frozen.py b/packaging/pyinstaller_rthook_frozen.pyindex 209accb5ae..16641cadef 100644--- a/packaging/pyinstaller_rthook_frozen.py+++ b/packaging/pyinstaller_rthook_frozen.py@@ -21,7 +21,11 @@ override variables at the per-user application directory and seeds a first-run``jarvis.toml`` from the copy inside the bundle.An explicitly exported ``JARVIS_CONFIG`` / ``JARVIS_DATA_DIR`` always wins, so a-maintainer can still run a frozen build against a scratch directory.+maintainer can still run a frozen build against a scratch directory. So does+``DODAIOS_CONFIG`` / ``DODAIOS_DATA_DIR``: a variable written under the+``DODAIOS_`` prefix is moved to its ``JARVIS_`` name first, by the hook's own+copy of ``jarvis.core.env_prefix._adopt`` (``tests/unit/core/test_env_prefix.py``+holds the copy identical).Standard library only, and no ``jarvis`` import: a failure in a runtime hookkills a windowed process before any logging exists. ``tests/unit/packaging/@@ -40,6 +44,27 @@ from pathlib import Path_WINDOWS_USER_DATA_DIR_NAME = "Jarvis"_FALLBACK_USER_DATA_DIR_NAME = ".jarvis"_CONFIG_FILE_NAME = "jarvis.toml"+# Mirrors jarvis.core.env_prefix: the prefixes and the adoption itself.+_PREFIXES = (("DODAIOS_", "JARVIS_"), ("DODAIOSCTL_", "JARVISCTL_"))+++def _adopt(environ):+ """Move every new-prefix variable to the name the code reads; return the clashing names."""+ clashes = []+ for name in list(environ):+ for new_prefix, old_prefix in _PREFIXES:+ if not name.startswith(new_prefix) or name == new_prefix:+ continue+ value = environ.pop(name)+ old_name = old_prefix + name[len(new_prefix) :]+ if value:+ if environ.get(old_name) not in (None, "", value):+ clashes.append(name)+ environ[old_name] = value+ elif old_name not in environ:+ environ[old_name] = value+ break+ return clashesdef _user_data_dir() -> Path:@@ -73,6 +98,17 @@ def _apply() -> None:if not (getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS")):return+ try:+ clashes = _adopt(os.environ)+ except (OSError, ValueError) as exc:+ # The operating system refused an environment write. The package runs+ # the same adoption on import and reports it with logging available;+ # the hook only has to keep the process alive until then.+ _warn(f"could not adopt the DODAIOS_ variable names: {exc}")+ clashes = []+ for new_name in clashes:+ _warn(f"{new_name} and its JARVIS_ spelling are set to different values; using {new_name}.")+home = _user_data_dir()config_path = home / _CONFIG_FILE_NAMEdiff --git a/tests/conftest.py b/tests/conftest.pyindex ee9c8c7cdc..fffb4f6829 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -418,6 +418,27 @@ async def fresh_bus():yield bus+def prefixed_environment_restored():+ """Put every ``JARVIS_*`` / ``DODAIOS_*`` variable back after the test.++ For a test that runs the new-prefix adoption on the real process+ environment (``jarvis.core.env_prefix``, or the frozen runtime hook that+ carries a copy of it): the adoption writes the ``JARVIS_`` name of every+ ``DODAIOS_`` variable, and ``monkeypatch`` only takes back the names the+ test itself set.+ """+ import os++ prefixes = ("JARVIS_", "DODAIOS_")+ before = {name: value for name, value in os.environ.items() if name.startswith(prefixes)}+ yield+ for name in [name for name in os.environ if name.startswith(prefixes)]:+ if name not in before:+ del os.environ[name]+ os.environ.update(before)++@pytest.fixturedef anyio_backend():return "asyncio"diff --git a/tests/unit/core/test_env_prefix.py b/tests/unit/core/test_env_prefix.pynew file mode 100644index 0000000000..d0f5767068--- /dev/null+++ b/tests/unit/core/test_env_prefix.py@@ -0,0 +1,394 @@+"""A variable written as ``DODAIOS_<NAME>`` reaches the reader of ``JARVIS_<NAME>``.++``jarvis.core.env_prefix`` moves every new-prefix variable to the name the code+reads, once per process, before any reader runs. These tests hold the+precedence, the reason the new name is moved rather than mirrored (scrubbing+and overrides keep working), the copy the frozen runtime hook carries, and+what a real child process sees.+"""++from __future__ import annotations++import ast+import importlib.util+import json+import logging+import os+import subprocess+import sys+from pathlib import Path+from types import ModuleType++import pytest++import jarvis.core.env_prefix as env_prefix+from jarvis.core import config as core_config+from jarvis.core.env_prefix import accepted_names, adopt_environment, old_name_of+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++_ROOT = Path(__file__).resolve().parents[3]+_HOOK_PATH = _ROOT / "packaging" / "pyinstaller_rthook_frozen.py"++# Some tests run the adoption on the real environment, as the package does.+pytestmark = pytest.mark.usefixtures("prefixed_environment_restored")+++# ---------------------------------------------------------------------------+# Both prefixes resolve+# ---------------------------------------------------------------------------+++def test_a_new_name_reaches_the_reader_of_the_old_name() -> None:+ environ = {"DODAIOS_DATA_DIR": "/srv/data", "PATH": "/bin"}++ assert adopt_environment(environ) == ()++ assert environ == {"JARVIS_DATA_DIR": "/srv/data", "PATH": "/bin"}+++def test_an_old_name_keeps_working_untouched() -> None:+ environ = {"JARVIS_BIND_HOST": "127.0.0.1", "JARVIS__BRAIN__PRIMARY": "gemini"}+ before = dict(environ)++ assert adopt_environment(environ) == ()++ assert environ == before+++def test_a_nested_config_override_works_under_the_new_prefix(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # Set (not deleted), so monkeypatch takes back what the adoption writes.+ monkeypatch.setenv("JARVIS__BRAIN__PRIMARY", "")+ monkeypatch.setenv("DODAIOS__BRAIN__PRIMARY", "openrouter")++ adopt_environment()++ # The reader is untouched: it still scans for the JARVIS__ spelling.+ assert core_config._apply_env_overrides({})["brain"]["primary"] == "openrouter"+ assert "DODAIOS__BRAIN__PRIMARY" not in os.environ+++def test_the_control_cli_prefix_is_adopted_too() -> None:+ environ = {"DODAIOSCTL_BASE_URL": "http://127.0.0.1:47821", "JARVISCTL_CACHE_HOME": "/c"}++ assert adopt_environment(environ) == ()++ assert environ == {+ "JARVISCTL_BASE_URL": "http://127.0.0.1:47821",+ "JARVISCTL_CACHE_HOME": "/c",+ }+++def test_unrelated_and_bare_prefix_names_are_left_alone() -> None:+ environ = {+ "DODAIOS_": "bare",+ "DODAIOSCTL_": "bare",+ "MY_DODAIOS_VAR": "1",+ "dodaios_lower": "2",+ "DODAIOSX_OTHER": "3",+ }+ before = dict(environ)++ assert adopt_environment(environ) == ()++ assert environ == before+++ ("new_name", "expected"),+ [+ ("DODAIOS_CONFIG", "JARVIS_CONFIG"),+ ("DODAIOS__TTS__PROVIDER", "JARVIS__TTS__PROVIDER"),+ ("DODAIOSCTL_CONTROL_KEY", "JARVISCTL_CONTROL_KEY"),+ ("JARVIS_CONFIG", None),+ ("DODAIOS_", None),+ ("PATH", None),+ ],+)+def test_the_name_the_code_reads(new_name: str, expected: str | None) -> None:+ assert old_name_of(new_name) == expected+++def test_every_spelling_of_a_name_the_code_reads() -> None:+ assert accepted_names("JARVIS_ADMIN_HMAC") == ("DODAIOS_ADMIN_HMAC", "JARVIS_ADMIN_HMAC")+ assert accepted_names("JARVISCTL_BASE_URL") == ("DODAIOSCTL_BASE_URL", "JARVISCTL_BASE_URL")+ assert accepted_names("GROQ_API_KEY") == ("GROQ_API_KEY",)+++# ---------------------------------------------------------------------------+# Precedence+# ---------------------------------------------------------------------------+++def test_the_new_name_wins_when_both_are_set_differently(+ caplog: pytest.LogCaptureFixture,+) -> None:+ environ = {"JARVIS_PERSONA": "old-value", "DODAIOS_PERSONA": "new-value"}++ with caplog.at_level(logging.WARNING, logger="jarvis.core.env_prefix"):+ clashes = adopt_environment(environ)++ assert clashes == ("DODAIOS_PERSONA",)+ assert environ == {"JARVIS_PERSONA": "new-value"}+ # One line, naming both spellings and never a value.+ assert len(caplog.records) == 1+ message = caplog.records[0].getMessage()+ assert "DODAIOS_PERSONA" in message and "JARVIS_PERSONA" in message+ assert "value" not in message.replace("different values", "")+++def test_equal_values_are_no_clash(caplog: pytest.LogCaptureFixture) -> None:+ environ = {"JARVIS_DEBUG": "1", "DODAIOS_DEBUG": "1"}++ with caplog.at_level(logging.WARNING, logger="jarvis.core.env_prefix"):+ assert adopt_environment(environ) == ()++ assert environ == {"JARVIS_DEBUG": "1"}+ assert caplog.records == []+++def test_a_blank_new_name_does_not_override_a_value() -> None:+ environ = {"JARVIS_CONFIG": "/etc/app.toml", "DODAIOS_CONFIG": ""}++ assert adopt_environment(environ) == ()++ assert environ == {"JARVIS_CONFIG": "/etc/app.toml"}+++def test_a_new_name_replaces_a_blank_old_one_without_a_clash() -> None:+ environ = {"JARVIS_CONFIG": "", "DODAIOS_CONFIG": "/etc/app.toml"}++ assert adopt_environment(environ) == ()++ assert environ == {"JARVIS_CONFIG": "/etc/app.toml"}+++def test_a_blank_new_name_alone_is_still_carried_over() -> None:+ environ = {"DODAIOS_VOICE": ""}++ assert adopt_environment(environ) == ()++ assert environ == {"JARVIS_VOICE": ""}+++def test_a_second_pass_changes_nothing() -> None:+ environ = {"JARVIS_A": "1", "DODAIOS_B": "2", "JARVIS_C": "x", "DODAIOS_C": "y"}+ assert adopt_environment(environ) == ("DODAIOS_C",)+ settled = dict(environ)++ assert adopt_environment(environ) == ()+ assert environ == settled == {"JARVIS_A": "1", "JARVIS_B": "2", "JARVIS_C": "y"}+++# ---------------------------------------------------------------------------+# Why the new name is moved: what the app does afterwards keeps working+# ---------------------------------------------------------------------------+++def test_a_variable_scrubbed_by_its_old_name_is_gone_from_the_child() -> None:+ # Code that starts an external tool drops credentials by the name the code+ # reads. Had the new spelling stayed beside it, the value would pass.+ environ = {"DODAIOS_CONTROL_API_KEY": "the-value", "DODAIOSCTL_CONTROL_KEY": "the-value"}+ adopt_environment(environ)++ child = dict(environ)+ for name in ("JARVIS_CONTROL_API_KEY", "JARVISCTL_CONTROL_KEY"):+ child.pop(name, None)++ assert "the-value" not in child.values()+++def test_an_override_set_for_a_child_is_what_the_child_reads() -> None:+ # The app points one worker at its own directory. The child must read+ # that, not the value the person originally set under the new name.+ environ = {"DODAIOS_DATA_DIR": "/home/u/data"}+ adopt_environment(environ)++ child = {**environ, "JARVIS_DATA_DIR": "/srv/worker"}++ assert adopt_environment(child) == ()+ assert child == {"JARVIS_DATA_DIR": "/srv/worker"}+++def test_a_marker_removed_before_a_restart_does_not_return() -> None:+ environ = {"DODAIOS_BRANDED_LAUNCH": "1", "JARVIS_DEBUG": "1"}+ adopt_environment(environ)++ child = dict(environ)+ del child["JARVIS_BRANDED_LAUNCH"]++ adopt_environment(child)+ assert child == {"JARVIS_DEBUG": "1"}+++# ---------------------------------------------------------------------------+# The package adopts the environment for every entry point+# ---------------------------------------------------------------------------++_CHILD_REPORT = (+ "import json, os, jarvis; "+ "print(json.dumps({k: v for k, v in os.environ.items() "+ "if k.startswith(('JARVIS', 'DODAIOS'))}))"+)+_GRANDCHILD_REPORT = (+ "import json, os, subprocess, sys, jarvis; "+ "from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS as F; "+ "os.environ['JARVIS_PRIMARY_INSTANCE'] = '0'; "+ "r = subprocess.run([sys.executable, '-c', sys.argv[1]], capture_output=True, text=True, "+ "encoding='utf-8', creationflags=F); "+ "sys.stderr.write(r.stderr); print(r.stdout.strip().splitlines()[-1])"+)+++def _run_child(environ: dict[str, str], code: str, *args: str) -> dict[str, str]:+ base = {+ name: value+ for name, value in os.environ.items()+ if not name.upper().startswith(("JARVIS", "DODAIOS"))+ }+ base["PYTHONPATH"] = str(_ROOT)+ result = subprocess.run( # noqa: S603 - the interpreter running this test+ [sys.executable, "-c", code, *args],+ env={**base, **environ},+ capture_output=True,+ text=True,+ encoding="utf-8",+ timeout=120,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ assert result.returncode == 0, result.stderr+ return json.loads(result.stdout.strip().splitlines()[-1])+++def test_importing_the_package_adopts_the_environment_of_a_real_process() -> None:+ seen = _run_child(+ {+ "DODAIOS_DATA_DIR": "new-only",+ "JARVIS_BIND_HOST": "old-only",+ "DODAIOS__UI__LANGUAGE": "en",+ "DODAIOSCTL_BASE_URL": "http://127.0.0.1:1",+ },+ _CHILD_REPORT,+ )++ assert seen == {+ "JARVIS_DATA_DIR": "new-only",+ "JARVIS_BIND_HOST": "old-only",+ "JARVIS__UI__LANGUAGE": "en",+ "JARVISCTL_BASE_URL": "http://127.0.0.1:1",+ }+++def test_a_grandchild_reads_what_its_parent_set_after_the_adoption() -> None:+ # The person starts the app with the new name; the app then sets the+ # variable itself (as the launcher does) and starts a helper.+ seen = _run_child(+ {"DODAIOS_PRIMARY_INSTANCE": "1", "DODAIOS_DEBUG": "1"},+ _GRANDCHILD_REPORT,+ _CHILD_REPORT,+ )++ assert seen == {"JARVIS_PRIMARY_INSTANCE": "0", "JARVIS_DEBUG": "1"}+++def test_the_module_needs_nothing_but_the_standard_library() -> None:+ tree = ast.parse((_ROOT / "jarvis" / "core" / "env_prefix.py").read_text(encoding="utf-8"))+ imported: set[str] = set()+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ imported.update(alias.name.split(".")[0] for alias in node.names)+ elif isinstance(node, ast.ImportFrom) and node.module:+ imported.add(node.module.split(".")[0])+ assert imported <= {"__future__", "collections", "logging", "os"}+++def test_the_package_runs_the_adoption_before_anything_else() -> None:+ tree = ast.parse((_ROOT / "jarvis" / "__init__.py").read_text(encoding="utf-8"))+ calls = [+ node.value.func.id+ for node in tree.body+ if isinstance(node, ast.Expr)+ and isinstance(node.value, ast.Call)+ and isinstance(node.value.func, ast.Name)+ ]+ assert calls and calls[0] == "_adopt_environment"+++# ---------------------------------------------------------------------------+# The frozen runtime hook carries an identical copy+# ---------------------------------------------------------------------------+++def _load_hook() -> ModuleType:+ spec = importlib.util.spec_from_file_location("env_prefix_rthook_frozen", _HOOK_PATH)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module) # a no-op outside a frozen build+ return module+++def _function_node(path: Path, name: str) -> ast.FunctionDef:+ for node in ast.parse(path.read_text(encoding="utf-8")).body:+ if isinstance(node, ast.FunctionDef) and node.name == name:+ return node+ raise AssertionError(f"{path} defines no {name}")+++def test_the_hook_copy_of_the_adoption_is_identical() -> None:+ package = _function_node(_ROOT / "jarvis" / "core" / "env_prefix.py", "_adopt")+ hook = _function_node(_HOOK_PATH, "_adopt")++ assert ast.dump(hook) == ast.dump(package), (+ "packaging/pyinstaller_rthook_frozen.py::_adopt must be a verbatim copy of "+ "jarvis/core/env_prefix.py::_adopt"+ )+++def test_the_hook_restates_the_prefixes() -> None:+ assert _load_hook()._PREFIXES == env_prefix._PREFIXES+++def _frozen(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> ModuleType:+ hook = _load_hook()+ bundle = tmp_path / "bundle"+ bundle.mkdir()+ monkeypatch.setattr(sys, "frozen", True, raising=False)+ monkeypatch.setattr(sys, "_MEIPASS", str(bundle), raising=False)+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "local"))+ return hook+++def test_the_hook_honours_an_override_under_the_new_prefix(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ hook = _frozen(tmp_path, monkeypatch)+ scratch = tmp_path / "scratch"+ monkeypatch.setenv("JARVIS_CONFIG", "")+ monkeypatch.setenv("JARVIS_DATA_DIR", "")+ monkeypatch.setenv("DODAIOS_CONFIG", str(scratch / "app.toml"))+ monkeypatch.setenv("DODAIOS_DATA_DIR", str(scratch / "data"))++ hook._apply()++ # The hook did not point them at the per-user directory: the override won.+ assert os.environ["JARVIS_CONFIG"] == str(scratch / "app.toml")+ assert os.environ["JARVIS_DATA_DIR"] == str(scratch / "data")+ assert "DODAIOS_CONFIG" not in os.environ and "DODAIOS_DATA_DIR" not in os.environ+ assert not (tmp_path / "local").exists()+++def test_the_hook_names_a_clash_without_its_values(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]+) -> None:+ hook = _frozen(tmp_path, monkeypatch)+ monkeypatch.setenv("JARVIS_CONFIG", str(tmp_path / "old-value.toml"))+ monkeypatch.setenv("DODAIOS_CONFIG", str(tmp_path / "new-value.toml"))+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path / "data"))++ hook._apply()++ assert os.environ["JARVIS_CONFIG"] == str(tmp_path / "new-value.toml")+ warning = capsys.readouterr().err+ assert "DODAIOS_CONFIG" in warning+ assert "old-value" not in warning and "new-value" not in warningdiff --git a/tests/unit/core/test_get_secret_env_fallback.py b/tests/unit/core/test_get_secret_env_fallback.pyindex 4b0f0c566f..0ca3dbd722 100644--- a/tests/unit/core/test_get_secret_env_fallback.py+++ b/tests/unit/core/test_get_secret_env_fallback.py@@ -85,3 +85,38 @@ def test_environment_still_precedes_file_fallback(monkeypatch, tmp_path):)assert get_secret("openai_api_key", "OPENAI_API_KEY") == "environment-value"+++ ("dotenv", "expected"),+ [+ ("JARVIS_ADMIN_HMAC=old-name-value\n", "old-name-value"),+ ("DODAIOS_ADMIN_HMAC='new-name-value'\n", "new-name-value"),+ # Both spellings in one file: the new one wins, whatever the order.+ ("JARVIS_ADMIN_HMAC=old\nDODAIOS_ADMIN_HMAC=new\n", "new"),+ ("DODAIOS_ADMIN_HMAC=new\nJARVIS_ADMIN_HMAC=old\n", "new"),+ ("OTHER_ADMIN_HMAC=unrelated\n", None),+ ],+)+def test_the_dotenv_fallback_reads_a_prefixed_name_under_both_prefixes(+ monkeypatch, tmp_path, dotenv, expected+):+ from jarvis.core import config++ monkeypatch.setattr(keyring, "get_password", lambda *a, **k: None)+ monkeypatch.setattr(config, "PROJECT_ROOT", tmp_path)+ monkeypatch.delenv("JARVIS_ADMIN_HMAC", raising=False)+ (tmp_path / ".env").write_text(dotenv, encoding="utf-8")++ assert get_secret("admin_hmac", env_fallback="JARVIS_ADMIN_HMAC") == expected+++def test_the_dotenv_fallback_matches_an_unprefixed_name_exactly(monkeypatch, tmp_path):+ from jarvis.core import config++ monkeypatch.setattr(keyring, "get_password", lambda *a, **k: None)+ monkeypatch.setattr(config, "PROJECT_ROOT", tmp_path)+ monkeypatch.delenv("GROQ_API_KEY", raising=False)+ (tmp_path / ".env").write_text("GROQ_API_KEY=gsk-from-file\n", encoding="utf-8")++ assert get_secret("groq_api_key") == "gsk-from-file"diff --git a/tests/unit/core/test_identity_single_source.py b/tests/unit/core/test_identity_single_source.pyindex c19369564b..9ffd441b24 100644--- a/tests/unit/core/test_identity_single_source.py+++ b/tests/unit/core/test_identity_single_source.py@@ -342,6 +342,7 @@ def test_config_and_the_early_log_resolve_through_it(assert desktop_log_path() == expected / DESKTOP_LOG_FILE_NAME[email protected]("prefixed_environment_restored")def test_the_frozen_hook_points_the_data_directory_inside_the_user_directory(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/tests/unit/install/test_install_option_names.py b/tests/unit/install/test_install_option_names.pynew file mode 100644index 0000000000..5ea1de327f--- /dev/null+++ b/tests/unit/install/test_install_option_names.py@@ -0,0 +1,280 @@+"""The shell installers answer to ``DODAIOS_INSTALL_*`` as well as ``JARVIS_INSTALL_*``.++``install.sh`` and ``install.ps1`` run before Python exists, so they cannot use+``jarvis.core.env_prefix``. Each carries one small block that folds the new+spelling into the old one the rest of the script reads. These tests run those+real blocks, extracted from the scripts, in a real shell.+"""++from __future__ import annotations++import os+import re+import shutil+import subprocess+from pathlib import Path++import pytest++from jarvis.core import env_prefix+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++_ROOT = Path(__file__).resolve().parents[3]+INSTALL_SH = _ROOT / "install" / "install.sh"+INSTALL_PS1 = _ROOT / "install" / "install.ps1"+UNINSTALL_SH = _ROOT / "install" / "uninstall.sh"+UNINSTALL_PS1 = _ROOT / "install" / "uninstall.ps1"++BLOCK_BEGIN = "# --- install-option-names begin"+BLOCK_END = "# --- install-option-names end"+SH_OPTIONS = ("REPO", "REF", "DIR", "PREREQS", "YES")+PS_OPTIONS = ("REPO", "REF", "DIR", "PREREQS")++SH_DRIVER = """#!/usr/bin/env bash+set -euo pipefail+source "$BLOCK_FILE"+for option in REPO REF DIR PREREQS YES; do+ name="JARVIS_INSTALL_$option"+ printf 'VALUE|%s|%s\\n' "$option" "${!name:-}"+done+bash -c 'printf "CHILD|%s\\n" "${JARVIS_INSTALL_DIR:-}"'+"""++PS_DRIVER = """$ErrorActionPreference = 'Stop'+function Write-Note([string]$Text) { Write-Host "NOTE|$Text" }+. $env:TEST_FUNCTION_FILE+Use-InstallOptionNames+foreach ($Option in 'REPO', 'REF', 'DIR', 'PREREQS') {+ $Value = [Environment]::GetEnvironmentVariable("JARVIS_INSTALL_$Option")+ Write-Host "VALUE|$Option|$Value"+}+"""+++def _find_bash() -> str | None:+ git = shutil.which("git")+ if git:+ for rel in ("../bin/bash.exe", "../../bin/bash.exe", "../usr/bin/bash.exe"):+ candidate = (Path(git).parent / rel).resolve()+ if candidate.exists():+ return str(candidate)+ bash = shutil.which("bash")+ # On Windows the first ``bash`` on PATH can be the WSL launcher stub.+ if bash and not any(part in bash.lower() for part in ("windowsapps", "system32")):+ return bash+ return None+++BASH = _find_bash()+POWERSHELL = shutil.which("pwsh") or shutil.which("powershell")++needs_bash = pytest.mark.skipif(BASH is None, reason="no usable bash on this host")+needs_powershell = pytest.mark.skipif(POWERSHELL is None, reason="no PowerShell on this host")+++def _base_env() -> dict[str, str]:+ """This process's environment without any prefixed variable or sync record."""+ return {+ name: value+ for name, value in os.environ.items()+ if not name.upper().startswith(("JARVIS_", "DODAIOS_"))+ }+++def _run(args: list[str], env: dict[str, str]) -> subprocess.CompletedProcess[str]:+ return subprocess.run( # noqa: S603 - test-controlled command+ args,+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=120,+ env=env,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+++def _values(output: str) -> dict[str, str]:+ found: dict[str, str] = {}+ for line in output.splitlines():+ if line.startswith("VALUE|"):+ _tag, option, value = line.split("|", 2)+ found[option] = value+ return found+++def _run_sh(tmp_path: Path, **variables: str) -> subprocess.CompletedProcess[str]:+ source = INSTALL_SH.read_text(encoding="utf-8")+ assert BLOCK_BEGIN in source and BLOCK_END in source, (+ "the install-option-names extraction markers vanished from install.sh"+ )+ block = tmp_path / "block.sh"+ block.write_text(+ source.split(BLOCK_BEGIN, 1)[1].split(BLOCK_END, 1)[0], encoding="utf-8", newline="\n"+ )+ driver = tmp_path / "driver.sh"+ driver.write_text(SH_DRIVER, encoding="utf-8", newline="\n")+ env = {**_base_env(), "BLOCK_FILE": str(block).replace("\\", "/"), **variables}+ result = _run([BASH, str(driver)], env)+ assert result.returncode == 0, result.stderr+ return result+++def _run_ps(tmp_path: Path, **variables: str) -> subprocess.CompletedProcess[str]:+ source = INSTALL_PS1.read_text(encoding="utf-8")+ match = re.search(r"^function Use-InstallOptionNames \{\r?\n.*?^\}\r?$", source, re.S | re.M)+ assert match is not None, "Use-InstallOptionNames vanished from install.ps1"+ assert re.search(r"^Use-InstallOptionNames\r?$", source, re.M), "the function is not called"+ function_file = tmp_path / "function.ps1"+ function_file.write_text(match.group(0), encoding="utf-8")+ driver = tmp_path / "driver.ps1"+ driver.write_text(PS_DRIVER, encoding="utf-8")+ env = {**_base_env(), "TEST_FUNCTION_FILE": str(function_file), **variables}+ result = _run(+ [+ POWERSHELL,+ "-NoProfile",+ "-NonInteractive",+ "-ExecutionPolicy",+ "Bypass",+ "-File",+ str(driver),+ ],+ env,+ )+ assert result.returncode == 0, result.stderr + result.stdout+ return result+++# ---------------------------------------------------------------------------+# install.sh+# ---------------------------------------------------------------------------+++@needs_bash+def test_install_sh_reads_every_option_under_the_new_prefix(tmp_path: Path) -> None:+ result = _run_sh(+ tmp_path, **{f"DODAIOS_INSTALL_{option}": f"new-{option}" for option in SH_OPTIONS}+ )++ assert _values(result.stdout) == {option: f"new-{option}" for option in SH_OPTIONS}+ # installer.py and every other child read the old spelling too.+ assert "CHILD|new-DIR" in result.stdout+ assert result.stderr == ""+++@needs_bash+def test_install_sh_keeps_reading_the_old_prefix(tmp_path: Path) -> None:+ result = _run_sh(tmp_path, JARVIS_INSTALL_DIR="old-dir", JARVIS_INSTALL_REF="old-ref")++ values = _values(result.stdout)+ assert values["DIR"] == "old-dir" and values["REF"] == "old-ref"+ assert values["REPO"] == "" and result.stderr == ""+++@needs_bash+def test_install_sh_lets_the_new_name_win_and_names_the_clash(tmp_path: Path) -> None:+ result = _run_sh(+ tmp_path, JARVIS_INSTALL_DIR="old-secret-dir", DODAIOS_INSTALL_DIR="new-secret-dir"+ )++ assert _values(result.stdout)["DIR"] == "new-secret-dir"+ assert "DODAIOS_INSTALL_DIR" in result.stderr and "JARVIS_INSTALL_DIR" in result.stderr+ assert "secret" not in result.stderr++++# ---------------------------------------------------------------------------+# install.ps1+# ---------------------------------------------------------------------------+++@needs_powershell+def test_install_ps1_reads_every_option_under_the_new_prefix(tmp_path: Path) -> None:+ result = _run_ps(+ tmp_path, **{f"DODAIOS_INSTALL_{option}": f"new-{option}" for option in PS_OPTIONS}+ )++ assert _values(result.stdout) == {option: f"new-{option}" for option in PS_OPTIONS}+ assert "NOTE|" not in result.stdout+++@needs_powershell+def test_install_ps1_keeps_reading_the_old_prefix(tmp_path: Path) -> None:+ result = _run_ps(tmp_path, JARVIS_INSTALL_DIR="old-dir")++ assert _values(result.stdout)["DIR"] == "old-dir"+ assert "NOTE|" not in result.stdout+++@needs_powershell+def test_install_ps1_lets_the_new_name_win_and_names_the_clash(tmp_path: Path) -> None:+ result = _run_ps(+ tmp_path, JARVIS_INSTALL_DIR="old-secret-dir", DODAIOS_INSTALL_DIR="new-secret-dir"+ )++ assert _values(result.stdout)["DIR"] == "new-secret-dir"+ notes = [line for line in result.stdout.splitlines() if line.startswith("NOTE|")]+ assert len(notes) == 1+ assert "DODAIOS_INSTALL_DIR" in notes[0] and "JARVIS_INSTALL_DIR" in notes[0]+ assert "secret" not in notes[0]++++# ---------------------------------------------------------------------------+# Both scripts, and the uninstallers, spell the same contract+# ---------------------------------------------------------------------------+++def test_the_two_installers_adopt_the_options_each_one_reads() -> None:+ shell = INSTALL_SH.read_text(encoding="utf-8")+ powershell = INSTALL_PS1.read_text(encoding="utf-8")+ assert f"for option in {' '.join(SH_OPTIONS)}; do" in shell+ assert "foreach ($Option in " + ", ".join(f"'{o}'" for o in PS_OPTIONS) + ")" in powershell+ # Every JARVIS_INSTALL_* option a script reads is one it also adopts.+ for source, adopted in ((shell, SH_OPTIONS), (powershell, PS_OPTIONS)):+ read = set(re.findall(r"JARVIS_INSTALL_([A-Z_]+)", source))+ assert read <= set(adopted), sorted(read - set(adopted))++[email protected]("path", [INSTALL_SH, INSTALL_PS1, UNINSTALL_SH, UNINSTALL_PS1])+def test_the_scripts_spell_the_prefixes_the_app_uses(path: Path) -> None:+ new_prefix, old_prefix = env_prefix._PREFIXES[0]+ source = path.read_text(encoding="utf-8")+ assert f"{new_prefix}INSTALL_" in source+ assert f"{old_prefix}INSTALL_" in source+++@needs_bash+ ("variables", "expected"),+ [+ ({"DODAIOS_INSTALL_DIR": "new-dir"}, "new-dir"),+ ({"JARVIS_INSTALL_DIR": "old-dir"}, "old-dir"),+ ({"JARVIS_INSTALL_DIR": "old-dir", "DODAIOS_INSTALL_DIR": "new-dir"}, "new-dir"),+ ({}, "HOME/.default"),+ ],+)+def test_the_shell_uninstaller_targets_the_directory_either_name_gives(+ tmp_path: Path, variables: dict[str, str], expected: str+) -> None:+ # The line that picks the directory: run exactly that, never the removal+ # below it.+ source = UNINSTALL_SH.read_text(encoding="utf-8")+ match = re.search(r"^INSTALL_DIR=[^\n]*\n", source, re.M)+ assert match is not None, "uninstall.sh no longer resolves INSTALL_DIR the tested way"+ script = tmp_path / "resolve.sh"+ script.write_text(+ "set -euo pipefail\n"+ 'HOME="HOME"\n'+ 'DEFAULT_INSTALL_DIR_NAME=".default"\n'+ + match.group(0)+ + 'printf "%s\\n" "$INSTALL_DIR"\n',+ encoding="utf-8",+ newline="\n",+ )++ result = _run([BASH, str(script)], {**_base_env(), **variables})++ assert result.returncode == 0, result.stderr+ assert result.stdout.strip() == expecteddiff --git a/tests/unit/packaging/test_frozen_runtime_hook.py b/tests/unit/packaging/test_frozen_runtime_hook.pyindex 7b4468b398..2d4c25c8a2 100644--- a/tests/unit/packaging/test_frozen_runtime_hook.py+++ b/tests/unit/packaging/test_frozen_runtime_hook.py@@ -21,6 +21,9 @@ from jarvis.core.paths import user_data_dirHOOK_PATH = Path(__file__).resolve().parents[3] / "packaging" / "pyinstaller_rthook_frozen.py"+# The hook moves DODAIOS_ variables to their JARVIS_ names on the real environment.+pytestmark = pytest.mark.usefixtures("prefixed_environment_restored")+def _load_hook() -> ModuleType:"""Import the hook as a module. Its top-level ``_apply()`` is a no-op here.diff --git a/tests/unit/ui/test_relauncher_fresh_env.py b/tests/unit/ui/test_relauncher_fresh_env.pyindex 344a84eebf..4f0ac4668d 100644--- a/tests/unit/ui/test_relauncher_fresh_env.py+++ b/tests/unit/ui/test_relauncher_fresh_env.py@@ -89,3 +89,59 @@ def test_main_spawns_the_new_launcher_with_the_fresh_env(monkeypatch):env = spawned[0]["kwargs"]["env"]assert env["JARVIS__TTS__VOICE_DE"] == "Charon"assert env["PATH"] == "/bin"+++def test_fresh_env_carries_an_override_persisted_under_the_new_prefix():+ # This process moved its own DODAIOS__* copy to the JARVIS__ spelling when+ # it started, so the inherited environment holds the old name only. The+ # registry is the fresher source and must reach the new process, where the+ # same move happens again.+ from jarvis.core.env_prefix import adopt_environment++ base = {"JARVIS__TTS__VOICE_DE": "Kore", "JARVIS__TTS__SEED": "7", "PATH": r"C:\bin"}+ persisted = {"DODAIOS__TTS__VOICE_DE": "Charon", "JARVIS__TTS__SEED": "9"}++ env = relauncher.fresh_user_env(base, _read_persisted=lambda: persisted)+ assert env["DODAIOS__TTS__VOICE_DE"] == "Charon"+ assert "JARVIS__TTS__VOICE_DE" not in env # the stale inherited value is gone++ assert adopt_environment(env) == () # what the new process does on import+ assert env == {+ "JARVIS__TTS__VOICE_DE": "Charon",+ "JARVIS__TTS__SEED": "9",+ "PATH": r"C:\bin",+ }+++def test_a_persisted_new_prefix_override_wins_over_its_persisted_old_spelling():+ from jarvis.core.env_prefix import adopt_environment++ persisted = {"JARVIS__BRAIN__PRIMARY": "gemini", "DODAIOS__BRAIN__PRIMARY": "openrouter"}++ env = relauncher.fresh_user_env({}, _read_persisted=lambda: persisted)++ assert adopt_environment(env) == ("DODAIOS__BRAIN__PRIMARY",)+ assert env == {"JARVIS__BRAIN__PRIMARY": "openrouter"}+++def test_an_override_deleted_from_the_persisted_env_does_not_survive_the_restart():+ # Started with DODAIOS__TTS__SEED=7, which became JARVIS__TTS__SEED; the+ # person has since removed it from the persisted environment.+ from jarvis.core.env_prefix import adopt_environment++ base = {"DODAIOS__TTS__SEED": "7"}+ adopt_environment(base)++ env = relauncher.fresh_user_env(base, _read_persisted=dict)++ assert env == {}+++def test_the_registry_reader_matches_both_prefixes():+ # The reader itself only runs on Windows against the real registry; this+ # pins the prefixes it filters on.+ import inspect++ assert relauncher._CONFIG_ENV_PREFIXES == ("DODAIOS__", "JARVIS__")+ reader = inspect.getsource(relauncher._read_windows_user_jarvis_env)+ assert "name.upper().startswith(_CONFIG_ENV_PREFIXES)" in reader