Skip to content

The agent that grows with you

feat(onboarding): one machine-level answer to "has Hermes been used here"

alt-glitch88be7bd28f46
diff --git a/hermes_cli/gateway_service_owner.py b/hermes_cli/gateway_service_owner.py
index 9801438d616..ea33d762489 100644
--- a/hermes_cli/gateway_service_owner.py
+++ b/hermes_cli/gateway_service_owner.py
@@ -97,13 +97,21 @@ def unit_belongs_to_caller(unit_path: Path, system: bool, action: str, run_as_us
return definition_belongs_to_home(unit_path, home, action)
+def service_definition_homes(definition: str) -> list[str]:
+ """Every HERMES_HOME a gateway service definition sets: systemd ``Environment=``, launchd
+ ``EnvironmentVariables``, the Windows ``gateway.cmd`` ``set`` line and the ``gateway.vbs`` env item."""
+ import re
+ homes = re.findall(r'HERMES_HOME=([^"\r\n]+)', definition)
+ homes += re.findall(r"<key>HERMES_HOME</key>\s*<string>(.*?)</string>", definition, flags=re.DOTALL)
+ homes += re.findall(r'Item\("HERMES_HOME"\)\s*=\s*"([^"\r\n]+)"', definition)
+ return homes
+
+
def temp_home_in_service_definition(definition: str) -> str | None:
"""Temp-dir HERMES_HOME baked into a systemd unit / launchd plist, or None. A temp home means a
test/E2E harness generated it; installing it leaves the gateway "running" but deaf to every platform."""
- import re
import tempfile
- candidates = re.findall(r'HERMES_HOME=([^"\n]+)', definition)
- candidates += re.findall(r"<key>HERMES_HOME</key>\s*<string>(.*?)</string>", definition, flags=re.DOTALL)
+ candidates = service_definition_homes(definition)
temp_roots = {
Path(tempfile.gettempdir()).resolve(),
Path("/tmp"), Path("/var/tmp"), Path("/private/tmp"), Path("/private/var/tmp"), # no-tmp: ok — detects a temp HERMES_HOME in service definitions
diff --git a/hermes_cli/install_state.py b/hermes_cli/install_state.py
new file mode 100644
index 00000000000..39cbcda318d
--- /dev/null
+++ b/hermes_cli/install_state.py
@@ -0,0 +1,357 @@
+"""Has someone already used Hermes on this machine?
+
+The desktop's welcome trial goes only to a first install, so ``onboarding.start`` asks this before it
+claims one. The answer is about the machine and the OS user, not the active profile: it looks at
+every Hermes root the machine names (default roots, channel and package roots, the roots gateway
+services and the ``hermes`` launcher point at) and at a marker file no Hermes setting can move.
+
+This is product gating, not security: the inference API's limits stop abuse. So it reads only small
+known files, never scans the disk, never writes into a Hermes root, and treats doubt as "used".
+"""
+
+from __future__ import annotations
+
+import contextlib
+import enum
+import json
+import os
+import sqlite3
+import sys
+from collections.abc import Callable, Iterable, Iterator
+from dataclasses import dataclass
+from functools import cache, cached_property
+from glob import glob
+from pathlib import Path
+from typing import Any
+
+_MAX_FILE_BYTES = 1 << 20
+
+
+class Evidence(enum.Enum):
+ """Why the machine counts as used. For logs and tests; never shown to users."""
+
+ MACHINE_MARKER = "machine-marker" # an earlier probe or trial claim on this machine
+ ONBOARDING_DONE = "onboarding-done" # a root's config has ``onboarding.run: false``
+ NAMED_PROFILE = "named-profile" # a live profile someone created
+ PROVIDER_CONFIG = "provider-config" # config.yaml picks a provider other than auto
+ PROVIDER_KEY = "provider-key" # .env holds a provider, tool, messaging or skill key
+ PROVIDER_LOGIN = "provider-login" # auth.json / nous_auth.json holds a login or a guest
+ MESSAGES = "messages" # state.db holds a message
+ UNREADABLE = "unreadable" # a root we could not, or must not, read
+
+
+@dataclass(frozen=True, slots=True)
+class Finding:
+ evidence: Evidence
+ where: Path
+
+
+@dataclass(frozen=True, slots=True)
+class InstallState:
+ findings: tuple[Finding, ...]
+
+ @property
+ def existing(self) -> bool:
+ return bool(self.findings)
+
+ @property
+ def fresh(self) -> bool:
+ return not self.findings
+
+
+Source = Callable[[], Iterable[Path]]
+
+
+@dataclass(frozen=True, slots=True)
+class Places:
+ """Where to look. ``markers[0]`` is the marker this process writes; every entry is read."""
+
+ markers: tuple[Path, ...]
+ sources: tuple[Source, ...]
+ protected: tuple[Path, ...] = ()
+
+ @classmethod
+ def of_this_machine(cls) -> Places:
+ from hermes_platform.resolver import known_dirs
+
+ return cls(
+ markers=tuple(_expand_all(known_dirs.machine_marker_files())),
+ sources=(_active_root, _home_globs, _shared_auth_dir, _registry_home, _service_homes, _launcher_root),
+ protected=tuple(_expand_all(known_dirs.mac_privacy_protected_dirs())),
+ )
+
+
+def machine_places() -> Places:
+ """The seam tests replace; production always looks at the real machine."""
+ return Places.of_this_machine()
+
+
+@cache
+def probe() -> InstallState:
+ """One answer per process (the first finding wins). :func:`mark_machine_used` clears it."""
+ places = machine_places()
+ if marker := next((m for m in places.markers if m.is_file()), None):
+ return InstallState((Finding(Evidence.MACHINE_MARKER, marker),))
+ for root in candidate_roots(places):
+ if finding := root_evidence(root, places):
+ if finding.evidence is not Evidence.UNREADABLE: # doubt blocks the trial, never marks
+ mark_machine_used()
+ return InstallState((finding,))
+ return InstallState(())
+
+
+def existing_install() -> bool:
+ return probe().existing
+
+
+def mark_machine_used() -> None:
+ """Record that this machine has a used install, or just claimed the trial. Atomic, idempotent."""
+ places = machine_places()
+ if places.markers:
+ marker = places.markers[0]
+ marker.parent.mkdir(parents=True, exist_ok=True)
+ tmp = marker.with_name(marker.name + ".tmp")
+ tmp.write_text("{}\n", encoding="utf-8")
+ tmp.replace(marker)
+ probe.cache_clear()
+
+
+# ── where to look ─────────────────────────────────────────────────────────────────────────────
+
+
+def candidate_roots(places: Places) -> Iterator[Path]:
+ """Each named root once, existing directories only. A root inside a protected folder is yielded
+ unresolved: :func:`root_evidence` reports it without touching it."""
+ seen: set[Path] = set()
+ for source in places.sources:
+ for raw in source():
+ path = Path(os.path.abspath(os.path.expanduser(str(raw))))
+ if not _is_protected(path, places):
+ try:
+ path = path.resolve()
+ except OSError:
+ continue
+ if not path.is_dir():
+ continue
+ if path not in seen:
+ seen.add(path)
+ yield path
+
+
+def _is_protected(path: Path, places: Places) -> bool:
+ return any(path == p or p in path.parents for p in places.protected)
+
+
+def _expand_all(patterns: Iterable[str]) -> Iterator[Path]:
+ """Expand ``~`` and environment variables (``$X`` on POSIX, ``%X%`` on Windows), then globs. An
+ entry naming an unset variable is dropped."""
+ for pattern in patterns:
+ expanded = os.path.expanduser(os.path.expandvars(pattern))
+ if "$" in expanded or "%" in expanded:
+ continue
+ if any(ch in expanded for ch in "*?["):
+ yield from (Path(hit) for hit in sorted(glob(expanded)))
+ else:
+ yield Path(expanded)
+
+
+def _active_root() -> Iterable[Path]:
+ from hermes_constants import _get_platform_default_hermes_home, get_default_hermes_root
+
+ return (get_default_hermes_root(), _get_platform_default_hermes_home())
+
+
+def _home_globs() -> Iterable[Path]:
+ from hermes_platform.resolver import known_dirs
+
+ return _expand_all(known_dirs.hermes_home_globs())
+
+
+def _shared_auth_dir() -> Iterable[Path]:
+ raw = os.environ.get("HERMES_SHARED_AUTH_DIR", "").strip()
+ return (Path(raw),) if raw else ()
+
+
+def _registry_home() -> Iterable[Path]:
+ """The ``HERMES_HOME`` older Windows installers saved for the user (the desktop honours it)."""
+ if sys.platform != "win32":
+ return ()
+ import winreg
+
+ try:
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment") as key:
+ value, _kind = winreg.QueryValueEx(key, "HERMES_HOME")
+ except OSError:
+ return ()
+ return (Path(os.path.expandvars(str(value))),) if str(value).strip() else ()
+
+
+def _service_homes() -> Iterable[Path]:
+ from hermes_cli.gateway_service_owner import service_definition_homes
+ from hermes_platform.resolver import known_dirs
+
+ for definition in _expand_all(known_dirs.gateway_service_definition_globs()):
+ with contextlib.suppress(OSError, UnicodeError, ValueError):
+ yield from (Path(home.strip().strip('"')) for home in service_definition_homes(_read_text(definition)))
+
+
+def _launcher_root() -> Iterable[Path]:
+ """The root that owns the ``hermes`` on PATH: its launcher execs that root's ``tools/`` Python."""
+ from hermes_cli._launchers import _launcher_python
+ from hermes_platform.resolver import locate_command
+
+ found = locate_command("hermes").command
+ if not found:
+ return ()
+ launcher = Path(found[0]).resolve()
+ python = _launcher_python(launcher)
+ owners = [p.parent for p in (python.parents if python else ()) if p.name == "tools"]
+ if not owners and launcher.parent.name == "bin" and launcher.parent.parent.name == ".hermes":
+ owners = [launcher.parent.parent.parent.parent] # <root>/<checkout>/.hermes/bin/hermes
+ return owners[:1]
+
+
+# ── what counts as used, per root ─────────────────────────────────────────────────────────────
+
+
+def root_evidence(root: Path, places: Places) -> Finding | None:
+ if _is_protected(root, places):
+ return Finding(Evidence.UNREADABLE, root)
+ home = _Root(root)
+ for evidence, check in CHECKS:
+ try:
+ if check(home):
+ return Finding(evidence, root)
+ except (OSError, ValueError, UnicodeError, sqlite3.Error):
+ return Finding(Evidence.UNREADABLE, root)
+ return None
+
+
+class _Root:
+ """One root's files, each read at most once. No ``load_config``: it writes SOUL.md and the
+ directory skeleton into the root it reads."""
+
+ def __init__(self, path: Path) -> None:
+ self.path = path
+
+ @cached_property
+ def config(self) -> dict[str, Any]:
+ return _read_mapping(self.path / "config.yaml", _parse_yaml)
+
+ @cached_property
+ def auth_stores(self) -> tuple[dict[str, Any], ...]:
+ # The shared-auth override names the directory itself, so its file sits at the top.
+ names = ("auth.json", "shared/nous_auth.json", "nous_auth.json")
+ return tuple(_read_mapping(self.path / name, json.loads) for name in names)
+
+
+def _onboarding_done(home: _Root) -> bool:
+ section = home.config.get("onboarding")
+ return isinstance(section, dict) and section.get("run") is False
+
+
+def _named_profile(home: _Root) -> bool:
+ from hermes_constants import PROFILE_ID_RE, named_profile_has_identity, named_profile_is_deleted
+
+ profiles = home.path / "profiles"
+ return profiles.is_dir() and any(
+ entry.is_dir() and entry.name != "default" and PROFILE_ID_RE.match(entry.name)
+ and named_profile_has_identity(entry) and not named_profile_is_deleted(entry)
+ for entry in profiles.iterdir())
+
+
+def _provider_config(home: _Root) -> bool:
+ model = home.config.get("model")
+ provider = model.get("provider") if isinstance(model, dict) else None
+ return isinstance(provider, str) and provider.strip() not in ("", "auto")
+
+
+# A deployment secret, not something a user entered.
+_IGNORED_ENV_KEYS = frozenset({"HERMES_ANON_API_SECRET"})
+_USER_ENV_CATEGORIES = frozenset({"provider", "tool", "messaging", "skill"})
+
+
+def _provider_key(home: _Root) -> bool:
+ from hermes_cli.config_defaults import OPTIONAL_ENV_VARS
+
+ path = home.path / ".env"
+ if not path.is_file():
+ return False
+ return any(value and key not in _IGNORED_ENV_KEYS
+ and (OPTIONAL_ENV_VARS.get(key) or {}).get("category") in _USER_ENV_CATEGORIES
+ for key, value in _parse_dotenv(_read_text(path)).items())
+
+
+def _provider_login(home: _Root) -> bool:
+ """A login, an active provider or a guest (only a connector action or a trial claim makes one),
+ or a credential the user added by hand. Pool rows Hermes seeds on its own (shell env keys, other
+ tools' CLI logins) prove nothing."""
+ for store in home.auth_stores:
+ providers = store.get("providers")
+ if store.get("active_provider") or (isinstance(providers, dict) and any(providers.values())):
+ return True
+ if store.get("auth_method") or store.get("anon_token") or store.get("refresh_token"):
+ return True # nous_auth.json holds one provider state at its top level
+ pool = store.get("credential_pool")
+ rows = (row for rows in (pool.values() if isinstance(pool, dict) else ()) if isinstance(rows, list)
+ for row in rows if isinstance(row, dict))
+ if any(str(row.get("source", "")).split(":", 1)[0] == "manual" for row in rows):
+ return True
+ return False
+
+
+def _messages(home: _Root) -> bool:
+ db = home.path / "state.db"
+ if not db.is_file():
+ return False
+ # Read-only URI, never the state registry: that opens a writer and migrates a schema we do not own.
+ with contextlib.closing(sqlite3.connect(f"{db.as_uri()}?mode=ro", uri=True, timeout=1)) as conn:
+ if conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='messages'").fetchone() is None:
+ return False
+ return conn.execute("SELECT 1 FROM messages LIMIT 1").fetchone() is not None
+
+
+CHECKS: tuple[tuple[Evidence, Callable[[_Root], bool]], ...] = (
+ (Evidence.ONBOARDING_DONE, _onboarding_done),
+ (Evidence.NAMED_PROFILE, _named_profile),
+ (Evidence.PROVIDER_CONFIG, _provider_config),
+ (Evidence.PROVIDER_KEY, _provider_key),
+ (Evidence.PROVIDER_LOGIN, _provider_login),
+ (Evidence.MESSAGES, _messages), # last: the only check that opens a database
+)
+
+
+# ── small readers ─────────────────────────────────────────────────────────────────────────────
+
+
+def _read_text(path: Path) -> str:
+ if path.stat().st_size > _MAX_FILE_BYTES:
+ raise ValueError(f"{path} is larger than {_MAX_FILE_BYTES} bytes")
+ return path.read_text(encoding="utf-8-sig")
+
+
+def _read_mapping(path: Path, parse: Callable[[str], Any]) -> dict[str, Any]:
+ if not path.is_file():
+ return {}
+ data = parse(_read_text(path))
+ return data if isinstance(data, dict) else {}
+
+
+def _parse_yaml(text: str) -> Any:
+ import hermes_yaml
+
+ try:
+ return hermes_yaml.safe_load(text)
+ except hermes_yaml.YAMLError as exc:
+ raise ValueError(str(exc)) from exc
+
+
+def _parse_dotenv(text: str) -> dict[str, str]:
+ pairs: dict[str, str] = {}
+ for line in text.splitlines():
+ line = line.strip()
+ if not line or line.startswith("#") or "=" not in line:
+ continue
+ key, value = line.removeprefix("export ").split("=", 1)
+ pairs[key.strip()] = value.strip().strip("'\"")
+ return pairs
diff --git a/hermes_cli/onboarding_run.py b/hermes_cli/onboarding_run.py
index fe6830dd041..76a5879c90a 100644
--- a/hermes_cli/onboarding_run.py
+++ b/hermes_cli/onboarding_run.py
@@ -3,60 +3,33 @@
The flag lives in the ROOT profile's ``config.yaml`` (``get_default_hermes_root()``), never in the
launch profile's: a pooled backend launched under ``-p work`` must read and write the same file as
one launched under ``default``, because onboarding always targets the default profile.
-Unset means "only on a fresh install"; ``true`` re-runs it once; ``false`` means done.
+Unset means "only on a machine that never used Hermes"; ``true`` re-runs it once; ``false`` means done.
"""
from __future__ import annotations
from pathlib import Path
-from hermes_constants import (
- PROFILE_ID_RE,
- get_default_hermes_root,
- named_profile_has_identity,
- named_profile_is_deleted,
-)
+from hermes_constants import get_default_hermes_root
+
def _root_config() -> Path:
return get_default_hermes_root() / "config.yaml"
-def install_has_history(root: Path) -> bool:
- """A session row in the root ``state.db``, or a named profile the user made. A fresh boot
- creates neither: it leaves an empty ``state.db``, ``auth.json`` (the free-tier mint) and
- ``SOUL.md``, which is why the signal is a session row and not a file."""
- if _named_profiles(root):
- return True
- db_path = root / "state.db"
- if not db_path.is_file():
- return False
- from hermes_state_registry import acquire, release_or_close
- db = acquire(db_path)
- try:
- return db.session_count_ge(1)
- finally:
- release_or_close(db)
-
-
-def _named_profiles(root: Path) -> list[Path]:
- """Live named profiles under *root*, with the same filter as ``profiles._iter_named_profile_dirs``."""
- profiles = root / "profiles"
- if not profiles.is_dir():
- return []
- return [entry for entry in profiles.iterdir()
- if entry.is_dir() and entry.name != "default" and PROFILE_ID_RE.match(entry.name)
- and named_profile_has_identity(entry) and not named_profile_is_deleted(entry)]
-
-
def should_run() -> bool:
"""The root config's explicit ``onboarding.run`` (managed overlay included) when it is a bool,
- else whether the install is fresh."""
+ else whether this machine has never used Hermes (``install_state``)."""
from hermes_cli.config_effective import load_user_config_effective
# Not load_config(): it resolves the launch profile and fills the default None for an unset flag.
section = load_user_config_effective(_root_config()).get("onboarding")
value = section.get("run") if isinstance(section, dict) else None
- return value if isinstance(value, bool) else not install_has_history(get_default_hermes_root())
+ if isinstance(value, bool):
+ return value
+ from hermes_cli.install_state import probe
+
+ return probe().fresh
def set_run(value: bool, *, mark_profile_offered: bool = False) -> None:
diff --git a/hermes_platform/resolver/known_dirs.py b/hermes_platform/resolver/known_dirs.py
index 3225a6ca144..fe0959eb2f7 100644
--- a/hermes_platform/resolver/known_dirs.py
+++ b/hermes_platform/resolver/known_dirs.py
@@ -33,6 +33,44 @@ def hermes_vendored_dirs() -> tuple[str, ...]:
return ("~/.hermes/bin",) if _POSIX else ("%USERPROFILE%/.hermes/bin",)
+def machine_marker_files() -> tuple[str, ...]:
+ """Where Hermes records that this OS user has used it. No Hermes data-dir setting moves these.
+ The first entry is the one written; the rest are read too (Windows: MSIX builds that ran with
+ filesystem virtualisation wrote under the package's LocalCache)."""
+ if _WIN:
+ return ("%LOCALAPPDATA%/Nous Research/.machine",
+ "%LOCALAPPDATA%/Packages/NousResearch*_*/LocalCache/Local/Nous Research/.machine")
+ if sys.platform == "darwin":
+ return ("~/Library/Application Support/Nous Research/.machine",)
+ return ("$XDG_STATE_HOME/nous-research/.machine", "~/.local/state/nous-research/.machine")
+
+
+def hermes_home_globs() -> tuple[str, ...]:
+ """Every place a Hermes data root can sit by default: suffixed channel roots, the legacy Windows
+ root, and the per-package roots of MSIX builds that ran with filesystem virtualisation."""
+ if _WIN:
+ return ("%LOCALAPPDATA%/hermes*", "%USERPROFILE%/.hermes",
+ "%LOCALAPPDATA%/Packages/NousResearch*_*/LocalCache/Local/hermes*")
+ return ("~/.hermes*",)
+
+
+def gateway_service_definition_globs() -> tuple[str, ...]:
+ """Gateway service definitions, each naming the HERMES_HOME it serves."""
+ if _WIN:
+ return ("%APPDATA%/Microsoft/Windows/Start Menu/Programs/Startup/Hermes_Gateway*",)
+ if sys.platform == "darwin":
+ return ("~/Library/LaunchAgents/ai.hermes.gateway*.plist",)
+ return ("$XDG_CONFIG_HOME/systemd/user/hermes-gateway*.service", "~/.config/systemd/user/hermes-gateway*.service",
+ "/etc/systemd/system/hermes-gateway*.service")
+
+
+def mac_privacy_protected_dirs() -> tuple[str, ...]:
+ """Folders macOS guards with a permission prompt (TCC); opening anything inside raises it."""
+ if sys.platform != "darwin":
+ return ()
+ return ("~/Documents", "~/Desktop", "~/Downloads", "~/Library/Mobile Documents") # windows-footgun: ok — macOS only
+
+
def windows_user_program_dirs() -> tuple[str, ...]:
if not _WIN:
return ()
diff --git a/tests/conftest.py b/tests/conftest.py
index 025f7a88173..255e7013276 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -309,6 +309,14 @@ def _hermetic_environment(tmp_path, tmp_path_factory, monkeypatch):
monkeypatch.setattr(_hc, "_PINNED_PROCESS_HERMES_HOME", None, raising=False)
except Exception:
pass
+ # The install probe looks past HERMES_HOME (other roots, gateway services, the launcher on
+ # PATH) and writes a marker at a fixed per-user path: confine it to this test's directory.
+ from hermes_cli import install_state
+
+ isolated_places = install_state.Places(markers=(tmp_path / "machine-marker",),
+ sources=(install_state._active_root,))
+ monkeypatch.setattr(install_state, "machine_places", lambda: isolated_places)
+ install_state.probe.cache_clear()
# Per-TEST host-rendezvous dir (see the session-level block at the top): the
# host gateway/serve record is shared per OS user by design, so without this
# one test's published owner makes the next test's lifecycle code attach to it.
diff --git a/tests/hermes_cli/test_install_state.py b/tests/hermes_cli/test_install_state.py
new file mode 100644
index 00000000000..70e6f3499f4
--- /dev/null
+++ b/tests/hermes_cli/test_install_state.py
@@ -0,0 +1,118 @@
+"""Behaviour of the machine-level install probe (``hermes_cli.install_state``)."""
+
+import json
+import sqlite3
+from pathlib import Path
+
+import pytest
+
+from hermes_cli import install_state
+from hermes_cli.install_state import Evidence, Places
+
+
+def machine(tmp_path, monkeypatch):
+ """An empty active root (``HERMES_HOME``) plus one other root the probe is told about."""
+ active = tmp_path / "active"
+ other = tmp_path / "other-root"
+ active.mkdir()
+ other.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(active))
+ places = Places(markers=(tmp_path / "state" / ".machine",),
+ sources=(install_state._active_root, lambda: (other,)))
+ monkeypatch.setattr(install_state, "machine_places", lambda: places)
+ install_state.probe.cache_clear()
+ yield other, places
+ install_state.probe.cache_clear()
+
+
+def _messages_db(path: Path) -> None:
+ with sqlite3.connect(path) as conn:
+ conn.execute("CREATE TABLE sessions (id TEXT PRIMARY KEY)")
+ conn.execute("CREATE TABLE messages (id INTEGER PRIMARY KEY, session_id TEXT, content TEXT)")
+ conn.execute("INSERT INTO messages (session_id, content) VALUES ('s', 'hi')")
+ conn.close()
+
+
+USE = {
+ Evidence.ONBOARDING_DONE: lambda r: (r / "config.yaml").write_text("onboarding:\n run: false\n", encoding="utf-8"),
+ Evidence.NAMED_PROFILE: lambda r: ((r / "profiles" / "work").mkdir(parents=True),
+ (r / "profiles" / "work" / "config.yaml").write_text("{}\n", encoding="utf-8")),
+ Evidence.PROVIDER_CONFIG: lambda r: (r / "config.yaml").write_text("model:\n provider: openrouter\n", encoding="utf-8"),
+ Evidence.PROVIDER_KEY: lambda r: (r / ".env").write_text("OPENROUTER_API_KEY=sk-test\n", encoding="utf-8"),
+ Evidence.PROVIDER_LOGIN: lambda r: (r / "auth.json").write_text(json.dumps(
+ {"providers": {"nous": {"auth_method": "anonymous", "anon_token": "anon_x"}}}), encoding="utf-8"),
+ Evidence.MESSAGES: lambda r: _messages_db(r / "state.db"),
+}
+
+
+def test_a_machine_with_only_install_time_files_is_fresh(machine):
+ other, places = machine
+ # What installers and a first boot write: template config, example .env keys, an empty state.db,
+ # pool rows Hermes seeded from the shell, the PM boot record.
+ (other / "config.yaml").write_text("_config_version: 50\nmodel:\n default: x\n provider: auto\n", encoding="utf-8")
+ (other / ".env").write_text("TERMINAL_ENV=local\n# OPENROUTER_API_KEY=\n", encoding="utf-8")
+ (other / "auth.json").write_text(json.dumps({"credential_pool": {"openrouter": [{"source": "env:OPENROUTER_API_KEY"}]}}), encoding="utf-8")
+ sqlite3.connect(other / "state.db").execute("CREATE TABLE messages (id INTEGER)").connection.close()
+ (other / "installs" / "k" / "bootstrap").mkdir(parents=True)
+ (other / "installs" / "k" / "bootstrap" / "default.json").write_text("{}", encoding="utf-8")
+
+ assert install_state.probe().fresh
+ assert not places.markers[0].exists()
+
+
[email protected]("evidence", list(USE))
+def test_use_in_another_root_beats_an_empty_hermes_home_and_marks_the_machine(machine, evidence):
+ other, places = machine
+ USE[evidence](other)
+
+ state = install_state.probe()
+
+ assert [(f.evidence, f.where) for f in state.findings] == [(evidence, other.resolve())]
+ assert places.markers[0].is_file()
+ # The marker answers for the machine from now on, even once that root is gone.
+ for child in sorted(other.rglob("*"), reverse=True):
+ child.unlink() if child.is_file() else child.rmdir()
+ install_state.probe.cache_clear()
+ assert install_state.probe().findings[0].evidence is Evidence.MACHINE_MARKER
+
+
+def test_an_unreadable_root_counts_as_existing_but_never_marks(machine):
+ other, places = machine
+ (other / "config.yaml").write_text("model: [unclosed\n", encoding="utf-8")
+
+ state = install_state.probe()
+
+ assert state.existing and state.findings[0].evidence is Evidence.UNREADABLE
+ assert not places.markers[0].exists()
+
+
+def test_a_root_in_a_protected_folder_is_existing_without_being_opened(machine, tmp_path, monkeypatch):
+ _other, places = machine
+ protected = tmp_path / "Documents"
+ places = Places(markers=places.markers, sources=(lambda: (protected / "hermes-home",),),
+ protected=(protected,))
+ monkeypatch.setattr(install_state, "machine_places", lambda: places)
+
+ assert install_state.probe().findings[0].evidence is Evidence.UNREADABLE
+
+
+def test_claiming_marks_the_machine_and_the_next_probe_sees_it(machine):
+ assert install_state.probe().fresh
+
+ install_state.mark_machine_used()
+
+ assert install_state.existing_install()
+
+
+def test_gateway_service_definitions_name_their_homes(tmp_path, monkeypatch):
+ home = tmp_path / "gw-home"
+ unit = tmp_path / "hermes-gateway.service"
+ unit.write_text(f'[Service]\nEnvironment="HERMES_HOME={home}"\n', encoding="utf-8")
+ vbs = tmp_path / "Hermes_Gateway.vbs"
+ vbs.write_text(f'env.Item("HERMES_HOME") = "{home}-win"\r\n', encoding="utf-8")
+ from hermes_platform.resolver import known_dirs
+ monkeypatch.setattr(known_dirs, "gateway_service_definition_globs", lambda: (str(tmp_path / "*Gateway*"),
+ str(tmp_path / "*gateway*")))
+
+ assert set(install_state._service_homes()) == {home, Path(f"{home}-win")}
diff --git a/tests/hermes_cli/test_onboarding_run.py b/tests/hermes_cli/test_onboarding_run.py
index bda06ebf38d..67b958b30a5 100644
--- a/tests/hermes_cli/test_onboarding_run.py
+++ b/tests/hermes_cli/test_onboarding_run.py
@@ -1,5 +1,5 @@
"""``onboarding.run`` lives in the root profile's config.yaml: unset runs onboarding only on a
-fresh install, an explicit bool wins, and a backend launched under a named profile reads and writes
+machine that never used Hermes, an explicit bool wins, and a backend launched under a named profile reads and writes
the same root file."""
from __future__ import annotations
@@ -22,10 +22,11 @@ def root(tmp_path, monkeypatch) -> Path:
return home
-def _add_session(home: Path) -> None:
+def _add_chat(home: Path) -> None:
db = SessionDB(home / "state.db")
try:
db.create_session("old-session", "desktop")
+ db.append_message("old-session", "user", "hello")
finally:
db.close()
@@ -44,8 +45,17 @@ def test_fresh_install_runs(root):
assert onboarding_run.should_run() is True
-def test_root_with_a_session_does_not_run(root):
- _add_session(root)
+def test_an_empty_session_row_is_not_use(root):
+ # Desktop resume and onboarding.start both write a session row before any message.
+ db = SessionDB(root / "state.db")
+ db.create_session("minted", "desktop")
+ db.close()
+
+ assert onboarding_run.should_run() is True
+
+
+def test_root_with_a_chat_does_not_run(root):
+ _add_chat(root)
assert onboarding_run.should_run() is False
@@ -69,7 +79,7 @@ def test_a_managed_run_false_wins_on_a_fresh_install(root, tmp_path, monkeypatch
def test_explicit_true_runs_despite_history(root):
- _add_session(root)
+ _add_chat(root)
onboarding_run.set_run(True)
assert onboarding_run.should_run() is True