Skip to content

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

feat(hermes): add gateway memory presets and sender attribution (#5293)

z1gon9f21385993b2
diff --git a/examples/hermes-plugin/DEVELOPMENT.md b/examples/hermes-plugin/DEVELOPMENT.md
index 1e40cbb15..b3889ab9e 100644
--- a/examples/hermes-plugin/DEVELOPMENT.md
+++ b/examples/hermes-plugin/DEVELOPMENT.md
@@ -23,6 +23,16 @@ The active-session commit lifecycle was ported from
with the original author retained. The OpenViking adaptation uses a configurable
pending-token threshold instead of the original six-turn trigger.
+Gateway sender attribution and recall scope adapt
+[Hermes PR #105812](https://github.com/NousResearch/hermes-agent/pull/105812),
+including liuhao1024's capture change from
+[PR #98506](https://github.com/NousResearch/hermes-agent/pull/98506), with the
+original author retained. The adaptation uses Hermes's existing per-turn author
+hooks and preserves the original sender-ID encoding and Personal/Shared setup
+presets. Shared Agent changes gateway session settings only after confirmation;
+Personal Agent preserves them. An upgrade with no recall scope set retains the
+previous recall requests. No Hermes core patch is required.
+
## Migration coordination
After this directory is merged, submit a Hermes catalog entry with:
@@ -37,8 +47,8 @@ bundled provider. Hermes PR [#114569](https://github.com/NousResearch/hermes-age
adds catalog recovery for configured providers that no longer resolve. The
bundled provider takes precedence while it remains present.
-This import does not add a Desktop `config_schema.py` or change the setup wizard.
-The wizard still uses private helpers from `hermes_cli.memory_setup`; changes to
+This plugin does not add a Desktop `config_schema.py`.
+The wizard uses private helpers from `hermes_cli.memory_setup`; changes to
those helpers require compatibility checks. The plugin uses HTTP and does not
install or package the OpenViking server.
@@ -57,7 +67,12 @@ PYTHONPATH="$PWD${PYTHONPATH:+:$PYTHONPATH}" HERMES_TEST_FILE_RETRIES=0 \
Hermes loads it under its own namespace. The tests use temporary profile homes
and remove bundled-provider discovery.
They check external loading across profiles, HTTP tool dispatch, and cancelled
-setup without changing existing configuration. Run the upstream OpenViking
+setup without changing existing configuration. Gateway tests use mock events
+through Hermes's turn hooks and memory manager. They cover sender changes,
+capture retries, commits, recall scopes, compression fallback, and missing
+sender metadata. Setup tests cover both presets, confirmation, cancellation,
+profile-local persistence, connection routes, and actual Hermes session keys.
+Run the upstream OpenViking
provider tests in Hermes as well when changing provider behavior:
```bash
diff --git a/examples/hermes-plugin/README.md b/examples/hermes-plugin/README.md
index f9e5248c8..2580163c0 100644
--- a/examples/hermes-plugin/README.md
+++ b/examples/hermes-plugin/README.md
@@ -89,6 +89,24 @@ The setup can link to an existing `~/.openviking/ovcli.conf`, copy its current
connection values into Hermes, or create a minimal `ovcli.conf` when one does
not exist.
+Setup first asks how the Hermes instance is used:
+
+| Preset | Hermes conversation history | OpenViking long-term recall |
+|--------|-----------------------------|-----------------------------|
+| **Personal Agent** | Keeps existing group/thread session settings | Common memory and the current sender's memory (`peer`) |
+| **Shared Agent** | Shares each group or thread session between its participants | Common memory and all sender memories under the same OpenViking user (`shared`) |
+
+Shared Agent requires confirmation before it sets `group_sessions_per_user` and
+`thread_sessions_per_user` to `false`. Different groups still have separate
+conversation histories. Restart the gateway to apply changed session settings.
+Personal Agent does not make an already shared conversation private.
+
+Both presets retain sender attribution during capture. After commit and
+extraction, OpenViking can recall those memories across chats according to the
+chosen scope. Upgrading the plugin alone does not apply a preset or change
+session settings. Rerunning setup preselects the saved recall choice; a new
+setup starts on Personal Agent.
+
Or manually:
```bash
@@ -167,6 +185,55 @@ Set `agent: hermes` to restore peer-scoped writes. Memories written at user
scope before this change stay there and remain searchable. This setting
changes future writes, not the location of existing memories.
+### Gateway senders and automatic recall
+
+The external provider attaches the current gateway sender to captured user
+messages as a peer, for example `telegram.123456`. The OpenViking account and
+user stay unchanged. Assistant messages keep the configured `agent` peer.
+CLI messages without a gateway sender keep their existing user-level attribution.
+Existing memories are not moved.
+
+The setup presets save the automatic recall scope. You can also set it in the
+active profile's `config.yaml`:
+
+```yaml
+memory:
+ openviking:
+ recall_scope: peer
+```
+
+| Value | Automatic recall |
+|-------|------------------|
+| `shared` | Common memory and all peer memories under the same OpenViking user. |
+| `peer` | Common memory and the current gateway sender's memory. With no sender, only common memory is recalled. |
+
+With no scope set, the provider preserves the previous requests: normally
+shared recall, but an explicitly configured assistant peer can narrow list
+recall. Existing compression behavior is also retained. This is compatibility
+handling for existing installations, not a third setup mode. Invalid values
+warn and preserve that behavior.
+
+`OPENVIKING_RECALL_SCOPE` overrides YAML. On successful setup, the wizard removes
+this override from the profile's `.env` so the selected preset takes effect.
+An override supplied again by a service or shell still takes precedence.
+The configuration schema exposes only `shared` and `peer`. A stable
+alternate sender ID is used when Hermes supplies one; unsafe IDs are encoded
+to valid peer IDs. Queued captures retain their own sender when another
+participant sends a turn.
+
+The scope applies to automatic query recall, including compression and search
+fallbacks. If an older server cannot confirm sender-scoped compression, the
+provider uses scoped list recall. Enabled resource recall includes common
+resources and, in `peer` mode, the sender's resources.
+
+This is a retrieval setting, not an access-control boundary. It does not filter
+shared conversation history or change explicit `viking_*` tools, native memory
+mirroring, or credentials. Setting `recall_scope` alone does not change gateway
+sessions; the confirmed Shared Agent setup preset applies those settings.
+Explicit tools retain
+the configured assistant view. Use separate OpenViking users and credentials
+when participants require separate access rights.
+
## Tools
| Tool | Description |
diff --git a/examples/hermes-plugin/__init__.py b/examples/hermes-plugin/__init__.py
index c1482bb21..e3d286f0f 100644
--- a/examples/hermes-plugin/__init__.py
+++ b/examples/hermes-plugin/__init__.py
@@ -28,6 +28,7 @@ import time
import uuid
import zipfile
from contextlib import suppress
+from contextvars import ContextVar
from dataclasses import dataclass, field, replace
from functools import lru_cache
from pathlib import Path
@@ -89,6 +90,8 @@ _CONFIG_SCHEMA = [
_cfg_field("account", "Advanced local identity override (leave blank for user API keys)"),
_cfg_field("user", "Advanced local user override (leave blank for user API keys)"),
_cfg_field("agent", "Optional peer ID for separate assistant context. Uses user memory when no peer is configured.", default=_DEFAULT_AGENT),
+ _cfg_field("recall_scope", "Automatic recall: all peers (shared) or current sender (peer). Unset preserves existing behavior.",
+ type="string", choices=["shared", "peer"], default=None),
_cfg_field(
"recall_compress",
"Cloud recall compression: off, server or auto (no local compressor)",
@@ -149,6 +152,21 @@ _INVALID_SETTING_WARNINGS: Set[tuple[str, str]] = set()
_INVALID_SETTING_WARNINGS_LOCK = threading.Lock()
+def _gateway_peer_id(platform: str, sender: Any) -> str:
+ """Namespace transport IDs and encode path-like IDs without merging distinct senders."""
+ platform, sender = str(platform or "").strip().lower(), str(sender or "").strip()
+ if not platform or not sender:
+ return ""
+ raw = f"{platform}.{sender}"
+ if len(raw) <= 128 and re.fullmatch(r"[a-zA-Z0-9_.@-]+", raw) and raw.count("@") <= 1:
+ return raw
+ # Preserve the peer paths generated by the original Hermes #105812.
+ safe = re.sub(r"[^a-zA-Z0-9_.@-]+", "-", raw)
+ safe = re.sub(r"@+", "-", safe).strip(".-") or "gateway-peer"
+ digest = hashlib.sha256(raw.encode("utf-8")).hexdigest()[:12]
+ return f"{safe[:128 - len(digest) - 1].rstrip('.-') or 'gateway-peer'}-{digest}"
+
+
@dataclass(frozen=True)
class _OvcliProfile:
source: str
@@ -1171,6 +1189,7 @@ class _TurnUpload:
user_content: str
assistant_content: str
assistant_peer_id: str
+ user_peer_id: str = ""
next_index: int = 0
def _trace(self, fmt: str, *args) -> None:
@@ -1194,11 +1213,14 @@ class _TurnUpload:
if self.batch_messages and self.next_index == len(self.batch_messages):
return
# Plain-text fallback: one user + one assistant message.
+ user_message: Dict[str, Any] = {"role": "user", "parts": [{"type": "text", "text": self.user_content[:4000]}]}
+ if self.user_peer_id:
+ user_message["peer_id"] = self.user_peer_id
assistant_message: Dict[str, Any] = {"role": "assistant", "parts": [{"type": "text", "text": _message_text(self.assistant_content)[:4000]}]}
if self.assistant_peer_id:
assistant_message["peer_id"] = self.assistant_peer_id
client.post(f"/api/v1/sessions/{self.sid}/messages/batch",
- {"messages": [{"role": "user", "parts": [{"type": "text", "text": self.user_content[:4000]}]}, assistant_message]})
+ {"messages": [user_message, assistant_message]})
def run(self) -> Optional[_VikingClient]:
try:
@@ -1245,6 +1267,12 @@ class OpenVikingMemoryProvider(MemoryProvider):
def __init__(self):
self._client: Optional[_VikingClient] = None
self._endpoint = self._api_key = self._account = self._user = self._agent = ""
+ # The gateway sender is a peer within the configured OpenViking user.
+ self._user_id = ""
+ self._gateway_platform = self._gateway_user_id = self._gateway_user_id_alt = ""
+ # Hermes copies the calling context into recall/sync workers. A later
+ # speaker must not change an earlier queued turn's identity.
+ self._turn_peer: ContextVar[Optional[str]] = ContextVar("openviking_turn_peer", default=None)
self._session_id, self._turn_count, self._hermes_home = "", 0, ""
# (conn snapshot, user): keyed on the snapshot so every client built from it
# shares the resolved user and a /reload invalidates it.
@@ -1348,7 +1376,13 @@ class OpenVikingMemoryProvider(MemoryProvider):
def post_setup(self, hermes_home: str, config: dict) -> None:
"""Interactive setup that can reuse OpenViking's shared CLI config (see ``_setup``)."""
- _setup.run_setup(hermes_home, config)
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ token = set_hermes_home_override(hermes_home)
+ try:
+ _setup.run_setup(hermes_home, config)
+ finally:
+ reset_hermes_home_override(token)
# -- connection lifecycle ------------------------------------------------
@@ -1466,6 +1500,11 @@ class OpenVikingMemoryProvider(MemoryProvider):
self._env_refresh_enabled = True
self._session_id = session_id
self._turn_count = 0
+ self._gateway_platform = str(kwargs.get("platform") or "").strip().lower()
+ self._gateway_user_id = str(kwargs.get("user_id") or "").strip()
+ self._gateway_user_id_alt = str(kwargs.get("user_id_alt") or "").strip()
+ self._user_id = _gateway_peer_id(self._gateway_platform, self._gateway_user_id_alt or self._gateway_user_id)
+ self._turn_peer.set(None)
self._hermes_home = str(kwargs.get("hermes_home") or "").strip() or str(get_hermes_home())
self._acquire_run_lock()
self._profile_prefetched_sessions.clear()
@@ -1576,6 +1615,19 @@ class OpenVikingMemoryProvider(MemoryProvider):
# -- prompt / prefetch ---------------------------------------------------
+ def _sender_peer(self, author_id: Any) -> str:
+ sender = str(author_id or "").strip()
+ if sender and sender in {self._gateway_user_id, self._gateway_user_id_alt}:
+ sender = self._gateway_user_id_alt or sender
+ return _gateway_peer_id(self._gateway_platform, sender)
+
+ def on_turn_start(self, turn_number: int, message: str, **kwargs) -> None:
+ self._turn_peer.set(self._sender_peer(kwargs["author_id"]) if "author_id" in kwargs else self._user_id)
+
+ def _current_sender_peer(self) -> str:
+ current = self._turn_peer.get()
+ return self._user_id if current is None else current
+
def system_prompt_block(self) -> str:
if not self._ensure_client():
return ""
@@ -1631,9 +1683,12 @@ class OpenVikingMemoryProvider(MemoryProvider):
@classmethod
def _post_prefetch_search(cls, client: _VikingClient, query: str, session_id: str, *, limit: int,
- context_type: str | List[str], deadline: float, request_timeout: float) -> dict:
+ context_type: str | List[str], deadline: float, request_timeout: float,
+ target_uri: Optional[List[str]] = None) -> dict:
"""Session-aware search first, falling back to search/find (budget errors propagate)."""
base_payload = {"query": query, "limit": limit, "score_threshold": 0, "context_type": context_type}
+ if target_uri:
+ base_payload["target_uri"] = target_uri
if session_id:
try:
return client.post("/api/v1/search/search", {**base_payload, "session_id": session_id},
@@ -1646,6 +1701,7 @@ class OpenVikingMemoryProvider(MemoryProvider):
def _search_prefetch_context(self, query: str, *, session_id: str = "", client: Optional[_VikingClient] = None) -> str:
query_text = (query or "").strip()
+ sender_peer = self._current_sender_peer()
if len(query_text) < _RECALL_QUERY_MIN_CHARS:
return ""
try:
@@ -1663,7 +1719,29 @@ class OpenVikingMemoryProvider(MemoryProvider):
try:
cfg = self._recall_config()
deadline = time.monotonic() + cfg["timeout_seconds"]
- if cfg["compress"] in ("server", "auto"):
+ scope = cfg["scope"]
+ target_uri = None
+ if scope in ("shared", "peer"):
+ endpoint, api_key, account, user, _agent = client._conn_snapshot
+ client = _VikingClient(endpoint, api_key, account=account, user=user,
+ agent=sender_peer if scope == "peer" else "")
+ if scope == "peer":
+ # Explicit roots also constrain fallback searches when there is
+ # no sender. An actor-less user-root search includes all peers.
+ user = _resolve_user_space(client, timeout=self._remaining_recall_timeout(deadline, cfg["request_timeout_seconds"]))
+ if not user:
+ return ""
+ user_root = f"viking://user/{user}"
+ target_uri = [f"{user_root}/memories"]
+ if sender_peer:
+ target_uri.append(f"{user_root}/peers/{sender_peer}/memories")
+ if cfg["resources"]:
+ target_uri += [f"{user_root}/resources", "viking://resources"]
+ if sender_peer:
+ target_uri.append(f"{user_root}/peers/{sender_peer}/resources")
+ # Without an actor, context-mode resource defaults include peers.
+ # Use scoped list recall for that case, even with compression on.
+ if cfg["compress"] in ("server", "auto") and (scope != "peer" or sender_peer):
payload = {
"query": query_text,
"mode": "context",
@@ -1675,6 +1753,8 @@ class OpenVikingMemoryProvider(MemoryProvider):
}
if session_id:
payload["session_id"] = session_id
+ if scope in ("shared", "peer"):
+ payload["peer_scope"] = "actor" if scope == "peer" else "all"
try:
assembled = self._unwrap_result(
client.post(
@@ -1688,6 +1768,10 @@ class OpenVikingMemoryProvider(MemoryProvider):
if isinstance(assembled, dict) and any(
k in assembled for k in ("rendered", "digest", "entries")
):
+ if scope == "peer" and (assembled.get("stats") or {}).get("peer_scope") != "actor":
+ # Older servers may ignore an unknown field. Never
+ # inject a digest whose sender scope is unconfirmed.
+ raise ValueError("OpenViking did not confirm actor-scoped context")
if (assembled.get("stats") or {}).get("rewrite") == "no_relevant":
return ""
return str(
@@ -1708,6 +1792,7 @@ class OpenVikingMemoryProvider(MemoryProvider):
context_type=["memory", "resource"] if cfg["resources"] else "memory",
deadline=deadline,
request_timeout=cfg["request_timeout_seconds"],
+ target_uri=target_uri,
)
)
if not isinstance(result, dict):
@@ -1760,7 +1845,11 @@ class OpenVikingMemoryProvider(MemoryProvider):
value, source = env_value, spec["env_var"]
else:
value, source = provider_config.get(key, default), f"memory.openviking.{key}"
- parsed = cls._parse_setting_value(value, spec["type"])
+ if value is None and default is None:
+ return None # No policy override on installations that predate the presets.
+ parsed = str(value).strip().lower() if "choices" in spec else cls._parse_setting_value(value, spec["type"])
+ if "choices" in spec and parsed not in spec["choices"]:
+ parsed = None
if parsed is None:
warning_key = (source, repr(value))
with _INVALID_SETTING_WARNINGS_LOCK:
@@ -2082,7 +2171,7 @@ class OpenVikingMemoryProvider(MemoryProvider):
return [message for message in messages[start_idx : end_idx + 1] if isinstance(message, dict)]
@staticmethod
- def _messages_to_openviking_batch(messages: List[Dict[str, Any]], *, assistant_peer_id: str = "") -> List[Dict[str, Any]]:
+ def _messages_to_openviking_batch(messages: List[Dict[str, Any]], *, assistant_peer_id: str = "", user_peer_id: str = "") -> List[Dict[str, Any]]:
"""Convert Hermes canonical messages into OpenViking batch payloads.
Recall-tool calls/results are dropped (re-ingesting recalled memory would
@@ -2090,13 +2179,15 @@ class OpenVikingMemoryProvider(MemoryProvider):
whose result is in the slice is emitted only via its result part.
"""
assistant_peer_id = str(assistant_peer_id or "").strip()
+ user_peer_id = str(user_peer_id or "").strip()
dict_messages = [m for m in messages if isinstance(m, dict)]
tool_calls_by_id, completed_tool_ids, skipped_tool_ids = _index_tool_calls(dict_messages)
payload_messages: List[Dict[str, Any]] = []
pending_tool_parts: List[Dict[str, Any]] = []
def emit(role: str, parts: List[Dict[str, Any]]) -> None:
- peer = {"peer_id": assistant_peer_id} if role == "assistant" and assistant_peer_id else {}
+ peer_id = assistant_peer_id if role == "assistant" else user_peer_id if role == "user" else ""
+ peer = {"peer_id": peer_id} if peer_id else {}
payload_messages.append({"role": role, "parts": parts, **peer})
def flush_tool_parts() -> None:
@@ -2137,7 +2228,8 @@ class OpenVikingMemoryProvider(MemoryProvider):
return payload_messages
def sync_turn(self, user_content: str, assistant_content: str, *, session_id: str = "",
- messages: Optional[List[Dict[str, Any]]] = None) -> None:
+ messages: Optional[List[Dict[str, Any]]] = None,
+ turn_author: Optional[Dict[str, Any]] = None) -> None:
"""Record the conversation turn in OpenViking's session (non-blocking)."""
if not self._ensure_client():
return
@@ -2153,13 +2245,14 @@ class OpenVikingMemoryProvider(MemoryProvider):
return
client = self._new_client()
assistant_peer_id = self._agent
+ user_peer_id = self._sender_peer(turn_author.get("id")) if isinstance(turn_author, dict) else self._current_sender_peer()
turn_messages = [dict(m) for m in (self._extract_current_turn_messages(messages, user_content, assistant_content) if messages is not None else [])]
for message in turn_messages:
if message.get("role") == "user":
message["content"] = user_content # first user message carries the skill-stripped text
break
- batch_messages = self._messages_to_openviking_batch(turn_messages, assistant_peer_id=assistant_peer_id)
+ batch_messages = self._messages_to_openviking_batch(turn_messages, assistant_peer_id=assistant_peer_id, user_peer_id=user_peer_id)
if env_var_enabled(_SYNC_TRACE_ENV):
logger.info(
"OpenViking sync_turn trace: session_arg=%r cached_session=%r messages_param_supported=true messages_present=%s "
@@ -2196,7 +2289,7 @@ class OpenVikingMemoryProvider(MemoryProvider):
sid = str(session_id or self._session_id).strip()
if not sid:
return
- upload = _TurnUpload(client, sid, batch_messages, user_content, assistant_content, assistant_peer_id)
+ upload = _TurnUpload(client, sid, batch_messages, user_content, assistant_content, assistant_peer_id, user_peer_id)
self._spawn_tracked("openviking-sync", upload_and_check, self._inflight_lock, lambda: self._inflight_writers.setdefault(sid, set()),
after_discard=drop_empty)
diff --git a/examples/hermes-plugin/_setup.py b/examples/hermes-plugin/_setup.py
index 130220f51..83eee3a10 100644
--- a/examples/hermes-plugin/_setup.py
+++ b/examples/hermes-plugin/_setup.py
@@ -15,6 +15,8 @@ from typing import Optional
_SETUP_CANCELLED = object()
_CANCEL_OPTION = ("Cancel setup", "no changes saved")
+_PERSONAL_PROFILE = "personal"
+_SHARED_PROFILE = "shared"
def _ov():
@@ -26,6 +28,57 @@ def _say(message: str) -> None:
print(f" {message}", flush=True)
+def _select_usage_profile(select, cancelled, provider_config: dict) -> str | object:
+ """Choose the original Personal/Shared preset before any connection writes."""
+ default = 1 if provider_config.get("recall_scope") == "shared" else 0
+ while True:
+ choice = select(
+ " OpenViking usage profile",
+ [("Personal Agent", "recall common and sender memory; keep sessions"),
+ ("Shared Agent", "share history and recall all senders")],
+ default=default, cancel_returns=cancelled,
+ )
+ if choice == cancelled:
+ return _SETUP_CANCELLED
+ if choice == 0:
+ return _PERSONAL_PROFILE
+ if choice != 1:
+ continue
+ from hermes_cli.curses_ui import curses_radiolist
+ from hermes_cli.memory_setup import _clear_interactive_transition
+
+ description = (
+ " Participants share conversation history within each group or thread.\n"
+ " Different groups keep separate conversation histories.\n"
+ " Recall includes common memory and all senders under this\n"
+ " OpenViking user, across chats."
+ )
+ print(description, flush=True) # Also visible with Hermes's numbered fallback.
+ confirm = curses_radiolist(
+ " Confirm Shared Agent",
+ ["Apply Shared Agent", "Go back - choose a different usage profile",
+ "Cancel setup - no changes saved"],
+ selected=1, cancel_returns=cancelled,
+ description=description,
+ )
+ _clear_interactive_transition()
+ if confirm == 0:
+ return _SHARED_PROFILE
+ if confirm != 1:
+ return _SETUP_CANCELLED
+
+
+def _apply_usage_profile(config: dict, provider_config: dict, profile: str) -> None:
+ if profile == _PERSONAL_PROFILE:
+ provider_config["recall_scope"] = "peer"
+ elif profile == _SHARED_PROFILE:
+ provider_config["recall_scope"] = "shared"
+ config["group_sessions_per_user"] = False
+ config["thread_sessions_per_user"] = False
+ else:
+ raise ValueError(f"Unknown OpenViking usage profile: {profile}")
+
+
def _retry_or_cancel_manual_setup(select, title: str, message: str, cancelled):
"""-> True (retry) or _SETUP_CANCELLED."""
_say(message)
@@ -369,14 +422,18 @@ def run_setup(hermes_home: str, config: dict) -> None:
from hermes_cli.memory_setup import _CANCELLED, _curses_select, _print_cancelled_setup, _prompt
env_path = Path(hermes_home) / ".env"
+ memory_config = config.get("memory")
+ provider_config = memory_config.get("openviking", {}) if isinstance(memory_config, dict) else {}
+ provider_config = provider_config if isinstance(provider_config, dict) else {}
+ print("\n OpenViking memory setup\n")
+ usage_profile = _select_usage_profile(_curses_select, _CANCELLED, provider_config)
+ if usage_profile is _SETUP_CANCELLED:
+ _print_cancelled_setup()
+ return
if not isinstance(config.get("memory"), dict):
config["memory"] = {}
- provider_config = config["memory"].get("openviking", {})
- provider_config = provider_config if isinstance(provider_config, dict) else {}
common = dict(select=_curses_select, cancelled=_CANCELLED, config=config, provider_config=provider_config, env_path=env_path)
- print("\n OpenViking memory setup\n")
-
profiles = _ov()._discover_ovcli_profiles()
if profiles:
choice = _curses_select(" OpenViking config source",
@@ -396,4 +453,12 @@ def run_setup(hermes_home: str, config: dict) -> None:
if result is _SETUP_CANCELLED:
_print_cancelled_setup()
elif result:
+ _apply_usage_profile(config, provider_config, usage_profile)
+ # A saved environment override must not silently defeat the chosen preset.
+ _ov()._write_env_vars(env_path, {}, remove_keys=("OPENVIKING_RECALL_SCOPE",))
+ os.environ.pop("OPENVIKING_RECALL_SCOPE", None)
save_config(config)
+ if usage_profile == _SHARED_PROFILE:
+ _say("Restart the Hermes gateway to apply the shared session settings.")
+ else:
+ _say("Personal recall enabled. Conversation-sharing settings are unchanged.")
diff --git a/examples/hermes-plugin/tests/conftest.py b/examples/hermes-plugin/tests/conftest.py
new file mode 100644
index 000000000..2dbb976b2
--- /dev/null
+++ b/examples/hermes-plugin/tests/conftest.py
@@ -0,0 +1,55 @@
+"""Load the plugin through Hermes discovery in isolated profile homes."""
+
+import os
+import shutil
+import sys
+from pathlib import Path
+
+import pytest
+
+
+def external_provider(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
+ monkeypatch.setenv("HERMES_ENABLE_PROJECT_PLUGINS", "0")
+ for key in list(os.environ):
+ if key.startswith("OPENVIKING_"):
+ monkeypatch.delenv(key)
+
+ import plugins.memory as memory
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ monkeypatch.setattr(memory, "_MEMORY_PLUGINS_DIR", tmp_path / "empty-bundled")
+ providers = []
+
+ def load(profile):
+ home = tmp_path / profile
+ target = home / "plugins" / "openviking"
+ if not target.exists():
+ shutil.copytree(
+ Path(__file__).resolve().parents[1],
+ target,
+ ignore=shutil.ignore_patterns("tests", "__pycache__", ".pytest_cache"),
+ )
+ (home / "config.yaml").write_text(
+ "memory:\n provider: openviking\n openviking:\n"
+ " use_ovcli_config: false\n"
+ f" agent: {profile}\n",
+ encoding="utf-8",
+ )
+ token = set_hermes_home_override(home)
+ try:
+ assert memory.find_provider_dir("openviking") == target
+ provider = memory.load_memory_provider("openviking", register_skills=False)
+ assert provider is not None
+ module = sys.modules[type(provider).__module__]
+ settings = module._resolve_connection_settings(module._load_hermes_openviking_config())
+ finally:
+ reset_hermes_home_override(token)
+ providers.append(provider)
+ return home, provider, module, settings
+
+ yield load
+ for provider in providers:
+ provider.shutdown()
diff --git a/examples/hermes-plugin/tests/test_gateway_recall.py b/examples/hermes-plugin/tests/test_gateway_recall.py
new file mode 100644
index 000000000..6fdfd89fd
--- /dev/null
+++ b/examples/hermes-plugin/tests/test_gateway_recall.py
@@ -0,0 +1,372 @@
+"""Mock gateway turns through the external loader, Hermes manager and HTTP client."""
+
+import json
+import threading
+from contextlib import contextmanager
+from types import SimpleNamespace
+
+import httpx
+import pytest
+import yaml
+
+
+@contextmanager
+def profile_scope(home):
+ from agent.secret_scope import build_profile_secret_scope, reset_secret_scope, set_secret_scope
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ token = set_hermes_home_override(home)
+ secrets = set_secret_scope(build_profile_secret_scope(home))
+ try:
+ yield
+ finally:
+ reset_secret_scope(secrets)
+ reset_hermes_home_override(token)
+
+
+class GatewayBackend:
+ """In-memory HTTP service: capture/archive plus deterministic indexed fixtures."""
+
+ def __init__(self):
+ self.pending = []
+ self.archived = []
+ self.searches = []
+ self.requests = []
+ self.batch_failures = 0
+ self.reject_context = False
+ self.reject_session_search = False
+ self.unconfirmed_context = False
+ self.reject_identity = False
+ self.upload_started = None
+ self.release_upload = None
+
+ def __call__(self, request):
+ path = request.url.path
+ payload = json.loads(request.content) if request.content else {}
+ self.requests.append((request, payload))
+ result = {}
+ if path == "/health":
+ return httpx.Response(200, json={"status": "ok", "healthy": True, "version": "0.4.21"})
+ if path == "/api/v1/system/status":
+ if self.reject_identity:
+ return httpx.Response(503)
+ result = {"user": "tenant"}
+ elif path.endswith("/messages/batch") or path.endswith("/messages"):
+ if self.upload_started:
+ self.upload_started.set()
+ assert self.release_upload.wait(10)
+ if path.endswith("/batch") and self.batch_failures:
+ self.batch_failures -= 1
+ return httpx.Response(500, json={"error": {"message": "temporary capture failure"}})
+ self.pending.extend(payload.get("messages", [payload]))
+ elif path.endswith("/commit"):
+ assert payload == {"keep_recent_count": 0}
+ self.archived.extend(self.pending)
+ self.pending.clear()
+ result = {"status": "accepted"}
+ elif path.startswith("/api/v1/sessions/"):
+ result = {"pending_tokens": 0}
+ elif path.startswith("/api/v1/search/"):
+ self.searches.append((request, payload))
+ if self.reject_session_search and payload.get("session_id"):
+ return httpx.Response(503)
+ if payload.get("mode") == "context" and self.reject_context:
+ return httpx.Response(422)
+ actor = request.headers.get("X-OpenViking-Actor-Peer", "")
+ roots = payload.get("target_uri")
+ if roots is None:
+ all_peers = not actor or (
+ payload.get("mode") == "context" and payload.get("peer_scope", "all") == "all"
+ )
+ roots = (
+ ["viking://user/tenant", "viking://resources"]
+ if all_peers
+ else [
+ "viking://user/tenant/memories",
+ f"viking://user/tenant/peers/{actor}",
+ "viking://resources",
+ ]
+ )
+ docs = [("common", "viking://user/tenant/memories/preferences/common.md")]
+ docs += [
+ (name, f"viking://user/tenant/peers/telegram.{name}/memories/preferences/fact.md")
+ for name in ("alice", "bob", "assistant")
+ ]
+ docs += [("resource", "viking://resources/manual/readme.md")]
+ allowed = [
+ (name, uri)
+ for name, uri in docs
+ if any(uri.startswith(root.rstrip("/") + "/") for root in roots)
+ ]
+ if "resource" not in payload.get("context_type", []):
+ allowed = [(name, uri) for name, uri in allowed if name != "resource"]
+ if payload.get("mode") == "context":
+ result = {
+ "rendered": " ".join(name for name, _ in allowed),
+ "entries": [],
+ "stats": {"peer_scope": payload.get("peer_scope", "all")},
+ }
+ if self.unconfirmed_context:
+ result = {"rendered": "WRONG_BOB_CONTEXT", "entries": [], "stats": {}}
+ else:
+ result = {
+ "memories": [
+ {"uri": uri, "score": 0.9, "abstract": name, "level": 2}
+ for name, uri in allowed
+ ]
+ }
+ elif path == "/api/v1/fs/ls":
+ result = []
+ elif path.startswith("/api/v1/content/"):
+ return httpx.Response(404)
+ return httpx.Response(200, json={"status": "ok", "result": result})
+
+
+def initialize(
+ external_provider, monkeypatch, *, name="gateway", scope="peer", compress="off", **identity
+):
+ from agent.memory_manager import MemoryManager
+
+ home, provider, module, _ = external_provider(name)
+ config = {
+ "endpoint": f"http://{name}.test",
+ "use_ovcli_config": False,
+ "agent": "telegram.assistant",
+ "api_key": "mock-key",
+ "recall_scope": scope,
+ "recall_compress": compress,
+ "recall_prefer_abstract": True,
+ "recall_resources": True,
+ "recall_timeout_seconds": 10,
+ "recall_request_timeout_seconds": 5,
+ }
+ (home / "config.yaml").write_text(
+ yaml.safe_dump({"memory": {"provider": "openviking", "openviking": config}})
+ )
+ backend = GatewayBackend()
+ client = httpx.Client(transport=httpx.MockTransport(backend))
+ monkeypatch.setattr(module, "_get_httpx", lambda: client)
+ manager = MemoryManager(external_prefetch_timeout=10)
+ manager.add_provider(provider)
+ with profile_scope(home):
+ manager.initialize_all(
+ session_id="shared-group",
+ hermes_home=str(home),
+ platform="telegram",
+ user_id="alice",
+ **identity,
+ )
+ return home, provider, module, manager, backend
+
+
[email protected]("compress", ["off", "server"])
[email protected]("scope", [None, "shared", "peer"])
+def test_gateway_capture_commit_and_sender_scoped_recall(
+ external_provider, monkeypatch, scope, compress
+):
+ from agent.turn_context import _memory_turn_start_and_prefetch
+
+ home, provider, _, manager, backend = initialize(
+ external_provider, monkeypatch, scope=scope, compress=compress
+ )
+ agent = SimpleNamespace(
+ _memory_manager=manager,
+ _user_turn_count=0,
+ session_id="shared-group",
+ _emit_status=lambda _: None,
+ )
+ try:
+ with profile_scope(home):
+ for index, sender in enumerate(("alice", "bob", "alice"), start=1):
+ author = {"id": sender, "name": sender, "is_bot": False}
+ query = f"Remember my {sender} drink preference"
+ agent._user_turn_count = index
+ recalled = _memory_turn_start_and_prefetch(agent, query, author)
+ assert "common" in recalled
+ if scope == "peer":
+ assert sender in recalled
+ assert ("bob" if sender == "alice" else "alice") not in recalled
+ assert "assistant" not in recalled
+ elif scope == "shared":
+ assert "alice" in recalled and "bob" in recalled
+ elif compress == "off":
+ assert (
+ "assistant" in recalled
+ and "alice" not in recalled
+ and "bob" not in recalled
+ )
+ manager.sync_all(
+ query,
+ "Acknowledged",
+ session_id="shared-group",
+ turn_author=author,
+ messages=[
+ {"role": "user", "content": query},
+ {"role": "assistant", "content": "Acknowledged"},
+ ],
+ )
+ assert manager.flush_pending(timeout=10)
+ assert provider._drain_writers("shared-group", timeout=10)
+ provider.on_session_end([])
+ assert provider._drain_finalizers(timeout=10)
+ assert [m["peer_id"] for m in backend.archived if m["role"] == "user"] == [
+ "telegram.alice",
+ "telegram.bob",
+ "telegram.alice",
+ ]
+ assert all(
+ m["peer_id"] == "telegram.assistant"
+ for m in backend.archived
+ if m["role"] == "assistant"
+ )
+ assert backend.pending == []
+ assert not provider._state_path("pending", "shared-group").exists()
+ # Sender recall never changes the configured identity used for capture/tools.
+ with profile_scope(home):
+ provider.handle_tool_call("viking_search", {"query": "preference"})
+ assert backend.searches[-1][0].headers["X-OpenViking-Actor-Peer"] == "telegram.assistant"
+ finally:
+ manager.shutdown_all()
+
+
[email protected]("batch_failures,structured", [(1, True), (4, True), (0, False)])
+def test_delayed_capture_keeps_author_through_fallback(
+ external_provider, monkeypatch, batch_failures, structured
+):
+ home, provider, _, manager, backend = initialize(external_provider, monkeypatch)
+ backend.batch_failures = batch_failures
+ backend.upload_started, backend.release_upload = threading.Event(), threading.Event()
+ try:
+ with profile_scope(home):
+ manager.on_turn_start(1, "Alice fact", author_id="alice")
+ provider.sync_turn(
+ "Alice fact",
+ "Reply",
+ session_id="shared-group",
+ turn_author={"id": "alice"},
+ messages=[{"role": "user", "content": "Alice fact"}] if structured else None,
+ )
+ assert backend.upload_started.wait(5)
+ manager.on_turn_start(2, "Bob fact", author_id="bob")
+ backend.release_upload.set()
+ assert provider._drain_writers("shared-group", timeout=10)
+ assert backend.pending
+ assert {m["peer_id"] for m in backend.pending if m["role"] == "user"} == {"telegram.alice"}
+ finally:
+ backend.release_upload.set()
+ manager.shutdown_all()
+
+
[email protected]("author_id", [None, "", "bob"])
+def test_missing_author_and_context_fallback_keep_scope(external_provider, monkeypatch, author_id):
+ home, provider, _, manager, backend = initialize(
+ external_provider, monkeypatch, compress="server"
+ )
+ try:
+ with profile_scope(home):
+ manager.on_turn_start(1, "Alice fact", author_id="alice")
+ manager.on_turn_start(2, "Recall preferences", author_id=author_id)
+ for fault in ("reject_context", "unconfirmed_context"):
+ setattr(backend, fault, True)
+ result = provider.prefetch("Recall preferences", session_id="shared-group")
+ assert "common" in result and "resource" in result
+ assert "alice" not in result and "assistant" not in result and "WRONG" not in result
+ assert ("bob" in result) == bool(author_id)
+ assert backend.searches[-1][1]["target_uri"]
+ setattr(backend, fault, False)
+ backend.reject_identity = True
+ backend.searches.clear()
+ assert provider.prefetch("Recall preferences", session_id="shared-group") == ""
+ assert not backend.searches
+ finally:
+ manager.shutdown_all()
+
+
+def test_peer_identity_alt_ids_and_profile_settings(external_provider, monkeypatch):
+ home_a, provider_a, module_a, manager_a, _ = initialize(
+ external_provider, monkeypatch, name="profile-a", user_id_alt="stable-alice"
+ )
+ home_b, provider_b, _, manager_b, _ = initialize(
+ external_provider, monkeypatch, name="profile-b", scope="shared"
+ )
+ try:
+ for home, provider, expected in (
+ (home_a, provider_a, "peer"),
+ (home_b, provider_b, "shared"),
+ (home_a, provider_a, "peer"),
+ ):
+ with profile_scope(home):
+ assert provider._recall_config()["scope"] == expected
+ with profile_scope(home_a):
+ provider_a.on_turn_start(1, "hello", author_id="alice")
+ assert provider_a._current_sender_peer() == "telegram.stable-alice"
+ provider_a.on_turn_start(2, "hello", author_id="bob")
+ assert provider_a._current_sender_peer() == "telegram.bob"
+ assert module_a._gateway_peer_id("telegram", "alice") != module_a._gateway_peer_id(
+ "discord", "alice"
+ )
+ assert module_a._gateway_peer_id("telegram", "a/b") != module_a._gateway_peer_id(
+ "telegram", "a?b"
+ )
+ peer = module_a._gateway_peer_id("telegram", "a/b" * 100)
+ assert len(peer) <= 128 and "/" not in peer
+ provider_a.save_config({"recall_scope": "shared"}, str(home_a))
+ assert (
+ yaml.safe_load((home_a / "config.yaml").read_text())["memory"]["openviking"][
+ "recall_scope"
+ ]
+ == "shared"
+ )
+ finally:
+ manager_a.shutdown_all()
+ manager_b.shutdown_all()
+
+
+def test_find_fallback_retains_sender_roots(external_provider, monkeypatch):
+ home, provider, _, manager, backend = initialize(external_provider, monkeypatch)
+ backend.reject_session_search = True
+ try:
+ with profile_scope(home):
+ manager.on_turn_start(1, "Recall preferences", author_id="bob")
+ result = provider.prefetch("Recall preferences", session_id="shared-group")
+ assert "bob" in result and "common" in result and "resource" in result
+ assert "alice" not in result and "assistant" not in result
+ assert backend.searches[-1][0].url.path == "/api/v1/search/find"
+ assert backend.searches[-1][1]["target_uri"] == backend.searches[-2][1]["target_uri"]
+ finally:
+ manager.shutdown_all()
+
+
[email protected]("platform,expected", [("telegram", "telegram.alice"), ("", None)])
+def test_older_hooks_and_no_gateway_sender(external_provider, monkeypatch, platform, expected):
+ home, provider, _, manager, backend = initialize(external_provider, monkeypatch)
+ try:
+ with profile_scope(home):
+ provider._gateway_platform = platform
+ provider._user_id = provider._sender_peer("alice")
+ # Older Hermes does not pass per-turn author metadata.
+ provider.on_turn_start(1, "Remember this")
+ provider.sync_turn("Remember this", "OK", session_id="shared-group")
+ assert provider._drain_writers("shared-group", timeout=10)
+ assert backend.pending[0].get("peer_id") == expected
+ backend.pending.clear()
+ # An explicit missing author must clear the initialized sender.
+ provider.on_turn_start(2, "Remember another fact", author_id=None)
+ provider.sync_turn(
+ "Remember another fact", "OK", session_id="shared-group", turn_author={"id": None}
+ )
+ assert provider._drain_writers("shared-group", timeout=10)
+ assert "peer_id" not in backend.pending[0]
+ finally:
+ manager.shutdown_all()
+
+
+def test_recall_scope_default_and_environment_override(external_provider, monkeypatch):
+ _, provider, module, _ = external_provider("config")
+ schema = {field["key"]: field for field in provider.get_config_schema()}
+ assert schema["recall_scope"]["choices"] == ["shared", "peer"]
+ assert module.OpenVikingMemoryProvider._setting("recall_scope", {}) is None
+ monkeypatch.setenv("OPENVIKING_RECALL_SCOPE", "peer")
+ assert provider._setting("recall_scope", {"recall_scope": "shared"}) == "peer"
+ monkeypatch.delenv("OPENVIKING_RECALL_SCOPE")
+ assert provider._setting("recall_scope", {"recall_scope": "invalid"}) is None
diff --git a/examples/hermes-plugin/tests/test_setup_profiles.py b/examples/hermes-plugin/tests/test_setup_profiles.py
new file mode 100644
index 000000000..3db203240
--- /dev/null
+++ b/examples/hermes-plugin/tests/test_setup_profiles.py
@@ -0,0 +1,223 @@
+"""Exercise the external setup wizard and its saved Hermes session policy."""
+
+import copy
+from types import SimpleNamespace
+
+import pytest
+import yaml
+
+
+def patch_menu(monkeypatch, select):
+ from hermes_cli import curses_ui
+
+ def radio(title, options, *, selected=0, **kwargs):
+ return select(title, options, default=selected, **kwargs)
+
+ monkeypatch.setattr(curses_ui, "curses_radiolist", radio)
+
+
+def setup_state(external_provider, monkeypatch, *, route="local"):
+ import hermes_cli.memory_setup as setup
+
+ home, provider, module, _ = external_provider("setup-profile")
+ config = {
+ "group_sessions_per_user": True,
+ "thread_sessions_per_user": False,
+ "memory": {"provider": "openviking", "openviking": {"recall_limit": 9}},
+ }
+ (home / "config.yaml").write_text(yaml.safe_dump(config))
+ (home / ".env").write_text("UNRELATED=keep\nOPENVIKING_RECALL_SCOPE=shared\n")
+ monkeypatch.setenv("OPENVIKING_RECALL_SCOPE", "shared")
+ values = {"endpoint": "http://127.0.0.1:1933", "user": "example"}
+ saved = module._default_ovcli_config_path().with_name("ovcli.conf.existing")
+ saved.parent.mkdir(parents=True, exist_ok=True)
+ saved.write_text('{"url":"http://127.0.0.1:1933","user":"example"}')
+ profiles = (
+ [module._OvcliProfile("saved", "existing", saved, values)] if route == "linked" else []
+ )
+ monkeypatch.setattr(module, "_discover_ovcli_profiles", lambda: profiles)
+ monkeypatch.setattr(module, "_validate_openviking_reachability", lambda *_: (True, "ok"))
+ monkeypatch.setattr(
+ module, "_validate_openviking_setup_values", lambda *_, **__: (True, "ok", None)
+ )
+ monkeypatch.setattr(
+ setup,
+ "_prompt",
+ lambda label, **_: "new-profile" if "profile name" in label else values["endpoint"],
+ )
+ return home, provider, module, config, setup
+
+
+def select_profile(profile, route, menus, setup):
+ def select(title, options, **kwargs):
+ menus.append((title, options, kwargs))
+ return {
+ " OpenViking usage profile": 0 if profile == "personal" else 1,
+ " Confirm Shared Agent": 0,
+ " OpenViking config source": 0,
+ " OpenViking profile": 0,
+ " OpenViking connection": 1,
+ " OpenViking credential": 2,
+ " Save OpenViking config": 1 if route == "mirror" else 0,
+ }.get(title, setup._CANCELLED)
+
+ return select
+
+
[email protected]("route", ["local", "linked", "mirror"])
[email protected]("profile", ["personal", "shared"])
+def test_setup_persists_preset_and_real_gateway_session_boundaries(
+ external_provider, monkeypatch, capsys, route, profile
+):
+ from gateway.config import Platform
+ from gateway.session import build_session_key
+ from hermes_constants import (
+ get_hermes_home,
+ reset_hermes_home_override,
+ set_hermes_home_override,
+ )
+
+ home, provider, module, config, setup = setup_state(external_provider, monkeypatch, route=route)
+ other_home, _, _, _ = external_provider("other-profile")
+ other_before = (other_home / "config.yaml").read_bytes()
+ menus = []
+ patch_menu(monkeypatch, select_profile(profile, route, menus, setup))
+ token = set_hermes_home_override(other_home)
+ try:
+ provider.post_setup(str(home), config)
+ assert get_hermes_home() == other_home
+ finally:
+ reset_hermes_home_override(token)
+ output = capsys.readouterr().out
+ assert (
+ "Personal recall enabled. Conversation-sharing settings are unchanged." in output
+ ) == (profile == "personal")
+ assert (
+ "Restart the Hermes gateway to apply the shared session settings." in output
+ ) == (profile == "shared")
+ assert (other_home / "config.yaml").read_bytes() == other_before
+ saved = yaml.safe_load((home / "config.yaml").read_text())
+ settings = saved["memory"]["openviking"]
+ assert settings["recall_scope"] == ("peer" if profile == "personal" else "shared")
+ assert settings["recall_limit"] == 9
+ assert settings["use_ovcli_config"] == (route != "local")
+ assert saved["group_sessions_per_user"] == (profile == "personal")
+ assert saved["thread_sessions_per_user"] is False
+ assert "UNRELATED=keep" in (home / ".env").read_text()
+ assert "OPENVIKING_RECALL_SCOPE=" not in (home / ".env").read_text()
+ assert (
+ module.OpenVikingMemoryProvider._setting("recall_scope", settings)
+ == settings["recall_scope"]
+ )
+ assert [item[0] for item in menus].count(" Confirm Shared Agent") == (profile == "shared")
+ assert len(menus[0][1]) == 2
+ if profile == "shared":
+ confirmation = next(menu for menu in menus if menu[0] == " Confirm Shared Agent")
+ assert confirmation[2]["default"] == 1
+ assert "across chats" in confirmation[2]["description"]
+ assert "Different groups keep separate" in confirmation[2]["description"]
+
+ def key(sender, *, chat="group-a", thread=None):
+ source = SimpleNamespace(
+ platform=Platform.TELEGRAM,
+ chat_type="group",
+ chat_id=chat,
+ thread_id=thread,
+ prospective_thread_id=None,
+ user_id=sender,
+ user_id_alt=None,
+ )
+ return build_session_key(
+ source,
+ group_sessions_per_user=saved["group_sessions_per_user"],
+ thread_sessions_per_user=saved["thread_sessions_per_user"],
+ )
+
+ assert (key("alice") == key("bob")) == (profile == "shared")
+ assert key("alice", thread="topic") == key("bob", thread="topic")
+ assert key("alice", chat="group-a") != key("alice", chat="group-b")
+
+
[email protected]("stage", ["usage", "confirm", "connection", "save", "validation"])
+def test_cancelled_or_failed_setup_does_not_apply_preset(
+ external_provider, monkeypatch, capsys, stage
+):
+ home, provider, module, config, setup = setup_state(
+ external_provider, monkeypatch, route="linked" if stage == "validation" else "local"
+ )
+ before = copy.deepcopy(config)
+ paths = [
+ home / "config.yaml",
+ home / ".env",
+ module._default_ovcli_config_path().with_name("ovcli.conf.existing"),
+ ]
+ contents = {path: path.read_bytes() for path in paths}
+ selectors = {
+ "usage": [setup._CANCELLED],
+ "confirm": [1, setup._CANCELLED],
+ "connection": [1, 0, setup._CANCELLED],
+ "save": [1, 0, 1, 2, setup._CANCELLED],
+ "validation": [1, 0, 0, 0, setup._CANCELLED],
+ }
+ selections = iter(selectors[stage])
+ patch_menu(monkeypatch, lambda *_, **__: next(selections))
+ if stage == "validation":
+ monkeypatch.setattr(
+ module,
+ "_validate_openviking_setup_values",
+ lambda *_, **__: (False, "unavailable", None),
+ )
+ provider.post_setup(str(home), config)
+ output = capsys.readouterr().out
+ assert "Personal recall enabled." not in output
+ assert "Restart the Hermes gateway" not in output
+ assert config == before
+ assert all(path.read_bytes() == content for path, content in contents.items())
+ assert not (module._default_ovcli_config_path().parent / "ovcli.conf.new-profile").exists()
+
+
+def test_saved_selection_and_back_from_shared_keep_personal_session_policy(
+ external_provider, monkeypatch
+):
+ home, provider, _, config, setup = setup_state(external_provider, monkeypatch)
+ config["memory"]["openviking"]["recall_scope"] = "shared"
+ config["group_sessions_per_user"] = False
+ config["thread_sessions_per_user"] = True
+ selections = iter([1, 1, 0, 1, 2, 0])
+ menus = []
+
+ def select(title, options, **kwargs):
+ menus.append((title, options, kwargs))
+ return next(selections)
+
+ patch_menu(monkeypatch, select)
+ provider.post_setup(str(home), config)
+ assert menus[0][2]["default"] == 1
+ assert menus[1][2]["default"] == 1 # Sharing always needs explicit confirmation.
+ assert len(menus[0][1]) == len(menus[2][1]) == 2
+ saved = yaml.safe_load((home / "config.yaml").read_text())
+ assert saved["memory"]["openviking"]["recall_scope"] == "peer"
+ assert saved["group_sessions_per_user"] is False
+ assert saved["thread_sessions_per_user"] is True
+
+
+ "platform,sender,expected",
+ [
+ (
+ "google/chat",
+ "google-chat.users-alice-example.com-1daa15b42c91",
+ ),
+ (
+ "google/chat",
+ "google-chat.users-alice-example.com-eaebc6db16c3",
+ ),
+ ("telegram", "x" * 500, "telegram." + "x" * 106 + "-c022671d1ba8"),
+ ("telegram", "alice@@example.com", "telegram.alice-example.com-c48af2cb6b43"),
+ ],
+)
+def test_peer_paths_match_original_hermes_pr(external_provider, platform, sender, expected):
+ _, _, module, _ = external_provider("peer-paths")
+ assert module._gateway_peer_id(platform, sender) == expected
diff --git a/examples/hermes-plugin/tests/test_standalone.py b/examples/hermes-plugin/tests/test_standalone.py
index b5d3d2e45..ba160ac21 100644
--- a/examples/hermes-plugin/tests/test_standalone.py
+++ b/examples/hermes-plugin/tests/test_standalone.py
@@ -1,63 +1,12 @@
"""Exercise the external provider through Hermes, with no bundled provider."""
import json
-import os
-import shutil
-import sys
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
-from pathlib import Path
import pytest
-def external_provider(tmp_path, monkeypatch):
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
- monkeypatch.setenv("HERMES_ENABLE_PROJECT_PLUGINS", "0")
- for key in list(os.environ):
- if key.startswith("OPENVIKING_"):
- monkeypatch.delenv(key)
-
- import plugins.memory as memory
- from hermes_constants import reset_hermes_home_override, set_hermes_home_override
-
- monkeypatch.setattr(memory, "_MEMORY_PLUGINS_DIR", tmp_path / "empty-bundled")
- providers = []
-
- def load(profile):
- home = tmp_path / profile
- target = home / "plugins" / "openviking"
- if not target.exists():
- shutil.copytree(
- Path(__file__).resolve().parents[1],
- target,
- ignore=shutil.ignore_patterns("tests", "__pycache__", ".pytest_cache"),
- )
- (home / "config.yaml").write_text(
- "memory:\n provider: openviking\n openviking:\n"
- " use_ovcli_config: false\n"
- f" agent: {profile}\n",
- encoding="utf-8",
- )
- token = set_hermes_home_override(home)
- try:
- assert memory.find_provider_dir("openviking") == target
- provider = memory.load_memory_provider("openviking", register_skills=False)
- assert provider is not None
- module = sys.modules[type(provider).__module__]
- settings = module._resolve_connection_settings(module._load_hermes_openviking_config())
- finally:
- reset_hermes_home_override(token)
- providers.append(provider)
- return home, provider, module, settings
-
- yield load
- for provider in providers:
- provider.shutdown()
-
-
def test_external_discovery_preserves_profile_config_and_relative_setup(external_provider):
home_a, provider_a, module_a, settings_a = external_provider("profile-a")
before = (home_a / "config.yaml").read_bytes()